Improve docstrings
[org-mode/org-tableheadings.git] / lisp / org.el
blob323417569024f81dc7dc21f64f47847f0e2fb562
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-2016 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"
119 (&optional arg start-day span with-hour))
120 (declare-function org-agenda-redo "org-agenda" (&optional all))
121 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
122 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
123 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
124 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
127 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
128 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
129 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
130 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
131 (declare-function org-clock-update-time-maybe "org-clock" ())
132 (declare-function org-clocktable-shift "org-clock" (dir n))
133 (declare-function org-element-at-point "org-element" ())
134 (declare-function org-element-cache-refresh "org-element" (pos))
135 (declare-function org-element-cache-reset "org-element" (&optional all))
136 (declare-function org-element-contents "org-element" (element))
137 (declare-function org-element-context "org-element" (&optional element))
138 (declare-function org-element-copy "org-element" (datum))
139 (declare-function org-element-interpret-data "org-element" (data))
140 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
141 (declare-function org-element-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-wrap-region "org-table" (arg))
171 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
172 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
173 (declare-function orgtbl-mode "org-table" (&optional arg))
175 (defsubst org-uniquify (list)
176 "Non-destructively remove duplicate elements from LIST."
177 (let ((res (copy-sequence list))) (delete-dups res)))
179 (defsubst org-get-at-bol (property)
180 "Get text property PROPERTY at the beginning of line."
181 (get-text-property (point-at-bol) property))
183 (defsubst org-trim (s &optional keep-lead)
184 "Remove whitespace at the beginning and the end of string S.
185 When optional argument KEEP-LEAD is non-nil, removing blank lines
186 at the beginning of the string does not affect leading indentation."
187 (replace-regexp-in-string
188 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
189 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
191 ;; load languages based on value of `org-babel-load-languages'
192 (defvar org-babel-load-languages)
194 ;;;###autoload
195 (defun org-babel-do-load-languages (sym value)
196 "Load the languages defined in `org-babel-load-languages'."
197 (set-default sym value)
198 (dolist (pair org-babel-load-languages)
199 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
200 (if active
201 (require (intern (concat "ob-" lang)))
202 (funcall 'fmakunbound
203 (intern (concat "org-babel-execute:" lang)))
204 (funcall 'fmakunbound
205 (intern (concat "org-babel-expand-body:" lang)))))))
207 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
208 ;;;###autoload
209 (defun org-babel-load-file (file &optional compile)
210 "Load Emacs Lisp source code blocks in the Org FILE.
211 This function exports the source code using `org-babel-tangle'
212 and then loads the resulting file using `load-file'. With prefix
213 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
214 file to byte-code before it is loaded."
215 (interactive "fFile to load: \nP")
216 (let* ((age (lambda (file)
217 (float-time
218 (time-subtract (current-time)
219 (nth 5 (or (file-attributes (file-truename file))
220 (file-attributes file)))))))
221 (base-name (file-name-sans-extension file))
222 (exported-file (concat base-name ".el")))
223 ;; tangle if the Org file is newer than the elisp file
224 (unless (and (file-exists-p exported-file)
225 (> (funcall age file) (funcall age exported-file)))
226 ;; Tangle-file traversal returns reversed list of tangled files
227 ;; and we want to evaluate the first target.
228 (setq exported-file
229 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
230 (message "%s %s"
231 (if compile
232 (progn (byte-compile-file exported-file 'load)
233 "Compiled and loaded")
234 (progn (load-file exported-file) "Loaded"))
235 exported-file)))
237 (defcustom org-babel-load-languages '((emacs-lisp . t))
238 "Languages which can be evaluated in Org buffers.
239 This list can be used to load support for any of the languages
240 below, note that each language will depend on a different set of
241 system executables and/or Emacs modes. When a language is
242 \"loaded\", then code blocks in that language can be evaluated
243 with `org-babel-execute-src-block' bound by default to C-c
244 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
245 be set to remove code block evaluation from the C-c C-c
246 keybinding. By default only Emacs Lisp (which has no
247 requirements) is loaded."
248 :group 'org-babel
249 :set 'org-babel-do-load-languages
250 :version "24.1"
251 :type '(alist :tag "Babel Languages"
252 :key-type
253 (choice
254 (const :tag "Awk" awk)
255 (const :tag "C" C)
256 (const :tag "R" R)
257 (const :tag "Asymptote" asymptote)
258 (const :tag "Calc" calc)
259 (const :tag "Clojure" clojure)
260 (const :tag "CSS" css)
261 (const :tag "Ditaa" ditaa)
262 (const :tag "Dot" dot)
263 (const :tag "Emacs Lisp" emacs-lisp)
264 (const :tag "Forth" forth)
265 (const :tag "Fortran" fortran)
266 (const :tag "Gnuplot" gnuplot)
267 (const :tag "Haskell" haskell)
268 (const :tag "IO" io)
269 (const :tag "J" J)
270 (const :tag "Java" java)
271 (const :tag "Javascript" js)
272 (const :tag "LaTeX" latex)
273 (const :tag "Ledger" ledger)
274 (const :tag "Lilypond" lilypond)
275 (const :tag "Lisp" lisp)
276 (const :tag "Makefile" makefile)
277 (const :tag "Maxima" maxima)
278 (const :tag "Matlab" matlab)
279 (const :tag "Mscgen" mscgen)
280 (const :tag "Ocaml" ocaml)
281 (const :tag "Octave" octave)
282 (const :tag "Org" org)
283 (const :tag "Perl" perl)
284 (const :tag "Pico Lisp" picolisp)
285 (const :tag "PlantUML" plantuml)
286 (const :tag "Python" python)
287 (const :tag "Ruby" ruby)
288 (const :tag "Sass" sass)
289 (const :tag "Scala" scala)
290 (const :tag "Scheme" scheme)
291 (const :tag "Screen" screen)
292 (const :tag "Shell Script" shell)
293 (const :tag "Shen" shen)
294 (const :tag "Sql" sql)
295 (const :tag "Sqlite" sqlite)
296 (const :tag "Stan" stan)
297 (const :tag "ebnf2ps" ebnf2ps))
298 :value-type (boolean :tag "Activate" :value t)))
300 ;;;; Customization variables
301 (defcustom org-clone-delete-id nil
302 "Remove ID property of clones of a subtree.
303 When non-nil, clones of a subtree don't inherit the ID property.
304 Otherwise they inherit the ID property with a new unique
305 identifier."
306 :type 'boolean
307 :version "24.1"
308 :group 'org-id)
310 ;;; Version
311 (org-check-version)
313 ;;;###autoload
314 (defun org-version (&optional here full message)
315 "Show the Org version.
316 Interactively, or when MESSAGE is non-nil, show it in echo area.
317 With prefix argument, or when HERE is non-nil, insert it at point.
318 In non-interactive uses, a reduced version string is output unless
319 FULL is given."
320 (interactive (list current-prefix-arg t (not current-prefix-arg)))
321 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
322 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
323 (load-suffixes (list ".el"))
324 (org-install-dir
325 (ignore-errors (org-find-library-dir "org-loaddefs"))))
326 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
327 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
328 (let* ((load-suffixes save-load-suffixes)
329 (release (org-release))
330 (git-version (org-git-version))
331 (version (format "Org mode version %s (%s @ %s)"
332 release
333 git-version
334 (if org-install-dir
335 (if (string= org-dir org-install-dir)
336 org-install-dir
337 (concat "mixed installation! "
338 org-install-dir
339 " and "
340 org-dir))
341 "org-loaddefs.el can not be found!")))
342 (version1 (if full version release)))
343 (when here (insert version1))
344 (when message (message "%s" version1))
345 version1)))
347 (defconst org-version (org-version))
350 ;;; Syntax Constants
352 ;;;; Block
354 (defconst org-block-regexp
355 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
356 "Regular expression for hiding blocks.")
358 (defconst org-dblock-start-re
359 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
360 "Matches the start line of a dynamic block, with parameters.")
362 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
363 "Matches the end of a dynamic block.")
365 ;;;; Clock and Planning
367 (defconst org-clock-string "CLOCK:"
368 "String used as prefix for timestamps clocking work hours on an item.")
370 (defvar org-closed-string "CLOSED:"
371 "String used as the prefix for timestamps logging closing a TODO entry.")
373 (defvar org-deadline-string "DEADLINE:"
374 "String to mark deadline entries.
375 \\<org-mode-map>
376 A deadline is this string, followed by a time stamp. It must be
377 a word, terminated by a colon. You can insert a schedule keyword
378 and a timestamp with `\\[org-deadline]'.")
380 (defvar org-scheduled-string "SCHEDULED:"
381 "String to mark scheduled TODO entries.
382 \\<org-mode-map>
383 A schedule is this string, followed by a time stamp. It must be
384 a word, terminated by a colon. You can insert a schedule keyword
385 and a timestamp with `\\[org-schedule]'.")
387 (defconst org-ds-keyword-length
388 (+ 2
389 (apply #'max
390 (mapcar #'length
391 (list org-deadline-string org-scheduled-string
392 org-clock-string org-closed-string))))
393 "Maximum length of the DEADLINE and SCHEDULED keywords.")
395 (defconst org-planning-line-re
396 (concat "^[ \t]*"
397 (regexp-opt
398 (list org-closed-string org-deadline-string org-scheduled-string)
400 "Matches a line with planning info.
401 Matched keyword is in group 1.")
403 (defconst org-clock-line-re
404 (concat "^[ \t]*" org-clock-string)
405 "Matches a line with clock info.")
407 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
408 "Matches the DEADLINE keyword.")
410 (defconst org-deadline-time-regexp
411 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
412 "Matches the DEADLINE keyword together with a time stamp.")
414 (defconst org-deadline-time-hour-regexp
415 (concat "\\<" org-deadline-string
416 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
417 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
419 (defconst org-deadline-line-regexp
420 (concat "\\<\\(" org-deadline-string "\\).*")
421 "Matches the DEADLINE keyword and the rest of the line.")
423 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
424 "Matches the SCHEDULED keyword.")
426 (defconst org-scheduled-time-regexp
427 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
428 "Matches the SCHEDULED keyword together with a time stamp.")
430 (defconst org-scheduled-time-hour-regexp
431 (concat "\\<" org-scheduled-string
432 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
433 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
435 (defconst org-closed-time-regexp
436 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
437 "Matches the CLOSED keyword together with a time stamp.")
439 (defconst org-keyword-time-regexp
440 (concat "\\<"
441 (regexp-opt
442 (list org-scheduled-string org-deadline-string org-closed-string
443 org-clock-string)
445 " *[[<]\\([^]>]+\\)[]>]")
446 "Matches any of the 4 keywords, together with the time stamp.")
448 (defconst org-keyword-time-not-clock-regexp
449 (concat
450 "\\<"
451 (regexp-opt
452 (list org-scheduled-string org-deadline-string org-closed-string) t)
453 " *[[<]\\([^]>]+\\)[]>]")
454 "Matches any of the 3 keywords, together with the time stamp.")
456 (defconst org-maybe-keyword-time-regexp
457 (concat "\\(\\<"
458 (regexp-opt
459 (list org-scheduled-string org-deadline-string org-closed-string
460 org-clock-string)
462 "\\)?"
463 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
464 "\\|"
465 "<%%([^\r\n>]*>\\)")
466 "Matches a timestamp, possibly preceded by a keyword.")
468 (defconst org-all-time-keywords
469 (mapcar (lambda (w) (substring w 0 -1))
470 (list org-scheduled-string org-deadline-string
471 org-clock-string org-closed-string))
472 "List of time keywords.")
474 ;;;; Drawer
476 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
477 "Matches first or last line of a hidden block.
478 Group 1 contains drawer's name or \"END\".")
480 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
481 "Regular expression matching the first line of a property drawer.")
483 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
484 "Regular expression matching the last line of a property drawer.")
486 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
487 "Regular expression matching the first line of a clock drawer.")
489 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
490 "Regular expression matching the last line of a clock drawer.")
492 (defconst org-property-drawer-re
493 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
494 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
495 "[ \t]*:END:[ \t]*$")
496 "Matches an entire property drawer.")
498 (defconst org-clock-drawer-re
499 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
500 org-clock-drawer-end-re "\\)\n?")
501 "Matches an entire clock drawer.")
503 ;;;; Headline
505 (defconst org-heading-keyword-regexp-format
506 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
507 "Printf format for a regexp matching a headline with some keyword.
508 This regexp will match the headline of any node which has the
509 exact keyword that is put into the format. The keyword isn't in
510 any group by default, but the stars and the body are.")
512 (defconst org-heading-keyword-maybe-regexp-format
513 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
514 "Printf format for a regexp matching a headline, possibly with some keyword.
515 This regexp can match any headline with the specified keyword, or
516 without a keyword. The keyword isn't in any group by default,
517 but the stars and the body are.")
519 (defconst org-archive-tag "ARCHIVE"
520 "The tag that marks a subtree as archived.
521 An archived subtree does not open during visibility cycling, and does
522 not contribute to the agenda listings.")
524 (defconst org-comment-string "COMMENT"
525 "Entries starting with this keyword will never be exported.
526 \\<org-mode-map>
527 An entry can be toggled between COMMENT and normal with
528 `\\[org-toggle-comment]'.")
531 ;;;; LaTeX Environments and Fragments
533 (defconst org-latex-regexps
534 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
535 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
536 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
537 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
538 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
539 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
540 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
541 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
542 "Regular expressions for matching embedded LaTeX.")
544 ;;;; Node Property
546 (defconst org-effort-property "Effort"
547 "The property that is being used to keep track of effort estimates.
548 Effort estimates given in this property need to have the format H:MM.")
550 ;;;; Table
552 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
553 "Detect an org-type or table-type table.")
555 (defconst org-table-line-regexp "^[ \t]*|"
556 "Detect an org-type table line.")
558 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
559 "Detect an org-type table line.")
561 (defconst org-table-hline-regexp "^[ \t]*|-"
562 "Detect an org-type table hline.")
564 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
565 "Detect a table-type table hline.")
567 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
568 "Detect the first line outside a table when searching from within it.
569 This works for both table types.")
571 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
572 "Detect a #+TBLFM line.")
574 ;;;; Timestamp
576 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
577 "Regular expression for fast time stamp matching.")
579 (defconst org-ts-regexp-inactive
580 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
581 "Regular expression for fast inactive time stamp matching.")
583 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
584 "Regular expression for fast time stamp matching.")
586 (defconst org-ts-regexp0
587 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
588 "Regular expression matching time strings for analysis.
589 This one does not require the space after the date, so it can be used
590 on a string that terminates immediately after the date.")
592 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
593 "Regular expression matching time strings for analysis.")
595 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
596 "Regular expression matching time stamps, with groups.")
598 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
599 "Regular expression matching time stamps (also [..]), with groups.")
601 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
602 "Regular expression matching a time stamp range.")
604 (defconst org-tr-regexp-both
605 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
606 "Regular expression matching a time stamp range.")
608 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
609 org-ts-regexp "\\)?")
610 "Regular expression matching a time stamp or time stamp range.")
612 (defconst org-tsr-regexp-both
613 (concat org-ts-regexp-both "\\(--?-?"
614 org-ts-regexp-both "\\)?")
615 "Regular expression matching a time stamp or time stamp range.
616 The time stamps may be either active or inactive.")
618 (defconst org-repeat-re
619 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
620 "Regular expression for specifying repeated events.
621 After a match, group 1 contains the repeat expression.")
623 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
624 "Formats for `format-time-string' which are used for time stamps.")
627 ;;; The custom variables
629 (defgroup org nil
630 "Outline-based notes management and organizer."
631 :tag "Org"
632 :group 'outlines
633 :group 'calendar)
635 (defcustom org-mode-hook nil
636 "Mode hook for Org mode, run after the mode was turned on."
637 :group 'org
638 :type 'hook)
640 (defcustom org-load-hook nil
641 "Hook that is run after org.el has been loaded."
642 :group 'org
643 :type 'hook)
645 (defcustom org-log-buffer-setup-hook nil
646 "Hook that is run after an Org log buffer is created."
647 :group 'org
648 :version "24.1"
649 :type 'hook)
651 (defvar org-modules) ; defined below
652 (defvar org-modules-loaded nil
653 "Have the modules been loaded already?")
655 (defun org-load-modules-maybe (&optional force)
656 "Load all extensions listed in `org-modules'."
657 (when (or force (not org-modules-loaded))
658 (dolist (ext org-modules)
659 (condition-case nil (require ext)
660 (error (message "Problems while trying to load feature `%s'" ext))))
661 (setq org-modules-loaded t)))
663 (defun org-set-modules (var value)
664 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
665 (set var value)
666 (when (featurep 'org)
667 (org-load-modules-maybe 'force)
668 (org-element-cache-reset 'all)))
670 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
671 "Modules that should always be loaded together with org.el.
673 If a description starts with <C>, the file is not part of Emacs
674 and loading it will require that you have downloaded and properly
675 installed the Org mode distribution.
677 You can also use this system to load external packages (i.e. neither Org
678 core modules, nor modules from the CONTRIB directory). Just add symbols
679 to the end of the list. If the package is called org-xyz.el, then you need
680 to add the symbol `xyz', and the package must have a call to:
682 (provide \\='org-xyz)
684 For export specific modules, see also `org-export-backends'."
685 :group 'org
686 :set 'org-set-modules
687 :version "24.4"
688 :package-version '(Org . "8.0")
689 :type
690 '(set :greedy t
691 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
692 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
693 (const :tag " crypt: Encryption of subtrees" org-crypt)
694 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
695 (const :tag " docview: Links to doc-view buffers" org-docview)
696 (const :tag " eww: Store link to url of eww" org-eww)
697 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
698 (const :tag " habit: Track your consistency with habits" org-habit)
699 (const :tag " id: Global IDs for identifying entries" org-id)
700 (const :tag " info: Links to Info nodes" org-info)
701 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
702 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
703 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
704 (const :tag " mouse: Additional mouse support" org-mouse)
705 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
706 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
707 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
709 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
710 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
711 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
712 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
713 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
714 (const :tag "C collector: Collect properties into tables" org-collector)
715 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
716 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
717 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
718 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
719 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
720 (const :tag "C eval: Include command output as text" org-eval)
721 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
722 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
723 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
724 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
725 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
726 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
727 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
728 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
729 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
730 (const :tag "C man: Support for links to manpages in Org mode" org-man)
731 (const :tag "C mew: Links to Mew folders/messages" org-mew)
732 (const :tag "C mtags: Support for muse-like tags" org-mtags)
733 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
734 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
735 (const :tag "C registry: A registry for Org links" org-registry)
736 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
737 (const :tag "C secretary: Team management with org-mode" org-secretary)
738 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
739 (const :tag "C toc: Table of contents for Org buffer" org-toc)
740 (const :tag "C track: Keep up with Org mode development" org-track)
741 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
742 (const :tag "C vm: Links to VM folders/messages" org-vm)
743 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
744 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
745 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
747 (defvar org-export-registered-backends) ; From ox.el.
748 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
749 (declare-function org-export-backend-name "ox" (backend) t)
750 (defcustom org-export-backends '(ascii html icalendar latex odt)
751 "List of export back-ends that should be always available.
753 If a description starts with <C>, the file is not part of Emacs
754 and loading it will require that you have downloaded and properly
755 installed the Org mode distribution.
757 Unlike to `org-modules', libraries in this list will not be
758 loaded along with Org, but only once the export framework is
759 needed.
761 This variable needs to be set before org.el is loaded. If you
762 need to make a change while Emacs is running, use the customize
763 interface or run the following code, where VAL stands for the new
764 value of the variable, after updating it:
766 (progn
767 (setq org-export-registered-backends
768 (cl-remove-if-not
769 (lambda (backend)
770 (let ((name (org-export-backend-name backend)))
771 (or (memq name val)
772 (catch \\='parentp
773 (dolist (b val)
774 (and (org-export-derived-backend-p b name)
775 (throw \\='parentp t)))))))
776 org-export-registered-backends))
777 (let ((new-list (mapcar #\\='org-export-backend-name
778 org-export-registered-backends)))
779 (dolist (backend val)
780 (cond
781 ((not (load (format \"ox-%s\" backend) t t))
782 (message \"Problems while trying to load export back-end \\=`%s\\='\"
783 backend))
784 ((not (memq backend new-list)) (push backend new-list))))
785 (set-default \\='org-export-backends new-list)))
787 Adding a back-end to this list will also pull the back-end it
788 depends on, if any."
789 :group 'org
790 :group 'org-export
791 :version "25.2"
792 :package-version '(Org . "9.0")
793 :initialize 'custom-initialize-set
794 :set (lambda (var val)
795 (if (not (featurep 'ox)) (set-default var val)
796 ;; Any back-end not required anymore (not present in VAL and not
797 ;; a parent of any back-end in the new value) is removed from the
798 ;; list of registered back-ends.
799 (setq org-export-registered-backends
800 (cl-remove-if-not
801 (lambda (backend)
802 (let ((name (org-export-backend-name backend)))
803 (or (memq name val)
804 (catch 'parentp
805 (dolist (b val)
806 (and (org-export-derived-backend-p b name)
807 (throw 'parentp t)))))))
808 org-export-registered-backends))
809 ;; Now build NEW-LIST of both new back-ends and required
810 ;; parents.
811 (let ((new-list (mapcar #'org-export-backend-name
812 org-export-registered-backends)))
813 (dolist (backend val)
814 (cond
815 ((not (load (format "ox-%s" backend) t t))
816 (message "Problems while trying to load export back-end `%s'"
817 backend))
818 ((not (memq backend new-list)) (push backend new-list))))
819 ;; Set VAR to that list with fixed dependencies.
820 (set-default var new-list))))
821 :type '(set :greedy t
822 (const :tag " ascii Export buffer to ASCII format" ascii)
823 (const :tag " beamer Export buffer to Beamer presentation" beamer)
824 (const :tag " html Export buffer to HTML format" html)
825 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
826 (const :tag " latex Export buffer to LaTeX format" latex)
827 (const :tag " man Export buffer to MAN format" man)
828 (const :tag " md Export buffer to Markdown format" md)
829 (const :tag " odt Export buffer to ODT format" odt)
830 (const :tag " org Export buffer to Org format" org)
831 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
832 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
833 (const :tag "C deck Export buffer to deck.js presentations" deck)
834 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
835 (const :tag "C groff Export buffer to Groff format" groff)
836 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
837 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
838 (const :tag "C s5 Export buffer to s5 presentations" s5)
839 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
841 (eval-after-load 'ox
842 '(dolist (backend org-export-backends)
843 (condition-case nil (require (intern (format "ox-%s" backend)))
844 (error (message "Problems while trying to load export back-end `%s'"
845 backend)))))
847 (defcustom org-support-shift-select nil
848 "Non-nil means make shift-cursor commands select text when possible.
849 \\<org-mode-map>\
851 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
852 start selecting a region, or enlarge regions started in this way.
853 In Org mode, in special contexts, these same keys are used for
854 other purposes, important enough to compete with shift selection.
855 Org tries to balance these needs by supporting `shift-select-mode'
856 outside these special contexts, under control of this variable.
858 The default of this variable is nil, to avoid confusing behavior. Shifted
859 cursor keys will then execute Org commands in the following contexts:
860 - on a headline, changing TODO state (left/right) and priority (up/down)
861 - on a time stamp, changing the time
862 - in a plain list item, changing the bullet type
863 - in a property definition line, switching between allowed values
864 - in the BEGIN line of a clock table (changing the time block).
865 Outside these contexts, the commands will throw an error.
867 When this variable is t and the cursor is not in a special
868 context, Org mode will support shift-selection for making and
869 enlarging regions. To make this more effective, the bullet
870 cycling will no longer happen anywhere in an item line, but only
871 if the cursor is exactly on the bullet.
873 If you set this variable to the symbol `always', then the keys
874 will not be special in headlines, property lines, and item lines,
875 to make shift selection work there as well. If this is what you
876 want, you can use the following alternative commands:
877 `\\[org-todo]' and `\\[org-priority]' \
878 to change TODO state and priority,
879 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
880 can be used to switch TODO sets,
881 `\\[org-ctrl-c-minus]' to cycle item bullet types,
882 and properties can be edited by hand or in column view.
884 However, when the cursor is on a timestamp, shift-cursor commands
885 will still edit the time stamp - this is just too good to give up."
886 :group 'org
887 :type '(choice
888 (const :tag "Never" nil)
889 (const :tag "When outside special context" t)
890 (const :tag "Everywhere except timestamps" always)))
892 (defcustom org-loop-over-headlines-in-active-region nil
893 "Shall some commands act upon headlines in the active region?
895 When set to t, some commands will be performed in all headlines
896 within the active region.
898 When set to `start-level', some commands will be performed in all
899 headlines within the active region, provided that these headlines
900 are of the same level than the first one.
902 When set to a string, those commands will be performed on the
903 matching headlines within the active region. Such string must be
904 a tags/property/todo match as it is used in the agenda tags view.
906 The list of commands is: `org-schedule', `org-deadline',
907 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
908 `org-archive-to-archive-sibling'. The archiving commands skip
909 already archived entries."
910 :type '(choice (const :tag "Don't loop" nil)
911 (const :tag "All headlines in active region" t)
912 (const :tag "In active region, headlines at the same level than the first one" start-level)
913 (string :tag "Tags/Property/Todo matcher"))
914 :version "24.1"
915 :group 'org-todo
916 :group 'org-archive)
918 (defgroup org-startup nil
919 "Options concerning startup of Org mode."
920 :tag "Org Startup"
921 :group 'org)
923 (defcustom org-startup-folded t
924 "Non-nil means entering Org mode will switch to OVERVIEW.
925 This can also be configured on a per-file basis by adding one of
926 the following lines anywhere in the buffer:
928 #+STARTUP: fold (or `overview', this is equivalent)
929 #+STARTUP: nofold (or `showall', this is equivalent)
930 #+STARTUP: content
931 #+STARTUP: showeverything
933 By default, this option is ignored when Org opens agenda files
934 for the first time. If you want the agenda to honor the startup
935 option, set `org-agenda-inhibit-startup' to nil."
936 :group 'org-startup
937 :type '(choice
938 (const :tag "nofold: show all" nil)
939 (const :tag "fold: overview" t)
940 (const :tag "content: all headlines" content)
941 (const :tag "show everything, even drawers" showeverything)))
943 (defcustom org-startup-truncated t
944 "Non-nil means entering Org mode will set `truncate-lines'.
945 This is useful since some lines containing links can be very long and
946 uninteresting. Also tables look terrible when wrapped.
948 The variable `org-startup-truncated' allows to configure
949 truncation for Org mode different to the other modes that use the
950 variable `truncate-lines' and as a shortcut instead of putting
951 the variable `truncate-lines' into the `org-mode-hook'. If one
952 wants to configure truncation for Org mode not statically but
953 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
954 the variable `truncate-lines' has to be used because in such a
955 case it is too late to set the variable `org-startup-truncated'."
956 :group 'org-startup
957 :type 'boolean)
959 (defcustom org-startup-indented nil
960 "Non-nil means turn on `org-indent-mode' on startup.
961 This can also be configured on a per-file basis by adding one of
962 the following lines anywhere in the buffer:
964 #+STARTUP: indent
965 #+STARTUP: noindent"
966 :group 'org-structure
967 :type '(choice
968 (const :tag "Not" nil)
969 (const :tag "Globally (slow on startup in large files)" t)))
971 (defcustom org-use-sub-superscripts t
972 "Non-nil means interpret \"_\" and \"^\" for display.
974 If you want to control how Org exports those characters, see
975 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
976 used to be an alias for `org-export-with-sub-superscripts' in
977 Org <8.0, it is not anymore.
979 When this option is turned on, you can use TeX-like syntax for
980 sub- and superscripts within the buffer. Several characters after
981 \"_\" or \"^\" will be considered as a single item - so grouping
982 with {} is normally not needed. For example, the following things
983 will be parsed as single sub- or superscripts:
985 10^24 or 10^tau several digits will be considered 1 item.
986 10^-12 or 10^-tau a leading sign with digits or a word
987 x^2-y^3 will be read as x^2 - y^3, because items are
988 terminated by almost any nonword/nondigit char.
989 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
991 Still, ambiguity is possible. So when in doubt, use {} to enclose
992 the sub/superscript. If you set this variable to the symbol `{}',
993 the braces are *required* in order to trigger interpretations as
994 sub/superscript. This can be helpful in documents that need \"_\"
995 frequently in plain text."
996 :group 'org-startup
997 :version "24.4"
998 :package-version '(Org . "8.0")
999 :type '(choice
1000 (const :tag "Always interpret" t)
1001 (const :tag "Only with braces" {})
1002 (const :tag "Never interpret" nil)))
1004 (defcustom org-startup-with-beamer-mode nil
1005 "Non-nil means turn on `org-beamer-mode' on startup.
1006 This can also be configured on a per-file basis by adding one of
1007 the following lines anywhere in the buffer:
1009 #+STARTUP: beamer"
1010 :group 'org-startup
1011 :version "24.1"
1012 :type 'boolean)
1014 (defcustom org-startup-align-all-tables nil
1015 "Non-nil means align all tables when visiting a file.
1016 This is useful when the column width in tables is forced with <N> cookies
1017 in table fields. Such tables will look correct only after the first re-align.
1018 This can also be configured on a per-file basis by adding one of
1019 the following lines anywhere in the buffer:
1020 #+STARTUP: align
1021 #+STARTUP: noalign"
1022 :group 'org-startup
1023 :type 'boolean)
1025 (defcustom org-startup-with-inline-images nil
1026 "Non-nil means show inline images when loading a new Org file.
1027 This can also be configured on a per-file basis by adding one of
1028 the following lines anywhere in the buffer:
1029 #+STARTUP: inlineimages
1030 #+STARTUP: noinlineimages"
1031 :group 'org-startup
1032 :version "24.1"
1033 :type 'boolean)
1035 (defcustom org-startup-with-latex-preview nil
1036 "Non-nil means preview LaTeX fragments when loading a new Org file.
1038 This can also be configured on a per-file basis by adding one of
1039 the following lines anywhere in the buffer:
1040 #+STARTUP: latexpreview
1041 #+STARTUP: nolatexpreview"
1042 :group 'org-startup
1043 :version "24.4"
1044 :package-version '(Org . "8.0")
1045 :type 'boolean)
1047 (defcustom org-insert-mode-line-in-empty-file nil
1048 "Non-nil means insert the first line setting Org mode in empty files.
1049 When the function `org-mode' is called interactively in an empty file, this
1050 normally means that the file name does not automatically trigger Org mode.
1051 To ensure that the file will always be in Org mode in the future, a
1052 line enforcing Org mode will be inserted into the buffer, if this option
1053 has been set."
1054 :group 'org-startup
1055 :type 'boolean)
1057 (defcustom org-replace-disputed-keys nil
1058 "Non-nil means use alternative key bindings for some keys.
1059 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1060 These keys are also used by other packages like shift-selection-mode'
1061 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1062 If you want to use Org mode together with one of these other modes,
1063 or more generally if you would like to move some Org mode commands to
1064 other keys, set this variable and configure the keys with the variable
1065 `org-disputed-keys'.
1067 This option is only relevant at load-time of Org mode, and must be set
1068 *before* org.el is loaded. Changing it requires a restart of Emacs to
1069 become effective."
1070 :group 'org-startup
1071 :type 'boolean)
1073 (defcustom org-use-extra-keys nil
1074 "Non-nil means use extra key sequence definitions for certain commands.
1075 This happens automatically if `window-system' is nil. This
1076 variable lets you do the same manually. You must set it before
1077 loading Org."
1078 :group 'org-startup
1079 :type 'boolean)
1081 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1083 (defcustom org-disputed-keys
1084 '(([(shift up)] . [(meta p)])
1085 ([(shift down)] . [(meta n)])
1086 ([(shift left)] . [(meta -)])
1087 ([(shift right)] . [(meta +)])
1088 ([(control shift right)] . [(meta shift +)])
1089 ([(control shift left)] . [(meta shift -)]))
1090 "Keys for which Org mode and other modes compete.
1091 This is an alist, cars are the default keys, second element specifies
1092 the alternative to use when `org-replace-disputed-keys' is t.
1094 Keys can be specified in any syntax supported by `define-key'.
1095 The value of this option takes effect only at Org mode startup,
1096 therefore you'll have to restart Emacs to apply it after changing."
1097 :group 'org-startup
1098 :type 'alist)
1100 (defun org-key (key)
1101 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1102 Or return the original if not disputed."
1103 (when org-replace-disputed-keys
1104 (let* ((nkey (key-description key))
1105 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1106 org-disputed-keys)))
1107 (setq key (if x (cdr x) key))))
1108 key)
1110 (defun org-defkey (keymap key def)
1111 "Define a key, possibly translated, as returned by `org-key'."
1112 (define-key keymap (org-key key) def))
1114 (defcustom org-ellipsis nil
1115 "The ellipsis to use in the Org mode outline.
1117 When nil, just use the standard three dots.
1118 When a string, use that string instead.
1120 The change affects only Org mode (which will then use its own display table).
1121 Changing this requires executing `\\[org-mode]' in a buffer to become
1122 effective."
1123 :group 'org-startup
1124 :type '(choice (const :tag "Default" nil)
1125 (string :tag "String" :value "...#"))
1126 :safe #'string-or-null-p)
1128 (defvar org-display-table nil
1129 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1131 (defgroup org-keywords nil
1132 "Keywords in Org mode."
1133 :tag "Org Keywords"
1134 :group 'org)
1136 (defcustom org-closed-keep-when-no-todo nil
1137 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1138 :group 'org-todo
1139 :group 'org-keywords
1140 :version "24.4"
1141 :package-version '(Org . "8.0")
1142 :type 'boolean)
1144 (defgroup org-structure nil
1145 "Options concerning the general structure of Org files."
1146 :tag "Org Structure"
1147 :group 'org)
1149 (defgroup org-reveal-location nil
1150 "Options about how to make context of a location visible."
1151 :tag "Org Reveal Location"
1152 :group 'org-structure)
1154 (defcustom org-show-context-detail '((agenda . local)
1155 (bookmark-jump . lineage)
1156 (isearch . lineage)
1157 (default . ancestors))
1158 "Alist between context and visibility span when revealing a location.
1160 \\<org-mode-map>Some actions may move point into invisible
1161 locations. As a consequence, Org always expose a neighborhood
1162 around point. How much is shown depends on the initial action,
1163 or context. Valid contexts are
1165 agenda when exposing an entry from the agenda
1166 org-goto when using the command `org-goto' (`\\[org-goto]')
1167 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1168 tags-tree when constructing a sparse tree based on tags matches
1169 link-search when exposing search matches associated with a link
1170 mark-goto when exposing the jump goal of a mark
1171 bookmark-jump when exposing a bookmark location
1172 isearch when exiting from an incremental search
1173 default default for all contexts not set explicitly
1175 Allowed visibility spans are
1177 minimal show current headline; if point is not on headline,
1178 also show entry
1180 local show current headline, entry and next headline
1182 ancestors show current headline and its direct ancestors; if
1183 point is not on headline, also show entry
1185 lineage show current headline, its direct ancestors and all
1186 their children; if point is not on headline, also show
1187 entry and first child
1189 tree show current headline, its direct ancestors and all
1190 their children; if point is not on headline, also show
1191 entry and all children
1193 canonical show current headline, its direct ancestors along with
1194 their entries and children; if point is not located on
1195 the headline, also show current entry and all children
1197 As special cases, a nil or t value means show all contexts in
1198 `minimal' or `canonical' view, respectively.
1200 Some views can make displayed information very compact, but also
1201 make it harder to edit the location of the match. In such
1202 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1203 more context."
1204 :group 'org-reveal-location
1205 :version "25.2"
1206 :package-version '(Org . "9.0")
1207 :type '(choice
1208 (const :tag "Canonical" t)
1209 (const :tag "Minimal" nil)
1210 (repeat :greedy t :tag "Individual contexts"
1211 (cons
1212 (choice :tag "Context"
1213 (const agenda)
1214 (const org-goto)
1215 (const occur-tree)
1216 (const tags-tree)
1217 (const link-search)
1218 (const mark-goto)
1219 (const bookmark-jump)
1220 (const isearch)
1221 (const default))
1222 (choice :tag "Detail level"
1223 (const minimal)
1224 (const local)
1225 (const ancestors)
1226 (const lineage)
1227 (const tree)
1228 (const canonical))))))
1230 (defcustom org-indirect-buffer-display 'other-window
1231 "How should indirect tree buffers be displayed?
1233 This applies to indirect buffers created with the commands
1234 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1236 Valid values are:
1237 current-window Display in the current window
1238 other-window Just display in another window.
1239 dedicated-frame Create one new frame, and re-use it each time.
1240 new-frame Make a new frame each time. Note that in this case
1241 previously-made indirect buffers are kept, and you need to
1242 kill these buffers yourself."
1243 :group 'org-structure
1244 :group 'org-agenda-windows
1245 :type '(choice
1246 (const :tag "In current window" current-window)
1247 (const :tag "In current frame, other window" other-window)
1248 (const :tag "Each time a new frame" new-frame)
1249 (const :tag "One dedicated frame" dedicated-frame)))
1251 (defcustom org-use-speed-commands nil
1252 "Non-nil means activate single letter commands at beginning of a headline.
1253 This may also be a function to test for appropriate locations where speed
1254 commands should be active.
1256 For example, to activate speed commands when the point is on any
1257 star at the beginning of the headline, you can do this:
1259 (setq org-use-speed-commands
1260 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1261 :group 'org-structure
1262 :type '(choice
1263 (const :tag "Never" nil)
1264 (const :tag "At beginning of headline stars" t)
1265 (function)))
1267 (defcustom org-speed-commands-user nil
1268 "Alist of additional speed commands.
1269 This list will be checked before `org-speed-commands-default'
1270 when the variable `org-use-speed-commands' is non-nil
1271 and when the cursor is at the beginning of a headline.
1272 The car if each entry is a string with a single letter, which must
1273 be assigned to `self-insert-command' in the global map.
1274 The cdr is either a command to be called interactively, a function
1275 to be called, or a form to be evaluated.
1276 An entry that is just a list with a single string will be interpreted
1277 as a descriptive headline that will be added when listing the speed
1278 commands in the Help buffer using the `?' speed command."
1279 :group 'org-structure
1280 :type '(repeat :value ("k" . ignore)
1281 (choice :value ("k" . ignore)
1282 (list :tag "Descriptive Headline" (string :tag "Headline"))
1283 (cons :tag "Letter and Command"
1284 (string :tag "Command letter")
1285 (choice
1286 (function)
1287 (sexp))))))
1289 (defcustom org-bookmark-names-plist
1290 '(:last-capture "org-capture-last-stored"
1291 :last-refile "org-refile-last-stored"
1292 :last-capture-marker "org-capture-last-stored-marker")
1293 "Names for bookmarks automatically set by some Org commands.
1294 This can provide strings as names for a number of bookmarks Org sets
1295 automatically. The following keys are currently implemented:
1296 :last-capture
1297 :last-capture-marker
1298 :last-refile
1299 When a key does not show up in the property list, the corresponding bookmark
1300 is not set."
1301 :group 'org-structure
1302 :type 'plist)
1304 (defgroup org-cycle nil
1305 "Options concerning visibility cycling in Org mode."
1306 :tag "Org Cycle"
1307 :group 'org-structure)
1309 (defcustom org-cycle-skip-children-state-if-no-children t
1310 "Non-nil means skip CHILDREN state in entries that don't have any."
1311 :group 'org-cycle
1312 :type 'boolean)
1314 (defcustom org-cycle-max-level nil
1315 "Maximum level which should still be subject to visibility cycling.
1316 Levels higher than this will, for cycling, be treated as text, not a headline.
1317 When `org-odd-levels-only' is set, a value of N in this variable actually
1318 means 2N-1 stars as the limiting headline.
1319 When nil, cycle all levels.
1320 Note that the limiting level of cycling is also influenced by
1321 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1322 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1323 than its value."
1324 :group 'org-cycle
1325 :type '(choice
1326 (const :tag "No limit" nil)
1327 (integer :tag "Maximum level")))
1329 (defcustom org-hide-block-startup nil
1330 "Non-nil means entering Org mode will fold all blocks.
1331 This can also be set in on a per-file basis with
1333 #+STARTUP: hideblocks
1334 #+STARTUP: showblocks"
1335 :group 'org-startup
1336 :group 'org-cycle
1337 :type 'boolean)
1339 (defcustom org-cycle-global-at-bob nil
1340 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1342 This makes it possible to do global cycling without having to use `S-TAB'
1343 or `\\[universal-argument] TAB'. For this special case to work, the first \
1344 line of the buffer
1345 must not be a headline -- it may be empty or some other text.
1347 When used in this way, `org-cycle-hook' is disabled temporarily to make
1348 sure the cursor stays at the beginning of the buffer.
1350 When this option is nil, don't do anything special at the beginning of
1351 the buffer."
1352 :group 'org-cycle
1353 :type 'boolean)
1355 (defcustom org-cycle-level-after-item/entry-creation t
1356 "Non-nil means cycle entry level or item indentation in new empty entries.
1358 When the cursor is at the end of an empty headline, i.e., with only stars
1359 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1360 and then all possible ancestor states, before returning to the original state.
1361 This makes data entry extremely fast: M-RET to create a new headline,
1362 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1364 When the cursor is at the end of an empty plain list item, one TAB will
1365 make it a subitem, two or more tabs will back up to make this an item
1366 higher up in the item hierarchy."
1367 :group 'org-cycle
1368 :type 'boolean)
1370 (defcustom org-cycle-emulate-tab t
1371 "Where should `org-cycle' emulate TAB.
1372 nil Never
1373 white Only in completely white lines
1374 whitestart Only at the beginning of lines, before the first non-white char
1375 t Everywhere except in headlines
1376 exc-hl-bol Everywhere except at the start of a headline
1377 If TAB is used in a place where it does not emulate TAB, the current subtree
1378 visibility is cycled."
1379 :group 'org-cycle
1380 :type '(choice (const :tag "Never" nil)
1381 (const :tag "Only in completely white lines" white)
1382 (const :tag "Before first char in a line" whitestart)
1383 (const :tag "Everywhere except in headlines" t)
1384 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1386 (defcustom org-cycle-separator-lines 2
1387 "Number of empty lines needed to keep an empty line between collapsed trees.
1388 If you leave an empty line between the end of a subtree and the following
1389 headline, this empty line is hidden when the subtree is folded.
1390 Org mode will leave (exactly) one empty line visible if the number of
1391 empty lines is equal or larger to the number given in this variable.
1392 So the default 2 means at least 2 empty lines after the end of a subtree
1393 are needed to produce free space between a collapsed subtree and the
1394 following headline.
1396 If the number is negative, and the number of empty lines is at least -N,
1397 all empty lines are shown.
1399 Special case: when 0, never leave empty lines in collapsed view."
1400 :group 'org-cycle
1401 :type 'integer)
1402 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1404 (defcustom org-pre-cycle-hook nil
1405 "Hook that is run before visibility cycling is happening.
1406 The function(s) in this hook must accept a single argument which indicates
1407 the new state that will be set right after running this hook. The
1408 argument is a symbol. Before a global state change, it can have the values
1409 `overview', `content', or `all'. Before a local state change, it can have
1410 the values `folded', `children', or `subtree'."
1411 :group 'org-cycle
1412 :type 'hook)
1414 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1415 org-cycle-hide-drawers
1416 org-cycle-show-empty-lines
1417 org-optimize-window-after-visibility-change)
1418 "Hook that is run after `org-cycle' has changed the buffer visibility.
1419 The function(s) in this hook must accept a single argument which indicates
1420 the new state that was set by the most recent `org-cycle' command. The
1421 argument is a symbol. After a global state change, it can have the values
1422 `overview', `contents', or `all'. After a local state change, it can have
1423 the values `folded', `children', or `subtree'."
1424 :group 'org-cycle
1425 :type 'hook
1426 :version "25.2"
1427 :package-version '(Org . "8.3"))
1429 (defgroup org-edit-structure nil
1430 "Options concerning structure editing in Org mode."
1431 :tag "Org Edit Structure"
1432 :group 'org-structure)
1434 (defcustom org-odd-levels-only nil
1435 "Non-nil means skip even levels and only use odd levels for the outline.
1436 This has the effect that two stars are being added/taken away in
1437 promotion/demotion commands. It also influences how levels are
1438 handled by the exporters.
1439 Changing it requires restart of `font-lock-mode' to become effective
1440 for fontification also in regions already fontified.
1441 You may also set this on a per-file basis by adding one of the following
1442 lines to the buffer:
1444 #+STARTUP: odd
1445 #+STARTUP: oddeven"
1446 :group 'org-edit-structure
1447 :group 'org-appearance
1448 :type 'boolean)
1450 (defcustom org-adapt-indentation t
1451 "Non-nil means adapt indentation to outline node level.
1453 When this variable is set, Org assumes that you write outlines by
1454 indenting text in each node to align with the headline (after the
1455 stars). The following issues are influenced by this variable:
1457 - The indentation is increased by one space in a demotion
1458 command, and decreased by one in a promotion command. However,
1459 in the latter case, if shifting some line in the entry body
1460 would alter document structure (e.g., insert a new headline),
1461 indentation is not changed at all.
1463 - Property drawers and planning information is inserted indented
1464 when this variable is set. When nil, they will not be indented.
1466 - TAB indents a line relative to current level. The lines below
1467 a headline will be indented when this variable is set.
1469 Note that this is all about true indentation, by adding and
1470 removing space characters. See also `org-indent.el' which does
1471 level-dependent indentation in a virtual way, i.e. at display
1472 time in Emacs."
1473 :group 'org-edit-structure
1474 :type 'boolean)
1476 (defcustom org-special-ctrl-a/e nil
1477 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1479 When t, `C-a' will bring back the cursor to the beginning of the
1480 headline text, i.e. after the stars and after a possible TODO
1481 keyword. In an item, this will be the position after bullet and
1482 check-box, if any. When the cursor is already at that position,
1483 another `C-a' will bring it to the beginning of the line.
1485 `C-e' will jump to the end of the headline, ignoring the presence
1486 of tags in the headline. A second `C-e' will then jump to the
1487 true end of the line, after any tags. This also means that, when
1488 this variable is non-nil, `C-e' also will never jump beyond the
1489 end of the heading of a folded section, i.e. not after the
1490 ellipses.
1492 When set to the symbol `reversed', the first `C-a' or `C-e' works
1493 normally, going to the true line boundary first. Only a directly
1494 following, identical keypress will bring the cursor to the
1495 special positions.
1497 This may also be a cons cell where the behavior for `C-a' and
1498 `C-e' is set separately."
1499 :group 'org-edit-structure
1500 :type '(choice
1501 (const :tag "off" nil)
1502 (const :tag "on: after stars/bullet and before tags first" t)
1503 (const :tag "reversed: true line boundary first" reversed)
1504 (cons :tag "Set C-a and C-e separately"
1505 (choice :tag "Special C-a"
1506 (const :tag "off" nil)
1507 (const :tag "on: after stars/bullet first" t)
1508 (const :tag "reversed: before stars/bullet first" reversed))
1509 (choice :tag "Special C-e"
1510 (const :tag "off" nil)
1511 (const :tag "on: before tags first" t)
1512 (const :tag "reversed: after tags first" reversed)))))
1513 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1515 (defcustom org-special-ctrl-k nil
1516 "Non-nil means `C-k' will behave specially in headlines.
1517 When nil, `C-k' will call the default `kill-line' command.
1518 When t, the following will happen while the cursor is in the headline:
1520 - When the cursor is at the beginning of a headline, kill the entire
1521 line and possible the folded subtree below the line.
1522 - When in the middle of the headline text, kill the headline up to the tags.
1523 - When after the headline text, kill the tags."
1524 :group 'org-edit-structure
1525 :type 'boolean)
1527 (defcustom org-ctrl-k-protect-subtree nil
1528 "Non-nil means, do not delete a hidden subtree with C-k.
1529 When set to the symbol `error', simply throw an error when C-k is
1530 used to kill (part-of) a headline that has hidden text behind it.
1531 Any other non-nil value will result in a query to the user, if it is
1532 OK to kill that hidden subtree. When nil, kill without remorse."
1533 :group 'org-edit-structure
1534 :version "24.1"
1535 :type '(choice
1536 (const :tag "Do not protect hidden subtrees" nil)
1537 (const :tag "Protect hidden subtrees with a security query" t)
1538 (const :tag "Never kill a hidden subtree with C-k" error)))
1540 (defcustom org-special-ctrl-o t
1541 "Non-nil means, make `C-o' insert a row in tables."
1542 :group 'org-edit-structure
1543 :type 'boolean)
1545 (defcustom org-catch-invisible-edits nil
1546 "Check if in invisible region before inserting or deleting a character.
1547 Valid values are:
1549 nil Do not check, so just do invisible edits.
1550 error Throw an error and do nothing.
1551 show Make point visible, and do the requested edit.
1552 show-and-error Make point visible, then throw an error and abort the edit.
1553 smart Make point visible, and do insertion/deletion if it is
1554 adjacent to visible text and the change feels predictable.
1555 Never delete a previously invisible character or add in the
1556 middle or right after an invisible region. Basically, this
1557 allows insertion and backward-delete right before ellipses.
1558 FIXME: maybe in this case we should not even show?"
1559 :group 'org-edit-structure
1560 :version "24.1"
1561 :type '(choice
1562 (const :tag "Do not check" nil)
1563 (const :tag "Throw error when trying to edit" error)
1564 (const :tag "Unhide, but do not do the edit" show-and-error)
1565 (const :tag "Show invisible part and do the edit" show)
1566 (const :tag "Be smart and do the right thing" smart)))
1568 (defcustom org-yank-folded-subtrees t
1569 "Non-nil means when yanking subtrees, fold them.
1570 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1571 it starts with a heading and all other headings in it are either children
1572 or siblings, then fold all the subtrees. However, do this only if no
1573 text after the yank would be swallowed into a folded tree by this action."
1574 :group 'org-edit-structure
1575 :type 'boolean)
1577 (defcustom org-yank-adjusted-subtrees nil
1578 "Non-nil means when yanking subtrees, adjust the level.
1579 With this setting, `org-paste-subtree' is used to insert the subtree, see
1580 this function for details."
1581 :group 'org-edit-structure
1582 :type 'boolean)
1584 (defcustom org-M-RET-may-split-line '((default . t))
1585 "Non-nil means M-RET will split the line at the cursor position.
1586 When nil, it will go to the end of the line before making a
1587 new line.
1588 You may also set this option in a different way for different
1589 contexts. Valid contexts are:
1591 headline when creating a new headline
1592 item when creating a new item
1593 table in a table field
1594 default the value to be used for all contexts not explicitly
1595 customized"
1596 :group 'org-structure
1597 :group 'org-table
1598 :type '(choice
1599 (const :tag "Always" t)
1600 (const :tag "Never" nil)
1601 (repeat :greedy t :tag "Individual contexts"
1602 (cons
1603 (choice :tag "Context"
1604 (const headline)
1605 (const item)
1606 (const table)
1607 (const default))
1608 (boolean)))))
1611 (defcustom org-insert-heading-respect-content nil
1612 "Non-nil means insert new headings after the current subtree.
1613 \\<org-mode-map>
1614 When nil, the new heading is created directly after the current line.
1615 The commands `\\[org-insert-heading-respect-content]' and \
1616 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1617 for the duration of the command."
1618 :group 'org-structure
1619 :type 'boolean)
1621 (defcustom org-blank-before-new-entry '((heading . auto)
1622 (plain-list-item . auto))
1623 "Should `org-insert-heading' leave a blank line before new heading/item?
1624 The value is an alist, with `heading' and `plain-list-item' as CAR,
1625 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1626 which case Org will look at the surrounding headings/items and try to
1627 make an intelligent decision whether to insert a blank line or not."
1628 :group 'org-edit-structure
1629 :type '(list
1630 (cons (const heading)
1631 (choice (const :tag "Never" nil)
1632 (const :tag "Always" t)
1633 (const :tag "Auto" auto)))
1634 (cons (const plain-list-item)
1635 (choice (const :tag "Never" nil)
1636 (const :tag "Always" t)
1637 (const :tag "Auto" auto)))))
1639 (defcustom org-insert-heading-hook nil
1640 "Hook being run after inserting a new heading."
1641 :group 'org-edit-structure
1642 :type 'hook)
1644 (defcustom org-enable-fixed-width-editor t
1645 "Non-nil means lines starting with \":\" are treated as fixed-width.
1646 This currently only means they are never auto-wrapped.
1647 When nil, such lines will be treated like ordinary lines."
1648 :group 'org-edit-structure
1649 :type 'boolean)
1651 (defcustom org-goto-auto-isearch t
1652 "Non-nil means typing characters in `org-goto' starts incremental search.
1653 When nil, you can use these keybindings to navigate the buffer:
1655 q Quit the org-goto interface
1656 n Go to the next visible heading
1657 p Go to the previous visible heading
1658 f Go one heading forward on same level
1659 b Go one heading backward on same level
1660 u Go one heading up"
1661 :group 'org-edit-structure
1662 :type 'boolean)
1664 (defgroup org-sparse-trees nil
1665 "Options concerning sparse trees in Org mode."
1666 :tag "Org Sparse Trees"
1667 :group 'org-structure)
1669 (defcustom org-highlight-sparse-tree-matches t
1670 "Non-nil means highlight all matches that define a sparse tree.
1671 The highlights will automatically disappear the next time the buffer is
1672 changed by an edit command."
1673 :group 'org-sparse-trees
1674 :type 'boolean)
1676 (defcustom org-remove-highlights-with-change t
1677 "Non-nil means any change to the buffer will remove temporary highlights.
1678 \\<org-mode-map>\
1679 Such highlights are created by `org-occur' and `org-clock-display'.
1680 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1681 to get rid of the highlights.
1682 The highlights created by `org-toggle-latex-fragment' always need
1683 `\\[org-toggle-latex-fragment]' to be removed."
1684 :group 'org-sparse-trees
1685 :group 'org-time
1686 :type 'boolean)
1688 (defcustom org-occur-case-fold-search t
1689 "Non-nil means `org-occur' should be case-insensitive.
1690 If set to `smart' the search will be case-insensitive only if it
1691 doesn't specify any upper case character."
1692 :group 'org-sparse-trees
1693 :version "25.2"
1694 :type '(choice
1695 (const :tag "Case-sensitive" nil)
1696 (const :tag "Case-insensitive" t)
1697 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1699 (defcustom org-occur-hook '(org-first-headline-recenter)
1700 "Hook that is run after `org-occur' has constructed a sparse tree.
1701 This can be used to recenter the window to show as much of the structure
1702 as possible."
1703 :group 'org-sparse-trees
1704 :type 'hook)
1706 (defgroup org-imenu-and-speedbar nil
1707 "Options concerning imenu and speedbar in Org mode."
1708 :tag "Org Imenu and Speedbar"
1709 :group 'org-structure)
1711 (defcustom org-imenu-depth 2
1712 "The maximum level for Imenu access to Org headlines.
1713 This also applied for speedbar access."
1714 :group 'org-imenu-and-speedbar
1715 :type 'integer)
1717 (defgroup org-table nil
1718 "Options concerning tables in Org mode."
1719 :tag "Org Table"
1720 :group 'org)
1722 (defcustom org-enable-table-editor 'optimized
1723 "Non-nil means lines starting with \"|\" are handled by the table editor.
1724 When nil, such lines will be treated like ordinary lines.
1726 When equal to the symbol `optimized', the table editor will be optimized to
1727 do the following:
1728 - Automatic overwrite mode in front of whitespace in table fields.
1729 This makes the structure of the table stay in tact as long as the edited
1730 field does not exceed the column width.
1731 - Minimize the number of realigns. Normally, the table is aligned each time
1732 TAB or RET are pressed to move to another field. With optimization this
1733 happens only if changes to a field might have changed the column width.
1734 Optimization requires replacing the functions `self-insert-command',
1735 `delete-char', and `backward-delete-char' in Org buffers, with a
1736 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1737 good at guessing when a re-align will be necessary, but you can always
1738 force one with `\\[org-ctrl-c-ctrl-c]'.
1740 If you would like to use the optimized version in Org mode, but the
1741 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1743 This variable can be used to turn on and off the table editor during a session,
1744 but in order to toggle optimization, a restart is required.
1746 See also the variable `org-table-auto-blank-field'."
1747 :group 'org-table
1748 :type '(choice
1749 (const :tag "off" nil)
1750 (const :tag "on" t)
1751 (const :tag "on, optimized" optimized)))
1753 (defcustom org-self-insert-cluster-for-undo nil
1754 "Non-nil means cluster self-insert commands for undo when possible.
1755 If this is set, then, like in the Emacs command loop, 20 consecutive
1756 characters will be undone together.
1757 This is configurable, because there is some impact on typing performance."
1758 :group 'org-table
1759 :type 'boolean)
1761 (defcustom org-table-tab-recognizes-table.el t
1762 "Non-nil means TAB will automatically notice a table.el table.
1763 When it sees such a table, it moves point into it and - if necessary -
1764 calls `table-recognize-table'."
1765 :group 'org-table-editing
1766 :type 'boolean)
1768 (defgroup org-link nil
1769 "Options concerning links in Org mode."
1770 :tag "Org Link"
1771 :group 'org)
1773 (defvar-local org-link-abbrev-alist-local nil
1774 "Buffer-local version of `org-link-abbrev-alist', which see.
1775 The value of this is taken from the #+LINK lines.")
1777 (defcustom org-link-parameters
1778 '(("doi" :follow org--open-doi-link)
1779 ("elisp" :follow org--open-elisp-link)
1780 ("file" :complete org-file-complete-link)
1781 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1782 ("help" :follow org--open-help-link)
1783 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1784 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1785 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1786 ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
1787 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1788 ("shell" :follow org--open-shell-link))
1789 "An alist of properties that defines all the links in Org mode.
1790 The key in each association is a string of the link type.
1791 Subsequent optional elements make up a p-list of link properties.
1793 :follow - A function that takes the link path as an argument.
1795 :export - A function that takes the link path, description and
1796 export-backend as arguments.
1798 :store - A function responsible for storing the link. See the
1799 function `org-store-link-functions'.
1801 :complete - A function that inserts a link with completion. The
1802 function takes one optional prefix arg.
1804 :face - A face for the link, or a function that returns a face.
1805 The function takes one argument which is the link path. The
1806 default face is `org-link'.
1808 :mouse-face - The mouse-face. The default is `highlight'.
1810 :display - `full' will not fold the link in descriptive
1811 display. Default is `org-link'.
1813 :help-echo - A string or function that takes (window object position)
1814 as arguments and returns a string.
1816 :keymap - A keymap that is active on the link. The default is
1817 `org-mouse-map'.
1819 :htmlize-link - A function for the htmlize-link. Defaults
1820 to (list :uri \"type:path\")
1822 :activate-func - A function to run at the end of font-lock
1823 activation. The function must accept (link-start link-end path bracketp)
1824 as arguments."
1825 :group 'org-link
1826 :type '(alist :tag "Link display parameters"
1827 :value-type plist))
1829 (defun org-link-get-parameter (type key)
1830 "Get TYPE link property for KEY.
1831 TYPE is a string and KEY is a plist keyword."
1832 (plist-get
1833 (cdr (assoc type org-link-parameters))
1834 key))
1836 (defun org-link-set-parameters (type &rest parameters)
1837 "Set link TYPE properties to PARAMETERS.
1838 PARAMETERS should be :key val pairs."
1839 (let ((data (assoc type org-link-parameters)))
1840 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1841 (push (cons type parameters) org-link-parameters)
1842 (org-make-link-regexps)
1843 (org-element-update-syntax))))
1845 (defun org-link-types ()
1846 "Return a list of known link types."
1847 (mapcar #'car org-link-parameters))
1849 (defcustom org-link-abbrev-alist nil
1850 "Alist of link abbreviations.
1851 The car of each element is a string, to be replaced at the start of a link.
1852 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1853 links in Org buffers can have an optional tag after a double colon, e.g.,
1855 [[linkkey:tag][description]]
1857 The `linkkey' must be a single word, starting with a letter, followed
1858 by letters, numbers, `-' or `_'.
1860 If REPLACE is a string, the tag will simply be appended to create the link.
1861 If the string contains \"%s\", the tag will be inserted there. If the string
1862 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1863 at that point (see the function `url-hexify-string'). If the string contains
1864 the specifier \"%(my-function)\", then the custom function `my-function' will
1865 be invoked: this function takes the tag as its only argument and must return
1866 a string.
1868 REPLACE may also be a function that will be called with the tag as the
1869 only argument to create the link, which should be returned as a string.
1871 See the manual for examples."
1872 :group 'org-link
1873 :type '(repeat
1874 (cons
1875 (string :tag "Protocol")
1876 (choice
1877 (string :tag "Format")
1878 (function)))))
1880 (defcustom org-descriptive-links t
1881 "Non-nil means Org will display descriptive links.
1882 E.g. [[http://orgmode.org][Org website]] will be displayed as
1883 \"Org Website\", hiding the link itself and just displaying its
1884 description. When set to nil, Org will display the full links
1885 literally.
1887 You can interactively set the value of this variable by calling
1888 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1889 :group 'org-link
1890 :type 'boolean)
1892 (defcustom org-link-file-path-type 'adaptive
1893 "How the path name in file links should be stored.
1894 Valid values are:
1896 relative Relative to the current directory, i.e. the directory of the file
1897 into which the link is being inserted.
1898 absolute Absolute path, if possible with ~ for home directory.
1899 noabbrev Absolute path, no abbreviation of home directory.
1900 adaptive Use relative path for files in the current directory and sub-
1901 directories of it. For other files, use an absolute path."
1902 :group 'org-link
1903 :type '(choice
1904 (const relative)
1905 (const absolute)
1906 (const noabbrev)
1907 (const adaptive)))
1909 (defvaralias 'org-activate-links 'org-highlight-links)
1910 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1911 "Types of links that should be highlighted in Org files.
1913 This is a list of symbols, each one of them leading to the
1914 highlighting of a certain link type.
1916 You can still open links that are not highlighted.
1918 In principle, it does not hurt to turn on highlighting for all
1919 link types. There may be a small gain when turning off unused
1920 link types. The types are:
1922 bracket The recommended [[link][description]] or [[link]] links with hiding.
1923 angle Links in angular brackets that may contain whitespace like
1924 <bbdb:Carsten Dominik>.
1925 plain Plain links in normal text, no whitespace, like http://google.com.
1926 radio Text that is matched by a radio target, see manual for details.
1927 tag Tag settings in a headline (link to tag search).
1928 date Time stamps (link to calendar).
1929 footnote Footnote labels.
1931 If you set this variable during an Emacs session, use `org-mode-restart'
1932 in the Org buffer so that the change takes effect."
1933 :group 'org-link
1934 :group 'org-appearance
1935 :type '(set :greedy t
1936 (const :tag "Double bracket links" bracket)
1937 (const :tag "Angular bracket links" angle)
1938 (const :tag "Plain text links" plain)
1939 (const :tag "Radio target matches" radio)
1940 (const :tag "Tags" tag)
1941 (const :tag "Timestamps" date)
1942 (const :tag "Footnotes" footnote)))
1944 (defcustom org-make-link-description-function nil
1945 "Function to use for generating link descriptions from links.
1946 When nil, the link location will be used. This function must take
1947 two parameters: the first one is the link, the second one is the
1948 description generated by `org-insert-link'. The function should
1949 return the description to use."
1950 :group 'org-link
1951 :type '(choice (const nil) (function)))
1953 (defgroup org-link-store nil
1954 "Options concerning storing links in Org mode."
1955 :tag "Org Store Link"
1956 :group 'org-link)
1958 (defcustom org-url-hexify-p t
1959 "When non-nil, hexify URL when creating a link."
1960 :type 'boolean
1961 :version "24.3"
1962 :group 'org-link-store)
1964 (defcustom org-email-link-description-format "Email %c: %.30s"
1965 "Format of the description part of a link to an email or usenet message.
1966 The following %-escapes will be replaced by corresponding information:
1968 %F full \"From\" field
1969 %f name, taken from \"From\" field, address if no name
1970 %T full \"To\" field
1971 %t first name in \"To\" field, address if no name
1972 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1973 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1974 %s subject
1975 %d date
1976 %m message-id.
1978 You may use normal field width specification between the % and the letter.
1979 This is for example useful to limit the length of the subject.
1981 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1982 :group 'org-link-store
1983 :type 'string)
1985 (defcustom org-from-is-user-regexp
1986 (let (r1 r2)
1987 (when (and user-mail-address (not (string= user-mail-address "")))
1988 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1989 (when (and user-full-name (not (string= user-full-name "")))
1990 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1991 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1992 "Regexp matched against the \"From:\" header of an email or usenet message.
1993 It should match if the message is from the user him/herself."
1994 :group 'org-link-store
1995 :type 'regexp)
1997 (defcustom org-context-in-file-links t
1998 "Non-nil means file links from `org-store-link' contain context.
1999 \\<org-mode-map>
2000 A search string will be added to the file name with :: as separator
2001 and used to find the context when the link is activated by the command
2002 `org-open-at-point'. When this option is t, the entire active region
2003 will be placed in the search string of the file link. If set to a
2004 positive integer, only the first n lines of context will be stored.
2006 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2007 \\[org-store-link]')
2008 negates this setting for the duration of the command."
2009 :group 'org-link-store
2010 :type '(choice boolean integer))
2012 (defcustom org-keep-stored-link-after-insertion nil
2013 "Non-nil means keep link in list for entire session.
2014 \\<org-mode-map>
2015 The command `org-store-link' adds a link pointing to the current
2016 location to an internal list. These links accumulate during a session.
2017 The command `org-insert-link' can be used to insert links into any
2018 Org file (offering completion for all stored links).
2020 When this option is nil, every link which has been inserted once using
2021 `\\[org-insert-link]' will be removed from the list, to make completing the \
2022 unused
2023 links more efficient."
2024 :group 'org-link-store
2025 :type 'boolean)
2027 (defgroup org-link-follow nil
2028 "Options concerning following links in Org mode."
2029 :tag "Org Follow Link"
2030 :group 'org-link)
2032 (defcustom org-link-translation-function nil
2033 "Function to translate links with different syntax to Org syntax.
2034 This can be used to translate links created for example by the Planner
2035 or emacs-wiki packages to Org syntax.
2036 The function must accept two parameters, a TYPE containing the link
2037 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2038 which is everything after the link protocol. It should return a cons
2039 with possibly modified values of type and path.
2040 Org contains a function for this, so if you set this variable to
2041 `org-translate-link-from-planner', you should be able follow many
2042 links created by planner."
2043 :group 'org-link-follow
2044 :type '(choice (const nil) (function)))
2046 (defcustom org-follow-link-hook nil
2047 "Hook that is run after a link has been followed."
2048 :group 'org-link-follow
2049 :type 'hook)
2051 (defcustom org-tab-follows-link nil
2052 "Non-nil means on links TAB will follow the link.
2053 Needs to be set before org.el is loaded.
2054 This really should not be used, it does not make sense, and the
2055 implementation is bad."
2056 :group 'org-link-follow
2057 :type 'boolean)
2059 (defcustom org-return-follows-link nil
2060 "Non-nil means on links RET will follow the link.
2061 In tables, the special behavior of RET has precedence."
2062 :group 'org-link-follow
2063 :type 'boolean)
2065 (defcustom org-mouse-1-follows-link
2066 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2067 "Non-nil means mouse-1 on a link will follow the link.
2068 A longer mouse click will still set point. Needs to be set
2069 before org.el is loaded."
2070 :group 'org-link-follow
2071 :version "24.4"
2072 :package-version '(Org . "8.3")
2073 :type '(choice
2074 (const :tag "A double click follows the link" double)
2075 (const :tag "Unconditionally follow the link with mouse-1" t)
2076 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2078 (defcustom org-mark-ring-length 4
2079 "Number of different positions to be recorded in the ring.
2080 Changing this requires a restart of Emacs to work correctly."
2081 :group 'org-link-follow
2082 :type 'integer)
2084 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2085 "Non-nil means internal links in Org files must exactly match a headline.
2086 When nil, the link search tries to match a phrase with all words
2087 in the search text."
2088 :group 'org-link-follow
2089 :version "24.1"
2090 :type '(choice
2091 (const :tag "Use fuzzy text search" nil)
2092 (const :tag "Match only exact headline" t)
2093 (const :tag "Match exact headline or query to create it"
2094 query-to-create)))
2096 (defcustom org-link-frame-setup
2097 '((vm . vm-visit-folder-other-frame)
2098 (vm-imap . vm-visit-imap-folder-other-frame)
2099 (gnus . org-gnus-no-new-news)
2100 (file . find-file-other-window)
2101 (wl . wl-other-frame))
2102 "Setup the frame configuration for following links.
2103 When following a link with Emacs, it may often be useful to display
2104 this link in another window or frame. This variable can be used to
2105 set this up for the different types of links.
2106 For VM, use any of
2107 `vm-visit-folder'
2108 `vm-visit-folder-other-window'
2109 `vm-visit-folder-other-frame'
2110 For Gnus, use any of
2111 `gnus'
2112 `gnus-other-frame'
2113 `org-gnus-no-new-news'
2114 For FILE, use any of
2115 `find-file'
2116 `find-file-other-window'
2117 `find-file-other-frame'
2118 For Wanderlust use any of
2119 `wl'
2120 `wl-other-frame'
2121 For the calendar, use the variable `calendar-setup'.
2122 For BBDB, it is currently only possible to display the matches in
2123 another window."
2124 :group 'org-link-follow
2125 :type '(list
2126 (cons (const vm)
2127 (choice
2128 (const vm-visit-folder)
2129 (const vm-visit-folder-other-window)
2130 (const vm-visit-folder-other-frame)))
2131 (cons (const vm-imap)
2132 (choice
2133 (const vm-visit-imap-folder)
2134 (const vm-visit-imap-folder-other-window)
2135 (const vm-visit-imap-folder-other-frame)))
2136 (cons (const gnus)
2137 (choice
2138 (const gnus)
2139 (const gnus-other-frame)
2140 (const org-gnus-no-new-news)))
2141 (cons (const file)
2142 (choice
2143 (const find-file)
2144 (const find-file-other-window)
2145 (const find-file-other-frame)))
2146 (cons (const wl)
2147 (choice
2148 (const wl)
2149 (const wl-other-frame)))))
2151 (defcustom org-display-internal-link-with-indirect-buffer nil
2152 "Non-nil means use indirect buffer to display infile links.
2153 Activating internal links (from one location in a file to another location
2154 in the same file) normally just jumps to the location. When the link is
2155 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2156 is displayed in
2157 another window. When this option is set, the other window actually displays
2158 an indirect buffer clone of the current buffer, to avoid any visibility
2159 changes to the current buffer."
2160 :group 'org-link-follow
2161 :type 'boolean)
2163 (defcustom org-open-non-existing-files nil
2164 "Non-nil means `org-open-file' will open non-existing files.
2165 When nil, an error will be generated.
2166 This variable applies only to external applications because they
2167 might choke on non-existing files. If the link is to a file that
2168 will be opened in Emacs, the variable is ignored."
2169 :group 'org-link-follow
2170 :type 'boolean)
2172 (defcustom org-open-directory-means-index-dot-org nil
2173 "Non-nil means a link to a directory really means to index.org.
2174 When nil, following a directory link will run dired or open a finder/explorer
2175 window on that directory."
2176 :group 'org-link-follow
2177 :type 'boolean)
2179 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2180 "Non-nil means ask for confirmation before executing shell links.
2181 Shell links can be dangerous: just think about a link
2183 [[shell:rm -rf ~/*][Google Search]]
2185 This link would show up in your Org document as \"Google Search\",
2186 but really it would remove your entire home directory.
2187 Therefore we advise against setting this variable to nil.
2188 Just change it to `y-or-n-p' if you want to confirm with a
2189 single keystroke rather than having to type \"yes\"."
2190 :group 'org-link-follow
2191 :type '(choice
2192 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2193 (const :tag "with y-or-n (faster)" y-or-n-p)
2194 (const :tag "no confirmation (dangerous)" nil)))
2195 (put 'org-confirm-shell-link-function
2196 'safe-local-variable
2197 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2199 (defcustom org-confirm-shell-link-not-regexp ""
2200 "A regexp to skip confirmation for shell links."
2201 :group 'org-link-follow
2202 :version "24.1"
2203 :type 'regexp)
2205 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2206 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2207 Elisp links can be dangerous: just think about a link
2209 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2211 This link would show up in your Org document as \"Google Search\",
2212 but really it would remove your entire home directory.
2213 Therefore we advise against setting this variable to nil.
2214 Just change it to `y-or-n-p' if you want to confirm with a
2215 single keystroke rather than having to type \"yes\"."
2216 :group 'org-link-follow
2217 :type '(choice
2218 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2219 (const :tag "with y-or-n (faster)" y-or-n-p)
2220 (const :tag "no confirmation (dangerous)" nil)))
2221 (put 'org-confirm-shell-link-function
2222 'safe-local-variable
2223 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2225 (defcustom org-confirm-elisp-link-not-regexp ""
2226 "A regexp to skip confirmation for Elisp links."
2227 :group 'org-link-follow
2228 :version "24.1"
2229 :type 'regexp)
2231 (defconst org-file-apps-defaults-gnu
2232 '((remote . emacs)
2233 (system . mailcap)
2234 (t . mailcap))
2235 "Default file applications on a UNIX or GNU/Linux system.
2236 See `org-file-apps'.")
2238 (defconst org-file-apps-defaults-macosx
2239 '((remote . emacs)
2240 (system . "open %s")
2241 ("ps.gz" . "gv %s")
2242 ("eps.gz" . "gv %s")
2243 ("dvi" . "xdvi %s")
2244 ("fig" . "xfig %s")
2245 (t . "open %s"))
2246 "Default file applications on a MacOS X system.
2247 The system \"open\" is known as a default, but we use X11 applications
2248 for some files for which the OS does not have a good default.
2249 See `org-file-apps'.")
2251 (defconst org-file-apps-defaults-windowsnt
2252 (list '(remote . emacs)
2253 (cons 'system (lambda (file _path)
2254 (with-no-warnings (w32-shell-execute "open" file))))
2255 (cons t (lambda (file _path)
2256 (with-no-warnings (w32-shell-execute "open" file)))))
2257 "Default file applications on a Windows NT system.
2258 The system \"open\" is used for most files.
2259 See `org-file-apps'.")
2261 (defcustom org-file-apps
2262 '((auto-mode . emacs)
2263 ("\\.mm\\'" . default)
2264 ("\\.x?html?\\'" . default)
2265 ("\\.pdf\\'" . default))
2266 "External applications for opening `file:path' items in a document.
2267 \\<org-mode-map>\
2269 Org mode uses system defaults for different file types, but
2270 you can use this variable to set the application for a given file
2271 extension. The entries in this list are cons cells where the car identifies
2272 files and the cdr the corresponding command.
2274 Possible values for the file identifier are:
2276 \"string\" A string as a file identifier can be interpreted in different
2277 ways, depending on its contents:
2279 - Alphanumeric characters only:
2280 Match links with this file extension.
2281 Example: (\"pdf\" . \"evince %s\")
2282 to open PDFs with evince.
2284 - Regular expression: Match links where the
2285 filename matches the regexp. If you want to
2286 use groups here, use shy groups.
2288 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2289 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2290 to open *.html and *.xhtml with firefox.
2292 - Regular expression which contains (non-shy) groups:
2293 Match links where the whole link, including \"::\", and
2294 anything after that, matches the regexp.
2295 In a custom command string, %1, %2, etc. are replaced with
2296 the parts of the link that were matched by the groups.
2297 For backwards compatibility, if a command string is given
2298 that does not use any of the group matches, this case is
2299 handled identically to the second one (i.e. match against
2300 file name only).
2301 In a custom function, you can access the group matches with
2302 \(match-string n link).
2304 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2305 \"evince -p %1 %s\")
2306 to open [[file:document.pdf::5]] with evince at page 5.
2308 `directory' Matches a directory
2309 `remote' Matches a remote file, accessible through tramp or efs.
2310 Remote files most likely should be visited through Emacs
2311 because external applications cannot handle such paths.
2312 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2313 so all files Emacs knows how to handle. Using this with
2314 command `emacs' will open most files in Emacs. Beware that this
2315 will also open html files inside Emacs, unless you add
2316 \(\"html\" . default) to the list as well.
2317 `system' The system command to open files, like `open' on Windows
2318 and Mac OS X, and mailcap under GNU/Linux. This is the command
2319 that will be selected if you call `org-open-at-point' with a
2320 double prefix argument (`\\[universal-argument] \
2321 \\[universal-argument] \\[org-open-at-point]').
2322 t Default for files not matched by any of the other options.
2324 Possible values for the command are:
2326 `emacs' The file will be visited by the current Emacs process.
2327 `default' Use the default application for this file type, which is the
2328 association for t in the list, most likely in the system-specific
2329 part. This can be used to overrule an unwanted setting in the
2330 system-specific variable.
2331 `system' Use the system command for opening files, like \"open\".
2332 This command is specified by the entry whose car is `system'.
2333 Most likely, the system-specific version of this variable
2334 does define this command, but you can overrule/replace it
2335 here.
2336 `mailcap' Use command specified in the mailcaps.
2337 string A command to be executed by a shell; %s will be replaced
2338 by the path to the file.
2339 function A Lisp function, which will be called with two arguments:
2340 the file path and the original link string, without the
2341 \"file:\" prefix.
2343 For more examples, see the system specific constants
2344 `org-file-apps-defaults-macosx'
2345 `org-file-apps-defaults-windowsnt'
2346 `org-file-apps-defaults-gnu'."
2347 :group 'org-link-follow
2348 :type '(repeat
2349 (cons (choice :value ""
2350 (string :tag "Extension")
2351 (const :tag "System command to open files" system)
2352 (const :tag "Default for unrecognized files" t)
2353 (const :tag "Remote file" remote)
2354 (const :tag "Links to a directory" directory)
2355 (const :tag "Any files that have Emacs modes"
2356 auto-mode))
2357 (choice :value ""
2358 (const :tag "Visit with Emacs" emacs)
2359 (const :tag "Use default" default)
2360 (const :tag "Use the system command" system)
2361 (string :tag "Command")
2362 (function :tag "Function")))))
2364 (defcustom org-doi-server-url "http://dx.doi.org/"
2365 "The URL of the DOI server."
2366 :type 'string
2367 :version "24.3"
2368 :group 'org-link-follow)
2370 (defgroup org-refile nil
2371 "Options concerning refiling entries in Org mode."
2372 :tag "Org Refile"
2373 :group 'org)
2375 (defcustom org-directory "~/org"
2376 "Directory with Org files.
2377 This is just a default location to look for Org files. There is no need
2378 at all to put your files into this directory. It is used in the
2379 following situations:
2381 1. When a capture template specifies a target file that is not an
2382 absolute path. The path will then be interpreted relative to
2383 `org-directory'
2384 2. When the value of variable `org-agenda-files' is a single file, any
2385 relative paths in this file will be taken as relative to
2386 `org-directory'."
2387 :group 'org-refile
2388 :group 'org-capture
2389 :type 'directory)
2391 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2392 "Default target for storing notes.
2393 Used as a fall back file for org-capture.el, for templates that
2394 do not specify a target file."
2395 :group 'org-refile
2396 :group 'org-capture
2397 :type 'file)
2399 (defcustom org-goto-interface 'outline
2400 "The default interface to be used for `org-goto'.
2401 Allowed values are:
2402 outline The interface shows an outline of the relevant file
2403 and the correct heading is found by moving through
2404 the outline or by searching with incremental search.
2405 outline-path-completion Headlines in the current buffer are offered via
2406 completion. This is the interface also used by
2407 the refile command."
2408 :group 'org-refile
2409 :type '(choice
2410 (const :tag "Outline" outline)
2411 (const :tag "Outline-path-completion" outline-path-completion)))
2413 (defcustom org-goto-max-level 5
2414 "Maximum target level when running `org-goto' with refile interface."
2415 :group 'org-refile
2416 :type 'integer)
2418 (defcustom org-reverse-note-order nil
2419 "Non-nil means store new notes at the beginning of a file or entry.
2420 When nil, new notes will be filed to the end of a file or entry.
2421 This can also be a list with cons cells of regular expressions that
2422 are matched against file names, and values."
2423 :group 'org-capture
2424 :group 'org-refile
2425 :type '(choice
2426 (const :tag "Reverse always" t)
2427 (const :tag "Reverse never" nil)
2428 (repeat :tag "By file name regexp"
2429 (cons regexp boolean))))
2431 (defcustom org-log-refile nil
2432 "Information to record when a task is refiled.
2434 Possible values are:
2436 nil Don't add anything
2437 time Add a time stamp to the task
2438 note Prompt for a note and add it with template `org-log-note-headings'
2440 This option can also be set with on a per-file-basis with
2442 #+STARTUP: nologrefile
2443 #+STARTUP: logrefile
2444 #+STARTUP: lognoterefile
2446 You can have local logging settings for a subtree by setting the LOGGING
2447 property to one or more of these keywords.
2449 When bulk-refiling from the agenda, the value `note' is forbidden and
2450 will temporarily be changed to `time'."
2451 :group 'org-refile
2452 :group 'org-progress
2453 :version "24.1"
2454 :type '(choice
2455 (const :tag "No logging" nil)
2456 (const :tag "Record timestamp" time)
2457 (const :tag "Record timestamp with note." note)))
2459 (defcustom org-refile-targets nil
2460 "Targets for refiling entries with `\\[org-refile]'.
2461 This is a list of cons cells. Each cell contains:
2462 - a specification of the files to be considered, either a list of files,
2463 or a symbol whose function or variable value will be used to retrieve
2464 a file name or a list of file names. If you use `org-agenda-files' for
2465 that, all agenda files will be scanned for targets. Nil means consider
2466 headings in the current buffer.
2467 - A specification of how to find candidate refile targets. This may be
2468 any of:
2469 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2470 This tag has to be present in all target headlines, inheritance will
2471 not be considered.
2472 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2473 todo keyword.
2474 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2475 headlines that are refiling targets.
2476 - a cons cell (:level . N). Any headline of level N is considered a target.
2477 Note that, when `org-odd-levels-only' is set, level corresponds to
2478 order in hierarchy, not to the number of stars.
2479 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2480 Note that, when `org-odd-levels-only' is set, level corresponds to
2481 order in hierarchy, not to the number of stars.
2483 Each element of this list generates a set of possible targets.
2484 The union of these sets is presented (with completion) to
2485 the user by `org-refile'.
2487 You can set the variable `org-refile-target-verify-function' to a function
2488 to verify each headline found by the simple criteria above.
2490 When this variable is nil, all top-level headlines in the current buffer
2491 are used, equivalent to the value `((nil . (:level . 1))'."
2492 :group 'org-refile
2493 :type '(repeat
2494 (cons
2495 (choice :value org-agenda-files
2496 (const :tag "All agenda files" org-agenda-files)
2497 (const :tag "Current buffer" nil)
2498 (function) (variable) (file))
2499 (choice :tag "Identify target headline by"
2500 (cons :tag "Specific tag" (const :value :tag) (string))
2501 (cons :tag "TODO keyword" (const :value :todo) (string))
2502 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2503 (cons :tag "Level number" (const :value :level) (integer))
2504 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2506 (defcustom org-refile-target-verify-function nil
2507 "Function to verify if the headline at point should be a refile target.
2508 The function will be called without arguments, with point at the
2509 beginning of the headline. It should return t and leave point
2510 where it is if the headline is a valid target for refiling.
2512 If the target should not be selected, the function must return nil.
2513 In addition to this, it may move point to a place from where the search
2514 should be continued. For example, the function may decide that the entire
2515 subtree of the current entry should be excluded and move point to the end
2516 of the subtree."
2517 :group 'org-refile
2518 :type '(choice
2519 (const nil)
2520 (function)))
2522 (defcustom org-refile-use-cache nil
2523 "Non-nil means cache refile targets to speed up the process.
2524 \\<org-mode-map>\
2525 The cache for a particular file will be updated automatically when
2526 the buffer has been killed, or when any of the marker used for flagging
2527 refile targets no longer points at a live buffer.
2528 If you have added new entries to a buffer that might themselves be targets,
2529 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2530 if you find that easier, \
2531 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2532 \\[org-refile]'."
2533 :group 'org-refile
2534 :version "24.1"
2535 :type 'boolean)
2537 (defcustom org-refile-use-outline-path nil
2538 "Non-nil means provide refile targets as paths.
2539 So a level 3 headline will be available as level1/level2/level3.
2541 When the value is `file', also include the file name (without directory)
2542 into the path. In this case, you can also stop the completion after
2543 the file name, to get entries inserted as top level in the file.
2545 When `full-file-path', include the full file path."
2546 :group 'org-refile
2547 :type '(choice
2548 (const :tag "Not" nil)
2549 (const :tag "Yes" t)
2550 (const :tag "Start with file name" file)
2551 (const :tag "Start with full file path" full-file-path)))
2553 (defcustom org-outline-path-complete-in-steps t
2554 "Non-nil means complete the outline path in hierarchical steps.
2555 When Org uses the refile interface to select an outline path (see
2556 `org-refile-use-outline-path'), the completion of the path can be
2557 done in a single go, or it can be done in steps down the headline
2558 hierarchy. Going in steps is probably the best if you do not use
2559 a special completion package like `ido' or `icicles'. However,
2560 when using these packages, going in one step can be very fast,
2561 while still showing the whole path to the entry."
2562 :group 'org-refile
2563 :type 'boolean)
2565 (defcustom org-refile-allow-creating-parent-nodes nil
2566 "Non-nil means allow the creation of new nodes as refile targets.
2567 New nodes are then created by adding \"/new node name\" to the completion
2568 of an existing node. When the value of this variable is `confirm',
2569 new node creation must be confirmed by the user (recommended).
2570 When nil, the completion must match an existing entry.
2572 Note that, if the new heading is not seen by the criteria
2573 listed in `org-refile-targets', multiple instances of the same
2574 heading would be created by trying again to file under the new
2575 heading."
2576 :group 'org-refile
2577 :type '(choice
2578 (const :tag "Never" nil)
2579 (const :tag "Always" t)
2580 (const :tag "Prompt for confirmation" confirm)))
2582 (defcustom org-refile-active-region-within-subtree nil
2583 "Non-nil means also refile active region within a subtree.
2585 By default `org-refile' doesn't allow refiling regions if they
2586 don't contain a set of subtrees, but it might be convenient to
2587 do so sometimes: in that case, the first line of the region is
2588 converted to a headline before refiling."
2589 :group 'org-refile
2590 :version "24.1"
2591 :type 'boolean)
2593 (defgroup org-todo nil
2594 "Options concerning TODO items in Org mode."
2595 :tag "Org TODO"
2596 :group 'org)
2598 (defgroup org-progress nil
2599 "Options concerning Progress logging in Org mode."
2600 :tag "Org Progress"
2601 :group 'org-time)
2603 (defvar org-todo-interpretation-widgets
2604 '((:tag "Sequence (cycling hits every state)" sequence)
2605 (:tag "Type (cycling directly to DONE)" type))
2606 "The available interpretation symbols for customizing `org-todo-keywords'.
2607 Interested libraries should add to this list.")
2609 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2610 "List of TODO entry keyword sequences and their interpretation.
2611 \\<org-mode-map>This is a list of sequences.
2613 Each sequence starts with a symbol, either `sequence' or `type',
2614 indicating if the keywords should be interpreted as a sequence of
2615 action steps, or as different types of TODO items. The first
2616 keywords are states requiring action - these states will select a headline
2617 for inclusion into the global TODO list Org produces. If one of the
2618 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2619 signify that no further action is necessary. If \"|\" is not found,
2620 the last keyword is treated as the only DONE state of the sequence.
2622 The command `\\[org-todo]' cycles an entry through these states, and one
2623 additional state where no keyword is present. For details about this
2624 cycling, see the manual.
2626 TODO keywords and interpretation can also be set on a per-file basis with
2627 the special #+SEQ_TODO and #+TYP_TODO lines.
2629 Each keyword can optionally specify a character for fast state selection
2630 \(in combination with the variable `org-use-fast-todo-selection')
2631 and specifiers for state change logging, using the same syntax that
2632 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2633 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2634 indicates to record a time stamp each time this state is selected.
2636 Each keyword may also specify if a timestamp or a note should be
2637 recorded when entering or leaving the state, by adding additional
2638 characters in the parenthesis after the keyword. This looks like this:
2639 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2640 record only the time of the state change. With X and Y being either
2641 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2642 Y when leaving the state if and only if the *target* state does not
2643 define X. You may omit any of the fast-selection key or X or /Y,
2644 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2646 For backward compatibility, this variable may also be just a list
2647 of keywords. In this case the interpretation (sequence or type) will be
2648 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2649 :group 'org-todo
2650 :group 'org-keywords
2651 :type '(choice
2652 (repeat :tag "Old syntax, just keywords"
2653 (string :tag "Keyword"))
2654 (repeat :tag "New syntax"
2655 (cons
2656 (choice
2657 :tag "Interpretation"
2658 ;;Quick and dirty way to see
2659 ;;`org-todo-interpretations'. This takes the
2660 ;;place of item arguments
2661 :convert-widget
2662 (lambda (widget)
2663 (widget-put widget
2664 :args (mapcar
2665 (lambda (x)
2666 (widget-convert
2667 (cons 'const x)))
2668 org-todo-interpretation-widgets))
2669 widget))
2670 (repeat
2671 (string :tag "Keyword"))))))
2673 (defvar-local org-todo-keywords-1 nil
2674 "All TODO and DONE keywords active in a buffer.")
2675 (defvar org-todo-keywords-for-agenda nil)
2676 (defvar org-done-keywords-for-agenda nil)
2677 (defvar org-todo-keyword-alist-for-agenda nil)
2678 (defvar org-tag-alist-for-agenda nil
2679 "Alist of all tags from all agenda files.")
2680 (defvar org-tag-groups-alist-for-agenda nil
2681 "Alist of all groups tags from all current agenda files.")
2682 (defvar-local org-tag-groups-alist nil)
2683 (defvar org-agenda-contributing-files nil)
2684 (defvar-local org-current-tag-alist nil
2685 "Alist of all tag groups in current buffer.
2686 This variable takes into consideration `org-tag-alist',
2687 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2688 (defvar-local org-not-done-keywords nil)
2689 (defvar-local org-done-keywords nil)
2690 (defvar-local org-todo-heads nil)
2691 (defvar-local org-todo-sets nil)
2692 (defvar-local org-todo-log-states nil)
2693 (defvar-local org-todo-kwd-alist nil)
2694 (defvar-local org-todo-key-alist nil)
2695 (defvar-local org-todo-key-trigger nil)
2697 (defcustom org-todo-interpretation 'sequence
2698 "Controls how TODO keywords are interpreted.
2699 This variable is in principle obsolete and is only used for
2700 backward compatibility, if the interpretation of todo keywords is
2701 not given already in `org-todo-keywords'. See that variable for
2702 more information."
2703 :group 'org-todo
2704 :group 'org-keywords
2705 :type '(choice (const sequence)
2706 (const type)))
2708 (defcustom org-use-fast-todo-selection t
2709 "\\<org-mode-map>\
2710 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2711 This variable describes if and under what circumstances the cycling
2712 mechanism for TODO keywords will be replaced by a single-key, direct
2713 selection scheme.
2715 When nil, fast selection is never used.
2717 When the symbol `prefix', it will be used when `org-todo' is called
2718 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2719 in an Org buffer, and
2720 `\\[universal-argument] t' in an agenda buffer.
2722 When t, fast selection is used by default. In this case, the prefix
2723 argument forces cycling instead.
2725 In all cases, the special interface is only used if access keys have
2726 actually been assigned by the user, i.e. if keywords in the configuration
2727 are followed by a letter in parenthesis, like TODO(t)."
2728 :group 'org-todo
2729 :type '(choice
2730 (const :tag "Never" nil)
2731 (const :tag "By default" t)
2732 (const :tag "Only with C-u C-c C-t" prefix)))
2734 (defcustom org-provide-todo-statistics t
2735 "Non-nil means update todo statistics after insert and toggle.
2736 ALL-HEADLINES means update todo statistics by including headlines
2737 with no TODO keyword as well, counting them as not done.
2738 A list of TODO keywords means the same, but skip keywords that are
2739 not in this list.
2740 When set to a list of two lists, the first list contains keywords
2741 to consider as TODO keywords, the second list contains keywords
2742 to consider as DONE keywords.
2744 When this is set, todo statistics is updated in the parent of the
2745 current entry each time a todo state is changed."
2746 :group 'org-todo
2747 :type '(choice
2748 (const :tag "Yes, only for TODO entries" t)
2749 (const :tag "Yes, including all entries" all-headlines)
2750 (repeat :tag "Yes, for TODOs in this list"
2751 (string :tag "TODO keyword"))
2752 (list :tag "Yes, for TODOs and DONEs in these lists"
2753 (repeat (string :tag "TODO keyword"))
2754 (repeat (string :tag "DONE keyword")))
2755 (other :tag "No TODO statistics" nil)))
2757 (defcustom org-hierarchical-todo-statistics t
2758 "Non-nil means TODO statistics covers just direct children.
2759 When nil, all entries in the subtree are considered.
2760 This has only an effect if `org-provide-todo-statistics' is set.
2761 To set this to nil for only a single subtree, use a COOKIE_DATA
2762 property and include the word \"recursive\" into the value."
2763 :group 'org-todo
2764 :type 'boolean)
2766 (defcustom org-after-todo-state-change-hook nil
2767 "Hook which is run after the state of a TODO item was changed.
2768 The new state (a string with a TODO keyword, or nil) is available in the
2769 Lisp variable `org-state'."
2770 :group 'org-todo
2771 :type 'hook)
2773 (defvar org-blocker-hook nil
2774 "Hook for functions that are allowed to block a state change.
2776 Functions in this hook should not modify the buffer.
2777 Each function gets as its single argument a property list,
2778 see `org-trigger-hook' for more information about this list.
2780 If any of the functions in this hook returns nil, the state change
2781 is blocked.")
2783 (defvar org-trigger-hook nil
2784 "Hook for functions that are triggered by a state change.
2786 Each function gets as its single argument a property list with at
2787 least the following elements:
2789 (:type type-of-change :position pos-at-entry-start
2790 :from old-state :to new-state)
2792 Depending on the type, more properties may be present.
2794 This mechanism is currently implemented for:
2796 TODO state changes
2797 ------------------
2798 :type todo-state-change
2799 :from previous state (keyword as a string), or nil, or a symbol
2800 `todo' or `done', to indicate the general type of state.
2801 :to new state, like in :from")
2803 (defcustom org-enforce-todo-dependencies nil
2804 "Non-nil means undone TODO entries will block switching the parent to DONE.
2805 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2806 be blocked if any prior sibling is not yet done.
2807 Finally, if the parent is blocked because of ordered siblings of its own,
2808 the child will also be blocked."
2809 :set (lambda (var val)
2810 (set var val)
2811 (if val
2812 (add-hook 'org-blocker-hook
2813 'org-block-todo-from-children-or-siblings-or-parent)
2814 (remove-hook 'org-blocker-hook
2815 'org-block-todo-from-children-or-siblings-or-parent)))
2816 :group 'org-todo
2817 :type 'boolean)
2819 (defcustom org-enforce-todo-checkbox-dependencies nil
2820 "Non-nil means unchecked boxes will block switching the parent to DONE.
2821 When this is nil, checkboxes have no influence on switching TODO states.
2822 When non-nil, you first need to check off all check boxes before the TODO
2823 entry can be switched to DONE.
2824 This variable needs to be set before org.el is loaded, and you need to
2825 restart Emacs after a change to make the change effective. The only way
2826 to change is while Emacs is running is through the customize interface."
2827 :set (lambda (var val)
2828 (set var val)
2829 (if val
2830 (add-hook 'org-blocker-hook
2831 'org-block-todo-from-checkboxes)
2832 (remove-hook 'org-blocker-hook
2833 'org-block-todo-from-checkboxes)))
2834 :group 'org-todo
2835 :type 'boolean)
2837 (defcustom org-treat-insert-todo-heading-as-state-change nil
2838 "Non-nil means inserting a TODO heading is treated as state change.
2839 So when the command `\\[org-insert-todo-heading]' is used, state change
2840 logging will apply if appropriate. When nil, the new TODO item will
2841 be inserted directly, and no logging will take place."
2842 :group 'org-todo
2843 :type 'boolean)
2845 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2846 "Non-nil means switching TODO states with S-cursor counts as state change.
2847 This is the default behavior. However, setting this to nil allows a
2848 convenient way to select a TODO state and bypass any logging associated
2849 with that."
2850 :group 'org-todo
2851 :type 'boolean)
2853 (defcustom org-todo-state-tags-triggers nil
2854 "Tag changes that should be triggered by TODO state changes.
2855 This is a list. Each entry is
2857 (state-change (tag . flag) .......)
2859 State-change can be a string with a state, and empty string to indicate the
2860 state that has no TODO keyword, or it can be one of the symbols `todo'
2861 or `done', meaning any not-done or done state, respectively."
2862 :group 'org-todo
2863 :group 'org-tags
2864 :type '(repeat
2865 (cons (choice :tag "When changing to"
2866 (const :tag "Not-done state" todo)
2867 (const :tag "Done state" done)
2868 (string :tag "State"))
2869 (repeat
2870 (cons :tag "Tag action"
2871 (string :tag "Tag")
2872 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2874 (defcustom org-log-done nil
2875 "Information to record when a task moves to the DONE state.
2877 Possible values are:
2879 nil Don't add anything, just change the keyword
2880 time Add a time stamp to the task
2881 note Prompt for a note and add it with template `org-log-note-headings'
2883 This option can also be set with on a per-file-basis with
2885 #+STARTUP: nologdone
2886 #+STARTUP: logdone
2887 #+STARTUP: lognotedone
2889 You can have local logging settings for a subtree by setting the LOGGING
2890 property to one or more of these keywords."
2891 :group 'org-todo
2892 :group 'org-progress
2893 :type '(choice
2894 (const :tag "No logging" nil)
2895 (const :tag "Record CLOSED timestamp" time)
2896 (const :tag "Record CLOSED timestamp with note." note)))
2898 ;; Normalize old uses of org-log-done.
2899 (cond
2900 ((eq org-log-done t) (setq org-log-done 'time))
2901 ((and (listp org-log-done) (memq 'done org-log-done))
2902 (setq org-log-done 'note)))
2904 (defcustom org-log-reschedule nil
2905 "Information to record when the scheduling date of a tasks is modified.
2907 Possible values are:
2909 nil Don't add anything, just change the date
2910 time Add a time stamp to the task
2911 note Prompt for a note and add it with template `org-log-note-headings'
2913 This option can also be set with on a per-file-basis with
2915 #+STARTUP: nologreschedule
2916 #+STARTUP: logreschedule
2917 #+STARTUP: lognotereschedule"
2918 :group 'org-todo
2919 :group 'org-progress
2920 :type '(choice
2921 (const :tag "No logging" nil)
2922 (const :tag "Record timestamp" time)
2923 (const :tag "Record timestamp with note." note)))
2925 (defcustom org-log-redeadline nil
2926 "Information to record when the deadline date of a tasks is modified.
2928 Possible values are:
2930 nil Don't add anything, just change the date
2931 time Add a time stamp to the task
2932 note Prompt for a note and add it with template `org-log-note-headings'
2934 This option can also be set with on a per-file-basis with
2936 #+STARTUP: nologredeadline
2937 #+STARTUP: logredeadline
2938 #+STARTUP: lognoteredeadline
2940 You can have local logging settings for a subtree by setting the LOGGING
2941 property to one or more of these keywords."
2942 :group 'org-todo
2943 :group 'org-progress
2944 :type '(choice
2945 (const :tag "No logging" nil)
2946 (const :tag "Record timestamp" time)
2947 (const :tag "Record timestamp with note." note)))
2949 (defcustom org-log-note-clock-out nil
2950 "Non-nil means record a note when clocking out of an item.
2951 This can also be configured on a per-file basis by adding one of
2952 the following lines anywhere in the buffer:
2954 #+STARTUP: lognoteclock-out
2955 #+STARTUP: nolognoteclock-out"
2956 :group 'org-todo
2957 :group 'org-progress
2958 :type 'boolean)
2960 (defcustom org-log-done-with-time t
2961 "Non-nil means the CLOSED time stamp will contain date and time.
2962 When nil, only the date will be recorded."
2963 :group 'org-progress
2964 :type 'boolean)
2966 (defcustom org-log-note-headings
2967 '((done . "CLOSING NOTE %t")
2968 (state . "State %-12s from %-12S %t")
2969 (note . "Note taken on %t")
2970 (reschedule . "Rescheduled from %S on %t")
2971 (delschedule . "Not scheduled, was %S on %t")
2972 (redeadline . "New deadline from %S on %t")
2973 (deldeadline . "Removed deadline, was %S on %t")
2974 (refile . "Refiled on %t")
2975 (clock-out . ""))
2976 "Headings for notes added to entries.
2978 The value is an alist, with the car being a symbol indicating the
2979 note context, and the cdr is the heading to be used. The heading
2980 may also be the empty string. The following placeholders can be
2981 used:
2983 %t a time stamp.
2984 %T an active time stamp instead the default inactive one
2985 %d a short-format time stamp.
2986 %D an active short-format time stamp.
2987 %s the new TODO state or time stamp (inactive), in double quotes.
2988 %S the old TODO state or time stamp (inactive), in double quotes.
2989 %u the user name.
2990 %U full user name.
2992 In fact, it is not a good idea to change the `state' entry,
2993 because Agenda Log mode depends on the format of these entries."
2994 :group 'org-todo
2995 :group 'org-progress
2996 :type '(list :greedy t
2997 (cons (const :tag "Heading when closing an item" done) string)
2998 (cons (const :tag
2999 "Heading when changing todo state (todo sequence only)"
3000 state) string)
3001 (cons (const :tag "Heading when just taking a note" note) string)
3002 (cons (const :tag "Heading when rescheduling" reschedule) string)
3003 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3004 (cons (const :tag "Heading when changing deadline" redeadline) string)
3005 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3006 (cons (const :tag "Heading when refiling" refile) string)
3007 (cons (const :tag "Heading when clocking out" clock-out) string)))
3009 (unless (assq 'note org-log-note-headings)
3010 (push '(note . "%t") org-log-note-headings))
3012 (defcustom org-log-into-drawer nil
3013 "Non-nil means insert state change notes and time stamps into a drawer.
3014 When nil, state changes notes will be inserted after the headline and
3015 any scheduling and clock lines, but not inside a drawer.
3017 The value of this variable should be the name of the drawer to use.
3018 LOGBOOK is proposed as the default drawer for this purpose, you can
3019 also set this to a string to define the drawer of your choice.
3021 A value of t is also allowed, representing \"LOGBOOK\".
3023 A value of t or nil can also be set with on a per-file-basis with
3025 #+STARTUP: logdrawer
3026 #+STARTUP: nologdrawer
3028 If this variable is set, `org-log-state-notes-insert-after-drawers'
3029 will be ignored.
3031 You can set the property LOG_INTO_DRAWER to overrule this setting for
3032 a subtree.
3034 Do not check directly this variable in a Lisp program. Call
3035 function `org-log-into-drawer' instead."
3036 :group 'org-todo
3037 :group 'org-progress
3038 :type '(choice
3039 (const :tag "Not into a drawer" nil)
3040 (const :tag "LOGBOOK" t)
3041 (string :tag "Other")))
3043 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3045 (defun org-log-into-drawer ()
3046 "Name of the log drawer, as a string, or nil.
3047 This is the value of `org-log-into-drawer'. However, if the
3048 current entry has or inherits a LOG_INTO_DRAWER property, it will
3049 be used instead of the default value."
3050 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3051 (cond ((equal p "nil") nil)
3052 ((equal p "t") "LOGBOOK")
3053 ((stringp p) p)
3054 (p "LOGBOOK")
3055 ((stringp org-log-into-drawer) org-log-into-drawer)
3056 (org-log-into-drawer "LOGBOOK"))))
3058 (defcustom org-log-state-notes-insert-after-drawers nil
3059 "Non-nil means insert state change notes after any drawers in entry.
3060 Only the drawers that *immediately* follow the headline and the
3061 deadline/scheduled line are skipped.
3062 When nil, insert notes right after the heading and perhaps the line
3063 with deadline/scheduling if present.
3065 This variable will have no effect if `org-log-into-drawer' is
3066 set."
3067 :group 'org-todo
3068 :group 'org-progress
3069 :type 'boolean)
3071 (defcustom org-log-states-order-reversed t
3072 "Non-nil means the latest state note will be directly after heading.
3073 When nil, the state change notes will be ordered according to time.
3075 This option can also be set with on a per-file-basis with
3077 #+STARTUP: logstatesreversed
3078 #+STARTUP: nologstatesreversed"
3079 :group 'org-todo
3080 :group 'org-progress
3081 :type 'boolean)
3083 (defcustom org-todo-repeat-to-state nil
3084 "The TODO state to which a repeater should return the repeating task.
3085 By default this is the first task in a TODO sequence, or the previous state
3086 in a TODO_TYP set. But you can specify another task here.
3087 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3088 :group 'org-todo
3089 :version "24.1"
3090 :type '(choice (const :tag "Head of sequence" nil)
3091 (string :tag "Specific state")))
3093 (defcustom org-log-repeat 'time
3094 "Non-nil means record moving through the DONE state when triggering repeat.
3095 An auto-repeating task is immediately switched back to TODO when
3096 marked DONE. If you are not logging state changes (by adding \"@\"
3097 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3098 record a closing note, there will be no record of the task moving
3099 through DONE. This variable forces taking a note anyway.
3101 nil Don't force a record
3102 time Record a time stamp
3103 note Prompt for a note and add it with template `org-log-note-headings'
3105 This option can also be set with on a per-file-basis with
3107 #+STARTUP: nologrepeat
3108 #+STARTUP: logrepeat
3109 #+STARTUP: lognoterepeat
3111 You can have local logging settings for a subtree by setting the LOGGING
3112 property to one or more of these keywords."
3113 :group 'org-todo
3114 :group 'org-progress
3115 :type '(choice
3116 (const :tag "Don't force a record" nil)
3117 (const :tag "Force recording the DONE state" time)
3118 (const :tag "Force recording a note with the DONE state" note)))
3121 (defgroup org-priorities nil
3122 "Priorities in Org mode."
3123 :tag "Org Priorities"
3124 :group 'org-todo)
3126 (defcustom org-enable-priority-commands t
3127 "Non-nil means priority commands are active.
3128 When nil, these commands will be disabled, so that you never accidentally
3129 set a priority."
3130 :group 'org-priorities
3131 :type 'boolean)
3133 (defcustom org-highest-priority ?A
3134 "The highest priority of TODO items. A character like ?A, ?B etc.
3135 Must have a smaller ASCII number than `org-lowest-priority'."
3136 :group 'org-priorities
3137 :type 'character)
3139 (defcustom org-lowest-priority ?C
3140 "The lowest priority of TODO items. A character like ?A, ?B etc.
3141 Must have a larger ASCII number than `org-highest-priority'."
3142 :group 'org-priorities
3143 :type 'character)
3145 (defcustom org-default-priority ?B
3146 "The default priority of TODO items.
3147 This is the priority an item gets if no explicit priority is given.
3148 When starting to cycle on an empty priority the first step in the cycle
3149 depends on `org-priority-start-cycle-with-default'. The resulting first
3150 step priority must not exceed the range from `org-highest-priority' to
3151 `org-lowest-priority' which means that `org-default-priority' has to be
3152 in this range exclusive or inclusive the range boundaries. Else the
3153 first step refuses to set the default and the second will fall back
3154 to (depending on the command used) the highest or lowest priority."
3155 :group 'org-priorities
3156 :type 'character)
3158 (defcustom org-priority-start-cycle-with-default t
3159 "Non-nil means start with default priority when starting to cycle.
3160 When this is nil, the first step in the cycle will be (depending on the
3161 command used) one higher or lower than the default priority.
3162 See also `org-default-priority'."
3163 :group 'org-priorities
3164 :type 'boolean)
3166 (defcustom org-get-priority-function nil
3167 "Function to extract the priority from a string.
3168 The string is normally the headline. If this is nil Org computes the
3169 priority from the priority cookie like [#A] in the headline. It returns
3170 an integer, increasing by 1000 for each priority level.
3171 The user can set a different function here, which should take a string
3172 as an argument and return the numeric priority."
3173 :group 'org-priorities
3174 :version "24.1"
3175 :type '(choice
3176 (const nil)
3177 (function)))
3179 (defgroup org-time nil
3180 "Options concerning time stamps and deadlines in Org mode."
3181 :tag "Org Time"
3182 :group 'org)
3184 (defcustom org-time-stamp-rounding-minutes '(0 5)
3185 "Number of minutes to round time stamps to.
3186 \\<org-mode-map>\
3187 These are two values, the first applies when first creating a time stamp.
3188 The second applies when changing it with the commands `S-up' and `S-down'.
3189 When changing the time stamp, this means that it will change in steps
3190 of N minutes, as given by the second value.
3192 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3193 numbers should be factors of 60, so for example 5, 10, 15.
3195 When this is larger than 1, you can still force an exact time stamp by using
3196 a double prefix argument to a time stamp command like \
3197 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3198 and by using a prefix arg to `S-up/down' to specify the exact number
3199 of minutes to shift."
3200 :group 'org-time
3201 :get (lambda (var) ; Make sure both elements are there
3202 (if (integerp (default-value var))
3203 (list (default-value var) 5)
3204 (default-value var)))
3205 :type '(list
3206 (integer :tag "when inserting times")
3207 (integer :tag "when modifying times")))
3209 ;; Normalize old customizations of this variable.
3210 (when (integerp org-time-stamp-rounding-minutes)
3211 (setq org-time-stamp-rounding-minutes
3212 (list org-time-stamp-rounding-minutes
3213 org-time-stamp-rounding-minutes)))
3215 (defcustom org-display-custom-times nil
3216 "Non-nil means overlay custom formats over all time stamps.
3217 The formats are defined through the variable `org-time-stamp-custom-formats'.
3218 To turn this on on a per-file basis, insert anywhere in the file:
3219 #+STARTUP: customtime"
3220 :group 'org-time
3221 :set 'set-default
3222 :type 'sexp)
3223 (make-variable-buffer-local 'org-display-custom-times)
3225 (defcustom org-time-stamp-custom-formats
3226 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3227 "Custom formats for time stamps. See `format-time-string' for the syntax.
3228 These are overlaid over the default ISO format if the variable
3229 `org-display-custom-times' is set. Time like %H:%M should be at the
3230 end of the second format. The custom formats are also honored by export
3231 commands, if custom time display is turned on at the time of export."
3232 :group 'org-time
3233 :type 'sexp)
3235 (defun org-time-stamp-format (&optional long inactive)
3236 "Get the right format for a time string."
3237 (let ((f (if long (cdr org-time-stamp-formats)
3238 (car org-time-stamp-formats))))
3239 (if inactive
3240 (concat "[" (substring f 1 -1) "]")
3241 f)))
3243 (defcustom org-time-clocksum-format
3244 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3245 "The format string used when creating CLOCKSUM lines.
3246 This is also used when Org mode generates a time duration.
3248 The value can be a single format string containing two
3249 %-sequences, which will be filled with the number of hours and
3250 minutes in that order.
3252 Alternatively, the value can be a plist associating any of the
3253 keys :years, :months, :weeks, :days, :hours or :minutes with
3254 format strings. The time duration is formatted using only the
3255 time components that are needed and concatenating the results.
3256 If a time unit in absent, it falls back to the next smallest
3257 unit.
3259 The keys :require-years, :require-months, :require-days,
3260 :require-weeks, :require-hours, :require-minutes are also
3261 meaningful. A non-nil value for these keys indicates that the
3262 corresponding time component should always be included, even if
3263 its value is 0.
3266 For example,
3268 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3269 :require-minutes t)
3271 means durations longer than a day will be expressed in days,
3272 hours and minutes, and durations less than a day will always be
3273 expressed in hours and minutes (even for durations less than an
3274 hour).
3276 The value
3278 (:days \"%dd\" :minutes \"%dm\")
3280 means durations longer than a day will be expressed in days and
3281 minutes, and durations less than a day will be expressed entirely
3282 in minutes (even for durations longer than an hour)."
3283 :group 'org-time
3284 :group 'org-clock
3285 :version "24.4"
3286 :package-version '(Org . "8.0")
3287 :type '(choice (string :tag "Format string")
3288 (set :tag "Plist"
3289 (group :inline t (const :tag "Years" :years)
3290 (string :tag "Format string"))
3291 (group :inline t
3292 (const :tag "Always show years" :require-years)
3293 (const t))
3294 (group :inline t (const :tag "Months" :months)
3295 (string :tag "Format string"))
3296 (group :inline t
3297 (const :tag "Always show months" :require-months)
3298 (const t))
3299 (group :inline t (const :tag "Weeks" :weeks)
3300 (string :tag "Format string"))
3301 (group :inline t
3302 (const :tag "Always show weeks" :require-weeks)
3303 (const t))
3304 (group :inline t (const :tag "Days" :days)
3305 (string :tag "Format string"))
3306 (group :inline t
3307 (const :tag "Always show days" :require-days)
3308 (const t))
3309 (group :inline t (const :tag "Hours" :hours)
3310 (string :tag "Format string"))
3311 (group :inline t
3312 (const :tag "Always show hours" :require-hours)
3313 (const t))
3314 (group :inline t (const :tag "Minutes" :minutes)
3315 (string :tag "Format string"))
3316 (group :inline t
3317 (const :tag "Always show minutes" :require-minutes)
3318 (const t)))))
3320 (defcustom org-time-clocksum-use-fractional nil
3321 "When non-nil, `\\[org-clock-display]' uses fractional times.
3322 See `org-time-clocksum-format' for more on time clock formats."
3323 :group 'org-time
3324 :group 'org-clock
3325 :version "24.3"
3326 :type 'boolean)
3328 (defcustom org-time-clocksum-use-effort-durations nil
3329 "When non-nil, `\\[org-clock-display]' uses effort durations.
3330 E.g. by default, one day is considered to be a 8 hours effort,
3331 so a task that has been clocked for 16 hours will be displayed
3332 as during 2 days in the clock display or in the clocktable.
3334 See `org-effort-durations' on how to set effort durations
3335 and `org-time-clocksum-format' for more on time clock formats."
3336 :group 'org-time
3337 :group 'org-clock
3338 :version "24.4"
3339 :package-version '(Org . "8.0")
3340 :type 'boolean)
3342 (defcustom org-time-clocksum-fractional-format "%.2f"
3343 "The format string used when creating CLOCKSUM lines,
3344 or when Org mode generates a time duration, if
3345 `org-time-clocksum-use-fractional' is enabled.
3347 The value can be a single format string containing one
3348 %-sequence, which will be filled with the number of hours as
3349 a float.
3351 Alternatively, the value can be a plist associating any of the
3352 keys :years, :months, :weeks, :days, :hours or :minutes with
3353 a format string. The time duration is formatted using the
3354 largest time unit which gives a non-zero integer part. If all
3355 specified formats have zero integer part, the smallest time unit
3356 is used."
3357 :group 'org-time
3358 :type '(choice (string :tag "Format string")
3359 (set (group :inline t (const :tag "Years" :years)
3360 (string :tag "Format string"))
3361 (group :inline t (const :tag "Months" :months)
3362 (string :tag "Format string"))
3363 (group :inline t (const :tag "Weeks" :weeks)
3364 (string :tag "Format string"))
3365 (group :inline t (const :tag "Days" :days)
3366 (string :tag "Format string"))
3367 (group :inline t (const :tag "Hours" :hours)
3368 (string :tag "Format string"))
3369 (group :inline t (const :tag "Minutes" :minutes)
3370 (string :tag "Format string")))))
3372 (defcustom org-deadline-warning-days 14
3373 "Number of days before expiration during which a deadline becomes active.
3374 This variable governs the display in sparse trees and in the agenda.
3375 When 0 or negative, it means use this number (the absolute value of it)
3376 even if a deadline has a different individual lead time specified.
3378 Custom commands can set this variable in the options section."
3379 :group 'org-time
3380 :group 'org-agenda-daily/weekly
3381 :type 'integer)
3383 (defcustom org-scheduled-delay-days 0
3384 "Number of days before a scheduled item becomes active.
3385 This variable governs the display in sparse trees and in the agenda.
3386 The default value (i.e. 0) means: don't delay scheduled item.
3387 When negative, it means use this number (the absolute value of it)
3388 even if a scheduled item has a different individual delay time
3389 specified.
3391 Custom commands can set this variable in the options section."
3392 :group 'org-time
3393 :group 'org-agenda-daily/weekly
3394 :version "24.4"
3395 :package-version '(Org . "8.0")
3396 :type 'integer)
3398 (defcustom org-read-date-prefer-future t
3399 "Non-nil means assume future for incomplete date input from user.
3400 This affects the following situations:
3401 1. The user gives a month but not a year.
3402 For example, if it is April and you enter \"feb 2\", this will be read
3403 as Feb 2, *next* year. \"May 5\", however, will be this year.
3404 2. The user gives a day, but no month.
3405 For example, if today is the 15th, and you enter \"3\", Org will read
3406 this as the third of *next* month. However, if you enter \"17\",
3407 it will be considered as *this* month.
3409 If you set this variable to the symbol `time', then also the following
3410 will work:
3412 3. If the user gives a time.
3413 If the time is before now, it will be interpreted as tomorrow.
3415 Currently none of this works for ISO week specifications.
3417 When this option is nil, the current day, month and year will always be
3418 used as defaults.
3420 See also `org-agenda-jump-prefer-future'."
3421 :group 'org-time
3422 :type '(choice
3423 (const :tag "Never" nil)
3424 (const :tag "Check month and day" t)
3425 (const :tag "Check month, day, and time" time)))
3427 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3428 "Should the agenda jump command prefer the future for incomplete dates?
3429 The default is to do the same as configured in `org-read-date-prefer-future'.
3430 But you can also set a deviating value here.
3431 This may t or nil, or the symbol `org-read-date-prefer-future'."
3432 :group 'org-agenda
3433 :group 'org-time
3434 :version "24.1"
3435 :type '(choice
3436 (const :tag "Use org-read-date-prefer-future"
3437 org-read-date-prefer-future)
3438 (const :tag "Never" nil)
3439 (const :tag "Always" t)))
3441 (defcustom org-read-date-force-compatible-dates t
3442 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3444 Depending on the system Emacs is running on, certain dates cannot
3445 be represented with the type used internally to represent time.
3446 Dates between 1970-1-1 and 2038-1-1 can always be represented
3447 correctly. Some systems allow for earlier dates, some for later,
3448 some for both. One way to find out it to insert any date into an
3449 Org buffer, putting the cursor on the year and hitting S-up and
3450 S-down to test the range.
3452 When this variable is set to t, the date/time prompt will not let
3453 you specify dates outside the 1970-2037 range, so it is certain that
3454 these dates will work in whatever version of Emacs you are
3455 running, and also that you can move a file from one Emacs implementation
3456 to another. WHenever Org is forcing the year for you, it will display
3457 a message and beep.
3459 When this variable is nil, Org will check if the date is
3460 representable in the specific Emacs implementation you are using.
3461 If not, it will force a year, usually the current year, and beep
3462 to remind you. Currently this setting is not recommended because
3463 the likelihood that you will open your Org files in an Emacs that
3464 has limited date range is not negligible.
3466 A workaround for this problem is to use diary sexp dates for time
3467 stamps outside of this range."
3468 :group 'org-time
3469 :version "24.1"
3470 :type 'boolean)
3472 (defcustom org-read-date-display-live t
3473 "Non-nil means display current interpretation of date prompt live.
3474 This display will be in an overlay, in the minibuffer."
3475 :group 'org-time
3476 :type 'boolean)
3478 (defcustom org-read-date-popup-calendar t
3479 "Non-nil means pop up a calendar when prompting for a date.
3480 In the calendar, the date can be selected with mouse-1. However, the
3481 minibuffer will also be active, and you can simply enter the date as well.
3482 When nil, only the minibuffer will be available."
3483 :group 'org-time
3484 :type 'boolean)
3485 (defvaralias 'org-popup-calendar-for-date-prompt
3486 'org-read-date-popup-calendar)
3488 (defcustom org-extend-today-until 0
3489 "The hour when your day really ends. Must be an integer.
3490 This has influence for the following applications:
3491 - When switching the agenda to \"today\". It it is still earlier than
3492 the time given here, the day recognized as TODAY is actually yesterday.
3493 - When a date is read from the user and it is still before the time given
3494 here, the current date and time will be assumed to be yesterday, 23:59.
3495 Also, timestamps inserted in capture templates follow this rule.
3497 IMPORTANT: This is a feature whose implementation is and likely will
3498 remain incomplete. Really, it is only here because past midnight seems to
3499 be the favorite working time of John Wiegley :-)"
3500 :group 'org-time
3501 :type 'integer)
3503 (defcustom org-use-effective-time nil
3504 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3505 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3506 \"effective time\" of any timestamps between midnight and 8am will be
3507 23:59 of the previous day."
3508 :group 'org-time
3509 :version "24.1"
3510 :type 'boolean)
3512 (defcustom org-use-last-clock-out-time-as-effective-time nil
3513 "When non-nil, use the last clock out time for `org-todo'.
3514 Note that this option has precedence over the combined use of
3515 `org-use-effective-time' and `org-extend-today-until'."
3516 :group 'org-time
3517 :version "24.4"
3518 :package-version '(Org . "8.0")
3519 :type 'boolean)
3521 (defcustom org-edit-timestamp-down-means-later nil
3522 "Non-nil means S-down will increase the time in a time stamp.
3523 When nil, S-up will increase."
3524 :group 'org-time
3525 :type 'boolean)
3527 (defcustom org-calendar-follow-timestamp-change t
3528 "Non-nil means make the calendar window follow timestamp changes.
3529 When a timestamp is modified and the calendar window is visible, it will be
3530 moved to the new date."
3531 :group 'org-time
3532 :type 'boolean)
3534 (defgroup org-tags nil
3535 "Options concerning tags in Org mode."
3536 :tag "Org Tags"
3537 :group 'org)
3539 (defcustom org-tag-alist nil
3540 "Default tags available in Org files.
3542 The value of this variable is an alist. Associations either:
3544 (TAG)
3545 (TAG . SELECT)
3546 (SPECIAL)
3548 where TAG is a tag as a string, SELECT is a character, used to
3549 select that tag through the fast tag selection interface, and
3550 SPECIAL is one of the following keywords: `:startgroup',
3551 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3552 `:newline'. These keywords are used to define a hierarchy of
3553 tags. See manual for details.
3555 When this variable is nil, Org mode bases tag input on what is
3556 already in the buffer. The value can be overridden locally by
3557 using a TAGS keyword, e.g.,
3559 #+TAGS: tag1 tag2
3561 See also `org-tag-persistent-alist' to sidestep this behavior."
3562 :group 'org-tags
3563 :type '(repeat
3564 (choice
3565 (cons (string :tag "Tag name")
3566 (character :tag "Access char"))
3567 (const :tag "Start radio group" (:startgroup))
3568 (const :tag "Start tag group, non distinct" (:startgrouptag))
3569 (const :tag "Group tags delimiter" (:grouptags))
3570 (const :tag "End radio group" (:endgroup))
3571 (const :tag "End tag group, non distinct" (:endgrouptag))
3572 (const :tag "New line" (:newline)))))
3574 (defcustom org-tag-persistent-alist nil
3575 "Tags always available in Org files.
3577 The value of this variable is an alist. Associations either:
3579 (TAG)
3580 (TAG . SELECT)
3581 (SPECIAL)
3583 where TAG is a tag as a string, SELECT is a character, used to
3584 select that tag through the fast tag selection interface, and
3585 SPECIAL is one of the following keywords: `:startgroup',
3586 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3587 `:newline'. These keywords are used to define a hierarchy of
3588 tags. See manual for details.
3590 Unlike to `org-tag-alist', tags defined in this variable do not
3591 depend on a local TAGS keyword. Instead, to disable these tags
3592 on a per-file basis, insert anywhere in the file:
3594 #+STARTUP: noptag"
3595 :group 'org-tags
3596 :type '(repeat
3597 (choice
3598 (cons (string :tag "Tag name")
3599 (character :tag "Access char"))
3600 (const :tag "Start radio group" (:startgroup))
3601 (const :tag "Start tag group, non distinct" (:startgrouptag))
3602 (const :tag "Group tags delimiter" (:grouptags))
3603 (const :tag "End radio group" (:endgroup))
3604 (const :tag "End tag group, non distinct" (:endgrouptag))
3605 (const :tag "New line" (:newline)))))
3607 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3608 "If non-nil, always offer completion for all tags of all agenda files.
3609 Instead of customizing this variable directly, you might want to
3610 set it locally for capture buffers, because there no list of
3611 tags in that file can be created dynamically (there are none).
3613 (add-hook \\='org-capture-mode-hook
3614 (lambda ()
3615 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3616 :group 'org-tags
3617 :version "24.1"
3618 :type 'boolean)
3620 (defvar org-file-tags nil
3621 "List of tags that can be inherited by all entries in the file.
3622 The tags will be inherited if the variable `org-use-tag-inheritance'
3623 says they should be.
3624 This variable is populated from #+FILETAGS lines.")
3626 (defcustom org-use-fast-tag-selection 'auto
3627 "Non-nil means use fast tag selection scheme.
3628 This is a special interface to select and deselect tags with single keys.
3629 When nil, fast selection is never used.
3630 When the symbol `auto', fast selection is used if and only if selection
3631 characters for tags have been configured, either through the variable
3632 `org-tag-alist' or through a #+TAGS line in the buffer.
3633 When t, fast selection is always used and selection keys are assigned
3634 automatically if necessary."
3635 :group 'org-tags
3636 :type '(choice
3637 (const :tag "Always" t)
3638 (const :tag "Never" nil)
3639 (const :tag "When selection characters are configured" auto)))
3641 (defcustom org-fast-tag-selection-single-key nil
3642 "Non-nil means fast tag selection exits after first change.
3643 When nil, you have to press RET to exit it.
3644 During fast tag selection, you can toggle this flag with `C-c'.
3645 This variable can also have the value `expert'. In this case, the window
3646 displaying the tags menu is not even shown, until you press C-c again."
3647 :group 'org-tags
3648 :type '(choice
3649 (const :tag "No" nil)
3650 (const :tag "Yes" t)
3651 (const :tag "Expert" expert)))
3653 (defvar org-fast-tag-selection-include-todo nil
3654 "Non-nil means fast tags selection interface will also offer TODO states.
3655 This is an undocumented feature, you should not rely on it.")
3657 (defcustom org-tags-column -77
3658 "The column to which tags should be indented in a headline.
3659 If this number is positive, it specifies the column. If it is negative,
3660 it means that the tags should be flushright to that column. For example,
3661 -80 works well for a normal 80 character screen.
3662 When 0, place tags directly after headline text, with only one space in
3663 between."
3664 :group 'org-tags
3665 :type 'integer)
3667 (defcustom org-auto-align-tags t
3668 "Non-nil keeps tags aligned when modifying headlines.
3669 Some operations (i.e. demoting) change the length of a headline and
3670 therefore shift the tags around. With this option turned on, after
3671 each such operation the tags are again aligned to `org-tags-column'."
3672 :group 'org-tags
3673 :type 'boolean)
3675 (defcustom org-use-tag-inheritance t
3676 "Non-nil means tags in levels apply also for sublevels.
3677 When nil, only the tags directly given in a specific line apply there.
3678 This may also be a list of tags that should be inherited, or a regexp that
3679 matches tags that should be inherited. Additional control is possible
3680 with the variable `org-tags-exclude-from-inheritance' which gives an
3681 explicit list of tags to be excluded from inheritance, even if the value of
3682 `org-use-tag-inheritance' would select it for inheritance.
3684 If this option is t, a match early-on in a tree can lead to a large
3685 number of matches in the subtree when constructing the agenda or creating
3686 a sparse tree. If you only want to see the first match in a tree during
3687 a search, check out the variable `org-tags-match-list-sublevels'."
3688 :group 'org-tags
3689 :type '(choice
3690 (const :tag "Not" nil)
3691 (const :tag "Always" t)
3692 (repeat :tag "Specific tags" (string :tag "Tag"))
3693 (regexp :tag "Tags matched by regexp")))
3695 (defcustom org-tags-exclude-from-inheritance nil
3696 "List of tags that should never be inherited.
3697 This is a way to exclude a few tags from inheritance. For way to do
3698 the opposite, to actively allow inheritance for selected tags,
3699 see the variable `org-use-tag-inheritance'."
3700 :group 'org-tags
3701 :type '(repeat (string :tag "Tag")))
3703 (defun org-tag-inherit-p (tag)
3704 "Check if TAG is one that should be inherited."
3705 (cond
3706 ((member tag org-tags-exclude-from-inheritance) nil)
3707 ((eq org-use-tag-inheritance t) t)
3708 ((not org-use-tag-inheritance) nil)
3709 ((stringp org-use-tag-inheritance)
3710 (string-match org-use-tag-inheritance tag))
3711 ((listp org-use-tag-inheritance)
3712 (member tag org-use-tag-inheritance))
3713 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3715 (defcustom org-tags-match-list-sublevels t
3716 "Non-nil means list also sublevels of headlines matching a search.
3717 This variable applies to tags/property searches, and also to stuck
3718 projects because this search is based on a tags match as well.
3720 When set to the symbol `indented', sublevels are indented with
3721 leading dots.
3723 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3724 the sublevels of a headline matching a tag search often also match
3725 the same search. Listing all of them can create very long lists.
3726 Setting this variable to nil causes subtrees of a match to be skipped.
3728 This variable is semi-obsolete and probably should always be true. It
3729 is better to limit inheritance to certain tags using the variables
3730 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3731 :group 'org-tags
3732 :type '(choice
3733 (const :tag "No, don't list them" nil)
3734 (const :tag "Yes, do list them" t)
3735 (const :tag "List them, indented with leading dots" indented)))
3737 (defcustom org-tags-sort-function nil
3738 "When set, tags are sorted using this function as a comparator."
3739 :group 'org-tags
3740 :type '(choice
3741 (const :tag "No sorting" nil)
3742 (const :tag "Alphabetical" string<)
3743 (const :tag "Reverse alphabetical" string>)
3744 (function :tag "Custom function" nil)))
3746 (defvar org-tags-history nil
3747 "History of minibuffer reads for tags.")
3748 (defvar org-last-tags-completion-table nil
3749 "The last used completion table for tags.")
3750 (defvar org-after-tags-change-hook nil
3751 "Hook that is run after the tags in a line have changed.")
3753 (defgroup org-properties nil
3754 "Options concerning properties in Org mode."
3755 :tag "Org Properties"
3756 :group 'org)
3758 (defcustom org-property-format "%-10s %s"
3759 "How property key/value pairs should be formatted by `indent-line'.
3760 When `indent-line' hits a property definition, it will format the line
3761 according to this format, mainly to make sure that the values are
3762 lined-up with respect to each other."
3763 :group 'org-properties
3764 :type 'string)
3766 (defcustom org-properties-postprocess-alist nil
3767 "Alist of properties and functions to adjust inserted values.
3768 Elements of this alist must be of the form
3770 ([string] [function])
3772 where [string] must be a property name and [function] must be a
3773 lambda expression: this lambda expression must take one argument,
3774 the value to adjust, and return the new value as a string.
3776 For example, this element will allow the property \"Remaining\"
3777 to be updated wrt the relation between the \"Effort\" property
3778 and the clock summary:
3780 ((\"Remaining\" (lambda(value)
3781 (let ((clocksum (org-clock-sum-current-item))
3782 (effort (org-duration-string-to-minutes
3783 (org-entry-get (point) \"Effort\"))))
3784 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3785 :group 'org-properties
3786 :version "24.1"
3787 :type '(alist :key-type (string :tag "Property")
3788 :value-type (function :tag "Function")))
3790 (defcustom org-use-property-inheritance nil
3791 "Non-nil means properties apply also for sublevels.
3793 This setting is chiefly used during property searches. Turning it on can
3794 cause significant overhead when doing a search, which is why it is not
3795 on by default.
3797 When nil, only the properties directly given in the current entry count.
3798 When t, every property is inherited. The value may also be a list of
3799 properties that should have inheritance, or a regular expression matching
3800 properties that should be inherited.
3802 However, note that some special properties use inheritance under special
3803 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3804 and the properties ending in \"_ALL\" when they are used as descriptor
3805 for valid values of a property.
3807 Note for programmers:
3808 When querying an entry with `org-entry-get', you can control if inheritance
3809 should be used. By default, `org-entry-get' looks only at the local
3810 properties. You can request inheritance by setting the inherit argument
3811 to t (to force inheritance) or to `selective' (to respect the setting
3812 in this variable)."
3813 :group 'org-properties
3814 :type '(choice
3815 (const :tag "Not" nil)
3816 (const :tag "Always" t)
3817 (repeat :tag "Specific properties" (string :tag "Property"))
3818 (regexp :tag "Properties matched by regexp")))
3820 (defun org-property-inherit-p (property)
3821 "Check if PROPERTY is one that should be inherited."
3822 (cond
3823 ((eq org-use-property-inheritance t) t)
3824 ((not org-use-property-inheritance) nil)
3825 ((stringp org-use-property-inheritance)
3826 (string-match org-use-property-inheritance property))
3827 ((listp org-use-property-inheritance)
3828 (member property org-use-property-inheritance))
3829 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3831 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3832 "The default column format, if no other format has been defined.
3833 This variable can be set on the per-file basis by inserting a line
3835 #+COLUMNS: %25ITEM ....."
3836 :group 'org-properties
3837 :type 'string)
3839 (defcustom org-columns-ellipses ".."
3840 "The ellipses to be used when a field in column view is truncated.
3841 When this is the empty string, as many characters as possible are shown,
3842 but then there will be no visual indication that the field has been truncated.
3843 When this is a string of length N, the last N characters of a truncated
3844 field are replaced by this string. If the column is narrower than the
3845 ellipses string, only part of the ellipses string will be shown."
3846 :group 'org-properties
3847 :type 'string)
3849 (defconst org-global-properties-fixed
3850 '(("VISIBILITY_ALL" . "folded children content all")
3851 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3852 "List of property/value pairs that can be inherited by any entry.
3854 These are fixed values, for the preset properties. The user variable
3855 that can be used to add to this list is `org-global-properties'.
3857 The entries in this list are cons cells where the car is a property
3858 name and cdr is a string with the value. If the value represents
3859 multiple items like an \"_ALL\" property, separate the items by
3860 spaces.")
3862 (defcustom org-global-properties nil
3863 "List of property/value pairs that can be inherited by any entry.
3865 This list will be combined with the constant `org-global-properties-fixed'.
3867 The entries in this list are cons cells where the car is a property
3868 name and cdr is a string with the value.
3870 You can set buffer-local values for the same purpose in the variable
3871 `org-file-properties' this by adding lines like
3873 #+PROPERTY: NAME VALUE"
3874 :group 'org-properties
3875 :type '(repeat
3876 (cons (string :tag "Property")
3877 (string :tag "Value"))))
3879 (defvar-local org-file-properties nil
3880 "List of property/value pairs that can be inherited by any entry.
3881 Valid for the current buffer.
3882 This variable is populated from #+PROPERTY lines.")
3884 (defgroup org-agenda nil
3885 "Options concerning agenda views in Org mode."
3886 :tag "Org Agenda"
3887 :group 'org)
3889 (defvar-local org-category nil
3890 "Variable used by org files to set a category for agenda display.
3891 Such files should use a file variable to set it, for example
3893 # -*- mode: org; org-category: \"ELisp\"
3895 or contain a special line
3897 #+CATEGORY: ELisp
3899 If the file does not specify a category, then file's base name
3900 is used instead.")
3901 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3903 (defcustom org-agenda-files nil
3904 "The files to be used for agenda display.
3906 If an entry is a directory, all files in that directory that are matched
3907 by `org-agenda-file-regexp' will be part of the file list.
3909 If the value of the variable is not a list but a single file name, then
3910 the list of agenda files is actually stored and maintained in that file,
3911 one agenda file per line. In this file paths can be given relative to
3912 `org-directory'. Tilde expansion and environment variable substitution
3913 are also made.
3915 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3916 and removed with `\\[org-remove-file]'."
3917 :group 'org-agenda
3918 :type '(choice
3919 (repeat :tag "List of files and directories" file)
3920 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3922 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3923 "Regular expression to match files for `org-agenda-files'.
3924 If any element in the list in that variable contains a directory instead
3925 of a normal file, all files in that directory that are matched by this
3926 regular expression will be included."
3927 :group 'org-agenda
3928 :type 'regexp)
3930 (defcustom org-agenda-text-search-extra-files nil
3931 "List of extra files to be searched by text search commands.
3932 These files will be searched in addition to the agenda files by the
3933 commands `org-search-view' (`\\[org-agenda] s') \
3934 and `org-occur-in-agenda-files'.
3935 Note that these files will only be searched for text search commands,
3936 not for the other agenda views like todo lists, tag searches or the weekly
3937 agenda. This variable is intended to list notes and possibly archive files
3938 that should also be searched by these two commands.
3939 In fact, if the first element in the list is the symbol `agenda-archives',
3940 then all archive files of all agenda files will be added to the search
3941 scope."
3942 :group 'org-agenda
3943 :type '(set :greedy t
3944 (const :tag "Agenda Archives" agenda-archives)
3945 (repeat :inline t (file))))
3947 (defvaralias 'org-agenda-multi-occur-extra-files
3948 'org-agenda-text-search-extra-files)
3950 (defcustom org-agenda-skip-unavailable-files nil
3951 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3952 A nil value means to remove them, after a query, from the list."
3953 :group 'org-agenda
3954 :type 'boolean)
3956 (defcustom org-calendar-to-agenda-key [?c]
3957 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3958 The command `org-calendar-goto-agenda' will be bound to this key. The
3959 default is the character `c' because then `c' can be used to switch back and
3960 forth between agenda and calendar."
3961 :group 'org-agenda
3962 :type 'sexp)
3964 (defcustom org-calendar-insert-diary-entry-key [?i]
3965 "The key to be installed in `calendar-mode-map' for adding diary entries.
3966 This option is irrelevant until `org-agenda-diary-file' has been configured
3967 to point to an Org file. When that is the case, the command
3968 `org-agenda-diary-entry' will be bound to the key given here, by default
3969 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3970 if you want to continue doing this, you need to change this to a different
3971 key."
3972 :group 'org-agenda
3973 :type 'sexp)
3975 (defcustom org-agenda-diary-file 'diary-file
3976 "File to which to add new entries with the `i' key in agenda and calendar.
3977 When this is the symbol `diary-file', the functionality in the Emacs
3978 calendar will be used to add entries to the `diary-file'. But when this
3979 points to a file, `org-agenda-diary-entry' will be used instead."
3980 :group 'org-agenda
3981 :type '(choice
3982 (const :tag "The standard Emacs diary file" diary-file)
3983 (file :tag "Special Org file diary entries")))
3985 (eval-after-load "calendar"
3986 '(progn
3987 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3988 'org-calendar-goto-agenda)
3989 (add-hook 'calendar-mode-hook
3990 (lambda ()
3991 (unless (eq org-agenda-diary-file 'diary-file)
3992 (define-key calendar-mode-map
3993 org-calendar-insert-diary-entry-key
3994 'org-agenda-diary-entry))))))
3996 (defgroup org-latex nil
3997 "Options for embedding LaTeX code into Org mode."
3998 :tag "Org LaTeX"
3999 :group 'org)
4001 (defcustom org-format-latex-options
4002 '(:foreground default :background default :scale 1.0
4003 :html-foreground "Black" :html-background "Transparent"
4004 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
4005 "Options for creating images from LaTeX fragments.
4006 This is a property list with the following properties:
4007 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
4008 `default' means use the foreground of the default face.
4009 `auto' means use the foreground from the text face.
4010 :background the background color, or \"Transparent\".
4011 `default' means use the background of the default face.
4012 `auto' means use the background from the text face.
4013 :scale a scaling factor for the size of the images, to get more pixels
4014 :html-foreground, :html-background, :html-scale
4015 the same numbers for HTML export.
4016 :matchers a list indicating which matchers should be used to
4017 find LaTeX fragments. Valid members of this list are:
4018 \"begin\" find environments
4019 \"$1\" find single characters surrounded by $.$
4020 \"$\" find math expressions surrounded by $...$
4021 \"$$\" find math expressions surrounded by $$....$$
4022 \"\\(\" find math expressions surrounded by \\(...\\)
4023 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4024 :group 'org-latex
4025 :type 'plist)
4027 (defcustom org-format-latex-signal-error t
4028 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4029 When nil, just push out a message."
4030 :group 'org-latex
4031 :version "24.1"
4032 :type 'boolean)
4034 (defcustom org-latex-to-mathml-jar-file nil
4035 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4036 Use this to specify additional executable file say a jar file.
4038 When using MathToWeb as the converter, specify the full-path to
4039 your mathtoweb.jar file."
4040 :group 'org-latex
4041 :version "24.1"
4042 :type '(choice
4043 (const :tag "None" nil)
4044 (file :tag "JAR file" :must-match t)))
4046 (defcustom org-latex-to-mathml-convert-command nil
4047 "Command to convert LaTeX fragments to MathML.
4048 Replace format-specifiers in the command as noted below and use
4049 `shell-command' to convert LaTeX to MathML.
4050 %j: Executable file in fully expanded form as specified by
4051 `org-latex-to-mathml-jar-file'.
4052 %I: Input LaTeX file in fully expanded form.
4053 %i: The latex fragment to be converted.
4054 %o: Output MathML file.
4056 This command is used by `org-create-math-formula'.
4058 When using MathToWeb as the converter, set this option to
4059 \"java -jar %j -unicode -force -df %o %I\".
4061 When using LaTeXML set this option to
4062 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4063 :group 'org-latex
4064 :version "24.1"
4065 :type '(choice
4066 (const :tag "None" nil)
4067 (string :tag "\nShell command")))
4069 (defcustom org-preview-latex-default-process 'dvipng
4070 "The default process to convert LaTeX fragments to image files.
4071 All available processes and theirs documents can be found in
4072 `org-preview-latex-process-alist', which see."
4073 :group 'org-latex
4074 :version "25.2"
4075 :package-version '(Org . "9.0")
4076 :type 'symbol)
4078 (defcustom org-preview-latex-process-alist
4079 '((dvipng
4080 :programs ("latex" "dvipng" "gs")
4081 :description "dvi > png"
4082 :message "you need to install the programs: latex, dvipng and ghostscript."
4083 :image-input-type "dvi"
4084 :image-output-type "png"
4085 :image-size-adjust (1.0 . 1.0)
4086 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4087 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
4088 (dvisvgm
4089 :programs ("latex" "dvisvgm" "gs")
4090 :description "dvi > svg"
4091 :message "you need to install the programs: latex, dvisvgm and ghostscript."
4092 :use-xcolor t
4093 :image-input-type "dvi"
4094 :image-output-type "svg"
4095 :image-size-adjust (1.7 . 1.5)
4096 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4097 :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
4098 (imagemagick
4099 :programs ("latex" "convert" "gs")
4100 :description "pdf > png"
4101 :message
4102 "you need to install the programs: latex, imagemagick and ghostscript."
4103 :use-xcolor t
4104 :image-input-type "pdf"
4105 :image-output-type "png"
4106 :image-size-adjust (1.0 . 1.0)
4107 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4108 :image-converter
4109 ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
4110 "Definitions of external processes for LaTeX previewing.
4111 Org mode can use some external commands to generate TeX snippet's images for
4112 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4113 `org-create-formula-image' how to call them.
4115 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4116 PROPERTIES accepts the following attributes:
4118 :programs list of strings, required programs.
4119 :description string, describe the process.
4120 :message string, message it when required programs cannot be found.
4121 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4122 :image-output-type string, output file type of image converter (e.g., \"png\").
4123 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4124 deal with background and foreground color of image.
4125 Otherwise, dvipng style background and foregroud color
4126 format are generated. You may then refer to them in
4127 command options with \"%F\" and \"%B\".
4128 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4129 image size showed in buffer and the cdr element is for
4130 HTML file. This option is only useful for process
4131 developers, users should use variable
4132 `org-format-latex-options' instead.
4133 :post-clean list of strings, files matched are to be cleaned up once
4134 the image is generated. When nil, the files with \".dvi\",
4135 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4136 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4137 be cleaned up.
4138 :latex-header list of strings, the LaTeX header of the snippet file.
4139 When nil, the fallback value is used instead, which is
4140 controlled by `org-format-latex-header',
4141 `org-latex-default-packages-alist' and
4142 `org-latex-packages-alist', which see.
4143 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4144 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4145 replaced with values defined below.
4146 :image-converter list of image converter commands strings. Each of them is
4147 given to the shell and supports any of the following
4148 place-holders defined below.
4150 Place-holders used by `:image-converter' and `:latex-compiler':
4152 %f input file name.
4153 %b base name of input file.
4154 %o base directory of input file.
4156 Place-holders only used by `:image-converter':
4158 %F foreground of image
4159 %B background of image
4160 %D dpi, which is used to adjust image size by some processing commands.
4161 %S the image size scale ratio, which is used to adjust image size by some
4162 processing commands."
4163 :group 'org-latex
4164 :version "25.2"
4165 :package-version '(Org . "9.0")
4166 :type '(alist :tag "LaTeX to image backends"
4167 :value-type (plist)))
4169 (defcustom org-preview-latex-image-directory "ltximg/"
4170 "Path to store latex preview images.
4171 A relative path here creates many directories relative to the
4172 processed org files paths. An absolute path puts all preview
4173 images at the same place."
4174 :group 'org-latex
4175 :version "25.2"
4176 :package-version '(Org . "9.0")
4177 :type 'string)
4179 (defun org-format-latex-mathml-available-p ()
4180 "Return t if `org-latex-to-mathml-convert-command' is usable."
4181 (save-match-data
4182 (when (and (boundp 'org-latex-to-mathml-convert-command)
4183 org-latex-to-mathml-convert-command)
4184 (let ((executable (car (split-string
4185 org-latex-to-mathml-convert-command))))
4186 (when (executable-find executable)
4187 (if (string-match
4188 "%j" org-latex-to-mathml-convert-command)
4189 (file-readable-p org-latex-to-mathml-jar-file)
4190 t))))))
4192 (defcustom org-format-latex-header "\\documentclass{article}
4193 \\usepackage[usenames]{color}
4194 \[PACKAGES]
4195 \[DEFAULT-PACKAGES]
4196 \\pagestyle{empty} % do not remove
4197 % The settings below are copied from fullpage.sty
4198 \\setlength{\\textwidth}{\\paperwidth}
4199 \\addtolength{\\textwidth}{-3cm}
4200 \\setlength{\\oddsidemargin}{1.5cm}
4201 \\addtolength{\\oddsidemargin}{-2.54cm}
4202 \\setlength{\\evensidemargin}{\\oddsidemargin}
4203 \\setlength{\\textheight}{\\paperheight}
4204 \\addtolength{\\textheight}{-\\headheight}
4205 \\addtolength{\\textheight}{-\\headsep}
4206 \\addtolength{\\textheight}{-\\footskip}
4207 \\addtolength{\\textheight}{-3cm}
4208 \\setlength{\\topmargin}{1.5cm}
4209 \\addtolength{\\topmargin}{-2.54cm}"
4210 "The document header used for processing LaTeX fragments.
4211 It is imperative that this header make sure that no page number
4212 appears on the page. The package defined in the variables
4213 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4214 will either replace the placeholder \"[PACKAGES]\" in this
4215 header, or they will be appended."
4216 :group 'org-latex
4217 :type 'string)
4219 (defun org-set-packages-alist (var val)
4220 "Set the packages alist and make sure it has 3 elements per entry."
4221 (set var (mapcar (lambda (x)
4222 (if (and (consp x) (= (length x) 2))
4223 (list (car x) (nth 1 x) t)
4225 val)))
4227 (defun org-get-packages-alist (var)
4228 "Get the packages alist and make sure it has 3 elements per entry."
4229 (mapcar (lambda (x)
4230 (if (and (consp x) (= (length x) 2))
4231 (list (car x) (nth 1 x) t)
4233 (default-value var)))
4235 (defcustom org-latex-default-packages-alist
4236 '(("AUTO" "inputenc" t ("pdflatex"))
4237 ("T1" "fontenc" t ("pdflatex"))
4238 ("" "graphicx" t)
4239 ("" "grffile" t)
4240 ("" "longtable" nil)
4241 ("" "wrapfig" nil)
4242 ("" "rotating" nil)
4243 ("normalem" "ulem" t)
4244 ("" "amsmath" t)
4245 ("" "textcomp" t)
4246 ("" "amssymb" t)
4247 ("" "capt-of" nil)
4248 ("" "hyperref" nil))
4249 "Alist of default packages to be inserted in the header.
4251 Change this only if one of the packages here causes an
4252 incompatibility with another package you are using.
4254 The packages in this list are needed by one part or another of
4255 Org mode to function properly:
4257 - inputenc, fontenc: for basic font and character selection
4258 - graphicx: for including images
4259 - grffile: allow periods and spaces in graphics file names
4260 - longtable: For multipage tables
4261 - wrapfig: for figure placement
4262 - rotating: for sideways figures and tables
4263 - ulem: for underline and strike-through
4264 - amsmath: for subscript and superscript and math environments
4265 - textcomp, amssymb: for various symbols used
4266 for interpreting the entities in `org-entities'. You can skip
4267 some of these packages if you don't use any of their symbols.
4268 - capt-of: for captions outside of floats
4269 - hyperref: for cross references
4271 Therefore you should not modify this variable unless you know
4272 what you are doing. The one reason to change it anyway is that
4273 you might be loading some other package that conflicts with one
4274 of the default packages. Each element is either a cell or
4275 a string.
4277 A cell is of the format
4279 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4281 If SNIPPET-FLAG is non-nil, the package also needs to be included
4282 when compiling LaTeX snippets into images for inclusion into
4283 non-LaTeX output. COMPILERS is a list of compilers that should
4284 include the package, see `org-latex-compiler'. If the document
4285 compiler is not in the list, and the list is non-nil, the package
4286 will not be inserted in the final document.
4288 A string will be inserted as-is in the header of the document."
4289 :group 'org-latex
4290 :group 'org-export-latex
4291 :set 'org-set-packages-alist
4292 :get 'org-get-packages-alist
4293 :version "25.2"
4294 :package-version '(Org . "8.3")
4295 :type '(repeat
4296 (choice
4297 (list :tag "options/package pair"
4298 (string :tag "options")
4299 (string :tag "package")
4300 (boolean :tag "Snippet"))
4301 (string :tag "A line of LaTeX"))))
4303 (defcustom org-latex-packages-alist nil
4304 "Alist of packages to be inserted in every LaTeX header.
4306 These will be inserted after `org-latex-default-packages-alist'.
4307 Each element is either a cell or a string.
4309 A cell is of the format:
4311 (\"options\" \"package\" SNIPPET-FLAG)
4313 SNIPPET-FLAG, when non-nil, indicates that this package is also
4314 needed when turning LaTeX snippets into images for inclusion into
4315 non-LaTeX output.
4317 A string will be inserted as-is in the header of the document.
4319 Make sure that you only list packages here which:
4321 - you want in every file;
4322 - do not conflict with the setup in `org-format-latex-header';
4323 - do not conflict with the default packages in
4324 `org-latex-default-packages-alist'."
4325 :group 'org-latex
4326 :group 'org-export-latex
4327 :set 'org-set-packages-alist
4328 :get 'org-get-packages-alist
4329 :type '(repeat
4330 (choice
4331 (list :tag "options/package pair"
4332 (string :tag "options")
4333 (string :tag "package")
4334 (boolean :tag "Snippet"))
4335 (string :tag "A line of LaTeX"))))
4337 (defgroup org-appearance nil
4338 "Settings for Org mode appearance."
4339 :tag "Org Appearance"
4340 :group 'org)
4342 (defcustom org-level-color-stars-only nil
4343 "Non-nil means fontify only the stars in each headline.
4344 When nil, the entire headline is fontified.
4345 Changing it requires restart of `font-lock-mode' to become effective
4346 also in regions already fontified."
4347 :group 'org-appearance
4348 :type 'boolean)
4350 (defcustom org-hide-leading-stars nil
4351 "Non-nil means hide the first N-1 stars in a headline.
4352 This works by using the face `org-hide' for these stars. This
4353 face is white for a light background, and black for a dark
4354 background. You may have to customize the face `org-hide' to
4355 make this work.
4356 Changing it requires restart of `font-lock-mode' to become effective
4357 also in regions already fontified.
4358 You may also set this on a per-file basis by adding one of the following
4359 lines to the buffer:
4361 #+STARTUP: hidestars
4362 #+STARTUP: showstars"
4363 :group 'org-appearance
4364 :type 'boolean)
4366 (defcustom org-hidden-keywords nil
4367 "List of symbols corresponding to keywords to be hidden the org buffer.
4368 For example, a value \\='(title) for this list will make the document's title
4369 appear in the buffer without the initial #+TITLE: keyword."
4370 :group 'org-appearance
4371 :version "24.1"
4372 :type '(set (const :tag "#+AUTHOR" author)
4373 (const :tag "#+DATE" date)
4374 (const :tag "#+EMAIL" email)
4375 (const :tag "#+TITLE" title)))
4377 (defcustom org-custom-properties nil
4378 "List of properties (as strings) with a special meaning.
4379 The default use of these custom properties is to let the user
4380 hide them with `org-toggle-custom-properties-visibility'."
4381 :group 'org-properties
4382 :group 'org-appearance
4383 :version "24.3"
4384 :type '(repeat (string :tag "Property Name")))
4386 (defcustom org-fontify-done-headline nil
4387 "Non-nil means change the face of a headline if it is marked DONE.
4388 Normally, only the TODO/DONE keyword indicates the state of a headline.
4389 When this is non-nil, the headline after the keyword is set to the
4390 `org-headline-done' as an additional indication."
4391 :group 'org-appearance
4392 :type 'boolean)
4394 (defcustom org-fontify-emphasized-text t
4395 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4396 Changing this variable requires a restart of Emacs to take effect."
4397 :group 'org-appearance
4398 :type 'boolean)
4400 (defcustom org-fontify-whole-heading-line nil
4401 "Non-nil means fontify the whole line for headings.
4402 This is useful when setting a background color for the
4403 org-level-* faces."
4404 :group 'org-appearance
4405 :type 'boolean)
4407 (defcustom org-highlight-latex-and-related nil
4408 "Non-nil means highlight LaTeX related syntax in the buffer.
4409 When non nil, the value should be a list containing any of the
4410 following symbols:
4411 `latex' Highlight LaTeX snippets and environments.
4412 `script' Highlight subscript and superscript.
4413 `entities' Highlight entities."
4414 :group 'org-appearance
4415 :version "24.4"
4416 :package-version '(Org . "8.0")
4417 :type '(choice
4418 (const :tag "No highlighting" nil)
4419 (set :greedy t :tag "Highlight"
4420 (const :tag "LaTeX snippets and environments" latex)
4421 (const :tag "Subscript and superscript" script)
4422 (const :tag "Entities" entities))))
4424 (defcustom org-hide-emphasis-markers nil
4425 "Non-nil mean font-lock should hide the emphasis marker characters."
4426 :group 'org-appearance
4427 :type 'boolean)
4429 (defcustom org-hide-macro-markers nil
4430 "Non-nil mean font-lock should hide the brackets marking macro calls."
4431 :group 'org-appearance
4432 :type 'boolean)
4434 (defcustom org-pretty-entities nil
4435 "Non-nil means show entities as UTF8 characters.
4436 When nil, the \\name form remains in the buffer."
4437 :group 'org-appearance
4438 :version "24.1"
4439 :type 'boolean)
4441 (defcustom org-pretty-entities-include-sub-superscripts t
4442 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4443 :group 'org-appearance
4444 :version "24.1"
4445 :type 'boolean)
4447 (defvar org-emph-re nil
4448 "Regular expression for matching emphasis.
4449 After a match, the match groups contain these elements:
4450 0 The match of the full regular expression, including the characters
4451 before and after the proper match
4452 1 The character before the proper match, or empty at beginning of line
4453 2 The proper match, including the leading and trailing markers
4454 3 The leading marker like * or /, indicating the type of highlighting
4455 4 The text between the emphasis markers, not including the markers
4456 5 The character after the match, empty at the end of a line")
4457 (defvar org-verbatim-re nil
4458 "Regular expression for matching verbatim text.")
4459 (defvar org-emphasis-regexp-components) ; defined just below
4460 (defvar org-emphasis-alist) ; defined just below
4461 (defun org-set-emph-re (var val)
4462 "Set variable and compute the emphasis regular expression."
4463 (set var val)
4464 (when (and (boundp 'org-emphasis-alist)
4465 (boundp 'org-emphasis-regexp-components)
4466 org-emphasis-alist org-emphasis-regexp-components)
4467 (let* ((e org-emphasis-regexp-components)
4468 (pre (car e))
4469 (post (nth 1 e))
4470 (border (nth 2 e))
4471 (body (nth 3 e))
4472 (nl (nth 4 e))
4473 (body1 (concat body "*?"))
4474 (markers (mapconcat 'car org-emphasis-alist ""))
4475 (vmarkers (mapconcat
4476 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4477 org-emphasis-alist "")))
4478 ;; make sure special characters appear at the right position in the class
4479 (if (string-match "\\^" markers)
4480 (setq markers (concat (replace-match "" t t markers) "^")))
4481 (if (string-match "-" markers)
4482 (setq markers (concat (replace-match "" t t markers) "-")))
4483 (if (string-match "\\^" vmarkers)
4484 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4485 (if (string-match "-" vmarkers)
4486 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4487 (if (> nl 0)
4488 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4489 (int-to-string nl) "\\}")))
4490 ;; Make the regexp
4491 (setq org-emph-re
4492 (concat "\\([" pre "]\\|^\\)"
4493 "\\("
4494 "\\([" markers "]\\)"
4495 "\\("
4496 "[^" border "]\\|"
4497 "[^" border "]"
4498 body1
4499 "[^" border "]"
4500 "\\)"
4501 "\\3\\)"
4502 "\\([" post "]\\|$\\)"))
4503 (setq org-verbatim-re
4504 (concat "\\([" pre "]\\|^\\)"
4505 "\\("
4506 "\\([" vmarkers "]\\)"
4507 "\\("
4508 "[^" border "]\\|"
4509 "[^" border "]"
4510 body1
4511 "[^" border "]"
4512 "\\)"
4513 "\\3\\)"
4514 "\\([" post "]\\|$\\)")))))
4516 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4517 ;; set this option proved cumbersome. See this message/thread:
4518 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4519 (defvar org-emphasis-regexp-components
4520 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4521 "Components used to build the regular expression for emphasis.
4522 This is a list with five entries. Terminology: In an emphasis string
4523 like \" *strong word* \", we call the initial space PREMATCH, the final
4524 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4525 and \"trong wor\" is the body. The different components in this variable
4526 specify what is allowed/forbidden in each part:
4528 pre Chars allowed as prematch. Beginning of line will be allowed too.
4529 post Chars allowed as postmatch. End of line will be allowed too.
4530 border The chars *forbidden* as border characters.
4531 body-regexp A regexp like \".\" to match a body character. Don't use
4532 non-shy groups here, and don't allow newline here.
4533 newline The maximum number of newlines allowed in an emphasis exp.
4535 You need to reload Org or to restart Emacs after customizing this.")
4537 (defcustom org-emphasis-alist
4538 '(("*" bold)
4539 ("/" italic)
4540 ("_" underline)
4541 ("=" org-verbatim verbatim)
4542 ("~" org-code verbatim)
4543 ("+" (:strike-through t)))
4544 "Alist of characters and faces to emphasize text.
4545 Text starting and ending with a special character will be emphasized,
4546 for example *bold*, _underlined_ and /italic/. This variable sets the
4547 marker characters and the face to be used by font-lock for highlighting
4548 in Org buffers.
4550 You need to reload Org or to restart Emacs after customizing this."
4551 :group 'org-appearance
4552 :set 'org-set-emph-re
4553 :version "24.4"
4554 :package-version '(Org . "8.0")
4555 :type '(repeat
4556 (list
4557 (string :tag "Marker character")
4558 (choice
4559 (face :tag "Font-lock-face")
4560 (plist :tag "Face property list"))
4561 (option (const verbatim)))))
4563 (defvar org-protecting-blocks '("src" "example" "export")
4564 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4565 This is needed for font-lock setup.")
4567 ;;; Functions and variables from their packages
4568 ;; Declared here to avoid compiler warnings
4569 (defvar mark-active)
4571 ;; Various packages
4572 (declare-function calc-eval "calc" (str &optional separator &rest args))
4573 (declare-function calendar-forward-day "cal-move" (arg))
4574 (declare-function calendar-goto-date "cal-move" (date))
4575 (declare-function calendar-goto-today "cal-move" ())
4576 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4577 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4578 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4579 (declare-function cdlatex-tab "ext:cdlatex" ())
4580 (declare-function dired-get-filename
4581 "dired"
4582 (&optional localp no-error-if-not-filep))
4583 (declare-function iswitchb-read-buffer
4584 "iswitchb"
4585 (prompt &optional
4586 default require-match _predicate start matches-set))
4587 (declare-function org-agenda-change-all-lines
4588 "org-agenda"
4589 (newhead hdmarker &optional fixface just-this))
4590 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4591 "org-agenda"
4592 (&optional end))
4593 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4594 (declare-function org-agenda-format-item
4595 "org-agenda"
4596 (extra txt &optional level category tags dotime
4597 remove-re habitp))
4598 (declare-function org-agenda-maybe-redo "org-agenda" ())
4599 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4600 (declare-function org-agenda-save-markers-for-cut-and-paste
4601 "org-agenda"
4602 (beg end))
4603 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4604 (declare-function org-agenda-skip "org-agenda" ())
4605 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4606 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4607 (declare-function org-indent-mode "org-indent" (&optional arg))
4608 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4609 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4610 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4611 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4612 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4613 (declare-function parse-time-string "parse-time" (string))
4614 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4616 (defvar align-mode-rules-list)
4617 (defvar calc-embedded-close-formula)
4618 (defvar calc-embedded-open-formula)
4619 (defvar calc-embedded-open-mode)
4620 (defvar font-lock-unfontify-region-function)
4621 (defvar iswitchb-temp-buflist)
4622 (defvar org-agenda-tags-todo-honor-ignore-options)
4623 (defvar remember-data-file)
4624 (defvar texmathp-why)
4626 ;;;###autoload
4627 (defun turn-on-orgtbl ()
4628 "Unconditionally turn on `orgtbl-mode'."
4629 (require 'org-table)
4630 (orgtbl-mode 1))
4632 (defun org-at-table-p (&optional table-type)
4633 "Non-nil if the cursor is inside an Org table.
4634 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4635 If `org-enable-table-editor' is nil, return nil unconditionally."
4636 (and
4637 org-enable-table-editor
4638 (save-excursion
4639 (beginning-of-line)
4640 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4641 (or (not (derived-mode-p 'org-mode))
4642 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4643 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4645 (defun org-at-table.el-p ()
4646 "Non-nil when point is at a table.el table."
4647 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4648 (let ((element (org-element-at-point)))
4649 (and (eq (org-element-type element) 'table)
4650 (eq (org-element-property :type element) 'table.el)))))
4652 (defun org-at-table-hline-p ()
4653 "Non-nil when point is inside a hline in a table.
4654 Assume point is already in a table. If `org-enable-table-editor'
4655 is nil, return nil unconditionally."
4656 (and org-enable-table-editor
4657 (save-excursion
4658 (beginning-of-line)
4659 (looking-at org-table-hline-regexp))))
4661 (defun org-table-map-tables (function &optional quietly)
4662 "Apply FUNCTION to the start of all tables in the buffer."
4663 (org-with-wide-buffer
4664 (goto-char (point-min))
4665 (while (re-search-forward org-table-any-line-regexp nil t)
4666 (unless quietly
4667 (message "Mapping tables: %d%%"
4668 (floor (* 100.0 (point)) (buffer-size))))
4669 (beginning-of-line 1)
4670 (when (and (looking-at org-table-line-regexp)
4671 ;; Exclude tables in src/example/verbatim/clocktable blocks
4672 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4673 (save-excursion (funcall function))
4674 (or (looking-at org-table-line-regexp)
4675 (forward-char 1)))
4676 (re-search-forward org-table-any-border-regexp nil 1)))
4677 (unless quietly (message "Mapping tables: done")))
4679 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4680 (declare-function org-clock-update-mode-line "org-clock" ())
4681 (declare-function org-resolve-clocks "org-clock"
4682 (&optional also-non-dangling-p prompt last-valid))
4684 (defun org-at-TBLFM-p (&optional pos)
4685 "Non-nil when point (or POS) is in #+TBLFM line."
4686 (save-excursion
4687 (goto-char (or pos (point)))
4688 (beginning-of-line)
4689 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4690 (eq (org-element-type (org-element-at-point)) 'table))))
4692 (defvar org-clock-start-time)
4693 (defvar org-clock-marker (make-marker)
4694 "Marker recording the last clock-in.")
4695 (defvar org-clock-hd-marker (make-marker)
4696 "Marker recording the last clock-in, but the headline position.")
4697 (defvar org-clock-heading ""
4698 "The heading of the current clock entry.")
4699 (defun org-clock-is-active ()
4700 "Return the buffer where the clock is currently running.
4701 Return nil if no clock is running."
4702 (marker-buffer org-clock-marker))
4704 (defun org-check-running-clock ()
4705 "Check if the current buffer contains the running clock.
4706 If yes, offer to stop it and to save the buffer with the changes."
4707 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4708 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4709 (buffer-name))))
4710 (org-clock-out)
4711 (when (y-or-n-p "Save changed buffer?")
4712 (save-buffer))))
4714 (defun org-clocktable-try-shift (dir n)
4715 "Check if this line starts a clock table, if yes, shift the time block."
4716 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4717 (org-clocktable-shift dir n)))
4719 ;;;###autoload
4720 (defun org-clock-persistence-insinuate ()
4721 "Set up hooks for clock persistence."
4722 (require 'org-clock)
4723 (add-hook 'org-mode-hook 'org-clock-load)
4724 (add-hook 'kill-emacs-hook 'org-clock-save))
4726 (defgroup org-archive nil
4727 "Options concerning archiving in Org mode."
4728 :tag "Org Archive"
4729 :group 'org-structure)
4731 (defcustom org-archive-location "%s_archive::"
4732 "The location where subtrees should be archived.
4734 The value of this variable is a string, consisting of two parts,
4735 separated by a double-colon. The first part is a filename and
4736 the second part is a headline.
4738 When the filename is omitted, archiving happens in the same file.
4739 %s in the filename will be replaced by the current file
4740 name (without the directory part). Archiving to a different file
4741 is useful to keep archived entries from contributing to the
4742 Org Agenda.
4744 The archived entries will be filed as subtrees of the specified
4745 headline. When the headline is omitted, the subtrees are simply
4746 filed away at the end of the file, as top-level entries. Also in
4747 the heading you can use %s to represent the file name, this can be
4748 useful when using the same archive for a number of different files.
4750 Here are a few examples:
4751 \"%s_archive::\"
4752 If the current file is Projects.org, archive in file
4753 Projects.org_archive, as top-level trees. This is the default.
4755 \"::* Archived Tasks\"
4756 Archive in the current file, under the top-level headline
4757 \"* Archived Tasks\".
4759 \"~/org/archive.org::\"
4760 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4762 \"~/org/archive.org::* From %s\"
4763 Archive in file ~/org/archive.org (absolute path), under headlines
4764 \"From FILENAME\" where file name is the current file name.
4766 \"~/org/datetree.org::datetree/* Finished Tasks\"
4767 The \"datetree/\" string is special, signifying to archive
4768 items to the datetree. Items are placed in either the CLOSED
4769 date of the item, or the current date if there is no CLOSED date.
4770 The heading will be a subentry to the current date. There doesn't
4771 need to be a heading, but there always needs to be a slash after
4772 datetree. For example, to store archived items directly in the
4773 datetree, use \"~/org/datetree.org::datetree/\".
4775 \"basement::** Finished Tasks\"
4776 Archive in file ./basement (relative path), as level 3 trees
4777 below the level 2 heading \"** Finished Tasks\".
4779 You may set this option on a per-file basis by adding to the buffer a
4780 line like
4782 #+ARCHIVE: basement::** Finished Tasks
4784 You may also define it locally for a subtree by setting an ARCHIVE property
4785 in the entry. If such a property is found in an entry, or anywhere up
4786 the hierarchy, it will be used."
4787 :group 'org-archive
4788 :type 'string)
4790 (defcustom org-agenda-skip-archived-trees t
4791 "Non-nil means the agenda will skip any items located in archived trees.
4792 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4793 variable is no longer recommended, you should leave it at the value t.
4794 Instead, use the key `v' to cycle the archives-mode in the agenda."
4795 :group 'org-archive
4796 :group 'org-agenda-skip
4797 :type 'boolean)
4799 (defcustom org-columns-skip-archived-trees t
4800 "Non-nil means ignore archived trees when creating column view."
4801 :group 'org-archive
4802 :group 'org-properties
4803 :type 'boolean)
4805 (defcustom org-cycle-open-archived-trees nil
4806 "Non-nil means `org-cycle' will open archived trees.
4807 An archived tree is a tree marked with the tag ARCHIVE.
4808 When nil, archived trees will stay folded. You can still open them with
4809 normal outline commands like `show-all', but not with the cycling commands."
4810 :group 'org-archive
4811 :group 'org-cycle
4812 :type 'boolean)
4814 (defcustom org-sparse-tree-open-archived-trees nil
4815 "Non-nil means sparse tree construction shows matches in archived trees.
4816 When nil, matches in these trees are highlighted, but the trees are kept in
4817 collapsed state."
4818 :group 'org-archive
4819 :group 'org-sparse-trees
4820 :type 'boolean)
4822 (defcustom org-sparse-tree-default-date-type nil
4823 "The default date type when building a sparse tree.
4824 When this is nil, a date is a scheduled or a deadline timestamp.
4825 Otherwise, these types are allowed:
4827 all: all timestamps
4828 active: only active timestamps (<...>)
4829 inactive: only inactive timestamps ([...])
4830 scheduled: only scheduled timestamps
4831 deadline: only deadline timestamps"
4832 :type '(choice (const :tag "Scheduled or deadline" nil)
4833 (const :tag "All timestamps" all)
4834 (const :tag "Only active timestamps" active)
4835 (const :tag "Only inactive timestamps" inactive)
4836 (const :tag "Only scheduled timestamps" scheduled)
4837 (const :tag "Only deadline timestamps" deadline)
4838 (const :tag "Only closed timestamps" closed))
4839 :version "25.2"
4840 :package-version '(Org . "8.3")
4841 :group 'org-sparse-trees)
4843 (defun org-cycle-hide-archived-subtrees (state)
4844 "Re-hide all archived subtrees after a visibility state change."
4845 (when (and (not org-cycle-open-archived-trees)
4846 (not (memq state '(overview folded))))
4847 (save-excursion
4848 (let* ((globalp (memq state '(contents all)))
4849 (beg (if globalp (point-min) (point)))
4850 (end (if globalp (point-max) (org-end-of-subtree t))))
4851 (org-hide-archived-subtrees beg end)
4852 (goto-char beg)
4853 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4854 (message "%s" (substitute-command-keys
4855 "Subtree is archived and stays closed. Use \
4856 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4858 (defun org-force-cycle-archived ()
4859 "Cycle subtree even if it is archived."
4860 (interactive)
4861 (setq this-command 'org-cycle)
4862 (let ((org-cycle-open-archived-trees t))
4863 (call-interactively 'org-cycle)))
4865 (defun org-hide-archived-subtrees (beg end)
4866 "Re-hide all archived subtrees after a visibility state change."
4867 (org-with-wide-buffer
4868 (let ((case-fold-search nil)
4869 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4870 (goto-char beg)
4871 ;; Include headline point is currently on.
4872 (beginning-of-line)
4873 (while (and (< (point) end) (re-search-forward re end t))
4874 (when (member org-archive-tag (org-get-tags))
4875 (org-flag-subtree t)
4876 (org-end-of-subtree t))))))
4878 (declare-function outline-end-of-heading "outline" ())
4879 (declare-function outline-flag-region "outline" (from to flag))
4880 (defun org-flag-subtree (flag)
4881 (save-excursion
4882 (org-back-to-heading t)
4883 (outline-end-of-heading)
4884 (outline-flag-region (point)
4885 (progn (org-end-of-subtree t) (point))
4886 flag)))
4888 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4890 ;; Declare Column View Code
4892 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4893 (declare-function org-columns-compute "org-colview" (property))
4895 ;; Declare ID code
4897 (declare-function org-id-store-link "org-id")
4898 (declare-function org-id-locations-load "org-id")
4899 (declare-function org-id-locations-save "org-id")
4900 (defvar org-id-track-globally)
4902 ;;; Variables for pre-computed regular expressions, all buffer local
4904 (defvar-local org-todo-regexp nil
4905 "Matches any of the TODO state keywords.")
4906 (defvar-local org-not-done-regexp nil
4907 "Matches any of the TODO state keywords except the last one.")
4908 (defvar-local org-not-done-heading-regexp nil
4909 "Matches a TODO headline that is not done.")
4910 (defvar-local org-todo-line-regexp nil
4911 "Matches a headline and puts TODO state into group 2 if present.")
4912 (defvar-local org-complex-heading-regexp nil
4913 "Matches a headline and puts everything into groups:
4914 group 1: the stars
4915 group 2: The todo keyword, maybe
4916 group 3: Priority cookie
4917 group 4: True headline
4918 group 5: Tags")
4919 (defvar-local org-complex-heading-regexp-format nil
4920 "Printf format to make regexp to match an exact headline.
4921 This regexp will match the headline of any node which has the
4922 exact headline text that is put into the format, but may have any
4923 TODO state, priority and tags.")
4924 (defvar-local org-todo-line-tags-regexp nil
4925 "Matches a headline and puts TODO state into group 2 if present.
4926 Also put tags into group 4 if tags are present.")
4928 (defconst org-plain-time-of-day-regexp
4929 (concat
4930 "\\(\\<[012]?[0-9]"
4931 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4932 "\\(--?"
4933 "\\(\\<[012]?[0-9]"
4934 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4935 "\\)?")
4936 "Regular expression to match a plain time or time range.
4937 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4938 groups carry important information:
4939 0 the full match
4940 1 the first time, range or not
4941 8 the second time, if it is a range.")
4943 (defconst org-plain-time-extension-regexp
4944 (concat
4945 "\\(\\<[012]?[0-9]"
4946 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4947 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4948 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4949 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4950 groups carry important information:
4951 0 the full match
4952 7 hours of duration
4953 9 minutes of duration")
4955 (defconst org-stamp-time-of-day-regexp
4956 (concat
4957 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4958 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4959 "\\(--?"
4960 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4961 "Regular expression to match a timestamp time or time range.
4962 After a match, the following groups carry important information:
4963 0 the full match
4964 1 date plus weekday, for back referencing to make sure both times are on the same day
4965 2 the first time, range or not
4966 4 the second time, if it is a range.")
4968 (defconst org-startup-options
4969 '(("fold" org-startup-folded t)
4970 ("overview" org-startup-folded t)
4971 ("nofold" org-startup-folded nil)
4972 ("showall" org-startup-folded nil)
4973 ("showeverything" org-startup-folded showeverything)
4974 ("content" org-startup-folded content)
4975 ("indent" org-startup-indented t)
4976 ("noindent" org-startup-indented nil)
4977 ("hidestars" org-hide-leading-stars t)
4978 ("showstars" org-hide-leading-stars nil)
4979 ("odd" org-odd-levels-only t)
4980 ("oddeven" org-odd-levels-only nil)
4981 ("align" org-startup-align-all-tables t)
4982 ("noalign" org-startup-align-all-tables nil)
4983 ("inlineimages" org-startup-with-inline-images t)
4984 ("noinlineimages" org-startup-with-inline-images nil)
4985 ("latexpreview" org-startup-with-latex-preview t)
4986 ("nolatexpreview" org-startup-with-latex-preview nil)
4987 ("customtime" org-display-custom-times t)
4988 ("logdone" org-log-done time)
4989 ("lognotedone" org-log-done note)
4990 ("nologdone" org-log-done nil)
4991 ("lognoteclock-out" org-log-note-clock-out t)
4992 ("nolognoteclock-out" org-log-note-clock-out nil)
4993 ("logrepeat" org-log-repeat state)
4994 ("lognoterepeat" org-log-repeat note)
4995 ("logdrawer" org-log-into-drawer t)
4996 ("nologdrawer" org-log-into-drawer nil)
4997 ("logstatesreversed" org-log-states-order-reversed t)
4998 ("nologstatesreversed" org-log-states-order-reversed nil)
4999 ("nologrepeat" org-log-repeat nil)
5000 ("logreschedule" org-log-reschedule time)
5001 ("lognotereschedule" org-log-reschedule note)
5002 ("nologreschedule" org-log-reschedule nil)
5003 ("logredeadline" org-log-redeadline time)
5004 ("lognoteredeadline" org-log-redeadline note)
5005 ("nologredeadline" org-log-redeadline nil)
5006 ("logrefile" org-log-refile time)
5007 ("lognoterefile" org-log-refile note)
5008 ("nologrefile" org-log-refile nil)
5009 ("fninline" org-footnote-define-inline t)
5010 ("nofninline" org-footnote-define-inline nil)
5011 ("fnlocal" org-footnote-section nil)
5012 ("fnauto" org-footnote-auto-label t)
5013 ("fnprompt" org-footnote-auto-label nil)
5014 ("fnconfirm" org-footnote-auto-label confirm)
5015 ("fnplain" org-footnote-auto-label plain)
5016 ("fnadjust" org-footnote-auto-adjust t)
5017 ("nofnadjust" org-footnote-auto-adjust nil)
5018 ("constcgs" constants-unit-system cgs)
5019 ("constSI" constants-unit-system SI)
5020 ("noptag" org-tag-persistent-alist nil)
5021 ("hideblocks" org-hide-block-startup t)
5022 ("nohideblocks" org-hide-block-startup nil)
5023 ("beamer" org-startup-with-beamer-mode t)
5024 ("entitiespretty" org-pretty-entities t)
5025 ("entitiesplain" org-pretty-entities nil))
5026 "Variable associated with STARTUP options for org-mode.
5027 Each element is a list of three items: the startup options (as written
5028 in the #+STARTUP line), the corresponding variable, and the value to set
5029 this variable to if the option is found. An optional forth element PUSH
5030 means to push this value onto the list in the variable.")
5032 (defcustom org-group-tags t
5033 "When non-nil (the default), use group tags.
5034 This can be turned on/off through `org-toggle-tags-groups'."
5035 :group 'org-tags
5036 :group 'org-startup
5037 :type 'boolean)
5039 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5041 (defun org-toggle-tags-groups ()
5042 "Toggle support for group tags.
5043 Support for group tags is controlled by the option
5044 `org-group-tags', which is non-nil by default."
5045 (interactive)
5046 (setq org-group-tags (not org-group-tags))
5047 (cond ((and (derived-mode-p 'org-agenda-mode)
5048 org-group-tags)
5049 (org-agenda-redo))
5050 ((derived-mode-p 'org-mode)
5051 (let ((org-inhibit-startup t)) (org-mode))))
5052 (message "Groups tags support has been turned %s"
5053 (if org-group-tags "on" "off")))
5055 (defun org-set-regexps-and-options (&optional tags-only)
5056 "Precompute regular expressions used in the current buffer.
5057 When optional argument TAGS-ONLY is non-nil, only compute tags
5058 related expressions."
5059 (when (derived-mode-p 'org-mode)
5060 (let ((alist (org--setup-collect-keywords
5061 (org-make-options-regexp
5062 (append '("FILETAGS" "TAGS" "SETUPFILE")
5063 (and (not tags-only)
5064 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5065 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5066 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5067 ;; Startup options. Get this early since it does change
5068 ;; behavior for other options (e.g., tags).
5069 (let ((startup (cdr (assq 'startup alist))))
5070 (dolist (option startup)
5071 (let ((entry (assoc-string option org-startup-options t)))
5072 (when entry
5073 (let ((var (nth 1 entry))
5074 (val (nth 2 entry)))
5075 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5076 (unless (listp (symbol-value var))
5077 (set (make-local-variable var) nil))
5078 (add-to-list var val)))))))
5079 (setq-local org-file-tags
5080 (mapcar #'org-add-prop-inherited
5081 (cdr (assq 'filetags alist))))
5082 (setq org-current-tag-alist
5083 (append org-tag-persistent-alist
5084 (let ((tags (cdr (assq 'tags alist))))
5085 (if tags (org-tag-string-to-alist tags)
5086 org-tag-alist))))
5087 (setq org-tag-groups-alist
5088 (org-tag-alist-to-groups org-current-tag-alist))
5089 (unless tags-only
5090 ;; File properties.
5091 (setq-local org-file-properties (cdr (assq 'property alist)))
5092 ;; Archive location.
5093 (let ((archive (cdr (assq 'archive alist))))
5094 (when archive (setq-local org-archive-location archive)))
5095 ;; Category.
5096 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5097 (when cat
5098 (setq-local org-category (intern cat))
5099 (setq-local org-file-properties
5100 (org--update-property-plist
5101 "CATEGORY" cat org-file-properties))))
5102 ;; Columns.
5103 (let ((column (cdr (assq 'columns alist))))
5104 (when column (setq-local org-columns-default-format column)))
5105 ;; Constants.
5106 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5107 ;; Link abbreviations.
5108 (let ((links (cdr (assq 'link alist))))
5109 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5110 ;; Priorities.
5111 (let ((priorities (cdr (assq 'priorities alist))))
5112 (when priorities
5113 (setq-local org-highest-priority (nth 0 priorities))
5114 (setq-local org-lowest-priority (nth 1 priorities))
5115 (setq-local org-default-priority (nth 2 priorities))))
5116 ;; Scripts.
5117 (let ((scripts (assq 'scripts alist)))
5118 (when scripts
5119 (setq-local org-use-sub-superscripts (cdr scripts))))
5120 ;; TODO keywords.
5121 (setq-local org-todo-kwd-alist nil)
5122 (setq-local org-todo-key-alist nil)
5123 (setq-local org-todo-key-trigger nil)
5124 (setq-local org-todo-keywords-1 nil)
5125 (setq-local org-done-keywords nil)
5126 (setq-local org-todo-heads nil)
5127 (setq-local org-todo-sets nil)
5128 (setq-local org-todo-log-states nil)
5129 (let ((todo-sequences
5130 (or (nreverse (cdr (assq 'todo alist)))
5131 (let ((d (default-value 'org-todo-keywords)))
5132 (if (not (stringp (car d))) d
5133 ;; XXX: Backward compatibility code.
5134 (list (cons org-todo-interpretation d)))))))
5135 (dolist (sequence todo-sequences)
5136 (let* ((sequence (or (run-hook-with-args-until-success
5137 'org-todo-setup-filter-hook sequence)
5138 sequence))
5139 (sequence-type (car sequence))
5140 (keywords (cdr sequence))
5141 (sep (member "|" keywords))
5142 names alist)
5143 (dolist (k (remove "|" keywords))
5144 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5146 (error "Invalid TODO keyword %s" k))
5147 (let ((name (match-string 1 k))
5148 (key (match-string 2 k))
5149 (log (org-extract-log-state-settings k)))
5150 (push name names)
5151 (push (cons name (and key (string-to-char key))) alist)
5152 (when log (push log org-todo-log-states))))
5153 (let* ((names (nreverse names))
5154 (done (if sep (org-remove-keyword-keys (cdr sep))
5155 (last names)))
5156 (head (car names))
5157 (tail (list sequence-type head (car done) (org-last done))))
5158 (add-to-list 'org-todo-heads head 'append)
5159 (push names org-todo-sets)
5160 (setq org-done-keywords (append org-done-keywords done nil))
5161 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5162 (setq org-todo-key-alist
5163 (append org-todo-key-alist
5164 (and alist
5165 (append '((:startgroup))
5166 (nreverse alist)
5167 '((:endgroup))))))
5168 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5169 (setq org-todo-sets (nreverse org-todo-sets)
5170 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5171 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5172 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5173 ;; Compute the regular expressions and other local variables.
5174 ;; Using `org-outline-regexp-bol' would complicate them much,
5175 ;; because of the fixed white space at the end of that string.
5176 (unless org-done-keywords
5177 (setq org-done-keywords
5178 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5179 (setq org-not-done-keywords
5180 (org-delete-all org-done-keywords
5181 (copy-sequence org-todo-keywords-1))
5182 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5183 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5184 org-not-done-heading-regexp
5185 (format org-heading-keyword-regexp-format org-not-done-regexp)
5186 org-todo-line-regexp
5187 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5188 org-complex-heading-regexp
5189 (concat "^\\(\\*+\\)"
5190 "\\(?: +" org-todo-regexp "\\)?"
5191 "\\(?: +\\(\\[#.\\]\\)\\)?"
5192 "\\(?: +\\(.*?\\)\\)??"
5193 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5194 "[ \t]*$")
5195 org-complex-heading-regexp-format
5196 (concat "^\\(\\*+\\)"
5197 "\\(?: +" org-todo-regexp "\\)?"
5198 "\\(?: +\\(\\[#.\\]\\)\\)?"
5199 "\\(?: +"
5200 ;; Stats cookies can be stuck to body.
5201 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5202 "\\(%s\\)"
5203 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5204 "\\)"
5205 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5206 "[ \t]*$")
5207 org-todo-line-tags-regexp
5208 (concat "^\\(\\*+\\)"
5209 "\\(?: +" org-todo-regexp "\\)?"
5210 "\\(?: +\\(.*?\\)\\)??"
5211 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5212 "[ \t]*$"))
5213 (org-compute-latex-and-related-regexp)))))
5215 (defun org--setup-collect-keywords (regexp &optional files alist)
5216 "Return setup keywords values as an alist.
5218 REGEXP matches a subset of setup keywords. FILES is a list of
5219 file names already visited. It is used to avoid circular setup
5220 files. ALIST, when non-nil, is the alist computed so far.
5222 Return value contains the following keys: `archive', `category',
5223 `columns', `constants', `filetags', `link', `priorities',
5224 `property', `scripts', `startup', `tags' and `todo'."
5225 (org-with-wide-buffer
5226 (goto-char (point-min))
5227 (let ((case-fold-search t))
5228 (while (re-search-forward regexp nil t)
5229 (let ((element (org-element-at-point)))
5230 (when (eq (org-element-type element) 'keyword)
5231 (let ((key (org-element-property :key element))
5232 (value (org-element-property :value element)))
5233 (cond
5234 ((equal key "ARCHIVE")
5235 (when (org-string-nw-p value)
5236 (push (cons 'archive value) alist)))
5237 ((equal key "CATEGORY") (push (cons 'category value) alist))
5238 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5239 ((equal key "CONSTANTS")
5240 (let* ((constants (assq 'constants alist))
5241 (store (cdr constants)))
5242 (dolist (pair (org-split-string value))
5243 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5244 pair)
5245 (let* ((name (match-string 1 pair))
5246 (value (match-string 2 pair))
5247 (old (assoc name store)))
5248 (if old (setcdr old value)
5249 (push (cons name value) store)))))
5250 (if constants (setcdr constants store)
5251 (push (cons 'constants store) alist))))
5252 ((equal key "FILETAGS")
5253 (when (org-string-nw-p value)
5254 (let ((old (assq 'filetags alist))
5255 (new (apply #'nconc
5256 (mapcar (lambda (x) (org-split-string x ":"))
5257 (org-split-string value)))))
5258 (if old (setcdr old (append new (cdr old)))
5259 (push (cons 'filetags new) alist)))))
5260 ((equal key "LINK")
5261 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5262 (let ((links (assq 'link alist))
5263 (pair (cons (match-string-no-properties 1 value)
5264 (match-string-no-properties 2 value))))
5265 (if links (push pair (cdr links))
5266 (push (list 'link pair) alist)))))
5267 ((equal key "OPTIONS")
5268 (when (and (org-string-nw-p value)
5269 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5270 (push (cons 'scripts (read (match-string 1 value))) alist)))
5271 ((equal key "PRIORITIES")
5272 (push (cons 'priorities
5273 (let ((prio (org-split-string value)))
5274 (if (< (length prio) 3) '(?A ?C ?B)
5275 (mapcar #'string-to-char prio))))
5276 alist))
5277 ((equal key "PROPERTY")
5278 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5279 (let* ((property (assq 'property alist))
5280 (value (org--update-property-plist
5281 (match-string-no-properties 1 value)
5282 (match-string-no-properties 2 value)
5283 (cdr property))))
5284 (if property (setcdr property value)
5285 (push (cons 'property value) alist)))))
5286 ((equal key "STARTUP")
5287 (let ((startup (assq 'startup alist)))
5288 (if startup
5289 (setcdr startup
5290 (append (cdr startup) (org-split-string value)))
5291 (push (cons 'startup (org-split-string value)) alist))))
5292 ((equal key "TAGS")
5293 (let ((tag-cell (assq 'tags alist)))
5294 (if tag-cell
5295 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5296 (push (cons 'tags value) alist))))
5297 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5298 (let ((todo (assq 'todo alist))
5299 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5300 (org-split-string value))))
5301 (if todo (push value (cdr todo))
5302 (push (list 'todo value) alist))))
5303 ((equal key "SETUPFILE")
5304 (unless buffer-read-only ; Do not check in Gnus messages.
5305 (let ((f (and (org-string-nw-p value)
5306 (expand-file-name
5307 (org-unbracket-string "\"" "\"" value)))))
5308 (when (and f (file-readable-p f) (not (member f files)))
5309 (with-temp-buffer
5310 (setq default-directory (file-name-directory f))
5311 (insert-file-contents f)
5312 (setq alist
5313 ;; Fake Org mode to benefit from cache
5314 ;; without recurring needlessly.
5315 (let ((major-mode 'org-mode))
5316 (org--setup-collect-keywords
5317 regexp (cons f files) alist)))))))))))))))
5318 alist)
5320 (defun org-tag-string-to-alist (s)
5321 "Return tag alist associated to string S.
5322 S is a value for TAGS keyword or produced with
5323 `org-tag-alist-to-string'. Return value is an alist suitable for
5324 `org-tag-alist' or `org-tag-persistent-alist'."
5325 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5326 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5327 "\\|{.+?}\\)" ; regular expression
5328 "\\(?:(\\(.\\))\\)?\\'"))
5329 alist group-flag)
5330 (dolist (tokens lines (cdr (nreverse alist)))
5331 (push '(:newline) alist)
5332 (while tokens
5333 (let ((token (pop tokens)))
5334 (pcase token
5335 ("{"
5336 (push '(:startgroup) alist)
5337 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5338 ("}"
5339 (push '(:endgroup) alist)
5340 (setq group-flag nil))
5341 ("["
5342 (push '(:startgrouptag) alist)
5343 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5344 ("]"
5345 (push '(:endgrouptag) alist)
5346 (setq group-flag nil))
5347 (":"
5348 (push '(:grouptags) alist))
5349 ((guard (string-match tag-re token))
5350 (let ((tag (match-string 1 token))
5351 (key (and (match-beginning 2)
5352 (string-to-char (match-string 2 token)))))
5353 ;; Push all tags in groups, no matter if they already
5354 ;; appear somewhere else in the list.
5355 (when (or group-flag (not (assoc tag alist)))
5356 (push (cons tag key) alist))))))))))
5358 (defun org-tag-alist-to-string (alist &optional skip-key)
5359 "Return tag string associated to ALIST.
5361 ALIST is an alist, as defined in `org-tag-alist' or
5362 `org-tag-persistent-alist', or produced with
5363 `org-tag-string-to-alist'.
5365 Return value is a string suitable as a value for \"TAGS\"
5366 keyword.
5368 When optional argument SKIP-KEY is non-nil, skip selection keys
5369 next to tags."
5370 (mapconcat (lambda (token)
5371 (pcase token
5372 (`(:startgroup) "{")
5373 (`(:endgroup) "}")
5374 (`(:startgrouptag) "[")
5375 (`(:endgrouptag) "]")
5376 (`(:grouptags) ":")
5377 (`(:newline) "\\n")
5378 ((and
5379 (guard (not skip-key))
5380 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5381 (format "%s(%c)" tag key))
5382 (`(,(and tag (pred stringp)) . ,_) tag)
5383 (_ (user-error "Invalid tag token: %S" token))))
5384 alist
5385 " "))
5387 (defun org-tag-alist-to-groups (alist)
5388 "Return group alist from tag ALIST.
5389 ALIST is an alist, as defined in `org-tag-alist' or
5390 `org-tag-persistent-alist', or produced with
5391 `org-tag-string-to-alist'. Return value is an alist following
5392 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5393 a string, summarizing TAGS, as a list of strings."
5394 (let (groups group-status current-group)
5395 (dolist (token alist (nreverse groups))
5396 (pcase token
5397 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5398 (`(,(or :endgroup :endgrouptag))
5399 (when (eq group-status 'append)
5400 (push (nreverse current-group) groups))
5401 (setq group-status nil))
5402 (`(:grouptags) (setq group-status 'append))
5403 ((and `(,tag . ,_) (guard group-status))
5404 (if (eq group-status 'append) (push tag current-group)
5405 (setq current-group (list tag))))
5406 (_ nil)))))
5408 (defun org-file-contents (file &optional noerror)
5409 "Return the contents of FILE, as a string."
5410 (if (and file (file-readable-p file))
5411 (with-temp-buffer
5412 (insert-file-contents file)
5413 (buffer-string))
5414 (funcall (if noerror 'message 'error)
5415 "Cannot read file \"%s\"%s"
5416 file
5417 (let ((from (buffer-file-name (buffer-base-buffer))))
5418 (if from (concat " (referenced in file \"" from "\")") "")))))
5420 (defun org-extract-log-state-settings (x)
5421 "Extract the log state setting from a TODO keyword string.
5422 This will extract info from a string like \"WAIT(w@/!)\"."
5423 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5424 (let ((kw (match-string 1 x))
5425 (log1 (and (match-end 3) (match-string 3 x)))
5426 (log2 (and (match-end 4) (match-string 4 x))))
5427 (and (or log1 log2)
5428 (list kw
5429 (and log1 (if (equal log1 "!") 'time 'note))
5430 (and log2 (if (equal log2 "!") 'time 'note)))))))
5432 (defun org-remove-keyword-keys (list)
5433 "Remove a pair of parenthesis at the end of each string in LIST."
5434 (mapcar (lambda (x)
5435 (if (string-match "(.*)$" x)
5436 (substring x 0 (match-beginning 0))
5438 list))
5440 (defun org-assign-fast-keys (alist)
5441 "Assign fast keys to a keyword-key alist.
5442 Respect keys that are already there."
5443 (let (new e (alt ?0))
5444 (while (setq e (pop alist))
5445 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5446 (cdr e)) ;; Key already assigned.
5447 (push e new)
5448 (let ((clist (string-to-list (downcase (car e))))
5449 (used (append new alist)))
5450 (when (= (car clist) ?@)
5451 (pop clist))
5452 (while (and clist (rassoc (car clist) used))
5453 (pop clist))
5454 (unless clist
5455 (while (rassoc alt used)
5456 (cl-incf alt)))
5457 (push (cons (car e) (or (car clist) alt)) new))))
5458 (nreverse new)))
5460 ;;; Some variables used in various places
5462 (defvar org-window-configuration nil
5463 "Used in various places to store a window configuration.")
5464 (defvar org-selected-window nil
5465 "Used in various places to store a window configuration.")
5466 (defvar org-finish-function nil
5467 "Function to be called when `C-c C-c' is used.
5468 This is for getting out of special buffers like capture.")
5469 (defvar org-last-state)
5471 ;; Defined somewhere in this file, but used before definition.
5472 (defvar org-entities) ;; defined in org-entities.el
5473 (defvar org-struct-menu)
5474 (defvar org-org-menu)
5475 (defvar org-tbl-menu)
5477 ;;;; Define the Org mode
5479 ;; We use a before-change function to check if a table might need
5480 ;; an update.
5481 (defvar org-table-may-need-update t
5482 "Indicates that a table might need an update.
5483 This variable is set by `org-before-change-function'.
5484 `org-table-align' sets it back to nil.")
5485 (defun org-before-change-function (_beg _end)
5486 "Every change indicates that a table might need an update."
5487 (setq org-table-may-need-update t))
5488 (defvar org-mode-map)
5489 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5490 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5491 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5492 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5493 (defvar org-table-buffer-is-an nil)
5495 (defvar bidi-paragraph-direction)
5496 (defvar buffer-face-mode-face)
5498 (require 'outline)
5500 ;; Other stuff we need.
5501 (require 'time-date)
5502 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5503 (require 'easymenu)
5504 (autoload 'easy-menu-add "easymenu")
5505 (require 'overlay)
5507 ;; (require 'org-macs) moved higher up in the file before it is first used
5508 (require 'org-entities)
5509 ;; (require 'org-compat) moved higher up in the file before it is first used
5510 (require 'org-faces)
5511 (require 'org-list)
5512 (require 'org-pcomplete)
5513 (require 'org-src)
5514 (require 'org-footnote)
5515 (require 'org-macro)
5517 ;; babel
5518 (require 'ob)
5520 ;;;###autoload
5521 (define-derived-mode org-mode outline-mode "Org"
5522 "Outline-based notes management and organizer, alias
5523 \"Carsten's outline-mode for keeping track of everything.\"
5525 Org mode develops organizational tasks around a NOTES file which
5526 contains information about projects as plain text. Org mode is
5527 implemented on top of Outline mode, which is ideal to keep the content
5528 of large files well structured. It supports ToDo items, deadlines and
5529 time stamps, which magically appear in the diary listing of the Emacs
5530 calendar. Tables are easily created with a built-in table editor.
5531 Plain text URL-like links connect to websites, emails (VM), Usenet
5532 messages (Gnus), BBDB entries, and any files related to the project.
5533 For printing and sharing of notes, an Org file (or a part of it)
5534 can be exported as a structured ASCII or HTML file.
5536 The following commands are available:
5538 \\{org-mode-map}"
5540 ;; Get rid of Outline menus, they are not needed
5541 ;; Need to do this here because define-derived-mode sets up
5542 ;; the keymap so late. Still, it is a waste to call this each time
5543 ;; we switch another buffer into Org mode.
5544 (define-key org-mode-map [menu-bar headings] 'undefined)
5545 (define-key org-mode-map [menu-bar hide] 'undefined)
5546 (define-key org-mode-map [menu-bar show] 'undefined)
5548 (org-load-modules-maybe)
5549 (org-install-agenda-files-menu)
5550 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5551 (add-to-invisibility-spec '(org-cwidth))
5552 (add-to-invisibility-spec '(org-hide-block . t))
5553 (setq-local outline-regexp org-outline-regexp)
5554 (setq-local outline-level 'org-outline-level)
5555 (setq bidi-paragraph-direction 'left-to-right)
5556 (when (and org-ellipsis
5557 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5558 (fboundp 'make-glyph-code))
5559 (unless org-display-table
5560 (setq org-display-table (make-display-table)))
5561 (set-display-table-slot
5562 org-display-table 4
5563 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5564 (if (stringp org-ellipsis) org-ellipsis "..."))))
5565 (setq buffer-display-table org-display-table))
5566 (org-set-regexps-and-options)
5567 (org-set-font-lock-defaults)
5568 (when (and org-tag-faces (not org-tags-special-faces-re))
5569 ;; tag faces set outside customize.... force initialization.
5570 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5571 ;; Calc embedded
5572 (setq-local calc-embedded-open-mode "# ")
5573 ;; Modify a few syntax entries
5574 (modify-syntax-entry ?@ "w")
5575 (modify-syntax-entry ?\" "\"")
5576 (modify-syntax-entry ?\\ "_")
5577 (modify-syntax-entry ?~ "_")
5578 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5579 ;; Activate before-change-function
5580 (setq-local org-table-may-need-update t)
5581 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5582 ;; Check for running clock before killing a buffer
5583 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5584 ;; Initialize macros templates.
5585 (org-macro-initialize-templates)
5586 ;; Initialize radio targets.
5587 (org-update-radio-target-regexp)
5588 ;; Indentation.
5589 (setq-local indent-line-function 'org-indent-line)
5590 (setq-local indent-region-function 'org-indent-region)
5591 ;; Filling and auto-filling.
5592 (org-setup-filling)
5593 ;; Comments.
5594 (org-setup-comments-handling)
5595 ;; Initialize cache.
5596 (org-element-cache-reset)
5597 ;; Beginning/end of defun
5598 (setq-local beginning-of-defun-function 'org-backward-element)
5599 (setq-local end-of-defun-function
5600 (lambda ()
5601 (if (not (org-at-heading-p))
5602 (org-forward-element)
5603 (org-forward-element)
5604 (forward-char -1))))
5605 ;; Next error for sparse trees
5606 (setq-local next-error-function 'org-occur-next-match)
5607 ;; Make sure dependence stuff works reliably, even for users who set it
5608 ;; too late :-(
5609 (if org-enforce-todo-dependencies
5610 (add-hook 'org-blocker-hook
5611 'org-block-todo-from-children-or-siblings-or-parent)
5612 (remove-hook 'org-blocker-hook
5613 'org-block-todo-from-children-or-siblings-or-parent))
5614 (if org-enforce-todo-checkbox-dependencies
5615 (add-hook 'org-blocker-hook
5616 'org-block-todo-from-checkboxes)
5617 (remove-hook 'org-blocker-hook
5618 'org-block-todo-from-checkboxes))
5620 ;; Align options lines
5621 (setq-local
5622 align-mode-rules-list
5623 '((org-in-buffer-settings
5624 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5625 (modes . '(org-mode)))))
5627 ;; Imenu
5628 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5630 ;; Make isearch reveal context
5631 (setq-local outline-isearch-open-invisible-function
5632 (lambda (&rest _) (org-show-context 'isearch)))
5634 ;; Setup the pcomplete hooks
5635 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5636 (setq-local pcomplete-command-name-function 'org-command-at-point)
5637 (setq-local pcomplete-default-completion-function 'ignore)
5638 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5639 (setq-local pcomplete-termination-string "")
5640 (setq-local buffer-face-mode-face 'org-default)
5642 ;; If empty file that did not turn on Org mode automatically, make
5643 ;; it to.
5644 (when (and org-insert-mode-line-in-empty-file
5645 (called-interactively-p 'any)
5646 (= (point-min) (point-max)))
5647 (insert "# -*- mode: org -*-\n\n"))
5648 (unless org-inhibit-startup
5649 (org-unmodified
5650 (when org-startup-with-beamer-mode (org-beamer-mode))
5651 (when org-startup-align-all-tables
5652 (org-table-map-tables #'org-table-align t))
5653 (when org-startup-with-inline-images (org-display-inline-images))
5654 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5655 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5656 (when org-startup-truncated (setq truncate-lines t))
5657 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5658 (org-refresh-effort-properties)))
5659 ;; Try to set `org-hide' face correctly.
5660 (let ((foreground (org-find-invisible-foreground)))
5661 (when foreground
5662 (set-face-foreground 'org-hide foreground))))
5664 ;; Update `customize-package-emacs-version-alist'
5665 (add-to-list 'customize-package-emacs-version-alist
5666 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5667 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5668 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5669 ("9.0" . "25.2")))
5671 (defvar org-mode-transpose-word-syntax-table
5672 (let ((st (make-syntax-table text-mode-syntax-table)))
5673 (dolist (c org-emphasis-alist st)
5674 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5676 (when (fboundp 'abbrev-table-put)
5677 (abbrev-table-put org-mode-abbrev-table
5678 :parents (list text-mode-abbrev-table)))
5680 (defun org-find-invisible-foreground ()
5681 (let ((candidates (remove
5682 "unspecified-bg"
5683 (nconc
5684 (list (face-background 'default)
5685 (face-background 'org-default))
5686 (mapcar
5687 (lambda (alist)
5688 (when (boundp alist)
5689 (cdr (assq 'background-color (symbol-value alist)))))
5690 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5691 (list (face-foreground 'org-hide))))))
5692 (car (remove nil candidates))))
5694 (defun org-current-time (&optional rounding-minutes past)
5695 "Current time, possibly rounded to ROUNDING-MINUTES.
5696 When ROUNDING-MINUTES is not an integer, fall back on the car of
5697 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5698 the rounding returns a past time."
5699 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5700 (car org-time-stamp-rounding-minutes)))
5701 (time (decode-time)) res)
5702 (if (< r 1)
5703 (current-time)
5704 (setq res
5705 (apply 'encode-time
5706 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5707 (nthcdr 2 time))))
5708 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5709 (seconds-to-time (- (float-time res) (* r 60)))
5710 res))))
5712 (defun org-today ()
5713 "Return today date, considering `org-extend-today-until'."
5714 (time-to-days
5715 (time-subtract (current-time)
5716 (list 0 (* 3600 org-extend-today-until) 0))))
5718 ;;;; Font-Lock stuff, including the activators
5720 (defvar org-mouse-map (make-sparse-keymap))
5721 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5722 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5723 (when org-mouse-1-follows-link
5724 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5725 (when org-tab-follows-link
5726 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5727 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5729 (require 'font-lock)
5731 (defconst org-non-link-chars "]\t\n\r<>")
5732 (defvar org-link-types-re nil
5733 "Matches a link that has a url-like prefix like \"http:\"")
5734 (defvar org-link-re-with-space nil
5735 "Matches a link with spaces, optional angular brackets around it.")
5736 (defvar org-link-re-with-space2 nil
5737 "Matches a link with spaces, optional angular brackets around it.")
5738 (defvar org-link-re-with-space3 nil
5739 "Matches a link with spaces, only for internal part in bracket links.")
5740 (defvar org-angle-link-re nil
5741 "Matches link with angular brackets, spaces are allowed.")
5742 (defvar org-plain-link-re nil
5743 "Matches plain link, without spaces.")
5744 (defvar org-bracket-link-regexp nil
5745 "Matches a link in double brackets.")
5746 (defvar org-bracket-link-analytic-regexp nil
5747 "Regular expression used to analyze links.
5748 Here is what the match groups contain after a match:
5749 1: http:
5750 2: http
5751 3: path
5752 4: [desc]
5753 5: desc")
5754 (defvar org-bracket-link-analytic-regexp++ nil
5755 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5756 (defvar org-any-link-re nil
5757 "Regular expression matching any link.")
5759 (defconst org-match-sexp-depth 3
5760 "Number of stacked braces for sub/superscript matching.")
5762 (defun org-create-multibrace-regexp (left right n)
5763 "Create a regular expression which will match a balanced sexp.
5764 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5765 as single character strings.
5766 The regexp returned will match the entire expression including the
5767 delimiters. It will also define a single group which contains the
5768 match except for the outermost delimiters. The maximum depth of
5769 stacked delimiters is N. Escaping delimiters is not possible."
5770 (let* ((nothing (concat "[^" left right "]*?"))
5771 (or "\\|")
5772 (re nothing)
5773 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5774 (while (> n 1)
5775 (setq n (1- n)
5776 re (concat re or next)
5777 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5778 (concat left "\\(" re "\\)" right)))
5780 (defconst org-match-substring-regexp
5781 (concat
5782 "\\(\\S-\\)\\([_^]\\)\\("
5783 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5784 "\\|"
5785 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5786 "\\|"
5787 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5788 "The regular expression matching a sub- or superscript.")
5790 (defconst org-match-substring-with-braces-regexp
5791 (concat
5792 "\\(\\S-\\)\\([_^]\\)"
5793 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5794 "The regular expression matching a sub- or superscript, forcing braces.")
5796 (defun org-make-link-regexps ()
5797 "Update the link regular expressions.
5798 This should be called after the variable `org-link-parameters' has changed."
5799 (let ((types-re (regexp-opt (org-link-types) t)))
5800 (setq org-link-types-re
5801 (concat "\\`" types-re ":")
5802 org-link-re-with-space
5803 (concat "<?" types-re ":"
5804 "\\([^" org-non-link-chars " ]"
5805 "[^" org-non-link-chars "]*"
5806 "[^" org-non-link-chars " ]\\)>?")
5807 org-link-re-with-space2
5808 (concat "<?" types-re ":"
5809 "\\([^" org-non-link-chars " ]"
5810 "[^\t\n\r]*"
5811 "[^" org-non-link-chars " ]\\)>?")
5812 org-link-re-with-space3
5813 (concat "<?" types-re ":"
5814 "\\([^" org-non-link-chars " ]"
5815 "[^\t\n\r]*\\)")
5816 org-angle-link-re
5817 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5818 types-re)
5819 org-plain-link-re
5820 (concat
5821 "\\<" types-re ":"
5822 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5823 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5824 org-bracket-link-regexp
5825 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5826 org-bracket-link-analytic-regexp
5827 (concat
5828 "\\[\\["
5829 "\\(" types-re ":\\)?"
5830 "\\([^]]+\\)"
5831 "\\]"
5832 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5833 "\\]")
5834 org-bracket-link-analytic-regexp++
5835 (concat
5836 "\\[\\["
5837 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5838 "\\([^]]+\\)"
5839 "\\]"
5840 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5841 "\\]")
5842 org-any-link-re
5843 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5844 org-angle-link-re "\\)\\|\\("
5845 org-plain-link-re "\\)"))))
5847 (org-make-link-regexps)
5849 (defvar org-emph-face nil)
5851 (defun org-do-emphasis-faces (limit)
5852 "Run through the buffer and emphasize strings."
5853 (let (rtn a)
5854 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5855 (let* ((border (char-after (match-beginning 3)))
5856 (bre (regexp-quote (char-to-string border))))
5857 (when (and (not (= border (char-after (match-beginning 4))))
5858 (not (string-match-p (concat bre ".*" bre)
5859 (replace-regexp-in-string
5860 "\n" " "
5861 (substring (match-string 2) 1 -1)))))
5862 (setq rtn t)
5863 (setq a (assoc (match-string 3) org-emphasis-alist))
5864 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5865 'face
5866 (nth 1 a))
5867 (and (nth 2 a)
5868 (org-remove-flyspell-overlays-in
5869 (match-beginning 0) (match-end 0)))
5870 (add-text-properties (match-beginning 2) (match-end 2)
5871 '(font-lock-multiline t org-emphasis t))
5872 (when org-hide-emphasis-markers
5873 (add-text-properties (match-end 4) (match-beginning 5)
5874 '(invisible org-link))
5875 (add-text-properties (match-beginning 3) (match-end 3)
5876 '(invisible org-link)))))
5877 (goto-char (1+ (match-beginning 0))))
5878 rtn))
5880 (defun org-emphasize (&optional char)
5881 "Insert or change an emphasis, i.e. a font like bold or italic.
5882 If there is an active region, change that region to a new emphasis.
5883 If there is no region, just insert the marker characters and position
5884 the cursor between them.
5885 CHAR should be the marker character. If it is a space, it means to
5886 remove the emphasis of the selected region.
5887 If CHAR is not given (for example in an interactive call) it will be
5888 prompted for."
5889 (interactive)
5890 (let ((erc org-emphasis-regexp-components)
5891 (string "") beg end move s)
5892 (if (org-region-active-p)
5893 (setq beg (region-beginning)
5894 end (region-end)
5895 string (buffer-substring beg end))
5896 (setq move t))
5898 (unless char
5899 (message "Emphasis marker or tag: [%s]"
5900 (mapconcat #'car org-emphasis-alist ""))
5901 (setq char (read-char-exclusive)))
5902 (if (equal char ?\s)
5903 (setq s ""
5904 move nil)
5905 (unless (assoc (char-to-string char) org-emphasis-alist)
5906 (user-error "No such emphasis marker: \"%c\"" char))
5907 (setq s (char-to-string char)))
5908 (while (and (> (length string) 1)
5909 (equal (substring string 0 1) (substring string -1))
5910 (assoc (substring string 0 1) org-emphasis-alist))
5911 (setq string (substring string 1 -1)))
5912 (setq string (concat s string s))
5913 (when beg (delete-region beg end))
5914 (unless (or (bolp)
5915 (string-match (concat "[" (nth 0 erc) "\n]")
5916 (char-to-string (char-before (point)))))
5917 (insert " "))
5918 (unless (or (eobp)
5919 (string-match (concat "[" (nth 1 erc) "\n]")
5920 (char-to-string (char-after (point)))))
5921 (insert " ") (backward-char 1))
5922 (insert string)
5923 (and move (backward-char 1))))
5925 (defconst org-nonsticky-props
5926 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5928 (defsubst org-rear-nonsticky-at (pos)
5929 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5931 (defun org-activate-plain-links (limit)
5932 "Add link properties for plain links."
5933 (when (and (re-search-forward org-plain-link-re limit t)
5934 (not (org-in-src-block-p)))
5936 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5937 'face))
5938 (link (match-string-no-properties 0))
5939 (type (match-string-no-properties 1))
5940 (path (match-string-no-properties 2))
5941 (link-start (match-beginning 0))
5942 (link-end (match-end 0))
5943 (link-face (org-link-get-parameter type :face))
5944 (help-echo (org-link-get-parameter type :help-echo))
5945 (htmlize-link (org-link-get-parameter type :htmlize-link))
5946 (activate-func (org-link-get-parameter type :activate-func)))
5947 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5948 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5949 (add-text-properties (match-beginning 0) (match-end 0)
5950 (list
5951 'mouse-face (or (org-link-get-parameter type :mouse-face)
5952 'highlight)
5953 'face (cond
5954 ;; A function that returns a face
5955 ((functionp link-face)
5956 (funcall link-face path))
5957 ;; a face
5958 ((facep link-face)
5959 link-face)
5960 ;; An anonymous face
5961 ((consp link-face)
5962 link-face)
5963 ;; default
5965 'org-link))
5966 'help-echo (cond
5967 ((stringp help-echo)
5968 help-echo)
5969 ((functionp help-echo)
5970 help-echo)
5972 (concat "LINK: "
5973 (save-match-data
5974 (org-link-unescape link)))))
5975 'htmlize-link (cond
5976 ((functionp htmlize-link)
5977 (funcall htmlize-link path))
5979 `(:uri ,link)))
5980 'keymap (or (org-link-get-parameter type :keymap)
5981 org-mouse-map)
5982 'org-link-start (match-beginning 0)))
5983 (org-rear-nonsticky-at (match-end 0))
5984 (when activate-func
5985 (funcall activate-func link-start link-end path nil))
5986 t))))
5988 (defun org-activate-code (limit)
5989 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5990 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5991 (remove-text-properties (match-beginning 0) (match-end 0)
5992 '(display t invisible t intangible t))
5995 (defcustom org-src-fontify-natively t
5996 "When non-nil, fontify code in code blocks.
5997 See also the `org-block' face."
5998 :type 'boolean
5999 :version "24.4"
6000 :package-version '(Org . "8.3")
6001 :group 'org-appearance
6002 :group 'org-babel)
6004 (defcustom org-allow-promoting-top-level-subtree nil
6005 "When non-nil, allow promoting a top level subtree.
6006 The leading star of the top level headline will be replaced
6007 by a #."
6008 :type 'boolean
6009 :version "24.1"
6010 :group 'org-appearance)
6012 (defun org-fontify-meta-lines-and-blocks (limit)
6013 (condition-case nil
6014 (org-fontify-meta-lines-and-blocks-1 limit)
6015 (error (message "org-mode fontification error in %S at %d"
6016 (current-buffer)
6017 (line-number-at-pos)))))
6019 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6020 "Fontify #+ lines and blocks."
6021 (let ((case-fold-search t))
6022 (when (re-search-forward
6023 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6024 limit t)
6025 (let ((beg (match-beginning 0))
6026 (block-start (match-end 0))
6027 (block-end nil)
6028 (lang (match-string 7))
6029 (beg1 (line-beginning-position 2))
6030 (dc1 (downcase (match-string 2)))
6031 (dc3 (downcase (match-string 3)))
6032 end end1 quoting block-type)
6033 (cond
6034 ((and (match-end 4) (equal dc3 "+begin"))
6035 ;; Truly a block
6036 (setq block-type (downcase (match-string 5))
6037 quoting (member block-type org-protecting-blocks))
6038 (when (re-search-forward
6039 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6040 nil t) ;; on purpose, we look further than LIMIT
6041 (setq end (min (point-max) (match-end 0))
6042 end1 (min (point-max) (1- (match-beginning 0))))
6043 (setq block-end (match-beginning 0))
6044 (when quoting
6045 (org-remove-flyspell-overlays-in beg1 end1)
6046 (remove-text-properties beg end
6047 '(display t invisible t intangible t)))
6048 (add-text-properties
6049 beg end '(font-lock-fontified t font-lock-multiline t))
6050 (add-text-properties beg beg1 '(face org-meta-line))
6051 (org-remove-flyspell-overlays-in beg beg1)
6052 (add-text-properties ; For end_src
6053 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6054 (org-remove-flyspell-overlays-in end1 end)
6055 (cond
6056 ((and lang (not (string= lang "")) org-src-fontify-natively)
6057 (org-src-font-lock-fontify-block lang block-start block-end)
6058 (add-text-properties beg1 block-end '(src-block t)))
6059 (quoting
6060 (add-text-properties beg1 (min (point-max) (1+ end1))
6061 (list 'face
6062 (list :inherit
6063 (let ((face-name
6064 (intern (format "org-block-%s" lang))))
6065 (append (and (facep face-name) (list face-name))
6066 '(org-block))))))) ; end of source block
6067 ((not org-fontify-quote-and-verse-blocks))
6068 ((string= block-type "quote")
6069 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
6070 ((string= block-type "verse")
6071 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
6072 (add-text-properties beg beg1 '(face org-block-begin-line))
6073 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6074 '(face org-block-end-line))
6076 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6077 (org-remove-flyspell-overlays-in
6078 (match-beginning 0)
6079 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6080 (add-text-properties
6081 beg (match-end 3)
6082 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6083 '(font-lock-fontified t invisible t)
6084 '(font-lock-fontified t face org-document-info-keyword)))
6085 (add-text-properties
6086 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6087 (if (string-equal dc1 "+title:")
6088 '(font-lock-fontified t face org-document-title)
6089 '(font-lock-fontified t face org-document-info))))
6090 ((equal dc1 "+caption:")
6091 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6092 (remove-text-properties (match-beginning 0) (match-end 0)
6093 '(display t invisible t intangible t))
6094 (add-text-properties (match-beginning 1) (match-end 3)
6095 '(font-lock-fontified t face org-meta-line))
6096 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
6097 '(font-lock-fontified t face org-block))
6099 ((member dc3 '(" " ""))
6100 (org-remove-flyspell-overlays-in beg (match-end 0))
6101 (add-text-properties
6102 beg (match-end 0)
6103 '(font-lock-fontified t face font-lock-comment-face)))
6104 (t ;; just any other in-buffer setting, but not indented
6105 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6106 (remove-text-properties (match-beginning 0) (match-end 0)
6107 '(display t invisible t intangible t))
6108 (add-text-properties beg (match-end 0)
6109 '(font-lock-fontified t face org-meta-line))
6110 t))))))
6112 (defun org-fontify-drawers (limit)
6113 "Fontify drawers."
6114 (when (re-search-forward org-drawer-regexp limit t)
6115 (add-text-properties
6116 (match-beginning 0) (match-end 0)
6117 '(font-lock-fontified t face org-special-keyword))
6118 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6121 (defun org-fontify-macros (limit)
6122 "Fontify macros."
6123 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6124 (add-text-properties
6125 (match-beginning 0) (match-end 0)
6126 '(font-lock-fontified t face org-macro))
6127 (when org-hide-macro-markers
6128 (add-text-properties (match-end 2) (match-beginning 2)
6129 '(invisible t))
6130 (add-text-properties (match-beginning 1) (match-end 1)
6131 '(invisible t)))
6132 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6135 (defun org-activate-angle-links (limit)
6136 "Add text properties for angle links."
6137 (when (and (re-search-forward org-angle-link-re limit t)
6138 (not (org-in-src-block-p)))
6139 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6140 (add-text-properties (match-beginning 0) (match-end 0)
6141 (list 'mouse-face 'highlight
6142 'keymap org-mouse-map
6143 'font-lock-multiline t))
6144 (org-rear-nonsticky-at (match-end 0))
6147 (defun org-activate-footnote-links (limit)
6148 "Add text properties for footnotes."
6149 (let ((fn (org-footnote-next-reference-or-definition limit)))
6150 (when fn
6151 (let* ((beg (nth 1 fn))
6152 (end (nth 2 fn))
6153 (label (car fn))
6154 (referencep (/= (line-beginning-position) beg)))
6155 (when (and referencep (nth 3 fn))
6156 (save-excursion
6157 (goto-char beg)
6158 (search-forward (or label "fn:"))
6159 (org-remove-flyspell-overlays-in beg (match-end 0))))
6160 (add-text-properties beg end
6161 (list 'mouse-face 'highlight
6162 'keymap org-mouse-map
6163 'help-echo
6164 (if referencep "Footnote reference"
6165 "Footnote definition")
6166 'font-lock-fontified t
6167 'font-lock-multiline t
6168 'face 'org-footnote))))))
6170 (defun org-activate-bracket-links (limit)
6171 "Add text properties for bracketed links."
6172 (when (and (re-search-forward org-bracket-link-regexp limit t)
6173 (not (org-in-src-block-p)))
6174 (let* ((hl (save-match-data
6175 (org-link-expand-abbrev (match-string-no-properties 1))))
6176 (type (save-match-data
6177 (and (string-match org-plain-link-re hl)
6178 (match-string-no-properties 1 hl))))
6179 (path (save-match-data
6180 (and (string-match org-plain-link-re hl)
6181 (match-string-no-properties 2 hl))))
6182 (link-start (match-beginning 0))
6183 (link-end (match-end 0))
6184 (bracketp t)
6185 (help-echo (org-link-get-parameter type :help-echo))
6186 (help (cond
6187 ((stringp help-echo)
6188 help-echo)
6189 ((functionp help-echo)
6190 help-echo)
6192 (concat "LINK: "
6193 (save-match-data
6194 (org-link-unescape hl))))))
6195 (link-face (org-link-get-parameter type :face))
6196 (face (cond
6197 ;; A function that returns a face
6198 ((functionp link-face)
6199 (funcall link-face path))
6200 ;; a face
6201 ((facep link-face)
6202 link-face)
6203 ;; An anonymous face
6204 ((consp link-face)
6205 link-face)
6206 ;; default
6208 'org-link)))
6209 (keymap (or (org-link-get-parameter type :keymap)
6210 org-mouse-map))
6211 (mouse-face (or (org-link-get-parameter type :mouse-face)
6212 'highlight))
6213 (htmlize (org-link-get-parameter type :htmlize-link))
6214 (htmlize-link (cond
6215 ((functionp htmlize)
6216 (funcall htmlize))
6218 `(:uri ,(format "%s:%s" type path)))))
6219 (activate-func (org-link-get-parameter type :activate-func))
6220 ;; invisible part
6221 (ip (list 'invisible (or
6222 (org-link-get-parameter type :display)
6223 'org-link)
6224 'face face
6225 'keymap keymap
6226 'mouse-face mouse-face
6227 'font-lock-multiline t
6228 'help-echo help
6229 'htmlize-link htmlize-link))
6230 ;; visible part
6231 (vp (list 'keymap keymap
6232 'face face
6233 'mouse-face mouse-face
6234 'font-lock-multiline t
6235 'help-echo help
6236 'htmlize-link htmlize-link)))
6237 ;; We need to remove the invisible property here. Table narrowing
6238 ;; may have made some of this invisible.
6239 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6240 (remove-text-properties (match-beginning 0) (match-end 0)
6241 '(invisible nil))
6242 (if (match-end 3)
6243 (progn
6244 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6245 (org-rear-nonsticky-at (match-beginning 3))
6246 (add-text-properties (match-beginning 3) (match-end 3) vp)
6247 (org-rear-nonsticky-at (match-end 3))
6248 (add-text-properties (match-end 3) (match-end 0) ip)
6249 (org-rear-nonsticky-at (match-end 0)))
6250 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6251 (org-rear-nonsticky-at (match-beginning 1))
6252 (add-text-properties (match-beginning 1) (match-end 1) vp)
6253 (org-rear-nonsticky-at (match-end 1))
6254 (add-text-properties (match-end 1) (match-end 0) ip)
6255 (org-rear-nonsticky-at (match-end 0)))
6256 (when activate-func
6257 (funcall activate-func link-start link-end path bracketp))
6258 t)))
6260 (defun org-activate-dates (limit)
6261 "Add text properties for dates."
6262 (when (and (re-search-forward org-tsr-regexp-both limit t)
6263 (not (equal (char-before (match-beginning 0)) 91)))
6264 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6265 (add-text-properties (match-beginning 0) (match-end 0)
6266 (list 'mouse-face 'highlight
6267 'keymap org-mouse-map))
6268 (org-rear-nonsticky-at (match-end 0))
6269 (when org-display-custom-times
6270 (if (match-end 3)
6271 (org-display-custom-time (match-beginning 3) (match-end 3))
6272 (org-display-custom-time (match-beginning 1) (match-end 1))))
6275 (defvar-local org-target-link-regexp nil
6276 "Regular expression matching radio targets in plain text.")
6278 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6279 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6280 border border border))
6281 "Regular expression matching a link target.")
6283 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6284 "Regular expression matching a radio target.")
6286 (defconst org-any-target-regexp
6287 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6288 "Regular expression matching any target.")
6290 (defun org-activate-target-links (limit)
6291 "Add text properties for target matches."
6292 (when org-target-link-regexp
6293 (let ((case-fold-search t))
6294 (when (re-search-forward org-target-link-regexp limit t)
6295 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6296 (add-text-properties (match-beginning 1) (match-end 1)
6297 (list 'mouse-face 'highlight
6298 'keymap org-mouse-map
6299 'help-echo "Radio target link"
6300 'org-linked-text t))
6301 (org-rear-nonsticky-at (match-end 1))
6302 t))))
6304 (defun org-update-radio-target-regexp ()
6305 "Find all radio targets in this file and update the regular expression.
6306 Also refresh fontification if needed."
6307 (interactive)
6308 (let ((old-regexp org-target-link-regexp)
6309 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6310 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6311 (targets
6312 (org-with-wide-buffer
6313 (goto-char (point-min))
6314 (let (rtn)
6315 (while (re-search-forward org-radio-target-regexp nil t)
6316 ;; Make sure point is really within the object.
6317 (backward-char)
6318 (let ((obj (org-element-context)))
6319 (when (eq (org-element-type obj) 'radio-target)
6320 (cl-pushnew (org-element-property :value obj) rtn
6321 :test #'equal))))
6322 rtn))))
6323 (setq org-target-link-regexp
6324 (and targets
6325 (concat before-re
6326 (mapconcat
6327 (lambda (x)
6328 (replace-regexp-in-string
6329 " +" "\\s-+" (regexp-quote x) t t))
6330 targets
6331 "\\|")
6332 after-re)))
6333 (unless (equal old-regexp org-target-link-regexp)
6334 ;; Clean-up cache.
6335 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6336 ((not org-target-link-regexp) old-regexp)
6338 (concat before-re
6339 (mapconcat
6340 (lambda (re)
6341 (substring re (length before-re)
6342 (- (length after-re))))
6343 (list old-regexp org-target-link-regexp)
6344 "\\|")
6345 after-re)))))
6346 (org-with-wide-buffer
6347 (goto-char (point-min))
6348 (while (re-search-forward regexp nil t)
6349 (org-element-cache-refresh (match-beginning 1)))))
6350 ;; Re fontify buffer.
6351 (when (memq 'radio org-highlight-links)
6352 (org-restart-font-lock)))))
6354 (defun org-hide-wide-columns (limit)
6355 (let (s e)
6356 (setq s (text-property-any (point) (or limit (point-max))
6357 'org-cwidth t))
6358 (when s
6359 (setq e (next-single-property-change s 'org-cwidth))
6360 (add-text-properties s e '(invisible org-cwidth))
6361 (goto-char e)
6362 t)))
6364 (defvar org-latex-and-related-regexp nil
6365 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6367 (defun org-compute-latex-and-related-regexp ()
6368 "Compute regular expression for LaTeX, entities and sub/superscript.
6369 Result depends on variable `org-highlight-latex-and-related'."
6370 (setq-local
6371 org-latex-and-related-regexp
6372 (let* ((re-sub
6373 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6374 ((eq org-use-sub-superscripts '{})
6375 (list org-match-substring-with-braces-regexp))
6376 (org-use-sub-superscripts (list org-match-substring-regexp))))
6377 (re-latex
6378 (when (memq 'latex org-highlight-latex-and-related)
6379 (let ((matchers (plist-get org-format-latex-options :matchers)))
6380 (delq nil
6381 (mapcar (lambda (x)
6382 (and (member (car x) matchers) (nth 1 x)))
6383 org-latex-regexps)))))
6384 (re-entities
6385 (when (memq 'entities org-highlight-latex-and-related)
6386 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6387 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6389 (defun org-do-latex-and-related (limit)
6390 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6391 LIMIT bounds the search for syntax to highlight. Stop at first
6392 highlighted object, if any. Return t if some highlighting was
6393 done, nil otherwise."
6394 (when (org-string-nw-p org-latex-and-related-regexp)
6395 (catch 'found
6396 (while (re-search-forward org-latex-and-related-regexp limit t)
6397 (unless
6398 (cl-some
6399 (lambda (f)
6400 (memq f '(org-code org-verbatim underline org-special-keyword)))
6401 (save-excursion
6402 (goto-char (1+ (match-beginning 0)))
6403 (face-at-point nil t)))
6404 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6405 '(?_ ?^))
6407 0)))
6408 (font-lock-prepend-text-property
6409 (+ offset (match-beginning 0)) (match-end 0)
6410 'face 'org-latex-and-related)
6411 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6412 '(font-lock-multiline t)))
6413 (throw 'found t)))
6414 nil)))
6416 (defun org-restart-font-lock ()
6417 "Restart `font-lock-mode', to force refontification."
6418 (when (and (boundp 'font-lock-mode) font-lock-mode)
6419 (font-lock-mode -1)
6420 (font-lock-mode 1)))
6422 (defun org-activate-tags (limit)
6423 (when (re-search-forward
6424 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6425 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6426 (add-text-properties (match-beginning 1) (match-end 1)
6427 (list 'mouse-face 'highlight
6428 'keymap org-mouse-map))
6429 (org-rear-nonsticky-at (match-end 1))
6432 (defun org-outline-level ()
6433 "Compute the outline level of the heading at point.
6435 If this is called at a normal headline, the level is the number
6436 of stars. Use `org-reduced-level' to remove the effect of
6437 `org-odd-levels'. Unlike to `org-current-level', this function
6438 takes into consideration inlinetasks."
6439 (org-with-wide-buffer
6440 (end-of-line)
6441 (if (re-search-backward org-outline-regexp-bol nil t)
6442 (1- (- (match-end 0) (match-beginning 0)))
6443 0)))
6445 (defvar org-font-lock-keywords nil)
6447 (defsubst org-re-property (property &optional literal allow-null value)
6448 "Return a regexp matching a PROPERTY line.
6450 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6451 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6452 non-nil, match properties even without a value.
6454 Match group 3 is set to the value when it exists. If there is no
6455 value and ALLOW-NULL is non-nil, it is set to the empty string.
6457 With optional argument VALUE, match only property lines with
6458 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6459 unless LITERAL is non-nil."
6460 (concat
6461 "^\\(?4:[ \t]*\\)"
6462 (format "\\(?1::\\(?2:%s\\):\\)"
6463 (if literal property (regexp-quote property)))
6464 (cond (value
6465 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6466 (if literal value (regexp-quote value))))
6467 (allow-null
6468 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6470 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6472 (defconst org-property-re
6473 (org-re-property "\\S-+" 'literal t)
6474 "Regular expression matching a property line.
6475 There are four matching groups:
6476 1: :PROPKEY: including the leading and trailing colon,
6477 2: PROPKEY without the leading and trailing colon,
6478 3: PROPVAL without leading or trailing spaces,
6479 4: the indentation of the current line,
6480 5: trailing whitespace.")
6482 (defvar org-font-lock-hook nil
6483 "Functions to be called for special font lock stuff.")
6485 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6487 (defvar org-font-lock-set-keywords-hook nil
6488 "Functions that can manipulate `org-font-lock-extra-keywords'.
6489 This is called after `org-font-lock-extra-keywords' is defined, but before
6490 it is installed to be used by font lock. This can be useful if something
6491 needs to be inserted at a specific position in the font-lock sequence.")
6493 (defun org-font-lock-hook (limit)
6494 "Run `org-font-lock-hook' within LIMIT."
6495 (run-hook-with-args 'org-font-lock-hook limit))
6497 (defun org-set-font-lock-defaults ()
6498 "Set font lock defaults for the current buffer."
6499 (let* ((em org-fontify-emphasized-text)
6500 (lk org-highlight-links)
6501 (org-font-lock-extra-keywords
6502 (list
6503 ;; Call the hook
6504 '(org-font-lock-hook)
6505 ;; Headlines
6506 `(,(if org-fontify-whole-heading-line
6507 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6508 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6509 (1 (org-get-level-face 1))
6510 (2 (org-get-level-face 2))
6511 (3 (org-get-level-face 3)))
6512 ;; Table lines
6513 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6514 (1 'org-table t))
6515 ;; Table internals
6516 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6517 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6518 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6519 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6520 ;; Drawers
6521 '(org-fontify-drawers)
6522 ;; Properties
6523 (list org-property-re
6524 '(1 'org-special-keyword t)
6525 '(3 'org-property-value t))
6526 ;; Links
6527 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6528 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6529 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6530 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6531 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6532 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6533 (when (memq 'footnote lk) '(org-activate-footnote-links))
6534 ;; Targets.
6535 (list org-any-target-regexp '(0 'org-target t))
6536 ;; Diary sexps.
6537 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6538 ;; Macro
6539 '(org-fontify-macros)
6540 '(org-hide-wide-columns (0 nil append))
6541 ;; TODO keyword
6542 (list (format org-heading-keyword-regexp-format
6543 org-todo-regexp)
6544 '(2 (org-get-todo-face 2) t))
6545 ;; DONE
6546 (if org-fontify-done-headline
6547 (list (format org-heading-keyword-regexp-format
6548 (concat
6549 "\\(?:"
6550 (mapconcat 'regexp-quote org-done-keywords "\\|")
6551 "\\)"))
6552 '(2 'org-headline-done t))
6553 nil)
6554 ;; Priorities
6555 '(org-font-lock-add-priority-faces)
6556 ;; Tags
6557 '(org-font-lock-add-tag-faces)
6558 ;; Tags groups
6559 (when (and org-group-tags org-tag-groups-alist)
6560 (list (concat org-outline-regexp-bol ".+\\(:"
6561 (regexp-opt (mapcar 'car org-tag-groups-alist))
6562 ":\\).*$")
6563 '(1 'org-tag-group prepend)))
6564 ;; Special keywords
6565 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6566 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6567 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6568 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6569 ;; Emphasis
6570 (when em '(org-do-emphasis-faces))
6571 ;; Checkboxes
6572 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6573 1 'org-checkbox prepend)
6574 (when (cdr (assq 'checkbox org-list-automatic-rules))
6575 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6576 (0 (org-get-checkbox-statistics-face) t)))
6577 ;; Description list items
6578 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6579 1 'org-list-dt prepend)
6580 ;; ARCHIVEd headings
6581 (list (concat
6582 org-outline-regexp-bol
6583 "\\(.*:" org-archive-tag ":.*\\)")
6584 '(1 'org-archived prepend))
6585 ;; Specials
6586 '(org-do-latex-and-related)
6587 '(org-fontify-entities)
6588 '(org-raise-scripts)
6589 ;; Code
6590 '(org-activate-code (1 'org-code t))
6591 ;; COMMENT
6592 (list (format
6593 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6594 org-todo-regexp
6595 org-comment-string)
6596 '(9 'org-special-keyword t))
6597 ;; Blocks and meta lines
6598 '(org-fontify-meta-lines-and-blocks))))
6599 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6600 (run-hooks 'org-font-lock-set-keywords-hook)
6601 ;; Now set the full font-lock-keywords
6602 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6603 (setq-local font-lock-defaults
6604 '(org-font-lock-keywords t nil nil backward-paragraph))
6605 (kill-local-variable 'font-lock-keywords)
6606 nil))
6608 (defun org-toggle-pretty-entities ()
6609 "Toggle the composition display of entities as UTF8 characters."
6610 (interactive)
6611 (setq-local org-pretty-entities (not org-pretty-entities))
6612 (org-restart-font-lock)
6613 (if org-pretty-entities
6614 (message "Entities are now displayed as UTF8 characters")
6615 (save-restriction
6616 (widen)
6617 (decompose-region (point-min) (point-max))
6618 (message "Entities are now displayed as plain text"))))
6620 (defvar-local org-custom-properties-overlays nil
6621 "List of overlays used for custom properties.")
6623 (defun org-toggle-custom-properties-visibility ()
6624 "Display or hide properties in `org-custom-properties'."
6625 (interactive)
6626 (if org-custom-properties-overlays
6627 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6628 (setq org-custom-properties-overlays nil))
6629 (when org-custom-properties
6630 (org-with-wide-buffer
6631 (goto-char (point-min))
6632 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6633 (while (re-search-forward regexp nil t)
6634 (let ((end (cdr (save-match-data (org-get-property-block)))))
6635 (when (and end (< (point) end))
6636 ;; Hide first custom property in current drawer.
6637 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6638 (overlay-put o 'invisible t)
6639 (overlay-put o 'org-custom-property t)
6640 (push o org-custom-properties-overlays))
6641 ;; Hide additional custom properties in the same drawer.
6642 (while (re-search-forward regexp end t)
6643 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6644 (overlay-put o 'invisible t)
6645 (overlay-put o 'org-custom-property t)
6646 (push o org-custom-properties-overlays)))))
6647 ;; Each entry is limited to a single property drawer.
6648 (outline-next-heading)))))))
6650 (defun org-fontify-entities (limit)
6651 "Find an entity to fontify."
6652 (let (ee)
6653 (when org-pretty-entities
6654 (catch 'match
6655 ;; "\_ "-family is left out on purpose. Only the first one,
6656 ;; i.e., "\_ ", could be fontified anyway, and it would be
6657 ;; confusing when adding a second white space character.
6658 (while (re-search-forward
6659 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6660 limit t)
6661 (when (and (not (org-at-comment-p))
6662 (setq ee (org-entity-get (match-string 1)))
6663 (= (length (nth 6 ee)) 1))
6664 (let* ((end (if (equal (match-string 2) "{}")
6665 (match-end 2)
6666 (match-end 1))))
6667 (add-text-properties
6668 (match-beginning 0) end
6669 (list 'font-lock-fontified t))
6670 (compose-region (match-beginning 0) end
6671 (nth 6 ee) nil)
6672 (backward-char 1)
6673 (throw 'match t))))
6674 nil))))
6676 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6677 "Fontify string S like in Org mode."
6678 (with-temp-buffer
6679 (insert s)
6680 (let ((org-odd-levels-only odd-levels))
6681 (org-mode)
6682 (org-font-lock-ensure)
6683 (buffer-string))))
6685 (defvar org-m nil)
6686 (defvar org-l nil)
6687 (defvar org-f nil)
6688 (defun org-get-level-face (n)
6689 "Get the right face for match N in font-lock matching of headlines."
6690 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6691 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6692 (if org-cycle-level-faces
6693 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6694 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6695 (cond
6696 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6697 ((eq n 2) org-f)
6698 (t (unless org-level-color-stars-only org-f))))
6700 (defun org-face-from-face-or-color (context inherit face-or-color)
6701 "Create a face list that inherits INHERIT, but sets the foreground color.
6702 When FACE-OR-COLOR is not a string, just return it."
6703 (if (stringp face-or-color)
6704 (list :inherit inherit
6705 (cdr (assoc context org-faces-easy-properties))
6706 face-or-color)
6707 face-or-color))
6709 (defun org-get-todo-face (kwd)
6710 "Get the right face for a TODO keyword KWD.
6711 If KWD is a number, get the corresponding match group."
6712 (when (numberp kwd) (setq kwd (match-string kwd)))
6713 (or (org-face-from-face-or-color
6714 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6715 (and (member kwd org-done-keywords) 'org-done)
6716 'org-todo))
6718 (defun org-get-priority-face (priority)
6719 "Get the right face for PRIORITY.
6720 PRIORITY is a character."
6721 (or (org-face-from-face-or-color
6722 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6723 'org-priority))
6725 (defun org-get-tag-face (tag)
6726 "Get the right face for TAG.
6727 If TAG is a number, get the corresponding match group."
6728 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6729 (or (org-face-from-face-or-color
6730 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6731 'org-tag)))
6733 (defun org-font-lock-add-priority-faces (limit)
6734 "Add the special priority faces."
6735 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6736 (add-text-properties
6737 (match-beginning 1) (match-end 1)
6738 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6739 'font-lock-fontified t))))
6741 (defun org-font-lock-add-tag-faces (limit)
6742 "Add the special tag faces."
6743 (when (and org-tag-faces org-tags-special-faces-re)
6744 (while (re-search-forward org-tags-special-faces-re limit t)
6745 (add-text-properties (match-beginning 1) (match-end 1)
6746 (list 'face (org-get-tag-face 1)
6747 'font-lock-fontified t))
6748 (backward-char 1))))
6750 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6751 "Remove fontification and activation overlays from links."
6752 (font-lock-default-unfontify-region beg end)
6753 (let* ((buffer-undo-list t)
6754 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6755 (inhibit-modification-hooks t)
6756 deactivate-mark buffer-file-name buffer-file-truename)
6757 (decompose-region beg end)
6758 (remove-text-properties beg end
6759 '(mouse-face t keymap t org-linked-text t
6760 invisible t intangible t
6761 org-emphasis t))
6762 (org-remove-font-lock-display-properties beg end)))
6764 (defconst org-script-display '(((raise -0.3) (height 0.7))
6765 ((raise 0.3) (height 0.7))
6766 ((raise -0.5))
6767 ((raise 0.5)))
6768 "Display properties for showing superscripts and subscripts.")
6770 (defun org-remove-font-lock-display-properties (beg end)
6771 "Remove specific display properties that have been added by font lock.
6772 The will remove the raise properties that are used to show superscripts
6773 and subscripts."
6774 (let (next prop)
6775 (while (< beg end)
6776 (setq next (next-single-property-change beg 'display nil end)
6777 prop (get-text-property beg 'display))
6778 (when (member prop org-script-display)
6779 (put-text-property beg next 'display nil))
6780 (setq beg next))))
6782 (defun org-raise-scripts (limit)
6783 "Add raise properties to sub/superscripts."
6784 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6785 (re-search-forward
6786 (if (eq org-use-sub-superscripts t)
6787 org-match-substring-regexp
6788 org-match-substring-with-braces-regexp)
6789 limit t))
6790 (let* ((pos (point)) table-p comment-p
6791 (mpos (match-beginning 3))
6792 (emph-p (get-text-property mpos 'org-emphasis))
6793 (link-p (get-text-property mpos 'mouse-face))
6794 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6795 (goto-char (point-at-bol))
6796 (setq table-p (looking-at-p org-table-dataline-regexp)
6797 comment-p (looking-at-p "^[ \t]*#[ +]"))
6798 (goto-char pos)
6799 ;; Handle a_b^c
6800 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6801 (unless (or comment-p emph-p link-p keyw-p)
6802 (put-text-property (match-beginning 3) (match-end 0)
6803 'display
6804 (if (equal (char-after (match-beginning 2)) ?^)
6805 (nth (if table-p 3 1) org-script-display)
6806 (nth (if table-p 2 0) org-script-display)))
6807 (add-text-properties (match-beginning 2) (match-end 2)
6808 (list 'invisible t
6809 'org-dwidth t 'org-dwidth-n 1))
6810 (if (and (eq (char-after (match-beginning 3)) ?{)
6811 (eq (char-before (match-end 3)) ?}))
6812 (progn
6813 (add-text-properties
6814 (match-beginning 3) (1+ (match-beginning 3))
6815 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6816 (add-text-properties
6817 (1- (match-end 3)) (match-end 3)
6818 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6819 t)))
6821 ;;;; Visibility cycling, including org-goto and indirect buffer
6823 ;;; Cycling
6825 (defvar-local org-cycle-global-status nil)
6826 (put 'org-cycle-global-status 'org-state t)
6827 (defvar-local org-cycle-subtree-status nil)
6828 (put 'org-cycle-subtree-status 'org-state t)
6830 (defvar org-inlinetask-min-level)
6832 (defun org-unlogged-message (&rest args)
6833 "Display a message, but avoid logging it in the *Messages* buffer."
6834 (let ((message-log-max nil))
6835 (apply 'message args)))
6837 ;;;###autoload
6838 (defun org-cycle (&optional arg)
6839 "TAB-action and visibility cycling for Org mode.
6841 This is the command invoked in Org mode by the `TAB' key. Its main
6842 purpose is outline visibility cycling, but it also invokes other actions
6843 in special contexts.
6845 When this function is called with a `\\[universal-argument]' prefix, rotate \
6846 the entire
6847 buffer through 3 states (global cycling)
6848 1. OVERVIEW: Show only top-level headlines.
6849 2. CONTENTS: Show all headlines of all levels, but no body text.
6850 3. SHOW ALL: Show everything.
6852 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6853 switch to the startup visibility,
6854 determined by the variable `org-startup-folded', and by any VISIBILITY
6855 properties in the buffer.
6857 With a `\\[universal-argument] \\[universal-argument] \
6858 \\[universal-argument]' prefix argument, show the entire buffer, including
6859 any drawers.
6861 When inside a table, re-align the table and move to the next field.
6863 When point is at the beginning of a headline, rotate the subtree started
6864 by this line through 3 different states (local cycling)
6865 1. FOLDED: Only the main headline is shown.
6866 2. CHILDREN: The main headline and the direct children are shown.
6867 From this state, you can move to one of the children
6868 and zoom in further.
6869 3. SUBTREE: Show the entire subtree, including body text.
6870 If there is no subtree, switch directly from CHILDREN to FOLDED.
6872 When point is at the beginning of an empty headline and the variable
6873 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6874 of the headline by demoting and promoting it to likely levels. This
6875 speeds up creation document structure by pressing `TAB' once or several
6876 times right after creating a new headline.
6878 When there is a numeric prefix, go up to a heading with level ARG, do
6879 a `show-subtree' and return to the previous cursor position. If ARG
6880 is negative, go up that many levels.
6882 When point is not at the beginning of a headline, execute the global
6883 binding for `TAB', which is re-indenting the line. See the option
6884 `org-cycle-emulate-tab' for details.
6886 As a special case, if point is at the beginning of the buffer and there is
6887 no headline in line 1, this function will act as if called with prefix arg
6888 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6889 prefix arg, but only
6890 if the variable `org-cycle-global-at-bob' is t."
6891 (interactive "P")
6892 (org-load-modules-maybe)
6893 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6894 (and org-cycle-level-after-item/entry-creation
6895 (or (org-cycle-level)
6896 (org-cycle-item-indentation))))
6897 (let* ((limit-level
6898 (or org-cycle-max-level
6899 (and (boundp 'org-inlinetask-min-level)
6900 org-inlinetask-min-level
6901 (1- org-inlinetask-min-level))))
6902 (nstars (and limit-level
6903 (if org-odd-levels-only
6904 (and limit-level (1- (* limit-level 2)))
6905 limit-level)))
6906 (org-outline-regexp
6907 (if (not (derived-mode-p 'org-mode))
6908 outline-regexp
6909 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6910 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6911 (not (looking-at org-outline-regexp))))
6912 (org-cycle-hook
6913 (if bob-special
6914 (delq 'org-optimize-window-after-visibility-change
6915 (copy-sequence org-cycle-hook))
6916 org-cycle-hook))
6917 (pos (point)))
6919 (when (or bob-special (equal arg '(4)))
6920 ;; special case: use global cycling
6921 (setq arg t))
6923 (cond
6925 ((equal arg '(16))
6926 (setq last-command 'dummy)
6927 (org-set-startup-visibility)
6928 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6930 ((equal arg '(64))
6931 (outline-show-all)
6932 (org-unlogged-message "Entire buffer visible, including drawers"))
6934 ;; Try cdlatex TAB completion
6935 ((org-try-cdlatex-tab))
6937 ;; Table: enter it or move to the next field.
6938 ((org-at-table-p 'any)
6939 (if (org-at-table.el-p)
6940 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6941 Use `\\[org-edit-special]' to edit table.el tables"))
6942 (if arg (org-table-edit-field t)
6943 (org-table-justify-field-maybe)
6944 (call-interactively 'org-table-next-field))))
6946 ((run-hook-with-args-until-success
6947 'org-tab-after-check-for-table-hook))
6949 ;; Global cycling: delegate to `org-cycle-internal-global'.
6950 ((eq arg t) (org-cycle-internal-global))
6952 ;; Drawers: delegate to `org-flag-drawer'.
6953 ((save-excursion
6954 (beginning-of-line 1)
6955 (looking-at org-drawer-regexp))
6956 (org-flag-drawer ; toggle block visibility
6957 (not (get-char-property (match-end 0) 'invisible))))
6959 ;; Show-subtree, ARG levels up from here.
6960 ((integerp arg)
6961 (save-excursion
6962 (org-back-to-heading)
6963 (outline-up-heading (if (< arg 0) (- arg)
6964 (- (funcall outline-level) arg)))
6965 (org-show-subtree)))
6967 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6968 ((and (featurep 'org-inlinetask)
6969 (org-inlinetask-at-task-p)
6970 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6971 (org-inlinetask-toggle-visibility))
6973 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6974 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6975 (save-excursion (move-beginning-of-line 1)
6976 (looking-at org-outline-regexp)))
6977 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6978 (org-cycle-internal-local))
6980 ;; From there: TAB emulation and template completion.
6981 (buffer-read-only (org-back-to-heading))
6983 ((run-hook-with-args-until-success
6984 'org-tab-after-check-for-cycling-hook))
6986 ((org-try-structure-completion))
6988 ((run-hook-with-args-until-success
6989 'org-tab-before-tab-emulation-hook))
6991 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6992 (or (not (bolp))
6993 (not (looking-at org-outline-regexp))))
6994 (call-interactively (global-key-binding "\t")))
6996 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6997 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6998 (or (and (eq org-cycle-emulate-tab 'white)
6999 (= (match-end 0) (point-at-eol)))
7000 (and (eq org-cycle-emulate-tab 'whitestart)
7001 (>= (match-end 0) pos))))
7003 (eq org-cycle-emulate-tab t))
7004 (call-interactively (global-key-binding "\t")))
7006 (t (save-excursion
7007 (org-back-to-heading)
7008 (org-cycle)))))))
7010 (defun org-cycle-internal-global ()
7011 "Do the global cycling action."
7012 ;; Hack to avoid display of messages for .org attachments in Gnus
7013 (let ((ga (string-match "\\*fontification" (buffer-name))))
7014 (cond
7015 ((and (eq last-command this-command)
7016 (eq org-cycle-global-status 'overview))
7017 ;; We just created the overview - now do table of contents
7018 ;; This can be slow in very large buffers, so indicate action
7019 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7020 (unless ga (org-unlogged-message "CONTENTS..."))
7021 (org-content)
7022 (unless ga (org-unlogged-message "CONTENTS...done"))
7023 (setq org-cycle-global-status 'contents)
7024 (run-hook-with-args 'org-cycle-hook 'contents))
7026 ((and (eq last-command this-command)
7027 (eq org-cycle-global-status 'contents))
7028 ;; We just showed the table of contents - now show everything
7029 (run-hook-with-args 'org-pre-cycle-hook 'all)
7030 (outline-show-all)
7031 (unless ga (org-unlogged-message "SHOW ALL"))
7032 (setq org-cycle-global-status 'all)
7033 (run-hook-with-args 'org-cycle-hook 'all))
7036 ;; Default action: go to overview
7037 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7038 (org-overview)
7039 (unless ga (org-unlogged-message "OVERVIEW"))
7040 (setq org-cycle-global-status 'overview)
7041 (run-hook-with-args 'org-cycle-hook 'overview)))))
7043 (defvar org-called-with-limited-levels nil
7044 "Non-nil when `org-with-limited-levels' is currently active.")
7046 (defun org-cycle-internal-local ()
7047 "Do the local cycling action."
7048 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7049 ;; First, determine end of headline (EOH), end of subtree or item
7050 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7051 (save-excursion
7052 (if (org-at-item-p)
7053 (progn
7054 (beginning-of-line)
7055 (setq struct (org-list-struct))
7056 (setq eoh (point-at-eol))
7057 (setq eos (org-list-get-item-end-before-blank (point) struct))
7058 (setq has-children (org-list-has-child-p (point) struct)))
7059 (org-back-to-heading)
7060 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7061 (setq eos (save-excursion (org-end-of-subtree t t)
7062 (when (bolp) (backward-char)) (point)))
7063 (setq has-children
7064 (or (save-excursion
7065 (let ((level (funcall outline-level)))
7066 (outline-next-heading)
7067 (and (org-at-heading-p t)
7068 (> (funcall outline-level) level))))
7069 (save-excursion
7070 (org-list-search-forward (org-item-beginning-re) eos t)))))
7071 ;; Determine end invisible part of buffer (EOL)
7072 (beginning-of-line 2)
7073 (while (and (not (eobp)) ;This is like `next-line'.
7074 (get-char-property (1- (point)) 'invisible))
7075 (goto-char (next-single-char-property-change (point) 'invisible))
7076 (and (eolp) (beginning-of-line 2)))
7077 (setq eol (point)))
7078 ;; Find out what to do next and set `this-command'
7079 (cond
7080 ((= eos eoh)
7081 ;; Nothing is hidden behind this heading
7082 (unless (org-before-first-heading-p)
7083 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7084 (org-unlogged-message "EMPTY ENTRY")
7085 (setq org-cycle-subtree-status nil)
7086 (save-excursion
7087 (goto-char eos)
7088 (outline-next-heading)
7089 (when (outline-invisible-p) (org-flag-heading nil))))
7090 ((and (or (>= eol eos)
7091 (not (string-match "\\S-" (buffer-substring eol eos))))
7092 (or has-children
7093 (not (setq children-skipped
7094 org-cycle-skip-children-state-if-no-children))))
7095 ;; Entire subtree is hidden in one line: children view
7096 (unless (org-before-first-heading-p)
7097 (run-hook-with-args 'org-pre-cycle-hook 'children))
7098 (if (org-at-item-p)
7099 (org-list-set-item-visibility (point-at-bol) struct 'children)
7100 (org-show-entry)
7101 (org-with-limited-levels (org-show-children))
7102 ;; FIXME: This slows down the func way too much.
7103 ;; How keep drawers hidden in subtree anyway?
7104 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7105 ;; (org-cycle-hide-drawers 'subtree))
7107 ;; Fold every list in subtree to top-level items.
7108 (when (eq org-cycle-include-plain-lists 'integrate)
7109 (save-excursion
7110 (org-back-to-heading)
7111 (while (org-list-search-forward (org-item-beginning-re) eos t)
7112 (beginning-of-line 1)
7113 (let* ((struct (org-list-struct))
7114 (prevs (org-list-prevs-alist struct))
7115 (end (org-list-get-bottom-point struct)))
7116 (dolist (e (org-list-get-all-items (point) struct prevs))
7117 (org-list-set-item-visibility e struct 'folded))
7118 (goto-char (if (< end eos) end eos)))))))
7119 (org-unlogged-message "CHILDREN")
7120 (save-excursion
7121 (goto-char eos)
7122 (outline-next-heading)
7123 (when (outline-invisible-p) (org-flag-heading nil)))
7124 (setq org-cycle-subtree-status 'children)
7125 (unless (org-before-first-heading-p)
7126 (run-hook-with-args 'org-cycle-hook 'children)))
7127 ((or children-skipped
7128 (and (eq last-command this-command)
7129 (eq org-cycle-subtree-status 'children)))
7130 ;; We just showed the children, or no children are there,
7131 ;; now show everything.
7132 (unless (org-before-first-heading-p)
7133 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7134 (outline-flag-region eoh eos nil)
7135 (org-unlogged-message
7136 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7137 (setq org-cycle-subtree-status 'subtree)
7138 (unless (org-before-first-heading-p)
7139 (run-hook-with-args 'org-cycle-hook 'subtree)))
7141 ;; Default action: hide the subtree.
7142 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7143 (outline-flag-region eoh eos t)
7144 (org-unlogged-message "FOLDED")
7145 (setq org-cycle-subtree-status 'folded)
7146 (unless (org-before-first-heading-p)
7147 (run-hook-with-args 'org-cycle-hook 'folded))))))
7149 ;;;###autoload
7150 (defun org-global-cycle (&optional arg)
7151 "Cycle the global visibility. For details see `org-cycle'.
7152 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7153 With a numeric prefix, show all headlines up to that level."
7154 (interactive "P")
7155 (let ((org-cycle-include-plain-lists
7156 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7157 (cond
7158 ((integerp arg)
7159 (outline-show-all)
7160 (outline-hide-sublevels arg)
7161 (setq org-cycle-global-status 'contents))
7162 ((equal arg '(4))
7163 (org-set-startup-visibility)
7164 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7166 (org-cycle '(4))))))
7168 (defun org-set-startup-visibility ()
7169 "Set the visibility required by startup options and properties."
7170 (cond
7171 ((eq org-startup-folded t)
7172 (org-overview))
7173 ((eq org-startup-folded 'content)
7174 (org-content))
7175 ((or (eq org-startup-folded 'showeverything)
7176 (eq org-startup-folded nil))
7177 (outline-show-all)))
7178 (unless (eq org-startup-folded 'showeverything)
7179 (when org-hide-block-startup (org-hide-block-all))
7180 (org-set-visibility-according-to-property 'no-cleanup)
7181 (org-cycle-hide-archived-subtrees 'all)
7182 (org-cycle-hide-drawers 'all)
7183 (org-cycle-show-empty-lines t)))
7185 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7186 "Switch subtree visibilities according to :VISIBILITY: property."
7187 (interactive)
7188 (org-with-wide-buffer
7189 (goto-char (point-min))
7190 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7191 (if (not (org-at-property-p)) (outline-next-heading)
7192 (let ((state (match-string 3)))
7193 (save-excursion
7194 (org-back-to-heading t)
7195 (outline-hide-subtree)
7196 (org-reveal)
7197 (cond
7198 ((equal state "folded")
7199 (outline-hide-subtree))
7200 ((equal state "children")
7201 (org-show-hidden-entry)
7202 (org-show-children))
7203 ((equal state "content")
7204 (save-excursion
7205 (save-restriction
7206 (org-narrow-to-subtree)
7207 (org-content))))
7208 ((member state '("all" "showall"))
7209 (outline-show-subtree)))))))
7210 (unless no-cleanup
7211 (org-cycle-hide-archived-subtrees 'all)
7212 (org-cycle-hide-drawers 'all)
7213 (org-cycle-show-empty-lines 'all))))
7215 ;; This function uses outline-regexp instead of the more fundamental
7216 ;; org-outline-regexp so that org-cycle-global works outside of Org
7217 ;; buffers, where outline-regexp is needed.
7218 (defun org-overview ()
7219 "Switch to overview mode, showing only top-level headlines.
7220 This shows all headlines with a level equal or greater than the level
7221 of the first headline in the buffer. This is important, because if the
7222 first headline is not level one, then (hide-sublevels 1) gives confusing
7223 results."
7224 (interactive)
7225 (save-excursion
7226 (let ((level
7227 (save-excursion
7228 (goto-char (point-min))
7229 (when (re-search-forward (concat "^" outline-regexp) nil t)
7230 (goto-char (match-beginning 0))
7231 (funcall outline-level)))))
7232 (and level (outline-hide-sublevels level)))))
7234 (defun org-content (&optional arg)
7235 "Show all headlines in the buffer, like a table of contents.
7236 With numerical argument N, show content up to level N."
7237 (interactive "P")
7238 (org-overview)
7239 (save-excursion
7240 ;; Visit all headings and show their offspring
7241 (and (integerp arg) (org-overview))
7242 (goto-char (point-max))
7243 (catch 'exit
7244 (while (and (progn (condition-case nil
7245 (outline-previous-visible-heading 1)
7246 (error (goto-char (point-min))))
7248 (looking-at org-outline-regexp))
7249 (if (integerp arg)
7250 (org-show-children (1- arg))
7251 (outline-show-branches))
7252 (when (bobp) (throw 'exit nil))))))
7254 (defun org-optimize-window-after-visibility-change (state)
7255 "Adjust the window after a change in outline visibility.
7256 This function is the default value of the hook `org-cycle-hook'."
7257 (when (get-buffer-window (current-buffer))
7258 (cond
7259 ((eq state 'content) nil)
7260 ((eq state 'all) nil)
7261 ((eq state 'folded) nil)
7262 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7263 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7265 (defun org-remove-empty-overlays-at (pos)
7266 "Remove outline overlays that do not contain non-white stuff."
7267 (dolist (o (overlays-at pos))
7268 (and (eq 'outline (overlay-get o 'invisible))
7269 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7270 (overlay-end o))))
7271 (delete-overlay o))))
7273 (defun org-clean-visibility-after-subtree-move ()
7274 "Fix visibility issues after moving a subtree."
7275 ;; First, find a reasonable region to look at:
7276 ;; Start two siblings above, end three below
7277 (let* ((beg (save-excursion
7278 (and (org-get-last-sibling)
7279 (org-get-last-sibling))
7280 (point)))
7281 (end (save-excursion
7282 (and (org-get-next-sibling)
7283 (org-get-next-sibling)
7284 (org-get-next-sibling))
7285 (if (org-at-heading-p)
7286 (point-at-eol)
7287 (point))))
7288 (level (looking-at "\\*+"))
7289 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7290 (save-excursion
7291 (save-restriction
7292 (narrow-to-region beg end)
7293 (when re
7294 ;; Properly fold already folded siblings
7295 (goto-char (point-min))
7296 (while (re-search-forward re nil t)
7297 (when (and (not (outline-invisible-p))
7298 (save-excursion
7299 (goto-char (point-at-eol)) (outline-invisible-p)))
7300 (outline-hide-entry))))
7301 (org-cycle-show-empty-lines 'overview)
7302 (org-cycle-hide-drawers 'overview)))))
7304 (defun org-cycle-show-empty-lines (state)
7305 "Show empty lines above all visible headlines.
7306 The region to be covered depends on STATE when called through
7307 `org-cycle-hook'. Lisp program can use t for STATE to get the
7308 entire buffer covered. Note that an empty line is only shown if there
7309 are at least `org-cycle-separator-lines' empty lines before the headline."
7310 (when (/= org-cycle-separator-lines 0)
7311 (save-excursion
7312 (let* ((n (abs org-cycle-separator-lines))
7313 (re (cond
7314 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7315 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7316 (t (let ((ns (number-to-string (- n 2))))
7317 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7318 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7319 beg end)
7320 (cond
7321 ((memq state '(overview contents t))
7322 (setq beg (point-min) end (point-max)))
7323 ((memq state '(children folded))
7324 (setq beg (point)
7325 end (progn (org-end-of-subtree t t)
7326 (line-beginning-position 2)))))
7327 (when beg
7328 (goto-char beg)
7329 (while (re-search-forward re end t)
7330 (unless (get-char-property (match-end 1) 'invisible)
7331 (let ((e (match-end 1))
7332 (b (if (>= org-cycle-separator-lines 0)
7333 (match-beginning 1)
7334 (save-excursion
7335 (goto-char (match-beginning 0))
7336 (skip-chars-backward " \t\n")
7337 (line-end-position)))))
7338 (outline-flag-region b e nil))))))))
7339 ;; Never hide empty lines at the end of the file.
7340 (save-excursion
7341 (goto-char (point-max))
7342 (outline-previous-heading)
7343 (outline-end-of-heading)
7344 (when (and (looking-at "[ \t\n]+")
7345 (= (match-end 0) (point-max)))
7346 (outline-flag-region (point) (match-end 0) nil))))
7348 (defun org-show-empty-lines-in-parent ()
7349 "Move to the parent and re-show empty lines before visible headlines."
7350 (save-excursion
7351 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7352 (org-cycle-show-empty-lines context))))
7354 (defun org-files-list ()
7355 "Return `org-agenda-files' list, plus all open Org files.
7356 This is useful for operations that need to scan all of a user's
7357 open and agenda-wise Org files."
7358 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7359 (dolist (buf (buffer-list))
7360 (with-current-buffer buf
7361 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7362 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7363 files))
7365 (defsubst org-entry-beginning-position ()
7366 "Return the beginning position of the current entry."
7367 (save-excursion (org-back-to-heading t) (point)))
7369 (defsubst org-entry-end-position ()
7370 "Return the end position of the current entry."
7371 (save-excursion (outline-next-heading) (point)))
7373 (defun org-cycle-hide-drawers (state &optional exceptions)
7374 "Re-hide all drawers after a visibility state change.
7375 When non-nil, optional argument EXCEPTIONS is a list of strings
7376 specifying which drawers should not be hidden."
7377 (when (and (derived-mode-p 'org-mode)
7378 (not (memq state '(overview folded contents))))
7379 (save-excursion
7380 (let* ((globalp (memq state '(contents all)))
7381 (beg (if globalp (point-min) (point)))
7382 (end (if globalp (point-max)
7383 (if (eq state 'children)
7384 (save-excursion (outline-next-heading) (point))
7385 (org-end-of-subtree t)))))
7386 (goto-char beg)
7387 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7388 (unless (member-ignore-case (match-string 1) exceptions)
7389 (let ((drawer (org-element-at-point)))
7390 (when (memq (org-element-type drawer) '(drawer property-drawer))
7391 (org-flag-drawer t drawer)
7392 ;; Make sure to skip drawer entirely or we might flag
7393 ;; it another time when matching its ending line with
7394 ;; `org-drawer-regexp'.
7395 (goto-char (org-element-property :end drawer))))))))))
7397 (defun org-flag-drawer (flag &optional element)
7398 "When FLAG is non-nil, hide the drawer we are at.
7399 Otherwise make it visible. When optional argument ELEMENT is
7400 a parsed drawer, as returned by `org-element-at-point', hide or
7401 show that drawer instead."
7402 (let ((drawer (or element
7403 (and (save-excursion
7404 (beginning-of-line)
7405 (looking-at-p org-drawer-regexp))
7406 (org-element-at-point)))))
7407 (when (memq (org-element-type drawer) '(drawer property-drawer))
7408 (let ((post (org-element-property :post-affiliated drawer)))
7409 (save-excursion
7410 (outline-flag-region
7411 (progn (goto-char post) (line-end-position))
7412 (progn (goto-char (org-element-property :end drawer))
7413 (skip-chars-backward " \r\t\n")
7414 (line-end-position))
7415 flag))
7416 ;; When the drawer is hidden away, make sure point lies in
7417 ;; a visible part of the buffer.
7418 (when (and flag (> (line-beginning-position) post))
7419 (goto-char post))))))
7421 (defun org-subtree-end-visible-p ()
7422 "Is the end of the current subtree visible?"
7423 (pos-visible-in-window-p
7424 (save-excursion (org-end-of-subtree t) (point))))
7426 (defun org-first-headline-recenter ()
7427 "Move cursor to the first headline and recenter the headline."
7428 (let ((window (get-buffer-window)))
7429 (when window
7430 (goto-char (point-min))
7431 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7432 (set-window-start window (line-beginning-position))))))
7434 ;;; Saving and restoring visibility
7436 (defun org-outline-overlay-data (&optional use-markers)
7437 "Return a list of the locations of all outline overlays.
7438 These are overlays with the `invisible' property value `outline'.
7439 The return value is a list of cons cells, with start and stop
7440 positions for each overlay.
7441 If USE-MARKERS is set, return the positions as markers."
7442 (let (beg end)
7443 (org-with-wide-buffer
7444 (delq nil
7445 (mapcar (lambda (o)
7446 (when (eq (overlay-get o 'invisible) 'outline)
7447 (setq beg (overlay-start o)
7448 end (overlay-end o))
7449 (and beg end (> end beg)
7450 (if use-markers
7451 (cons (copy-marker beg)
7452 (copy-marker end t))
7453 (cons beg end)))))
7454 (overlays-in (point-min) (point-max)))))))
7456 (defun org-set-outline-overlay-data (data)
7457 "Create visibility overlays for all positions in DATA.
7458 DATA should have been made by `org-outline-overlay-data'."
7459 (org-with-wide-buffer
7460 (outline-show-all)
7461 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7463 ;;; Folding of blocks
7465 (defvar-local org-hide-block-overlays nil
7466 "Overlays hiding blocks.")
7468 (defun org-block-map (function &optional start end)
7469 "Call FUNCTION at the head of all source blocks in the current buffer.
7470 Optional arguments START and END can be used to limit the range."
7471 (let ((start (or start (point-min)))
7472 (end (or end (point-max))))
7473 (save-excursion
7474 (goto-char start)
7475 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7476 (save-excursion
7477 (save-match-data
7478 (goto-char (match-beginning 0))
7479 (funcall function)))))))
7481 (defun org-hide-block-toggle-all ()
7482 "Toggle the visibility of all blocks in the current buffer."
7483 (org-block-map 'org-hide-block-toggle))
7485 (defun org-hide-block-all ()
7486 "Fold all blocks in the current buffer."
7487 (interactive)
7488 (org-show-block-all)
7489 (org-block-map 'org-hide-block-toggle-maybe))
7491 (defun org-show-block-all ()
7492 "Unfold all blocks in the current buffer."
7493 (interactive)
7494 (mapc #'delete-overlay org-hide-block-overlays)
7495 (setq org-hide-block-overlays nil))
7497 (defun org-hide-block-toggle-maybe ()
7498 "Toggle visibility of block at point.
7499 Unlike to `org-hide-block-toggle', this function does not throw
7500 an error. Return a non-nil value when toggling is successful."
7501 (interactive)
7502 (ignore-errors (org-hide-block-toggle)))
7504 (defun org-hide-block-toggle (&optional force)
7505 "Toggle the visibility of the current block.
7506 When optional argument FORCE is `off', make block visible. If it
7507 is non-nil, hide it unconditionally. Throw an error when not at
7508 a block. Return a non-nil value when toggling is successful."
7509 (interactive)
7510 (let ((element (org-element-at-point)))
7511 (unless (memq (org-element-type element)
7512 '(center-block comment-block dynamic-block example-block
7513 export-block quote-block special-block
7514 src-block verse-block))
7515 (user-error "Not at a block"))
7516 (let* ((start (save-excursion
7517 (goto-char (org-element-property :post-affiliated element))
7518 (line-end-position)))
7519 (end (save-excursion
7520 (goto-char (org-element-property :end element))
7521 (skip-chars-backward " \r\t\n")
7522 (line-end-position)))
7523 (overlays (overlays-at start)))
7524 (cond
7525 ;; Do nothing when not before or at the block opening line or
7526 ;; at the block closing line.
7527 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7528 ((and (not (eq force 'off))
7529 (not (memq t (mapcar
7530 (lambda (o)
7531 (eq (overlay-get o 'invisible) 'org-hide-block))
7532 overlays))))
7533 (let ((ov (make-overlay start end)))
7534 (overlay-put ov 'invisible 'org-hide-block)
7535 ;; Make the block accessible to `isearch'.
7536 (overlay-put
7537 ov 'isearch-open-invisible
7538 (lambda (ov)
7539 (when (memq ov org-hide-block-overlays)
7540 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7541 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7542 (delete-overlay ov))))
7543 (push ov org-hide-block-overlays)
7544 ;; When the block is hidden away, make sure point is left in
7545 ;; a visible part of the buffer.
7546 (when (> (line-beginning-position) start)
7547 (goto-char start)
7548 (beginning-of-line))
7549 ;; Signal successful toggling.
7551 ((or (not force) (eq force 'off))
7552 (dolist (ov overlays t)
7553 (when (memq ov org-hide-block-overlays)
7554 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7555 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7556 (delete-overlay ov))))))))
7558 ;; org-tab-after-check-for-cycling-hook
7559 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7560 ;; Remove overlays when changing major mode
7561 (add-hook 'org-mode-hook
7562 (lambda () (add-hook 'change-major-mode-hook
7563 'org-show-block-all 'append 'local)))
7565 ;;; Org-goto
7567 (defvar org-goto-window-configuration nil)
7568 (defvar org-goto-marker nil)
7569 (defvar org-goto-map)
7570 (defun org-goto-map ()
7571 "Set the keymap `org-goto'."
7572 (setq org-goto-map
7573 (let ((map (make-sparse-keymap)))
7574 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7575 mouse-drag-region universal-argument org-occur)))
7576 (dolist (cmd cmds)
7577 (substitute-key-definition cmd cmd map global-map)))
7578 (suppress-keymap map)
7579 (org-defkey map "\C-m" 'org-goto-ret)
7580 (org-defkey map [(return)] 'org-goto-ret)
7581 (org-defkey map [(left)] 'org-goto-left)
7582 (org-defkey map [(right)] 'org-goto-right)
7583 (org-defkey map [(control ?g)] 'org-goto-quit)
7584 (org-defkey map "\C-i" 'org-cycle)
7585 (org-defkey map [(tab)] 'org-cycle)
7586 (org-defkey map [(down)] 'outline-next-visible-heading)
7587 (org-defkey map [(up)] 'outline-previous-visible-heading)
7588 (if org-goto-auto-isearch
7589 (if (fboundp 'define-key-after)
7590 (define-key-after map [t] 'org-goto-local-auto-isearch)
7591 nil)
7592 (org-defkey map "q" 'org-goto-quit)
7593 (org-defkey map "n" 'outline-next-visible-heading)
7594 (org-defkey map "p" 'outline-previous-visible-heading)
7595 (org-defkey map "f" 'outline-forward-same-level)
7596 (org-defkey map "b" 'outline-backward-same-level)
7597 (org-defkey map "u" 'outline-up-heading))
7598 (org-defkey map "/" 'org-occur)
7599 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7600 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7601 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7602 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7603 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7604 map)))
7606 (defconst org-goto-help
7607 "Browse buffer copy, to find location or copy text.%s
7608 RET=jump to location C-g=quit and return to previous location
7609 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7611 (defvar org-goto-start-pos) ; dynamically scoped parameter
7613 (defun org-goto (&optional alternative-interface)
7614 "Look up a different location in the current file, keeping current visibility.
7616 When you want look-up or go to a different location in a
7617 document, the fastest way is often to fold the entire buffer and
7618 then dive into the tree. This method has the disadvantage, that
7619 the previous location will be folded, which may not be what you
7620 want.
7622 This command works around this by showing a copy of the current
7623 buffer in an indirect buffer, in overview mode. You can dive
7624 into the tree in that copy, use org-occur and incremental search
7625 to find a location. When pressing RET or `Q', the command
7626 returns to the original buffer in which the visibility is still
7627 unchanged. After RET it will also jump to the location selected
7628 in the indirect buffer and expose the headline hierarchy above.
7630 With a prefix argument, use the alternative interface: e.g., if
7631 `org-goto-interface' is `outline' use `outline-path-completion'."
7632 (interactive "P")
7633 (org-goto-map)
7634 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7635 (org-refile-use-outline-path t)
7636 (org-refile-target-verify-function nil)
7637 (interface
7638 (if (not alternative-interface)
7639 org-goto-interface
7640 (if (eq org-goto-interface 'outline)
7641 'outline-path-completion
7642 'outline)))
7643 (org-goto-start-pos (point))
7644 (selected-point
7645 (if (eq interface 'outline)
7646 (car (org-get-location (current-buffer) org-goto-help))
7647 (let ((pa (org-refile-get-location "Goto")))
7648 (org-refile-check-position pa)
7649 (nth 3 pa)))))
7650 (if selected-point
7651 (progn
7652 (org-mark-ring-push org-goto-start-pos)
7653 (goto-char selected-point)
7654 (when (or (outline-invisible-p) (org-invisible-p2))
7655 (org-show-context 'org-goto)))
7656 (message "Quit"))))
7658 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7659 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7660 (defvar org-goto-local-auto-isearch-map) ; defined below
7662 (defun org-get-location (_buf help)
7663 "Let the user select a location in current buffer.
7664 This function uses a recursive edit. It returns the selected position
7665 or nil."
7666 (org-no-popups
7667 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7668 (isearch-hide-immediately nil)
7669 (isearch-search-fun-function
7670 (lambda () 'org-goto-local-search-headings))
7671 (org-goto-selected-point org-goto-exit-command))
7672 (save-excursion
7673 (save-window-excursion
7674 (delete-other-windows)
7675 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7676 (pop-to-buffer-same-window
7677 (condition-case nil
7678 (make-indirect-buffer (current-buffer) "*org-goto*")
7679 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7680 (with-output-to-temp-buffer "*Org Help*"
7681 (princ (format help (if org-goto-auto-isearch
7682 " Just type for auto-isearch."
7683 " n/p/f/b/u to navigate, q to quit."))))
7684 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7685 (setq buffer-read-only nil)
7686 (let ((org-startup-truncated t)
7687 (org-startup-folded nil)
7688 (org-startup-align-all-tables nil))
7689 (org-mode)
7690 (org-overview))
7691 (setq buffer-read-only t)
7692 (if (and (boundp 'org-goto-start-pos)
7693 (integer-or-marker-p org-goto-start-pos))
7694 (progn (goto-char org-goto-start-pos)
7695 (when (outline-invisible-p)
7696 (org-show-set-visibility 'lineage)))
7697 (goto-char (point-min)))
7698 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7699 (message "Select location and press RET")
7700 (use-local-map org-goto-map)
7701 (recursive-edit)))
7702 (kill-buffer "*org-goto*")
7703 (cons org-goto-selected-point org-goto-exit-command))))
7705 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7706 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7707 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7708 (if (fboundp 'isearch-other-control-char)
7709 (progn
7710 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7711 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7712 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7713 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7714 (define-key org-goto-local-auto-isearch-map [return] nil))
7716 (defun org-goto-local-search-headings (string bound noerror)
7717 "Search and make sure that any matches are in headlines."
7718 (catch 'return
7719 (while (if isearch-forward
7720 (search-forward string bound noerror)
7721 (search-backward string bound noerror))
7722 (when (save-match-data
7723 (and (save-excursion
7724 (beginning-of-line)
7725 (looking-at org-complex-heading-regexp))
7726 (or (not (match-beginning 5))
7727 (< (point) (match-beginning 5)))))
7728 (throw 'return (point))))))
7730 (defun org-goto-local-auto-isearch ()
7731 "Start isearch."
7732 (interactive)
7733 (goto-char (point-min))
7734 (let ((keys (this-command-keys)))
7735 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7736 (isearch-mode t)
7737 (isearch-process-search-char (string-to-char keys)))))
7739 (defun org-goto-ret (&optional _arg)
7740 "Finish `org-goto' by going to the new location."
7741 (interactive "P")
7742 (setq org-goto-selected-point (point))
7743 (setq org-goto-exit-command 'return)
7744 (throw 'exit nil))
7746 (defun org-goto-left ()
7747 "Finish `org-goto' by going to the new location."
7748 (interactive)
7749 (if (org-at-heading-p)
7750 (progn
7751 (beginning-of-line 1)
7752 (setq org-goto-selected-point (point)
7753 org-goto-exit-command 'left)
7754 (throw 'exit nil))
7755 (user-error "Not on a heading")))
7757 (defun org-goto-right ()
7758 "Finish `org-goto' by going to the new location."
7759 (interactive)
7760 (if (org-at-heading-p)
7761 (progn
7762 (setq org-goto-selected-point (point)
7763 org-goto-exit-command 'right)
7764 (throw 'exit nil))
7765 (user-error "Not on a heading")))
7767 (defun org-goto-quit ()
7768 "Finish `org-goto' without cursor motion."
7769 (interactive)
7770 (setq org-goto-selected-point nil)
7771 (setq org-goto-exit-command 'quit)
7772 (throw 'exit nil))
7774 ;;; Indirect buffer display of subtrees
7776 (defvar org-indirect-dedicated-frame nil
7777 "This is the frame being used for indirect tree display.")
7778 (defvar org-last-indirect-buffer nil)
7780 (defun org-tree-to-indirect-buffer (&optional arg)
7781 "Create indirect buffer and narrow it to current subtree.
7783 With a numerical prefix ARG, go up to this level and then take that tree.
7784 If ARG is negative, go up that many levels.
7786 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7787 indirect buffer previously made with this command, to avoid proliferation of
7788 indirect buffers. However, when you call the command with a \
7789 `\\[universal-argument]' prefix, or
7790 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7791 so that you can work with several indirect buffers at the same time. If
7792 `org-indirect-buffer-display' is `dedicated-frame', the \
7793 `\\[universal-argument]' prefix also
7794 requests that a new frame be made for the new buffer, so that the dedicated
7795 frame is not changed."
7796 (interactive "P")
7797 (let ((cbuf (current-buffer))
7798 (cwin (selected-window))
7799 (pos (point))
7800 beg end level heading ibuf)
7801 (save-excursion
7802 (org-back-to-heading t)
7803 (when (numberp arg)
7804 (setq level (org-outline-level))
7805 (when (< arg 0) (setq arg (+ level arg)))
7806 (while (> (setq level (org-outline-level)) arg)
7807 (org-up-heading-safe)))
7808 (setq beg (point)
7809 heading (org-get-heading 'no-tags))
7810 (org-end-of-subtree t t)
7811 (when (org-at-heading-p) (backward-char 1))
7812 (setq end (point)))
7813 (when (and (buffer-live-p org-last-indirect-buffer)
7814 (not (eq org-indirect-buffer-display 'new-frame))
7815 (not arg))
7816 (kill-buffer org-last-indirect-buffer))
7817 (setq ibuf (org-get-indirect-buffer cbuf heading)
7818 org-last-indirect-buffer ibuf)
7819 (cond
7820 ((or (eq org-indirect-buffer-display 'new-frame)
7821 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7822 (select-frame (make-frame))
7823 (delete-other-windows)
7824 (pop-to-buffer-same-window ibuf)
7825 (org-set-frame-title heading))
7826 ((eq org-indirect-buffer-display 'dedicated-frame)
7827 (raise-frame
7828 (select-frame (or (and org-indirect-dedicated-frame
7829 (frame-live-p org-indirect-dedicated-frame)
7830 org-indirect-dedicated-frame)
7831 (setq org-indirect-dedicated-frame (make-frame)))))
7832 (delete-other-windows)
7833 (pop-to-buffer-same-window ibuf)
7834 (org-set-frame-title (concat "Indirect: " heading)))
7835 ((eq org-indirect-buffer-display 'current-window)
7836 (pop-to-buffer-same-window ibuf))
7837 ((eq org-indirect-buffer-display 'other-window)
7838 (pop-to-buffer ibuf))
7839 (t (error "Invalid value")))
7840 (narrow-to-region beg end)
7841 (outline-show-all)
7842 (goto-char pos)
7843 (run-hook-with-args 'org-cycle-hook 'all)
7844 (and (window-live-p cwin) (select-window cwin))))
7846 (defun org-get-indirect-buffer (&optional buffer heading)
7847 (setq buffer (or buffer (current-buffer)))
7848 (let ((n 1) (base (buffer-name buffer)) bname)
7849 (while (buffer-live-p
7850 (get-buffer
7851 (setq bname
7852 (concat base "-"
7853 (if heading (concat heading "-" (number-to-string n))
7854 (number-to-string n))))))
7855 (setq n (1+ n)))
7856 (condition-case nil
7857 (make-indirect-buffer buffer bname 'clone)
7858 (error (make-indirect-buffer buffer bname)))))
7860 (defun org-set-frame-title (title)
7861 "Set the title of the current frame to the string TITLE."
7862 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7864 ;;;; Structure editing
7866 ;;; Inserting headlines
7868 (defun org--line-empty-p (n)
7869 "Is the Nth next line empty?
7871 Counts the current line as N = 1 and the previous line as N = 0;
7872 see `beginning-of-line'."
7873 (save-excursion
7874 (and (not (bobp))
7875 (or (beginning-of-line n) t)
7876 (save-match-data
7877 (looking-at "[ \t]*$")))))
7879 (defun org-previous-line-empty-p ()
7880 "Is the previous line a blank line?
7881 When NEXT is non-nil, check the next line instead."
7882 (org--line-empty-p 0))
7884 (defun org-next-line-empty-p ()
7885 "Is the previous line a blank line?
7886 When NEXT is non-nil, check the next line instead."
7887 (org--line-empty-p 2))
7889 (defun org-insert-heading (&optional arg invisible-ok top)
7890 "Insert a new heading or an item with the same depth at point.
7892 If point is at the beginning of a heading or a list item, insert
7893 a new heading or a new item above the current one. When at the
7894 beginning of a regular line of text, turn it into a heading.
7896 If point is in the middle of a line, split it and create a new
7897 headline/item with the text in the current line after point (see
7898 `org-M-RET-may-split-line' on how to modify this behavior). As
7899 a special case, on a headline, splitting can only happen on the
7900 title itself. E.g., this excludes breaking stars or tags.
7902 With a `\\[universal-argument]' prefix, set \
7903 `org-insert-heading-respect-content' to
7904 a non-nil value for the duration of the command. This forces the
7905 insertion of a heading after the current subtree, independently
7906 on the location of point.
7908 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7909 insert the heading at the end of the tree
7910 above the current heading. For example, if point is within a
7911 2nd-level heading, then it will insert a 2nd-level heading at
7912 the end of the 1st-level parent subtree.
7914 When INVISIBLE-OK is set, stop at invisible headlines when going
7915 back. This is important for non-interactive uses of the
7916 command.
7918 When optional argument TOP is non-nil, insert a level 1 heading,
7919 unconditionally."
7920 (interactive "P")
7921 (let ((itemp (and (not top) (org-in-item-p)))
7922 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7923 (respect-content (or org-insert-heading-respect-content
7924 (equal arg '(4))))
7925 (initial-content ""))
7927 (cond
7929 ((or (= (buffer-size) 0)
7930 (and (not (save-excursion
7931 (and (ignore-errors (org-back-to-heading invisible-ok))
7932 (org-at-heading-p))))
7933 (or arg (not itemp))))
7934 ;; At beginning of buffer or so high up that only a heading
7935 ;; makes sense.
7936 (cond ((and (bolp) (not respect-content)) (insert "* "))
7937 ((not respect-content)
7938 (unless may-split (end-of-line))
7939 (insert "\n* "))
7940 ((re-search-forward org-outline-regexp-bol nil t)
7941 (beginning-of-line)
7942 (insert "* \n")
7943 (backward-char))
7944 (t (goto-char (point-max))
7945 (insert "\n* ")))
7946 (run-hooks 'org-insert-heading-hook))
7948 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7951 ;; Maybe move at the end of the subtree
7952 (when (equal arg '(16))
7953 (org-up-heading-safe)
7954 (org-end-of-subtree t))
7955 ;; Insert a heading
7956 (save-restriction
7957 (widen)
7958 (let* ((level nil)
7959 (on-heading (org-at-heading-p))
7960 (empty-line-p (if on-heading
7961 (org-previous-line-empty-p)
7962 ;; We will decide later
7963 nil))
7964 ;; Get a level string to fall back on.
7965 (fix-level
7966 (if (org-before-first-heading-p) "*"
7967 (save-excursion
7968 (org-back-to-heading t)
7969 (when (org-previous-line-empty-p) (setq empty-line-p t))
7970 (looking-at org-outline-regexp)
7971 (make-string (1- (length (match-string 0))) ?*))))
7972 (stars
7973 (save-excursion
7974 (condition-case nil
7975 (if top "* "
7976 (org-back-to-heading invisible-ok)
7977 (when (and (not on-heading)
7978 (featurep 'org-inlinetask)
7979 (integerp org-inlinetask-min-level)
7980 (>= (length (match-string 0))
7981 org-inlinetask-min-level))
7982 ;; Find a heading level before the inline
7983 ;; task.
7984 (while (and (setq level (org-up-heading-safe))
7985 (>= level org-inlinetask-min-level)))
7986 (if (org-at-heading-p)
7987 (org-back-to-heading invisible-ok)
7988 (error "This should not happen")))
7989 (unless (and (save-excursion
7990 (save-match-data
7991 (org-backward-heading-same-level
7992 1 invisible-ok))
7993 (= (point) (match-beginning 0)))
7994 (not (org-next-line-empty-p)))
7995 (setq empty-line-p (or empty-line-p
7996 (org-previous-line-empty-p))))
7997 (match-string 0))
7998 (error (or fix-level "* ")))))
7999 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
8000 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
8002 ;; If we insert after content, move there and clean up
8003 ;; whitespace.
8004 (when respect-content
8005 (if (not (org-before-first-heading-p))
8006 (org-end-of-subtree nil t)
8007 (re-search-forward org-outline-regexp-bol)
8008 (beginning-of-line 0))
8009 (skip-chars-backward " \r\t\n")
8010 (and (not (looking-back "^\\*+" (line-beginning-position)))
8011 (looking-at "[ \t]+") (replace-match ""))
8012 (unless (eobp) (forward-char 1))
8013 (when (looking-at "^\\*")
8014 (unless (bobp) (backward-char 1))
8015 (insert "\n")))
8017 ;; If we are splitting, grab the text that should be moved
8018 ;; to the new headline.
8019 (when may-split
8020 (if (org-at-heading-p)
8021 ;; This is a heading: split intelligently (keeping
8022 ;; tags).
8023 (let ((pos (point)))
8024 (beginning-of-line)
8025 (unless (looking-at org-complex-heading-regexp)
8026 (error "This should not happen"))
8027 (when (and (match-beginning 4)
8028 (> pos (match-beginning 4))
8029 (< pos (match-end 4)))
8030 (setq initial-content (buffer-substring pos (match-end 4)))
8031 (goto-char pos)
8032 (delete-region (point) (match-end 4))
8033 (if (looking-at "[ \t]*$")
8034 (replace-match "")
8035 (insert (make-string (length initial-content) ?\s)))
8036 (setq initial-content (org-trim initial-content)))
8037 (goto-char pos))
8038 ;; A normal line.
8039 (setq initial-content
8040 (org-trim
8041 (delete-and-extract-region (point) (line-end-position))))))
8043 ;; If we are at the beginning of the line, insert before it.
8044 ;; Otherwise, after it.
8045 (cond
8046 ((and (bolp) (looking-at "[ \t]*$")))
8047 ((bolp) (save-excursion (insert "\n")))
8048 (t (end-of-line)
8049 (insert "\n")))
8051 ;; Insert the new heading
8052 (insert stars)
8053 (just-one-space)
8054 (insert initial-content)
8055 (unless (and blank (org-previous-line-empty-p))
8056 (org-N-empty-lines-before-current (if blank 1 0)))
8057 ;; Adjust visibility, which may be messed up if we removed
8058 ;; blank lines while previous entry was hidden.
8059 (let ((bol (line-beginning-position)))
8060 (dolist (o (overlays-at (1- bol)))
8061 (when (and (eq (overlay-get o 'invisible) 'outline)
8062 (eq (overlay-end o) bol))
8063 (move-overlay o (overlay-start o) (1- bol)))))
8064 (run-hooks 'org-insert-heading-hook)))))))
8066 (defun org-N-empty-lines-before-current (N)
8067 "Make the number of empty lines before current exactly N.
8068 So this will delete or add empty lines."
8069 (save-excursion
8070 (beginning-of-line)
8071 (let ((p (point)))
8072 (skip-chars-backward " \r\t\n")
8073 (unless (bolp) (forward-line))
8074 (delete-region (point) p))
8075 (when (> N 0) (insert (make-string N ?\n)))))
8077 (defun org-get-heading (&optional no-tags no-todo)
8078 "Return the heading of the current entry, without the stars.
8079 When NO-TAGS is non-nil, don't include tags.
8080 When NO-TODO is non-nil, don't include TODO keywords."
8081 (save-excursion
8082 (org-back-to-heading t)
8083 (let ((case-fold-search nil))
8084 (cond
8085 ((and no-tags no-todo)
8086 (looking-at org-complex-heading-regexp)
8087 ;; Return value has to be a string, but match group 4 is
8088 ;; optional.
8089 (or (match-string 4) ""))
8090 (no-tags
8091 (looking-at (concat org-outline-regexp
8092 "\\(.*?\\)"
8093 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8094 (match-string 1))
8095 (no-todo
8096 (looking-at org-todo-line-regexp)
8097 (match-string 3))
8098 (t (looking-at org-heading-regexp)
8099 (match-string 2))))))
8101 (defvar orgstruct-mode) ; defined below
8103 (defun org-heading-components ()
8104 "Return the components of the current heading.
8105 This is a list with the following elements:
8106 - the level as an integer
8107 - the reduced level, different if `org-odd-levels-only' is set.
8108 - the TODO keyword, or nil
8109 - the priority character, like ?A, or nil if no priority is given
8110 - the headline text itself, or the tags string if no headline text
8111 - the tags string, or nil."
8112 (save-excursion
8113 (org-back-to-heading t)
8114 (when (let (case-fold-search)
8115 (looking-at
8116 (if orgstruct-mode
8117 org-heading-regexp
8118 org-complex-heading-regexp)))
8119 (if orgstruct-mode
8120 (list (length (match-string 1))
8121 (org-reduced-level (length (match-string 1)))
8124 (match-string 2)
8125 nil)
8126 (list (length (match-string 1))
8127 (org-reduced-level (length (match-string 1)))
8128 (match-string-no-properties 2)
8129 (and (match-end 3) (aref (match-string 3) 2))
8130 (match-string-no-properties 4)
8131 (match-string-no-properties 5))))))
8133 (defun org-get-entry ()
8134 "Get the entry text, after heading, entire subtree."
8135 (save-excursion
8136 (org-back-to-heading t)
8137 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8139 (defun org-edit-headline (&optional heading)
8140 "Edit the current headline.
8141 Set it to HEADING when provided."
8142 (interactive)
8143 (org-with-wide-buffer
8144 (org-back-to-heading t)
8145 (when (looking-at org-complex-heading-regexp)
8146 (let* ((old (match-string-no-properties 4))
8147 (new (save-match-data
8148 (org-trim (or heading (read-string "Edit: " old))))))
8149 (unless (equal old new)
8150 (if old (replace-match new t t nil 4)
8151 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8152 (insert " " new))
8153 (org-set-tags nil t)
8154 (when (looking-at "[ \t]*$") (replace-match "")))))))
8156 (defun org-insert-heading-after-current ()
8157 "Insert a new heading with same level as current, after current subtree."
8158 (interactive)
8159 (org-back-to-heading)
8160 (org-insert-heading)
8161 (org-move-subtree-down)
8162 (end-of-line 1))
8164 (defun org-insert-heading-respect-content (&optional invisible-ok)
8165 "Insert heading with `org-insert-heading-respect-content' set to t."
8166 (interactive)
8167 (org-insert-heading '(4) invisible-ok))
8169 (defun org-insert-todo-heading-respect-content (&optional force-state)
8170 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8171 (interactive)
8172 (org-insert-todo-heading force-state '(4)))
8174 (defun org-insert-todo-heading (arg &optional force-heading)
8175 "Insert a new heading with the same level and TODO state as current heading.
8177 If the heading has no TODO state, or if the state is DONE, use
8178 the first state (TODO by default). Also with one prefix arg,
8179 force first state. With two prefix args, force inserting at the
8180 end of the parent subtree.
8182 When called at a plain list item, insert a new item with an
8183 unchecked check box."
8184 (interactive "P")
8185 (when (or force-heading (not (org-insert-item 'checkbox)))
8186 (org-insert-heading (or (and (equal arg '(16)) '(16))
8187 force-heading))
8188 (save-excursion
8189 (org-back-to-heading)
8190 (outline-previous-heading)
8191 (looking-at org-todo-line-regexp))
8192 (let* ((new-mark-x
8193 (if (or (equal arg '(4))
8194 (not (match-beginning 2))
8195 (member (match-string 2) org-done-keywords))
8196 (car org-todo-keywords-1)
8197 (match-string 2)))
8198 (new-mark
8200 (run-hook-with-args-until-success
8201 'org-todo-get-default-hook new-mark-x nil)
8202 new-mark-x)))
8203 (beginning-of-line 1)
8204 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8205 (if org-treat-insert-todo-heading-as-state-change
8206 (org-todo new-mark)
8207 (insert new-mark " "))))
8208 (when org-provide-todo-statistics
8209 (org-update-parent-todo-statistics))))
8211 (defun org-insert-subheading (arg)
8212 "Insert a new subheading and demote it.
8213 Works for outline headings and for plain lists alike."
8214 (interactive "P")
8215 (org-insert-heading arg)
8216 (cond
8217 ((org-at-heading-p) (org-do-demote))
8218 ((org-at-item-p) (org-indent-item))))
8220 (defun org-insert-todo-subheading (arg)
8221 "Insert a new subheading with TODO keyword or checkbox and demote it.
8222 Works for outline headings and for plain lists alike."
8223 (interactive "P")
8224 (org-insert-todo-heading arg)
8225 (cond
8226 ((org-at-heading-p) (org-do-demote))
8227 ((org-at-item-p) (org-indent-item))))
8229 ;;; Promotion and Demotion
8231 (defvar org-after-demote-entry-hook nil
8232 "Hook run after an entry has been demoted.
8233 The cursor will be at the beginning of the entry.
8234 When a subtree is being demoted, the hook will be called for each node.")
8236 (defvar org-after-promote-entry-hook nil
8237 "Hook run after an entry has been promoted.
8238 The cursor will be at the beginning of the entry.
8239 When a subtree is being promoted, the hook will be called for each node.")
8241 (defun org-promote-subtree ()
8242 "Promote the entire subtree.
8243 See also `org-promote'."
8244 (interactive)
8245 (save-excursion
8246 (org-with-limited-levels (org-map-tree 'org-promote)))
8247 (org-fix-position-after-promote))
8249 (defun org-demote-subtree ()
8250 "Demote the entire subtree.
8251 See `org-demote' and `org-promote'."
8252 (interactive)
8253 (save-excursion
8254 (org-with-limited-levels (org-map-tree 'org-demote)))
8255 (org-fix-position-after-promote))
8257 (defun org-do-promote ()
8258 "Promote the current heading higher up the tree.
8259 If the region is active in `transient-mark-mode', promote all
8260 headings in the region."
8261 (interactive)
8262 (save-excursion
8263 (if (org-region-active-p)
8264 (org-map-region 'org-promote (region-beginning) (region-end))
8265 (org-promote)))
8266 (org-fix-position-after-promote))
8268 (defun org-do-demote ()
8269 "Demote the current heading lower down the tree.
8270 If the region is active in `transient-mark-mode', demote all
8271 headings in the region."
8272 (interactive)
8273 (save-excursion
8274 (if (org-region-active-p)
8275 (org-map-region 'org-demote (region-beginning) (region-end))
8276 (org-demote)))
8277 (org-fix-position-after-promote))
8279 (defun org-fix-position-after-promote ()
8280 "Fix cursor position and indentation after demoting/promoting."
8281 (let ((pos (point)))
8282 (when (save-excursion
8283 (beginning-of-line 1)
8284 (looking-at org-todo-line-regexp)
8285 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8286 (cond ((eobp) (insert " "))
8287 ((eolp) (insert " "))
8288 ((equal (char-after) ?\ ) (forward-char 1))))))
8290 (defun org-current-level ()
8291 "Return the level of the current entry, or nil if before the first headline.
8292 The level is the number of stars at the beginning of the
8293 headline. Use `org-reduced-level' to remove the effect of
8294 `org-odd-levels'. Unlike to `org-outline-level', this function
8295 ignores inlinetasks."
8296 (let ((level (org-with-limited-levels (org-outline-level))))
8297 (and (> level 0) level)))
8299 (defun org-get-previous-line-level ()
8300 "Return the outline depth of the last headline before the current line.
8301 Returns 0 for the first headline in the buffer, and nil if before the
8302 first headline."
8303 (and (org-current-level)
8304 (or (and (/= (line-beginning-position) (point-min))
8305 (save-excursion (beginning-of-line 0) (org-current-level)))
8306 0)))
8308 (defun org-reduced-level (l)
8309 "Compute the effective level of a heading.
8310 This takes into account the setting of `org-odd-levels-only'."
8311 (cond
8312 ((zerop l) 0)
8313 (org-odd-levels-only (1+ (floor (/ l 2))))
8314 (t l)))
8316 (defun org-level-increment ()
8317 "Return the number of stars that will be added or removed at a
8318 time to headlines when structure editing, based on the value of
8319 `org-odd-levels-only'."
8320 (if org-odd-levels-only 2 1))
8322 (defun org-get-valid-level (level &optional change)
8323 "Rectify a level change under the influence of `org-odd-levels-only'
8324 LEVEL is a current level, CHANGE is by how much the level should be
8325 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8326 even level numbers will become the next higher odd number."
8327 (if org-odd-levels-only
8328 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8329 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8330 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8331 (max 1 (+ level (or change 0)))))
8333 (defun org-promote ()
8334 "Promote the current heading higher up the tree."
8335 (org-with-wide-buffer
8336 (org-back-to-heading t)
8337 (let* ((after-change-functions (remq 'flyspell-after-change-function
8338 after-change-functions))
8339 (level (save-match-data (funcall outline-level)))
8340 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8341 (diff (abs (- level (length up-head) -1))))
8342 (cond
8343 ((and (= level 1) org-allow-promoting-top-level-subtree)
8344 (replace-match "# " nil t))
8345 ((= level 1)
8346 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8347 (t (replace-match up-head nil t)))
8348 (unless (= level 1)
8349 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8350 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8351 (run-hooks 'org-after-promote-entry-hook))))
8353 (defun org-demote ()
8354 "Demote the current heading lower down the tree."
8355 (org-with-wide-buffer
8356 (org-back-to-heading t)
8357 (let* ((after-change-functions (remq 'flyspell-after-change-function
8358 after-change-functions))
8359 (level (save-match-data (funcall outline-level)))
8360 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8361 (diff (abs (- level (length down-head) -1))))
8362 (replace-match down-head nil t)
8363 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8364 (when org-adapt-indentation (org-fixup-indentation diff))
8365 (run-hooks 'org-after-demote-entry-hook))))
8367 (defun org-cycle-level ()
8368 "Cycle the level of an empty headline through possible states.
8369 This goes first to child, then to parent, level, then up the hierarchy.
8370 After top level, it switches back to sibling level."
8371 (interactive)
8372 (let ((org-adapt-indentation nil))
8373 (when (org-point-at-end-of-empty-headline)
8374 (setq this-command 'org-cycle-level) ; Only needed for caching
8375 (let ((cur-level (org-current-level))
8376 (prev-level (org-get-previous-line-level)))
8377 (cond
8378 ;; If first headline in file, promote to top-level.
8379 ((= prev-level 0)
8380 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8381 do (org-do-promote)))
8382 ;; If same level as prev, demote one.
8383 ((= prev-level cur-level)
8384 (org-do-demote))
8385 ;; If parent is top-level, promote to top level if not already.
8386 ((= prev-level 1)
8387 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8388 do (org-do-promote)))
8389 ;; If top-level, return to prev-level.
8390 ((= cur-level 1)
8391 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8392 do (org-do-demote)))
8393 ;; If less than prev-level, promote one.
8394 ((< cur-level prev-level)
8395 (org-do-promote))
8396 ;; If deeper than prev-level, promote until higher than
8397 ;; prev-level.
8398 ((> cur-level prev-level)
8399 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8400 do (org-do-promote))))
8401 t))))
8403 (defun org-map-tree (fun)
8404 "Call FUN for every heading underneath the current one."
8405 (org-back-to-heading t)
8406 (let ((level (funcall outline-level)))
8407 (save-excursion
8408 (funcall fun)
8409 (while (and (progn
8410 (outline-next-heading)
8411 (> (funcall outline-level) level))
8412 (not (eobp)))
8413 (funcall fun)))))
8415 (defun org-map-region (fun beg end)
8416 "Call FUN for every heading between BEG and END."
8417 (let ((org-ignore-region t))
8418 (save-excursion
8419 (setq end (copy-marker end))
8420 (goto-char beg)
8421 (when (and (re-search-forward org-outline-regexp-bol nil t)
8422 (< (point) end))
8423 (funcall fun))
8424 (while (and (progn
8425 (outline-next-heading)
8426 (< (point) end))
8427 (not (eobp)))
8428 (funcall fun)))))
8430 (defun org-fixup-indentation (diff)
8431 "Change the indentation in the current entry by DIFF.
8433 DIFF is an integer. Indentation is done according to the
8434 following rules:
8436 - Planning information and property drawers are always indented
8437 according to the new level of the headline;
8439 - Footnote definitions and their contents are ignored;
8441 - Inlinetasks' boundaries are not shifted;
8443 - Empty lines are ignored;
8445 - Other lines' indentation are shifted by DIFF columns, unless
8446 it would introduce a structural change in the document, in
8447 which case no shifting is done at all.
8449 Assume point is at a heading or an inlinetask beginning."
8450 (org-with-wide-buffer
8451 (narrow-to-region (line-beginning-position)
8452 (save-excursion
8453 (if (org-with-limited-levels (org-at-heading-p))
8454 (org-with-limited-levels (outline-next-heading))
8455 (org-inlinetask-goto-end))
8456 (point)))
8457 (forward-line)
8458 ;; Indent properly planning info and property drawer.
8459 (when (looking-at-p org-planning-line-re)
8460 (org-indent-line)
8461 (forward-line))
8462 (when (looking-at org-property-drawer-re)
8463 (goto-char (match-end 0))
8464 (forward-line)
8465 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8466 (catch 'no-shift
8467 (when (zerop diff) (throw 'no-shift nil))
8468 ;; If DIFF is negative, first check if a shift is possible at all
8469 ;; (e.g., it doesn't break structure). This can only happen if
8470 ;; some contents are not properly indented.
8471 (let ((case-fold-search t))
8472 (when (< diff 0)
8473 (let ((diff (- diff))
8474 (forbidden-re (concat org-outline-regexp
8475 "\\|"
8476 (substring org-footnote-definition-re 1))))
8477 (save-excursion
8478 (while (not (eobp))
8479 (cond
8480 ((looking-at-p "[ \t]*$") (forward-line))
8481 ((and (looking-at-p org-footnote-definition-re)
8482 (let ((e (org-element-at-point)))
8483 (and (eq (org-element-type e) 'footnote-definition)
8484 (goto-char (org-element-property :end e))))))
8485 ((looking-at-p org-outline-regexp) (forward-line))
8486 ;; Give up if shifting would move before column 0 or
8487 ;; if it would introduce a headline or a footnote
8488 ;; definition.
8490 (skip-chars-forward " \t")
8491 (let ((ind (current-column)))
8492 (when (or (< ind diff)
8493 (and (= ind diff) (looking-at-p forbidden-re)))
8494 (throw 'no-shift nil)))
8495 ;; Ignore contents of example blocks and source
8496 ;; blocks if their indentation is meant to be
8497 ;; preserved. Jump to block's closing line.
8498 (beginning-of-line)
8499 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8500 (let ((e (org-element-at-point)))
8501 (and (memq (org-element-type e)
8502 '(example-block src-block))
8503 (or org-src-preserve-indentation
8504 (org-element-property :preserve-indent e))
8505 (goto-char (org-element-property :end e))
8506 (progn (skip-chars-backward " \r\t\n")
8507 (beginning-of-line)
8508 t))))
8509 (forward-line))))))))
8510 ;; Shift lines but footnote definitions, inlinetasks boundaries
8511 ;; by DIFF. Also skip contents of source or example blocks
8512 ;; when indentation is meant to be preserved.
8513 (while (not (eobp))
8514 (cond
8515 ((and (looking-at-p org-footnote-definition-re)
8516 (let ((e (org-element-at-point)))
8517 (and (eq (org-element-type e) 'footnote-definition)
8518 (goto-char (org-element-property :end e))))))
8519 ((looking-at-p org-outline-regexp) (forward-line))
8520 ((looking-at-p "[ \t]*$") (forward-line))
8522 (indent-line-to (+ (org-get-indentation) diff))
8523 (beginning-of-line)
8524 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8525 (let ((e (org-element-at-point)))
8526 (and (memq (org-element-type e)
8527 '(example-block src-block))
8528 (or org-src-preserve-indentation
8529 (org-element-property :preserve-indent e))
8530 (goto-char (org-element-property :end e))
8531 (progn (skip-chars-backward " \r\t\n")
8532 (beginning-of-line)
8533 t))))
8534 (forward-line)))))))))
8536 (defun org-convert-to-odd-levels ()
8537 "Convert an Org file with all levels allowed to one with odd levels.
8538 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8539 level 5 etc."
8540 (interactive)
8541 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8542 (let ((outline-level 'org-outline-level)
8543 (org-odd-levels-only nil) n)
8544 (save-excursion
8545 (goto-char (point-min))
8546 (while (re-search-forward "^\\*\\*+ " nil t)
8547 (setq n (- (length (match-string 0)) 2))
8548 (while (>= (setq n (1- n)) 0)
8549 (org-demote))
8550 (end-of-line 1))))))
8552 (defun org-convert-to-oddeven-levels ()
8553 "Convert an Org file with only odd levels to one with odd/even levels.
8554 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8555 file contains a section with an even level, conversion would
8556 destroy the structure of the file. An error is signaled in this
8557 case."
8558 (interactive)
8559 (goto-char (point-min))
8560 ;; First check if there are no even levels
8561 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8562 (org-show-set-visibility 'canonical)
8563 (error "Not all levels are odd in this file. Conversion not possible"))
8564 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8565 (let ((outline-regexp org-outline-regexp)
8566 (outline-level 'org-outline-level)
8567 (org-odd-levels-only nil) n)
8568 (save-excursion
8569 (goto-char (point-min))
8570 (while (re-search-forward "^\\*\\*+ " nil t)
8571 (setq n (/ (1- (length (match-string 0))) 2))
8572 (while (>= (setq n (1- n)) 0)
8573 (org-promote))
8574 (end-of-line 1))))))
8576 (defun org-tr-level (n)
8577 "Make N odd if required."
8578 (if org-odd-levels-only (1+ (/ n 2)) n))
8580 ;;; Vertical tree motion, cutting and pasting of subtrees
8582 (defun org-move-subtree-up (&optional arg)
8583 "Move the current subtree up past ARG headlines of the same level."
8584 (interactive "p")
8585 (org-move-subtree-down (- (prefix-numeric-value arg))))
8587 (defun org-move-subtree-down (&optional arg)
8588 "Move the current subtree down past ARG headlines of the same level."
8589 (interactive "p")
8590 (setq arg (prefix-numeric-value arg))
8591 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8592 'org-get-last-sibling))
8593 (ins-point (make-marker))
8594 (cnt (abs arg))
8595 (col (current-column))
8596 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8597 ;; Select the tree
8598 (org-back-to-heading)
8599 (setq beg0 (point))
8600 (save-excursion
8601 (setq ne-beg (org-back-over-empty-lines))
8602 (setq beg (point)))
8603 (save-match-data
8604 (save-excursion (outline-end-of-heading)
8605 (setq folded (outline-invisible-p)))
8606 (progn (org-end-of-subtree nil t)
8607 (unless (eobp) (backward-char))))
8608 (outline-next-heading)
8609 (setq ne-end (org-back-over-empty-lines))
8610 (setq end (point))
8611 (goto-char beg0)
8612 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8613 ;; include less whitespace
8614 (save-excursion
8615 (goto-char beg)
8616 (forward-line (- ne-beg ne-end))
8617 (setq beg (point))))
8618 ;; Find insertion point, with error handling
8619 (while (> cnt 0)
8620 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8621 (progn (goto-char beg0)
8622 (user-error "Cannot move past superior level or buffer limit")))
8623 (setq cnt (1- cnt)))
8624 (when (> arg 0)
8625 ;; Moving forward - still need to move over subtree
8626 (org-end-of-subtree t t)
8627 (save-excursion
8628 (org-back-over-empty-lines)
8629 (or (bolp) (newline))))
8630 (setq ne-ins (org-back-over-empty-lines))
8631 (move-marker ins-point (point))
8632 (setq txt (buffer-substring beg end))
8633 (org-save-markers-in-region beg end)
8634 (delete-region beg end)
8635 (org-remove-empty-overlays-at beg)
8636 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8637 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8638 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8639 (let ((bbb (point)))
8640 (insert-before-markers txt)
8641 (org-reinstall-markers-in-region bbb)
8642 (move-marker ins-point bbb))
8643 (or (bolp) (insert "\n"))
8644 (setq ins-end (point))
8645 (goto-char ins-point)
8646 (org-skip-whitespace)
8647 (when (and (< arg 0)
8648 (org-first-sibling-p)
8649 (> ne-ins ne-beg))
8650 ;; Move whitespace back to beginning
8651 (save-excursion
8652 (goto-char ins-end)
8653 (let ((kill-whole-line t))
8654 (kill-line (- ne-ins ne-beg)) (point)))
8655 (insert (make-string (- ne-ins ne-beg) ?\n)))
8656 (move-marker ins-point nil)
8657 (if folded
8658 (outline-hide-subtree)
8659 (org-show-entry)
8660 (org-show-children)
8661 (org-cycle-hide-drawers 'children))
8662 (org-clean-visibility-after-subtree-move)
8663 ;; move back to the initial column we were at
8664 (move-to-column col)))
8666 (defvar org-subtree-clip ""
8667 "Clipboard for cut and paste of subtrees.
8668 This is actually only a copy of the kill, because we use the normal kill
8669 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8671 (defvar org-subtree-clip-folded nil
8672 "Was the last copied subtree folded?
8673 This is used to fold the tree back after pasting.")
8675 (defun org-cut-subtree (&optional n)
8676 "Cut the current subtree into the clipboard.
8677 With prefix arg N, cut this many sequential subtrees.
8678 This is a short-hand for marking the subtree and then cutting it."
8679 (interactive "p")
8680 (org-copy-subtree n 'cut))
8682 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8683 "Copy the current subtree it in the clipboard.
8684 With prefix arg N, copy this many sequential subtrees.
8685 This is a short-hand for marking the subtree and then copying it.
8686 If CUT is non-nil, actually cut the subtree.
8687 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8688 of some markers in the region, even if CUT is non-nil. This is
8689 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8690 (interactive "p")
8691 (let (beg end folded (beg0 (point)))
8692 (if (called-interactively-p 'any)
8693 (org-back-to-heading nil) ; take what looks like a subtree
8694 (org-back-to-heading t)) ; take what is really there
8695 (setq beg (point))
8696 (skip-chars-forward " \t\r\n")
8697 (save-match-data
8698 (if nosubtrees
8699 (outline-next-heading)
8700 (save-excursion (outline-end-of-heading)
8701 (setq folded (outline-invisible-p)))
8702 (ignore-errors (org-forward-heading-same-level (1- n) t))
8703 (org-end-of-subtree t t)))
8704 ;; Include the end of an inlinetask
8705 (when (and (featurep 'org-inlinetask)
8706 (looking-at-p (concat (org-inlinetask-outline-regexp)
8707 "END[ \t]*$")))
8708 (end-of-line))
8709 (setq end (point))
8710 (goto-char beg0)
8711 (when (> end beg)
8712 (setq org-subtree-clip-folded folded)
8713 (when (or cut force-store-markers)
8714 (org-save-markers-in-region beg end))
8715 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8716 (setq org-subtree-clip (current-kill 0))
8717 (message "%s: Subtree(s) with %d characters"
8718 (if cut "Cut" "Copied")
8719 (length org-subtree-clip)))))
8721 (defun org-paste-subtree (&optional level tree for-yank remove)
8722 "Paste the clipboard as a subtree, with modification of headline level.
8723 The entire subtree is promoted or demoted in order to match a new headline
8724 level.
8726 If the cursor is at the beginning of a headline, the same level as
8727 that headline is used to paste the tree.
8729 If not, the new level is derived from the *visible* headings
8730 before and after the insertion point, and taken to be the inferior headline
8731 level of the two. So if the previous visible heading is level 3 and the
8732 next is level 4 (or vice versa), level 4 will be used for insertion.
8733 This makes sure that the subtree remains an independent subtree and does
8734 not swallow low level entries.
8736 You can also force a different level, either by using a numeric prefix
8737 argument, or by inserting the heading marker by hand. For example, if the
8738 cursor is after \"*****\", then the tree will be shifted to level 5.
8740 If optional TREE is given, use this text instead of the kill ring.
8742 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8743 move back over whitespace before inserting, and move point to the end of
8744 the inserted text when done.
8746 When REMOVE is non-nil, remove the subtree from the clipboard."
8747 (interactive "P")
8748 (setq tree (or tree (and kill-ring (current-kill 0))))
8749 (unless (org-kill-is-subtree-p tree)
8750 (user-error "%s"
8751 (substitute-command-keys
8752 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8753 (org-with-limited-levels
8754 (let* ((visp (not (outline-invisible-p)))
8755 (txt tree)
8756 (^re_ "\\(\\*+\\)[ \t]*")
8757 (old-level (if (string-match org-outline-regexp-bol txt)
8758 (- (match-end 0) (match-beginning 0) 1)
8759 -1))
8760 (force-level (cond (level (prefix-numeric-value level))
8761 ((and (looking-at "[ \t]*$")
8762 (string-match
8763 "^\\*+$" (buffer-substring
8764 (point-at-bol) (point))))
8765 (- (match-end 0) (match-beginning 0)))
8766 ((and (bolp)
8767 (looking-at org-outline-regexp))
8768 (- (match-end 0) (point) 1))))
8769 (previous-level (save-excursion
8770 (condition-case nil
8771 (progn
8772 (outline-previous-visible-heading 1)
8773 (if (looking-at ^re_)
8774 (- (match-end 0) (match-beginning 0) 1)
8776 (error 1))))
8777 (next-level (save-excursion
8778 (condition-case nil
8779 (progn
8780 (or (looking-at org-outline-regexp)
8781 (outline-next-visible-heading 1))
8782 (if (looking-at ^re_)
8783 (- (match-end 0) (match-beginning 0) 1)
8785 (error 1))))
8786 (new-level (or force-level (max previous-level next-level)))
8787 (shift (if (or (= old-level -1)
8788 (= new-level -1)
8789 (= old-level new-level))
8791 (- new-level old-level)))
8792 (delta (if (> shift 0) -1 1))
8793 (func (if (> shift 0) 'org-demote 'org-promote))
8794 (org-odd-levels-only nil)
8795 beg end newend)
8796 ;; Remove the forced level indicator
8797 (when force-level
8798 (delete-region (point-at-bol) (point)))
8799 ;; Paste
8800 (beginning-of-line (if (bolp) 1 2))
8801 (setq beg (point))
8802 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8803 (insert-before-markers txt)
8804 (unless (string-suffix-p "\n" txt) (insert "\n"))
8805 (setq newend (point))
8806 (org-reinstall-markers-in-region beg)
8807 (setq end (point))
8808 (goto-char beg)
8809 (skip-chars-forward " \t\n\r")
8810 (setq beg (point))
8811 (when (and (outline-invisible-p) visp)
8812 (save-excursion (outline-show-heading)))
8813 ;; Shift if necessary
8814 (unless (= shift 0)
8815 (save-restriction
8816 (narrow-to-region beg end)
8817 (while (not (= shift 0))
8818 (org-map-region func (point-min) (point-max))
8819 (setq shift (+ delta shift)))
8820 (goto-char (point-min))
8821 (setq newend (point-max))))
8822 (when (or (called-interactively-p 'interactive) for-yank)
8823 (message "Clipboard pasted as level %d subtree" new-level))
8824 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8825 kill-ring
8826 (eq org-subtree-clip (current-kill 0))
8827 org-subtree-clip-folded)
8828 ;; The tree was folded before it was killed/copied
8829 (outline-hide-subtree))
8830 (and for-yank (goto-char newend))
8831 (and remove (setq kill-ring (cdr kill-ring))))))
8833 (defun org-kill-is-subtree-p (&optional txt)
8834 "Check if the current kill is an outline subtree, or a set of trees.
8835 Returns nil if kill does not start with a headline, or if the first
8836 headline level is not the largest headline level in the tree.
8837 So this will actually accept several entries of equal levels as well,
8838 which is OK for `org-paste-subtree'.
8839 If optional TXT is given, check this string instead of the current kill."
8840 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8841 (re (org-get-limited-outline-regexp))
8842 (^re (concat "^" re))
8843 (start-level (and kill
8844 (string-match
8845 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8846 kill)
8847 (- (match-end 2) (match-beginning 2) 1)))
8848 (start (1+ (or (match-beginning 2) -1))))
8849 (if (not start-level)
8850 (progn
8851 nil) ;; does not even start with a heading
8852 (catch 'exit
8853 (while (setq start (string-match ^re kill (1+ start)))
8854 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8855 (throw 'exit nil)))
8856 t))))
8858 (defvar org-markers-to-move nil
8859 "Markers that should be moved with a cut-and-paste operation.
8860 Those markers are stored together with their positions relative to
8861 the start of the region.")
8863 (defun org-save-markers-in-region (beg end)
8864 "Check markers in region.
8865 If these markers are between BEG and END, record their position relative
8866 to BEG, so that after moving the block of text, we can put the markers back
8867 into place.
8868 This function gets called just before an entry or tree gets cut from the
8869 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8870 called immediately, to move the markers with the entries."
8871 (setq org-markers-to-move nil)
8872 (when (featurep 'org-clock)
8873 (org-clock-save-markers-for-cut-and-paste beg end))
8874 (when (featurep 'org-agenda)
8875 (org-agenda-save-markers-for-cut-and-paste beg end)))
8877 (defun org-check-and-save-marker (marker beg end)
8878 "Check if MARKER is between BEG and END.
8879 If yes, remember the marker and the distance to BEG."
8880 (when (and (marker-buffer marker)
8881 (equal (marker-buffer marker) (current-buffer))
8882 (>= marker beg) (< marker end))
8883 (push (cons marker (- marker beg)) org-markers-to-move)))
8885 (defun org-reinstall-markers-in-region (beg)
8886 "Move all remembered markers to their position relative to BEG."
8887 (dolist (x org-markers-to-move)
8888 (move-marker (car x) (+ beg (cdr x))))
8889 (setq org-markers-to-move nil))
8891 (defun org-narrow-to-subtree ()
8892 "Narrow buffer to the current subtree."
8893 (interactive)
8894 (save-excursion
8895 (save-match-data
8896 (org-with-limited-levels
8897 (narrow-to-region
8898 (progn (org-back-to-heading t) (point))
8899 (progn (org-end-of-subtree t t)
8900 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8901 (point)))))))
8903 (defun org-narrow-to-block ()
8904 "Narrow buffer to the current block."
8905 (interactive)
8906 (let* ((case-fold-search t)
8907 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8908 "^[ \t]*#\\+end_.*")))
8909 (if blockp
8910 (narrow-to-region (car blockp) (cdr blockp))
8911 (user-error "Not in a block"))))
8913 (defun org-clone-subtree-with-time-shift (n &optional shift)
8914 "Clone the task (subtree) at point N times.
8915 The clones will be inserted as siblings.
8917 In interactive use, the user will be prompted for the number of
8918 clones to be produced. If the entry has a timestamp, the user
8919 will also be prompted for a time shift, which may be a repeater
8920 as used in time stamps, for example `+3d'. To disable this,
8921 you can call the function with a universal prefix argument.
8923 When a valid repeater is given and the entry contains any time
8924 stamps, the clones will become a sequence in time, with time
8925 stamps in the subtree shifted for each clone produced. If SHIFT
8926 is nil or the empty string, time stamps will be left alone. The
8927 ID property of the original subtree is removed.
8929 In each clone, all the CLOCK entries will be removed. This
8930 prevents Org from considering that the clocked times overlap.
8932 If the original subtree did contain time stamps with a repeater,
8933 the following will happen:
8934 - the repeater will be removed in each clone
8935 - an additional clone will be produced, with the current, unshifted
8936 date(s) in the entry.
8937 - the original entry will be placed *after* all the clones, with
8938 repeater intact.
8939 - the start days in the repeater in the original entry will be shifted
8940 to past the last clone.
8941 In this way you can spell out a number of instances of a repeating task,
8942 and still retain the repeater to cover future instances of the task.
8944 As described above, N+1 clones are produced when the original
8945 subtree has a repeater. Setting N to 0, then, can be used to
8946 remove the repeater from a subtree and create a shifted clone
8947 with the original repeater."
8948 (interactive "nNumber of clones to produce: ")
8949 (let ((shift
8950 (or shift
8951 (if (and (not (equal current-prefix-arg '(4)))
8952 (save-excursion
8953 (re-search-forward org-ts-regexp-both
8954 (save-excursion
8955 (org-end-of-subtree t)
8956 (point)) t)))
8957 (read-from-minibuffer
8958 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8959 ""))) ;; No time shift
8960 (n-no-remove -1)
8961 (drawer-re org-drawer-regexp)
8962 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8963 beg end template task idprop
8964 shift-n shift-what doshift nmin nmax)
8965 (unless (wholenump n)
8966 (user-error "Invalid number of replications %s" n))
8967 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8968 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8969 shift)))
8970 (user-error "Invalid shift specification %s" shift))
8971 (when doshift
8972 (setq shift-n (string-to-number (match-string 1 shift))
8973 shift-what (cdr (assoc (match-string 2 shift)
8974 '(("d" . day) ("w" . week)
8975 ("m" . month) ("y" . year))))))
8976 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8977 (setq nmin 1 nmax n)
8978 (org-back-to-heading t)
8979 (setq beg (point))
8980 (setq idprop (org-entry-get nil "ID"))
8981 (org-end-of-subtree t t)
8982 (or (bolp) (insert "\n"))
8983 (setq end (point))
8984 (setq template (buffer-substring beg end))
8985 (when (and doshift
8986 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8987 (delete-region beg end)
8988 (setq end beg)
8989 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8990 (goto-char end)
8991 (cl-loop for n from nmin to nmax do
8992 ;; prepare clone
8993 (with-temp-buffer
8994 (insert template)
8995 (org-mode)
8996 (goto-char (point-min))
8997 (org-show-subtree)
8998 (and idprop (if org-clone-delete-id
8999 (org-entry-delete nil "ID")
9000 (org-id-get-create t)))
9001 (unless (= n 0)
9002 (while (re-search-forward org-clock-re nil t)
9003 (kill-whole-line))
9004 (goto-char (point-min))
9005 (while (re-search-forward drawer-re nil t)
9006 (org-remove-empty-drawer-at (point))))
9007 (goto-char (point-min))
9008 (when doshift
9009 (while (re-search-forward org-ts-regexp-both nil t)
9010 (org-timestamp-change (* n shift-n) shift-what))
9011 (unless (= n n-no-remove)
9012 (goto-char (point-min))
9013 (while (re-search-forward org-ts-regexp nil t)
9014 (save-excursion
9015 (goto-char (match-beginning 0))
9016 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
9017 (delete-region (match-beginning 1) (match-end 1)))))))
9018 (setq task (buffer-string)))
9019 (insert task))
9020 (goto-char beg)))
9022 ;;; Outline Sorting
9024 (defun org-sort (with-case)
9025 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
9026 Optional argument WITH-CASE means sort case-sensitively."
9027 (interactive "P")
9028 (cond
9029 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
9030 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
9032 (org-call-with-arg 'org-sort-entries with-case))))
9034 (defun org-sort-remove-invisible (s)
9035 "Remove invisible links from string S."
9036 (remove-text-properties 0 (length s) org-rm-props s)
9037 (while (string-match org-bracket-link-regexp s)
9038 (setq s (replace-match (if (match-end 2)
9039 (match-string 3 s)
9040 (match-string 1 s))
9041 t t s)))
9042 (let ((st (format " %s " s)))
9043 (while (string-match org-emph-re st)
9044 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
9045 (setq s (substring st 1 -1)))
9048 (defvar org-priority-regexp) ; defined later in the file
9050 (defvar org-after-sorting-entries-or-items-hook nil
9051 "Hook that is run after a bunch of entries or items have been sorted.
9052 When children are sorted, the cursor is in the parent line when this
9053 hook gets called. When a region or a plain list is sorted, the cursor
9054 will be in the first entry of the sorted region/list.")
9056 (defun org-sort-entries
9057 (&optional with-case sorting-type getkey-func compare-func property)
9058 "Sort entries on a certain level of an outline tree.
9059 If there is an active region, the entries in the region are sorted.
9060 Else, if the cursor is before the first entry, sort the top-level items.
9061 Else, the children of the entry at point are sorted.
9063 Sorting can be alphabetically, numerically, by date/time as given by
9064 a time stamp, by a property, by priority order, or by a custom function.
9066 The command prompts for the sorting type unless it has been given to the
9067 function through the SORTING-TYPE argument, which needs to be a character,
9068 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9069 the precise meaning of each character:
9071 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9072 c By creation time, which is assumed to be the first inactive time stamp
9073 at the beginning of a line.
9074 d By deadline date/time.
9075 k By clocking time.
9076 n Numerically, by converting the beginning of the entry/item to a number.
9077 o By order of TODO keywords.
9078 p By priority according to the cookie.
9079 r By the value of a property.
9080 s By scheduled date/time.
9081 t By date/time, either the first active time stamp in the entry, or, if
9082 none exist, by the first inactive one.
9084 Capital letters will reverse the sort order.
9086 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9087 called with point at the beginning of the record. It must return either
9088 a string or a number that should serve as the sorting key for that record.
9090 Comparing entries ignores case by default. However, with an optional argument
9091 WITH-CASE, the sorting considers case as well.
9093 Sorting is done against the visible part of the headlines, it ignores hidden
9094 links.
9096 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
9097 (interactive "P")
9098 (let ((case-func (if with-case 'identity 'downcase))
9099 (cmstr
9100 ;; The clock marker is lost when using `sort-subr', let's
9101 ;; store the clocking string.
9102 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9103 (save-excursion
9104 (goto-char org-clock-marker)
9105 (buffer-substring-no-properties (line-beginning-position)
9106 (point)))))
9107 start beg end stars re re2
9108 txt what tmp)
9109 ;; Find beginning and end of region to sort
9110 (cond
9111 ((org-region-active-p)
9112 ;; we will sort the region
9113 (setq end (region-end)
9114 what "region")
9115 (goto-char (region-beginning))
9116 (unless (org-at-heading-p) (outline-next-heading))
9117 (setq start (point)))
9118 ((or (org-at-heading-p)
9119 (ignore-errors (progn (org-back-to-heading) t)))
9120 ;; we will sort the children of the current headline
9121 (org-back-to-heading)
9122 (setq start (point)
9123 end (progn (org-end-of-subtree t t)
9124 (or (bolp) (insert "\n"))
9125 (when (>= (org-back-over-empty-lines) 1)
9126 (forward-line 1))
9127 (point))
9128 what "children")
9129 (goto-char start)
9130 (outline-show-subtree)
9131 (outline-next-heading))
9133 ;; we will sort the top-level entries in this file
9134 (goto-char (point-min))
9135 (or (org-at-heading-p) (outline-next-heading))
9136 (setq start (point))
9137 (goto-char (point-max))
9138 (beginning-of-line 1)
9139 (when (looking-at ".*?\\S-")
9140 ;; File ends in a non-white line
9141 (end-of-line 1)
9142 (insert "\n"))
9143 (setq end (point-max))
9144 (setq what "top-level")
9145 (goto-char start)
9146 (outline-show-all)))
9148 (setq beg (point))
9149 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9151 (looking-at "\\(\\*+\\)")
9152 (setq stars (match-string 1)
9153 re (concat "^" (regexp-quote stars) " +")
9154 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9155 txt (buffer-substring beg end))
9156 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9157 (when (and (not (equal stars "*")) (string-match re2 txt))
9158 (user-error "Region to sort contains a level above the first entry"))
9160 (unless sorting-type
9161 (message
9162 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9163 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9164 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9165 what)
9166 (setq sorting-type (read-char-exclusive))
9168 (unless getkey-func
9169 (and (= (downcase sorting-type) ?f)
9170 (setq getkey-func
9171 (completing-read "Sort using function: "
9172 obarray 'fboundp t nil nil))
9173 (setq getkey-func (intern getkey-func))))
9175 (and (= (downcase sorting-type) ?r)
9176 (not property)
9177 (setq property
9178 (completing-read "Property: "
9179 (mapcar #'list (org-buffer-property-keys t))
9180 nil t))))
9182 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9183 (message "Sorting entries...")
9185 (save-restriction
9186 (narrow-to-region start end)
9187 (let ((dcst (downcase sorting-type))
9188 (case-fold-search nil)
9189 (now (current-time)))
9190 (sort-subr
9191 (/= dcst sorting-type)
9192 ;; This function moves to the beginning character of the "record" to
9193 ;; be sorted.
9194 (lambda nil
9195 (if (re-search-forward re nil t)
9196 (goto-char (match-beginning 0))
9197 (goto-char (point-max))))
9198 ;; This function moves to the last character of the "record" being
9199 ;; sorted.
9200 (lambda nil
9201 (save-match-data
9202 (condition-case nil
9203 (outline-forward-same-level 1)
9204 (error
9205 (goto-char (point-max))))))
9206 ;; This function returns the value that gets sorted against.
9207 (lambda nil
9208 (cond
9209 ((= dcst ?n)
9210 (if (looking-at org-complex-heading-regexp)
9211 (string-to-number (org-sort-remove-invisible (match-string 4)))
9212 nil))
9213 ((= dcst ?a)
9214 (if (looking-at org-complex-heading-regexp)
9215 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9216 nil))
9217 ((= dcst ?k)
9218 (or (get-text-property (point) :org-clock-minutes) 0))
9219 ((= dcst ?t)
9220 (let ((end (save-excursion (outline-next-heading) (point))))
9221 (if (or (re-search-forward org-ts-regexp end t)
9222 (re-search-forward org-ts-regexp-both end t))
9223 (org-time-string-to-seconds (match-string 0))
9224 (float-time now))))
9225 ((= dcst ?c)
9226 (let ((end (save-excursion (outline-next-heading) (point))))
9227 (if (re-search-forward
9228 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9229 end t)
9230 (org-time-string-to-seconds (match-string 0))
9231 (float-time now))))
9232 ((= dcst ?s)
9233 (let ((end (save-excursion (outline-next-heading) (point))))
9234 (if (re-search-forward org-scheduled-time-regexp end t)
9235 (org-time-string-to-seconds (match-string 1))
9236 (float-time now))))
9237 ((= dcst ?d)
9238 (let ((end (save-excursion (outline-next-heading) (point))))
9239 (if (re-search-forward org-deadline-time-regexp end t)
9240 (org-time-string-to-seconds (match-string 1))
9241 (float-time now))))
9242 ((= dcst ?p)
9243 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9244 (string-to-char (match-string 2))
9245 org-default-priority))
9246 ((= dcst ?r)
9247 (or (org-entry-get nil property) ""))
9248 ((= dcst ?o)
9249 (when (looking-at org-complex-heading-regexp)
9250 (let* ((m (match-string 2))
9251 (s (if (member m org-done-keywords) '- '+)))
9252 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9253 ((= dcst ?f)
9254 (if getkey-func
9255 (progn
9256 (setq tmp (funcall getkey-func))
9257 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9258 tmp)
9259 (error "Invalid key function `%s'" getkey-func)))
9260 (t (error "Invalid sorting type `%c'" sorting-type))))
9262 (cond
9263 ((= dcst ?a) 'string<)
9264 ((= dcst ?f) compare-func)
9265 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9266 (run-hooks 'org-after-sorting-entries-or-items-hook)
9267 ;; Reset the clock marker if needed
9268 (when cmstr
9269 (save-excursion
9270 (goto-char start)
9271 (search-forward cmstr nil t)
9272 (move-marker org-clock-marker (point))))
9273 (message "Sorting entries...done")))
9275 ;;; The orgstruct minor mode
9277 ;; Define a minor mode which can be used in other modes in order to
9278 ;; integrate the Org mode structure editing commands.
9280 ;; This is really a hack, because the Org mode structure commands use
9281 ;; keys which normally belong to the major mode. Here is how it
9282 ;; works: The minor mode defines all the keys necessary to operate the
9283 ;; structure commands, but wraps the commands into a function which
9284 ;; tests if the cursor is currently at a headline or a plain list
9285 ;; item. If that is the case, the structure command is used,
9286 ;; temporarily setting many Org mode variables like regular
9287 ;; expressions for filling etc. However, when any of those keys is
9288 ;; used at a different location, function uses `key-binding' to look
9289 ;; up if the key has an associated command in another currently active
9290 ;; keymap (minor modes, major mode, global), and executes that
9291 ;; command. There might be problems if any of the keys is otherwise
9292 ;; used as a prefix key.
9294 (defcustom orgstruct-heading-prefix-regexp ""
9295 "Regexp that matches the custom prefix of Org headlines in
9296 orgstruct(++)-mode."
9297 :group 'org
9298 :version "24.4"
9299 :package-version '(Org . "8.3")
9300 :type 'regexp)
9301 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9303 (defcustom orgstruct-setup-hook nil
9304 "Hook run after orgstruct-mode-map is filled."
9305 :group 'org
9306 :version "24.4"
9307 :package-version '(Org . "8.0")
9308 :type 'hook)
9310 (defvar orgstruct-initialized nil)
9312 (defvar org-local-vars nil
9313 "List of local variables, for use by `orgstruct-mode'.")
9315 ;;;###autoload
9316 (define-minor-mode orgstruct-mode
9317 "Toggle the minor mode `orgstruct-mode'.
9318 This mode is for using Org mode structure commands in other
9319 modes. The following keys behave as if Org mode were active, if
9320 the cursor is on a headline, or on a plain list item (both as
9321 defined by Org mode)."
9322 nil " OrgStruct" (make-sparse-keymap)
9323 (funcall (if orgstruct-mode
9324 'add-to-invisibility-spec
9325 'remove-from-invisibility-spec)
9326 '(outline . t))
9327 (when orgstruct-mode
9328 (org-load-modules-maybe)
9329 (unless orgstruct-initialized
9330 (orgstruct-setup)
9331 (setq orgstruct-initialized t))))
9333 ;;;###autoload
9334 (defun turn-on-orgstruct ()
9335 "Unconditionally turn on `orgstruct-mode'."
9336 (orgstruct-mode 1))
9338 (defvar-local orgstruct-is-++ nil
9339 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9340 (defvar-local org-fb-vars nil)
9341 (defun orgstruct++-mode (&optional arg)
9342 "Toggle `orgstruct-mode', the enhanced version of it.
9343 In addition to setting orgstruct-mode, this also exports all
9344 indentation and autofilling variables from Org mode into the
9345 buffer. It will also recognize item context in multiline items."
9346 (interactive "P")
9347 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9348 (if (< arg 1)
9349 (progn (orgstruct-mode -1)
9350 (dolist (v org-fb-vars)
9351 (set (make-local-variable (car v))
9352 (if (eq (car-safe (cadr v)) 'quote)
9353 (cl-cadadr v)
9354 (nth 1 v)))))
9355 (orgstruct-mode 1)
9356 (setq org-fb-vars nil)
9357 (unless org-local-vars
9358 (setq org-local-vars (org-get-local-variables)))
9359 (let (var val)
9360 (dolist (x org-local-vars)
9361 (when (string-match
9362 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9363 \\|fill-prefix\\|indent-\\)"
9364 (symbol-name (car x)))
9365 (setq var (car x) val (nth 1 x))
9366 (push (list var `(quote ,(eval var))) org-fb-vars)
9367 (set (make-local-variable var)
9368 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9369 (setq-local orgstruct-is-++ t))))
9371 ;;;###autoload
9372 (defun turn-on-orgstruct++ ()
9373 "Unconditionally turn on `orgstruct++-mode'."
9374 (orgstruct++-mode 1))
9376 (defun orgstruct-error ()
9377 "Error when there is no default binding for a structure key."
9378 (interactive)
9379 (funcall (if (fboundp 'user-error)
9380 'user-error
9381 'error)
9382 "This key has no function outside structure elements"))
9384 (defun orgstruct-setup ()
9385 "Setup orgstruct keymap."
9386 (dolist (cell '((org-demote . t)
9387 (org-metaleft . t)
9388 (org-metaright . t)
9389 (org-promote . t)
9390 (org-shiftmetaleft . t)
9391 (org-shiftmetaright . t)
9392 org-backward-element
9393 org-backward-heading-same-level
9394 org-ctrl-c-ret
9395 org-ctrl-c-minus
9396 org-ctrl-c-star
9397 org-cycle
9398 org-force-cycle-archived
9399 org-forward-heading-same-level
9400 org-insert-heading
9401 org-insert-heading-respect-content
9402 org-kill-note-or-show-branches
9403 org-mark-subtree
9404 org-meta-return
9405 org-metadown
9406 org-metaup
9407 org-narrow-to-subtree
9408 org-promote-subtree
9409 org-reveal
9410 org-shiftdown
9411 org-shiftleft
9412 org-shiftmetadown
9413 org-shiftmetaup
9414 org-shiftright
9415 org-shifttab
9416 org-shifttab
9417 org-shiftup
9418 org-show-children
9419 org-show-subtree
9420 org-sort
9421 org-up-element
9422 outline-demote
9423 outline-next-visible-heading
9424 outline-previous-visible-heading
9425 outline-promote
9426 outline-up-heading))
9427 (let ((f (or (car-safe cell) cell))
9428 (disable-when-heading-prefix (cdr-safe cell)))
9429 (when (fboundp f)
9430 (let ((new-bindings))
9431 (dolist (binding (nconc (where-is-internal f org-mode-map)
9432 (where-is-internal f outline-mode-map)))
9433 (push binding new-bindings)
9434 ;; TODO use local-function-key-map
9435 (dolist (rep '(("<tab>" . "TAB")
9436 ("<return>" . "RET")
9437 ("<escape>" . "ESC")
9438 ("<delete>" . "DEL")))
9439 (setq binding (read-kbd-macro
9440 (let ((case-fold-search))
9441 (replace-regexp-in-string
9442 (regexp-quote (cdr rep))
9443 (car rep)
9444 (key-description binding)))))
9445 (cl-pushnew binding new-bindings :test 'equal)))
9446 (dolist (binding new-bindings)
9447 (let ((key (lookup-key orgstruct-mode-map binding)))
9448 (when (or (not key) (numberp key))
9449 (ignore-errors
9450 (org-defkey orgstruct-mode-map
9451 binding
9452 (orgstruct-make-binding
9453 f binding disable-when-heading-prefix))))))))))
9454 (run-hooks 'orgstruct-setup-hook))
9456 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9457 "Create a function for binding in the structure minor mode.
9458 FUN is the command to call inside a table. KEY is the key that
9459 should be checked in for a command to execute outside of tables.
9460 Non-nil `disable-when-heading-prefix' means to disable the command
9461 if `orgstruct-heading-prefix-regexp' is not empty."
9462 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9463 (let ((nname name)
9464 (i 0))
9465 (while (fboundp (intern nname))
9466 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9467 (setq name (intern nname)))
9468 (eval
9469 (let ((bindings '((org-heading-regexp
9470 (concat "^"
9471 orgstruct-heading-prefix-regexp
9472 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9473 (org-outline-regexp
9474 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9475 (org-outline-regexp-bol
9476 (concat "^" org-outline-regexp))
9477 (outline-regexp org-outline-regexp)
9478 (outline-heading-end-regexp "\n")
9479 (outline-level 'org-outline-level)
9480 (outline-heading-alist))))
9481 `(defun ,name (arg)
9482 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9483 "Outside of structure, run the binding of `"
9484 (key-description key) "'."
9485 (when disable-when-heading-prefix
9486 (concat
9487 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9488 "back to the default binding due to limitations of Org's implementation of\n"
9489 "`" (symbol-name fun) "'.")))
9490 (interactive "p")
9491 (let* ((disable
9492 ,(and disable-when-heading-prefix
9493 '(not (string= orgstruct-heading-prefix-regexp ""))))
9494 (fallback
9495 (or disable
9496 (not
9497 (let* ,bindings
9498 (org-context-p 'headline 'item
9499 ,(when (memq fun
9500 '(org-insert-heading
9501 org-insert-heading-respect-content
9502 org-meta-return))
9503 '(when orgstruct-is-++
9504 'item-body))))))))
9505 (if fallback
9506 (let* ((orgstruct-mode)
9507 (binding
9508 (let ((key ,key))
9509 (catch 'exit
9510 (dolist
9511 (rep
9512 '(nil
9513 ("<\\([^>]*\\)tab>" . "\\1TAB")
9514 ("<\\([^>]*\\)return>" . "\\1RET")
9515 ("<\\([^>]*\\)escape>" . "\\1ESC")
9516 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9517 nil)
9518 (when rep
9519 (setq key (read-kbd-macro
9520 (let ((case-fold-search))
9521 (replace-regexp-in-string
9522 (car rep)
9523 (cdr rep)
9524 (key-description key))))))
9525 (when (key-binding key)
9526 (throw 'exit (key-binding key))))))))
9527 (if (keymapp binding)
9528 (org-set-transient-map binding)
9529 (let ((func (or binding
9530 (unless disable
9531 'orgstruct-error))))
9532 (when func
9533 (call-interactively func)))))
9534 (org-run-like-in-org-mode
9535 (lambda ()
9536 (interactive)
9537 (let* ,bindings
9538 (call-interactively ',fun)))))))))
9539 name))
9541 (defun org-contextualize-keys (alist contexts)
9542 "Return valid elements in ALIST depending on CONTEXTS.
9544 `org-agenda-custom-commands' or `org-capture-templates' are the
9545 values used for ALIST, and `org-agenda-custom-commands-contexts'
9546 or `org-capture-templates-contexts' are the associated contexts
9547 definitions."
9548 (let ((contexts
9549 ;; normalize contexts
9550 (mapcar
9551 (lambda(c) (cond ((listp (cadr c))
9552 (list (car c) (car c) (nth 1 c)))
9553 ((string= "" (cadr c))
9554 (list (car c) (car c) (nth 2 c)))
9555 (t c)))
9556 contexts))
9557 (a alist) r s)
9558 ;; loop over all commands or templates
9559 (dolist (c a)
9560 (let (vrules repl)
9561 (cond
9562 ((not (assoc (car c) contexts))
9563 (push c r))
9564 ((and (assoc (car c) contexts)
9565 (setq vrules (org-contextualize-validate-key
9566 (car c) contexts)))
9567 (mapc (lambda (vr)
9568 (unless (equal (car vr) (cadr vr))
9569 (setq repl vr)))
9570 vrules)
9571 (if (not repl) (push c r)
9572 (push (cadr repl) s)
9573 (push
9574 (cons (car c)
9575 (cdr (or (assoc (cadr repl) alist)
9576 (error "Undefined key `%s' as contextual replacement for `%s'"
9577 (cadr repl) (car c)))))
9578 r))))))
9579 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9580 (delq
9582 (delete-dups
9583 (mapcar (lambda (x)
9584 (let ((tpl (car x)))
9585 (unless (delq
9587 (mapcar (lambda (y)
9588 (equal y tpl))
9590 x)))
9591 (reverse r))))))
9593 (defun org-contextualize-validate-key (key contexts)
9594 "Check CONTEXTS for agenda or capture KEY."
9595 (let (res)
9596 (dolist (r contexts)
9597 (dolist (rr (car (last r)))
9598 (when
9599 (and (equal key (car r))
9600 (if (functionp rr) (funcall rr)
9601 (or (and (eq (car rr) 'in-file)
9602 (buffer-file-name)
9603 (string-match (cdr rr) (buffer-file-name)))
9604 (and (eq (car rr) 'in-mode)
9605 (string-match (cdr rr) (symbol-name major-mode)))
9606 (and (eq (car rr) 'in-buffer)
9607 (string-match (cdr rr) (buffer-name)))
9608 (when (and (eq (car rr) 'not-in-file)
9609 (buffer-file-name))
9610 (not (string-match (cdr rr) (buffer-file-name))))
9611 (when (eq (car rr) 'not-in-mode)
9612 (not (string-match (cdr rr) (symbol-name major-mode))))
9613 (when (eq (car rr) 'not-in-buffer)
9614 (not (string-match (cdr rr) (buffer-name)))))))
9615 (push r res))))
9616 (delete-dups (delq nil res))))
9618 (defun org-context-p (&rest contexts)
9619 "Check if local context is any of CONTEXTS.
9620 Possible values in the list of contexts are `table', `headline', and `item'."
9621 (let ((pos (point)))
9622 (goto-char (point-at-bol))
9623 (prog1 (or (and (memq 'table contexts)
9624 (looking-at "[ \t]*|"))
9625 (and (memq 'headline contexts)
9626 (looking-at org-outline-regexp))
9627 (and (memq 'item contexts)
9628 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9629 (and (memq 'item-body contexts)
9630 (org-in-item-p)))
9631 (goto-char pos))))
9633 (defconst org-unique-local-variables
9634 '(org-element--cache
9635 org-element--cache-objects
9636 org-element--cache-sync-keys
9637 org-element--cache-sync-requests
9638 org-element--cache-sync-timer)
9639 "List of local variables that cannot be transferred to another buffer.")
9641 (defun org-get-local-variables ()
9642 "Return a list of all local variables in an Org mode buffer."
9643 (delq nil
9644 (mapcar
9645 (lambda (x)
9646 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9647 (name (car binding)))
9648 (and (not (get name 'org-state))
9649 (not (memq name org-unique-local-variables))
9650 (string-match-p
9651 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9652 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9653 (symbol-name name))
9654 binding)))
9655 (with-temp-buffer
9656 (org-mode)
9657 (buffer-local-variables)))))
9659 (defun org-clone-local-variables (from-buffer &optional regexp)
9660 "Clone local variables from FROM-BUFFER.
9661 Optional argument REGEXP selects variables to clone."
9662 (dolist (pair (buffer-local-variables from-buffer))
9663 (let ((name (car pair)))
9664 (when (and (symbolp name)
9665 (not (memq name org-unique-local-variables))
9666 (or (null regexp) (string-match regexp (symbol-name name))))
9667 (set (make-local-variable name) (cdr pair))))))
9669 ;;;###autoload
9670 (defun org-run-like-in-org-mode (cmd)
9671 "Run a command, pretending that the current buffer is in Org mode.
9672 This will temporarily bind local variables that are typically bound in
9673 Org mode to the values they have in Org mode, and then interactively
9674 call CMD."
9675 (org-load-modules-maybe)
9676 (unless org-local-vars
9677 (setq org-local-vars (org-get-local-variables)))
9678 (let (binds)
9679 (dolist (var org-local-vars)
9680 (when (or (not (boundp (car var)))
9681 (eq (symbol-value (car var))
9682 (default-value (car var))))
9683 (push (list (car var) `(quote ,(cadr var))) binds)))
9684 (eval `(let ,binds
9685 (call-interactively (quote ,cmd))))))
9687 (defun org-get-category (&optional pos force-refresh)
9688 "Get the category applying to position POS."
9689 (save-match-data
9690 (when force-refresh (org-refresh-category-properties))
9691 (let ((pos (or pos (point))))
9692 (or (get-text-property pos 'org-category)
9693 (progn (org-refresh-category-properties)
9694 (get-text-property pos 'org-category))))))
9696 ;;; Refresh properties
9698 (defun org-refresh-properties (dprop tprop)
9699 "Refresh buffer text properties.
9700 DPROP is the drawer property and TPROP is either the
9701 corresponding text property to set, or an alist with each element
9702 being a text property (as a symbol) and a function to apply to
9703 the value of the drawer property."
9704 (let ((case-fold-search t)
9705 (inhibit-read-only t))
9706 (org-with-silent-modifications
9707 (org-with-wide-buffer
9708 (goto-char (point-min))
9709 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9710 (org-refresh-property tprop (match-string-no-properties 1)))))))
9712 (defun org-refresh-property (tprop p)
9713 "Refresh the buffer text property TPROP from the drawer property P.
9714 The refresh happens only for the current tree (not subtree)."
9715 (unless (org-before-first-heading-p)
9716 (save-excursion
9717 (org-back-to-heading t)
9718 (if (symbolp tprop)
9719 ;; TPROP is a text property symbol
9720 (put-text-property
9721 (point) (or (outline-next-heading) (point-max)) tprop p)
9722 ;; TPROP is an alist with (properties . function) elements
9723 (dolist (al tprop)
9724 (save-excursion
9725 (put-text-property
9726 (line-beginning-position) (or (outline-next-heading) (point-max))
9727 (car al)
9728 (funcall (cdr al) p))))))))
9730 (defun org-refresh-category-properties ()
9731 "Refresh category text properties in the buffer."
9732 (let ((case-fold-search t)
9733 (inhibit-read-only t)
9734 (default-category
9735 (cond ((null org-category)
9736 (if buffer-file-name
9737 (file-name-sans-extension
9738 (file-name-nondirectory buffer-file-name))
9739 "???"))
9740 ((symbolp org-category) (symbol-name org-category))
9741 (t org-category))))
9742 (org-with-silent-modifications
9743 (org-with-wide-buffer
9744 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9745 ;; This is the default category for the buffer. If none is
9746 ;; found, fall-back to `org-category' or buffer file name.
9747 (put-text-property
9748 (point-min) (point-max)
9749 'org-category
9750 (catch 'buffer-category
9751 (goto-char (point-max))
9752 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9753 (let ((element (org-element-at-point)))
9754 (when (eq (org-element-type element) 'keyword)
9755 (throw 'buffer-category
9756 (org-element-property :value element)))))
9757 default-category))
9758 ;; Set sub-tree specific categories.
9759 (goto-char (point-min))
9760 (let ((regexp (org-re-property "CATEGORY")))
9761 (while (re-search-forward regexp nil t)
9762 (let ((value (match-string-no-properties 3)))
9763 (when (org-at-property-p)
9764 (put-text-property
9765 (save-excursion (org-back-to-heading t) (point))
9766 (save-excursion (org-end-of-subtree t t) (point))
9767 'org-category
9768 value)))))))))
9770 (defun org-refresh-stats-properties ()
9771 "Refresh stats text properties in the buffer."
9772 (let (stats)
9773 (org-with-silent-modifications
9774 (org-with-wide-buffer
9775 (goto-char (point-min))
9776 (while (re-search-forward
9777 (concat org-outline-regexp-bol ".*"
9778 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9779 nil t)
9780 (setq stats (cond ((equal (match-string 3) "0") 0)
9781 ((match-string 2)
9782 (/ (* (string-to-number (match-string 2)) 100)
9783 (string-to-number (match-string 3))))
9784 (t (string-to-number (match-string 1)))))
9785 (org-back-to-heading t)
9786 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9787 'org-stats stats))))))
9789 (defun org-refresh-effort-properties ()
9790 "Refresh effort properties"
9791 (org-refresh-properties
9792 org-effort-property
9793 '((effort . identity)
9794 (effort-minutes . org-duration-string-to-minutes))))
9796 ;;;; Link Stuff
9798 ;;; Link abbreviations
9800 (defun org-link-expand-abbrev (link)
9801 "Apply replacements as defined in `org-link-abbrev-alist'."
9802 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9803 (let* ((key (match-string 1 link))
9804 (as (or (assoc key org-link-abbrev-alist-local)
9805 (assoc key org-link-abbrev-alist)))
9806 (tag (and (match-end 2) (match-string 3 link)))
9807 rpl)
9808 (if (not as)
9809 link
9810 (setq rpl (cdr as))
9811 (cond
9812 ((symbolp rpl) (funcall rpl tag))
9813 ((string-match "%(\\([^)]+\\))" rpl)
9814 (replace-match
9815 (save-match-data
9816 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9817 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9818 ((string-match "%h" rpl)
9819 (replace-match (url-hexify-string (or tag "")) t t rpl))
9820 (t (concat rpl tag)))))
9821 link))
9823 ;;; Storing and inserting links
9825 (defvar org-insert-link-history nil
9826 "Minibuffer history for links inserted with `org-insert-link'.")
9828 (defvar org-stored-links nil
9829 "Contains the links stored with `org-store-link'.")
9831 (defvar org-store-link-plist nil
9832 "Plist with info about the most recently link created with `org-store-link'.")
9834 (defun org-store-link-functions ()
9835 "Return a list of functions that are called to create and store a link.
9836 The functions defined in the :store property of
9837 `org-link-parameters'.
9839 Each function will be called in turn until one returns a non-nil
9840 value. Each function should check if it is responsible for
9841 creating this link (for example by looking at the major mode).
9842 If not, it must exit and return nil. If yes, it should return
9843 a non-nil value after calling `org-store-link-props' with a list
9844 of properties and values. Special properties are:
9846 :type The link prefix, like \"http\". This must be given.
9847 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9848 This is obligatory as well.
9849 :description Optional default description for the second pair
9850 of brackets in an Org mode link. The user can still change
9851 this when inserting this link into an Org mode buffer.
9853 In addition to these, any additional properties can be specified
9854 and then used in capture templates."
9855 (cl-loop for link in org-link-parameters
9856 with store-func
9857 do (setq store-func (org-link-get-parameter (car link) :store))
9858 if store-func
9859 collect store-func))
9861 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9862 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9864 ;;;###autoload
9865 (defun org-store-link (arg)
9866 "Store an org-link to the current location.
9867 \\<org-mode-map>
9868 This link is added to `org-stored-links' and can later be inserted
9869 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9871 For some link types, a `\\[universal-argument]' prefix ARG is interpreted.
9872 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9873 For file links, ARG negates `org-context-in-file-links'.
9875 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9876 skipping storing functions that are not
9877 part of Org core.
9879 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9880 prefix ARG forces storing a link for each line in the
9881 active region."
9882 (interactive "P")
9883 (org-load-modules-maybe)
9884 (if (and (equal arg '(64)) (org-region-active-p))
9885 (save-excursion
9886 (let ((end (region-end)))
9887 (goto-char (region-beginning))
9888 (set-mark (point))
9889 (while (< (point-at-eol) end)
9890 (move-end-of-line 1) (activate-mark)
9891 (let (current-prefix-arg)
9892 (call-interactively 'org-store-link))
9893 (move-beginning-of-line 2)
9894 (set-mark (point)))))
9895 (setq org-store-link-plist nil)
9896 (let (link cpltxt desc description search
9897 txt custom-id agenda-link sfuns sfunsn)
9898 (cond
9900 ;; Store a link using an external link type
9901 ((and (not (equal arg '(16)))
9902 (setq sfuns
9903 (delq
9904 nil (mapcar (lambda (f)
9905 (let (fs) (if (funcall f) (push f fs))))
9906 (org-store-link-functions)))
9907 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9908 (or (and (cdr sfuns)
9909 (funcall (intern
9910 (completing-read
9911 "Which function for creating the link? "
9912 sfunsn nil t (car sfunsn)))))
9913 (funcall (caar sfuns)))
9914 (setq link (plist-get org-store-link-plist :link)
9915 desc (or (plist-get org-store-link-plist
9916 :description)
9917 link))))
9919 ;; Store a link from a source code buffer.
9920 ((org-src-edit-buffer-p)
9921 (let ((coderef-format (org-src-coderef-format)))
9922 (cond ((save-excursion
9923 (beginning-of-line)
9924 (looking-at (org-src-coderef-regexp coderef-format)))
9925 (setq link (format "(%s)" (match-string-no-properties 3))))
9926 ((called-interactively-p 'any)
9927 (let ((label (read-string "Code line label: ")))
9928 (end-of-line)
9929 (setq link (format coderef-format label))
9930 (let ((gc (- 79 (length link))))
9931 (if (< (current-column) gc)
9932 (org-move-to-column gc t)
9933 (insert " ")))
9934 (insert link)
9935 (setq link (concat "(" label ")"))
9936 (setq desc nil)))
9937 (t (setq link nil)))))
9939 ;; We are in the agenda, link to referenced location
9940 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9941 (let ((m (or (get-text-property (point) 'org-hd-marker)
9942 (get-text-property (point) 'org-marker))))
9943 (when m
9944 (org-with-point-at m
9945 (setq agenda-link
9946 (if (called-interactively-p 'any)
9947 (call-interactively 'org-store-link)
9948 (org-store-link nil)))))))
9950 ((eq major-mode 'calendar-mode)
9951 (let ((cd (calendar-cursor-to-date)))
9952 (setq link
9953 (format-time-string
9954 (car org-time-stamp-formats)
9955 (apply 'encode-time
9956 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9957 nil nil nil))))
9958 (org-store-link-props :type "calendar" :date cd)))
9960 ((eq major-mode 'help-mode)
9961 (setq link (concat "help:" (save-excursion
9962 (goto-char (point-min))
9963 (looking-at "^[^ ]+")
9964 (match-string 0))))
9965 (org-store-link-props :type "help"))
9967 ((eq major-mode 'w3-mode)
9968 (setq cpltxt (if (and (buffer-name)
9969 (not (string-match "Untitled" (buffer-name))))
9970 (buffer-name)
9971 (url-view-url t))
9972 link (url-view-url t))
9973 (org-store-link-props :type "w3" :url (url-view-url t)))
9975 ((eq major-mode 'image-mode)
9976 (setq cpltxt (concat "file:"
9977 (abbreviate-file-name buffer-file-name))
9978 link cpltxt)
9979 (org-store-link-props :type "image" :file buffer-file-name))
9981 ;; In dired, store a link to the file of the current line
9982 ((derived-mode-p 'dired-mode)
9983 (let ((file (dired-get-filename nil t)))
9984 (setq file (if file
9985 (abbreviate-file-name
9986 (expand-file-name (dired-get-filename nil t)))
9987 ;; otherwise, no file so use current directory.
9988 default-directory))
9989 (setq cpltxt (concat "file:" file)
9990 link cpltxt)))
9992 ((setq search (run-hook-with-args-until-success
9993 'org-create-file-search-functions))
9994 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9995 "::" search))
9996 (setq cpltxt (or description link)))
9998 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9999 (org-with-limited-levels
10000 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
10001 (cond
10002 ;; Store a link using the target at point
10003 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
10004 (setq cpltxt
10005 (concat "file:"
10006 (abbreviate-file-name
10007 (buffer-file-name (buffer-base-buffer)))
10008 "::" (match-string 1))
10009 link cpltxt))
10010 ((and (featurep 'org-id)
10011 (or (eq org-id-link-to-org-use-id t)
10012 (and (called-interactively-p 'any)
10013 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
10014 (and (eq org-id-link-to-org-use-id
10015 'create-if-interactive-and-no-custom-id)
10016 (not custom-id))))
10017 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
10018 ;; Store a link using the ID at point
10019 (setq link (condition-case nil
10020 (prog1 (org-id-store-link)
10021 (setq desc (or (plist-get org-store-link-plist
10022 :description)
10023 "")))
10024 (error
10025 ;; Probably before first headline, link only to file
10026 (concat "file:"
10027 (abbreviate-file-name
10028 (buffer-file-name (buffer-base-buffer))))))))
10030 ;; Just link to current headline
10031 (setq cpltxt (concat "file:"
10032 (abbreviate-file-name
10033 (buffer-file-name (buffer-base-buffer)))))
10034 ;; Add a context search string
10035 (when (org-xor org-context-in-file-links arg)
10036 (let* ((element (org-element-at-point))
10037 (name (org-element-property :name element)))
10038 (setq txt (cond
10039 ((org-at-heading-p) nil)
10040 (name)
10041 ((org-region-active-p)
10042 (buffer-substring (region-beginning) (region-end)))))
10043 (when (or (null txt) (string-match "\\S-" txt))
10044 (setq cpltxt
10045 (concat cpltxt "::"
10046 (condition-case nil
10047 (org-make-org-heading-search-string txt)
10048 (error "")))
10049 desc (or name
10050 (nth 4 (ignore-errors (org-heading-components)))
10051 "NONE")))))
10052 (when (string-match "::\\'" cpltxt)
10053 (setq cpltxt (substring cpltxt 0 -2)))
10054 (setq link cpltxt)))))
10056 ((buffer-file-name (buffer-base-buffer))
10057 ;; Just link to this file here.
10058 (setq cpltxt (concat "file:"
10059 (abbreviate-file-name
10060 (buffer-file-name (buffer-base-buffer)))))
10061 ;; Add a context string.
10062 (when (org-xor org-context-in-file-links arg)
10063 (setq txt (if (org-region-active-p)
10064 (buffer-substring (region-beginning) (region-end))
10065 (buffer-substring (point-at-bol) (point-at-eol))))
10066 ;; Only use search option if there is some text.
10067 (when (string-match "\\S-" txt)
10068 (setq cpltxt
10069 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10070 desc "NONE")))
10071 (setq link cpltxt))
10073 ((called-interactively-p 'interactive)
10074 (user-error "No method for storing a link from this buffer"))
10076 (t (setq link nil)))
10078 ;; We're done setting link and desc, clean up
10079 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10080 (setq link (or link cpltxt)
10081 desc (or desc cpltxt))
10082 (cond ((not desc))
10083 ((equal desc "NONE") (setq desc nil))
10084 (t (setq desc
10085 (replace-regexp-in-string
10086 org-bracket-link-analytic-regexp
10087 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10088 desc))))
10089 ;; Return the link
10090 (if (not (and (or (called-interactively-p 'any)
10091 executing-kbd-macro)
10092 link))
10093 (or agenda-link (and link (org-make-link-string link desc)))
10094 (push (list link desc) org-stored-links)
10095 (message "Stored: %s" (or desc link))
10096 (when custom-id
10097 (setq link (concat "file:" (abbreviate-file-name
10098 (buffer-file-name)) "::#" custom-id))
10099 (push (list link desc) org-stored-links))
10100 (car org-stored-links)))))
10102 (defun org-store-link-props (&rest plist)
10103 "Store link properties, extract names, addresses and dates."
10104 (let ((x (plist-get plist :from)))
10105 (when x
10106 (let ((adr (mail-extract-address-components x)))
10107 (setq plist (plist-put plist :fromname (car adr)))
10108 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10109 (let ((x (plist-get plist :to)))
10110 (when x
10111 (let ((adr (mail-extract-address-components x)))
10112 (setq plist (plist-put plist :toname (car adr)))
10113 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10114 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10115 (when x
10116 (setq plist (plist-put plist :date-timestamp
10117 (format-time-string
10118 (org-time-stamp-format t) x)))
10119 (setq plist (plist-put plist :date-timestamp-inactive
10120 (format-time-string
10121 (org-time-stamp-format t t) x)))))
10122 (let ((from (plist-get plist :from))
10123 (to (plist-get plist :to)))
10124 (when (and from to org-from-is-user-regexp)
10125 (setq plist
10126 (plist-put plist :fromto
10127 (if (string-match org-from-is-user-regexp from)
10128 (concat "to %t")
10129 (concat "from %f"))))))
10130 (setq org-store-link-plist plist))
10132 (defun org-add-link-props (&rest plist)
10133 "Add these properties to the link property list."
10134 (let (key value)
10135 (while plist
10136 (setq key (pop plist) value (pop plist))
10137 (setq org-store-link-plist
10138 (plist-put org-store-link-plist key value)))))
10140 (defun org-email-link-description (&optional fmt)
10141 "Return the description part of an email link.
10142 This takes information from `org-store-link-plist' and formats it
10143 according to FMT (default from `org-email-link-description-format')."
10144 (setq fmt (or fmt org-email-link-description-format))
10145 (let* ((p org-store-link-plist)
10146 (to (plist-get p :toaddress))
10147 (from (plist-get p :fromaddress))
10148 (table
10149 (list
10150 (cons "%c" (plist-get p :fromto))
10151 (cons "%F" (plist-get p :from))
10152 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10153 (cons "%T" (plist-get p :to))
10154 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10155 (cons "%s" (plist-get p :subject))
10156 (cons "%d" (plist-get p :date))
10157 (cons "%m" (plist-get p :message-id)))))
10158 (when (string-match "%c" fmt)
10159 ;; Check if the user wrote this message
10160 (if (and org-from-is-user-regexp from to
10161 (save-match-data (string-match org-from-is-user-regexp from)))
10162 (setq fmt (replace-match "to %t" t t fmt))
10163 (setq fmt (replace-match "from %f" t t fmt))))
10164 (org-replace-escapes fmt table)))
10166 (defun org-make-org-heading-search-string (&optional string)
10167 "Make search string for the current headline or STRING."
10168 (let ((s (or string
10169 (and (derived-mode-p 'org-mode)
10170 (save-excursion
10171 (org-back-to-heading t)
10172 (org-element-property :raw-value (org-element-at-point))))))
10173 (lines org-context-in-file-links))
10174 (or string (setq s (concat "*" s))) ; Add * for headlines
10175 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10176 (when (and string (integerp lines) (> lines 0))
10177 (let ((slines (org-split-string s "\n")))
10178 (when (< lines (length slines))
10179 (setq s (mapconcat
10180 'identity
10181 (reverse (nthcdr (- (length slines) lines)
10182 (reverse slines))) "\n")))))
10183 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10185 (defun org-make-link-string (link &optional description)
10186 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10187 (unless (org-string-nw-p link) (error "Empty link"))
10188 (let ((uri (cond ((string-match org-link-types-re link)
10189 (concat (match-string 1 link)
10190 (org-link-escape (substring link (match-end 1)))))
10191 ;; For readability, url-encode internal links only
10192 ;; when absolutely needed (i.e, when they contain
10193 ;; square brackets). File links however, are
10194 ;; encoded since, e.g., spaces are significant.
10195 ((or (file-name-absolute-p link)
10196 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10197 (org-link-escape link))
10198 (t link)))
10199 (description
10200 (and (org-string-nw-p description)
10201 ;; Remove brackets from description, as they are fatal.
10202 (replace-regexp-in-string
10203 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10204 (org-trim description)))))
10205 (format "[[%s]%s]"
10207 (if description (format "[%s]" description) ""))))
10209 (defconst org-link-escape-chars
10210 ;;%20 %5B %5D %25
10211 '(?\s ?\[ ?\] ?%)
10212 "List of characters that should be escaped in a link when stored to Org.
10213 This is the list that is used for internal purposes.")
10215 (defun org-link-escape (text &optional table merge)
10216 "Return percent escaped representation of TEXT.
10217 TEXT is a string with the text to escape.
10218 Optional argument TABLE is a list with characters that should be
10219 escaped. When nil, `org-link-escape-chars' is used.
10220 If optional argument MERGE is set, merge TABLE into
10221 `org-link-escape-chars'."
10222 (let ((characters-to-encode
10223 (cond ((null table) org-link-escape-chars)
10224 (merge (append org-link-escape-chars table))
10225 (t table))))
10226 (mapconcat
10227 (lambda (c)
10228 (if (or (memq c characters-to-encode)
10229 (and org-url-hexify-p (or (< c 32) (> c 126))))
10230 (mapconcat (lambda (e) (format "%%%.2X" e))
10231 (or (encode-coding-char c 'utf-8)
10232 (error "Unable to percent escape character: %c" c))
10234 (char-to-string c)))
10235 text "")))
10237 (defun org-link-unescape (str)
10238 "Unhex hexified Unicode parts in string STR.
10239 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10240 reciprocal of `org-link-escape', which see."
10241 (if (org-string-nw-p str)
10242 (replace-regexp-in-string
10243 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10244 str))
10246 (defun org-link-unescape-compound (hex)
10247 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10248 Note: this function also decodes single byte encodings like
10249 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10250 (save-match-data
10251 (let* ((bytes (cdr (split-string hex "%")))
10252 (ret "")
10253 (eat 0)
10254 (sum 0))
10255 (while bytes
10256 (let* ((val (string-to-number (pop bytes) 16))
10257 (shift-xor
10258 (if (= 0 eat)
10259 (cond
10260 ((>= val 252) (cons 6 252))
10261 ((>= val 248) (cons 5 248))
10262 ((>= val 240) (cons 4 240))
10263 ((>= val 224) (cons 3 224))
10264 ((>= val 192) (cons 2 192))
10265 (t (cons 0 0)))
10266 (cons 6 128))))
10267 (when (>= val 192) (setq eat (car shift-xor)))
10268 (setq val (logxor val (cdr shift-xor)))
10269 (setq sum (+ (lsh sum (car shift-xor)) val))
10270 (when (> eat 0) (setq eat (- eat 1)))
10271 (cond
10272 ((= 0 eat) ;multi byte
10273 (setq ret (concat ret (char-to-string sum)))
10274 (setq sum 0))
10275 ((not bytes) ; single byte(s)
10276 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10277 ret)))
10279 (defun org-link-unescape-single-byte-sequence (hex)
10280 "Unhexify hex-encoded single byte character sequences."
10281 (mapconcat (lambda (byte)
10282 (char-to-string (string-to-number byte 16)))
10283 (cdr (split-string hex "%")) ""))
10285 (defun org-xor (a b)
10286 "Exclusive or."
10287 (if a (not b) b))
10289 (defun org-fixup-message-id-for-http (s)
10290 "Replace special characters in a message id, so it can be used in an http query."
10291 (when (string-match "%" s)
10292 (setq s (mapconcat (lambda (c)
10293 (if (eq c ?%)
10294 "%25"
10295 (char-to-string c)))
10296 s "")))
10297 (while (string-match "<" s)
10298 (setq s (replace-match "%3C" t t s)))
10299 (while (string-match ">" s)
10300 (setq s (replace-match "%3E" t t s)))
10301 (while (string-match "@" s)
10302 (setq s (replace-match "%40" t t s)))
10305 (defun org-link-prettify (link)
10306 "Return a human-readable representation of LINK.
10307 The car of LINK must be a raw link.
10308 The cdr of LINK must be either a link description or nil."
10309 (let ((desc (or (cadr link) "<no description>")))
10310 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10311 "<" (car link) ">")))
10313 ;;;###autoload
10314 (defun org-insert-link-global ()
10315 "Insert a link like Org mode does.
10316 This command can be called in any mode to insert a link in Org syntax."
10317 (interactive)
10318 (org-load-modules-maybe)
10319 (org-run-like-in-org-mode 'org-insert-link))
10321 (defun org-insert-all-links (arg &optional pre post)
10322 "Insert all links in `org-stored-links'.
10323 When a universal prefix, do not delete the links from `org-stored-links'.
10324 When `ARG' is a number, insert the last N link(s).
10325 `PRE' and `POST' are optional arguments to define a string to
10326 prepend or to append."
10327 (interactive "P")
10328 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10329 (links (copy-sequence org-stored-links))
10330 (pr (or pre "- "))
10331 (po (or post "\n"))
10332 (cnt 1) l)
10333 (if (null org-stored-links)
10334 (message "No link to insert")
10335 (while (and (or (listp arg) (>= arg cnt))
10336 (setq l (if (listp arg)
10337 (pop links)
10338 (pop org-stored-links))))
10339 (setq cnt (1+ cnt))
10340 (insert pr)
10341 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10342 (insert po)))))
10344 (defun org-insert-last-stored-link (arg)
10345 "Insert the last link stored in `org-stored-links'."
10346 (interactive "p")
10347 (org-insert-all-links arg "" "\n"))
10349 (defun org-link-fontify-links-to-this-file ()
10350 "Fontify links to the current file in `org-stored-links'."
10351 (let ((f (buffer-file-name)) a b)
10352 (setq a (mapcar (lambda(l)
10353 (let ((ll (car l)))
10354 (when (and (string-match "^file:\\(.+\\)::" ll)
10355 (equal f (expand-file-name (match-string 1 ll))))
10356 ll)))
10357 org-stored-links))
10358 (when (featurep 'org-id)
10359 (setq b (mapcar (lambda(l)
10360 (let ((ll (car l)))
10361 (when (and (string-match "^id:\\(.+\\)$" ll)
10362 (equal f (expand-file-name
10363 (or (org-id-find-id-file
10364 (match-string 1 ll)) ""))))
10365 ll)))
10366 org-stored-links)))
10367 (mapcar (lambda(l)
10368 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10369 (delq nil (append a b)))))
10371 (defvar org--links-history nil)
10372 (defun org-insert-link (&optional complete-file link-location default-description)
10373 "Insert a link. At the prompt, enter the link.
10375 Completion can be used to insert any of the link protocol prefixes in use.
10377 The history can be used to select a link previously stored with
10378 `org-store-link'. When the empty string is entered (i.e. if you just
10379 press `RET' at the prompt), the link defaults to the most recently
10380 stored link. As `SPC' triggers completion in the minibuffer, you need to
10381 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10383 You will also be prompted for a description, and if one is given, it will
10384 be displayed in the buffer instead of the link.
10386 If there is already a link at point, this command will allow you to edit
10387 link and description parts.
10389 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10390 file name can be
10391 selected using completion. The path to the file will be relative to the
10392 current directory if the file is in the current directory or a subdirectory.
10393 Otherwise, the link will be the absolute path as completed in the minibuffer
10394 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10395 option `org-link-file-path-type'.
10397 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10398 absolute path even if the file is in
10399 the current directory or below.
10401 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10402 prefix negates `org-keep-stored-link-after-insertion'.
10404 If `org-make-link-description-function' is non-nil, this function will be
10405 called with the link target, and the result will be the default
10406 link description.
10408 If the LINK-LOCATION parameter is non-nil, this value will be used as
10409 the link location instead of reading one interactively.
10411 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10412 as the default description."
10413 (interactive "P")
10414 (let* ((wcf (current-window-configuration))
10415 (origbuf (current-buffer))
10416 (region (when (org-region-active-p)
10417 (buffer-substring (region-beginning) (region-end))))
10418 (remove (and region (list (region-beginning) (region-end))))
10419 (desc region)
10420 (link link-location)
10421 (abbrevs org-link-abbrev-alist-local)
10422 entry all-prefixes auto-desc)
10423 (cond
10424 (link-location) ; specified by arg, just use it.
10425 ((org-in-regexp org-bracket-link-regexp 1)
10426 ;; We do have a link at point, and we are going to edit it.
10427 (setq remove (list (match-beginning 0) (match-end 0)))
10428 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10429 (setq link (read-string "Link: "
10430 (org-link-unescape
10431 (match-string-no-properties 1)))))
10432 ((or (org-in-regexp org-angle-link-re)
10433 (org-in-regexp org-plain-link-re))
10434 ;; Convert to bracket link
10435 (setq remove (list (match-beginning 0) (match-end 0))
10436 link (read-string "Link: "
10437 (org-unbracket-string "<" ">" (match-string 0)))))
10438 ((member complete-file '((4) (16)))
10439 ;; Completing read for file names.
10440 (setq link (org-file-complete-link complete-file)))
10442 ;; Read link, with completion for stored links.
10443 (org-link-fontify-links-to-this-file)
10444 (org-switch-to-buffer-other-window "*Org Links*")
10445 (with-current-buffer "*Org Links*"
10446 (erase-buffer)
10447 (insert "Insert a link.
10448 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10449 (when org-stored-links
10450 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10451 (insert (mapconcat 'org-link-prettify
10452 (reverse org-stored-links) "\n")))
10453 (goto-char (point-min)))
10454 (let ((cw (selected-window)))
10455 (select-window (get-buffer-window "*Org Links*" 'visible))
10456 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10457 (unless (pos-visible-in-window-p (point-max))
10458 (org-fit-window-to-buffer))
10459 (and (window-live-p cw) (select-window cw)))
10460 (setq all-prefixes (append (mapcar 'car abbrevs)
10461 (mapcar 'car org-link-abbrev-alist)
10462 (org-link-types)))
10463 (unwind-protect
10464 ;; Fake a link history, containing the stored links.
10465 (let ((org--links-history
10466 (append (mapcar #'car org-stored-links)
10467 org-insert-link-history)))
10468 (setq link
10469 (org-completing-read
10470 "Link: "
10471 (append
10472 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10473 (mapcar #'car org-stored-links))
10474 nil nil nil
10475 'org--links-history
10476 (caar org-stored-links)))
10477 (unless (org-string-nw-p link) (user-error "No link selected"))
10478 (dolist (l org-stored-links)
10479 (when (equal link (cadr l))
10480 (setq link (car l))
10481 (setq auto-desc t)))
10482 (when (or (member link all-prefixes)
10483 (and (equal ":" (substring link -1))
10484 (member (substring link 0 -1) all-prefixes)
10485 (setq link (substring link 0 -1))))
10486 (setq link (with-current-buffer origbuf
10487 (org-link-try-special-completion link)))))
10488 (set-window-configuration wcf)
10489 (kill-buffer "*Org Links*"))
10490 (setq entry (assoc link org-stored-links))
10491 (or entry (push link org-insert-link-history))
10492 (setq desc (or desc (nth 1 entry)))))
10494 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10495 (not org-keep-stored-link-after-insertion))
10496 (setq org-stored-links (delq (assoc link org-stored-links)
10497 org-stored-links)))
10499 (when (and (string-match org-plain-link-re link)
10500 (not (string-match org-ts-regexp link)))
10501 ;; URL-like link, normalize the use of angular brackets.
10502 (setq link (org-unbracket-string "<" ">" link)))
10504 ;; Check if we are linking to the current file with a search
10505 ;; option If yes, simplify the link by using only the search
10506 ;; option.
10507 (when (and buffer-file-name
10508 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10509 (let* ((path (match-string 1 link))
10510 (case-fold-search nil)
10511 (search (match-string 2 link)))
10512 (save-match-data
10513 (when (equal (file-truename buffer-file-name) (file-truename path))
10514 ;; We are linking to this same file, with a search option
10515 (setq link search)))))
10517 ;; Check if we can/should use a relative path. If yes, simplify the link
10518 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10519 (let* ((type (match-string 1 link))
10520 (path (match-string 2 link))
10521 (origpath path)
10522 (case-fold-search nil))
10523 (cond
10524 ((or (eq org-link-file-path-type 'absolute)
10525 (equal complete-file '(16)))
10526 (setq path (abbreviate-file-name (expand-file-name path))))
10527 ((eq org-link-file-path-type 'noabbrev)
10528 (setq path (expand-file-name path)))
10529 ((eq org-link-file-path-type 'relative)
10530 (setq path (file-relative-name path)))
10532 (save-match-data
10533 (if (string-match (concat "^" (regexp-quote
10534 (expand-file-name
10535 (file-name-as-directory
10536 default-directory))))
10537 (expand-file-name path))
10538 ;; We are linking a file with relative path name.
10539 (setq path (substring (expand-file-name path)
10540 (match-end 0)))
10541 (setq path (abbreviate-file-name (expand-file-name path)))))))
10542 (setq link (concat type path))
10543 (when (equal desc origpath)
10544 (setq desc path))))
10546 (if org-make-link-description-function
10547 (setq desc
10548 (or (condition-case nil
10549 (funcall org-make-link-description-function link desc)
10550 (error (progn (message "Can't get link description from `%s'"
10551 (symbol-name org-make-link-description-function))
10552 (sit-for 2) nil)))
10553 (read-string "Description: " default-description)))
10554 (if default-description (setq desc default-description)
10555 (setq desc (or (and auto-desc desc)
10556 (read-string "Description: " desc)))))
10558 (unless (string-match "\\S-" desc) (setq desc nil))
10559 (when remove (apply 'delete-region remove))
10560 (insert (org-make-link-string link desc))
10561 ;; Redisplay so as the new link has proper invisible characters.
10562 (sit-for 0)))
10564 (defun org-link-try-special-completion (type)
10565 "If there is completion support for link type TYPE, offer it."
10566 (let ((fun (org-link-get-parameter type :complete)))
10567 (if (functionp fun)
10568 (funcall fun)
10569 (read-string "Link (no completion support): " (concat type ":")))))
10571 (defun org-file-complete-link (&optional arg)
10572 "Create a file link using completion."
10573 (let ((file (read-file-name "File: "))
10574 (pwd (file-name-as-directory (expand-file-name ".")))
10575 (pwd1 (file-name-as-directory (abbreviate-file-name
10576 (expand-file-name ".")))))
10577 (cond ((equal arg '(16))
10578 (concat "file:"
10579 (abbreviate-file-name (expand-file-name file))))
10580 ((string-match
10581 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10582 (concat "file:" (match-string 1 file)))
10583 ((string-match
10584 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10585 (expand-file-name file))
10586 (concat "file:"
10587 (match-string 1 (expand-file-name file))))
10588 (t (concat "file:" file)))))
10590 (defun org-completing-read (&rest args)
10591 "Completing-read with SPACE being a normal character."
10592 (let ((enable-recursive-minibuffers t)
10593 (minibuffer-local-completion-map
10594 (copy-keymap minibuffer-local-completion-map)))
10595 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10596 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10597 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10598 'org-time-stamp-inactive)
10599 (apply #'completing-read args)))
10601 ;;; Opening/following a link
10603 (defvar org-link-search-failed nil)
10605 (defvar org-open-link-functions nil
10606 "Hook for functions finding a plain text link.
10607 These functions must take a single argument, the link content.
10608 They will be called for links that look like [[link text][description]]
10609 when LINK TEXT does not have a protocol like \"http:\" and does not look
10610 like a filename (e.g. \"./blue.png\").
10612 These functions will be called *before* Org attempts to resolve the
10613 link by doing text searches in the current buffer - so if you want a
10614 link \"[[target]]\" to still find \"<<target>>\", your function should
10615 handle this as a special case.
10617 When the function does handle the link, it must return a non-nil value.
10618 If it decides that it is not responsible for this link, it must return
10619 nil to indicate that that Org can continue with other options like
10620 exact and fuzzy text search.")
10622 (defun org-next-link (&optional search-backward)
10623 "Move forward to the next link.
10624 If the link is in hidden text, expose it."
10625 (interactive "P")
10626 (when (and org-link-search-failed (eq this-command last-command))
10627 (goto-char (point-min))
10628 (message "Link search wrapped back to beginning of buffer"))
10629 (setq org-link-search-failed nil)
10630 (let* ((pos (point))
10631 (ct (org-context))
10632 (a (assq :link ct))
10633 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10634 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10635 ((looking-at org-any-link-re)
10636 ;; Don't stay stuck at link without an org-link face
10637 (forward-char (if search-backward -1 1))))
10638 (if (funcall srch-fun org-any-link-re nil t)
10639 (progn
10640 (goto-char (match-beginning 0))
10641 (when (outline-invisible-p) (org-show-context)))
10642 (goto-char pos)
10643 (setq org-link-search-failed t)
10644 (message "No further link found"))))
10646 (defun org-previous-link ()
10647 "Move backward to the previous link.
10648 If the link is in hidden text, expose it."
10649 (interactive)
10650 (funcall 'org-next-link t))
10652 (defun org-translate-link (s)
10653 "Translate a link string if a translation function has been defined."
10654 (with-temp-buffer
10655 (insert (org-trim s))
10656 (org-trim (org-element-interpret-data (org-element-context)))))
10658 (defun org-translate-link-from-planner (type path)
10659 "Translate a link from Emacs Planner syntax so that Org can follow it.
10660 This is still an experimental function, your mileage may vary."
10661 (cond
10662 ((member type '("http" "https" "news" "ftp"))
10663 ;; standard Internet links are the same.
10664 nil)
10665 ((and (equal type "irc") (string-match "^//" path))
10666 ;; Planner has two / at the beginning of an irc link, we have 1.
10667 ;; We should have zero, actually....
10668 (setq path (substring path 1)))
10669 ((and (equal type "lisp") (string-match "^/" path))
10670 ;; Planner has a slash, we do not.
10671 (setq type "elisp" path (substring path 1)))
10672 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10673 ;; A typical message link. Planner has the id after the final slash,
10674 ;; we separate it with a hash mark
10675 (setq path (concat (match-string 1 path) "#"
10676 (org-unbracket-string "<" ">" (match-string 2 path))))))
10677 (cons type path))
10679 (defun org-find-file-at-mouse (ev)
10680 "Open file link or URL at mouse."
10681 (interactive "e")
10682 (mouse-set-point ev)
10683 (org-open-at-point 'in-emacs))
10685 (defun org-open-at-mouse (ev)
10686 "Open file link or URL at mouse.
10687 See the docstring of `org-open-file' for details."
10688 (interactive "e")
10689 (mouse-set-point ev)
10690 (when (eq major-mode 'org-agenda-mode)
10691 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10692 (org-open-at-point))
10694 (defvar org-window-config-before-follow-link nil
10695 "The window configuration before following a link.
10696 This is saved in case the need arises to restore it.")
10698 ;;;###autoload
10699 (defun org-open-at-point-global ()
10700 "Follow a link or time-stamp like Org mode does.
10701 This command can be called in any mode to follow an external link
10702 or a time-stamp that has Org mode syntax. Its behavior is
10703 undefined when called on internal links (e.g., fuzzy links).
10704 Raise an error when there is nothing to follow. "
10705 (interactive)
10706 (cond ((org-in-regexp org-any-link-re)
10707 (org-open-link-from-string (match-string-no-properties 0)))
10708 ((or (org-in-regexp org-ts-regexp-both nil t)
10709 (org-in-regexp org-tsr-regexp-both nil t))
10710 (org-follow-timestamp-link))
10711 (t (user-error "No link found"))))
10713 ;;;###autoload
10714 (defun org-open-link-from-string (s &optional arg reference-buffer)
10715 "Open a link in the string S, as if it was in Org mode."
10716 (interactive "sLink: \nP")
10717 (let ((reference-buffer (or reference-buffer (current-buffer))))
10718 (with-temp-buffer
10719 (let ((org-inhibit-startup (not reference-buffer)))
10720 (org-mode)
10721 (insert s)
10722 (goto-char (point-min))
10723 (when reference-buffer
10724 (setq org-link-abbrev-alist-local
10725 (with-current-buffer reference-buffer
10726 org-link-abbrev-alist-local)))
10727 (org-open-at-point arg reference-buffer)))))
10729 (defvar org-open-at-point-functions nil
10730 "Hook that is run when following a link at point.
10732 Functions in this hook must return t if they identify and follow
10733 a link at point. If they don't find anything interesting at point,
10734 they must return nil.")
10736 (defvar org-link-search-inhibit-query nil)
10737 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10738 (defun org--open-doi-link (path)
10739 "Open a \"doi\" type link.
10740 PATH is a the path to search for, as a string."
10741 (browse-url (url-encode-url (concat org-doi-server-url path))))
10743 (defun org--open-elisp-link (path)
10744 "Open a \"elisp\" type link.
10745 PATH is the sexp to evaluate, as a string."
10746 (let ((cmd path))
10747 (if (or (and (org-string-nw-p
10748 org-confirm-elisp-link-not-regexp)
10749 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10750 (not org-confirm-elisp-link-function)
10751 (funcall org-confirm-elisp-link-function
10752 (format "Execute \"%s\" as elisp? "
10753 (org-add-props cmd nil 'face 'org-warning))))
10754 (message "%s => %s" cmd
10755 (if (eq (string-to-char cmd) ?\()
10756 (eval (read cmd))
10757 (call-interactively (read cmd))))
10758 (user-error "Abort"))))
10760 (defun org--open-help-link (path)
10761 "Open a \"help\" type link.
10762 PATH is a symbol name, as a string."
10763 (pcase (intern path)
10764 ((and (pred fboundp) variable) (describe-function variable))
10765 ((and (pred boundp) function) (describe-variable function))
10766 (name (user-error "Unknown function or variable: %s" name))))
10768 (defun org--open-shell-link (path)
10769 "Open a \"shell\" type link.
10770 PATH is the command to execute, as a string."
10771 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10772 (cmd path))
10773 (if (or (and (org-string-nw-p
10774 org-confirm-shell-link-not-regexp)
10775 (string-match
10776 org-confirm-shell-link-not-regexp cmd))
10777 (not org-confirm-shell-link-function)
10778 (funcall org-confirm-shell-link-function
10779 (format "Execute \"%s\" in shell? "
10780 (org-add-props cmd nil
10781 'face 'org-warning))))
10782 (progn
10783 (message "Executing %s" cmd)
10784 (shell-command cmd buf)
10785 (when (featurep 'midnight)
10786 (setq clean-buffer-list-kill-buffer-names
10787 (cons (buffer-name buf)
10788 clean-buffer-list-kill-buffer-names))))
10789 (user-error "Abort"))))
10791 (defun org-open-at-point (&optional arg reference-buffer)
10792 "Open link, timestamp, footnote or tags at point.
10794 When point is on a link, follow it. Normally, files will be
10795 opened by an appropriate application. If the optional prefix
10796 argument ARG is non-nil, Emacs will visit the file. With
10797 a double prefix argument, try to open outside of Emacs, in the
10798 application the system uses for this file type.
10800 When point is on a timestamp, open the agenda at the day
10801 specified.
10803 When point is a footnote definition, move to the first reference
10804 found. If it is on a reference, move to the associated
10805 definition.
10807 When point is on a headline, display a list of every link in the
10808 entry, so it is possible to pick one, or all, of them. If point
10809 is on a tag, call `org-tags-view' instead.
10811 When optional argument REFERENCE-BUFFER is non-nil, it should
10812 specify a buffer from where the link search should happen. This
10813 is used internally by `org-open-link-from-string'.
10815 On top of syntactically correct links, this function will open
10816 the link at point in comments or comment blocks and the first
10817 link in a property drawer line."
10818 (interactive "P")
10819 ;; On a code block, open block's results.
10820 (unless (call-interactively 'org-babel-open-src-block-result)
10821 (org-load-modules-maybe)
10822 (setq org-window-config-before-follow-link (current-window-configuration))
10823 (org-remove-occur-highlights nil nil t)
10824 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10825 (let* ((context
10826 ;; Only consider supported types, even if they are not
10827 ;; the closest one.
10828 (org-element-lineage
10829 (org-element-context)
10830 '(clock comment comment-block footnote-definition
10831 footnote-reference headline inlinetask keyword link
10832 node-property timestamp)
10834 (type (org-element-type context))
10835 (value (org-element-property :value context)))
10836 (cond
10837 ((not context) (user-error "No link found"))
10838 ;; Exception: open timestamps and links in properties
10839 ;; drawers, keywords and comments.
10840 ((memq type '(comment comment-block keyword node-property))
10841 (call-interactively #'org-open-at-point-global))
10842 ;; On a headline or an inlinetask, but not on a timestamp,
10843 ;; a link, a footnote reference or on tags.
10844 ((and (memq type '(headline inlinetask))
10845 ;; Not on tags.
10846 (progn (save-excursion (beginning-of-line)
10847 (looking-at org-complex-heading-regexp))
10848 (or (not (match-beginning 5))
10849 (< (point) (match-beginning 5)))))
10850 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10851 (links (car data))
10852 (links-end (cdr data)))
10853 (if links
10854 (dolist (link (if (stringp links) (list links) links))
10855 (search-forward link nil links-end)
10856 (goto-char (match-beginning 0))
10857 (org-open-at-point))
10858 (require 'org-attach)
10859 (org-attach-reveal 'if-exists))))
10860 ;; On a clock line, make sure point is on the timestamp
10861 ;; before opening it.
10862 ((and (eq type 'clock)
10863 value
10864 (>= (point) (org-element-property :begin value))
10865 (<= (point) (org-element-property :end value)))
10866 (org-follow-timestamp-link))
10867 ;; Do nothing on white spaces after an object.
10868 ((>= (point)
10869 (save-excursion
10870 (goto-char (org-element-property :end context))
10871 (skip-chars-backward " \t")
10872 (point)))
10873 (user-error "No link found"))
10874 ((eq type 'timestamp) (org-follow-timestamp-link))
10875 ;; On tags within a headline or an inlinetask.
10876 ((and (memq type '(headline inlinetask))
10877 (progn (save-excursion (beginning-of-line)
10878 (looking-at org-complex-heading-regexp))
10879 (and (match-beginning 5)
10880 (>= (point) (match-beginning 5)))))
10881 (org-tags-view arg (substring (match-string 5) 0 -1)))
10882 ((eq type 'link)
10883 ;; When link is located within the description of another
10884 ;; link (e.g., an inline image), always open the parent
10885 ;; link.
10886 (let* ((link (let ((up (org-element-property :parent context)))
10887 (if (eq (org-element-type up) 'link) up context)))
10888 (type (org-element-property :type link))
10889 (path (org-link-unescape (org-element-property :path link))))
10890 ;; Switch back to REFERENCE-BUFFER needed when called in
10891 ;; a temporary buffer through `org-open-link-from-string'.
10892 (with-current-buffer (or reference-buffer (current-buffer))
10893 (cond
10894 ((equal type "file")
10895 (if (string-match "[*?{]" (file-name-nondirectory path))
10896 (dired path)
10897 ;; Look into `org-link-parameters' in order to find
10898 ;; a DEDICATED-FUNCTION to open file. The function
10899 ;; will be applied on raw link instead of parsed
10900 ;; link due to the limitation in `org-add-link-type'
10901 ;; ("open" function called with a single argument).
10902 ;; If no such function is found, fallback to
10903 ;; `org-open-file'.
10904 (let* ((option (org-element-property :search-option link))
10905 (app (org-element-property :application link))
10906 (dedicated-function
10907 (org-link-get-parameter
10908 (if app (concat type "+" app) type)
10909 :follow)))
10910 (if dedicated-function
10911 (funcall dedicated-function
10912 (concat path
10913 (and option (concat "::" option))))
10914 (apply #'org-open-file
10915 path
10916 (cond (arg)
10917 ((equal app "emacs") 'emacs)
10918 ((equal app "sys") 'system))
10919 (cond ((not option) nil)
10920 ((string-match-p "\\`[0-9]+\\'" option)
10921 (list (string-to-number option)))
10922 (t (list nil
10923 (org-link-unescape option)))))))))
10924 ((functionp (org-link-get-parameter type :follow))
10925 (funcall (org-link-get-parameter type :follow) path))
10926 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10927 (unless (run-hook-with-args-until-success
10928 'org-open-link-functions path)
10929 (if (not arg) (org-mark-ring-push)
10930 (switch-to-buffer-other-window
10931 (org-get-buffer-for-internal-link (current-buffer))))
10932 (let ((destination
10933 (org-with-wide-buffer
10934 (if (equal type "radio")
10935 (org-search-radio-target
10936 (org-element-property :path link))
10937 (org-link-search
10938 (if (member type '("custom-id" "coderef"))
10939 (org-element-property :raw-link link)
10940 path)
10941 ;; Prevent fuzzy links from matching
10942 ;; themselves.
10943 (and (equal type "fuzzy")
10944 (+ 2 (org-element-property :begin link)))))
10945 (point))))
10946 (unless (and (<= (point-min) destination)
10947 (>= (point-max) destination))
10948 (widen))
10949 (goto-char destination))))
10950 (t (browse-url-at-point))))))
10951 ;; On a footnote reference or at a footnote definition's label.
10952 ((or (eq type 'footnote-reference)
10953 (and (eq type 'footnote-definition)
10954 (save-excursion
10955 ;; Do not validate action when point is on the
10956 ;; spaces right after the footnote label, in
10957 ;; order to be on par with behaviour on links.
10958 (skip-chars-forward " \t")
10959 (let ((begin
10960 (org-element-property :contents-begin context)))
10961 (if begin (< (point) begin)
10962 (= (org-element-property :post-affiliated context)
10963 (line-beginning-position)))))))
10964 (org-footnote-action))
10965 (t (user-error "No link found")))))
10966 (run-hook-with-args 'org-follow-link-hook)))
10968 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10969 "Offer links in the current entry and return the selected link.
10970 If there is only one link, return it.
10971 If NTH is an integer, return the NTH link found.
10972 If ZERO is a string, check also this string for a link, and if
10973 there is one, return it."
10974 (with-current-buffer buffer
10975 (org-with-wide-buffer
10976 (goto-char marker)
10977 (let ((cnt ?0)
10978 have-zero end links link c)
10979 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10980 (push (match-string 0 zero) links)
10981 (setq cnt (1- cnt) have-zero t))
10982 (save-excursion
10983 (org-back-to-heading t)
10984 (setq end (save-excursion (outline-next-heading) (point)))
10985 (while (re-search-forward org-any-link-re end t)
10986 (push (match-string 0) links))
10987 (setq links (org-uniquify (reverse links))))
10988 (cond
10989 ((null links)
10990 (message "No links"))
10991 ((equal (length links) 1)
10992 (setq link (car links)))
10993 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10994 (setq link (nth (if have-zero nth (1- nth)) links)))
10995 (t ; we have to select a link
10996 (save-excursion
10997 (save-window-excursion
10998 (delete-other-windows)
10999 (with-output-to-temp-buffer "*Select Link*"
11000 (dolist (l links)
11001 (cond
11002 ((not (string-match org-bracket-link-regexp l))
11003 (princ (format "[%c] %s\n" (cl-incf cnt)
11004 (org-unbracket-string "<" ">" l))))
11005 ((match-end 3)
11006 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
11007 (match-string 3 l) (match-string 1 l))))
11008 (t (princ (format "[%c] %s\n" (cl-incf cnt)
11009 (match-string 1 l)))))))
11010 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
11011 (message "Select link to open, RET to open all:")
11012 (setq c (read-char-exclusive))
11013 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
11014 (when (equal c ?q) (user-error "Abort"))
11015 (if (equal c ?\C-m)
11016 (setq link links)
11017 (setq nth (- c ?0))
11018 (when have-zero (setq nth (1+ nth)))
11019 (unless (and (integerp nth) (>= (length links) nth))
11020 (user-error "Invalid link selection"))
11021 (setq link (nth (1- nth) links)))))
11022 (cons link end)))))
11024 ;; TODO: These functions are deprecated since `org-open-at-point'
11025 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
11026 (defun org-open-file-with-system (path)
11027 "Open file at PATH using the system way of opening it."
11028 (org-open-file path 'system))
11029 (defun org-open-file-with-emacs (path)
11030 "Open file at PATH in Emacs."
11031 (org-open-file path 'emacs))
11034 ;;; File search
11036 (defvar org-create-file-search-functions nil
11037 "List of functions to construct the right search string for a file link.
11038 These functions are called in turn with point at the location to
11039 which the link should point.
11041 A function in the hook should first test if it would like to
11042 handle this file type, for example by checking the `major-mode'
11043 or the file extension. If it decides not to handle this file, it
11044 should just return nil to give other functions a chance. If it
11045 does handle the file, it must return the search string to be used
11046 when following the link. The search string will be part of the
11047 file link, given after a double colon, and `org-open-at-point'
11048 will automatically search for it. If special measures must be
11049 taken to make the search successful, another function should be
11050 added to the companion hook `org-execute-file-search-functions',
11051 which see.
11053 A function in this hook may also use `setq' to set the variable
11054 `description' to provide a suggestion for the descriptive text to
11055 be used for this link when it gets inserted into an Org buffer
11056 with \\[org-insert-link].")
11058 (defvar org-execute-file-search-functions nil
11059 "List of functions to execute a file search triggered by a link.
11061 Functions added to this hook must accept a single argument, the
11062 search string that was part of the file link, the part after the
11063 double colon. The function must first check if it would like to
11064 handle this search, for example by checking the `major-mode' or
11065 the file extension. If it decides not to handle this search, it
11066 should just return nil to give other functions a chance. If it
11067 does handle the search, it must return a non-nil value to keep
11068 other functions from trying.
11070 Each function can access the current prefix argument through the
11071 variable `current-prefix-arg'. Note that a single prefix is used
11072 to force opening a link in Emacs, so it may be good to only use a
11073 numeric or double prefix to guide the search function.
11075 In case this is needed, a function in this hook can also restore
11076 the window configuration before `org-open-at-point' was called using:
11078 \(set-window-configuration org-window-config-before-follow-link)")
11080 (defun org-search-radio-target (target)
11081 "Search a radio target matching TARGET in current buffer.
11082 White spaces are not significant."
11083 (let ((re (format "<<<%s>>>"
11084 (mapconcat #'regexp-quote
11085 (org-split-string target "[ \t\n]+")
11086 "[ \t]+\\(?:\n[ \t]*\\)?")))
11087 (origin (point)))
11088 (goto-char (point-min))
11089 (catch :radio-match
11090 (while (re-search-forward re nil t)
11091 (backward-char)
11092 (let ((object (org-element-context)))
11093 (when (eq (org-element-type object) 'radio-target)
11094 (goto-char (org-element-property :begin object))
11095 (org-show-context 'link-search)
11096 (throw :radio-match nil))))
11097 (goto-char origin)
11098 (user-error "No match for radio target: %s" target))))
11100 (defun org-link-search (s &optional avoid-pos stealth)
11101 "Search for a search string S.
11103 If S starts with \"#\", it triggers a custom ID search.
11105 If S is enclosed within parenthesis, it initiates a coderef
11106 search.
11108 If S is surrounded by forward slashes, it is interpreted as
11109 a regular expression. In Org mode files, this will create an
11110 `org-occur' sparse tree. In ordinary files, `occur' will be used
11111 to list matches. If the current buffer is in `dired-mode', grep
11112 will be used to search in all files.
11114 When AVOID-POS is given, ignore matches near that position.
11116 When optional argument STEALTH is non-nil, do not modify
11117 visibility around point, thus ignoring `org-show-context-detail'
11118 variable.
11120 Search is case-insensitive and ignores white spaces. Return type
11121 of matched result, which is either `dedicated' or `fuzzy'."
11122 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11123 (let* ((case-fold-search t)
11124 (origin (point))
11125 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11126 (words (org-split-string s "[ \t\n]+"))
11127 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11128 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11129 type)
11130 (cond
11131 ;; Check if there are any special search functions.
11132 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11133 ((eq (string-to-char s) ?#)
11134 ;; Look for a custom ID S if S starts with "#".
11135 (let* ((id (substring normalized 1))
11136 (match (org-find-property "CUSTOM_ID" id)))
11137 (if match (progn (goto-char match) (setf type 'dedicated))
11138 (error "No match for custom ID: %s" id))))
11139 ((string-match "\\`(\\(.*\\))\\'" normalized)
11140 ;; Look for coderef targets if S is enclosed within parenthesis.
11141 (let ((coderef (match-string-no-properties 1 normalized))
11142 (re (substring s-single-re 1 -1)))
11143 (goto-char (point-min))
11144 (catch :coderef-match
11145 (while (re-search-forward re nil t)
11146 (let ((element (org-element-at-point)))
11147 (when (and (memq (org-element-type element)
11148 '(example-block src-block))
11149 ;; Build proper regexp according to current
11150 ;; block's label format.
11151 (let ((label-fmt
11152 (regexp-quote
11153 (or (org-element-property :label-fmt element)
11154 org-coderef-label-format))))
11155 (save-excursion
11156 (beginning-of-line)
11157 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11158 (format label-fmt coderef))))))
11159 (setq type 'dedicated)
11160 (goto-char (match-beginning 1))
11161 (throw :coderef-match nil))))
11162 (goto-char origin)
11163 (error "No match for coderef: %s" coderef))))
11164 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11165 ;; Look for a regular expression.
11166 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11167 (match-string 1 s)))
11168 ;; Fuzzy links.
11170 (let ((starred (eq (string-to-char normalized) ?*)))
11171 (cond
11172 ;; Look for targets, only if not in a headline search.
11173 ((and (not starred)
11174 (let ((target (format "<<%s>>" s-multi-re)))
11175 (catch :target-match
11176 (goto-char (point-min))
11177 (while (re-search-forward target nil t)
11178 (backward-char)
11179 (let ((context (org-element-context)))
11180 (when (eq (org-element-type context) 'target)
11181 (setq type 'dedicated)
11182 (goto-char (org-element-property :begin context))
11183 (throw :target-match t))))
11184 nil))))
11185 ;; Look for elements named after S, only if not in a headline
11186 ;; search.
11187 ((and (not starred)
11188 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11189 (catch :name-match
11190 (goto-char (point-min))
11191 (while (re-search-forward name nil t)
11192 (let ((element (org-element-at-point)))
11193 (when (equal (org-split-string
11194 (org-element-property :name element)
11195 "[ \t]+")
11196 words)
11197 (setq type 'dedicated)
11198 (beginning-of-line)
11199 (throw :name-match t))))
11200 nil))))
11201 ;; Regular text search. Prefer headlines in Org mode
11202 ;; buffers.
11203 ((and (derived-mode-p 'org-mode)
11204 (let* ((wspace "[ \t]")
11205 (wspaceopt (concat wspace "*"))
11206 (cookie (concat "\\(?:"
11207 wspaceopt
11208 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11209 wspaceopt
11210 "\\)"))
11211 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11212 (re (concat
11213 org-outline-regexp-bol
11214 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11215 "\\(?:\\[#.\\][ \t]+\\)?"
11216 "\\(?:" org-comment-string "[ \t]+\\)?"
11217 sep "?"
11218 (let ((title (mapconcat #'regexp-quote
11219 words
11220 sep)))
11221 (if starred (substring title 1) title))
11222 sep "?"
11223 "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
11224 "[ \t]*$")))
11225 (goto-char (point-min))
11226 (re-search-forward re nil t)))
11227 (goto-char (match-beginning 0))
11228 (setq type 'dedicated))
11229 ;; Offer to create non-existent headline depending on
11230 ;; `org-link-search-must-match-exact-headline'.
11231 ((and (derived-mode-p 'org-mode)
11232 (not org-link-search-inhibit-query)
11233 (eq org-link-search-must-match-exact-headline 'query-to-create)
11234 (yes-or-no-p "No match - create this as a new heading? "))
11235 (goto-char (point-max))
11236 (unless (bolp) (newline))
11237 (org-insert-heading nil t t)
11238 (insert s "\n")
11239 (beginning-of-line 0))
11240 ;; Only headlines are looked after. No need to process
11241 ;; further: throw an error.
11242 ((and (derived-mode-p 'org-mode)
11243 (or starred org-link-search-must-match-exact-headline))
11244 (goto-char origin)
11245 (error "No match for fuzzy expression: %s" normalized))
11246 ;; Regular text search.
11247 ((catch :fuzzy-match
11248 (goto-char (point-min))
11249 (while (re-search-forward s-multi-re nil t)
11250 ;; Skip match if it contains AVOID-POS or it is included
11251 ;; in a link with a description but outside the
11252 ;; description.
11253 (unless (or (and avoid-pos
11254 (<= (match-beginning 0) avoid-pos)
11255 (> (match-end 0) avoid-pos))
11256 (and (save-match-data
11257 (org-in-regexp org-bracket-link-regexp))
11258 (match-beginning 3)
11259 (or (> (match-beginning 3) (point))
11260 (<= (match-end 3) (point)))
11261 (org-element-lineage
11262 (save-match-data (org-element-context))
11263 '(link) t)))
11264 (goto-char (match-beginning 0))
11265 (setq type 'fuzzy)
11266 (throw :fuzzy-match t)))
11267 nil))
11268 ;; All failed. Throw an error.
11269 (t (goto-char origin)
11270 (error "No match for fuzzy expression: %s" normalized))))))
11271 ;; Disclose surroundings of match, if appropriate.
11272 (when (and (derived-mode-p 'org-mode) (not stealth))
11273 (org-show-context 'link-search))
11274 type))
11276 (defun org-get-buffer-for-internal-link (buffer)
11277 "Return a buffer to be used for displaying the link target of internal links."
11278 (cond
11279 ((not org-display-internal-link-with-indirect-buffer)
11280 buffer)
11281 ((string-suffix-p "(Clone)" (buffer-name buffer))
11282 (message "Buffer is already a clone, not making another one")
11283 ;; we also do not modify visibility in this case
11284 buffer)
11285 (t ; make a new indirect buffer for displaying the link
11286 (let* ((bn (buffer-name buffer))
11287 (ibn (concat bn "(Clone)"))
11288 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11289 (with-current-buffer ib (org-overview))
11290 ib))))
11292 (defun org-do-occur (regexp &optional cleanup)
11293 "Call the Emacs command `occur'.
11294 If CLEANUP is non-nil, remove the printout of the regular expression
11295 in the *Occur* buffer. This is useful if the regex is long and not useful
11296 to read."
11297 (occur regexp)
11298 (when cleanup
11299 (let ((cwin (selected-window)) win beg end)
11300 (when (setq win (get-buffer-window "*Occur*"))
11301 (select-window win))
11302 (goto-char (point-min))
11303 (when (re-search-forward "match[a-z]+" nil t)
11304 (setq beg (match-end 0))
11305 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11306 (setq end (1- (match-beginning 0)))))
11307 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11308 (goto-char (point-min))
11309 (select-window cwin))))
11311 ;;; The mark ring for links jumps
11313 (defvar org-mark-ring nil
11314 "Mark ring for positions before jumps in Org mode.")
11315 (defvar org-mark-ring-last-goto nil
11316 "Last position in the mark ring used to go back.")
11317 ;; Fill and close the ring
11318 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11319 (dotimes (_ org-mark-ring-length)
11320 (push (make-marker) org-mark-ring))
11321 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11322 org-mark-ring)
11324 (defun org-mark-ring-push (&optional pos buffer)
11325 "Put the current position or POS into the mark ring and rotate it."
11326 (interactive)
11327 (setq pos (or pos (point)))
11328 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11329 (move-marker (car org-mark-ring)
11330 (or pos (point))
11331 (or buffer (current-buffer)))
11332 (message "%s"
11333 (substitute-command-keys
11334 "Position saved to mark ring, go back with \
11335 `\\[org-mark-ring-goto]'.")))
11337 (defun org-mark-ring-goto (&optional n)
11338 "Jump to the previous position in the mark ring.
11339 With prefix arg N, jump back that many stored positions. When
11340 called several times in succession, walk through the entire ring.
11341 Org mode commands jumping to a different position in the current file,
11342 or to another Org file, automatically push the old position onto the ring."
11343 (interactive "p")
11344 (let (p m)
11345 (if (eq last-command this-command)
11346 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11347 (setq p org-mark-ring))
11348 (setq org-mark-ring-last-goto p)
11349 (setq m (car p))
11350 (pop-to-buffer-same-window (marker-buffer m))
11351 (goto-char m)
11352 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11354 (defun org-add-angle-brackets (s)
11355 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11356 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11359 ;;; Following specific links
11361 (defvar org-agenda-buffer-tmp-name)
11362 (defvar org-agenda-start-on-weekday)
11363 (defun org-follow-timestamp-link ()
11364 "Open an agenda view for the time-stamp date/range at point."
11365 (cond
11366 ((org-at-date-range-p t)
11367 (let ((org-agenda-start-on-weekday)
11368 (t1 (match-string 1))
11369 (t2 (match-string 2)) tt1 tt2)
11370 (setq tt1 (time-to-days (org-time-string-to-time t1))
11371 tt2 (time-to-days (org-time-string-to-time t2)))
11372 (let ((org-agenda-buffer-tmp-name
11373 (format "*Org Agenda(a:%s)"
11374 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11375 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11376 ((org-at-timestamp-p t)
11377 (let ((org-agenda-buffer-tmp-name
11378 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11379 (org-agenda-list nil (time-to-days (org-time-string-to-time
11380 (substring (match-string 1) 0 10)))
11381 1)))
11382 (t (error "This should not happen"))))
11385 ;;; Following file links
11386 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11387 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11388 (declare-function mailcap-mime-info
11389 "mailcap" (string &optional request no-decode))
11390 (defvar org-wait nil)
11391 (defun org-open-file (path &optional in-emacs line search)
11392 "Open the file at PATH.
11393 First, this expands any special file name abbreviations. Then the
11394 configuration variable `org-file-apps' is checked if it contains an
11395 entry for this file type, and if yes, the corresponding command is launched.
11397 If no application is found, Emacs simply visits the file.
11399 With optional prefix argument IN-EMACS, Emacs will visit the file.
11400 With a double \\[universal-argument] \\[universal-argument] \
11401 prefix arg, Org tries to avoid opening in Emacs
11402 and to use an external application to visit the file.
11404 Optional LINE specifies a line to go to, optional SEARCH a string
11405 to search for. If LINE or SEARCH is given, the file will be
11406 opened in Emacs, unless an entry from org-file-apps that makes
11407 use of groups in a regexp matches.
11409 If you want to change the way frames are used when following a
11410 link, please customize `org-link-frame-setup'.
11412 If the file does not exist, an error is thrown."
11413 (let* ((file (if (equal path "")
11414 buffer-file-name
11415 (substitute-in-file-name (expand-file-name path))))
11416 (file-apps (append org-file-apps (org-default-apps)))
11417 (apps (cl-remove-if
11418 'org-file-apps-entry-match-against-dlink-p file-apps))
11419 (apps-dlink (cl-remove-if-not
11420 'org-file-apps-entry-match-against-dlink-p file-apps))
11421 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11422 (dirp (unless remp (file-directory-p file)))
11423 (file (if (and dirp org-open-directory-means-index-dot-org)
11424 (concat (file-name-as-directory file) "index.org")
11425 file))
11426 (a-m-a-p (assq 'auto-mode apps))
11427 (dfile (downcase file))
11428 ;; Reconstruct the original link from the PATH, LINE and
11429 ;; SEARCH args.
11430 (link (cond (line (concat file "::" (number-to-string line)))
11431 (search (concat file "::" search))
11432 (t file)))
11433 (dlink (downcase link))
11434 (old-buffer (current-buffer))
11435 (old-pos (point))
11436 (old-mode major-mode)
11437 (ext
11438 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11439 (match-string 1 dfile)))
11440 cmd link-match-data)
11441 (cond
11442 ((member in-emacs '((16) system))
11443 (setq cmd (cdr (assq 'system apps))))
11444 (in-emacs (setq cmd 'emacs))
11446 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11447 (and dirp (cdr (assq 'directory apps)))
11448 ;; First, try matching against apps-dlink if we
11449 ;; get a match here, store the match data for
11450 ;; later.
11451 (let ((match (assoc-default dlink apps-dlink
11452 'string-match)))
11453 (if match
11454 (progn (setq link-match-data (match-data))
11455 match)
11456 (progn (setq in-emacs (or in-emacs line search))
11457 nil))) ; if we have no match in apps-dlink,
11458 ; always open the file in emacs if line or search
11459 ; is given (for backwards compatibility)
11460 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11461 'string-match)
11462 (cdr (assoc ext apps))
11463 (cdr (assq t apps))))))
11464 (when (eq cmd 'system)
11465 (setq cmd (cdr (assq 'system apps))))
11466 (when (eq cmd 'default)
11467 (setq cmd (cdr (assoc t apps))))
11468 (when (eq cmd 'mailcap)
11469 (require 'mailcap)
11470 (mailcap-parse-mailcaps)
11471 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11472 (command (mailcap-mime-info mime-type)))
11473 (if (stringp command)
11474 (setq cmd command)
11475 (setq cmd 'emacs))))
11476 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11477 (not (file-exists-p file))
11478 (not org-open-non-existing-files))
11479 (user-error "No such file: %s" file))
11480 (cond
11481 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11482 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11483 (while (string-match "['\"]%s['\"]" cmd)
11484 (setq cmd (replace-match "%s" t t cmd)))
11485 (setq cmd (replace-regexp-in-string
11486 "%s"
11487 (shell-quote-argument (convert-standard-filename file))
11489 nil t))
11491 ;; Replace "%1", "%2" etc. in command with group matches from regex
11492 (save-match-data
11493 (let ((match-index 1)
11494 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11495 (set-match-data link-match-data)
11496 (while (<= match-index number-of-groups)
11497 (let ((regex (concat "%" (number-to-string match-index)))
11498 (replace-with (match-string match-index dlink)))
11499 (while (string-match regex cmd)
11500 (setq cmd (replace-match replace-with t t cmd))))
11501 (setq match-index (+ match-index 1)))))
11503 (save-window-excursion
11504 (message "Running %s...done" cmd)
11505 (start-process-shell-command cmd nil cmd)
11506 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11507 ((or (stringp cmd)
11508 (eq cmd 'emacs))
11509 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11510 (widen)
11511 (cond (line (org-goto-line line)
11512 (when (derived-mode-p 'org-mode) (org-reveal)))
11513 (search (org-link-search search))))
11514 ((functionp cmd)
11515 (save-match-data
11516 (set-match-data link-match-data)
11517 (condition-case nil
11518 (funcall cmd file link)
11519 ;; FIXME: Remove this check when most default installations
11520 ;; of Emacs have at least Org 9.0.
11521 ((debug wrong-number-of-arguments wrong-type-argument
11522 invalid-function)
11523 (user-error "Please see Org News for version 9.0 about \
11524 `org-file-apps'--Lisp error: %S" cmd)))))
11525 ((consp cmd)
11526 ;; FIXME: Remove this check when most default installations of
11527 ;; Emacs have at least Org 9.0.
11528 ;; Heads-up instead of silently fall back to
11529 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11530 ;; with sexp instead of a function for `cmd'.
11531 (user-error "Please see Org News for version 9.0 about \
11532 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11533 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11534 (and (derived-mode-p 'org-mode)
11535 (eq old-mode 'org-mode)
11536 (or (not (eq old-buffer (current-buffer)))
11537 (not (eq old-pos (point))))
11538 (org-mark-ring-push old-pos old-buffer))))
11540 (defun org-file-apps-entry-match-against-dlink-p (entry)
11541 "This function returns non-nil if `entry' uses a regular
11542 expression which should be matched against the whole link by
11543 org-open-file.
11545 It assumes that is the case when the entry uses a regular
11546 expression which has at least one grouping construct and the
11547 action is either a lisp form or a command string containing
11548 `%1', i.e. using at least one subexpression match as a
11549 parameter."
11550 (let ((selector (car entry))
11551 (action (cdr entry)))
11552 (if (stringp selector)
11553 (and (> (regexp-opt-depth selector) 0)
11554 (or (and (stringp action)
11555 (string-match "%[0-9]" action))
11556 (consp action)))
11557 nil)))
11559 (defun org-default-apps ()
11560 "Return the default applications for this operating system."
11561 (cond
11562 ((eq system-type 'darwin)
11563 org-file-apps-defaults-macosx)
11564 ((eq system-type 'windows-nt)
11565 org-file-apps-defaults-windowsnt)
11566 (t org-file-apps-defaults-gnu)))
11568 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11569 "Convert extensions to regular expressions in the cars of LIST.
11570 Also, weed out any non-string entries, because the return value is used
11571 only for regexp matching.
11572 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11573 point to the symbol `emacs', indicating that the file should
11574 be opened in Emacs."
11575 (append
11576 (delq nil
11577 (mapcar (lambda (x)
11578 (unless (not (stringp (car x)))
11579 (if (string-match "\\W" (car x))
11581 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11582 list))
11583 (when add-auto-mode
11584 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11586 (defvar ange-ftp-name-format)
11587 (defun org-file-remote-p (file)
11588 "Test whether FILE specifies a location on a remote system.
11589 Return non-nil if the location is indeed remote.
11591 For example, the filename \"/user@host:/foo\" specifies a location
11592 on the system \"/user@host:\"."
11593 (cond ((fboundp 'file-remote-p)
11594 (file-remote-p file))
11595 ((fboundp 'tramp-handle-file-remote-p)
11596 (tramp-handle-file-remote-p file))
11597 ((and (boundp 'ange-ftp-name-format)
11598 (string-match (car ange-ftp-name-format) file))
11599 t)))
11602 ;;;; Refiling
11604 (defun org-get-org-file ()
11605 "Read a filename, with default directory `org-directory'."
11606 (let ((default (or org-default-notes-file remember-data-file)))
11607 (read-file-name (format "File name [%s]: " default)
11608 (file-name-as-directory org-directory)
11609 default)))
11611 (defun org-notes-order-reversed-p ()
11612 "Check if the current file should receive notes in reversed order."
11613 (cond
11614 ((not org-reverse-note-order) nil)
11615 ((eq t org-reverse-note-order) t)
11616 ((not (listp org-reverse-note-order)) nil)
11617 (t (catch 'exit
11618 (dolist (entry org-reverse-note-order)
11619 (when (string-match (car entry) buffer-file-name)
11620 (throw 'exit (cdr entry))))))))
11622 (defvar org-refile-target-table nil
11623 "The list of refile targets, created by `org-refile'.")
11625 (defvar org-agenda-new-buffers nil
11626 "Buffers created to visit agenda files.")
11628 (defvar org-refile-cache nil
11629 "Cache for refile targets.")
11631 (defvar org-refile-markers nil
11632 "All the markers used for caching refile locations.")
11634 (defun org-refile-marker (pos)
11635 "Get a new refile marker, but only if caching is in use."
11636 (if (not org-refile-use-cache)
11638 (let ((m (make-marker)))
11639 (move-marker m pos)
11640 (push m org-refile-markers)
11641 m)))
11643 (defun org-refile-cache-clear ()
11644 "Clear the refile cache and disable all the markers."
11645 (dolist (m org-refile-markers) (move-marker m nil))
11646 (setq org-refile-markers nil)
11647 (setq org-refile-cache nil)
11648 (message "Refile cache has been cleared"))
11650 (defun org-refile-cache-check-set (set)
11651 "Check if all the markers in the cache still have live buffers."
11652 (let (marker)
11653 (catch 'exit
11654 (while (and set (setq marker (nth 3 (pop set))))
11655 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11656 (when (and marker (null (marker-buffer marker)))
11657 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11658 (sit-for 3)
11659 (throw 'exit nil)))
11660 t)))
11662 (defun org-refile-cache-put (set &rest identifiers)
11663 "Push the refile targets SET into the cache, under IDENTIFIERS."
11664 (let* ((key (sha1 (prin1-to-string identifiers)))
11665 (entry (assoc key org-refile-cache)))
11666 (if entry
11667 (setcdr entry set)
11668 (push (cons key set) org-refile-cache))))
11670 (defun org-refile-cache-get (&rest identifiers)
11671 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11672 (cond
11673 ((not org-refile-cache) nil)
11674 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11676 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11677 org-refile-cache))))
11678 (and set (org-refile-cache-check-set set) set)))))
11680 (defvar org-outline-path-cache nil
11681 "Alist between buffer positions and outline paths.
11682 It value is an alist (POSITION . PATH) where POSITION is the
11683 buffer position at the beginning of an entry and PATH is a list
11684 of strings describing the outline path for that entry, in reverse
11685 order.")
11687 (defun org-refile-get-targets (&optional default-buffer)
11688 "Produce a table with refile targets."
11689 (let ((case-fold-search nil)
11690 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11691 (entries (or org-refile-targets '((nil . (:level . 1)))))
11692 targets tgs files desc descre)
11693 (message "Getting targets...")
11694 (with-current-buffer (or default-buffer (current-buffer))
11695 (dolist (entry entries)
11696 (setq files (car entry) desc (cdr entry))
11697 (cond
11698 ((null files) (setq files (list (current-buffer))))
11699 ((eq files 'org-agenda-files)
11700 (setq files (org-agenda-files 'unrestricted)))
11701 ((and (symbolp files) (fboundp files))
11702 (setq files (funcall files)))
11703 ((and (symbolp files) (boundp files))
11704 (setq files (symbol-value files))))
11705 (when (stringp files) (setq files (list files)))
11706 (cond
11707 ((eq (car desc) :tag)
11708 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11709 ((eq (car desc) :todo)
11710 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11711 ((eq (car desc) :regexp)
11712 (setq descre (cdr desc)))
11713 ((eq (car desc) :level)
11714 (setq descre (concat "^\\*\\{" (number-to-string
11715 (if org-odd-levels-only
11716 (1- (* 2 (cdr desc)))
11717 (cdr desc)))
11718 "\\}[ \t]")))
11719 ((eq (car desc) :maxlevel)
11720 (setq descre (concat "^\\*\\{1," (number-to-string
11721 (if org-odd-levels-only
11722 (1- (* 2 (cdr desc)))
11723 (cdr desc)))
11724 "\\}[ \t]")))
11725 (t (error "Bad refiling target description %s" desc)))
11726 (dolist (f files)
11727 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11729 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11730 (progn
11731 (when (bufferp f)
11732 (setq f (buffer-file-name (buffer-base-buffer f))))
11733 (setq f (and f (expand-file-name f)))
11734 (when (eq org-refile-use-outline-path 'file)
11735 (push (list (file-name-nondirectory f) f nil nil) tgs))
11736 (org-with-wide-buffer
11737 (goto-char (point-min))
11738 (setq org-outline-path-cache nil)
11739 (while (re-search-forward descre nil t)
11740 (beginning-of-line)
11741 (looking-at org-complex-heading-regexp)
11742 (let ((begin (point))
11743 (heading (match-string-no-properties 4)))
11744 (unless (or (and
11745 org-refile-target-verify-function
11746 (not
11747 (funcall org-refile-target-verify-function)))
11748 (not heading))
11749 (let ((re (format org-complex-heading-regexp-format
11750 (regexp-quote heading)))
11751 (target
11752 (if (not org-refile-use-outline-path) heading
11753 (mapconcat
11754 #'org-protect-slash
11755 (append
11756 (pcase org-refile-use-outline-path
11757 (`file (list (file-name-nondirectory
11758 (buffer-file-name
11759 (buffer-base-buffer)))))
11760 (`full-file-path
11761 (list (buffer-file-name
11762 (buffer-base-buffer))))
11763 (_ nil))
11764 (org-get-outline-path t t))
11765 "/"))))
11766 (push (list target f re (org-refile-marker (point)))
11767 tgs)))
11768 (when (= (point) begin)
11769 ;; Verification function has not moved point.
11770 (end-of-line)))))))
11771 (when org-refile-use-cache
11772 (org-refile-cache-put tgs (buffer-file-name) descre))
11773 (setq targets (append tgs targets))))))
11774 (message "Getting targets...done")
11775 (nreverse targets)))
11777 (defun org-protect-slash (s)
11778 (replace-regexp-in-string "/" "\\/" s nil t))
11780 (defun org--get-outline-path-1 (&optional use-cache)
11781 "Return outline path to current headline.
11783 Outline path is a list of strings, in reverse order. When
11784 optional argument USE-CACHE is non-nil, make use of a cache. See
11785 `org-get-outline-path' for details.
11787 Assume buffer is widened and point is on a headline."
11788 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11789 (let ((p (point))
11790 (heading (progn
11791 (looking-at org-complex-heading-regexp)
11792 (if (not (match-end 4)) ""
11793 ;; Remove statistics cookies.
11794 (org-trim
11795 (org-link-display-format
11796 (replace-regexp-in-string
11797 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11798 (match-string-no-properties 4))))))))
11799 (if (org-up-heading-safe)
11800 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11801 (when use-cache
11802 (push (cons p path) org-outline-path-cache))
11803 path)
11804 ;; This is a new root node. Since we assume we are moving
11805 ;; forward, we can drop previous cache so as to limit number
11806 ;; of associations there.
11807 (let ((path (list heading)))
11808 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11809 path)))))
11811 (defun org-get-outline-path (&optional with-self use-cache)
11812 "Return the outline path to the current entry.
11814 An outline path is a list of ancestors for current headline, as
11815 a list of strings. Statistics cookies are removed and links are
11816 replaced with their description, if any, or their path otherwise.
11818 When optional argument WITH-SELF is non-nil, the path also
11819 includes the current headline.
11821 When optional argument USE-CACHE is non-nil, cache outline paths
11822 between calls to this function so as to avoid backtracking. This
11823 argument is useful when planning to find more than one outline
11824 path in the same document. In that case, there are two
11825 conditions to satisfy:
11826 - `org-outline-path-cache' is set to nil before starting the
11827 process;
11828 - outline paths are computed by increasing buffer positions."
11829 (org-with-wide-buffer
11830 (and (or (and with-self (org-back-to-heading t))
11831 (org-up-heading-safe))
11832 (reverse (org--get-outline-path-1 use-cache)))))
11834 (defun org-format-outline-path (path &optional width prefix separator)
11835 "Format the outline path PATH for display.
11836 WIDTH is the maximum number of characters that is available.
11837 PREFIX is a prefix to be included in the returned string,
11838 such as the file name.
11839 SEPARATOR is inserted between the different parts of the path,
11840 the default is \"/\"."
11841 (setq width (or width 79))
11842 (setq path (delq nil path))
11843 (unless (> width 0)
11844 (user-error "Argument `width' must be positive"))
11845 (setq separator (or separator "/"))
11846 (let* ((org-odd-levels-only nil)
11847 (fpath (concat
11848 prefix (and prefix path separator)
11849 (mapconcat
11850 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11851 (cl-loop for head in path
11852 for n from 0
11853 collect (org-add-props
11854 head nil 'face
11855 (nth (% n org-n-level-faces) org-level-faces)))
11856 separator))))
11857 (when (> (length fpath) width)
11858 (if (< width 7)
11859 ;; It's unlikely that `width' will be this small, but don't
11860 ;; waste characters by adding ".." if it is.
11861 (setq fpath (substring fpath 0 width))
11862 (setf (substring fpath (- width 2)) "..")))
11863 fpath))
11865 (defun org-display-outline-path (&optional file current separator just-return-string)
11866 "Display the current outline path in the echo area.
11868 If FILE is non-nil, prepend the output with the file name.
11869 If CURRENT is non-nil, append the current heading to the output.
11870 SEPARATOR is passed through to `org-format-outline-path'. It separates
11871 the different parts of the path and defaults to \"/\".
11872 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11873 (interactive "P")
11874 (let* (case-fold-search
11875 (bfn (buffer-file-name (buffer-base-buffer)))
11876 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11877 res)
11878 (when current (setq path (append path
11879 (save-excursion
11880 (org-back-to-heading t)
11881 (when (looking-at org-complex-heading-regexp)
11882 (list (match-string 4)))))))
11883 (setq res
11884 (org-format-outline-path
11885 path
11886 (1- (frame-width))
11887 (and file bfn (concat (file-name-nondirectory bfn) separator))
11888 separator))
11889 (if just-return-string
11890 (org-no-properties res)
11891 (org-unlogged-message "%s" res))))
11893 (defvar org-refile-history nil
11894 "History for refiling operations.")
11896 (defvar org-after-refile-insert-hook nil
11897 "Hook run after `org-refile' has inserted its stuff at the new location.
11898 Note that this is still *before* the stuff will be removed from
11899 the *old* location.")
11901 (defvar org-capture-last-stored-marker)
11902 (defvar org-refile-keep nil
11903 "Non-nil means `org-refile' will copy instead of refile.")
11905 (defun org-copy ()
11906 "Like `org-refile', but copy."
11907 (interactive)
11908 (let ((org-refile-keep t))
11909 (funcall 'org-refile nil nil nil "Copy")))
11911 (defun org-refile (&optional arg default-buffer rfloc msg)
11912 "Move the entry or entries at point to another heading.
11914 The list of target headings is compiled using the information in
11915 `org-refile-targets', which see.
11917 At the target location, the entry is filed as a subitem of the
11918 target heading. Depending on `org-reverse-note-order', the new
11919 subitem will either be the first or the last subitem.
11921 If there is an active region, all entries in that region will be
11922 refiled. However, the region must fulfill the requirement that
11923 the first heading sets the top-level of the moved text.
11925 With a `\\[universal-argument]' ARG, the command will only visit the target \
11926 location
11927 and not actually move anything.
11929 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11930 location where the last
11931 refiling operation has put the subtree.
11933 With a numeric prefix argument of `2', refile to the running clock.
11935 With a numeric prefix argument of `3', emulate `org-refile-keep'
11936 being set to t and copy to the target location, don't move it.
11937 Beware that keeping refiled entries may result in duplicated ID
11938 properties.
11940 RFLOC can be a refile location obtained in a different way.
11942 MSG is a string to replace \"Refile\" in the default prompt with
11943 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11945 See also `org-refile-use-outline-path'.
11947 If you are using target caching (see `org-refile-use-cache'), you
11948 have to clear the target cache in order to find new targets.
11949 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11950 prefix argument (`C-u C-u C-u C-c C-w')."
11951 (interactive "P")
11952 (if (member arg '(0 (64)))
11953 (org-refile-cache-clear)
11954 (let* ((actionmsg (cond (msg msg)
11955 ((equal arg 3) "Refile (and keep)")
11956 (t "Refile")))
11957 (regionp (org-region-active-p))
11958 (region-start (and regionp (region-beginning)))
11959 (region-end (and regionp (region-end)))
11960 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11961 pos it nbuf file level reversed)
11962 (setq last-command nil)
11963 (when regionp
11964 (goto-char region-start)
11965 (or (bolp) (goto-char (point-at-bol)))
11966 (setq region-start (point))
11967 (unless (or (org-kill-is-subtree-p
11968 (buffer-substring region-start region-end))
11969 (prog1 org-refile-active-region-within-subtree
11970 (let ((s (point-at-eol)))
11971 (org-toggle-heading)
11972 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11973 (user-error "The region is not a (sequence of) subtree(s)")))
11974 (if (equal arg '(16))
11975 (org-refile-goto-last-stored)
11976 (when (or
11977 (and (equal arg 2)
11978 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11979 (prog1
11980 (setq it (list (or org-clock-heading "running clock")
11981 (buffer-file-name
11982 (marker-buffer org-clock-hd-marker))
11984 (marker-position org-clock-hd-marker)))
11985 (setq arg nil)))
11986 (setq it
11987 (or rfloc
11988 (let (heading-text)
11989 (save-excursion
11990 (unless (and arg (listp arg))
11991 (org-back-to-heading t)
11992 (setq heading-text
11993 (replace-regexp-in-string
11994 org-bracket-link-regexp
11995 "\\3"
11996 (or (nth 4 (org-heading-components))
11997 ""))))
11998 (org-refile-get-location
11999 (cond ((and arg (listp arg)) "Goto")
12000 (regionp (concat actionmsg " region to"))
12001 (t (concat actionmsg " subtree \""
12002 heading-text "\" to")))
12003 default-buffer
12004 (and (not (equal '(4) arg))
12005 org-refile-allow-creating-parent-nodes)))))))
12006 (setq file (nth 1 it)
12007 pos (nth 3 it))
12008 (when (and (not arg)
12010 (equal (buffer-file-name) file)
12011 (if regionp
12012 (and (>= pos region-start)
12013 (<= pos region-end))
12014 (and (>= pos (point))
12015 (< pos (save-excursion
12016 (org-end-of-subtree t t))))))
12017 (error "Cannot refile to position inside the tree or region"))
12018 (setq nbuf (or (find-buffer-visiting file)
12019 (find-file-noselect file)))
12020 (if (and arg (not (equal arg 3)))
12021 (progn
12022 (pop-to-buffer-same-window nbuf)
12023 (goto-char pos)
12024 (org-show-context 'org-goto))
12025 (if regionp
12026 (progn
12027 (org-kill-new (buffer-substring region-start region-end))
12028 (org-save-markers-in-region region-start region-end))
12029 (org-copy-subtree 1 nil t))
12030 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
12031 (find-file-noselect file)))
12032 (setq reversed (org-notes-order-reversed-p))
12033 (org-with-wide-buffer
12034 (if pos
12035 (progn
12036 (goto-char pos)
12037 (looking-at org-outline-regexp)
12038 (setq level (org-get-valid-level (funcall outline-level) 1))
12039 (goto-char
12040 (if reversed
12041 (or (outline-next-heading) (point-max))
12042 (or (save-excursion (org-get-next-sibling))
12043 (org-end-of-subtree t t)
12044 (point-max)))))
12045 (setq level 1)
12046 (if (not reversed)
12047 (goto-char (point-max))
12048 (goto-char (point-min))
12049 (or (outline-next-heading) (goto-char (point-max)))))
12050 (unless (bolp) (newline))
12051 (org-paste-subtree level nil nil t)
12052 (when org-log-refile
12053 (org-add-log-setup 'refile nil nil org-log-refile)
12054 (unless (eq org-log-refile 'note)
12055 (save-excursion (org-add-log-note))))
12056 (and org-auto-align-tags
12057 (let ((org-loop-over-headlines-in-active-region nil))
12058 (org-set-tags nil t)))
12059 (let ((bookmark-name (plist-get org-bookmark-names-plist
12060 :last-refile)))
12061 (when bookmark-name
12062 (with-demoted-errors
12063 (bookmark-set bookmark-name))))
12064 ;; If we are refiling for capture, make sure that the
12065 ;; last-capture pointers point here
12066 (when (bound-and-true-p org-capture-is-refiling)
12067 (let ((bookmark-name (plist-get org-bookmark-names-plist
12068 :last-capture-marker)))
12069 (when bookmark-name
12070 (with-demoted-errors
12071 (bookmark-set bookmark-name))))
12072 (move-marker org-capture-last-stored-marker (point)))
12073 (when (fboundp 'deactivate-mark) (deactivate-mark))
12074 (run-hooks 'org-after-refile-insert-hook)))
12075 (unless org-refile-keep
12076 (if regionp
12077 (delete-region (point) (+ (point) (- region-end region-start)))
12078 (delete-region
12079 (and (org-back-to-heading t) (point))
12080 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12081 (when (featurep 'org-inlinetask)
12082 (org-inlinetask-remove-END-maybe))
12083 (setq org-markers-to-move nil)
12084 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12086 (defun org-refile-goto-last-stored ()
12087 "Go to the location where the last refile was stored."
12088 (interactive)
12089 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12090 (message "This is the location of the last refile"))
12092 (defun org-refile--get-location (refloc tbl)
12093 "When user refile to REFLOC, find the associated target in TBL.
12094 Also check `org-refile-target-table'."
12095 (car (delq
12097 (mapcar
12098 (lambda (r) (or (assoc r tbl)
12099 (assoc r org-refile-target-table)))
12100 (list (replace-regexp-in-string "/$" "" refloc)
12101 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12103 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12104 "Prompt the user for a refile location, using PROMPT.
12105 PROMPT should not be suffixed with a colon and a space, because
12106 this function appends the default value from
12107 `org-refile-history' automatically, if that is not empty."
12108 (let ((org-refile-targets org-refile-targets)
12109 (org-refile-use-outline-path org-refile-use-outline-path))
12110 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12111 (unless org-refile-target-table
12112 (user-error "No refile targets"))
12113 (let* ((cbuf (current-buffer))
12114 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12115 (cfunc (if (and org-refile-use-outline-path
12116 org-outline-path-complete-in-steps)
12117 #'org-olpath-completing-read
12118 #'completing-read))
12119 (extra (if org-refile-use-outline-path "/" ""))
12120 (cbnex (concat (buffer-name) extra))
12121 (filename (and cfn (expand-file-name cfn)))
12122 (tbl (mapcar
12123 (lambda (x)
12124 (if (and (not (member org-refile-use-outline-path
12125 '(file full-file-path)))
12126 (not (equal filename (nth 1 x))))
12127 (cons (concat (car x) extra " ("
12128 (file-name-nondirectory (nth 1 x)) ")")
12129 (cdr x))
12130 (cons (concat (car x) extra) (cdr x))))
12131 org-refile-target-table))
12132 (completion-ignore-case t)
12133 cdef
12134 (prompt (concat prompt
12135 (or (and (car org-refile-history)
12136 (concat " (default " (car org-refile-history) ")"))
12137 (and (assoc cbnex tbl) (setq cdef cbnex)
12138 (concat " (default " cbnex ")"))) ": "))
12139 pa answ parent-target child parent old-hist)
12140 (setq old-hist org-refile-history)
12141 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12142 nil 'org-refile-history (or cdef (car org-refile-history))))
12143 (if (setq pa (org-refile--get-location answ tbl))
12144 (progn
12145 (org-refile-check-position pa)
12146 (when (or (not org-refile-history)
12147 (not (eq old-hist org-refile-history))
12148 (not (equal (car pa) (car org-refile-history))))
12149 (setq org-refile-history
12150 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12151 org-refile-history
12152 (cdr org-refile-history))))
12153 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12154 (pop org-refile-history)))
12156 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12157 (progn
12158 (setq parent (match-string 1 answ)
12159 child (match-string 2 answ))
12160 (setq parent-target (org-refile--get-location parent tbl))
12161 (when (and parent-target
12162 (or (eq new-nodes t)
12163 (and (eq new-nodes 'confirm)
12164 (y-or-n-p (format "Create new node \"%s\"? "
12165 child)))))
12166 (org-refile-new-child parent-target child)))
12167 (user-error "Invalid target location")))))
12169 (declare-function org-string-nw-p "org-macs" (s))
12170 (defun org-refile-check-position (refile-pointer)
12171 "Check if the refile pointer matches the headline to which it points."
12172 (let* ((file (nth 1 refile-pointer))
12173 (re (nth 2 refile-pointer))
12174 (pos (nth 3 refile-pointer))
12175 buffer)
12176 (if (and (not (markerp pos)) (not file))
12177 (user-error "Please indicate a target file in the refile path")
12178 (when (org-string-nw-p re)
12179 (setq buffer (if (markerp pos)
12180 (marker-buffer pos)
12181 (or (find-buffer-visiting file)
12182 (find-file-noselect file))))
12183 (with-current-buffer buffer
12184 (org-with-wide-buffer
12185 (goto-char pos)
12186 (beginning-of-line 1)
12187 (unless (looking-at-p re)
12188 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12190 (defun org-refile-new-child (parent-target child)
12191 "Use refile target PARENT-TARGET to add new CHILD below it."
12192 (unless parent-target
12193 (error "Cannot find parent for new node"))
12194 (let ((file (nth 1 parent-target))
12195 (pos (nth 3 parent-target))
12196 level)
12197 (with-current-buffer (or (find-buffer-visiting file)
12198 (find-file-noselect file))
12199 (org-with-wide-buffer
12200 (if pos
12201 (goto-char pos)
12202 (goto-char (point-max))
12203 (unless (bolp) (newline)))
12204 (when (looking-at org-outline-regexp)
12205 (setq level (funcall outline-level))
12206 (org-end-of-subtree t t))
12207 (org-back-over-empty-lines)
12208 (insert "\n" (make-string
12209 (if pos (org-get-valid-level level 1) 1) ?*)
12210 " " child "\n")
12211 (beginning-of-line 0)
12212 (list (concat (car parent-target) "/" child) file "" (point))))))
12214 (defun org-olpath-completing-read (prompt collection &rest args)
12215 "Read an outline path like a file name."
12216 (let ((thetable collection))
12217 (apply #'completing-read
12218 prompt
12219 (lambda (string predicate &optional flag)
12220 (cond
12221 ((eq flag nil) (try-completion string thetable))
12222 ((eq flag t)
12223 (let ((l (length string)))
12224 (mapcar (lambda (x)
12225 (let ((r (substring x l))
12226 (f (if (string-match " ([^)]*)$" x)
12227 (match-string 0 x)
12228 "")))
12229 (if (string-match "/" r)
12230 (concat string (substring r 0 (match-end 0)) f)
12231 x)))
12232 (all-completions string thetable predicate))))
12233 ;; Exact match?
12234 ((eq flag 'lambda) (assoc string thetable))))
12235 args)))
12237 ;;;; Dynamic blocks
12239 (defun org-find-dblock (name)
12240 "Find the first dynamic block with name NAME in the buffer.
12241 If not found, stay at current position and return nil."
12242 (let ((case-fold-search t) pos)
12243 (save-excursion
12244 (goto-char (point-min))
12245 (setq pos (and (re-search-forward
12246 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12247 (match-beginning 0))))
12248 (when pos (goto-char pos))
12249 pos))
12251 (defun org-create-dblock (plist)
12252 "Create a dynamic block section, with parameters taken from PLIST.
12253 PLIST must contain a :name entry which is used as the name of the block."
12254 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12255 (end-of-line 1)
12256 (newline))
12257 (let ((col (current-column))
12258 (name (plist-get plist :name)))
12259 (insert "#+BEGIN: " name)
12260 (while plist
12261 (if (eq (car plist) :name)
12262 (setq plist (cddr plist))
12263 (insert " " (prin1-to-string (pop plist)))))
12264 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12265 (beginning-of-line -2)))
12267 (defun org-prepare-dblock ()
12268 "Prepare dynamic block for refresh.
12269 This empties the block, puts the cursor at the insert position and returns
12270 the property list including an extra property :name with the block name."
12271 (unless (looking-at org-dblock-start-re)
12272 (user-error "Not at a dynamic block"))
12273 (let* ((begdel (1+ (match-end 0)))
12274 (name (org-no-properties (match-string 1)))
12275 (params (append (list :name name)
12276 (read (concat "(" (match-string 3) ")")))))
12277 (save-excursion
12278 (beginning-of-line 1)
12279 (skip-chars-forward " \t")
12280 (setq params (plist-put params :indentation-column (current-column))))
12281 (unless (re-search-forward org-dblock-end-re nil t)
12282 (error "Dynamic block not terminated"))
12283 (setq params
12284 (append params
12285 (list :content (buffer-substring
12286 begdel (match-beginning 0)))))
12287 (delete-region begdel (match-beginning 0))
12288 (goto-char begdel)
12289 (open-line 1)
12290 params))
12292 (defun org-map-dblocks (&optional command)
12293 "Apply COMMAND to all dynamic blocks in the current buffer.
12294 If COMMAND is not given, use `org-update-dblock'."
12295 (let ((cmd (or command 'org-update-dblock)))
12296 (save-excursion
12297 (goto-char (point-min))
12298 (while (re-search-forward org-dblock-start-re nil t)
12299 (goto-char (match-beginning 0))
12300 (save-excursion
12301 (condition-case nil
12302 (funcall cmd)
12303 (error (message "Error during update of dynamic block"))))
12304 (unless (re-search-forward org-dblock-end-re nil t)
12305 (error "Dynamic block not terminated"))))))
12307 (defun org-dblock-update (&optional arg)
12308 "User command for updating dynamic blocks.
12309 Update the dynamic block at point. With prefix ARG, update all dynamic
12310 blocks in the buffer."
12311 (interactive "P")
12312 (if arg
12313 (org-update-all-dblocks)
12314 (or (looking-at org-dblock-start-re)
12315 (org-beginning-of-dblock))
12316 (org-update-dblock)))
12318 (defun org-update-dblock ()
12319 "Update the dynamic block at point.
12320 This means to empty the block, parse for parameters and then call
12321 the correct writing function."
12322 (interactive)
12323 (save-excursion
12324 (let* ((win (selected-window))
12325 (pos (point))
12326 (line (org-current-line))
12327 (params (org-prepare-dblock))
12328 (name (plist-get params :name))
12329 (indent (plist-get params :indentation-column))
12330 (cmd (intern (concat "org-dblock-write:" name))))
12331 (message "Updating dynamic block `%s' at line %d..." name line)
12332 (funcall cmd params)
12333 (message "Updating dynamic block `%s' at line %d...done" name line)
12334 (goto-char pos)
12335 (when (and indent (> indent 0))
12336 (setq indent (make-string indent ?\ ))
12337 (save-excursion
12338 (select-window win)
12339 (org-beginning-of-dblock)
12340 (forward-line 1)
12341 (while (not (looking-at org-dblock-end-re))
12342 (insert indent)
12343 (beginning-of-line 2))
12344 (when (looking-at org-dblock-end-re)
12345 (and (looking-at "[ \t]+")
12346 (replace-match ""))
12347 (insert indent)))))))
12349 (defun org-beginning-of-dblock ()
12350 "Find the beginning of the dynamic block at point.
12351 Error if there is no such block at point."
12352 (let ((pos (point))
12353 beg)
12354 (end-of-line 1)
12355 (if (and (re-search-backward org-dblock-start-re nil t)
12356 (setq beg (match-beginning 0))
12357 (re-search-forward org-dblock-end-re nil t)
12358 (> (match-end 0) pos))
12359 (goto-char beg)
12360 (goto-char pos)
12361 (error "Not in a dynamic block"))))
12363 (defun org-update-all-dblocks ()
12364 "Update all dynamic blocks in the buffer.
12365 This function can be used in a hook."
12366 (interactive)
12367 (when (derived-mode-p 'org-mode)
12368 (org-map-dblocks 'org-update-dblock)))
12371 ;;;; Completion
12373 (declare-function org-export-backend-options "ox" (cl-x) t)
12374 (defun org-get-export-keywords ()
12375 "Return a list of all currently understood export keywords.
12376 Export keywords include options, block names, attributes and
12377 keywords relative to each registered export back-end."
12378 (let (keywords)
12379 (dolist (backend
12380 (bound-and-true-p org-export-registered-backends)
12381 (delq nil keywords))
12382 ;; Back-end name (for keywords, like #+LATEX:)
12383 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12384 (dolist (option-entry (org-export-backend-options backend))
12385 ;; Back-end options.
12386 (push (nth 1 option-entry) keywords)))))
12388 (defconst org-options-keywords
12389 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12390 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12391 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12392 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12393 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12395 (defcustom org-structure-template-alist
12396 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12397 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12398 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12399 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12400 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12401 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12402 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12403 ("L" "#+LaTeX: ")
12404 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12405 ("H" "#+HTML: ")
12406 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12407 ("A" "#+ASCII: ")
12408 ("i" "#+INDEX: ?")
12409 ("I" "#+INCLUDE: %file ?"))
12410 "Structure completion elements.
12411 This is a list of abbreviation keys and values. The value gets inserted
12412 if you type `<' followed by the key and then press the completion key,
12413 usually `TAB'. %file will be replaced by a file name after prompting
12414 for the file using completion. The cursor will be placed at the position
12415 of the `?' in the template.
12416 There are two templates for each key, the first uses the original Org syntax,
12417 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12418 the default when the /org-mtags.el/ module has been loaded. See also the
12419 variable `org-mtags-prefer-muse-templates'."
12420 :group 'org-completion
12421 :type '(repeat
12422 (list
12423 (string :tag "Key")
12424 (string :tag "Template")))
12425 :version "25.2"
12426 :package-version '(Org . "8.3"))
12428 (defun org-try-structure-completion ()
12429 "Try to complete a structure template before point.
12430 This looks for strings like \"<e\" on an otherwise empty line and
12431 expands them."
12432 (let ((l (buffer-substring (point-at-bol) (point)))
12434 (when (and (looking-at "[ \t]*$")
12435 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12436 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12437 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12438 (match-beginning 1)) a)
12439 t)))
12441 (defun org-complete-expand-structure-template (start cell)
12442 "Expand a structure template."
12443 (let ((rpl (nth 1 cell))
12444 (ind ""))
12445 (delete-region start (point))
12446 (when (string-match "\\`[ \t]*#\\+" rpl)
12447 (cond
12448 ((bolp))
12449 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12450 (setq ind (buffer-substring (point-at-bol) (point))))
12451 (t (newline))))
12452 (setq start (point))
12453 (when (string-match "%file" rpl)
12454 (setq rpl (replace-match
12455 (concat
12456 "\""
12457 (save-match-data
12458 (abbreviate-file-name (read-file-name "Include file: ")))
12459 "\"")
12460 t t rpl)))
12461 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12462 (concat "\n" ind)))
12463 (insert rpl)
12464 (when (re-search-backward "\\?" start t) (delete-char 1))))
12466 ;;;; TODO, DEADLINE, Comments
12468 (defun org-toggle-comment ()
12469 "Change the COMMENT state of an entry."
12470 (interactive)
12471 (save-excursion
12472 (org-back-to-heading)
12473 (looking-at org-complex-heading-regexp)
12474 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12475 (skip-chars-forward " \t")
12476 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12477 (if (org-in-commented-heading-p t)
12478 (delete-region (point)
12479 (progn (search-forward " " (line-end-position) 'move)
12480 (skip-chars-forward " \t")
12481 (point)))
12482 (insert org-comment-string)
12483 (unless (eolp) (insert " ")))))
12485 (defvar org-last-todo-state-is-todo nil
12486 "This is non-nil when the last TODO state change led to a TODO state.
12487 If the last change removed the TODO tag or switched to DONE, then
12488 this is nil.")
12490 (defvar org-setting-tags nil) ; dynamically skipped
12492 (defvar org-todo-setup-filter-hook nil
12493 "Hook for functions that pre-filter todo specs.
12494 Each function takes a todo spec and returns either nil or the spec
12495 transformed into canonical form." )
12497 (defvar org-todo-get-default-hook nil
12498 "Hook for functions that get a default item for todo.
12499 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12500 nil or a string to be used for the todo mark." )
12502 (defvar org-agenda-headline-snapshot-before-repeat)
12504 (defun org-current-effective-time ()
12505 "Return current time adjusted for `org-extend-today-until' variable."
12506 (let* ((ct (org-current-time))
12507 (dct (decode-time ct))
12508 (ct1
12509 (cond
12510 (org-use-last-clock-out-time-as-effective-time
12511 (or (org-clock-get-last-clock-out-time) ct))
12512 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12513 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12514 (t ct))))
12515 ct1))
12517 (defun org-todo-yesterday (&optional arg)
12518 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12519 (interactive "P")
12520 (if (eq major-mode 'org-agenda-mode)
12521 (apply 'org-agenda-todo-yesterday arg)
12522 (let* ((org-use-effective-time t)
12523 (hour (nth 2 (decode-time (org-current-time))))
12524 (org-extend-today-until (1+ hour)))
12525 (org-todo arg))))
12527 (defvar org-block-entry-blocking ""
12528 "First entry preventing the TODO state change.")
12530 (defun org-cancel-repeater ()
12531 "Cancel a repeater by setting its numeric value to zero."
12532 (interactive)
12533 (save-excursion
12534 (org-back-to-heading t)
12535 (let ((bound1 (point))
12536 (bound0 (save-excursion (outline-next-heading) (point))))
12537 (when (and (re-search-forward
12538 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12539 org-deadline-time-regexp "\\)\\|\\("
12540 org-ts-regexp "\\)")
12541 bound0 t)
12542 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12543 bound1 t))
12544 (replace-match "0" t nil nil 1)))))
12546 (defvar org-state) ;; dynamically scoped into this function
12547 (defun org-todo (&optional arg)
12548 "Change the TODO state of an item.
12550 The state of an item is given by a keyword at the start of the heading,
12551 like
12552 *** TODO Write paper
12553 *** DONE Call mom
12555 The different keywords are specified in the variable `org-todo-keywords'.
12556 By default the available states are \"TODO\" and \"DONE\". So, for this
12557 example: when the item starts with TODO, it is changed to DONE.
12558 When it starts with DONE, the DONE is removed. And when neither TODO nor
12559 DONE are present, add TODO at the beginning of the heading.
12561 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12562 state.
12563 With numeric prefix ARG, switch to that state.
12564 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12565 next set of TODO \
12566 keywords (nextset).
12567 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12568 prefix, circumvent any state blocking.
12569 With a numeric prefix arg of 0, inhibit note taking for the change.
12570 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12572 When called through ELisp, arg is also interpreted in the following way:
12573 `none' -> empty state
12574 \"\" -> switch to empty state
12575 `done' -> switch to DONE
12576 `nextset' -> switch to the next set of keywords
12577 `previousset' -> switch to the previous set of keywords
12578 \"WAITING\" -> switch to the specified keyword, but only if it
12579 really is a member of `org-todo-keywords'."
12580 (interactive "P")
12581 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12582 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12583 'region-start-level 'region))
12584 org-loop-over-headlines-in-active-region)
12585 (org-map-entries
12586 `(org-todo ,arg)
12587 org-loop-over-headlines-in-active-region
12588 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12589 (when (equal arg '(16)) (setq arg 'nextset))
12590 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12591 (let ((org-blocker-hook org-blocker-hook)
12592 commentp
12593 case-fold-search)
12594 (when (equal arg '(64))
12595 (setq arg nil org-blocker-hook nil))
12596 (when (and org-blocker-hook
12597 (or org-inhibit-blocking
12598 (org-entry-get nil "NOBLOCKING")))
12599 (setq org-blocker-hook nil))
12600 (save-excursion
12601 (catch 'exit
12602 (org-back-to-heading t)
12603 (when (org-in-commented-heading-p t)
12604 (org-toggle-comment)
12605 (setq commentp t))
12606 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12607 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12608 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12609 (let* ((match-data (match-data))
12610 (startpos (point-at-bol))
12611 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12612 (org-log-done org-log-done)
12613 (org-log-repeat org-log-repeat)
12614 (org-todo-log-states org-todo-log-states)
12615 (org-inhibit-logging
12616 (if (equal arg 0)
12617 (progn (setq arg nil) 'note) org-inhibit-logging))
12618 (this (match-string 1))
12619 (hl-pos (match-beginning 0))
12620 (head (org-get-todo-sequence-head this))
12621 (ass (assoc head org-todo-kwd-alist))
12622 (interpret (nth 1 ass))
12623 (done-word (nth 3 ass))
12624 (final-done-word (nth 4 ass))
12625 (org-last-state (or this ""))
12626 (completion-ignore-case t)
12627 (member (member this org-todo-keywords-1))
12628 (tail (cdr member))
12629 (org-state (cond
12630 ((and org-todo-key-trigger
12631 (or (and (equal arg '(4))
12632 (eq org-use-fast-todo-selection 'prefix))
12633 (and (not arg) org-use-fast-todo-selection
12634 (not (eq org-use-fast-todo-selection
12635 'prefix)))))
12636 ;; Use fast selection
12637 (org-fast-todo-selection))
12638 ((and (equal arg '(4))
12639 (or (not org-use-fast-todo-selection)
12640 (not org-todo-key-trigger)))
12641 ;; Read a state with completion
12642 (completing-read
12643 "State: " (mapcar #'list org-todo-keywords-1)
12644 nil t))
12645 ((eq arg 'right)
12646 (if this
12647 (if tail (car tail) nil)
12648 (car org-todo-keywords-1)))
12649 ((eq arg 'left)
12650 (unless (equal member org-todo-keywords-1)
12651 (if this
12652 (nth (- (length org-todo-keywords-1)
12653 (length tail) 2)
12654 org-todo-keywords-1)
12655 (org-last org-todo-keywords-1))))
12656 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12657 (setq arg nil))) ; hack to fall back to cycling
12658 (arg
12659 ;; user or caller requests a specific state
12660 (cond
12661 ((equal arg "") nil)
12662 ((eq arg 'none) nil)
12663 ((eq arg 'done) (or done-word (car org-done-keywords)))
12664 ((eq arg 'nextset)
12665 (or (car (cdr (member head org-todo-heads)))
12666 (car org-todo-heads)))
12667 ((eq arg 'previousset)
12668 (let ((org-todo-heads (reverse org-todo-heads)))
12669 (or (car (cdr (member head org-todo-heads)))
12670 (car org-todo-heads))))
12671 ((car (member arg org-todo-keywords-1)))
12672 ((stringp arg)
12673 (user-error "State `%s' not valid in this file" arg))
12674 ((nth (1- (prefix-numeric-value arg))
12675 org-todo-keywords-1))))
12676 ((null member) (or head (car org-todo-keywords-1)))
12677 ((equal this final-done-word) nil) ;; -> make empty
12678 ((null tail) nil) ;; -> first entry
12679 ((memq interpret '(type priority))
12680 (if (eq this-command last-command)
12681 (car tail)
12682 (if (> (length tail) 0)
12683 (or done-word (car org-done-keywords))
12684 nil)))
12686 (car tail))))
12687 (org-state (or
12688 (run-hook-with-args-until-success
12689 'org-todo-get-default-hook org-state org-last-state)
12690 org-state))
12691 (next (if org-state (concat " " org-state " ") " "))
12692 (change-plist (list :type 'todo-state-change :from this :to org-state
12693 :position startpos))
12694 dolog now-done-p)
12695 (when org-blocker-hook
12696 (setq org-last-todo-state-is-todo
12697 (not (member this org-done-keywords)))
12698 (unless (save-excursion
12699 (save-match-data
12700 (org-with-wide-buffer
12701 (run-hook-with-args-until-failure
12702 'org-blocker-hook change-plist))))
12703 (if (called-interactively-p 'interactive)
12704 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12705 this org-state org-block-entry-blocking)
12706 ;; fail silently
12707 (message "TODO state change from %s to %s blocked (by \"%s\")"
12708 this org-state org-block-entry-blocking)
12709 (throw 'exit nil))))
12710 (store-match-data match-data)
12711 (replace-match next t t)
12712 (cond ((equal this org-state)
12713 (message "TODO state was already %s" (org-trim next)))
12714 ((pos-visible-in-window-p hl-pos)
12715 (message "TODO state changed to %s" (org-trim next))))
12716 (unless head
12717 (setq head (org-get-todo-sequence-head org-state)
12718 ass (assoc head org-todo-kwd-alist)
12719 interpret (nth 1 ass)
12720 done-word (nth 3 ass)
12721 final-done-word (nth 4 ass)))
12722 (when (memq arg '(nextset previousset))
12723 (message "Keyword-Set %d/%d: %s"
12724 (- (length org-todo-sets) -1
12725 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12726 (length org-todo-sets)
12727 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12728 (setq org-last-todo-state-is-todo
12729 (not (member org-state org-done-keywords)))
12730 (setq now-done-p (and (member org-state org-done-keywords)
12731 (not (member this org-done-keywords))))
12732 (and logging (org-local-logging logging))
12733 (when (and (or org-todo-log-states org-log-done)
12734 (not (eq org-inhibit-logging t))
12735 (not (memq arg '(nextset previousset))))
12736 ;; we need to look at recording a time and note
12737 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12738 (nth 2 (assoc this org-todo-log-states))))
12739 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12740 (setq dolog 'time))
12741 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12742 (and org-state
12743 (member org-state org-not-done-keywords)
12744 (not (member this org-not-done-keywords))))
12745 ;; This is now a todo state and was not one before
12746 ;; If there was a CLOSED time stamp, get rid of it.
12747 (org-add-planning-info nil nil 'closed))
12748 (when (and now-done-p org-log-done)
12749 ;; It is now done, and it was not done before
12750 (org-add-planning-info 'closed (org-current-effective-time))
12751 (when (and (not dolog) (eq 'note org-log-done))
12752 (org-add-log-setup 'done org-state this 'note)))
12753 (when (and org-state dolog)
12754 ;; This is a non-nil state, and we need to log it
12755 (org-add-log-setup 'state org-state this dolog)))
12756 ;; Fixup tag positioning
12757 (org-todo-trigger-tag-changes org-state)
12758 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12759 (when org-provide-todo-statistics
12760 (org-update-parent-todo-statistics))
12761 (run-hooks 'org-after-todo-state-change-hook)
12762 (when (and arg (not (member org-state org-done-keywords)))
12763 (setq head (org-get-todo-sequence-head org-state)))
12764 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12765 ;; Do we need to trigger a repeat?
12766 (when now-done-p
12767 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12768 ;; This is for the agenda, take a snapshot of the headline.
12769 (save-match-data
12770 (setq org-agenda-headline-snapshot-before-repeat
12771 (org-get-heading))))
12772 (org-auto-repeat-maybe org-state))
12773 ;; Fixup cursor location if close to the keyword
12774 (when (and (outline-on-heading-p)
12775 (not (bolp))
12776 (save-excursion (beginning-of-line 1)
12777 (looking-at org-todo-line-regexp))
12778 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12779 (goto-char (or (match-end 2) (match-end 1)))
12780 (and (looking-at " ") (just-one-space)))
12781 (when org-trigger-hook
12782 (save-excursion
12783 (run-hook-with-args 'org-trigger-hook change-plist)))
12784 (when commentp (org-toggle-comment))))))))
12786 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12787 "Block turning an entry into a TODO, using the hierarchy.
12788 This checks whether the current task should be blocked from state
12789 changes. Such blocking occurs when:
12791 1. The task has children which are not all in a completed state.
12793 2. A task has a parent with the property :ORDERED:, and there
12794 are siblings prior to the current task with incomplete
12795 status.
12797 3. The parent of the task is blocked because it has siblings that should
12798 be done first, or is child of a block grandparent TODO entry."
12800 (if (not org-enforce-todo-dependencies)
12801 t ; if locally turned off don't block
12802 (catch 'dont-block
12803 ;; If this is not a todo state change, or if this entry is already DONE,
12804 ;; do not block
12805 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12806 (member (plist-get change-plist :from)
12807 (cons 'done org-done-keywords))
12808 (member (plist-get change-plist :to)
12809 (cons 'todo org-not-done-keywords))
12810 (not (plist-get change-plist :to)))
12811 (throw 'dont-block t))
12812 ;; If this task has children, and any are undone, it's blocked
12813 (save-excursion
12814 (org-back-to-heading t)
12815 (let ((this-level (funcall outline-level)))
12816 (outline-next-heading)
12817 (let ((child-level (funcall outline-level)))
12818 (while (and (not (eobp))
12819 (> child-level this-level))
12820 ;; this todo has children, check whether they are all
12821 ;; completed
12822 (when (and (not (org-entry-is-done-p))
12823 (org-entry-is-todo-p))
12824 (setq org-block-entry-blocking (org-get-heading))
12825 (throw 'dont-block nil))
12826 (outline-next-heading)
12827 (setq child-level (funcall outline-level))))))
12828 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12829 ;; any previous siblings are undone, it's blocked
12830 (save-excursion
12831 (org-back-to-heading t)
12832 (let* ((pos (point))
12833 (parent-pos (and (org-up-heading-safe) (point))))
12834 (unless parent-pos (throw 'dont-block t)) ; no parent
12835 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12836 (forward-line 1)
12837 (re-search-forward org-not-done-heading-regexp pos t))
12838 (setq org-block-entry-blocking (match-string 0))
12839 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12840 ;; Search further up the hierarchy, to see if an ancestor is blocked
12841 (while t
12842 (goto-char parent-pos)
12843 (unless (looking-at org-not-done-heading-regexp)
12844 (throw 'dont-block t)) ; do not block, parent is not a TODO
12845 (setq pos (point))
12846 (setq parent-pos (and (org-up-heading-safe) (point)))
12847 (unless parent-pos (throw 'dont-block t)) ; no parent
12848 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12849 (forward-line 1)
12850 (re-search-forward org-not-done-heading-regexp pos t)
12851 (setq org-block-entry-blocking (org-get-heading)))
12852 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12854 (defcustom org-track-ordered-property-with-tag nil
12855 "Should the ORDERED property also be shown as a tag?
12856 The ORDERED property decides if an entry should require subtasks to be
12857 completed in sequence. Since a property is not very visible, setting
12858 this option means that toggling the ORDERED property with the command
12859 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12860 not relevant for the behavior, but it makes things more visible.
12862 Note that toggling the tag with tags commands will not change the property
12863 and therefore not influence behavior!
12865 This can be t, meaning the tag ORDERED should be used, It can also be a
12866 string to select a different tag for this task."
12867 :group 'org-todo
12868 :type '(choice
12869 (const :tag "No tracking" nil)
12870 (const :tag "Track with ORDERED tag" t)
12871 (string :tag "Use other tag")))
12873 (defun org-toggle-ordered-property ()
12874 "Toggle the ORDERED property of the current entry.
12875 For better visibility, you can track the value of this property with a tag.
12876 See variable `org-track-ordered-property-with-tag'."
12877 (interactive)
12878 (let* ((t1 org-track-ordered-property-with-tag)
12879 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12880 (save-excursion
12881 (org-back-to-heading)
12882 (if (org-entry-get nil "ORDERED")
12883 (progn
12884 (org-delete-property "ORDERED")
12885 (and tag (org-toggle-tag tag 'off))
12886 (message "Subtasks can be completed in arbitrary order"))
12887 (org-entry-put nil "ORDERED" "t")
12888 (and tag (org-toggle-tag tag 'on))
12889 (message "Subtasks must be completed in sequence")))))
12891 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12892 (defun org-block-todo-from-checkboxes (change-plist)
12893 "Block turning an entry into a TODO, using checkboxes.
12894 This checks whether the current task should be blocked from state
12895 changes because there are unchecked boxes in this entry."
12896 (if (not org-enforce-todo-checkbox-dependencies)
12897 t ; if locally turned off don't block
12898 (catch 'dont-block
12899 ;; If this is not a todo state change, or if this entry is already DONE,
12900 ;; do not block
12901 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12902 (member (plist-get change-plist :from)
12903 (cons 'done org-done-keywords))
12904 (member (plist-get change-plist :to)
12905 (cons 'todo org-not-done-keywords))
12906 (not (plist-get change-plist :to)))
12907 (throw 'dont-block t))
12908 ;; If this task has checkboxes that are not checked, it's blocked
12909 (save-excursion
12910 (org-back-to-heading t)
12911 (let ((beg (point)) end)
12912 (outline-next-heading)
12913 (setq end (point))
12914 (goto-char beg)
12915 (when (org-list-search-forward
12916 (concat (org-item-beginning-re)
12917 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12918 "\\[[- ]\\]")
12919 end t)
12920 (when (boundp 'org-blocked-by-checkboxes)
12921 (setq org-blocked-by-checkboxes t))
12922 (throw 'dont-block nil))))
12923 t))) ; do not block
12925 (defun org-entry-blocked-p ()
12926 "Non-nil if entry at point is blocked."
12927 (and (not (org-entry-get nil "NOBLOCKING"))
12928 (member (org-entry-get nil "TODO") org-not-done-keywords)
12929 (not (run-hook-with-args-until-failure
12930 'org-blocker-hook
12931 (list :type 'todo-state-change
12932 :position (point)
12933 :from 'todo
12934 :to 'done)))))
12936 (defun org-update-statistics-cookies (all)
12937 "Update the statistics cookie, either from TODO or from checkboxes.
12938 This should be called with the cursor in a line with a statistics
12939 cookie. When called with a \\[universal-argument] prefix, update
12940 all statistics cookies in the buffer."
12941 (interactive "P")
12942 (if all
12943 (progn
12944 (org-update-checkbox-count 'all)
12945 (org-map-entries 'org-update-parent-todo-statistics))
12946 (if (not (org-at-heading-p))
12947 (org-update-checkbox-count)
12948 (let ((pos (point-marker))
12949 end l1 l2)
12950 (ignore-errors (org-back-to-heading t))
12951 (if (not (org-at-heading-p))
12952 (org-update-checkbox-count)
12953 (setq l1 (org-outline-level))
12954 (setq end (save-excursion
12955 (outline-next-heading)
12956 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12957 (point)))
12958 (if (and (save-excursion
12959 (re-search-forward
12960 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12961 (not (save-excursion (re-search-forward
12962 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12963 (org-update-checkbox-count)
12964 (if (and l2 (> l2 l1))
12965 (progn
12966 (goto-char end)
12967 (org-update-parent-todo-statistics))
12968 (goto-char pos)
12969 (beginning-of-line 1)
12970 (while (re-search-forward
12971 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12972 (point-at-eol) t)
12973 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12974 (goto-char pos)
12975 (move-marker pos nil)))))
12977 (defvar org-entry-property-inherited-from) ;; defined below
12978 (defun org-update-parent-todo-statistics ()
12979 "Update any statistics cookie in the parent of the current headline.
12980 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12981 the entire subtree and this will travel up the hierarchy and update
12982 statistics everywhere."
12983 (let* ((prop (save-excursion (org-up-heading-safe)
12984 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12985 (recursive (or (not org-hierarchical-todo-statistics)
12986 (and prop (string-match "\\<recursive\\>" prop))))
12987 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12989 (first t)
12990 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12991 level ltoggle l1 new ndel
12992 (cnt-all 0) (cnt-done 0) is-percent kwd
12993 checkbox-beg cookie-present)
12994 (catch 'exit
12995 (save-excursion
12996 (beginning-of-line 1)
12997 (setq ltoggle (funcall outline-level))
12998 ;; Three situations are to consider:
13000 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
13001 ;; to the top-level ancestor on the headline;
13003 ;; 2. If parent has "recursive" property, repeat up to the
13004 ;; headline setting that property, taking inheritance into
13005 ;; account;
13007 ;; 3. Else, move up to direct parent and proceed only once.
13008 (while (and (setq level (org-up-heading-safe))
13009 (or recursive first)
13010 (>= (point) lim))
13011 (setq first nil cookie-present nil)
13012 (unless (and level
13013 (not (string-match
13014 "\\<checkbox\\>"
13015 (downcase (or (org-entry-get nil "COOKIE_DATA")
13016 "")))))
13017 (throw 'exit nil))
13018 (while (re-search-forward box-re (point-at-eol) t)
13019 (setq cnt-all 0 cnt-done 0 cookie-present t)
13020 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
13021 (save-match-data
13022 (unless (outline-next-heading) (throw 'exit nil))
13023 (while (and (looking-at org-complex-heading-regexp)
13024 (> (setq l1 (length (match-string 1))) level))
13025 (setq kwd (and (or recursive (= l1 ltoggle))
13026 (match-string 2)))
13027 (if (or (eq org-provide-todo-statistics 'all-headlines)
13028 (and (eq org-provide-todo-statistics t)
13029 (or (member kwd org-done-keywords)))
13030 (and (listp org-provide-todo-statistics)
13031 (stringp (car org-provide-todo-statistics))
13032 (or (member kwd org-provide-todo-statistics)
13033 (member kwd org-done-keywords)))
13034 (and (listp org-provide-todo-statistics)
13035 (listp (car org-provide-todo-statistics))
13036 (or (member kwd (car org-provide-todo-statistics))
13037 (and (member kwd org-done-keywords)
13038 (member kwd (cadr org-provide-todo-statistics))))))
13039 (setq cnt-all (1+ cnt-all))
13040 (and (eq org-provide-todo-statistics t)
13042 (setq cnt-all (1+ cnt-all))))
13043 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13044 (member kwd org-done-keywords))
13045 (and (listp org-provide-todo-statistics)
13046 (listp (car org-provide-todo-statistics))
13047 (member kwd org-done-keywords)
13048 (member kwd (cadr org-provide-todo-statistics)))
13049 (and (listp org-provide-todo-statistics)
13050 (stringp (car org-provide-todo-statistics))
13051 (member kwd org-done-keywords)))
13052 (setq cnt-done (1+ cnt-done)))
13053 (outline-next-heading)))
13054 (setq new
13055 (if is-percent
13056 (format "[%d%%]" (floor (* 100.0 cnt-done)
13057 (max 1 cnt-all)))
13058 (format "[%d/%d]" cnt-done cnt-all))
13059 ndel (- (match-end 0) checkbox-beg))
13060 (goto-char checkbox-beg)
13061 (insert new)
13062 (delete-region (point) (+ (point) ndel))
13063 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13064 (when cookie-present
13065 (run-hook-with-args 'org-after-todo-statistics-hook
13066 cnt-done (- cnt-all cnt-done))))))
13067 (run-hooks 'org-todo-statistics-hook)))
13069 (defvar org-after-todo-statistics-hook nil
13070 "Hook that is called after a TODO statistics cookie has been updated.
13071 Each function is called with two arguments: the number of not-done entries
13072 and the number of done entries.
13074 For example, the following function, when added to this hook, will switch
13075 an entry to DONE when all children are done, and back to TODO when new
13076 entries are set to a TODO status. Note that this hook is only called
13077 when there is a statistics cookie in the headline!
13079 \(defun org-summary-todo (n-done n-not-done)
13080 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13081 \(let (org-log-done org-log-states) ; turn off logging
13082 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13085 (defvar org-todo-statistics-hook nil
13086 "Hook that is run whenever Org thinks TODO statistics should be updated.
13087 This hook runs even if there is no statistics cookie present, in which case
13088 `org-after-todo-statistics-hook' would not run.")
13090 (defun org-todo-trigger-tag-changes (state)
13091 "Apply the changes defined in `org-todo-state-tags-triggers'."
13092 (let ((l org-todo-state-tags-triggers)
13093 changes)
13094 (when (or (not state) (equal state ""))
13095 (setq changes (append changes (cdr (assoc "" l)))))
13096 (when (and (stringp state) (> (length state) 0))
13097 (setq changes (append changes (cdr (assoc state l)))))
13098 (when (member state org-not-done-keywords)
13099 (setq changes (append changes (cdr (assq 'todo l)))))
13100 (when (member state org-done-keywords)
13101 (setq changes (append changes (cdr (assq 'done l)))))
13102 (dolist (c changes)
13103 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13105 (defun org-local-logging (value)
13106 "Get logging settings from a property VALUE."
13107 ;; Directly set the variables, they are already local.
13108 (setq org-log-done nil
13109 org-log-repeat nil
13110 org-todo-log-states nil)
13111 (dolist (w (org-split-string value))
13112 (let (a)
13113 (cond
13114 ((setq a (assoc w org-startup-options))
13115 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13116 (set (nth 1 a) (nth 2 a))))
13117 ((setq a (org-extract-log-state-settings w))
13118 (and (member (car a) org-todo-keywords-1)
13119 (push a org-todo-log-states)))))))
13121 (defun org-get-todo-sequence-head (kwd)
13122 "Return the head of the TODO sequence to which KWD belongs.
13123 If KWD is not set, check if there is a text property remembering the
13124 right sequence."
13125 (let (p)
13126 (cond
13127 ((not kwd)
13128 (or (get-text-property (point-at-bol) 'org-todo-head)
13129 (progn
13130 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13131 nil (point-at-eol)))
13132 (get-text-property p 'org-todo-head))))
13133 ((not (member kwd org-todo-keywords-1))
13134 (car org-todo-keywords-1))
13135 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13137 (defun org-fast-todo-selection ()
13138 "Fast TODO keyword selection with single keys.
13139 Returns the new TODO keyword, or nil if no state change should occur."
13140 (let* ((fulltable org-todo-key-alist)
13141 (done-keywords org-done-keywords) ;; needed for the faces.
13142 (maxlen (apply 'max (mapcar
13143 (lambda (x)
13144 (if (stringp (car x)) (string-width (car x)) 0))
13145 fulltable)))
13146 (expert nil)
13147 (fwidth (+ maxlen 3 1 3))
13148 (ncol (/ (- (window-width) 4) fwidth))
13149 tg cnt e c tbl
13150 groups ingroup)
13151 (save-excursion
13152 (save-window-excursion
13153 (if expert
13154 (set-buffer (get-buffer-create " *Org todo*"))
13155 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13156 (erase-buffer)
13157 (setq-local org-done-keywords done-keywords)
13158 (setq tbl fulltable cnt 0)
13159 (while (setq e (pop tbl))
13160 (cond
13161 ((equal e '(:startgroup))
13162 (push '() groups) (setq ingroup t)
13163 (unless (= cnt 0)
13164 (setq cnt 0)
13165 (insert "\n"))
13166 (insert "{ "))
13167 ((equal e '(:endgroup))
13168 (setq ingroup nil cnt 0)
13169 (insert "}\n"))
13170 ((equal e '(:newline))
13171 (unless (= cnt 0)
13172 (setq cnt 0)
13173 (insert "\n")
13174 (setq e (car tbl))
13175 (while (equal (car tbl) '(:newline))
13176 (insert "\n")
13177 (setq tbl (cdr tbl)))))
13179 (setq tg (car e) c (cdr e))
13180 (when ingroup (push tg (car groups)))
13181 (setq tg (org-add-props tg nil 'face
13182 (org-get-todo-face tg)))
13183 (when (and (= cnt 0) (not ingroup)) (insert " "))
13184 (insert "[" c "] " tg (make-string
13185 (- fwidth 4 (length tg)) ?\ ))
13186 (when (= (setq cnt (1+ cnt)) ncol)
13187 (insert "\n")
13188 (when ingroup (insert " "))
13189 (setq cnt 0)))))
13190 (insert "\n")
13191 (goto-char (point-min))
13192 (unless expert (org-fit-window-to-buffer))
13193 (message "[a-z..]:Set [SPC]:clear")
13194 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13195 (cond
13196 ((or (= c ?\C-g)
13197 (and (= c ?q) (not (rassoc c fulltable))))
13198 (setq quit-flag t))
13199 ((= c ?\ ) nil)
13200 ((setq e (rassoc c fulltable) tg (car e))
13202 (t (setq quit-flag t)))))))
13204 (defun org-entry-is-todo-p ()
13205 (member (org-get-todo-state) org-not-done-keywords))
13207 (defun org-entry-is-done-p ()
13208 (member (org-get-todo-state) org-done-keywords))
13210 (defun org-get-todo-state ()
13211 "Return the TODO keyword of the current subtree."
13212 (save-excursion
13213 (org-back-to-heading t)
13214 (and (looking-at org-todo-line-regexp)
13215 (match-end 2)
13216 (match-string 2))))
13218 (defun org-at-date-range-p (&optional inactive-ok)
13219 "Non-nil if point is inside a date range.
13221 When optional argument INACTIVE-OK is non-nil, also consider
13222 inactive time ranges.
13224 When this function returns a non-nil value, match data is set
13225 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13226 on INACTIVE-OK."
13227 (interactive)
13228 (save-excursion
13229 (catch 'exit
13230 (let ((pos (point)))
13231 (skip-chars-backward "^[<\r\n")
13232 (skip-chars-backward "<[")
13233 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13234 (>= (match-end 0) pos)
13235 (throw 'exit t))
13236 (skip-chars-backward "^<[\r\n")
13237 (skip-chars-backward "<[")
13238 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13239 (>= (match-end 0) pos)
13240 (throw 'exit t)))
13241 nil)))
13243 (defun org-get-repeat (&optional tagline)
13244 "Check if there is a deadline/schedule with repeater in this entry."
13245 (save-match-data
13246 (save-excursion
13247 (org-back-to-heading t)
13248 (and (re-search-forward (if tagline
13249 (concat tagline "\\s-*" org-repeat-re)
13250 org-repeat-re)
13251 (org-entry-end-position) t)
13252 (match-string-no-properties 1)))))
13254 (defvar org-last-changed-timestamp)
13255 (defvar org-last-inserted-timestamp)
13256 (defvar org-log-post-message)
13257 (defvar org-log-note-purpose)
13258 (defvar org-log-note-how nil)
13259 (defvar org-log-note-extra)
13260 (defun org-auto-repeat-maybe (done-word)
13261 "Check if the current headline contains a repeated time-stamp.
13263 If yes, set TODO state back to what it was and change the base date
13264 of repeating deadline/scheduled time stamps to new date.
13266 This function is run automatically after each state change to a DONE state."
13267 (let* ((repeat (org-get-repeat))
13268 (aa (assoc org-last-state org-todo-kwd-alist))
13269 (interpret (nth 1 aa))
13270 (head (nth 2 aa))
13271 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13272 (msg "Entry repeats: ")
13273 (org-log-done nil)
13274 (org-todo-log-states nil))
13275 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13276 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13277 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13278 org-todo-repeat-to-state)))
13279 (unless (and to-state (member to-state org-todo-keywords-1))
13280 (setq to-state (if (eq interpret 'type) org-last-state head)))
13281 (org-todo to-state))
13282 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13283 (org-entry-put nil "LAST_REPEAT" (format-time-string
13284 (org-time-stamp-format t t))))
13285 (when org-log-repeat
13286 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13287 (memq 'org-add-log-note post-command-hook))
13288 ;; We are already setup for some record.
13289 (when (eq org-log-repeat 'note)
13290 ;; Make sure we take a note, not only a time stamp.
13291 (setq org-log-note-how 'note))
13292 ;; Set up for taking a record.
13293 (org-add-log-setup 'state
13294 (or done-word (car org-done-keywords))
13295 org-last-state
13296 org-log-repeat)))
13297 (org-back-to-heading t)
13298 (org-add-planning-info nil nil 'closed)
13299 (let ((end (save-excursion (outline-next-heading) (point))))
13300 (while (re-search-forward org-ts-regexp end t)
13301 (when (save-match-data
13302 (or (org-at-planning-p)
13303 (org-at-property-p)
13304 (eq (org-element-type (save-excursion
13305 (backward-char)
13306 (org-element-context)))
13307 'timestamp)))
13308 (let ((type (cond ((match-end 1) org-scheduled-string)
13309 ((match-end 3) org-deadline-string)
13310 (t "Plain:")))
13311 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13312 (cond
13313 ((not
13314 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13315 ;; Time-stamps without a repeater are usually skipped.
13316 ;; However, a SCHEDULED time-stamp without one is
13317 ;; removed, as it is considered as no longer relevant.
13318 (when (equal type org-scheduled-string)
13319 (org-remove-timestamp-with-keyword type)))
13321 (let ((n (string-to-number (match-string 2 ts)))
13322 (what (match-string 3 ts)))
13323 (when (equal what "w") (setq n (* n 7) what "d"))
13324 (when (and (equal what "h")
13325 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13326 ts)))
13327 (user-error
13328 "Cannot repeat in Repeat in %d hour(s) because no hour \
13329 has been set"
13331 ;; Preparation, see if we need to modify the start
13332 ;; date for the change.
13333 (when (match-end 1)
13334 (let ((time (save-match-data (org-time-string-to-time ts))))
13335 (cond
13336 ((equal (match-string 1 ts) ".")
13337 ;; Shift starting date to today
13338 (org-timestamp-change
13339 (- (org-today) (time-to-days time))
13340 'day))
13341 ((equal (match-string 1 ts) "+")
13342 (let ((nshiftmax 10)
13343 (nshift 0))
13344 (while (or (= nshift 0)
13345 (not (time-less-p (current-time) time)))
13346 (when (= (cl-incf nshift) nshiftmax)
13347 (or (y-or-n-p
13348 (format "%d repeater intervals were not \
13349 enough to shift date past today. Continue? "
13350 nshift))
13351 (user-error "Abort")))
13352 (org-timestamp-change n (cdr (assoc what whata)))
13353 (org-at-timestamp-p t)
13354 (setq ts (match-string 1))
13355 (setq time
13356 (save-match-data
13357 (org-time-string-to-time ts)))))
13358 (org-timestamp-change (- n) (cdr (assoc what whata)))
13359 ;; Rematch, so that we have everything in
13360 ;; place for the real shift.
13361 (org-at-timestamp-p t)
13362 (setq ts (match-string 1))
13363 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13364 ts)))))
13365 (save-excursion
13366 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13367 (setq msg
13368 (concat
13369 msg type " " org-last-changed-timestamp " ")))))))))
13370 (setq org-log-post-message msg)
13371 (message "%s" msg))))
13373 (defun org-show-todo-tree (arg)
13374 "Make a compact tree which shows all headlines marked with TODO.
13375 The tree will show the lines where the regexp matches, and all higher
13376 headlines above the match.
13377 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13378 With a numeric prefix N, construct a sparse tree for the Nth element
13379 of `org-todo-keywords-1'."
13380 (interactive "P")
13381 (let ((case-fold-search nil)
13382 (kwd-re
13383 (cond ((null arg) org-not-done-regexp)
13384 ((equal arg '(4))
13385 (let ((kwd
13386 (completing-read "Keyword (or KWD1|KWD2|...): "
13387 (mapcar #'list org-todo-keywords-1))))
13388 (concat "\\("
13389 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13390 "\\)\\>")))
13391 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13392 (regexp-quote (nth (1- (prefix-numeric-value arg))
13393 org-todo-keywords-1)))
13394 (t (user-error "Invalid prefix argument: %s" arg)))))
13395 (message "%d TODO entries found"
13396 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13398 (defun org-deadline (arg &optional time)
13399 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13400 With one universal prefix argument, remove any deadline from the item.
13401 With two universal prefix arguments, prompt for a warning delay.
13402 With argument TIME, set the deadline at the corresponding date. TIME
13403 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13404 (interactive "P")
13405 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13406 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13407 'region-start-level 'region))
13408 org-loop-over-headlines-in-active-region)
13409 (org-map-entries
13410 `(org-deadline ',arg ,time)
13411 org-loop-over-headlines-in-active-region
13412 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13413 (let* ((old-date (org-entry-get nil "DEADLINE"))
13414 (old-date-time (when old-date (org-time-string-to-time old-date)))
13415 (repeater (and old-date
13416 (string-match
13417 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13418 old-date)
13419 (match-string 1 old-date))))
13420 (cond
13421 ((equal arg '(4))
13422 (when (and old-date org-log-redeadline)
13423 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13424 (org-remove-timestamp-with-keyword org-deadline-string)
13425 (message "Item no longer has a deadline."))
13426 ((equal arg '(16))
13427 (save-excursion
13428 (org-back-to-heading t)
13429 (if (re-search-forward
13430 org-deadline-time-regexp
13431 (save-excursion (outline-next-heading) (point)) t)
13432 (let* ((rpl0 (match-string 1))
13433 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13434 (replace-match
13435 (concat org-deadline-string
13436 " <" rpl
13437 (format " -%dd"
13438 (abs
13439 (- (time-to-days
13440 (save-match-data
13441 (org-read-date nil t nil "Warn starting from" old-date-time)))
13442 (time-to-days old-date-time))))
13443 ">") t t))
13444 (user-error "No deadline information to update"))))
13446 (org-add-planning-info 'deadline time 'closed)
13447 (when (and old-date
13448 org-log-redeadline
13449 (not (equal old-date org-last-inserted-timestamp)))
13450 (org-add-log-setup
13451 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13452 (when repeater
13453 (save-excursion
13454 (org-back-to-heading t)
13455 (when (re-search-forward (concat org-deadline-string " "
13456 org-last-inserted-timestamp)
13457 (save-excursion
13458 (outline-next-heading) (point)) t)
13459 (goto-char (1- (match-end 0)))
13460 (insert " " repeater)
13461 (setq org-last-inserted-timestamp
13462 (concat (substring org-last-inserted-timestamp 0 -1)
13463 " " repeater
13464 (substring org-last-inserted-timestamp -1))))))
13465 (message "Deadline on %s" org-last-inserted-timestamp))))))
13467 (defun org-schedule (arg &optional time)
13468 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13469 With one universal prefix argument, remove any scheduling date from the item.
13470 With two universal prefix arguments, prompt for a delay cookie.
13471 With argument TIME, scheduled at the corresponding date. TIME can
13472 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13473 (interactive "P")
13474 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13475 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13476 'region-start-level 'region))
13477 org-loop-over-headlines-in-active-region)
13478 (org-map-entries
13479 `(org-schedule ',arg ,time)
13480 org-loop-over-headlines-in-active-region
13481 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13482 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13483 (old-date-time (when old-date (org-time-string-to-time old-date)))
13484 (repeater (and old-date
13485 (string-match
13486 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13487 old-date)
13488 (match-string 1 old-date))))
13489 (cond
13490 ((equal arg '(4))
13491 (progn
13492 (when (and old-date org-log-reschedule)
13493 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13494 (org-remove-timestamp-with-keyword org-scheduled-string)
13495 (message "Item is no longer scheduled.")))
13496 ((equal arg '(16))
13497 (save-excursion
13498 (org-back-to-heading t)
13499 (if (re-search-forward
13500 org-scheduled-time-regexp
13501 (save-excursion (outline-next-heading) (point)) t)
13502 (let* ((rpl0 (match-string 1))
13503 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13504 (replace-match
13505 (concat org-scheduled-string
13506 " <" rpl
13507 (format " -%dd"
13508 (abs
13509 (- (time-to-days
13510 (save-match-data
13511 (org-read-date nil t nil "Delay until" old-date-time)))
13512 (time-to-days old-date-time))))
13513 ">") t t))
13514 (user-error "No scheduled information to update"))))
13516 (org-add-planning-info 'scheduled time 'closed)
13517 (when (and old-date
13518 org-log-reschedule
13519 (not (equal old-date org-last-inserted-timestamp)))
13520 (org-add-log-setup
13521 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13522 (when repeater
13523 (save-excursion
13524 (org-back-to-heading t)
13525 (when (re-search-forward (concat org-scheduled-string " "
13526 org-last-inserted-timestamp)
13527 (save-excursion
13528 (outline-next-heading) (point)) t)
13529 (goto-char (1- (match-end 0)))
13530 (insert " " repeater)
13531 (setq org-last-inserted-timestamp
13532 (concat (substring org-last-inserted-timestamp 0 -1)
13533 " " repeater
13534 (substring org-last-inserted-timestamp -1))))))
13535 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13537 (defun org-get-scheduled-time (pom &optional inherit)
13538 "Get the scheduled time as a time tuple, of a format suitable
13539 for calling org-schedule with, or if there is no scheduling,
13540 returns nil."
13541 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13542 (when time
13543 (apply 'encode-time (org-parse-time-string time)))))
13545 (defun org-get-deadline-time (pom &optional inherit)
13546 "Get the deadline as a time tuple, of a format suitable for
13547 calling org-deadline with, or if there is no scheduling, returns
13548 nil."
13549 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13550 (when time
13551 (apply 'encode-time (org-parse-time-string time)))))
13553 (defun org-remove-timestamp-with-keyword (keyword)
13554 "Remove all time stamps with KEYWORD in the current entry."
13555 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13556 beg)
13557 (save-excursion
13558 (org-back-to-heading t)
13559 (setq beg (point))
13560 (outline-next-heading)
13561 (while (re-search-backward re beg t)
13562 (replace-match "")
13563 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13564 (equal (char-before) ?\ ))
13565 (backward-delete-char 1)
13566 (when (string-match "^[ \t]*$" (buffer-substring
13567 (point-at-bol) (point-at-eol)))
13568 (delete-region (point-at-bol)
13569 (min (point-max) (1+ (point-at-eol))))))))))
13571 (defvar org-time-was-given) ; dynamically scoped parameter
13572 (defvar org-end-time-was-given) ; dynamically scoped parameter
13574 (defun org-at-planning-p ()
13575 "Non-nil when point is on a planning info line."
13576 ;; This is as accurate and faster than `org-element-at-point' since
13577 ;; planning info location is fixed in the section.
13578 (org-with-wide-buffer
13579 (beginning-of-line)
13580 (and (looking-at-p org-planning-line-re)
13581 (eq (point)
13582 (ignore-errors
13583 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13584 (org-back-to-heading t)
13585 (org-with-limited-levels (org-back-to-heading t)))
13586 (line-beginning-position 2))))))
13588 (defun org-add-planning-info (what &optional time &rest remove)
13589 "Insert new timestamp with keyword in the planning line.
13590 WHAT indicates what kind of time stamp to add. It is a symbol
13591 among `closed', `deadline', `scheduled' and nil. TIME indicates
13592 the time to use. If none is given, the user is prompted for
13593 a date. REMOVE indicates what kind of entries to remove. An old
13594 WHAT entry will also be removed."
13595 (let (org-time-was-given org-end-time-was-given default-time default-input)
13596 (catch 'exit
13597 (when (and (memq what '(scheduled deadline))
13598 (or (not time)
13599 (and (stringp time)
13600 (string-match "^[-+]+[0-9]" time))))
13601 ;; Try to get a default date/time from existing timestamp
13602 (save-excursion
13603 (org-back-to-heading t)
13604 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13605 (when (re-search-forward (if (eq what 'scheduled)
13606 org-scheduled-time-regexp
13607 org-deadline-time-regexp)
13608 end t)
13609 (setq ts (match-string 1)
13610 default-time (apply 'encode-time (org-parse-time-string ts))
13611 default-input (and ts (org-get-compact-tod ts)))))))
13612 (when what
13613 (setq time
13614 (if (stringp time)
13615 ;; This is a string (relative or absolute), set
13616 ;; proper date.
13617 (apply #'encode-time
13618 (org-read-date-analyze
13619 time default-time (decode-time default-time)))
13620 ;; If necessary, get the time from the user
13621 (or time (org-read-date nil 'to-time nil nil
13622 default-time default-input)))))
13624 (org-with-wide-buffer
13625 (org-back-to-heading t)
13626 (forward-line)
13627 (unless (bolp) (insert "\n"))
13628 (cond ((looking-at-p org-planning-line-re)
13629 ;; Move to current indentation.
13630 (skip-chars-forward " \t")
13631 ;; Check if we have to remove something.
13632 (dolist (type (if what (cons what remove) remove))
13633 (save-excursion
13634 (when (re-search-forward
13635 (cl-case type
13636 (closed org-closed-time-regexp)
13637 (deadline org-deadline-time-regexp)
13638 (scheduled org-scheduled-time-regexp)
13639 (otherwise
13640 (error "Invalid planning type: %s" type)))
13641 (line-end-position) t)
13642 ;; Delete until next keyword or end of line.
13643 (delete-region
13644 (match-beginning 0)
13645 (if (re-search-forward org-keyword-time-not-clock-regexp
13646 (line-end-position)
13648 (match-beginning 0)
13649 (line-end-position))))))
13650 ;; If there is nothing more to add and no more keyword
13651 ;; is left, remove the line completely.
13652 (if (and (looking-at-p "[ \t]*$") (not what))
13653 (delete-region (line-beginning-position)
13654 (line-beginning-position 2))
13655 ;; If we removed last keyword, do not leave trailing
13656 ;; white space at the end of line.
13657 (let ((p (point)))
13658 (save-excursion
13659 (end-of-line)
13660 (unless (= (skip-chars-backward " \t" p) 0)
13661 (delete-region (point) (line-end-position)))))))
13662 ((not what) (throw 'exit nil)) ; Nothing to do.
13663 (t (insert-before-markers "\n")
13664 (backward-char 1)
13665 (when org-adapt-indentation
13666 (indent-to-column (1+ (org-outline-level))))))
13667 (when what
13668 ;; Insert planning keyword.
13669 (insert (cl-case what
13670 (closed org-closed-string)
13671 (deadline org-deadline-string)
13672 (scheduled org-scheduled-string)
13673 (otherwise (error "Invalid planning type: %s" what)))
13674 " ")
13675 ;; Insert associated timestamp.
13676 (let ((ts (org-insert-time-stamp
13677 time
13678 (or org-time-was-given
13679 (and (eq what 'closed) org-log-done-with-time))
13680 (eq what 'closed)
13681 nil nil (list org-end-time-was-given))))
13682 (unless (eolp) (insert " "))
13683 ts))))))
13685 (defvar org-log-note-marker (make-marker)
13686 "Marker pointing at the entry where the note is to be inserted.")
13687 (defvar org-log-note-purpose nil)
13688 (defvar org-log-note-state nil)
13689 (defvar org-log-note-previous-state nil)
13690 (defvar org-log-note-extra nil)
13691 (defvar org-log-note-window-configuration nil)
13692 (defvar org-log-note-return-to (make-marker))
13693 (defvar org-log-note-effective-time nil
13694 "Remembered current time so that dynamically scoped
13695 `org-extend-today-until' affects timestamps in state change log")
13697 (defvar org-log-post-message nil
13698 "Message to be displayed after a log note has been stored.
13699 The auto-repeater uses this.")
13701 (defun org-add-note ()
13702 "Add a note to the current entry.
13703 This is done in the same way as adding a state change note."
13704 (interactive)
13705 (org-add-log-setup 'note))
13707 (defun org-log-beginning (&optional create)
13708 "Return expected start of log notes in current entry.
13709 When optional argument CREATE is non-nil, the function creates
13710 a drawer to store notes, if necessary. Returned position ignores
13711 narrowing."
13712 (org-with-wide-buffer
13713 (let ((drawer (org-log-into-drawer)))
13714 (cond
13715 (drawer
13716 (org-end-of-meta-data)
13717 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13718 (end (if (org-at-heading-p) (point)
13719 (save-excursion (outline-next-heading) (point))))
13720 (case-fold-search t))
13721 (catch 'exit
13722 ;; Try to find existing drawer.
13723 (while (re-search-forward regexp end t)
13724 (let ((element (org-element-at-point)))
13725 (when (eq (org-element-type element) 'drawer)
13726 (let ((cend (org-element-property :contents-end element)))
13727 (when (and (not org-log-states-order-reversed) cend)
13728 (goto-char cend)))
13729 (throw 'exit nil))))
13730 ;; No drawer found. Create one, if permitted.
13731 (when create
13732 (unless (bolp) (insert "\n"))
13733 (let ((beg (point)))
13734 (insert ":" drawer ":\n:END:\n")
13735 (org-indent-region beg (point)))
13736 (end-of-line -1)))))
13738 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13739 (skip-chars-forward " \t\n")
13740 (beginning-of-line)
13741 (unless org-log-states-order-reversed
13742 (org-skip-over-state-notes)
13743 (skip-chars-backward " \t\n")
13744 (forward-line)))))
13745 (if (bolp) (point) (line-beginning-position 2))))
13747 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13748 "Set up the post command hook to take a note.
13749 If this is about to TODO state change, the new state is expected in STATE.
13750 HOW is an indicator what kind of note should be created.
13751 EXTRA is additional text that will be inserted into the notes buffer."
13752 (move-marker org-log-note-marker (point))
13753 (setq org-log-note-purpose purpose
13754 org-log-note-state state
13755 org-log-note-previous-state prev-state
13756 org-log-note-how how
13757 org-log-note-extra extra
13758 org-log-note-effective-time (org-current-effective-time))
13759 (add-hook 'post-command-hook 'org-add-log-note 'append))
13761 (defun org-skip-over-state-notes ()
13762 "Skip past the list of State notes in an entry."
13763 (when (ignore-errors (goto-char (org-in-item-p)))
13764 (let* ((struct (org-list-struct))
13765 (prevs (org-list-prevs-alist struct))
13766 (regexp
13767 (concat "[ \t]*- +"
13768 (replace-regexp-in-string
13769 " +" " +"
13770 (org-replace-escapes
13771 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13772 `(("%d" . ,org-ts-regexp-inactive)
13773 ("%D" . ,org-ts-regexp)
13774 ("%s" . "\"\\S-+\"")
13775 ("%S" . "\"\\S-+\"")
13776 ("%t" . ,org-ts-regexp-inactive)
13777 ("%T" . ,org-ts-regexp)
13778 ("%u" . ".*?")
13779 ("%U" . ".*?")))))))
13780 (while (looking-at-p regexp)
13781 (goto-char (or (org-list-get-next-item (point) struct prevs)
13782 (org-list-get-item-end (point) struct)))))))
13784 (defun org-add-log-note (&optional _purpose)
13785 "Pop up a window for taking a note, and add this note later."
13786 (remove-hook 'post-command-hook 'org-add-log-note)
13787 (setq org-log-note-window-configuration (current-window-configuration))
13788 (delete-other-windows)
13789 (move-marker org-log-note-return-to (point))
13790 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13791 (goto-char org-log-note-marker)
13792 (org-switch-to-buffer-other-window "*Org Note*")
13793 (erase-buffer)
13794 (if (memq org-log-note-how '(time state))
13795 (let (current-prefix-arg) (org-store-log-note))
13796 (let ((org-inhibit-startup t)) (org-mode))
13797 (insert (format "# Insert note for %s.
13798 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13799 (cond
13800 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13801 ((eq org-log-note-purpose 'done) "closed todo item")
13802 ((eq org-log-note-purpose 'state)
13803 (format "state change from \"%s\" to \"%s\""
13804 (or org-log-note-previous-state "")
13805 (or org-log-note-state "")))
13806 ((eq org-log-note-purpose 'reschedule)
13807 "rescheduling")
13808 ((eq org-log-note-purpose 'delschedule)
13809 "no longer scheduled")
13810 ((eq org-log-note-purpose 'redeadline)
13811 "changing deadline")
13812 ((eq org-log-note-purpose 'deldeadline)
13813 "removing deadline")
13814 ((eq org-log-note-purpose 'refile)
13815 "refiling")
13816 ((eq org-log-note-purpose 'note)
13817 "this entry")
13818 (t (error "This should not happen")))))
13819 (when org-log-note-extra (insert org-log-note-extra))
13820 (setq-local org-finish-function 'org-store-log-note)
13821 (run-hooks 'org-log-buffer-setup-hook)))
13823 (defvar org-note-abort nil) ; dynamically scoped
13824 (defun org-store-log-note ()
13825 "Finish taking a log note, and insert it to where it belongs."
13826 (let ((txt (prog1 (buffer-string)
13827 (kill-buffer)))
13828 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13829 lines)
13830 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13831 (setq txt (replace-match "" t t txt)))
13832 (when (string-match "\\s-+\\'" txt)
13833 (setq txt (replace-match "" t t txt)))
13834 (setq lines (org-split-string txt "\n"))
13835 (when (org-string-nw-p note)
13836 (setq note
13837 (org-replace-escapes
13838 note
13839 (list (cons "%u" (user-login-name))
13840 (cons "%U" user-full-name)
13841 (cons "%t" (format-time-string
13842 (org-time-stamp-format 'long 'inactive)
13843 org-log-note-effective-time))
13844 (cons "%T" (format-time-string
13845 (org-time-stamp-format 'long nil)
13846 org-log-note-effective-time))
13847 (cons "%d" (format-time-string
13848 (org-time-stamp-format nil 'inactive)
13849 org-log-note-effective-time))
13850 (cons "%D" (format-time-string
13851 (org-time-stamp-format nil nil)
13852 org-log-note-effective-time))
13853 (cons "%s" (cond
13854 ((not org-log-note-state) "")
13855 ((string-match-p org-ts-regexp
13856 org-log-note-state)
13857 (format "\"[%s]\""
13858 (substring org-log-note-state 1 -1)))
13859 (t (format "\"%s\"" org-log-note-state))))
13860 (cons "%S"
13861 (cond
13862 ((not org-log-note-previous-state) "")
13863 ((string-match-p org-ts-regexp
13864 org-log-note-previous-state)
13865 (format "\"[%s]\""
13866 (substring
13867 org-log-note-previous-state 1 -1)))
13868 (t (format "\"%s\""
13869 org-log-note-previous-state)))))))
13870 (when lines (setq note (concat note " \\\\")))
13871 (push note lines))
13872 (when (and lines (not (or current-prefix-arg org-note-abort)))
13873 (with-current-buffer (marker-buffer org-log-note-marker)
13874 (org-with-wide-buffer
13875 ;; Find location for the new note.
13876 (goto-char org-log-note-marker)
13877 (set-marker org-log-note-marker nil)
13878 (goto-char (org-log-beginning t))
13879 ;; Make sure point is at the beginning of an empty line.
13880 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13881 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13882 ;; In an existing list, add a new item at the top level.
13883 ;; Otherwise, indent line like a regular one.
13884 (let ((itemp (org-in-item-p)))
13885 (if itemp
13886 (indent-line-to
13887 (let ((struct (save-excursion
13888 (goto-char itemp) (org-list-struct))))
13889 (org-list-get-ind (org-list-get-top-point struct) struct)))
13890 (org-indent-line)))
13891 (insert (org-list-bullet-string "-") (pop lines))
13892 (let ((ind (org-list-item-body-column (line-beginning-position))))
13893 (dolist (line lines)
13894 (insert "\n")
13895 (indent-line-to ind)
13896 (insert line)))
13897 (message "Note stored")
13898 (org-back-to-heading t)
13899 (org-cycle-hide-drawers 'children))
13900 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13901 ;; from within `org-add-log-note' because `buffer-undo-list'
13902 ;; is then modified outside of `org-with-remote-undo'.
13903 (when (eq this-command 'org-agenda-todo)
13904 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13905 ;; Don't add undo information when called from `org-agenda-todo'.
13906 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13907 (set-window-configuration org-log-note-window-configuration)
13908 (with-current-buffer (marker-buffer org-log-note-return-to)
13909 (goto-char org-log-note-return-to))
13910 (move-marker org-log-note-return-to nil)
13911 (when org-log-post-message (message "%s" org-log-post-message))))
13913 (defun org-remove-empty-drawer-at (pos)
13914 "Remove an empty drawer at position POS.
13915 POS may also be a marker."
13916 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13917 (org-with-wide-buffer
13918 (goto-char pos)
13919 (let ((drawer (org-element-at-point)))
13920 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13921 (not (org-element-property :contents-begin drawer)))
13922 (delete-region (org-element-property :begin drawer)
13923 (progn (goto-char (org-element-property :end drawer))
13924 (skip-chars-backward " \r\t\n")
13925 (forward-line)
13926 (point))))))))
13928 (defvar org-ts-type nil)
13929 (defun org-sparse-tree (&optional arg type)
13930 "Create a sparse tree, prompt for the details.
13931 This command can create sparse trees. You first need to select the type
13932 of match used to create the tree:
13934 t Show all TODO entries.
13935 T Show entries with a specific TODO keyword.
13936 m Show entries selected by a tags/property match.
13937 p Enter a property name and its value (both with completion on existing
13938 names/values) and show entries with that property.
13939 r Show entries matching a regular expression (`/' can be used as well).
13940 b Show deadlines and scheduled items before a date.
13941 a Show deadlines and scheduled items after a date.
13942 d Show deadlines due within `org-deadline-warning-days'.
13943 D Show deadlines and scheduled items between a date range."
13944 (interactive "P")
13945 (setq type (or type org-sparse-tree-default-date-type))
13946 (setq org-ts-type type)
13947 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13948 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13949 \[c]ycle through date types: %s"
13950 (cl-case type
13951 (all "all timestamps")
13952 (scheduled "only scheduled")
13953 (deadline "only deadline")
13954 (active "only active timestamps")
13955 (inactive "only inactive timestamps")
13956 (closed "with a closed time-stamp")
13957 (otherwise "scheduled/deadline")))
13958 (let ((answer (read-char-exclusive)))
13959 (cl-case answer
13961 (org-sparse-tree
13963 (cadr
13964 (memq type '(nil all scheduled deadline active inactive closed)))))
13965 (?d (call-interactively 'org-check-deadlines))
13966 (?b (call-interactively 'org-check-before-date))
13967 (?a (call-interactively 'org-check-after-date))
13968 (?D (call-interactively 'org-check-dates-range))
13969 (?t (call-interactively 'org-show-todo-tree))
13970 (?T (org-show-todo-tree '(4)))
13971 (?m (call-interactively 'org-match-sparse-tree))
13972 ((?p ?P)
13973 (let* ((kwd (completing-read
13974 "Property: " (mapcar #'list (org-buffer-property-keys))))
13975 (value (completing-read
13976 "Value: " (mapcar #'list (org-property-values kwd)))))
13977 (unless (string-match "\\`{.*}\\'" value)
13978 (setq value (concat "\"" value "\"")))
13979 (org-match-sparse-tree arg (concat kwd "=" value))))
13980 ((?r ?R ?/) (call-interactively 'org-occur))
13981 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13983 (defvar-local org-occur-highlights nil
13984 "List of overlays used for occur matches.")
13985 (defvar-local org-occur-parameters nil
13986 "Parameters of the active org-occur calls.
13987 This is a list, each call to org-occur pushes as cons cell,
13988 containing the regular expression and the callback, onto the list.
13989 The list can contain several entries if `org-occur' has been called
13990 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13991 will only contain one set of parameters. When the highlights are
13992 removed (for example with `C-c C-c', or with the next edit (depending
13993 on `org-remove-highlights-with-change'), this variable is emptied
13994 as well.")
13996 (defun org-occur (regexp &optional keep-previous callback)
13997 "Make a compact tree which shows all matches of REGEXP.
13999 The tree will show the lines where the regexp matches, and any other context
14000 defined in `org-show-context-detail', which see.
14002 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
14003 done by a previous call to `org-occur' will be kept, to allow stacking of
14004 calls to this command.
14006 Optional argument CALLBACK can be a function of no argument. In this case,
14007 it is called with point at the end of the match, match data being set
14008 accordingly. Current match is shown only if the return value is non-nil.
14009 The function must neither move point nor alter narrowing."
14010 (interactive "sRegexp: \nP")
14011 (when (equal regexp "")
14012 (user-error "Regexp cannot be empty"))
14013 (unless keep-previous
14014 (org-remove-occur-highlights nil nil t))
14015 (push (cons regexp callback) org-occur-parameters)
14016 (let ((cnt 0))
14017 (save-excursion
14018 (goto-char (point-min))
14019 (when (or (not keep-previous) ; do not want to keep
14020 (not org-occur-highlights)) ; no previous matches
14021 ;; hide everything
14022 (org-overview))
14023 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
14024 (isearch-no-upper-case-p regexp t)
14025 org-occur-case-fold-search)))
14026 (while (re-search-forward regexp nil t)
14027 (when (or (not callback)
14028 (save-match-data (funcall callback)))
14029 (setq cnt (1+ cnt))
14030 (when org-highlight-sparse-tree-matches
14031 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14032 (org-show-context 'occur-tree)))))
14033 (when org-remove-highlights-with-change
14034 (add-hook 'before-change-functions 'org-remove-occur-highlights
14035 nil 'local))
14036 (unless org-sparse-tree-open-archived-trees
14037 (org-hide-archived-subtrees (point-min) (point-max)))
14038 (run-hooks 'org-occur-hook)
14039 (when (called-interactively-p 'interactive)
14040 (message "%d match(es) for regexp %s" cnt regexp))
14041 cnt))
14043 (defun org-occur-next-match (&optional n _reset)
14044 "Function for `next-error-function' to find sparse tree matches.
14045 N is the number of matches to move, when negative move backwards.
14046 This function always goes back to the starting point when no
14047 match is found."
14048 (let* ((limit (if (< n 0) (point-min) (point-max)))
14049 (search-func (if (< n 0)
14050 'previous-single-char-property-change
14051 'next-single-char-property-change))
14052 (n (abs n))
14053 (pos (point))
14055 (catch 'exit
14056 (while (setq p1 (funcall search-func (point) 'org-type))
14057 (when (equal p1 limit)
14058 (goto-char pos)
14059 (user-error "No more matches"))
14060 (when (equal (get-char-property p1 'org-type) 'org-occur)
14061 (setq n (1- n))
14062 (when (= n 0)
14063 (goto-char p1)
14064 (throw 'exit (point))))
14065 (goto-char p1))
14066 (goto-char p1)
14067 (user-error "No more matches"))))
14069 (defun org-show-context (&optional key)
14070 "Make sure point and context are visible.
14071 Optional argument KEY, when non-nil, is a symbol. See
14072 `org-show-context-detail' for allowed values and how much is to
14073 be shown."
14074 (org-show-set-visibility
14075 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14076 ((cdr (assq key org-show-context-detail)))
14077 (t (cdr (assq 'default org-show-context-detail))))))
14079 (defun org-show-set-visibility (detail)
14080 "Set visibility around point according to DETAIL.
14081 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14082 `tree', `canonical' or t. See `org-show-context-detail' for more
14083 information."
14084 ;; Show current heading and possibly its entry, following headline
14085 ;; or all children.
14086 (if (and (org-at-heading-p) (not (eq detail 'local)))
14087 (org-flag-heading nil)
14088 (org-show-entry)
14089 ;; If point is hidden within a drawer or a block, make sure to
14090 ;; expose it.
14091 (dolist (o (overlays-at (point)))
14092 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14093 (delete-overlay o)))
14094 (unless (org-before-first-heading-p)
14095 (org-with-limited-levels
14096 (cl-case detail
14097 ((tree canonical t) (org-show-children))
14098 ((nil minimal ancestors))
14099 (t (save-excursion
14100 (outline-next-heading)
14101 (org-flag-heading nil)))))))
14102 ;; Show all siblings.
14103 (when (eq detail 'lineage) (org-show-siblings))
14104 ;; Show ancestors, possibly with their children.
14105 (when (memq detail '(ancestors lineage tree canonical t))
14106 (save-excursion
14107 (while (org-up-heading-safe)
14108 (org-flag-heading nil)
14109 (when (memq detail '(canonical t)) (org-show-entry))
14110 (when (memq detail '(tree canonical t)) (org-show-children))))))
14112 (defvar org-reveal-start-hook nil
14113 "Hook run before revealing a location.")
14115 (defun org-reveal (&optional siblings)
14116 "Show current entry, hierarchy above it, and the following headline.
14118 This can be used to show a consistent set of context around
14119 locations exposed with `org-show-context'.
14121 With optional argument SIBLINGS, on each level of the hierarchy all
14122 siblings are shown. This repairs the tree structure to what it would
14123 look like when opened with hierarchical calls to `org-cycle'.
14125 With a \\[universal-argument] \\[universal-argument] prefix, \
14126 go to the parent and show the entire tree."
14127 (interactive "P")
14128 (run-hooks 'org-reveal-start-hook)
14129 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14130 ((equal siblings '(16))
14131 (save-excursion
14132 (when (org-up-heading-safe)
14133 (org-show-subtree)
14134 (run-hook-with-args 'org-cycle-hook 'subtree))))
14135 (t (org-show-set-visibility 'lineage))))
14137 (defun org-highlight-new-match (beg end)
14138 "Highlight from BEG to END and mark the highlight is an occur headline."
14139 (let ((ov (make-overlay beg end)))
14140 (overlay-put ov 'face 'secondary-selection)
14141 (overlay-put ov 'org-type 'org-occur)
14142 (push ov org-occur-highlights)))
14144 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14145 "Remove the occur highlights from the buffer.
14146 BEG and END are ignored. If NOREMOVE is nil, remove this function
14147 from the `before-change-functions' in the current buffer."
14148 (interactive)
14149 (unless org-inhibit-highlight-removal
14150 (mapc #'delete-overlay org-occur-highlights)
14151 (setq org-occur-highlights nil)
14152 (setq org-occur-parameters nil)
14153 (unless noremove
14154 (remove-hook 'before-change-functions
14155 'org-remove-occur-highlights 'local))))
14157 ;;;; Priorities
14159 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14160 "Regular expression matching the priority indicator.")
14162 (defvar org-remove-priority-next-time nil)
14164 (defun org-priority-up ()
14165 "Increase the priority of the current item."
14166 (interactive)
14167 (org-priority 'up))
14169 (defun org-priority-down ()
14170 "Decrease the priority of the current item."
14171 (interactive)
14172 (org-priority 'down))
14174 (defun org-priority (&optional action _show)
14175 "Change the priority of an item.
14176 ACTION can be `set', `up', `down', or a character."
14177 (interactive "P")
14178 (if (equal action '(4))
14179 (org-show-priority)
14180 (unless org-enable-priority-commands
14181 (user-error "Priority commands are disabled"))
14182 (setq action (or action 'set))
14183 (let (current new news have remove)
14184 (save-excursion
14185 (org-back-to-heading t)
14186 (when (looking-at org-priority-regexp)
14187 (setq current (string-to-char (match-string 2))
14188 have t))
14189 (cond
14190 ((eq action 'remove)
14191 (setq remove t new ?\ ))
14192 ((or (eq action 'set)
14193 (integerp action))
14194 (if (not (eq action 'set))
14195 (setq new action)
14196 (message "Priority %c-%c, SPC to remove: "
14197 org-highest-priority org-lowest-priority)
14198 (save-match-data
14199 (setq new (read-char-exclusive))))
14200 (when (and (= (upcase org-highest-priority) org-highest-priority)
14201 (= (upcase org-lowest-priority) org-lowest-priority))
14202 (setq new (upcase new)))
14203 (cond ((equal new ?\ ) (setq remove t))
14204 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14205 (user-error "Priority must be between `%c' and `%c'"
14206 org-highest-priority org-lowest-priority))))
14207 ((eq action 'up)
14208 (setq new (if have
14209 (1- current) ; normal cycling
14210 ;; last priority was empty
14211 (if (eq last-command this-command)
14212 org-lowest-priority ; wrap around empty to lowest
14213 ;; default
14214 (if org-priority-start-cycle-with-default
14215 org-default-priority
14216 (1- org-default-priority))))))
14217 ((eq action 'down)
14218 (setq new (if have
14219 (1+ current) ; normal cycling
14220 ;; last priority was empty
14221 (if (eq last-command this-command)
14222 org-highest-priority ; wrap around empty to highest
14223 ;; default
14224 (if org-priority-start-cycle-with-default
14225 org-default-priority
14226 (1+ org-default-priority))))))
14227 (t (user-error "Invalid action")))
14228 (when (or (< (upcase new) org-highest-priority)
14229 (> (upcase new) org-lowest-priority))
14230 (if (and (memq action '(up down))
14231 (not have) (not (eq last-command this-command)))
14232 ;; `new' is from default priority
14233 (error
14234 "The default can not be set, see `org-default-priority' why")
14235 ;; normal cycling: `new' is beyond highest/lowest priority
14236 ;; and is wrapped around to the empty priority
14237 (setq remove t)))
14238 (setq news (format "%c" new))
14239 (if have
14240 (if remove
14241 (replace-match "" t t nil 1)
14242 (replace-match news t t nil 2))
14243 (if remove
14244 (user-error "No priority cookie found in line")
14245 (let ((case-fold-search nil))
14246 (looking-at org-todo-line-regexp))
14247 (if (match-end 2)
14248 (progn
14249 (goto-char (match-end 2))
14250 (insert " [#" news "]"))
14251 (goto-char (match-beginning 3))
14252 (insert "[#" news "] "))))
14253 (org-set-tags nil 'align))
14254 (if remove
14255 (message "Priority removed")
14256 (message "Priority of current item set to %s" news)))))
14258 (defun org-show-priority ()
14259 "Show the priority of the current item.
14260 This priority is composed of the main priority given with the [#A] cookies,
14261 and by additional input from the age of a schedules or deadline entry."
14262 (interactive)
14263 (let ((pri (if (eq major-mode 'org-agenda-mode)
14264 (org-get-at-bol 'priority)
14265 (save-excursion
14266 (save-match-data
14267 (beginning-of-line)
14268 (and (looking-at org-heading-regexp)
14269 (org-get-priority (match-string 0))))))))
14270 (message "Priority is %d" (if pri pri -1000))))
14272 (defun org-get-priority (s)
14273 "Find priority cookie and return priority."
14274 (save-match-data
14275 (if (functionp org-get-priority-function)
14276 (funcall org-get-priority-function)
14277 (if (not (string-match org-priority-regexp s))
14278 (* 1000 (- org-lowest-priority org-default-priority))
14279 (* 1000 (- org-lowest-priority
14280 (string-to-char (match-string 2 s))))))))
14282 ;;;; Tags
14284 (defvar org-agenda-archives-mode)
14285 (defvar org-map-continue-from nil
14286 "Position from where mapping should continue.
14287 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14289 (defvar org-scanner-tags nil
14290 "The current tag list while the tags scanner is running.")
14292 (defvar org-trust-scanner-tags nil
14293 "Should `org-get-tags-at' use the tags for the scanner.
14294 This is for internal dynamical scoping only.
14295 When this is non-nil, the function `org-get-tags-at' will return the value
14296 of `org-scanner-tags' instead of building the list by itself. This
14297 can lead to large speed-ups when the tags scanner is used in a file with
14298 many entries, and when the list of tags is retrieved, for example to
14299 obtain a list of properties. Building the tags list for each entry in such
14300 a file becomes an N^2 operation - but with this variable set, it scales
14301 as N.")
14303 (defvar org--matcher-tags-todo-only nil)
14305 (defun org-scan-tags (action matcher todo-only &optional start-level)
14306 "Scan headline tags with inheritance and produce output ACTION.
14308 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14309 or `agenda' to produce an entry list for an agenda view. It can also be
14310 a Lisp form or a function that should be called at each matched headline, in
14311 this case the return value is a list of all return values from these calls.
14313 MATCHER is a function accepting three arguments, returning
14314 a non-nil value whenever a given set of tags qualifies a headline
14315 for inclusion. See `org-make-tags-matcher' for more information.
14316 As a special case, it can also be set to t (respectively nil) in
14317 order to match all (respectively none) headline.
14319 When TODO-ONLY is non-nil, only lines with a not-done TODO
14320 keyword are included in the output.
14322 START-LEVEL can be a string with asterisks, reducing the scope to
14323 headlines matching this string."
14324 (require 'org-agenda)
14325 (let* ((re (concat "^"
14326 (if start-level
14327 ;; Get the correct level to match
14328 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14329 org-outline-regexp)
14330 " *\\(\\<\\("
14331 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14332 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14333 (props (list 'face 'default
14334 'done-face 'org-agenda-done
14335 'undone-face 'default
14336 'mouse-face 'highlight
14337 'org-not-done-regexp org-not-done-regexp
14338 'org-todo-regexp org-todo-regexp
14339 'org-complex-heading-regexp org-complex-heading-regexp
14340 'help-echo
14341 (format "mouse-2 or RET jump to org file %s"
14342 (abbreviate-file-name
14343 (or (buffer-file-name (buffer-base-buffer))
14344 (buffer-name (buffer-base-buffer)))))))
14345 (org-map-continue-from nil)
14346 lspos tags tags-list
14347 (tags-alist (list (cons 0 org-file-tags)))
14348 (llast 0) rtn rtn1 level category i txt
14349 todo marker entry priority
14350 ts-date ts-date-type ts-date-pair)
14351 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14352 (setq action (list 'lambda nil action)))
14353 (save-excursion
14354 (goto-char (point-min))
14355 (when (eq action 'sparse-tree)
14356 (org-overview)
14357 (org-remove-occur-highlights))
14358 (while (let (case-fold-search)
14359 (re-search-forward re nil t))
14360 (setq org-map-continue-from nil)
14361 (catch :skip
14362 (setq todo
14363 ;; TODO: is the 1-2 difference a bug?
14364 (when (match-end 1) (match-string-no-properties 2))
14365 tags (when (match-end 4) (match-string-no-properties 4)))
14366 (goto-char (setq lspos (match-beginning 0)))
14367 (setq level (org-reduced-level (org-outline-level))
14368 category (org-get-category))
14369 (when (eq action 'agenda)
14370 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14371 ts-date (car ts-date-pair)
14372 ts-date-type (cdr ts-date-pair)))
14373 (setq i llast llast level)
14374 ;; remove tag lists from same and sublevels
14375 (while (>= i level)
14376 (when (setq entry (assoc i tags-alist))
14377 (setq tags-alist (delete entry tags-alist)))
14378 (setq i (1- i)))
14379 ;; add the next tags
14380 (when tags
14381 (setq tags (org-split-string tags ":")
14382 tags-alist
14383 (cons (cons level tags) tags-alist)))
14384 ;; compile tags for current headline
14385 (setq tags-list
14386 (if org-use-tag-inheritance
14387 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14388 tags)
14389 org-scanner-tags tags-list)
14390 (when org-use-tag-inheritance
14391 (setcdr (car tags-alist)
14392 (mapcar (lambda (x)
14393 (setq x (copy-sequence x))
14394 (org-add-prop-inherited x))
14395 (cdar tags-alist))))
14396 (when (and tags org-use-tag-inheritance
14397 (or (not (eq t org-use-tag-inheritance))
14398 org-tags-exclude-from-inheritance))
14399 ;; Selective inheritance, remove uninherited ones.
14400 (setcdr (car tags-alist)
14401 (org-remove-uninherited-tags (cdar tags-alist))))
14402 (when (and
14404 ;; eval matcher only when the todo condition is OK
14405 (and (or (not todo-only) (member todo org-not-done-keywords))
14406 (if (functionp matcher)
14407 (let ((case-fold-search t) (org-trust-scanner-tags t))
14408 (funcall matcher todo tags-list level))
14409 matcher))
14411 ;; Call the skipper, but return t if it does not
14412 ;; skip, so that the `and' form continues evaluating.
14413 (progn
14414 (unless (eq action 'sparse-tree) (org-agenda-skip))
14417 ;; Check if timestamps are deselecting this entry
14418 (or (not todo-only)
14419 (and (member todo org-not-done-keywords)
14420 (or (not org-agenda-tags-todo-honor-ignore-options)
14421 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14423 ;; select this headline
14424 (cond
14425 ((eq action 'sparse-tree)
14426 (and org-highlight-sparse-tree-matches
14427 (org-get-heading) (match-end 0)
14428 (org-highlight-new-match
14429 (match-beginning 1) (match-end 1)))
14430 (org-show-context 'tags-tree))
14431 ((eq action 'agenda)
14432 (setq txt (org-agenda-format-item
14434 (concat
14435 (if (eq org-tags-match-list-sublevels 'indented)
14436 (make-string (1- level) ?.) "")
14437 (org-get-heading))
14438 (make-string level ?\s)
14439 category
14440 tags-list)
14441 priority (org-get-priority txt))
14442 (goto-char lspos)
14443 (setq marker (org-agenda-new-marker))
14444 (org-add-props txt props
14445 'org-marker marker 'org-hd-marker marker 'org-category category
14446 'todo-state todo
14447 'ts-date ts-date
14448 'priority priority
14449 'type (concat "tagsmatch" ts-date-type))
14450 (push txt rtn))
14451 ((functionp action)
14452 (setq org-map-continue-from nil)
14453 (save-excursion
14454 (setq rtn1 (funcall action))
14455 (push rtn1 rtn)))
14456 (t (user-error "Invalid action")))
14458 ;; if we are to skip sublevels, jump to end of subtree
14459 (unless org-tags-match-list-sublevels
14460 (org-end-of-subtree t)
14461 (backward-char 1))))
14462 ;; Get the correct position from where to continue
14463 (if org-map-continue-from
14464 (goto-char org-map-continue-from)
14465 (and (= (point) lspos) (end-of-line 1)))))
14466 (when (and (eq action 'sparse-tree)
14467 (not org-sparse-tree-open-archived-trees))
14468 (org-hide-archived-subtrees (point-min) (point-max)))
14469 (nreverse rtn)))
14471 (defun org-remove-uninherited-tags (tags)
14472 "Remove all tags that are not inherited from the list TAGS."
14473 (cond
14474 ((eq org-use-tag-inheritance t)
14475 (if org-tags-exclude-from-inheritance
14476 (org-delete-all org-tags-exclude-from-inheritance tags)
14477 tags))
14478 ((not org-use-tag-inheritance) nil)
14479 ((stringp org-use-tag-inheritance)
14480 (delq nil (mapcar
14481 (lambda (x)
14482 (if (and (string-match org-use-tag-inheritance x)
14483 (not (member x org-tags-exclude-from-inheritance)))
14484 x nil))
14485 tags)))
14486 ((listp org-use-tag-inheritance)
14487 (delq nil (mapcar
14488 (lambda (x)
14489 (if (member x org-use-tag-inheritance) x nil))
14490 tags)))))
14492 (defun org-match-sparse-tree (&optional todo-only match)
14493 "Create a sparse tree according to tags string MATCH.
14494 MATCH can contain positive and negative selection of tags, like
14495 \"+WORK+URGENT-WITHBOSS\".
14496 If optional argument TODO-ONLY is non-nil, only select lines that are
14497 also TODO lines."
14498 (interactive "P")
14499 (org-agenda-prepare-buffers (list (current-buffer)))
14500 (let ((org--matcher-tags-todo-only todo-only))
14501 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14502 org--matcher-tags-todo-only)))
14504 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14506 (defvar org-cached-props nil)
14507 (defun org-cached-entry-get (pom property)
14508 (if (or (eq t org-use-property-inheritance)
14509 (and (stringp org-use-property-inheritance)
14510 (let ((case-fold-search t))
14511 (string-match-p org-use-property-inheritance property)))
14512 (and (listp org-use-property-inheritance)
14513 (member-ignore-case property org-use-property-inheritance)))
14514 ;; Caching is not possible, check it directly.
14515 (org-entry-get pom property 'inherit)
14516 ;; Get all properties, so we can do complicated checks easily.
14517 (cdr (assoc-string property
14518 (or org-cached-props
14519 (setq org-cached-props (org-entry-properties pom)))
14520 t))))
14522 (defun org-global-tags-completion-table (&optional files)
14523 "Return the list of all tags in all agenda buffer/files.
14524 Optional FILES argument is a list of files which can be used
14525 instead of the agenda files."
14526 (save-excursion
14527 (org-uniquify
14528 (delq nil
14529 (apply #'append
14530 (mapcar
14531 (lambda (file)
14532 (set-buffer (find-file-noselect file))
14533 (mapcar (lambda (x)
14534 (and (stringp (car-safe x))
14535 (list (car-safe x))))
14536 (or org-current-tag-alist (org-get-buffer-tags))))
14537 (if (car-safe files) files
14538 (org-agenda-files))))))))
14540 (defun org-make-tags-matcher (match)
14541 "Create the TAGS/TODO matcher form for the selection string MATCH.
14543 Returns a cons of the selection string MATCH and a function
14544 implementing the matcher.
14546 The matcher is to be called at an Org entry, with point on the
14547 headline, and returns non-nil if the entry matches the selection
14548 string MATCH. It must be called with three arguments: the TODO
14549 keyword at the entry (or nil if none), the list of all tags at
14550 the entry including inherited ones and the reduced level of the
14551 headline. Additionally, the category of the entry, if any, must
14552 be specified as the text property `org-category' on the headline.
14554 This function sets the variable `org--matcher-tags-todo-only' to
14555 a non-nil value if the matcher restricts matching to TODO
14556 entries, otherwise it is not touched.
14558 See also `org-scan-tags'."
14559 (unless match
14560 ;; Get a new match request, with completion against the global
14561 ;; tags table and the local tags in current buffer.
14562 (let ((org-last-tags-completion-table
14563 (org-uniquify
14564 (delq nil (append (org-get-buffer-tags)
14565 (org-global-tags-completion-table))))))
14566 (setq match
14567 (completing-read
14568 "Match: "
14569 'org-tags-completion-function nil nil nil 'org-tags-history))))
14571 (let ((match0 match)
14572 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14573 (start 0)
14574 tagsmatch todomatch tagsmatcher todomatcher)
14576 ;; Expand group tags.
14577 (setq match (org-tags-expand match))
14579 ;; Check if there is a TODO part of this match, which would be the
14580 ;; part after a "/". To make sure that this slash is not part of
14581 ;; a property value to be matched against, we also check that
14582 ;; there is no / after that slash. First, find the last slash.
14583 (let ((s 0))
14584 (while (string-match "/+" match s)
14585 (setq start (match-beginning 0))
14586 (setq s (match-end 0))))
14587 (if (and (string-match "/+" match start)
14588 (not (string-match-p "\"" match start)))
14589 ;; Match contains also a TODO-matching request.
14590 (progn
14591 (setq tagsmatch (substring match 0 (match-beginning 0)))
14592 (setq todomatch (substring match (match-end 0)))
14593 (when (string-prefix-p "!" todomatch)
14594 (setq org--matcher-tags-todo-only t)
14595 (setq todomatch (substring todomatch 1)))
14596 (when (string-match "\\`\\s-*\\'" todomatch)
14597 (setq todomatch nil)))
14598 ;; Only matching tags.
14599 (setq tagsmatch match)
14600 (setq todomatch nil))
14602 ;; Make the tags matcher.
14603 (when (org-string-nw-p tagsmatch)
14604 (let ((orlist nil)
14605 (orterms (org-split-string tagsmatch "|"))
14606 term)
14607 (while (setq term (pop orterms))
14608 (while (and (equal (substring term -1) "\\") orterms)
14609 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14610 (while (string-match re term)
14611 (let* ((rest (substring term (match-end 0)))
14612 (minus (and (match-end 1)
14613 (equal (match-string 1 term) "-")))
14614 (tag (save-match-data
14615 (replace-regexp-in-string
14616 "\\\\-" "-" (match-string 2 term))))
14617 (regexp (eq (string-to-char tag) ?{))
14618 (levelp (match-end 4))
14619 (propp (match-end 5))
14621 (cond
14622 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14623 (levelp
14624 `(,(org-op-to-function (match-string 3 term))
14625 level
14626 ,(string-to-number (match-string 4 term))))
14627 (propp
14628 (let* ((gv (pcase (upcase (match-string 5 term))
14629 ("CATEGORY"
14630 '(get-text-property (point) 'org-category))
14631 ("TODO" 'todo)
14632 (p `(org-cached-entry-get nil ,p))))
14633 (pv (match-string 7 term))
14634 (regexp (eq (string-to-char pv) ?{))
14635 (strp (eq (string-to-char pv) ?\"))
14636 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14637 (po (org-op-to-function (match-string 6 term)
14638 (if timep 'time strp))))
14639 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14640 (when timep (setq pv (org-matcher-time pv)))
14641 (cond ((and regexp (eq po 'org<>))
14642 `(not (string-match ,pv (or ,gv ""))))
14643 (regexp `(string-match ,pv (or ,gv "")))
14644 (strp `(,po (or ,gv "") ,pv))
14646 `(,po
14647 (string-to-number (or ,gv ""))
14648 ,(string-to-number pv))))))
14649 (t `(member ,tag tags-list)))))
14650 (push (if minus `(not ,mm) mm) tagsmatcher)
14651 (setq term rest)))
14652 (push `(and ,@tagsmatcher) orlist)
14653 (setq tagsmatcher nil))
14654 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14656 ;; Make the TODO matcher.
14657 (when (org-string-nw-p todomatch)
14658 (let ((orlist nil))
14659 (dolist (term (org-split-string todomatch "|"))
14660 (while (string-match re term)
14661 (let* ((minus (and (match-end 1)
14662 (equal (match-string 1 term) "-")))
14663 (kwd (match-string 2 term))
14664 (regexp (eq (string-to-char kwd) ?{))
14665 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14666 `(equal todo ,kwd))))
14667 (push (if minus `(not ,mm) mm) todomatcher))
14668 (setq term (substring term (match-end 0))))
14669 (push (if (> (length todomatcher) 1)
14670 (cons 'and todomatcher)
14671 (car todomatcher))
14672 orlist)
14673 (setq todomatcher nil))
14674 (setq todomatcher (cons 'or orlist))))
14676 ;; Return the string and function of the matcher. If no
14677 ;; tags-specific or todo-specific matcher exists, match
14678 ;; everything.
14679 (let ((matcher (if (and tagsmatcher todomatcher)
14680 `(and ,tagsmatcher ,todomatcher)
14681 (or tagsmatcher todomatcher t))))
14682 (when org--matcher-tags-todo-only
14683 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14684 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14686 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14687 "Expand group tags in MATCH.
14689 This replaces every group tag in MATCH with a regexp tag search.
14690 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14691 will be replaced like this:
14693 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14694 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14695 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14697 Replacing by a regexp preserves the structure of the match.
14698 E.g., this expansion
14700 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14702 will match anything tagged with \"Lab\" and \"Home\", or tagged
14703 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14705 A group tag in MATCH can contain regular expressions of its own.
14706 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14707 will be replaced like this:
14709 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14711 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14712 assumed to be a single group tag, and the function will return
14713 the list of tags in this group.
14715 When DOWNCASE is non-nil, expand downcased TAGS."
14716 (if org-group-tags
14717 (let* ((case-fold-search t)
14718 (stable org-mode-syntax-table)
14719 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14720 (taggroups (if downcased
14721 (mapcar (lambda (tg) (mapcar #'downcase tg))
14722 taggroups)
14723 taggroups))
14724 (taggroups-keys (mapcar #'car taggroups))
14725 (return-match (if downcased (downcase match) match))
14726 (count 0)
14727 (work-already-expanded tags-already-expanded)
14728 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14729 ;; @ and _ are allowed as word-components in tags.
14730 (modify-syntax-entry ?@ "w" stable)
14731 (modify-syntax-entry ?_ "w" stable)
14732 ;; Temporarily replace regexp-expressions in the match-expression.
14733 (while (string-match "{.+?}" return-match)
14734 (cl-incf count)
14735 (push (match-string 0 return-match) regexps-in-match)
14736 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14737 (while (and taggroups-keys
14738 (with-syntax-table stable
14739 (string-match
14740 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14741 (regexp-opt taggroups-keys) "\\>\\)")
14742 return-match)))
14743 (let* ((dir (match-string 1 return-match))
14744 (tag (match-string 2 return-match))
14745 (tag (if downcased (downcase tag) tag)))
14746 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14747 (member tag work-already-expanded))
14748 (setq tags-in-group (assoc tag taggroups))
14749 (push tag work-already-expanded)
14750 ;; Recursively expand each tag in the group, if the tag hasn't
14751 ;; already been expanded. Restore the match-data after all recursive calls.
14752 (save-match-data
14753 (let (tags-expanded)
14754 (dolist (x (cdr tags-in-group))
14755 (if (and (member x taggroups-keys)
14756 (not (member x work-already-expanded)))
14757 (setq tags-expanded
14758 (delete-dups
14759 (append
14760 (org-tags-expand x t downcased
14761 work-already-expanded)
14762 tags-expanded)))
14763 (setq tags-expanded
14764 (append (list x) tags-expanded)))
14765 (setq work-already-expanded
14766 (delete-dups
14767 (append tags-expanded
14768 work-already-expanded))))
14769 (setq tags-in-group
14770 (delete-dups (cons (car tags-in-group)
14771 tags-expanded)))))
14772 ;; Filter tag-regexps from tags.
14773 (setq regexp-in-group-escaped
14774 (delq nil (mapcar (lambda (x)
14775 (if (stringp x)
14776 (and (equal "{" (substring x 0 1))
14777 (equal "}" (substring x -1))
14780 tags-in-group))
14781 regexp-in-group
14782 (mapcar (lambda (x)
14783 (substring x 1 -1))
14784 regexp-in-group-escaped)
14785 tags-in-group
14786 (delq nil (mapcar (lambda (x)
14787 (if (stringp x)
14788 (and (not (equal "{" (substring x 0 1)))
14789 (not (equal "}" (substring x -1)))
14792 tags-in-group)))
14793 ;; If single-as-list, do no more in the while-loop.
14794 (if (not single-as-list)
14795 (progn
14796 (when regexp-in-group
14797 (setq regexp-in-group
14798 (concat "\\|"
14799 (mapconcat 'identity regexp-in-group
14800 "\\|"))))
14801 (setq tags-in-group
14802 (concat dir
14803 "{\\<"
14804 (regexp-opt tags-in-group)
14805 "\\>"
14806 regexp-in-group
14807 "}"))
14808 (when (stringp tags-in-group)
14809 (org-add-props tags-in-group '(grouptag t)))
14810 (setq return-match
14811 (replace-match tags-in-group t t return-match)))
14812 (setq tags-in-group
14813 (append regexp-in-group-escaped tags-in-group))))
14814 (setq taggroups-keys (delete tag taggroups-keys))))
14815 ;; Add the regular expressions back into the match-expression again.
14816 (while regexps-in-match
14817 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14818 (pop regexps-in-match)
14819 return-match t t))
14820 (cl-decf count))
14821 (if single-as-list
14822 (if tags-in-group tags-in-group (list return-match))
14823 return-match))
14824 (if single-as-list
14825 (list (if downcased (downcase match) match))
14826 match)))
14828 (defun org-op-to-function (op &optional stringp)
14829 "Turn an operator into the appropriate function."
14830 (setq op
14831 (cond
14832 ((equal op "<" ) '(< string< org-time<))
14833 ((equal op ">" ) '(> org-string> org-time>))
14834 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14835 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14836 ((member op '("=" "==")) '(= string= org-time=))
14837 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14838 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14840 (defun org<> (a b) (not (= a b)))
14841 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14842 (defun org-string>= (a b) (not (string< a b)))
14843 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14844 (defun org-string<> (a b) (not (string= a b)))
14845 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14846 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14847 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14848 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14849 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14850 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14851 (defun org-2ft (s)
14852 "Convert S to a floating point time.
14853 If S is already a number, just return it. If it is a string, parse
14854 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14855 (cond
14856 ((numberp s) s)
14857 ((stringp s)
14858 (condition-case nil
14859 (float-time (apply 'encode-time (org-parse-time-string s)))
14860 (error 0.)))
14861 (t 0.)))
14863 (defun org-time-today ()
14864 "Time in seconds today at 0:00.
14865 Returns the float number of seconds since the beginning of the
14866 epoch to the beginning of today (00:00)."
14867 (float-time (apply 'encode-time
14868 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14870 (defun org-matcher-time (s)
14871 "Interpret a time comparison value."
14872 (save-match-data
14873 (cond
14874 ((string= s "<now>") (float-time))
14875 ((string= s "<today>") (org-time-today))
14876 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14877 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14878 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14879 (+ (org-time-today)
14880 (* (string-to-number (match-string 1 s))
14881 (cdr (assoc (match-string 2 s)
14882 '(("d" . 86400.0) ("w" . 604800.0)
14883 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14884 (t (org-2ft s)))))
14886 (defun org-match-any-p (re list)
14887 "Does re match any element of list?"
14888 (setq list (mapcar (lambda (x) (string-match re x)) list))
14889 (delq nil list))
14891 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14892 (defvar org-tags-overlay (make-overlay 1 1))
14893 (delete-overlay org-tags-overlay)
14895 (defun org-get-local-tags-at (&optional pos)
14896 "Get a list of tags defined in the current headline."
14897 (org-get-tags-at pos 'local))
14899 (defun org-get-local-tags ()
14900 "Get a list of tags defined in the current headline."
14901 (org-get-tags-at nil 'local))
14903 (defun org-get-tags-at (&optional pos local)
14904 "Get a list of all headline tags applicable at POS.
14905 POS defaults to point. If tags are inherited, the list contains
14906 the targets in the same sequence as the headlines appear, i.e.
14907 the tags of the current headline come last.
14908 When LOCAL is non-nil, only return tags from the current headline,
14909 ignore inherited ones."
14910 (interactive)
14911 (if (and org-trust-scanner-tags
14912 (or (not pos) (equal pos (point)))
14913 (not local))
14914 org-scanner-tags
14915 (let (tags ltags lastpos parent)
14916 (save-excursion
14917 (save-restriction
14918 (widen)
14919 (goto-char (or pos (point)))
14920 (save-match-data
14921 (catch 'done
14922 (condition-case nil
14923 (progn
14924 (org-back-to-heading t)
14925 (while (not (equal lastpos (point)))
14926 (setq lastpos (point))
14927 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14928 (setq ltags (org-split-string
14929 (match-string-no-properties 1) ":"))
14930 (when parent
14931 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14932 (setq tags (append
14933 (if parent
14934 (org-remove-uninherited-tags ltags)
14935 ltags)
14936 tags)))
14937 (or org-use-tag-inheritance (throw 'done t))
14938 (when local (throw 'done t))
14939 (or (org-up-heading-safe) (error nil))
14940 (setq parent t)))
14941 (error nil)))))
14942 (if local
14943 tags
14944 (reverse (delete-dups
14945 (reverse (append
14946 (org-remove-uninherited-tags
14947 org-file-tags)
14948 tags)))))))))
14950 (defun org-add-prop-inherited (s)
14951 (add-text-properties 0 (length s) '(inherited t) s)
14954 (defun org-toggle-tag (tag &optional onoff)
14955 "Toggle the tag TAG for the current line.
14956 If ONOFF is `on' or `off', don't toggle but set to this state."
14957 (let (res current)
14958 (save-excursion
14959 (org-back-to-heading t)
14960 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14961 (point-at-eol) t)
14962 (progn
14963 (setq current (match-string 1))
14964 (replace-match ""))
14965 (setq current ""))
14966 (setq current (nreverse (org-split-string current ":")))
14967 (cond
14968 ((eq onoff 'on)
14969 (setq res t)
14970 (or (member tag current) (push tag current)))
14971 ((eq onoff 'off)
14972 (or (not (member tag current)) (setq current (delete tag current))))
14973 (t (if (member tag current)
14974 (setq current (delete tag current))
14975 (setq res t)
14976 (push tag current))))
14977 (end-of-line 1)
14978 (if current
14979 (progn
14980 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14981 (org-set-tags nil t))
14982 (delete-horizontal-space))
14983 (run-hooks 'org-after-tags-change-hook))
14984 res))
14986 (defun org--align-tags-here (to-col)
14987 "Align tags on the current headline to TO-COL.
14988 Assume point is on a headline."
14989 (let ((pos (point)))
14990 (beginning-of-line)
14991 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14992 (>= pos (match-beginning 2)))
14993 ;; No tags or point within tags: do not align.
14994 (goto-char pos)
14995 (goto-char (match-beginning 1))
14996 (let ((shift (max (- (if (>= to-col 0) to-col
14997 (- (abs to-col) (string-width (match-string 2))))
14998 (current-column))
14999 1)))
15000 (replace-match (make-string shift ?\s) nil nil nil 1)
15001 ;; Preserve initial position, if possible. In any case, stop
15002 ;; before tags.
15003 (when (< pos (point)) (goto-char pos))))))
15005 (defun org-set-tags-command (&optional arg just-align)
15006 "Call the set-tags command for the current entry."
15007 (interactive "P")
15008 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
15009 (org-set-tags arg just-align)
15010 (save-excursion
15011 (unless (and (org-region-active-p)
15012 org-loop-over-headlines-in-active-region)
15013 (org-back-to-heading t))
15014 (org-set-tags arg just-align))))
15016 (defun org-set-tags-to (data)
15017 "Set the tags of the current entry to DATA, replacing the current tags.
15018 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
15019 If DATA is nil or the empty string, any tags will be removed."
15020 (interactive "sTags: ")
15021 (setq data
15022 (cond
15023 ((eq data nil) "")
15024 ((equal data "") "")
15025 ((stringp data)
15026 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
15027 ":"))
15028 ((listp data)
15029 (concat ":" (mapconcat 'identity data ":") ":"))))
15030 (when data
15031 (save-excursion
15032 (org-back-to-heading t)
15033 (when (looking-at org-complex-heading-regexp)
15034 (if (match-end 5)
15035 (progn
15036 (goto-char (match-beginning 5))
15037 (insert data)
15038 (delete-region (point) (point-at-eol))
15039 (org-set-tags nil 'align))
15040 (goto-char (point-at-eol))
15041 (insert " " data)
15042 (org-set-tags nil 'align)))
15043 (beginning-of-line 1)
15044 (when (looking-at ".*?\\([ \t]+\\)$")
15045 (delete-region (match-beginning 1) (match-end 1))))))
15047 (defun org-align-all-tags ()
15048 "Align the tags in all headings."
15049 (interactive)
15050 (save-excursion
15051 (or (ignore-errors (org-back-to-heading t))
15052 (outline-next-heading))
15053 (if (org-at-heading-p)
15054 (org-set-tags t)
15055 (message "No headings"))))
15057 (defvar org-indent-indentation-per-level)
15058 (defun org-set-tags (&optional arg just-align)
15059 "Set the tags for the current headline.
15060 With prefix ARG, realign all tags in headings in the current buffer.
15061 When JUST-ALIGN is non-nil, only align tags."
15062 (interactive "P")
15063 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15064 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15065 'region-start-level
15066 'region))
15067 org-loop-over-headlines-in-active-region)
15068 (org-map-entries
15069 ;; We don't use ARG and JUST-ALIGN here because these args
15070 ;; are not useful when looping over headlines.
15071 #'org-set-tags
15072 org-loop-over-headlines-in-active-region
15074 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15075 (let ((org-setting-tags t))
15076 (if arg
15077 (save-excursion
15078 (goto-char (point-min))
15079 (while (re-search-forward org-outline-regexp-bol nil t)
15080 (org-set-tags nil t)
15081 (end-of-line))
15082 (message "All tags realigned to column %d" org-tags-column))
15083 (let* ((current (org-get-tags-string))
15084 (tags
15085 (if just-align current
15086 ;; Get a new set of tags from the user.
15087 (save-excursion
15088 (let* ((seen)
15089 (table
15090 (setq
15091 org-last-tags-completion-table
15092 ;; Uniquify tags in alists, yet preserve
15093 ;; structure (i.e., keywords).
15094 (delq nil
15095 (mapcar
15096 (lambda (pair)
15097 (let ((head (car pair)))
15098 (cond ((symbolp head) pair)
15099 ((member head seen) nil)
15100 (t (push head seen)
15101 pair))))
15102 (append
15103 (or org-current-tag-alist
15104 (org-get-buffer-tags))
15105 (and
15106 org-complete-tags-always-offer-all-agenda-tags
15107 (org-global-tags-completion-table
15108 (org-agenda-files))))))))
15109 (current-tags (org-split-string current ":"))
15110 (inherited-tags
15111 (nreverse (nthcdr (length current-tags)
15112 (nreverse (org-get-tags-at))))))
15113 (replace-regexp-in-string
15114 "\\([-+&]+\\|,\\)"
15116 (if (or (eq t org-use-fast-tag-selection)
15117 (and org-use-fast-tag-selection
15118 (delq nil (mapcar #'cdr table))))
15119 (org-fast-tag-selection
15120 current-tags inherited-tags table
15121 (and org-fast-tag-selection-include-todo
15122 org-todo-key-alist))
15123 (let ((org-add-colon-after-tag-completion
15124 (< 1 (length table))))
15125 (org-trim
15126 (completing-read
15127 "Tags: "
15128 #'org-tags-completion-function
15129 nil nil current 'org-tags-history))))))))))
15131 (when org-tags-sort-function
15132 (setq tags
15133 (mapconcat
15134 #'identity
15135 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15136 org-tags-sort-function)
15137 ":")))
15139 (if (not (org-string-nw-p tags)) (setq tags "")
15140 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15141 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15143 ;; Insert new tags at the correct column.
15144 (unless (equal current tags)
15145 (save-excursion
15146 (beginning-of-line)
15147 (looking-at org-complex-heading-regexp)
15148 ;; Remove current tags, if any.
15149 (when (match-end 5) (replace-match "" nil nil nil 5))
15150 ;; Insert new tags, if any. Otherwise, remove trailing
15151 ;; white spaces.
15152 (end-of-line)
15153 (if (not (equal tags ""))
15154 (insert " " tags)
15155 (skip-chars-backward " \t")
15156 (delete-region (point) (line-end-position)))))
15157 ;; Align tags, if any. Fix tags column if `org-indent-mode'
15158 ;; is on.
15159 (unless (equal tags "")
15160 (let* ((level (save-excursion
15161 (beginning-of-line)
15162 (skip-chars-forward "\\*")))
15163 (offset (if (bound-and-true-p org-indent-mode)
15164 (* (1- org-indent-indentation-per-level)
15165 (1- level))
15167 (tags-column
15168 (+ org-tags-column
15169 (if (> org-tags-column 0) (- offset) offset))))
15170 (org--align-tags-here tags-column))))
15171 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15173 (defun org-change-tag-in-region (beg end tag off)
15174 "Add or remove TAG for each entry in the region.
15175 This works in the agenda, and also in an Org buffer."
15176 (interactive
15177 (list (region-beginning) (region-end)
15178 (let ((org-last-tags-completion-table
15179 (if (derived-mode-p 'org-mode)
15180 (org-uniquify
15181 (delq nil (append (org-get-buffer-tags)
15182 (org-global-tags-completion-table))))
15183 (org-global-tags-completion-table))))
15184 (completing-read
15185 "Tag: " 'org-tags-completion-function nil nil nil
15186 'org-tags-history))
15187 (progn
15188 (message "[s]et or [r]emove? ")
15189 (equal (read-char-exclusive) ?r))))
15190 (when (fboundp 'deactivate-mark) (deactivate-mark))
15191 (let ((agendap (equal major-mode 'org-agenda-mode))
15192 l1 l2 m buf pos newhead (cnt 0))
15193 (goto-char end)
15194 (setq l2 (1- (org-current-line)))
15195 (goto-char beg)
15196 (setq l1 (org-current-line))
15197 (cl-loop for l from l1 to l2 do
15198 (org-goto-line l)
15199 (setq m (get-text-property (point) 'org-hd-marker))
15200 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15201 (and agendap m))
15202 (setq buf (if agendap (marker-buffer m) (current-buffer))
15203 pos (if agendap m (point)))
15204 (with-current-buffer buf
15205 (save-excursion
15206 (save-restriction
15207 (goto-char pos)
15208 (setq cnt (1+ cnt))
15209 (org-toggle-tag tag (if off 'off 'on))
15210 (setq newhead (org-get-heading)))))
15211 (and agendap (org-agenda-change-all-lines newhead m))))
15212 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15214 (defun org-tags-completion-function (string _predicate &optional flag)
15215 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15216 (confirm (lambda (x) (stringp (car x)))))
15217 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15218 (setq s1 (match-string 1 string)
15219 s2 (match-string 2 string))
15220 (setq s1 "" s2 string))
15221 (cond
15222 ((eq flag nil)
15223 ;; try completion
15224 (setq rtn (try-completion s2 ctable confirm))
15225 (when (stringp rtn)
15226 (setq rtn
15227 (concat s1 s2 (substring rtn (length s2))
15228 (if (and org-add-colon-after-tag-completion
15229 (assoc rtn ctable))
15230 ":" ""))))
15231 rtn)
15232 ((eq flag t)
15233 ;; all-completions
15234 (all-completions s2 ctable confirm))
15235 ((eq flag 'lambda)
15236 ;; exact match?
15237 (assoc s2 ctable)))))
15239 (defun org-fast-tag-insert (kwd tags face &optional end)
15240 "Insert KDW, and the TAGS, the latter with face FACE.
15241 Also insert END."
15242 (insert (format "%-12s" (concat kwd ":"))
15243 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15244 (or end "")))
15246 (defun org-fast-tag-show-exit (flag)
15247 (save-excursion
15248 (org-goto-line 3)
15249 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15250 (replace-match ""))
15251 (when flag
15252 (end-of-line 1)
15253 (org-move-to-column (- (window-width) 19) t)
15254 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15256 (defun org-set-current-tags-overlay (current prefix)
15257 "Add an overlay to CURRENT tag with PREFIX."
15258 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15259 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15260 (org-overlay-display org-tags-overlay (concat prefix s))))
15262 (defvar org-last-tag-selection-key nil)
15263 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15264 "Fast tag selection with single keys.
15265 CURRENT is the current list of tags in the headline, INHERITED is the
15266 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15267 possibly with grouping information. TODO-TABLE is a similar table with
15268 TODO keywords, should these have keys assigned to them.
15269 If the keys are nil, a-z are automatically assigned.
15270 Returns the new tags string, or nil to not change the current settings."
15271 (let* ((fulltable (append table todo-table))
15272 (maxlen (apply 'max (mapcar
15273 (lambda (x)
15274 (if (stringp (car x)) (string-width (car x)) 0))
15275 fulltable)))
15276 (buf (current-buffer))
15277 (expert (eq org-fast-tag-selection-single-key 'expert))
15278 (buffer-tags nil)
15279 (fwidth (+ maxlen 3 1 3))
15280 (ncol (/ (- (window-width) 4) fwidth))
15281 (i-face 'org-done)
15282 (c-face 'org-todo)
15283 tg cnt e c char c1 c2 ntable tbl rtn
15284 ov-start ov-end ov-prefix
15285 (exit-after-next org-fast-tag-selection-single-key)
15286 (done-keywords org-done-keywords)
15287 groups ingroup intaggroup)
15288 (save-excursion
15289 (beginning-of-line 1)
15290 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15291 (setq ov-start (match-beginning 1)
15292 ov-end (match-end 1)
15293 ov-prefix "")
15294 (setq ov-start (1- (point-at-eol))
15295 ov-end (1+ ov-start))
15296 (skip-chars-forward "^\n\r")
15297 (setq ov-prefix
15298 (concat
15299 (buffer-substring (1- (point)) (point))
15300 (if (> (current-column) org-tags-column)
15302 (make-string (- org-tags-column (current-column)) ?\ ))))))
15303 (move-overlay org-tags-overlay ov-start ov-end)
15304 (save-window-excursion
15305 (if expert
15306 (set-buffer (get-buffer-create " *Org tags*"))
15307 (delete-other-windows)
15308 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15309 (org-switch-to-buffer-other-window " *Org tags*"))
15310 (erase-buffer)
15311 (setq-local org-done-keywords done-keywords)
15312 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15313 (org-fast-tag-insert "Current" current c-face "\n\n")
15314 (org-fast-tag-show-exit exit-after-next)
15315 (org-set-current-tags-overlay current ov-prefix)
15316 (setq tbl fulltable char ?a cnt 0)
15317 (while (setq e (pop tbl))
15318 (cond
15319 ((eq (car e) :startgroup)
15320 (push '() groups) (setq ingroup t)
15321 (unless (zerop cnt)
15322 (setq cnt 0)
15323 (insert "\n"))
15324 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15325 ((eq (car e) :endgroup)
15326 (setq ingroup nil cnt 0)
15327 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15328 ((eq (car e) :startgrouptag)
15329 (setq intaggroup t)
15330 (unless (zerop cnt)
15331 (setq cnt 0)
15332 (insert "\n"))
15333 (insert "[ "))
15334 ((eq (car e) :endgrouptag)
15335 (setq intaggroup nil cnt 0)
15336 (insert "]\n"))
15337 ((equal e '(:newline))
15338 (unless (zerop cnt)
15339 (setq cnt 0)
15340 (insert "\n")
15341 (setq e (car tbl))
15342 (while (equal (car tbl) '(:newline))
15343 (insert "\n")
15344 (setq tbl (cdr tbl)))))
15345 ((equal e '(:grouptags)) (insert " : "))
15347 (setq tg (copy-sequence (car e)) c2 nil)
15348 (if (cdr e)
15349 (setq c (cdr e))
15350 ;; automatically assign a character.
15351 (setq c1 (string-to-char
15352 (downcase (substring
15353 tg (if (= (string-to-char tg) ?@) 1 0)))))
15354 (if (or (rassoc c1 ntable) (rassoc c1 table))
15355 (while (or (rassoc char ntable) (rassoc char table))
15356 (setq char (1+ char)))
15357 (setq c2 c1))
15358 (setq c (or c2 char)))
15359 (when ingroup (push tg (car groups)))
15360 (setq tg (org-add-props tg nil 'face
15361 (cond
15362 ((not (assoc tg table))
15363 (org-get-todo-face tg))
15364 ((member tg current) c-face)
15365 ((member tg inherited) i-face))))
15366 (when (equal (caar tbl) :grouptags)
15367 (org-add-props tg nil 'face 'org-tag-group))
15368 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15369 (insert "[" c "] " tg (make-string
15370 (- fwidth 4 (length tg)) ?\ ))
15371 (push (cons tg c) ntable)
15372 (when (= (cl-incf cnt) ncol)
15373 (insert "\n")
15374 (when (or ingroup intaggroup) (insert " "))
15375 (setq cnt 0)))))
15376 (setq ntable (nreverse ntable))
15377 (insert "\n")
15378 (goto-char (point-min))
15379 (unless expert (org-fit-window-to-buffer))
15380 (setq rtn
15381 (catch 'exit
15382 (while t
15383 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15384 (if (not groups) "no " "")
15385 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15386 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15387 (setq org-last-tag-selection-key c)
15388 (cond
15389 ((= c ?\r) (throw 'exit t))
15390 ((= c ?!)
15391 (setq groups (not groups))
15392 (goto-char (point-min))
15393 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15394 ((= c ?\C-c)
15395 (if (not expert)
15396 (org-fast-tag-show-exit
15397 (setq exit-after-next (not exit-after-next)))
15398 (setq expert nil)
15399 (delete-other-windows)
15400 (set-window-buffer (split-window-vertically) " *Org tags*")
15401 (org-switch-to-buffer-other-window " *Org tags*")
15402 (org-fit-window-to-buffer)))
15403 ((or (= c ?\C-g)
15404 (and (= c ?q) (not (rassoc c ntable))))
15405 (delete-overlay org-tags-overlay)
15406 (setq quit-flag t))
15407 ((= c ?\ )
15408 (setq current nil)
15409 (when exit-after-next (setq exit-after-next 'now)))
15410 ((= c ?\t)
15411 (condition-case nil
15412 (setq tg (completing-read
15413 "Tag: "
15414 (or buffer-tags
15415 (with-current-buffer buf
15416 (setq buffer-tags
15417 (org-get-buffer-tags))))))
15418 (quit (setq tg "")))
15419 (when (string-match "\\S-" tg)
15420 (cl-pushnew (list tg) buffer-tags :test #'equal)
15421 (if (member tg current)
15422 (setq current (delete tg current))
15423 (push tg current)))
15424 (when exit-after-next (setq exit-after-next 'now)))
15425 ((setq e (rassoc c todo-table) tg (car e))
15426 (with-current-buffer buf
15427 (save-excursion (org-todo tg)))
15428 (when exit-after-next (setq exit-after-next 'now)))
15429 ((setq e (rassoc c ntable) tg (car e))
15430 (if (member tg current)
15431 (setq current (delete tg current))
15432 (cl-loop for g in groups do
15433 (when (member tg g)
15434 (dolist (x g) (setq current (delete x current)))))
15435 (push tg current))
15436 (when exit-after-next (setq exit-after-next 'now))))
15438 ;; Create a sorted list
15439 (setq current
15440 (sort current
15441 (lambda (a b)
15442 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15443 (when (eq exit-after-next 'now) (throw 'exit t))
15444 (goto-char (point-min))
15445 (beginning-of-line 2)
15446 (delete-region (point) (point-at-eol))
15447 (org-fast-tag-insert "Current" current c-face)
15448 (org-set-current-tags-overlay current ov-prefix)
15449 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15450 (setq tg (match-string 1))
15451 (add-text-properties
15452 (match-beginning 1) (match-end 1)
15453 (list 'face
15454 (cond
15455 ((member tg current) c-face)
15456 ((member tg inherited) i-face)
15457 (t (get-text-property (match-beginning 1) 'face))))))
15458 (goto-char (point-min)))))
15459 (delete-overlay org-tags-overlay)
15460 (if rtn
15461 (mapconcat 'identity current ":")
15462 nil))))
15464 (defun org-get-tags-string ()
15465 "Get the TAGS string in the current headline."
15466 (unless (org-at-heading-p t)
15467 (user-error "Not on a heading"))
15468 (save-excursion
15469 (beginning-of-line 1)
15470 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15471 (match-string-no-properties 1)
15472 "")))
15474 (defun org-get-tags ()
15475 "Get the list of tags specified in the current headline."
15476 (org-split-string (org-get-tags-string) ":"))
15478 (defun org-get-buffer-tags ()
15479 "Get a table of all tags used in the buffer, for completion."
15480 (org-with-wide-buffer
15481 (goto-char (point-min))
15482 (let ((tag-re (concat org-outline-regexp-bol
15483 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15484 tags)
15485 (while (re-search-forward tag-re nil t)
15486 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15487 (push tag tags)))
15488 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15490 ;;;; The mapping API
15492 (defvar org-agenda-skip-comment-trees)
15493 (defvar org-agenda-skip-function)
15494 (defun org-map-entries (func &optional match scope &rest skip)
15495 "Call FUNC at each headline selected by MATCH in SCOPE.
15497 FUNC is a function or a lisp form. The function will be called without
15498 arguments, with the cursor positioned at the beginning of the headline.
15499 The return values of all calls to the function will be collected and
15500 returned as a list.
15502 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15503 does not need to preserve point. After evaluation, the cursor will be
15504 moved to the end of the line (presumably of the headline of the
15505 processed entry) and search continues from there. Under some
15506 circumstances, this may not produce the wanted results. For example,
15507 if you have removed (e.g. archived) the current (sub)tree it could
15508 mean that the next entry will be skipped entirely. In such cases, you
15509 can specify the position from where search should continue by making
15510 FUNC set the variable `org-map-continue-from' to the desired buffer
15511 position.
15513 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15514 Only headlines that are matched by this query will be considered during
15515 the iteration. When MATCH is nil or t, all headlines will be
15516 visited by the iteration.
15518 SCOPE determines the scope of this command. It can be any of:
15520 nil The current buffer, respecting the restriction if any
15521 tree The subtree started with the entry at point
15522 region The entries within the active region, if any
15523 region-start-level
15524 The entries within the active region, but only those at
15525 the same level than the first one.
15526 file The current buffer, without restriction
15527 file-with-archives
15528 The current buffer, and any archives associated with it
15529 agenda All agenda files
15530 agenda-with-archives
15531 All agenda files with any archive files associated with them
15532 \(file1 file2 ...)
15533 If this is a list, all files in the list will be scanned
15535 The remaining args are treated as settings for the skipping facilities of
15536 the scanner. The following items can be given here:
15538 archive skip trees with the archive tag
15539 comment skip trees with the COMMENT keyword
15540 function or Emacs Lisp form:
15541 will be used as value for `org-agenda-skip-function', so
15542 whenever the function returns a position, FUNC will not be
15543 called for that entry and search will continue from the
15544 position returned
15546 If your function needs to retrieve the tags including inherited tags
15547 at the *current* entry, you can use the value of the variable
15548 `org-scanner-tags' which will be much faster than getting the value
15549 with `org-get-tags-at'. If your function gets properties with
15550 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15551 to t around the call to `org-entry-properties' to get the same speedup.
15552 Note that if your function moves around to retrieve tags and properties at
15553 a *different* entry, you cannot use these techniques."
15554 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15555 (not (org-region-active-p)))
15556 (let* ((org-agenda-archives-mode nil) ; just to make sure
15557 (org-agenda-skip-archived-trees (memq 'archive skip))
15558 (org-agenda-skip-comment-trees (memq 'comment skip))
15559 (org-agenda-skip-function
15560 (car (org-delete-all '(comment archive) skip)))
15561 (org-tags-match-list-sublevels t)
15562 (start-level (eq scope 'region-start-level))
15563 matcher res
15564 org-todo-keywords-for-agenda
15565 org-done-keywords-for-agenda
15566 org-todo-keyword-alist-for-agenda
15567 org-tag-alist-for-agenda
15568 org--matcher-tags-todo-only)
15570 (cond
15571 ((eq match t) (setq matcher t))
15572 ((eq match nil) (setq matcher t))
15573 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15575 (save-excursion
15576 (save-restriction
15577 (cond ((eq scope 'tree)
15578 (org-back-to-heading t)
15579 (org-narrow-to-subtree)
15580 (setq scope nil))
15581 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15582 (org-region-active-p))
15583 ;; If needed, set start-level to a string like "2"
15584 (when start-level
15585 (save-excursion
15586 (goto-char (region-beginning))
15587 (unless (org-at-heading-p) (outline-next-heading))
15588 (setq start-level (org-current-level))))
15589 (narrow-to-region (region-beginning)
15590 (save-excursion
15591 (goto-char (region-end))
15592 (unless (and (bolp) (org-at-heading-p))
15593 (outline-next-heading))
15594 (point)))
15595 (setq scope nil)))
15597 (if (not scope)
15598 (progn
15599 (org-agenda-prepare-buffers
15600 (and buffer-file-name (list buffer-file-name)))
15601 (setq res
15602 (org-scan-tags
15603 func matcher org--matcher-tags-todo-only start-level)))
15604 ;; Get the right scope
15605 (cond
15606 ((and scope (listp scope) (symbolp (car scope)))
15607 (setq scope (eval scope)))
15608 ((eq scope 'agenda)
15609 (setq scope (org-agenda-files t)))
15610 ((eq scope 'agenda-with-archives)
15611 (setq scope (org-agenda-files t))
15612 (setq scope (org-add-archive-files scope)))
15613 ((eq scope 'file)
15614 (setq scope (and buffer-file-name (list buffer-file-name))))
15615 ((eq scope 'file-with-archives)
15616 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15617 (org-agenda-prepare-buffers scope)
15618 (dolist (file scope)
15619 (with-current-buffer (org-find-base-buffer-visiting file)
15620 (org-with-wide-buffer
15621 (goto-char (point-min))
15622 (setq res
15623 (append
15625 (org-scan-tags
15626 func matcher org--matcher-tags-todo-only)))))))))
15627 res)))
15629 ;;; Properties API
15631 (defconst org-special-properties
15632 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15633 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15634 "The special properties valid in Org mode.
15635 These are properties that are not defined in the property drawer,
15636 but in some other way.")
15638 (defconst org-default-properties
15639 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15640 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15641 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15642 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15643 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15644 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15645 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15646 "Some properties that are used by Org mode for various purposes.
15647 Being in this list makes sure that they are offered for completion.")
15649 (defun org--valid-property-p (property)
15650 "Non nil when string PROPERTY is a valid property name."
15651 (not
15652 (or (equal property "")
15653 (string-match-p "\\s-" property))))
15655 (defun org--update-property-plist (key val props)
15656 "Associate KEY to VAL in alist PROPS.
15657 Modifications are made by side-effect. Return new alist."
15658 (let* ((appending (string= (substring key -1) "+"))
15659 (key (if appending (substring key 0 -1) key))
15660 (old (assoc-string key props t)))
15661 (if (not old) (cons (cons key val) props)
15662 (setcdr old (if appending (concat (cdr old) " " val) val))
15663 props)))
15665 (defun org-get-property-block (&optional beg force)
15666 "Return the (beg . end) range of the body of the property drawer.
15667 BEG is the beginning of the current subtree, or of the part
15668 before the first headline. If it is not given, it will be found.
15669 If the drawer does not exist, create it if FORCE is non-nil, or
15670 return nil."
15671 (org-with-wide-buffer
15672 (when beg (goto-char beg))
15673 (unless (org-before-first-heading-p)
15674 (let ((beg (cond (beg)
15675 ((or (not (featurep 'org-inlinetask))
15676 (org-inlinetask-in-task-p))
15677 (org-back-to-heading t))
15678 (t (org-with-limited-levels (org-back-to-heading t))))))
15679 (forward-line)
15680 (when (looking-at-p org-planning-line-re) (forward-line))
15681 (cond ((looking-at org-property-drawer-re)
15682 (forward-line)
15683 (cons (point) (progn (goto-char (match-end 0))
15684 (line-beginning-position))))
15685 (force
15686 (goto-char beg)
15687 (org-insert-property-drawer)
15688 (let ((pos (save-excursion (search-forward ":END:")
15689 (line-beginning-position))))
15690 (cons pos pos))))))))
15692 (defun org-at-property-p ()
15693 "Non-nil when point is inside a property drawer.
15694 See `org-property-re' for match data, if applicable."
15695 (save-excursion
15696 (beginning-of-line)
15697 (and (looking-at org-property-re)
15698 (let ((property-drawer (save-match-data (org-get-property-block))))
15699 (and property-drawer
15700 (>= (point) (car property-drawer))
15701 (< (point) (cdr property-drawer)))))))
15703 (defun org-property-action ()
15704 "Do an action on properties."
15705 (interactive)
15706 (unless (org-at-property-p) (user-error "Not at a property"))
15707 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15708 (let ((c (read-char-exclusive)))
15709 (cl-case c
15710 (?s (call-interactively #'org-set-property))
15711 (?d (call-interactively #'org-delete-property))
15712 (?D (call-interactively #'org-delete-property-globally))
15713 (?c (call-interactively #'org-compute-property-at-point))
15714 (otherwise (user-error "No such property action %c" c)))))
15716 (defun org-inc-effort ()
15717 "Increment the value of the effort property in the current entry."
15718 (interactive)
15719 (org-set-effort nil t))
15721 (defvar org-clock-effort) ; Defined in org-clock.el.
15722 (defvar org-clock-current-task) ; Defined in org-clock.el.
15723 (defun org-set-effort (&optional value increment)
15724 "Set the effort property of the current entry.
15725 With numerical prefix arg, use the nth allowed value, 0 stands for the
15726 10th allowed value.
15728 When INCREMENT is non-nil, set the property to the next allowed value."
15729 (interactive "P")
15730 (when (equal value 0) (setq value 10))
15731 (let* ((completion-ignore-case t)
15732 (prop org-effort-property)
15733 (cur (org-entry-get nil prop))
15734 (allowed (org-property-get-allowed-values nil prop 'table))
15735 (existing (mapcar 'list (org-property-values prop)))
15736 (heading (nth 4 (org-heading-components)))
15738 (val (cond
15739 ((stringp value) value)
15740 ((and allowed (integerp value))
15741 (or (car (nth (1- value) allowed))
15742 (car (org-last allowed))))
15743 ((and allowed increment)
15744 (or (cl-caadr (member (list cur) allowed))
15745 (user-error "Allowed effort values are not set")))
15746 (allowed
15747 (message "Select 1-9,0, [RET%s]: %s"
15748 (if cur (concat "=" cur) "")
15749 (mapconcat 'car allowed " "))
15750 (setq rpl (read-char-exclusive))
15751 (if (equal rpl ?\r)
15753 (setq rpl (- rpl ?0))
15754 (when (equal rpl 0) (setq rpl 10))
15755 (if (and (> rpl 0) (<= rpl (length allowed)))
15756 (car (nth (1- rpl) allowed))
15757 (org-completing-read "Effort: " allowed nil))))
15759 (org-completing-read
15760 (concat "Effort" (and cur (string-match "\\S-" cur)
15761 (concat " [" cur "]"))
15762 ": ")
15763 existing nil nil "" nil cur)))))
15764 (unless (equal (org-entry-get nil prop) val)
15765 (org-entry-put nil prop val))
15766 (org-refresh-property
15767 '((effort . identity)
15768 (effort-minutes . org-duration-string-to-minutes))
15769 val)
15770 (when (equal heading (bound-and-true-p org-clock-current-task))
15771 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15772 (org-clock-update-mode-line))
15773 (message "%s is now %s" prop val)))
15775 (defun org-entry-properties (&optional pom which)
15776 "Get all properties of the current entry.
15778 When POM is a buffer position, get all properties from the entry
15779 there instead.
15781 This includes the TODO keyword, the tags, time strings for
15782 deadline, scheduled, and clocking, and any additional properties
15783 defined in the entry.
15785 If WHICH is nil or `all', get all properties. If WHICH is
15786 `special' or `standard', only get that subclass. If WHICH is
15787 a string, only get that property.
15789 Return value is an alist. Keys are properties, as upcased
15790 strings."
15791 (org-with-point-at pom
15792 (when (and (derived-mode-p 'org-mode)
15793 (ignore-errors (org-back-to-heading t)))
15794 (catch 'exit
15795 (let* ((beg (point))
15796 (specific (and (stringp which) (upcase which)))
15797 (which (cond ((not specific) which)
15798 ((member specific org-special-properties) 'special)
15799 (t 'standard)))
15800 props)
15801 ;; Get the special properties, like TODO and TAGS.
15802 (when (memq which '(nil all special))
15803 (when (or (not specific) (string= specific "CLOCKSUM"))
15804 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15805 (when clocksum
15806 (push (cons "CLOCKSUM"
15807 (org-minutes-to-clocksum-string clocksum))
15808 props)))
15809 (when specific (throw 'exit props)))
15810 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15811 (let ((clocksumt (get-text-property (point)
15812 :org-clock-minutes-today)))
15813 (when clocksumt
15814 (push (cons "CLOCKSUM_T"
15815 (org-minutes-to-clocksum-string clocksumt))
15816 props)))
15817 (when specific (throw 'exit props)))
15818 (when (or (not specific) (string= specific "ITEM"))
15819 (when (looking-at org-complex-heading-regexp)
15820 (push (cons "ITEM"
15821 (let ((title (match-string-no-properties 4)))
15822 (if (org-string-nw-p title)
15823 (org-remove-tabs title)
15824 "")))
15825 props))
15826 (when specific (throw 'exit props)))
15827 (when (or (not specific) (string= specific "TODO"))
15828 (let ((case-fold-search nil))
15829 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15830 (push (cons "TODO" (match-string-no-properties 2)) props)))
15831 (when specific (throw 'exit props)))
15832 (when (or (not specific) (string= specific "PRIORITY"))
15833 (push (cons "PRIORITY"
15834 (if (looking-at org-priority-regexp)
15835 (match-string-no-properties 2)
15836 (char-to-string org-default-priority)))
15837 props)
15838 (when specific (throw 'exit props)))
15839 (when (or (not specific) (string= specific "FILE"))
15840 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15841 props)
15842 (when specific (throw 'exit props)))
15843 (when (or (not specific) (string= specific "TAGS"))
15844 (let ((value (org-string-nw-p (org-get-tags-string))))
15845 (when value (push (cons "TAGS" value) props)))
15846 (when specific (throw 'exit props)))
15847 (when (or (not specific) (string= specific "ALLTAGS"))
15848 (let ((value (org-get-tags-at)))
15849 (when value
15850 (push (cons "ALLTAGS"
15851 (format ":%s:" (mapconcat #'identity value ":")))
15852 props)))
15853 (when specific (throw 'exit props)))
15854 (when (or (not specific) (string= specific "BLOCKED"))
15855 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15856 (when specific (throw 'exit props)))
15857 (when (or (not specific)
15858 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15859 (forward-line)
15860 (when (looking-at-p org-planning-line-re)
15861 (end-of-line)
15862 (let ((bol (line-beginning-position))
15863 ;; Backward compatibility: time keywords used to
15864 ;; be configurable (before 8.3). Make sure we
15865 ;; get the correct keyword.
15866 (key-assoc `(("CLOSED" . ,org-closed-string)
15867 ("DEADLINE" . ,org-deadline-string)
15868 ("SCHEDULED" . ,org-scheduled-string))))
15869 (dolist (pair (if specific (list (assoc specific key-assoc))
15870 key-assoc))
15871 (save-excursion
15872 (when (search-backward (cdr pair) bol t)
15873 (goto-char (match-end 0))
15874 (skip-chars-forward " \t")
15875 (and (looking-at org-ts-regexp-both)
15876 (push (cons (car pair)
15877 (match-string-no-properties 0))
15878 props)))))))
15879 (when specific (throw 'exit props)))
15880 (when (or (not specific)
15881 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15882 (let ((find-ts
15883 (lambda (end ts)
15884 ;; Fix next time-stamp before END. TS is the
15885 ;; list of time-stamps found so far.
15886 (let ((ts ts)
15887 (regexp (cond
15888 ((string= specific "TIMESTAMP")
15889 org-ts-regexp)
15890 ((string= specific "TIMESTAMP_IA")
15891 org-ts-regexp-inactive)
15892 ((assoc "TIMESTAMP_IA" ts)
15893 org-ts-regexp)
15894 ((assoc "TIMESTAMP" ts)
15895 org-ts-regexp-inactive)
15896 (t org-ts-regexp-both))))
15897 (catch 'next
15898 (while (re-search-forward regexp end t)
15899 (backward-char)
15900 (let ((object (org-element-context)))
15901 ;; Accept to match timestamps in node
15902 ;; properties, too.
15903 (when (memq (org-element-type object)
15904 '(node-property timestamp))
15905 (let ((type
15906 (org-element-property :type object)))
15907 (cond
15908 ((and (memq type '(active active-range))
15909 (not (equal specific "TIMESTAMP_IA")))
15910 (unless (assoc "TIMESTAMP" ts)
15911 (push (cons "TIMESTAMP"
15912 (org-element-property
15913 :raw-value object))
15915 (when specific (throw 'exit ts))))
15916 ((and (memq type '(inactive inactive-range))
15917 (not (string= specific "TIMESTAMP")))
15918 (unless (assoc "TIMESTAMP_IA" ts)
15919 (push (cons "TIMESTAMP_IA"
15920 (org-element-property
15921 :raw-value object))
15923 (when specific (throw 'exit ts))))))
15924 ;; Both timestamp types are found,
15925 ;; move to next part.
15926 (when (= (length ts) 2) (throw 'next ts)))))
15927 ts)))))
15928 (goto-char beg)
15929 ;; First look for timestamps within headline.
15930 (let ((ts (funcall find-ts (line-end-position) nil)))
15931 (if (= (length ts) 2) (setq props (nconc ts props))
15932 (forward-line)
15933 ;; Then find timestamps in the section, skipping
15934 ;; planning line.
15935 (when (looking-at-p org-planning-line-re)
15936 (forward-line))
15937 (let ((end (save-excursion (outline-next-heading))))
15938 (setq props (nconc (funcall find-ts end ts) props))))))))
15939 ;; Get the standard properties, like :PROP:.
15940 (when (memq which '(nil all standard))
15941 ;; If we are looking after a specific property, delegate
15942 ;; to `org-entry-get', which is faster. However, make an
15943 ;; exception for "CATEGORY", since it can be also set
15944 ;; through keywords (i.e. #+CATEGORY).
15945 (if (and specific (not (equal specific "CATEGORY")))
15946 (let ((value (org-entry-get beg specific nil t)))
15947 (throw 'exit (and value (list (cons specific value)))))
15948 (let ((range (org-get-property-block beg)))
15949 (when range
15950 (let ((end (cdr range)) seen-base)
15951 (goto-char (car range))
15952 ;; Unlike to `org--update-property-plist', we
15953 ;; handle the case where base values is found
15954 ;; after its extension. We also forbid standard
15955 ;; properties to be named as special properties.
15956 (while (re-search-forward org-property-re end t)
15957 (let* ((key (upcase (match-string-no-properties 2)))
15958 (extendp (string-match-p "\\+\\'" key))
15959 (key-base (if extendp (substring key 0 -1) key))
15960 (value (match-string-no-properties 3)))
15961 (cond
15962 ((member-ignore-case key-base org-special-properties))
15963 (extendp
15964 (setq props
15965 (org--update-property-plist key value props)))
15966 ((member key seen-base))
15967 (t (push key seen-base)
15968 (let ((p (assoc-string key props t)))
15969 (if p (setcdr p (concat value " " (cdr p)))
15970 (push (cons key value) props))))))))))))
15971 (unless (assoc "CATEGORY" props)
15972 (push (cons "CATEGORY" (org-get-category beg)) props)
15973 (when (string= specific "CATEGORY") (throw 'exit props)))
15974 ;; Return value.
15975 props)))))
15977 (defun org-property--local-values (property literal-nil)
15978 "Return value for PROPERTY in current entry.
15979 Value is a list whose car is the base value for PROPERTY and cdr
15980 a list of accumulated values. Return nil if neither is found in
15981 the entry. Also return nil when PROPERTY is set to \"nil\",
15982 unless LITERAL-NIL is non-nil."
15983 (let ((range (org-get-property-block)))
15984 (when range
15985 (goto-char (car range))
15986 (let* ((case-fold-search t)
15987 (end (cdr range))
15988 (value
15989 ;; Base value.
15990 (save-excursion
15991 (let ((v (and (re-search-forward
15992 (org-re-property property nil t) end t)
15993 (match-string-no-properties 3))))
15994 (list (if literal-nil v (org-not-nil v)))))))
15995 ;; Find additional values.
15996 (let* ((property+ (org-re-property (concat property "+") nil t)))
15997 (while (re-search-forward property+ end t)
15998 (push (match-string-no-properties 3) value)))
15999 ;; Return final values.
16000 (and (not (equal value '(nil))) (nreverse value))))))
16002 (defun org-entry-get (pom property &optional inherit literal-nil)
16003 "Get value of PROPERTY for entry or content at point-or-marker POM.
16005 If INHERIT is non-nil and the entry does not have the property,
16006 then also check higher levels of the hierarchy. If INHERIT is
16007 the symbol `selective', use inheritance only if the setting in
16008 `org-use-property-inheritance' selects PROPERTY for inheritance.
16010 If the property is present but empty, the return value is the
16011 empty string. If the property is not present at all, nil is
16012 returned. In any other case, return the value as a string.
16013 Search is case-insensitive.
16015 If LITERAL-NIL is set, return the string value \"nil\" as
16016 a string, do not interpret it as the list atom nil. This is used
16017 for inheritance when a \"nil\" value can supersede a non-nil
16018 value higher up the hierarchy."
16019 (org-with-point-at pom
16020 (cond
16021 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
16022 ;; We need a special property. Use `org-entry-properties' to
16023 ;; retrieve it, but specify the wanted property.
16024 (cdr (assoc-string property (org-entry-properties nil property))))
16025 ((and inherit
16026 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
16027 (org-entry-get-with-inheritance property literal-nil))
16029 (let* ((local (org-property--local-values property literal-nil))
16030 (value (and local (mapconcat #'identity (delq nil local) " "))))
16031 (if literal-nil value (org-not-nil value)))))))
16033 (defun org-property-or-variable-value (var &optional inherit)
16034 "Check if there is a property fixing the value of VAR.
16035 If yes, return this value. If not, return the current value of the variable."
16036 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16037 (if (and prop (stringp prop) (string-match "\\S-" prop))
16038 (read prop)
16039 (symbol-value var))))
16041 (defun org-entry-delete (pom property)
16042 "Delete PROPERTY from entry at point-or-marker POM.
16043 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16044 non-nil when a property was removed."
16045 (unless (member property org-special-properties)
16046 (org-with-point-at pom
16047 (let ((range (org-get-property-block)))
16048 (when range
16049 (let* ((begin (car range))
16050 (origin (cdr range))
16051 (end (copy-marker origin))
16052 (re (org-re-property
16053 (concat (regexp-quote property) "\\+?") t t)))
16054 (goto-char begin)
16055 (while (re-search-forward re end t)
16056 (delete-region (match-beginning 0) (line-beginning-position 2)))
16057 ;; If drawer is empty, remove it altogether.
16058 (when (= begin end)
16059 (delete-region (line-beginning-position 0)
16060 (line-beginning-position 2)))
16061 ;; Return non-nil if some property was removed.
16062 (prog1 (/= end origin) (set-marker end nil))))))))
16064 ;; Multi-values properties are properties that contain multiple values
16065 ;; These values are assumed to be single words, separated by whitespace.
16066 (defun org-entry-add-to-multivalued-property (pom property value)
16067 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16068 (let* ((old (org-entry-get pom property))
16069 (values (and old (org-split-string old "[ \t]"))))
16070 (setq value (org-entry-protect-space value))
16071 (unless (member value values)
16072 (setq values (append values (list value)))
16073 (org-entry-put pom property
16074 (mapconcat 'identity values " ")))))
16076 (defun org-entry-remove-from-multivalued-property (pom property value)
16077 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16078 (let* ((old (org-entry-get pom property))
16079 (values (and old (org-split-string old "[ \t]"))))
16080 (setq value (org-entry-protect-space value))
16081 (when (member value values)
16082 (setq values (delete value values))
16083 (org-entry-put pom property
16084 (mapconcat 'identity values " ")))))
16086 (defun org-entry-member-in-multivalued-property (pom property value)
16087 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16088 (let* ((old (org-entry-get pom property))
16089 (values (and old (org-split-string old "[ \t]"))))
16090 (setq value (org-entry-protect-space value))
16091 (member value values)))
16093 (defun org-entry-get-multivalued-property (pom property)
16094 "Return a list of values in a multivalued property."
16095 (let* ((value (org-entry-get pom property))
16096 (values (and value (org-split-string value "[ \t]"))))
16097 (mapcar 'org-entry-restore-space values)))
16099 (defun org-entry-put-multivalued-property (pom property &rest values)
16100 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16101 VALUES should be a list of strings. Spaces will be protected."
16102 (org-entry-put pom property
16103 (mapconcat 'org-entry-protect-space values " "))
16104 (let* ((value (org-entry-get pom property))
16105 (values (and value (org-split-string value "[ \t]"))))
16106 (mapcar 'org-entry-restore-space values)))
16108 (defun org-entry-protect-space (s)
16109 "Protect spaces and newline in string S."
16110 (while (string-match " " s)
16111 (setq s (replace-match "%20" t t s)))
16112 (while (string-match "\n" s)
16113 (setq s (replace-match "%0A" t t s)))
16116 (defun org-entry-restore-space (s)
16117 "Restore spaces and newline in string S."
16118 (while (string-match "%20" s)
16119 (setq s (replace-match " " t t s)))
16120 (while (string-match "%0A" s)
16121 (setq s (replace-match "\n" t t s)))
16124 (defvar org-entry-property-inherited-from (make-marker)
16125 "Marker pointing to the entry from where a property was inherited.
16126 Each call to `org-entry-get-with-inheritance' will set this marker to the
16127 location of the entry where the inheritance search matched. If there was
16128 no match, the marker will point nowhere.
16129 Note that also `org-entry-get' calls this function, if the INHERIT flag
16130 is set.")
16132 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16133 "Get PROPERTY of entry or content at point, search higher levels if needed.
16134 The search will stop at the first ancestor which has the property defined.
16135 If the value found is \"nil\", return nil to show that the property
16136 should be considered as undefined (this is the meaning of nil here).
16137 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16138 (move-marker org-entry-property-inherited-from nil)
16139 (org-with-wide-buffer
16140 (let (value)
16141 (catch 'exit
16142 (while t
16143 (let ((v (org-property--local-values property literal-nil)))
16144 (when v
16145 (setq value
16146 (concat (mapconcat #'identity (delq nil v) " ")
16147 (and value " ")
16148 value)))
16149 (cond
16150 ((car v)
16151 (org-back-to-heading t)
16152 (move-marker org-entry-property-inherited-from (point))
16153 (throw 'exit nil))
16154 ((org-up-heading-safe))
16156 (let ((global
16157 (cdr (or (assoc-string property org-file-properties t)
16158 (assoc-string property org-global-properties t)
16159 (assoc-string property org-global-properties-fixed t)))))
16160 (cond ((not global))
16161 (value (setq value (concat global " " value)))
16162 (t (setq value global))))
16163 (throw 'exit nil))))))
16164 (if literal-nil value (org-not-nil value)))))
16166 (defvar org-property-changed-functions nil
16167 "Hook called when the value of a property has changed.
16168 Each hook function should accept two arguments, the name of the property
16169 and the new value.")
16171 (defun org-entry-put (pom property value)
16172 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16174 If the value is nil, it is converted to the empty string. If it
16175 is not a string, an error is raised. Also raise an error on
16176 invalid property names.
16178 PROPERTY can be any regular property (see
16179 `org-special-properties'). It can also be \"TODO\",
16180 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16182 For the last two properties, VALUE may have any of the special
16183 values \"earlier\" and \"later\". The function then increases or
16184 decreases scheduled or deadline date by one day."
16185 (cond ((null value) (setq value ""))
16186 ((not (stringp value)) (error "Properties values should be strings"))
16187 ((not (org--valid-property-p property))
16188 (user-error "Invalid property name: \"%s\"" property)))
16189 (org-with-point-at pom
16190 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16191 (org-back-to-heading t)
16192 (org-with-limited-levels (org-back-to-heading t)))
16193 (let ((beg (point)))
16194 (cond
16195 ((equal property "TODO")
16196 (cond ((not (org-string-nw-p value)) (setq value 'none))
16197 ((not (member value org-todo-keywords-1))
16198 (user-error "\"%s\" is not a valid TODO state" value)))
16199 (org-todo value)
16200 (org-set-tags nil 'align))
16201 ((equal property "PRIORITY")
16202 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16203 (org-set-tags nil 'align))
16204 ((equal property "SCHEDULED")
16205 (forward-line)
16206 (if (and (looking-at-p org-planning-line-re)
16207 (re-search-forward
16208 org-scheduled-time-regexp (line-end-position) t))
16209 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16210 ((string= value "later") (org-timestamp-change 1 'day))
16211 ((string= value "") (org-schedule '(4)))
16212 (t (org-schedule nil value)))
16213 (if (member value '("earlier" "later" ""))
16214 (call-interactively #'org-schedule)
16215 (org-schedule nil value))))
16216 ((equal property "DEADLINE")
16217 (forward-line)
16218 (if (and (looking-at-p org-planning-line-re)
16219 (re-search-forward
16220 org-deadline-time-regexp (line-end-position) t))
16221 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16222 ((string= value "later") (org-timestamp-change 1 'day))
16223 ((string= value "") (org-deadline '(4)))
16224 (t (org-deadline nil value)))
16225 (if (member value '("earlier" "later" ""))
16226 (call-interactively #'org-deadline)
16227 (org-deadline nil value))))
16228 ((member property org-special-properties)
16229 (error "The %s property cannot be set with `org-entry-put'" property))
16231 (let* ((range (org-get-property-block beg 'force))
16232 (end (cdr range))
16233 (case-fold-search t))
16234 (goto-char (car range))
16235 (if (re-search-forward (org-re-property property nil t) end t)
16236 (progn (delete-region (match-beginning 0) (match-end 0))
16237 (goto-char (match-beginning 0)))
16238 (goto-char end)
16239 (insert "\n")
16240 (backward-char))
16241 (insert ":" property ":")
16242 (when value (insert " " value))
16243 (org-indent-line)))))
16244 (run-hook-with-args 'org-property-changed-functions property value)))
16246 (defun org-buffer-property-keys
16247 (&optional specials defaults columns ignore-malformed)
16248 "Get all property keys in the current buffer.
16250 When SPECIALS is non-nil, also list the special properties that
16251 reflect things like tags and TODO state.
16253 When DEFAULTS is non-nil, also include properties that has
16254 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16255 DESCRIPTION, LOCATION, and LOGGING and others.
16257 When COLUMNS in non-nil, also include property names given in
16258 COLUMN formats in the current buffer.
16260 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16261 automatically performed, such drawers will be silently ignored."
16262 (let ((case-fold-search t)
16263 (props (append
16264 (and specials org-special-properties)
16265 (and defaults (cons org-effort-property org-default-properties))
16266 nil)))
16267 (org-with-wide-buffer
16268 (goto-char (point-min))
16269 (while (re-search-forward org-property-start-re nil t)
16270 (let ((range (org-get-property-block)))
16271 (catch 'skip
16272 (unless range
16273 (when (and (not ignore-malformed)
16274 (not (org-before-first-heading-p))
16275 (y-or-n-p (format "Malformed drawer at %d, repair?"
16276 (line-beginning-position))))
16277 (org-get-property-block nil t))
16278 (throw 'skip nil))
16279 (goto-char (car range))
16280 (let ((begin (car range))
16281 (end (cdr range)))
16282 ;; Make sure that found property block is not located
16283 ;; before current point, as it would generate an infloop.
16284 ;; It can happen, for example, in the following
16285 ;; situation:
16287 ;; * Headline
16288 ;; :PROPERTIES:
16289 ;; ...
16290 ;; :END:
16291 ;; *************** Inlinetask
16292 ;; #+BEGIN_EXAMPLE
16293 ;; :PROPERTIES:
16294 ;; #+END_EXAMPLE
16296 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16297 (while (< (point) end)
16298 (let ((p (progn (looking-at org-property-re)
16299 (match-string-no-properties 2))))
16300 ;; Only add true property name, not extension symbol.
16301 (push (if (not (string-match-p "\\+\\'" p)) p
16302 (substring p 0 -1))
16303 props))
16304 (forward-line))))
16305 (outline-next-heading)))
16306 (when columns
16307 (goto-char (point-min))
16308 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16309 (let ((element (org-element-at-point)))
16310 (when (memq (org-element-type element) '(keyword node-property))
16311 (let ((value (org-element-property :value element))
16312 (start 0))
16313 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16314 (setq start (match-end 0))
16315 (let ((p (match-string-no-properties 1 value)))
16316 (unless (member-ignore-case p org-special-properties)
16317 (push p props))))))))))
16318 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16320 (defun org-property-values (key)
16321 "List all non-nil values of property KEY in current buffer."
16322 (org-with-wide-buffer
16323 (goto-char (point-min))
16324 (let ((case-fold-search t)
16325 (re (org-re-property key))
16326 values)
16327 (while (re-search-forward re nil t)
16328 (push (org-entry-get (point) key) values))
16329 (delete-dups values))))
16331 (defun org-insert-property-drawer ()
16332 "Insert a property drawer into the current entry."
16333 (org-with-wide-buffer
16334 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16335 (org-back-to-heading t)
16336 (org-with-limited-levels (org-back-to-heading t)))
16337 (forward-line)
16338 (when (looking-at-p org-planning-line-re) (forward-line))
16339 (unless (looking-at-p org-property-drawer-re)
16340 ;; Make sure we start editing a line from current entry, not from
16341 ;; next one. It prevents extending text properties or overlays
16342 ;; belonging to the latter.
16343 (when (bolp) (backward-char))
16344 (let ((begin (1+ (point)))
16345 (inhibit-read-only t))
16346 (insert "\n:PROPERTIES:\n:END:")
16347 (when (eobp) (insert "\n"))
16348 (org-indent-region begin (point))))))
16350 (defun org-insert-drawer (&optional arg drawer)
16351 "Insert a drawer at point.
16353 When optional argument ARG is non-nil, insert a property drawer.
16355 Optional argument DRAWER, when non-nil, is a string representing
16356 drawer's name. Otherwise, the user is prompted for a name.
16358 If a region is active, insert the drawer around that region
16359 instead.
16361 Point is left between drawer's boundaries."
16362 (interactive "P")
16363 (let* ((drawer (if arg "PROPERTIES"
16364 (or drawer (read-from-minibuffer "Drawer: ")))))
16365 (cond
16366 ;; With C-u, fall back on `org-insert-property-drawer'
16367 (arg (org-insert-property-drawer))
16368 ;; Check validity of suggested drawer's name.
16369 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16370 (user-error "Invalid drawer name"))
16371 ;; With an active region, insert a drawer at point.
16372 ((not (org-region-active-p))
16373 (progn
16374 (unless (bolp) (insert "\n"))
16375 (insert (format ":%s:\n\n:END:\n" drawer))
16376 (forward-line -2)))
16377 ;; Otherwise, insert the drawer at point
16379 (let ((rbeg (region-beginning))
16380 (rend (copy-marker (region-end))))
16381 (unwind-protect
16382 (progn
16383 (goto-char rbeg)
16384 (beginning-of-line)
16385 (when (save-excursion
16386 (re-search-forward org-outline-regexp-bol rend t))
16387 (user-error "Drawers cannot contain headlines"))
16388 ;; Position point at the beginning of the first
16389 ;; non-blank line in region. Insert drawer's opening
16390 ;; there, then indent it.
16391 (org-skip-whitespace)
16392 (beginning-of-line)
16393 (insert ":" drawer ":\n")
16394 (forward-line -1)
16395 (indent-for-tab-command)
16396 ;; Move point to the beginning of the first blank line
16397 ;; after the last non-blank line in region. Insert
16398 ;; drawer's closing, then indent it.
16399 (goto-char rend)
16400 (skip-chars-backward " \r\t\n")
16401 (insert "\n:END:")
16402 (deactivate-mark t)
16403 (indent-for-tab-command)
16404 (unless (eolp) (insert "\n")))
16405 ;; Clear marker, whatever the outcome of insertion is.
16406 (set-marker rend nil)))))))
16408 (defvar org-property-set-functions-alist nil
16409 "Property set function alist.
16410 Each entry should have the following format:
16412 (PROPERTY . READ-FUNCTION)
16414 The read function will be called with the same argument as
16415 `org-completing-read'.")
16417 (defun org-set-property-function (property)
16418 "Get the function that should be used to set PROPERTY.
16419 This is computed according to `org-property-set-functions-alist'."
16420 (or (cdr (assoc property org-property-set-functions-alist))
16421 'org-completing-read))
16423 (defun org-read-property-value (property)
16424 "Read PROPERTY value from user."
16425 (let* ((completion-ignore-case t)
16426 (allowed (org-property-get-allowed-values nil property 'table))
16427 (cur (org-entry-get nil property))
16428 (prompt (concat property " value"
16429 (if (and cur (string-match "\\S-" cur))
16430 (concat " [" cur "]") "") ": "))
16431 (set-function (org-set-property-function property))
16432 (val (if allowed
16433 (funcall set-function prompt allowed nil
16434 (not (get-text-property 0 'org-unrestricted
16435 (caar allowed))))
16436 (funcall set-function prompt
16437 (mapcar 'list (org-property-values property))
16438 nil nil "" nil cur))))
16439 (org-trim val)))
16441 (defvar org-last-set-property nil)
16442 (defvar org-last-set-property-value nil)
16443 (defun org-read-property-name ()
16444 "Read a property name."
16445 (let ((completion-ignore-case t)
16446 (default-prop (or (and (org-at-property-p)
16447 (match-string-no-properties 2))
16448 org-last-set-property)))
16449 (org-completing-read
16450 (concat "Property"
16451 (if default-prop (concat " [" default-prop "]") "")
16452 ": ")
16453 (mapcar #'list (org-buffer-property-keys nil t t))
16454 nil nil nil nil default-prop)))
16456 (defun org-set-property-and-value (use-last)
16457 "Allow to set [PROPERTY]: [value] direction from prompt.
16458 When use-default, don't even ask, just use the last
16459 \"[PROPERTY]: [value]\" string from the history."
16460 (interactive "P")
16461 (let* ((completion-ignore-case t)
16462 (pv (or (and use-last org-last-set-property-value)
16463 (org-completing-read
16464 "Enter a \"[Property]: [value]\" pair: "
16465 nil nil nil nil nil
16466 org-last-set-property-value)))
16467 prop val)
16468 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16469 (setq prop (match-string 1 pv)
16470 val (match-string 2 pv))
16471 (org-set-property prop val))))
16473 (defun org-set-property (property value)
16474 "In the current entry, set PROPERTY to VALUE.
16476 When called interactively, this will prompt for a property name, offering
16477 completion on existing and default properties. And then it will prompt
16478 for a value, offering completion either on allowed values (via an inherited
16479 xxx_ALL property) or on existing values in other instances of this property
16480 in the current file.
16482 Throw an error when trying to set a property with an invalid name."
16483 (interactive (list nil nil))
16484 (let ((property (or property (org-read-property-name))))
16485 ;; `org-entry-put' also makes the following check, but this one
16486 ;; avoids polluting `org-last-set-property' and
16487 ;; `org-last-set-property-value' needlessly.
16488 (unless (org--valid-property-p property)
16489 (user-error "Invalid property name: \"%s\"" property))
16490 (let ((value (or value (org-read-property-value property)))
16491 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16492 (setq org-last-set-property property)
16493 (setq org-last-set-property-value (concat property ": " value))
16494 ;; Possibly postprocess the inserted value:
16495 (when fn (setq value (funcall fn value)))
16496 (unless (equal (org-entry-get nil property) value)
16497 (org-entry-put nil property value)))))
16499 (defun org-find-property (property &optional value)
16500 "Find first entry in buffer that sets PROPERTY.
16502 When optional argument VALUE is non-nil, only consider an entry
16503 if it contains PROPERTY set to this value. If PROPERTY should be
16504 explicitly set to nil, use string \"nil\" for VALUE.
16506 Return position where the entry begins, or nil if there is no
16507 such entry. If narrowing is in effect, only search the visible
16508 part of the buffer."
16509 (save-excursion
16510 (goto-char (point-min))
16511 (let ((case-fold-search t)
16512 (re (org-re-property property nil (not value) value)))
16513 (catch 'exit
16514 (while (re-search-forward re nil t)
16515 (when (if value (org-at-property-p)
16516 (org-entry-get (point) property nil t))
16517 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16519 (defun org-delete-property (property)
16520 "In the current entry, delete PROPERTY."
16521 (interactive
16522 (let* ((completion-ignore-case t)
16523 (cat (org-entry-get (point) "CATEGORY"))
16524 (props0 (org-entry-properties nil 'standard))
16525 (props (if cat props0
16526 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16527 (prop (if (< 1 (length props))
16528 (completing-read "Property: " props nil t)
16529 (caar props))))
16530 (list prop)))
16531 (if (not property)
16532 (message "No property to delete in this entry")
16533 (org-entry-delete nil property)
16534 (message "Property \"%s\" deleted" property)))
16536 (defun org-delete-property-globally (property)
16537 "Remove PROPERTY globally, from all entries.
16538 This function ignores narrowing, if any."
16539 (interactive
16540 (let* ((completion-ignore-case t)
16541 (prop (completing-read
16542 "Globally remove property: "
16543 (mapcar #'list (org-buffer-property-keys)))))
16544 (list prop)))
16545 (org-with-wide-buffer
16546 (goto-char (point-min))
16547 (let ((count 0)
16548 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16549 (while (re-search-forward re nil t)
16550 (when (org-entry-delete (point) property) (cl-incf count)))
16551 (message "Property \"%s\" removed from %d entries" property count))))
16553 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16555 (defun org-compute-property-at-point ()
16556 "Compute the property at point.
16557 This looks for an enclosing column format, extracts the operator and
16558 then applies it to the property in the column format's scope."
16559 (interactive)
16560 (unless (org-at-property-p)
16561 (user-error "Not at a property"))
16562 (let ((prop (match-string-no-properties 2)))
16563 (org-columns-get-format-and-top-level)
16564 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16565 (user-error "No operator defined for property %s" prop))
16566 (org-columns-compute prop)))
16568 (defvar org-property-allowed-value-functions nil
16569 "Hook for functions supplying allowed values for a specific property.
16570 The functions must take a single argument, the name of the property, and
16571 return a flat list of allowed values. If \":ETC\" is one of
16572 the values, this means that these values are intended as defaults for
16573 completion, but that other values should be allowed too.
16574 The functions must return nil if they are not responsible for this
16575 property.")
16577 (defun org-property-get-allowed-values (pom property &optional table)
16578 "Get allowed values for the property PROPERTY.
16579 When TABLE is non-nil, return an alist that can directly be used for
16580 completion."
16581 (let (vals)
16582 (cond
16583 ((equal property "TODO")
16584 (setq vals (org-with-point-at pom
16585 (append org-todo-keywords-1 '("")))))
16586 ((equal property "PRIORITY")
16587 (let ((n org-lowest-priority))
16588 (while (>= n org-highest-priority)
16589 (push (char-to-string n) vals)
16590 (setq n (1- n)))))
16591 ((equal property "CATEGORY"))
16592 ((member property org-special-properties))
16593 ((setq vals (run-hook-with-args-until-success
16594 'org-property-allowed-value-functions property)))
16596 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16597 (when (and vals (string-match "\\S-" vals))
16598 (setq vals (car (read-from-string (concat "(" vals ")"))))
16599 (setq vals (mapcar (lambda (x)
16600 (cond ((stringp x) x)
16601 ((numberp x) (number-to-string x))
16602 ((symbolp x) (symbol-name x))
16603 (t "???")))
16604 vals)))))
16605 (when (member ":ETC" vals)
16606 (setq vals (remove ":ETC" vals))
16607 (org-add-props (car vals) '(org-unrestricted t)))
16608 (if table (mapcar 'list vals) vals)))
16610 (defun org-property-previous-allowed-value (&optional _previous)
16611 "Switch to the next allowed value for this property."
16612 (interactive)
16613 (org-property-next-allowed-value t))
16615 (defun org-property-next-allowed-value (&optional previous)
16616 "Switch to the next allowed value for this property."
16617 (interactive)
16618 (unless (org-at-property-p)
16619 (user-error "Not at a property"))
16620 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16621 (key (match-string 2))
16622 (value (match-string 3))
16623 (allowed (or (org-property-get-allowed-values (point) key)
16624 (and (member value '("[ ]" "[-]" "[X]"))
16625 '("[ ]" "[X]"))))
16626 (heading (save-match-data (nth 4 (org-heading-components))))
16627 nval)
16628 (unless allowed
16629 (user-error "Allowed values for this property have not been defined"))
16630 (when previous (setq allowed (reverse allowed)))
16631 (when (member value allowed)
16632 (setq nval (car (cdr (member value allowed)))))
16633 (setq nval (or nval (car allowed)))
16634 (when (equal nval value)
16635 (user-error "Only one allowed value for this property"))
16636 (org-at-property-p)
16637 (replace-match (concat " :" key ": " nval) t t)
16638 (org-indent-line)
16639 (beginning-of-line 1)
16640 (skip-chars-forward " \t")
16641 (when (equal prop org-effort-property)
16642 (org-refresh-property
16643 '((effort . identity)
16644 (effort-minutes . org-duration-string-to-minutes))
16645 nval)
16646 (when (string= org-clock-current-task heading)
16647 (setq org-clock-effort nval)
16648 (org-clock-update-mode-line)))
16649 (run-hook-with-args 'org-property-changed-functions key nval)))
16651 (defun org-find-olp (path &optional this-buffer)
16652 "Return a marker pointing to the entry at outline path OLP.
16653 If anything goes wrong, throw an error.
16654 You can wrap this call to catch the error like this:
16656 \(condition-case msg
16657 \(org-mobile-locate-entry (match-string 4))
16658 \(error (nth 1 msg)))
16660 The return value will then be either a string with the error message,
16661 or a marker if everything is OK.
16663 If THIS-BUFFER is set, the outline path does not contain a file,
16664 only headings."
16665 (let* ((file (if this-buffer buffer-file-name (pop path)))
16666 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16667 (level 1)
16668 (lmin 1)
16669 (lmax 1)
16670 end found flevel)
16671 (unless buffer (error "File not found :%s" file))
16672 (with-current-buffer buffer
16673 (org-with-wide-buffer
16674 (goto-char (point-min))
16675 (dolist (heading path)
16676 (let ((re (format org-complex-heading-regexp-format
16677 (regexp-quote heading)))
16678 (cnt 0))
16679 (while (re-search-forward re end t)
16680 (setq level (- (match-end 1) (match-beginning 1)))
16681 (when (and (>= level lmin) (<= level lmax))
16682 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16683 (when (= cnt 0)
16684 (error "Heading not found on level %d: %s" lmax heading))
16685 (when (> cnt 1)
16686 (error "Heading not unique on level %d: %s" lmax heading))
16687 (goto-char found)
16688 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16689 (setq end (save-excursion (org-end-of-subtree t t)))))
16690 (when (org-at-heading-p)
16691 (point-marker))))))
16693 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16694 "Find node HEADING in BUFFER.
16695 Return a marker to the heading if it was found, or nil if not.
16696 If POS-ONLY is set, return just the position instead of a marker.
16698 The heading text must match exact, but it may have a TODO keyword,
16699 a priority cookie and tags in the standard locations."
16700 (with-current-buffer (or buffer (current-buffer))
16701 (org-with-wide-buffer
16702 (goto-char (point-min))
16703 (let (case-fold-search)
16704 (when (re-search-forward
16705 (format org-complex-heading-regexp-format
16706 (regexp-quote heading)) nil t)
16707 (if pos-only
16708 (match-beginning 0)
16709 (move-marker (make-marker) (match-beginning 0))))))))
16711 (defun org-find-exact-heading-in-directory (heading &optional dir)
16712 "Find Org node headline HEADING in all .org files in directory DIR.
16713 When the target headline is found, return a marker to this location."
16714 (let ((files (directory-files (or dir default-directory)
16715 t "\\`[^.#].*\\.org\\'"))
16716 visiting m buffer)
16717 (catch 'found
16718 (dolist (file files)
16719 (message "trying %s" file)
16720 (setq visiting (org-find-base-buffer-visiting file))
16721 (setq buffer (or visiting (find-file-noselect file)))
16722 (setq m (org-find-exact-headline-in-buffer
16723 heading buffer))
16724 (when (and (not m) (not visiting)) (kill-buffer buffer))
16725 (and m (throw 'found m))))))
16727 (defun org-find-entry-with-id (ident)
16728 "Locate the entry that contains the ID property with exact value IDENT.
16729 IDENT can be a string, a symbol or a number, this function will search for
16730 the string representation of it.
16731 Return the position where this entry starts, or nil if there is no such entry."
16732 (interactive "sID: ")
16733 (let ((id (cond
16734 ((stringp ident) ident)
16735 ((symbolp ident) (symbol-name ident))
16736 ((numberp ident) (number-to-string ident))
16737 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16738 (org-with-wide-buffer (org-find-property "ID" id))))
16740 ;;;; Timestamps
16742 (defvar org-last-changed-timestamp nil)
16743 (defvar org-last-inserted-timestamp nil
16744 "The last time stamp inserted with `org-insert-time-stamp'.")
16745 (defvar org-ts-what) ; dynamically scoped parameter
16747 (defun org-time-stamp (arg &optional inactive)
16748 "Prompt for a date/time and insert a time stamp.
16750 If the user specifies a time like HH:MM or if this command is
16751 called with at least one prefix argument, the time stamp contains
16752 the date and the time. Otherwise, only the date is included.
16754 All parts of a date not specified by the user are filled in from
16755 the timestamp at point, if any, or the current date/time
16756 otherwise.
16758 If there is already a timestamp at the cursor, it is replaced.
16760 With two universal prefix arguments, insert an active timestamp
16761 with the current time without prompting the user.
16763 When called from lisp, the timestamp is inactive if INACTIVE is
16764 non-nil."
16765 (interactive "P")
16766 (let* ((ts (cond
16767 ((org-at-date-range-p t)
16768 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16769 ((org-at-timestamp-p t) (match-string 0))))
16770 ;; Default time is either the timestamp at point or today.
16771 ;; When entering a range, only the range start is considered.
16772 (default-time (if (not ts) (current-time)
16773 (apply #'encode-time (org-parse-time-string ts))))
16774 (default-input (and ts (org-get-compact-tod ts)))
16775 (repeater (and ts
16776 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16777 (match-string 0 ts)))
16778 org-time-was-given
16779 org-end-time-was-given
16780 (time
16781 (and (if (equal arg '(16)) (current-time)
16782 ;; Preserve `this-command' and `last-command'.
16783 (let ((this-command this-command)
16784 (last-command last-command))
16785 (org-read-date
16786 arg 'totime nil nil default-time default-input
16787 inactive))))))
16788 (cond
16789 ((and ts
16790 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16791 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16792 (insert "--")
16793 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16795 ;; Make sure we're on a timestamp. When in the middle of a date
16796 ;; range, move arbitrarily to range end.
16797 (unless (org-at-timestamp-p t)
16798 (skip-chars-forward "-")
16799 (org-at-timestamp-p t))
16800 (replace-match "")
16801 (setq org-last-changed-timestamp
16802 (org-insert-time-stamp
16803 time (or org-time-was-given arg)
16804 inactive nil nil (list org-end-time-was-given)))
16805 (when repeater
16806 (backward-char)
16807 (insert " " repeater)
16808 (setq org-last-changed-timestamp
16809 (concat (substring org-last-inserted-timestamp 0 -1)
16810 " " repeater ">")))
16811 (message "Timestamp updated"))
16812 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16813 (t (org-insert-time-stamp
16814 time (or org-time-was-given arg) inactive nil nil
16815 (list org-end-time-was-given))))))
16817 ;; FIXME: can we use this for something else, like computing time differences?
16818 (defun org-get-compact-tod (s)
16819 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16820 (let* ((t1 (match-string 1 s))
16821 (h1 (string-to-number (match-string 2 s)))
16822 (m1 (string-to-number (match-string 3 s)))
16823 (t2 (and (match-end 4) (match-string 5 s)))
16824 (h2 (and t2 (string-to-number (match-string 6 s))))
16825 (m2 (and t2 (string-to-number (match-string 7 s))))
16826 dh dm)
16827 (if (not t2)
16829 (setq dh (- h2 h1) dm (- m2 m1))
16830 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16831 (concat t1 "+" (number-to-string dh)
16832 (and (/= 0 dm) (format ":%02d" dm)))))))
16834 (defun org-time-stamp-inactive (&optional arg)
16835 "Insert an inactive time stamp.
16836 An inactive time stamp is enclosed in square brackets instead of angle
16837 brackets. It is inactive in the sense that it does not trigger agenda entries,
16838 does not link to the calendar and cannot be changed with the S-cursor keys.
16839 So these are more for recording a certain time/date."
16840 (interactive "P")
16841 (org-time-stamp arg 'inactive))
16843 (defvar org-date-ovl (make-overlay 1 1))
16844 (overlay-put org-date-ovl 'face 'org-date-selected)
16845 (delete-overlay org-date-ovl)
16847 (defvar org-ans1) ; dynamically scoped parameter
16848 (defvar org-ans2) ; dynamically scoped parameter
16850 (defvar org-plain-time-of-day-regexp) ; defined below
16852 (defvar org-overriding-default-time nil) ; dynamically scoped
16853 (defvar org-read-date-overlay nil)
16854 (defvar org-dcst nil) ; dynamically scoped
16855 (defvar org-read-date-history nil)
16856 (defvar org-read-date-final-answer nil)
16857 (defvar org-read-date-analyze-futurep nil)
16858 (defvar org-read-date-analyze-forced-year nil)
16859 (defvar org-read-date-inactive)
16861 (defvar org-read-date-minibuffer-local-map
16862 (let* ((map (make-sparse-keymap)))
16863 (set-keymap-parent map minibuffer-local-map)
16864 (org-defkey map (kbd ".")
16865 (lambda () (interactive)
16866 ;; Are we at the beginning of the prompt?
16867 (if (looking-back "^[^:]+: "
16868 (let ((inhibit-field-text-motion t))
16869 (line-beginning-position)))
16870 (org-eval-in-calendar '(calendar-goto-today))
16871 (insert "."))))
16872 (org-defkey map (kbd "C-.")
16873 (lambda () (interactive)
16874 (org-eval-in-calendar '(calendar-goto-today))))
16875 (org-defkey map [(meta shift left)]
16876 (lambda () (interactive)
16877 (org-eval-in-calendar '(calendar-backward-month 1))))
16878 (org-defkey map [(meta shift right)]
16879 (lambda () (interactive)
16880 (org-eval-in-calendar '(calendar-forward-month 1))))
16881 (org-defkey map [(meta shift up)]
16882 (lambda () (interactive)
16883 (org-eval-in-calendar '(calendar-backward-year 1))))
16884 (org-defkey map [(meta shift down)]
16885 (lambda () (interactive)
16886 (org-eval-in-calendar '(calendar-forward-year 1))))
16887 (org-defkey map [?\e (shift left)]
16888 (lambda () (interactive)
16889 (org-eval-in-calendar '(calendar-backward-month 1))))
16890 (org-defkey map [?\e (shift right)]
16891 (lambda () (interactive)
16892 (org-eval-in-calendar '(calendar-forward-month 1))))
16893 (org-defkey map [?\e (shift up)]
16894 (lambda () (interactive)
16895 (org-eval-in-calendar '(calendar-backward-year 1))))
16896 (org-defkey map [?\e (shift down)]
16897 (lambda () (interactive)
16898 (org-eval-in-calendar '(calendar-forward-year 1))))
16899 (org-defkey map [(shift up)]
16900 (lambda () (interactive)
16901 (org-eval-in-calendar '(calendar-backward-week 1))))
16902 (org-defkey map [(shift down)]
16903 (lambda () (interactive)
16904 (org-eval-in-calendar '(calendar-forward-week 1))))
16905 (org-defkey map [(shift left)]
16906 (lambda () (interactive)
16907 (org-eval-in-calendar '(calendar-backward-day 1))))
16908 (org-defkey map [(shift right)]
16909 (lambda () (interactive)
16910 (org-eval-in-calendar '(calendar-forward-day 1))))
16911 (org-defkey map "!"
16912 (lambda () (interactive)
16913 (org-eval-in-calendar '(diary-view-entries))
16914 (message "")))
16915 (org-defkey map ">"
16916 (lambda () (interactive)
16917 (org-eval-in-calendar '(calendar-scroll-left 1))))
16918 (org-defkey map "<"
16919 (lambda () (interactive)
16920 (org-eval-in-calendar '(calendar-scroll-right 1))))
16921 (org-defkey map "\C-v"
16922 (lambda () (interactive)
16923 (org-eval-in-calendar
16924 '(calendar-scroll-left-three-months 1))))
16925 (org-defkey map "\M-v"
16926 (lambda () (interactive)
16927 (org-eval-in-calendar
16928 '(calendar-scroll-right-three-months 1))))
16929 map)
16930 "Keymap for minibuffer commands when using `org-read-date'.")
16932 (defvar org-def)
16933 (defvar org-defdecode)
16934 (defvar org-with-time)
16936 (defvar calendar-setup) ; Dynamically scoped.
16937 (defun org-read-date (&optional with-time to-time from-string prompt
16938 default-time default-input inactive)
16939 "Read a date, possibly a time, and make things smooth for the user.
16940 The prompt will suggest to enter an ISO date, but you can also enter anything
16941 which will at least partially be understood by `parse-time-string'.
16942 Unrecognized parts of the date will default to the current day, month, year,
16943 hour and minute. If this command is called to replace a timestamp at point,
16944 or to enter the second timestamp of a range, the default time is taken
16945 from the existing stamp. Furthermore, the command prefers the future,
16946 so if you are giving a date where the year is not given, and the day-month
16947 combination is already past in the current year, it will assume you
16948 mean next year. For details, see the manual. A few examples:
16950 3-2-5 --> 2003-02-05
16951 feb 15 --> currentyear-02-15
16952 2/15 --> currentyear-02-15
16953 sep 12 9 --> 2009-09-12
16954 12:45 --> today 12:45
16955 22 sept 0:34 --> currentyear-09-22 0:34
16956 12 --> currentyear-currentmonth-12
16957 Fri --> nearest Friday after today
16958 -Tue --> last Tuesday
16959 etc.
16961 Furthermore you can specify a relative date by giving, as the *first* thing
16962 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16963 change in days weeks, months, years.
16964 With a single plus or minus, the date is relative to today. With a double
16965 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16966 +4d --> four days from today
16967 +4 --> same as above
16968 +2w --> two weeks from today
16969 ++5 --> five days from default date
16971 The function understands only English month and weekday abbreviations.
16973 While prompting, a calendar is popped up - you can also select the
16974 date with the mouse (button 1). The calendar shows a period of three
16975 months. To scroll it to other months, use the keys `>' and `<'.
16976 If you don't like the calendar, turn it off with
16977 (setq org-read-date-popup-calendar nil)
16979 With optional argument TO-TIME, the date will immediately be converted
16980 to an internal time.
16981 With an optional argument WITH-TIME, the prompt will suggest to
16982 also insert a time. Note that when WITH-TIME is not set, you can
16983 still enter a time, and this function will inform the calling routine
16984 about this change. The calling routine may then choose to change the
16985 format used to insert the time stamp into the buffer to include the time.
16986 With optional argument FROM-STRING, read from this string instead from
16987 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16988 the time/date that is used for everything that is not specified by the
16989 user."
16990 (require 'parse-time)
16991 (let* ((org-with-time with-time)
16992 (org-time-stamp-rounding-minutes
16993 (if (equal org-with-time '(16))
16994 '(0 0)
16995 org-time-stamp-rounding-minutes))
16996 (org-dcst org-display-custom-times)
16997 (ct (org-current-time))
16998 (org-def (or org-overriding-default-time default-time ct))
16999 (org-defdecode (decode-time org-def))
17000 (cur-frame (selected-frame))
17001 (mouse-autoselect-window nil) ; Don't let the mouse jump
17002 (calendar-setup
17003 (and (eq calendar-setup 'calendar-only) 'calendar-only))
17004 (calendar-move-hook nil)
17005 (calendar-view-diary-initially-flag nil)
17006 (calendar-view-holidays-initially-flag nil)
17007 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
17008 ;; Rationalize `org-def' and `org-defdecode', if required.
17009 (when (< (nth 2 org-defdecode) org-extend-today-until)
17010 (setf (nth 2 org-defdecode) -1)
17011 (setf (nth 1 org-defdecode) 59)
17012 (setq org-def (apply #'encode-time org-defdecode))
17013 (setq org-defdecode (decode-time org-def)))
17014 (let* ((timestr (format-time-string
17015 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
17016 org-def))
17017 (prompt (concat (if prompt (concat prompt " ") "")
17018 (format "Date+time [%s]: " timestr))))
17019 (cond
17020 (from-string (setq ans from-string))
17021 (org-read-date-popup-calendar
17022 (save-excursion
17023 (save-window-excursion
17024 (calendar)
17025 (when (eq calendar-setup 'calendar-only)
17026 (setq cal-frame
17027 (window-frame (get-buffer-window "*Calendar*" 'visible)))
17028 (select-frame cal-frame))
17029 (org-eval-in-calendar '(setq cursor-type nil) t)
17030 (unwind-protect
17031 (progn
17032 (calendar-forward-day (- (time-to-days org-def)
17033 (calendar-absolute-from-gregorian
17034 (calendar-current-date))))
17035 (org-eval-in-calendar nil t)
17036 (let* ((old-map (current-local-map))
17037 (map (copy-keymap calendar-mode-map))
17038 (minibuffer-local-map
17039 (copy-keymap org-read-date-minibuffer-local-map)))
17040 (org-defkey map (kbd "RET") 'org-calendar-select)
17041 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17042 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17043 (unwind-protect
17044 (progn
17045 (use-local-map map)
17046 (setq org-read-date-inactive inactive)
17047 (add-hook 'post-command-hook 'org-read-date-display)
17048 (setq org-ans0
17049 (read-string prompt
17050 default-input
17051 'org-read-date-history
17052 nil))
17053 ;; org-ans0: from prompt
17054 ;; org-ans1: from mouse click
17055 ;; org-ans2: from calendar motion
17056 (setq ans
17057 (concat org-ans0 " " (or org-ans1 org-ans2))))
17058 (remove-hook 'post-command-hook 'org-read-date-display)
17059 (use-local-map old-map)
17060 (when org-read-date-overlay
17061 (delete-overlay org-read-date-overlay)
17062 (setq org-read-date-overlay nil)))))
17063 (bury-buffer "*Calendar*")
17064 (when cal-frame
17065 (delete-frame cal-frame)
17066 (select-frame-set-input-focus cur-frame))))))
17068 (t ; Naked prompt only
17069 (unwind-protect
17070 (setq ans (read-string prompt default-input
17071 'org-read-date-history timestr))
17072 (when org-read-date-overlay
17073 (delete-overlay org-read-date-overlay)
17074 (setq org-read-date-overlay nil))))))
17076 (setq final (org-read-date-analyze ans org-def org-defdecode))
17078 (when org-read-date-analyze-forced-year
17079 (message "Year was forced into %s"
17080 (if org-read-date-force-compatible-dates
17081 "compatible range (1970-2037)"
17082 "range representable on this machine"))
17083 (ding))
17085 ;; One round trip to get rid of 34th of August and stuff like that....
17086 (setq final (decode-time (apply 'encode-time final)))
17088 (setq org-read-date-final-answer ans)
17090 (if to-time
17091 (apply 'encode-time final)
17092 (if (and (boundp 'org-time-was-given) org-time-was-given)
17093 (format "%04d-%02d-%02d %02d:%02d"
17094 (nth 5 final) (nth 4 final) (nth 3 final)
17095 (nth 2 final) (nth 1 final))
17096 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17098 (defun org-read-date-display ()
17099 "Display the current date prompt interpretation in the minibuffer."
17100 (when org-read-date-display-live
17101 (when org-read-date-overlay
17102 (delete-overlay org-read-date-overlay))
17103 (when (minibufferp (current-buffer))
17104 (save-excursion
17105 (end-of-line 1)
17106 (while (not (equal (buffer-substring
17107 (max (point-min) (- (point) 4)) (point))
17108 " "))
17109 (insert " ")))
17110 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17111 " " (or org-ans1 org-ans2)))
17112 (org-end-time-was-given nil)
17113 (f (org-read-date-analyze ans org-def org-defdecode))
17114 (fmts (if org-dcst
17115 org-time-stamp-custom-formats
17116 org-time-stamp-formats))
17117 (fmt (if (or org-with-time
17118 (and (boundp 'org-time-was-given) org-time-was-given))
17119 (cdr fmts)
17120 (car fmts)))
17121 (txt (format-time-string fmt (apply 'encode-time f)))
17122 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17123 (txt (concat "=> " txt)))
17124 (when (and org-end-time-was-given
17125 (string-match org-plain-time-of-day-regexp txt))
17126 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17127 org-end-time-was-given
17128 (substring txt (match-end 0)))))
17129 (when org-read-date-analyze-futurep
17130 (setq txt (concat txt " (=>F)")))
17131 (setq org-read-date-overlay
17132 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17133 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17135 (defun org-read-date-analyze (ans def defdecode)
17136 "Analyze the combined answer of the date prompt."
17137 ;; FIXME: cleanup and comment
17138 ;; Pass `current-time' result to `decode-time' (instead of calling
17139 ;; without arguments) so that only `current-time' has to be
17140 ;; overriden in tests.
17141 (let ((org-def def)
17142 (org-defdecode defdecode)
17143 (nowdecode (decode-time (current-time)))
17144 delta deltan deltaw deltadef year month day
17145 hour minute second wday pm h2 m2 tl wday1
17146 iso-year iso-weekday iso-week iso-date futurep kill-year)
17147 (setq org-read-date-analyze-futurep nil
17148 org-read-date-analyze-forced-year nil)
17149 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17150 (setq ans "+0"))
17152 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17153 (setq ans (replace-match "" t t ans)
17154 deltan (car delta)
17155 deltaw (nth 1 delta)
17156 deltadef (nth 2 delta)))
17158 ;; Check if there is an iso week date in there. If yes, store the
17159 ;; info and postpone interpreting it until the rest of the parsing
17160 ;; is done.
17161 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17162 (setq iso-year (when (match-end 1)
17163 (org-small-year-to-year
17164 (string-to-number (match-string 1 ans))))
17165 iso-weekday (when (match-end 3)
17166 (string-to-number (match-string 3 ans)))
17167 iso-week (string-to-number (match-string 2 ans)))
17168 (setq ans (replace-match "" t t ans)))
17170 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17171 (when (string-match
17172 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17173 (setq year (if (match-end 2)
17174 (string-to-number (match-string 2 ans))
17175 (progn (setq kill-year t)
17176 (string-to-number (format-time-string "%Y"))))
17177 month (string-to-number (match-string 3 ans))
17178 day (string-to-number (match-string 4 ans)))
17179 (setq year (org-small-year-to-year year))
17180 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17181 t nil ans)))
17183 ;; Help matching dotted european dates
17184 (when (string-match
17185 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17186 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17187 (setq kill-year t)
17188 (string-to-number (format-time-string "%Y")))
17189 day (string-to-number (match-string 1 ans))
17190 month (string-to-number (match-string 2 ans))
17191 ans (replace-match (format "%04d-%02d-%02d" year month day)
17192 t nil ans)))
17194 ;; Help matching american dates, like 5/30 or 5/30/7
17195 (when (string-match
17196 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17197 (setq year (if (match-end 4)
17198 (string-to-number (match-string 4 ans))
17199 (progn (setq kill-year t)
17200 (string-to-number (format-time-string "%Y"))))
17201 month (string-to-number (match-string 1 ans))
17202 day (string-to-number (match-string 2 ans)))
17203 (setq year (org-small-year-to-year year))
17204 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17205 t nil ans)))
17206 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17207 ;; If there is a time with am/pm, and *no* time without it, we convert
17208 ;; so that matching will be successful.
17209 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17210 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17211 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17212 (setq hour (string-to-number (match-string 1 ans))
17213 minute (if (match-end 3)
17214 (string-to-number (match-string 3 ans))
17216 pm (equal ?p
17217 (string-to-char (downcase (match-string 4 ans)))))
17218 (if (and (= hour 12) (not pm))
17219 (setq hour 0)
17220 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17221 (setq ans (replace-match (format "%02d:%02d" hour minute)
17222 t t ans))))
17224 ;; Check if a time range is given as a duration
17225 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17226 (setq hour (string-to-number (match-string 1 ans))
17227 h2 (+ hour (string-to-number (match-string 3 ans)))
17228 minute (string-to-number (match-string 2 ans))
17229 m2 (+ minute (if (match-end 5) (string-to-number
17230 (match-string 5 ans))0)))
17231 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17232 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17233 t t ans)))
17235 ;; Check if there is a time range
17236 (when (boundp 'org-end-time-was-given)
17237 (setq org-time-was-given nil)
17238 (when (and (string-match org-plain-time-of-day-regexp ans)
17239 (match-end 8))
17240 (setq org-end-time-was-given (match-string 8 ans))
17241 (setq ans (concat (substring ans 0 (match-beginning 7))
17242 (substring ans (match-end 7))))))
17244 (setq tl (parse-time-string ans)
17245 day (or (nth 3 tl) (nth 3 org-defdecode))
17246 month
17247 (cond ((nth 4 tl))
17248 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17249 ;; Day was specified. Make sure DAY+MONTH
17250 ;; combination happens in the future.
17251 ((nth 3 tl)
17252 (setq futurep t)
17253 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17254 (nth 4 nowdecode)))
17255 (t (nth 4 org-defdecode)))
17256 year
17257 (cond ((and (not kill-year) (nth 5 tl)))
17258 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17259 ;; Month was guessed in the future and is at least
17260 ;; equal to NOWDECODE's. Fix year accordingly.
17261 (futurep
17262 (if (or (> month (nth 4 nowdecode))
17263 (>= day (nth 3 nowdecode)))
17264 (nth 5 nowdecode)
17265 (1+ (nth 5 nowdecode))))
17266 ;; Month was specified. Make sure MONTH+YEAR
17267 ;; combination happens in the future.
17268 ((nth 4 tl)
17269 (setq futurep t)
17270 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17271 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17272 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17273 (t (nth 5 nowdecode))))
17274 (t (nth 5 org-defdecode)))
17275 hour (or (nth 2 tl) (nth 2 org-defdecode))
17276 minute (or (nth 1 tl) (nth 1 org-defdecode))
17277 second (or (nth 0 tl) 0)
17278 wday (nth 6 tl))
17280 (when (and (eq org-read-date-prefer-future 'time)
17281 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17282 (equal day (nth 3 nowdecode))
17283 (equal month (nth 4 nowdecode))
17284 (equal year (nth 5 nowdecode))
17285 (nth 2 tl)
17286 (or (< (nth 2 tl) (nth 2 nowdecode))
17287 (and (= (nth 2 tl) (nth 2 nowdecode))
17288 (nth 1 tl)
17289 (< (nth 1 tl) (nth 1 nowdecode)))))
17290 (setq day (1+ day)
17291 futurep t))
17293 ;; Special date definitions below
17294 (cond
17295 (iso-week
17296 ;; There was an iso week
17297 (require 'cal-iso)
17298 (setq futurep nil)
17299 (setq year (or iso-year year)
17300 day (or iso-weekday wday 1)
17301 wday nil ; to make sure that the trigger below does not match
17302 iso-date (calendar-gregorian-from-absolute
17303 (calendar-iso-to-absolute
17304 (list iso-week day year))))
17305 ; FIXME: Should we also push ISO weeks into the future?
17306 ; (when (and org-read-date-prefer-future
17307 ; (not iso-year)
17308 ; (< (calendar-absolute-from-gregorian iso-date)
17309 ; (time-to-days (current-time))))
17310 ; (setq year (1+ year)
17311 ; iso-date (calendar-gregorian-from-absolute
17312 ; (calendar-iso-to-absolute
17313 ; (list iso-week day year)))))
17314 (setq month (car iso-date)
17315 year (nth 2 iso-date)
17316 day (nth 1 iso-date)))
17317 (deltan
17318 (setq futurep nil)
17319 (unless deltadef
17320 ;; Pass `current-time' result to `decode-time' (instead of
17321 ;; calling without arguments) so that only `current-time' has
17322 ;; to be overriden in tests.
17323 (let ((now (decode-time (current-time))))
17324 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17325 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17326 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17327 ((equal deltaw "m") (setq month (+ month deltan)))
17328 ((equal deltaw "y") (setq year (+ year deltan)))))
17329 ((and wday (not (nth 3 tl)))
17330 ;; Weekday was given, but no day, so pick that day in the week
17331 ;; on or after the derived date.
17332 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17333 (unless (equal wday wday1)
17334 (setq day (+ day (% (- wday wday1 -7) 7))))))
17335 (when (and (boundp 'org-time-was-given)
17336 (nth 2 tl))
17337 (setq org-time-was-given t))
17338 (when (< year 100) (setq year (+ 2000 year)))
17339 ;; Check of the date is representable
17340 (if org-read-date-force-compatible-dates
17341 (progn
17342 (when (< year 1970)
17343 (setq year 1970 org-read-date-analyze-forced-year t))
17344 (when (> year 2037)
17345 (setq year 2037 org-read-date-analyze-forced-year t)))
17346 (condition-case nil
17347 (ignore (encode-time second minute hour day month year))
17348 (error
17349 (setq year (nth 5 org-defdecode))
17350 (setq org-read-date-analyze-forced-year t))))
17351 (setq org-read-date-analyze-futurep futurep)
17352 (list second minute hour day month year)))
17354 (defvar parse-time-weekdays)
17355 (defun org-read-date-get-relative (s today default)
17356 "Check string S for special relative date string.
17357 TODAY and DEFAULT are internal times, for today and for a default.
17358 Return shift list (N what def-flag)
17359 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17360 N is the number of WHATs to shift.
17361 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17362 the DEFAULT date rather than TODAY."
17363 (require 'parse-time)
17364 (when (and
17365 (string-match
17366 (concat
17367 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17368 "\\([0-9]+\\)?"
17369 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17370 "\\([ \t]\\|$\\)") s)
17371 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17372 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17373 (string-to-char (substring (match-string 1 s) -1))
17374 ?+))
17375 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17376 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17377 (what (if (match-end 3) (match-string 3 s) "d"))
17378 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17379 (date (if rel default today))
17380 (wday (nth 6 (decode-time date)))
17381 delta)
17382 (if wday1
17383 (progn
17384 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17385 (when (= delta 0) (setq delta 7))
17386 (when (= dir ?-)
17387 (setq delta (- delta 7))
17388 (when (= delta 0) (setq delta -7)))
17389 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17390 (list delta "d" rel))
17391 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17393 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17394 "Turn a user-specified date into the internal representation.
17395 The internal representation needed by the calendar is (month day year).
17396 This is a wrapper to handle the brain-dead convention in calendar that
17397 user function argument order change dependent on argument order."
17398 (pcase calendar-date-style
17399 (`american (list arg1 arg2 arg3))
17400 (`european (list arg2 arg1 arg3))
17401 (`iso (list arg2 arg3 arg1))))
17403 (defun org-eval-in-calendar (form &optional keepdate)
17404 "Eval FORM in the calendar window and return to current window.
17405 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17406 (let ((sf (selected-frame))
17407 (sw (selected-window)))
17408 (select-window (get-buffer-window "*Calendar*" t))
17409 (eval form)
17410 (when (and (not keepdate) (calendar-cursor-to-date))
17411 (let* ((date (calendar-cursor-to-date))
17412 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17413 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17414 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17415 (select-window sw)
17416 (select-frame-set-input-focus sf)))
17418 (defun org-calendar-select ()
17419 "Return to `org-read-date' with the date currently selected.
17420 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17421 (interactive)
17422 (when (calendar-cursor-to-date)
17423 (let* ((date (calendar-cursor-to-date))
17424 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17425 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17426 (when (active-minibuffer-window) (exit-minibuffer))))
17428 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17429 "Insert a date stamp for the date given by the internal TIME.
17430 See `format-time-string' for the format of TIME.
17431 WITH-HM means use the stamp format that includes the time of the day.
17432 INACTIVE means use square brackets instead of angular ones, so that the
17433 stamp will not contribute to the agenda.
17434 PRE and POST are optional strings to be inserted before and after the
17435 stamp.
17436 The command returns the inserted time stamp."
17437 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17438 stamp)
17439 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17440 (insert-before-markers (or pre ""))
17441 (when (listp extra)
17442 (setq extra (car extra))
17443 (if (and (stringp extra)
17444 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17445 (setq extra (format "-%02d:%02d"
17446 (string-to-number (match-string 1 extra))
17447 (string-to-number (match-string 2 extra))))
17448 (setq extra nil)))
17449 (when extra
17450 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17451 (insert-before-markers (setq stamp (format-time-string fmt time)))
17452 (insert-before-markers (or post ""))
17453 (setq org-last-inserted-timestamp stamp)))
17455 (defun org-toggle-time-stamp-overlays ()
17456 "Toggle the use of custom time stamp formats."
17457 (interactive)
17458 (setq org-display-custom-times (not org-display-custom-times))
17459 (unless org-display-custom-times
17460 (let ((p (point-min)) (bmp (buffer-modified-p)))
17461 (while (setq p (next-single-property-change p 'display))
17462 (when (and (get-text-property p 'display)
17463 (eq (get-text-property p 'face) 'org-date))
17464 (remove-text-properties
17465 p (setq p (next-single-property-change p 'display))
17466 '(display t))))
17467 (set-buffer-modified-p bmp)))
17468 (org-restart-font-lock)
17469 (setq org-table-may-need-update t)
17470 (if org-display-custom-times
17471 (message "Time stamps are overlaid with custom format")
17472 (message "Time stamp overlays removed")))
17474 (defun org-display-custom-time (beg end)
17475 "Overlay modified time stamp format over timestamp between BEG and END."
17476 (let* ((ts (buffer-substring beg end))
17477 t1 w1 with-hm tf time str w2 (off 0))
17478 (save-match-data
17479 (setq t1 (org-parse-time-string ts t))
17480 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17481 (setq off (- (match-end 0) (match-beginning 0)))))
17482 (setq end (- end off))
17483 (setq w1 (- end beg)
17484 with-hm (and (nth 1 t1) (nth 2 t1))
17485 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17486 time (org-fix-decoded-time t1)
17487 str (org-add-props
17488 (format-time-string
17489 (substring tf 1 -1) (apply 'encode-time time))
17490 nil 'mouse-face 'highlight)
17491 w2 (length str))
17492 (unless (= w2 w1)
17493 (add-text-properties (1+ beg) (+ 2 beg)
17494 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17495 (put-text-property beg end 'display str)))
17497 (defun org-fix-decoded-time (time)
17498 "Set 0 instead of nil for the first 6 elements of time.
17499 Don't touch the rest."
17500 (let ((n 0))
17501 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17503 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17504 "Difference between TIMESTAMP-STRING and now in days.
17505 If SECONDS is non-nil, return the difference in seconds."
17506 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17507 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17508 (funcall fdiff (current-time)))))
17510 (defun org-deadline-close-p (timestamp-string &optional ndays)
17511 "Is the time in TIMESTAMP-STRING close to the current date?"
17512 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17513 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17514 (not (org-entry-is-done-p))))
17516 (defun org-get-wdays (ts &optional delay zero-delay)
17517 "Get the deadline lead time appropriate for timestring TS.
17518 When DELAY is non-nil, get the delay time for scheduled items
17519 instead of the deadline lead time. When ZERO-DELAY is non-nil
17520 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17521 don't try to find the delay cookie in the scheduled timestamp."
17522 (let ((tv (if delay org-scheduled-delay-days
17523 org-deadline-warning-days)))
17524 (cond
17525 ((or (and delay (< tv 0))
17526 (and delay zero-delay (<= tv 0))
17527 (and (not delay) (<= tv 0)))
17528 ;; Enforce this value no matter what
17529 (- tv))
17530 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17531 ;; lead time is specified.
17532 (floor (* (string-to-number (match-string 1 ts))
17533 (cdr (assoc (match-string 2 ts)
17534 '(("d" . 1) ("w" . 7)
17535 ("m" . 30.4) ("y" . 365.25)
17536 ("h" . 0.041667)))))))
17537 ;; go for the default.
17538 (t tv))))
17540 (defun org-calendar-select-mouse (ev)
17541 "Return to `org-read-date' with the date currently selected.
17542 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17543 (interactive "e")
17544 (mouse-set-point ev)
17545 (when (calendar-cursor-to-date)
17546 (let* ((date (calendar-cursor-to-date))
17547 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17548 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17549 (when (active-minibuffer-window) (exit-minibuffer))))
17551 (defun org-check-deadlines (ndays)
17552 "Check if there are any deadlines due or past due.
17553 A deadline is considered due if it happens within `org-deadline-warning-days'
17554 days from today's date. If the deadline appears in an entry marked DONE,
17555 it is not shown. A numeric prefix argument NDAYS can be used to test that
17556 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17557 are shown."
17558 (interactive "P")
17559 (let* ((org-warn-days
17560 (cond
17561 ((equal ndays '(4)) 100000)
17562 (ndays (prefix-numeric-value ndays))
17563 (t (abs org-deadline-warning-days))))
17564 (case-fold-search nil)
17565 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17566 (callback
17567 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17568 (message "%d deadlines past-due or due within %d days"
17569 (org-occur regexp nil callback)
17570 org-warn-days)))
17572 (defsubst org-re-timestamp (type)
17573 "Return a regexp for timestamp TYPE.
17574 Allowed values for TYPE are:
17576 all: all timestamps
17577 active: only active timestamps (<...>)
17578 inactive: only inactive timestamps ([...])
17579 scheduled: only scheduled timestamps
17580 deadline: only deadline timestamps
17581 closed: only closed time-stamps
17583 When TYPE is nil, fall back on returning a regexp that matches
17584 both scheduled and deadline timestamps."
17585 (cl-case type
17586 (all org-ts-regexp-both)
17587 (active org-ts-regexp)
17588 (inactive org-ts-regexp-inactive)
17589 (scheduled org-scheduled-time-regexp)
17590 (deadline org-deadline-time-regexp)
17591 (closed org-closed-time-regexp)
17592 (otherwise
17593 (concat "\\<"
17594 (regexp-opt (list org-deadline-string org-scheduled-string))
17595 " *<\\([^>]+\\)>"))))
17597 (defun org-check-before-date (d)
17598 "Check if there are deadlines or scheduled entries before date D."
17599 (interactive (list (org-read-date)))
17600 (let* ((case-fold-search nil)
17601 (regexp (org-re-timestamp org-ts-type))
17602 (ts-type org-ts-type)
17603 (callback
17604 (lambda ()
17605 (let ((match (match-string 1)))
17606 (and (if (memq ts-type '(active inactive all))
17607 (eq (org-element-type (save-excursion
17608 (backward-char)
17609 (org-element-context)))
17610 'timestamp)
17611 (org-at-planning-p))
17612 (time-less-p
17613 (org-time-string-to-time match)
17614 (org-time-string-to-time d)))))))
17615 (message "%d entries before %s"
17616 (org-occur regexp nil callback)
17617 d)))
17619 (defun org-check-after-date (d)
17620 "Check if there are deadlines or scheduled entries after date D."
17621 (interactive (list (org-read-date)))
17622 (let* ((case-fold-search nil)
17623 (regexp (org-re-timestamp org-ts-type))
17624 (ts-type org-ts-type)
17625 (callback
17626 (lambda ()
17627 (let ((match (match-string 1)))
17628 (and (if (memq ts-type '(active inactive all))
17629 (eq (org-element-type (save-excursion
17630 (backward-char)
17631 (org-element-context)))
17632 'timestamp)
17633 (org-at-planning-p))
17634 (not (time-less-p
17635 (org-time-string-to-time match)
17636 (org-time-string-to-time d))))))))
17637 (message "%d entries after %s"
17638 (org-occur regexp nil callback)
17639 d)))
17641 (defun org-check-dates-range (start-date end-date)
17642 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17643 (interactive (list (org-read-date nil nil nil "Range starts")
17644 (org-read-date nil nil nil "Range end")))
17645 (let ((case-fold-search nil)
17646 (regexp (org-re-timestamp org-ts-type))
17647 (callback
17648 (let ((type org-ts-type))
17649 (lambda ()
17650 (let ((match (match-string 1)))
17651 (and
17652 (if (memq type '(active inactive all))
17653 (eq (org-element-type (save-excursion
17654 (backward-char)
17655 (org-element-context)))
17656 'timestamp)
17657 (org-at-planning-p))
17658 (not (time-less-p
17659 (org-time-string-to-time match)
17660 (org-time-string-to-time start-date)))
17661 (time-less-p
17662 (org-time-string-to-time match)
17663 (org-time-string-to-time end-date))))))))
17664 (message "%d entries between %s and %s"
17665 (org-occur regexp nil callback) start-date end-date)))
17667 (defun org-evaluate-time-range (&optional to-buffer)
17668 "Evaluate a time range by computing the difference between start and end.
17669 Normally the result is just printed in the echo area, but with prefix arg
17670 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17671 If the time range is actually in a table, the result is inserted into the
17672 next column.
17673 For time difference computation, a year is assumed to be exactly 365
17674 days in order to avoid rounding problems."
17675 (interactive "P")
17677 (org-clock-update-time-maybe)
17678 (save-excursion
17679 (unless (org-at-date-range-p t)
17680 (goto-char (point-at-bol))
17681 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17682 (unless (org-at-date-range-p t)
17683 (user-error "Not at a time-stamp range, and none found in current line")))
17684 (let* ((ts1 (match-string 1))
17685 (ts2 (match-string 2))
17686 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17687 (match-end (match-end 0))
17688 (time1 (org-time-string-to-time ts1))
17689 (time2 (org-time-string-to-time ts2))
17690 (t1 (float-time time1))
17691 (t2 (float-time time2))
17692 (diff (abs (- t2 t1)))
17693 (negative (< (- t2 t1) 0))
17694 ;; (ys (floor (* 365 24 60 60)))
17695 (ds (* 24 60 60))
17696 (hs (* 60 60))
17697 (fy "%dy %dd %02d:%02d")
17698 (fy1 "%dy %dd")
17699 (fd "%dd %02d:%02d")
17700 (fd1 "%dd")
17701 (fh "%02d:%02d")
17702 y d h m align)
17703 (if havetime
17704 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17706 d (floor (/ diff ds)) diff (mod diff ds)
17707 h (floor (/ diff hs)) diff (mod diff hs)
17708 m (floor (/ diff 60)))
17709 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17711 d (floor (+ (/ diff ds) 0.5))
17712 h 0 m 0))
17713 (if (not to-buffer)
17714 (message "%s" (org-make-tdiff-string y d h m))
17715 (if (org-at-table-p)
17716 (progn
17717 (goto-char match-end)
17718 (setq align t)
17719 (and (looking-at " *|") (goto-char (match-end 0))))
17720 (goto-char match-end))
17721 (when (looking-at
17722 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17723 (replace-match ""))
17724 (when negative (insert " -"))
17725 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17726 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17727 (insert " " (format fh h m))))
17728 (when align (org-table-align))
17729 (message "Time difference inserted")))))
17731 (defun org-make-tdiff-string (y d h m)
17732 (let ((fmt "")
17733 (l nil))
17734 (when (> y 0)
17735 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17736 (push y l))
17737 (when (> d 0)
17738 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17739 (push d l))
17740 (when (> h 0)
17741 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17742 (push h l))
17743 (when (> m 0)
17744 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17745 (push m l))
17746 (apply 'format fmt (nreverse l))))
17748 (defun org-time-string-to-time (s &optional buffer pos)
17749 "Convert a timestamp string into internal time."
17750 (condition-case errdata
17751 (apply 'encode-time (org-parse-time-string s))
17752 (error (error "Bad timestamp `%s'%s\nError was: %s"
17753 s (if (not (and buffer pos))
17755 (format-message " at %d in buffer `%s'" pos buffer))
17756 (cdr errdata)))))
17758 (defun org-time-string-to-seconds (s)
17759 "Convert a timestamp string to a number of seconds."
17760 (float-time (org-time-string-to-time s)))
17762 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17764 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17765 "Convert time stamp S to an absolute day number.
17767 If DAYNR in non-nil, and there is a specifier for a cyclic time
17768 stamp, get the closest date to DAYNR. If PREFER is
17769 `past' (respectively `future') return a date past (respectively
17770 after) or equal to DAYNR.
17772 POS is the location of time stamp S, as a buffer position in
17773 BUFFER.
17775 Diary sexp timestamps are matched against DAYNR, when non-nil.
17776 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17777 signalled."
17778 (cond
17779 ((string-match "\\`%%\\((.*)\\)" s)
17780 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17781 ;; only able to match individual dates. If it fails, raise an
17782 ;; error.
17783 (if (and daynr
17784 (org-diary-sexp-entry
17785 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17786 daynr
17787 (signal 'org-diary-sexp-no-match (list s))))
17788 ((and daynr show-all) (org-closest-date s daynr prefer))
17789 (t (time-to-days
17790 (condition-case errdata
17791 (apply #'encode-time (org-parse-time-string s))
17792 (error (error "Bad timestamp `%s'%s\nError was: %s"
17794 (if (not (and buffer pos)) ""
17795 (format-message " at %d in buffer `%s'" pos buffer))
17796 (cdr errdata))))))))
17798 (defun org-days-to-iso-week (days)
17799 "Return the iso week number."
17800 (require 'cal-iso)
17801 (car (calendar-iso-from-absolute days)))
17803 (defun org-small-year-to-year (year)
17804 "Convert 2-digit years into 4-digit years.
17805 YEAR is expanded into one of the 30 next years, if possible, or
17806 into a past one. Any year larger than 99 is returned unchanged."
17807 (if (>= year 100) year
17808 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17809 (century (/ current 100))
17810 (offset (- year (% current 100))))
17811 (cond ((> offset 30) (+ (* (1- century) 100) year))
17812 ((> offset -70) (+ (* century 100) year))
17813 (t (+ (* (1+ century) 100) year))))))
17815 (defun org-time-from-absolute (d)
17816 "Return the time corresponding to date D.
17817 D may be an absolute day number, or a calendar-type list (month day year)."
17818 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17819 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17821 (defvar org-agenda-current-date)
17822 (defun org-calendar-holiday ()
17823 "List of holidays, for Diary display in Org mode."
17824 (require 'holidays)
17825 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17826 (and hl (mapconcat #'identity hl "; "))))
17828 (defun org-diary-sexp-entry (sexp entry d)
17829 "Process a SEXP diary ENTRY for date D."
17830 (require 'diary-lib)
17831 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17832 ;; dynamically.
17833 (let* ((sexp `(let ((entry ,entry)
17834 (date ',d))
17835 ,(car (read-from-string sexp))))
17836 (result (if calendar-debug-sexp (eval sexp)
17837 (condition-case nil
17838 (eval sexp)
17839 (error
17840 (beep)
17841 (message "Bad sexp at line %d in %s: %s"
17842 (org-current-line)
17843 (buffer-file-name) sexp)
17844 (sleep-for 2))))))
17845 (cond ((stringp result) (split-string result "; "))
17846 ((and (consp result)
17847 (not (consp (cdr result)))
17848 (stringp (cdr result))) (cdr result))
17849 ((and (consp result)
17850 (stringp (car result))) result)
17851 (result entry))))
17853 (defun org-diary-to-ical-string (frombuf)
17854 "Get iCalendar entries from diary entries in buffer FROMBUF.
17855 This uses the icalendar.el library."
17856 (let* ((tmpdir temporary-file-directory)
17857 (tmpfile (make-temp-name
17858 (expand-file-name "orgics" tmpdir)))
17859 buf rtn b e)
17860 (with-current-buffer frombuf
17861 (icalendar-export-region (point-min) (point-max) tmpfile)
17862 (setq buf (find-buffer-visiting tmpfile))
17863 (set-buffer buf)
17864 (goto-char (point-min))
17865 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17866 (setq b (match-beginning 0)))
17867 (goto-char (point-max))
17868 (when (re-search-backward "^END:VEVENT" nil t)
17869 (setq e (match-end 0)))
17870 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17871 (kill-buffer buf)
17872 (delete-file tmpfile)
17873 rtn))
17875 (defun org-closest-date (start current prefer)
17876 "Return closest date to CURRENT starting from START.
17878 CURRENT and START are both time stamps.
17880 When PREFER is `past', return a date that is either CURRENT or
17881 past. When PREFER is `future', return a date that is either
17882 CURRENT or future.
17884 Only time stamps with a repeater are modified. Any other time
17885 stamp stay unchanged. In any case, return value is an absolute
17886 day number."
17887 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17888 ;; No repeater. Do not shift time stamp.
17889 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17890 (let ((value (string-to-number (match-string 1 start)))
17891 (type (match-string 2 start)))
17892 (if (= 0 value)
17893 ;; Repeater with a 0-value is considered as void.
17894 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17895 (let* ((base (org-date-to-gregorian start))
17896 (target (org-date-to-gregorian current))
17897 (sday (calendar-absolute-from-gregorian base))
17898 (cday (calendar-absolute-from-gregorian target))
17899 n1 n2)
17900 ;; If START is already past CURRENT, just return START.
17901 (if (<= cday sday) sday
17902 ;; Compute closest date before (N1) and closest date past
17903 ;; (N2) CURRENT.
17904 (pcase type
17905 ("h"
17906 (let ((missing-hours
17907 (mod (+ (- (* 24 (- cday sday))
17908 (nth 2 (org-parse-time-string start)))
17909 org-extend-today-until)
17910 value)))
17911 (setf n1 (if (= missing-hours 0) cday
17912 (- cday (1+ (/ missing-hours 24)))))
17913 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17914 ((or "d" "w")
17915 (let ((value (if (equal type "w") (* 7 value) value)))
17916 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17917 (setf n2 (+ n1 value))))
17918 ("m"
17919 (let* ((add-months
17920 (lambda (d n)
17921 ;; Add N months to gregorian date D, i.e.,
17922 ;; a list (MONTH DAY YEAR). Return a valid
17923 ;; gregorian date.
17924 (let ((m (+ (nth 0 d) n)))
17925 (list (mod m 12)
17926 (nth 1 d)
17927 (+ (/ m 12) (nth 2 d))))))
17928 (months ; Complete months to TARGET.
17929 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17930 (- (nth 0 target) (nth 0 base))
17931 ;; If START's day is greater than
17932 ;; TARGET's, remove incomplete month.
17933 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17934 value)
17935 value))
17936 (before (funcall add-months base months)))
17937 (setf n1 (calendar-absolute-from-gregorian before))
17938 (setf n2
17939 (calendar-absolute-from-gregorian
17940 (funcall add-months before value)))))
17942 (let* ((d (nth 1 base))
17943 (m (nth 0 base))
17944 (y (nth 2 base))
17945 (years ; Complete years to TARGET.
17946 (* (/ (- (nth 2 target)
17948 ;; If START's month and day are
17949 ;; greater than TARGET's, remove
17950 ;; incomplete year.
17951 (if (or (> (nth 0 target) m)
17952 (and (= (nth 0 target) m)
17953 (> (nth 1 target) d)))
17956 value)
17957 value))
17958 (before (list m d (+ y years))))
17959 (setf n1 (calendar-absolute-from-gregorian before))
17960 (setf n2 (calendar-absolute-from-gregorian
17961 (list m d (+ (nth 2 before) value)))))))
17962 ;; Handle PREFER parameter, if any.
17963 (cond
17964 ((eq prefer 'past) (if (= cday n2) n2 n1))
17965 ((eq prefer 'future) (if (= cday n1) n1 n2))
17966 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17968 (defun org-date-to-gregorian (d)
17969 "Turn any specification of date D into a Gregorian date for the calendar."
17970 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17971 ((and (listp d) (= (length d) 3)) d)
17972 ((stringp d)
17973 (let ((d (org-parse-time-string d)))
17974 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17975 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17977 (defun org-parse-time-string (s &optional nodefault)
17978 "Parse the standard Org time string.
17979 This should be a lot faster than the normal `parse-time-string'.
17980 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17981 hour and minute fields will be nil if not given."
17982 (cond ((string-match org-ts-regexp0 s)
17983 (list 0
17984 (when (or (match-beginning 8) (not nodefault))
17985 (string-to-number (or (match-string 8 s) "0")))
17986 (when (or (match-beginning 7) (not nodefault))
17987 (string-to-number (or (match-string 7 s) "0")))
17988 (string-to-number (match-string 4 s))
17989 (string-to-number (match-string 3 s))
17990 (string-to-number (match-string 2 s))
17991 nil nil nil))
17992 ((string-match "^<[^>]+>$" s)
17993 (decode-time (seconds-to-time (org-matcher-time s))))
17994 (t (error "Not a standard Org time string: %s" s))))
17996 (defun org-timestamp-up (&optional arg)
17997 "Increase the date item at the cursor by one.
17998 If the cursor is on the year, change the year. If it is on the month,
17999 the day or the time, change that.
18000 With prefix ARG, change by that many units."
18001 (interactive "p")
18002 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
18004 (defun org-timestamp-down (&optional arg)
18005 "Decrease the date item at the cursor by one.
18006 If the cursor is on the year, change the year. If it is on the month,
18007 the day or the time, change that.
18008 With prefix ARG, change by that many units."
18009 (interactive "p")
18010 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
18012 (defun org-timestamp-up-day (&optional arg)
18013 "Increase the date in the time stamp by one day.
18014 With prefix ARG, change that many days."
18015 (interactive "p")
18016 (if (and (not (org-at-timestamp-p t))
18017 (org-at-heading-p))
18018 (org-todo 'up)
18019 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
18021 (defun org-timestamp-down-day (&optional arg)
18022 "Decrease the date in the time stamp by one day.
18023 With prefix ARG, change that many days."
18024 (interactive "p")
18025 (if (and (not (org-at-timestamp-p t))
18026 (org-at-heading-p))
18027 (org-todo 'down)
18028 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
18030 (defun org-at-timestamp-p (&optional inactive-ok)
18031 "Non-nil if point is inside a timestamp.
18033 When optional argument INACTIVE-OK is non-nil, also consider
18034 inactive timestamps.
18036 When this function returns a non-nil value, match data is set
18037 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18038 INACTIVE-OK."
18039 (interactive)
18040 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18041 (pos (point))
18042 (ans (or (looking-at tsr)
18043 (save-excursion
18044 (skip-chars-backward "^[<\n\r\t")
18045 (when (> (point) (point-min)) (backward-char 1))
18046 (and (looking-at tsr)
18047 (> (- (match-end 0) pos) -1))))))
18048 (and ans
18049 (boundp 'org-ts-what)
18050 (setq org-ts-what
18051 (cond
18052 ((= pos (match-beginning 0)) 'bracket)
18053 ;; Point is considered to be "on the bracket" whether
18054 ;; it's really on it or right after it.
18055 ((= pos (1- (match-end 0))) 'bracket)
18056 ((= pos (match-end 0)) 'after)
18057 ((org-pos-in-match-range pos 2) 'year)
18058 ((org-pos-in-match-range pos 3) 'month)
18059 ((org-pos-in-match-range pos 7) 'hour)
18060 ((org-pos-in-match-range pos 8) 'minute)
18061 ((or (org-pos-in-match-range pos 4)
18062 (org-pos-in-match-range pos 5)) 'day)
18063 ((and (> pos (or (match-end 8) (match-end 5)))
18064 (< pos (match-end 0)))
18065 (- pos (or (match-end 8) (match-end 5))))
18066 (t 'day))))
18067 ans))
18069 (defun org-toggle-timestamp-type ()
18070 "Toggle the type (<active> or [inactive]) of a time stamp."
18071 (interactive)
18072 (when (org-at-timestamp-p t)
18073 (let ((beg (match-beginning 0)) (end (match-end 0))
18074 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18075 (save-excursion
18076 (goto-char beg)
18077 (while (re-search-forward "[][<>]" end t)
18078 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18079 t t)))
18080 (message "Timestamp is now %sactive"
18081 (if (equal (char-after beg) ?<) "" "in")))))
18083 (defun org-at-clock-log-p nil
18084 "Is the cursor on the clock log line?"
18085 (save-excursion
18086 (move-beginning-of-line 1)
18087 (looking-at org-clock-line-re)))
18089 (defvar org-clock-history) ; defined in org-clock.el
18090 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18091 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18092 "Change the date in the time stamp at point.
18093 The date will be changed by N times WHAT. WHAT can be `day', `month',
18094 `year', `minute', `second'. If WHAT is not given, the cursor position
18095 in the timestamp determines what will be changed.
18096 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18097 (let ((origin (point)) origin-cat
18098 with-hm inactive
18099 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18100 org-ts-what
18101 extra rem
18102 ts time time0 fixnext clrgx)
18103 (unless (org-at-timestamp-p t)
18104 (user-error "Not at a timestamp"))
18105 (if (and (not what) (eq org-ts-what 'bracket))
18106 (org-toggle-timestamp-type)
18107 ;; Point isn't on brackets. Remember the part of the time-stamp
18108 ;; the point was in. Indeed, size of time-stamps may change,
18109 ;; but point must be kept in the same category nonetheless.
18110 (setq origin-cat org-ts-what)
18111 (when (and (not what) (not (eq org-ts-what 'day))
18112 org-display-custom-times
18113 (get-text-property (point) 'display)
18114 (not (get-text-property (1- (point)) 'display)))
18115 (setq org-ts-what 'day))
18116 (setq org-ts-what (or what org-ts-what)
18117 inactive (= (char-after (match-beginning 0)) ?\[)
18118 ts (match-string 0))
18119 (replace-match "")
18120 (when (string-match
18121 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18123 (setq extra (match-string 1 ts))
18124 (when suppress-tmp-delay
18125 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18126 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18127 (setq with-hm t))
18128 (setq time0 (org-parse-time-string ts))
18129 (when (and updown
18130 (eq org-ts-what 'minute)
18131 (not current-prefix-arg))
18132 ;; This looks like s-up and s-down. Change by one rounding step.
18133 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18134 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18135 (setcar (cdr time0) (+ (nth 1 time0)
18136 (if (> n 0) (- rem) (- dm rem))))))
18137 (setq time
18138 (apply #'encode-time
18139 (or (car time0) 0)
18140 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18141 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18142 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18143 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18144 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18145 (nthcdr 6 time0)))
18146 (when (and (member org-ts-what '(hour minute))
18147 extra
18148 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18149 (setq extra (org-modify-ts-extra
18150 extra
18151 (if (eq org-ts-what 'hour) 2 5)
18152 n dm)))
18153 (when (integerp org-ts-what)
18154 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18155 (when (eq what 'calendar)
18156 (let ((cal-date (org-get-date-from-calendar)))
18157 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18158 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18159 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18160 (setcar time0 (or (car time0) 0))
18161 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18162 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18163 (setq time (apply 'encode-time time0))))
18164 ;; Insert the new time-stamp, and ensure point stays in the same
18165 ;; category as before (i.e. not after the last position in that
18166 ;; category).
18167 (let ((pos (point)))
18168 ;; Stay before inserted string. `save-excursion' is of no use.
18169 (setq org-last-changed-timestamp
18170 (org-insert-time-stamp time with-hm inactive nil nil extra))
18171 (goto-char pos))
18172 (save-match-data
18173 (looking-at org-ts-regexp3)
18174 (goto-char (cond
18175 ;; `day' category ends before `hour' if any, or at
18176 ;; the end of the day name.
18177 ((eq origin-cat 'day)
18178 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18179 ((eq origin-cat 'hour) (min (match-end 7) origin))
18180 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18181 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18182 ;; `year' and `month' have both fixed size: point
18183 ;; couldn't have moved into another part.
18184 (t origin))))
18185 ;; Update clock if on a CLOCK line.
18186 (org-clock-update-time-maybe)
18187 ;; Maybe adjust the closest clock in `org-clock-history'
18188 (when org-clock-adjust-closest
18189 (if (not (and (org-at-clock-log-p)
18190 (< 1 (length (delq nil (mapcar 'marker-position
18191 org-clock-history))))))
18192 (message "No clock to adjust")
18193 (cond ((save-excursion ; fix previous clock?
18194 (re-search-backward org-ts-regexp0 nil t)
18195 (looking-back (concat org-clock-string " \\[")
18196 (line-beginning-position)))
18197 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18198 ((save-excursion ; fix next clock?
18199 (re-search-backward org-ts-regexp0 nil t)
18200 (looking-at (concat org-ts-regexp0 "\\] =>")))
18201 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18202 (save-window-excursion
18203 ;; Find closest clock to point, adjust the previous/next one in history
18204 (let* ((p (save-excursion (org-back-to-heading t)))
18205 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18206 (clfixnth
18207 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18208 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18209 (if (not clfixpos)
18210 (message "No clock to adjust")
18211 (save-excursion
18212 (org-goto-marker-or-bmk clfixpos)
18213 (org-show-subtree)
18214 (when (re-search-forward clrgx nil t)
18215 (goto-char (match-beginning 1))
18216 (let (org-clock-adjust-closest)
18217 (org-timestamp-change n org-ts-what updown))
18218 (message "Clock adjusted in %s for heading: %s"
18219 (file-name-nondirectory (buffer-file-name))
18220 (org-get-heading t t)))))))))
18221 ;; Try to recenter the calendar window, if any.
18222 (when (and org-calendar-follow-timestamp-change
18223 (get-buffer-window "*Calendar*" t)
18224 (memq org-ts-what '(day month year)))
18225 (org-recenter-calendar (time-to-days time))))))
18227 (defun org-modify-ts-extra (s pos n dm)
18228 "Change the different parts of the lead-time and repeat fields in timestamp."
18229 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18230 ng h m new rem)
18231 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18232 (cond
18233 ((or (org-pos-in-match-range pos 2)
18234 (org-pos-in-match-range pos 3))
18235 (setq m (string-to-number (match-string 3 s))
18236 h (string-to-number (match-string 2 s)))
18237 (if (org-pos-in-match-range pos 2)
18238 (setq h (+ h n))
18239 (setq n (* dm (with-no-warnings (signum n))))
18240 (unless (= 0 (setq rem (% m dm)))
18241 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18242 (setq m (+ m n)))
18243 (when (< m 0) (setq m (+ m 60) h (1- h)))
18244 (when (> m 59) (setq m (- m 60) h (1+ h)))
18245 (setq h (mod h 24))
18246 (setq ng 1 new (format "-%02d:%02d" h m)))
18247 ((org-pos-in-match-range pos 6)
18248 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18249 ((org-pos-in-match-range pos 5)
18250 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18252 ((org-pos-in-match-range pos 9)
18253 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18254 ((org-pos-in-match-range pos 8)
18255 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18257 (when ng
18258 (setq s (concat
18259 (substring s 0 (match-beginning ng))
18261 (substring s (match-end ng))))))
18264 (defun org-recenter-calendar (d)
18265 "If the calendar is visible, recenter it to date D."
18266 (let ((cwin (get-buffer-window "*Calendar*" t)))
18267 (when cwin
18268 (let ((calendar-move-hook nil))
18269 (with-selected-window cwin
18270 (calendar-goto-date
18271 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18273 (defun org-goto-calendar (&optional arg)
18274 "Go to the Emacs calendar at the current date.
18275 If there is a time stamp in the current line, go to that date.
18276 A prefix ARG can be used to force the current date."
18277 (interactive "P")
18278 (let ((tsr org-ts-regexp) diff
18279 (calendar-move-hook nil)
18280 (calendar-view-holidays-initially-flag nil)
18281 (calendar-view-diary-initially-flag nil))
18282 (when (or (org-at-timestamp-p)
18283 (save-excursion
18284 (beginning-of-line 1)
18285 (looking-at (concat ".*" tsr))))
18286 (let ((d1 (time-to-days (current-time)))
18287 (d2 (time-to-days
18288 (org-time-string-to-time (match-string 1)))))
18289 (setq diff (- d2 d1))))
18290 (calendar)
18291 (calendar-goto-today)
18292 (when (and diff (not arg)) (calendar-forward-day diff))))
18294 (defun org-get-date-from-calendar ()
18295 "Return a list (month day year) of date at point in calendar."
18296 (with-current-buffer "*Calendar*"
18297 (save-match-data
18298 (calendar-cursor-to-date))))
18300 (defun org-date-from-calendar ()
18301 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18302 If there is already a time stamp at the cursor position, update it."
18303 (interactive)
18304 (if (org-at-timestamp-p t)
18305 (org-timestamp-change 0 'calendar)
18306 (let ((cal-date (org-get-date-from-calendar)))
18307 (org-insert-time-stamp
18308 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18310 (defcustom org-effort-durations
18311 `(("min" . 1)
18312 ("h" . 60)
18313 ("d" . ,(* 60 8))
18314 ("w" . ,(* 60 8 5))
18315 ("m" . ,(* 60 8 5 4))
18316 ("y" . ,(* 60 8 5 40)))
18317 "Conversion factor to minutes for an effort modifier.
18319 Each entry has the form (MODIFIER . MINUTES).
18321 In an effort string, a number followed by MODIFIER is multiplied
18322 by the specified number of MINUTES to obtain an effort in
18323 minutes.
18325 For example, if the value of this variable is ((\"hours\" . 60)), then an
18326 effort string \"2hours\" is equivalent to 120 minutes."
18327 :group 'org-agenda
18328 :version "25.2"
18329 :package-version '(Org . "8.3")
18330 :type '(alist :key-type (string :tag "Modifier")
18331 :value-type (number :tag "Minutes")))
18333 (defun org-minutes-to-clocksum-string (m)
18334 "Format number of minutes as a clocksum string.
18335 The format is determined by `org-time-clocksum-format',
18336 `org-time-clocksum-use-fractional' and
18337 `org-time-clocksum-fractional-format' and
18338 `org-time-clocksum-use-effort-durations'."
18339 (let ((clocksum "")
18340 (m (round m)) ; Don't allow fractions of minutes
18341 h d w mo y fmt n)
18342 (setq h (if org-time-clocksum-use-effort-durations
18343 (cdr (assoc "h" org-effort-durations)) 60)
18344 d (if org-time-clocksum-use-effort-durations
18345 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18346 w (if org-time-clocksum-use-effort-durations
18347 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18348 mo (if org-time-clocksum-use-effort-durations
18349 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18350 y (if org-time-clocksum-use-effort-durations
18351 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18352 ;; fractional format
18353 (if org-time-clocksum-use-fractional
18354 (cond
18355 ;; single format string
18356 ((stringp org-time-clocksum-fractional-format)
18357 (format org-time-clocksum-fractional-format (/ m (float h))))
18358 ;; choice of fractional formats for different time units
18359 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18360 (> (/ (truncate m) (* y d h)) 0))
18361 (format fmt (/ m (* y d (float h)))))
18362 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18363 (> (/ (truncate m) (* mo d h)) 0))
18364 (format fmt (/ m (* mo d (float h)))))
18365 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18366 (> (/ (truncate m) (* w d h)) 0))
18367 (format fmt (/ m (* w d (float h)))))
18368 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18369 (> (/ (truncate m) (* d h)) 0))
18370 (format fmt (/ m (* d (float h)))))
18371 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18372 (> (/ (truncate m) h) 0))
18373 (format fmt (/ m (float h))))
18374 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18375 (format fmt m))
18376 ;; fall back to smallest time unit with a format
18377 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18378 (format fmt (/ m (float h))))
18379 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18380 (format fmt (/ m (* d (float h)))))
18381 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18382 (format fmt (/ m (* w d (float h)))))
18383 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18384 (format fmt (/ m (* mo d (float h)))))
18385 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18386 (format fmt (/ m (* y d (float h))))))
18387 ;; standard (non-fractional) format, with single format string
18388 (if (stringp org-time-clocksum-format)
18389 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18390 ;; separate formats components
18391 (and (setq fmt (plist-get org-time-clocksum-format :years))
18392 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18393 (plist-get org-time-clocksum-format :require-years))
18394 (setq clocksum (concat clocksum (format fmt n))
18395 m (- m (* n y d h))))
18396 (and (setq fmt (plist-get org-time-clocksum-format :months))
18397 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18398 (plist-get org-time-clocksum-format :require-months))
18399 (setq clocksum (concat clocksum (format fmt n))
18400 m (- m (* n mo d h))))
18401 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18402 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18403 (plist-get org-time-clocksum-format :require-weeks))
18404 (setq clocksum (concat clocksum (format fmt n))
18405 m (- m (* n w d h))))
18406 (and (setq fmt (plist-get org-time-clocksum-format :days))
18407 (or (> (setq n (/ (truncate m) (* d h))) 0)
18408 (plist-get org-time-clocksum-format :require-days))
18409 (setq clocksum (concat clocksum (format fmt n))
18410 m (- m (* n d h))))
18411 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18412 (or (> (setq n (/ (truncate m) h)) 0)
18413 (plist-get org-time-clocksum-format :require-hours))
18414 (setq clocksum (concat clocksum (format fmt n))
18415 m (- m (* n h))))
18416 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18417 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18418 (setq clocksum (concat clocksum (format fmt m))))
18419 ;; return formatted time duration
18420 clocksum))))
18422 (defun org-hours-to-clocksum-string (n)
18423 (org-minutes-to-clocksum-string (* n 60)))
18425 (defun org-hh:mm-string-to-minutes (s)
18426 "Convert a string H:MM to a number of minutes.
18427 If the string is just a number, interpret it as minutes.
18428 In fact, the first hh:mm or number in the string will be taken,
18429 there can be extra stuff in the string.
18430 If no number is found, the return value is 0."
18431 (cond
18432 ((integerp s) s)
18433 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18434 (+ (* (string-to-number (match-string 1 s)) 60)
18435 (string-to-number (match-string 2 s))))
18436 ((string-match "\\([0-9]+\\)" s)
18437 (string-to-number (match-string 1 s)))
18438 (t 0)))
18440 (defcustom org-image-actual-width t
18441 "Should we use the actual width of images when inlining them?
18443 When set to t, always use the image width.
18445 When set to a number, use imagemagick (when available) to set
18446 the image's width to this value.
18448 When set to a number in a list, try to get the width from any
18449 #+ATTR.* keyword if it matches a width specification like
18451 #+ATTR_HTML: :width 300px
18453 and fall back on that number if none is found.
18455 When set to nil, try to get the width from an #+ATTR.* keyword
18456 and fall back on the original width if none is found.
18458 This requires Emacs >= 24.1, build with imagemagick support."
18459 :group 'org-appearance
18460 :version "24.4"
18461 :package-version '(Org . "8.0")
18462 :type '(choice
18463 (const :tag "Use the image width" t)
18464 (integer :tag "Use a number of pixels")
18465 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18466 (const :tag "Use #+ATTR* or don't resize" nil)))
18468 (defcustom org-agenda-inhibit-startup nil
18469 "Inhibit startup when preparing agenda buffers.
18470 When this variable is t, the initialization of the Org agenda
18471 buffers is inhibited: e.g. the visibility state is not set, the
18472 tables are not re-aligned, etc."
18473 :type 'boolean
18474 :version "24.3"
18475 :group 'org-agenda)
18477 (defcustom org-agenda-ignore-properties nil
18478 "Avoid updating text properties when building the agenda.
18479 Properties are used to prepare buffers for effort estimates,
18480 appointments, statistics and subtree-local categories.
18481 If you don't use these in the agenda, you can add them to this
18482 list and agenda building will be a bit faster.
18483 The value is a list, with zero or more of the symbols `effort', `appt',
18484 `stats' or `category'."
18485 :type '(set :greedy t
18486 (const effort)
18487 (const appt)
18488 (const stats)
18489 (const category))
18490 :version "25.2"
18491 :package-version '(Org . "8.3")
18492 :group 'org-agenda)
18494 (defun org-duration-string-to-minutes (s &optional output-to-string)
18495 "Convert a duration string S to minutes.
18497 A bare number is interpreted as minutes, modifiers can be set by
18498 customizing `org-effort-durations' (which see).
18500 Entries containing a colon are interpreted as H:MM by
18501 `org-hh:mm-string-to-minutes'."
18502 (let ((result 0)
18503 (re (concat "\\([0-9.]+\\) *\\("
18504 (regexp-opt (mapcar 'car org-effort-durations))
18505 "\\)")))
18506 (while (string-match re s)
18507 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18508 (string-to-number (match-string 1 s))))
18509 (setq s (replace-match "" nil t s)))
18510 (setq result (floor result))
18511 (cl-incf result (org-hh:mm-string-to-minutes s))
18512 (if output-to-string (number-to-string result) result)))
18514 ;;;; Files
18516 (defun org-save-all-org-buffers ()
18517 "Save all Org buffers without user confirmation."
18518 (interactive)
18519 (message "Saving all Org buffers...")
18520 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18521 (when (featurep 'org-id) (org-id-locations-save))
18522 (message "Saving all Org buffers... done"))
18524 (defun org-revert-all-org-buffers ()
18525 "Revert all Org buffers.
18526 Prompt for confirmation when there are unsaved changes.
18527 Be sure you know what you are doing before letting this function
18528 overwrite your changes.
18530 This function is useful in a setup where one tracks org files
18531 with a version control system, to revert on one machine after pulling
18532 changes from another. I believe the procedure must be like this:
18534 1. M-x org-save-all-org-buffers
18535 2. Pull changes from the other machine, resolve conflicts
18536 3. M-x org-revert-all-org-buffers"
18537 (interactive)
18538 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18539 (user-error "Abort"))
18540 (save-excursion
18541 (save-window-excursion
18542 (dolist (b (buffer-list))
18543 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18544 (with-current-buffer b buffer-file-name))
18545 (pop-to-buffer-same-window b)
18546 (revert-buffer t 'no-confirm)))
18547 (when (and (featurep 'org-id) org-id-track-globally)
18548 (org-id-locations-load)))))
18550 ;;;; Agenda files
18552 ;;;###autoload
18553 (defun org-switchb (&optional arg)
18554 "Switch between Org buffers.
18556 With `\\[universal-argument]' prefix, restrict available buffers to files.
18558 With `\\[universal-argument] \\[universal-argument]' \
18559 prefix, restrict available buffers to agenda files."
18560 (interactive "P")
18561 (let ((blist (org-buffer-list
18562 (cond ((equal arg '(4)) 'files)
18563 ((equal arg '(16)) 'agenda)))))
18564 (pop-to-buffer-same-window
18565 (completing-read "Org buffer: "
18566 (mapcar #'list (mapcar #'buffer-name blist))
18567 nil t))))
18569 (defun org-buffer-list (&optional predicate exclude-tmp)
18570 "Return a list of Org buffers.
18571 PREDICATE can be `export', `files' or `agenda'.
18573 export restrict the list to Export buffers.
18574 files restrict the list to buffers visiting Org files.
18575 agenda restrict the list to buffers visiting agenda files.
18577 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18578 (let* ((bfn nil)
18579 (agenda-files (and (eq predicate 'agenda)
18580 (mapcar 'file-truename (org-agenda-files t))))
18581 (filter
18582 (cond
18583 ((eq predicate 'files)
18584 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18585 ((eq predicate 'export)
18586 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18587 ((eq predicate 'agenda)
18588 (lambda (b)
18589 (with-current-buffer b
18590 (and (derived-mode-p 'org-mode)
18591 (setq bfn (buffer-file-name b))
18592 (member (file-truename bfn) agenda-files)))))
18593 (t (lambda (b) (with-current-buffer b
18594 (or (derived-mode-p 'org-mode)
18595 (string-match "\\*Org .*Export"
18596 (buffer-name b)))))))))
18597 (delq nil
18598 (mapcar
18599 (lambda(b)
18600 (if (and (funcall filter b)
18601 (or (not exclude-tmp)
18602 (not (string-match "tmp" (buffer-name b)))))
18604 nil))
18605 (buffer-list)))))
18607 (defun org-agenda-files (&optional unrestricted archives)
18608 "Get the list of agenda files.
18609 Optional UNRESTRICTED means return the full list even if a restriction
18610 is currently in place.
18611 When ARCHIVES is t, include all archive files that are really being
18612 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18613 `org-agenda-archives-mode' is t."
18614 (let ((files
18615 (cond
18616 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18617 ((stringp org-agenda-files) (org-read-agenda-file-list))
18618 ((listp org-agenda-files) org-agenda-files)
18619 (t (error "Invalid value of `org-agenda-files'")))))
18620 (setq files (apply 'append
18621 (mapcar (lambda (f)
18622 (if (file-directory-p f)
18623 (directory-files
18624 f t org-agenda-file-regexp)
18625 (list f)))
18626 files)))
18627 (when org-agenda-skip-unavailable-files
18628 (setq files (delq nil
18629 (mapcar (function
18630 (lambda (file)
18631 (and (file-readable-p file) file)))
18632 files))))
18633 (when (or (eq archives t)
18634 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18635 (setq files (org-add-archive-files files)))
18636 files))
18638 (defun org-agenda-file-p (&optional file)
18639 "Return non-nil, if FILE is an agenda file.
18640 If FILE is omitted, use the file associated with the current
18641 buffer."
18642 (let ((fname (or file (buffer-file-name))))
18643 (and fname
18644 (member (file-truename fname)
18645 (mapcar #'file-truename (org-agenda-files t))))))
18647 (defun org-edit-agenda-file-list ()
18648 "Edit the list of agenda files.
18649 Depending on setup, this either uses customize to edit the variable
18650 `org-agenda-files', or it visits the file that is holding the list. In the
18651 latter case, the buffer is set up in a way that saving it automatically kills
18652 the buffer and restores the previous window configuration."
18653 (interactive)
18654 (if (stringp org-agenda-files)
18655 (let ((cw (current-window-configuration)))
18656 (find-file org-agenda-files)
18657 (setq-local org-window-configuration cw)
18658 (add-hook 'after-save-hook
18659 (lambda ()
18660 (set-window-configuration
18661 (prog1 org-window-configuration
18662 (kill-buffer (current-buffer))))
18663 (org-install-agenda-files-menu)
18664 (message "New agenda file list installed"))
18665 nil 'local)
18666 (message "%s" (substitute-command-keys
18667 "Edit list and finish with \\[save-buffer]")))
18668 (customize-variable 'org-agenda-files)))
18670 (defun org-store-new-agenda-file-list (list)
18671 "Set new value for the agenda file list and save it correctly."
18672 (if (stringp org-agenda-files)
18673 (let ((fe (org-read-agenda-file-list t)) b u)
18674 (while (setq b (find-buffer-visiting org-agenda-files))
18675 (kill-buffer b))
18676 (with-temp-file org-agenda-files
18677 (insert
18678 (mapconcat
18679 (lambda (f) ;; Keep un-expanded entries.
18680 (if (setq u (assoc f fe))
18681 (cdr u)
18683 list "\n")
18684 "\n")))
18685 (let ((org-mode-hook nil) (org-inhibit-startup t)
18686 (org-insert-mode-line-in-empty-file nil))
18687 (setq org-agenda-files list)
18688 (customize-save-variable 'org-agenda-files org-agenda-files))))
18690 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18691 "Read the list of agenda files from a file.
18692 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18693 filenames, used by `org-store-new-agenda-file-list' to write back
18694 un-expanded file names."
18695 (when (file-directory-p org-agenda-files)
18696 (error "`org-agenda-files' cannot be a single directory"))
18697 (when (stringp org-agenda-files)
18698 (with-temp-buffer
18699 (insert-file-contents org-agenda-files)
18700 (mapcar
18701 (lambda (f)
18702 (let ((e (expand-file-name (substitute-in-file-name f)
18703 org-directory)))
18704 (if pair-with-expansion
18705 (cons e f)
18706 e)))
18707 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18709 ;;;###autoload
18710 (defun org-cycle-agenda-files ()
18711 "Cycle through the files in `org-agenda-files'.
18712 If the current buffer visits an agenda file, find the next one in the list.
18713 If the current buffer does not, find the first agenda file."
18714 (interactive)
18715 (let* ((fs (or (org-agenda-files t)
18716 (user-error "No agenda files")))
18717 (files (copy-sequence fs))
18718 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18719 file)
18720 (when tcf
18721 (while (and (setq file (pop files))
18722 (not (equal (file-truename file) tcf)))))
18723 (find-file (car (or files fs)))
18724 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18726 (defun org-agenda-file-to-front (&optional to-end)
18727 "Move/add the current file to the top of the agenda file list.
18728 If the file is not present in the list, it is added to the front. If it is
18729 present, it is moved there. With optional argument TO-END, add/move to the
18730 end of the list."
18731 (interactive "P")
18732 (let ((org-agenda-skip-unavailable-files nil)
18733 (file-alist (mapcar (lambda (x)
18734 (cons (file-truename x) x))
18735 (org-agenda-files t)))
18736 (ctf (file-truename
18737 (or buffer-file-name
18738 (user-error "Please save the current buffer to a file"))))
18739 x had)
18740 (setq x (assoc ctf file-alist) had x)
18742 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18743 (if to-end
18744 (setq file-alist (append (delq x file-alist) (list x)))
18745 (setq file-alist (cons x (delq x file-alist))))
18746 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18747 (org-install-agenda-files-menu)
18748 (message "File %s to %s of agenda file list"
18749 (if had "moved" "added") (if to-end "end" "front"))))
18751 (defun org-remove-file (&optional file)
18752 "Remove current file from the list of files in variable `org-agenda-files'.
18753 These are the files which are being checked for agenda entries.
18754 Optional argument FILE means use this file instead of the current."
18755 (interactive)
18756 (let* ((org-agenda-skip-unavailable-files nil)
18757 (file (or file buffer-file-name
18758 (user-error "Current buffer does not visit a file")))
18759 (true-file (file-truename file))
18760 (afile (abbreviate-file-name file))
18761 (files (delq nil (mapcar
18762 (lambda (x)
18763 (unless (equal true-file
18764 (file-truename x))
18766 (org-agenda-files t)))))
18767 (if (not (= (length files) (length (org-agenda-files t))))
18768 (progn
18769 (org-store-new-agenda-file-list files)
18770 (org-install-agenda-files-menu)
18771 (message "Removed from Org Agenda list: %s" afile))
18772 (message "File was not in list: %s (not removed)" afile))))
18774 (defun org-file-menu-entry (file)
18775 (vector file (list 'find-file file) t))
18777 (defun org-check-agenda-file (file)
18778 "Make sure FILE exists. If not, ask user what to do."
18779 (unless (file-exists-p file)
18780 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18781 (abbreviate-file-name file))
18782 (let ((r (downcase (read-char-exclusive))))
18783 (cond
18784 ((equal r ?r)
18785 (org-remove-file file)
18786 (throw 'nextfile t))
18787 (t (user-error "Abort"))))))
18789 (defun org-get-agenda-file-buffer (file)
18790 "Get an agenda buffer visiting FILE.
18791 If the buffer needs to be created, add it to the list of buffers
18792 which might be released later."
18793 (let ((buf (org-find-base-buffer-visiting file)))
18794 (if buf
18795 buf ; just return it
18796 ;; Make a new buffer and remember it
18797 (setq buf (find-file-noselect file))
18798 (when buf (push buf org-agenda-new-buffers))
18799 buf)))
18801 (defun org-release-buffers (blist)
18802 "Release all buffers in list, asking the user for confirmation when needed.
18803 When a buffer is unmodified, it is just killed. When modified, it is saved
18804 \(if the user agrees) and then killed."
18805 (let (file)
18806 (dolist (buf blist)
18807 (setq file (buffer-file-name buf))
18808 (when (and (buffer-modified-p buf)
18809 file
18810 (y-or-n-p (format "Save file %s? " file)))
18811 (with-current-buffer buf (save-buffer)))
18812 (kill-buffer buf))))
18814 (defun org-agenda-prepare-buffers (files)
18815 "Create buffers for all agenda files, protect archived trees and comments."
18816 (interactive)
18817 (let ((pa '(:org-archived t))
18818 (pc '(:org-comment t))
18819 (pall '(:org-archived t :org-comment t))
18820 (inhibit-read-only t)
18821 (org-inhibit-startup org-agenda-inhibit-startup)
18822 (rea (concat ":" org-archive-tag ":"))
18823 re pos)
18824 (setq org-tag-alist-for-agenda nil
18825 org-tag-groups-alist-for-agenda nil)
18826 (save-excursion
18827 (save-restriction
18828 (dolist (file files)
18829 (catch 'nextfile
18830 (if (bufferp file)
18831 (set-buffer file)
18832 (org-check-agenda-file file)
18833 (set-buffer (org-get-agenda-file-buffer file)))
18834 (widen)
18835 (org-set-regexps-and-options 'tags-only)
18836 (setq pos (point))
18837 (or (memq 'category org-agenda-ignore-properties)
18838 (org-refresh-category-properties))
18839 (or (memq 'stats org-agenda-ignore-properties)
18840 (org-refresh-stats-properties))
18841 (or (memq 'effort org-agenda-ignore-properties)
18842 (org-refresh-effort-properties))
18843 (or (memq 'appt org-agenda-ignore-properties)
18844 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18845 (setq org-todo-keywords-for-agenda
18846 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18847 (setq org-done-keywords-for-agenda
18848 (append org-done-keywords-for-agenda org-done-keywords))
18849 (setq org-todo-keyword-alist-for-agenda
18850 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18851 (setq org-tag-alist-for-agenda
18852 (org-uniquify
18853 (append org-tag-alist-for-agenda
18854 org-current-tag-alist)))
18855 ;; Merge current file's tag groups into global
18856 ;; `org-tag-groups-alist-for-agenda'.
18857 (when org-group-tags
18858 (dolist (alist org-tag-groups-alist)
18859 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18860 (if old
18861 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18862 (push alist org-tag-groups-alist-for-agenda)))))
18863 (org-with-silent-modifications
18864 (save-excursion
18865 (remove-text-properties (point-min) (point-max) pall)
18866 (when org-agenda-skip-archived-trees
18867 (goto-char (point-min))
18868 (while (re-search-forward rea nil t)
18869 (when (org-at-heading-p t)
18870 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18871 (goto-char (point-min))
18872 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18873 (while (re-search-forward re nil t)
18874 (when (save-match-data (org-in-commented-heading-p t))
18875 (add-text-properties
18876 (match-beginning 0) (org-end-of-subtree t) pc)))))
18877 (goto-char pos)))))
18878 (setq org-todo-keywords-for-agenda
18879 (org-uniquify org-todo-keywords-for-agenda))
18880 (setq org-todo-keyword-alist-for-agenda
18881 (org-uniquify org-todo-keyword-alist-for-agenda))))
18884 ;;;; CDLaTeX minor mode
18886 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18887 "Keymap for the minor `org-cdlatex-mode'.")
18889 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18890 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18891 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18892 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18893 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18895 (defvar org-cdlatex-texmathp-advice-is-done nil
18896 "Flag remembering if we have applied the advice to texmathp already.")
18898 (define-minor-mode org-cdlatex-mode
18899 "Toggle the minor `org-cdlatex-mode'.
18900 This mode supports entering LaTeX environment and math in LaTeX fragments
18901 in Org mode.
18902 \\{org-cdlatex-mode-map}"
18903 nil " OCDL" nil
18904 (when org-cdlatex-mode
18905 (require 'cdlatex)
18906 (run-hooks 'cdlatex-mode-hook)
18907 (cdlatex-compute-tables))
18908 (unless org-cdlatex-texmathp-advice-is-done
18909 (setq org-cdlatex-texmathp-advice-is-done t)
18910 (defadvice texmathp (around org-math-always-on activate)
18911 "Always return t in Org buffers.
18912 This is because we want to insert math symbols without dollars even outside
18913 the LaTeX math segments. If Org mode thinks that point is actually inside
18914 an embedded LaTeX fragment, let `texmathp' do its job.
18915 `\\[org-cdlatex-mode-map]'"
18916 (interactive)
18917 (let (p)
18918 (cond
18919 ((not (derived-mode-p 'org-mode)) ad-do-it)
18920 ((eq this-command 'cdlatex-math-symbol)
18921 (setq ad-return-value t
18922 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18924 (let ((p (org-inside-LaTeX-fragment-p)))
18925 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18926 (setq ad-return-value t
18927 texmathp-why '("Org mode embedded math" . 0))
18928 (when p ad-do-it)))))))))
18930 (defun turn-on-org-cdlatex ()
18931 "Unconditionally turn on `org-cdlatex-mode'."
18932 (org-cdlatex-mode 1))
18934 (defun org-try-cdlatex-tab ()
18935 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18936 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18937 - inside a LaTeX fragment, or
18938 - after the first word in a line, where an abbreviation expansion could
18939 insert a LaTeX environment."
18940 (when org-cdlatex-mode
18941 (cond
18942 ;; Before any word on the line: No expansion possible.
18943 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18944 ;; Just after first word on the line: Expand it. Make sure it
18945 ;; cannot happen on headlines, though.
18946 ((save-excursion
18947 (skip-chars-backward "a-zA-Z0-9*")
18948 (skip-chars-backward " \t")
18949 (and (bolp) (not (org-at-heading-p))))
18950 (cdlatex-tab) t)
18951 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18953 (defun org-cdlatex-underscore-caret (&optional _arg)
18954 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18955 Revert to the normal definition outside of these fragments."
18956 (interactive "P")
18957 (if (org-inside-LaTeX-fragment-p)
18958 (call-interactively 'cdlatex-sub-superscript)
18959 (let (org-cdlatex-mode)
18960 (call-interactively (key-binding (vector last-input-event))))))
18962 (defun org-cdlatex-math-modify (&optional _arg)
18963 "Execute `cdlatex-math-modify' in LaTeX fragments.
18964 Revert to the normal definition outside of these fragments."
18965 (interactive "P")
18966 (if (org-inside-LaTeX-fragment-p)
18967 (call-interactively 'cdlatex-math-modify)
18968 (let (org-cdlatex-mode)
18969 (call-interactively (key-binding (vector last-input-event))))))
18971 (defun org-cdlatex-environment-indent (&optional environment item)
18972 "Execute `cdlatex-environment' and indent the inserted environment.
18974 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18976 The inserted environment is indented to current indentation
18977 unless point is at the beginning of the line, in which the
18978 environment remains unintended."
18979 (interactive)
18980 ;; cdlatex-environment always return nil. Therefore, capture output
18981 ;; first and determine if an environment was selected.
18982 (let* ((beg (point-marker))
18983 (end (copy-marker (point) t))
18984 (inserted (progn
18985 (ignore-errors (cdlatex-environment environment item))
18986 (< beg end)))
18987 ;; Figure out how many lines to move forward after the
18988 ;; environment has been inserted.
18989 (lines (when inserted
18990 (save-excursion
18991 (- (cl-loop while (< beg (point))
18992 with x = 0
18993 do (forward-line -1)
18994 (cl-incf x)
18995 finally return x)
18996 (if (progn (goto-char beg)
18997 (and (progn (skip-chars-forward " \t") (eolp))
18998 (progn (skip-chars-backward " \t") (bolp))))
18999 1 0)))))
19000 (env (org-trim (delete-and-extract-region beg end))))
19001 (when inserted
19002 ;; Get indentation of next line unless at column 0.
19003 (let ((ind (if (bolp) 0
19004 (save-excursion
19005 (org-return-indent)
19006 (prog1 (org-get-indentation)
19007 (when (progn (skip-chars-forward " \t") (eolp))
19008 (delete-region beg (point)))))))
19009 (bol (progn (skip-chars-backward " \t") (bolp))))
19010 ;; Insert a newline before environment unless at column zero
19011 ;; to "escape" the current line. Insert a newline if
19012 ;; something is one the same line as \end{ENVIRONMENT}.
19013 (insert
19014 (concat (unless bol "\n") env
19015 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
19016 (unless (zerop ind)
19017 (save-excursion
19018 (goto-char beg)
19019 (while (< (point) end)
19020 (unless (eolp) (indent-line-to ind))
19021 (forward-line))))
19022 (goto-char beg)
19023 (forward-line lines)
19024 (indent-line-to ind)))
19025 (set-marker beg nil)
19026 (set-marker end nil)))
19029 ;;;; LaTeX fragments
19031 (defun org-inside-LaTeX-fragment-p ()
19032 "Test if point is inside a LaTeX fragment.
19033 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19034 sequence appearing also before point.
19035 Even though the matchers for math are configurable, this function assumes
19036 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19037 delimiters are skipped when they have been removed by customization.
19038 The return value is nil, or a cons cell with the delimiter and the
19039 position of this delimiter.
19041 This function does a reasonably good job, but can locally be fooled by
19042 for example currency specifications. For example it will assume being in
19043 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19044 fragments that are properly closed, but during editing, we have to live
19045 with the uncertainty caused by missing closing delimiters. This function
19046 looks only before point, not after."
19047 (catch 'exit
19048 (let ((pos (point))
19049 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19050 (lim (progn
19051 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19052 (point)))
19053 dd-on str (start 0) m re)
19054 (goto-char pos)
19055 (when dodollar
19056 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19057 re (nth 1 (assoc "$" org-latex-regexps)))
19058 (while (string-match re str start)
19059 (cond
19060 ((= (match-end 0) (length str))
19061 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19062 ((= (match-end 0) (- (length str) 5))
19063 (throw 'exit nil))
19064 (t (setq start (match-end 0))))))
19065 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19066 (goto-char pos)
19067 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19068 (and (match-beginning 2) (throw 'exit nil))
19069 ;; count $$
19070 (while (re-search-backward "\\$\\$" lim t)
19071 (setq dd-on (not dd-on)))
19072 (goto-char pos)
19073 (when dd-on (cons "$$" m))))))
19075 (defun org-inside-latex-macro-p ()
19076 "Is point inside a LaTeX macro or its arguments?"
19077 (save-match-data
19078 (org-in-regexp
19079 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19081 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19082 "Build an overlay between BEG and END using IMAGE file.
19083 Argument IMAGETYPE is the extension of the displayed image,
19084 as a string. It defaults to \"png\"."
19085 (let ((ov (make-overlay beg end))
19086 (imagetype (or (intern imagetype) 'png)))
19087 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19088 (overlay-put ov 'evaporate t)
19089 (overlay-put ov
19090 'modification-hooks
19091 (list (lambda (o _flag _beg _end &optional _l)
19092 (delete-overlay o))))
19093 (overlay-put ov
19094 'display
19095 (list 'image :type imagetype :file image :ascent 'center))))
19097 (defun org--list-latex-overlays (&optional beg end)
19098 "List all Org LaTeX overlays in current buffer.
19099 Limit to overlays between BEG and END when those are provided."
19100 (cl-remove-if-not
19101 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19102 (overlays-in (or beg (point-min)) (or end (point-max)))))
19104 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19105 "Remove all overlays with LaTeX fragment images in current buffer.
19106 When optional arguments BEG and END are non-nil, remove all
19107 overlays between them instead. Return a non-nil value when some
19108 overlays were removed, nil otherwise."
19109 (let ((overlays (org--list-latex-overlays beg end)))
19110 (mapc #'delete-overlay overlays)
19111 overlays))
19113 (defun org-toggle-latex-fragment (&optional arg)
19114 "Preview the LaTeX fragment at point, or all locally or globally.
19116 If the cursor is on a LaTeX fragment, create the image and overlay
19117 it over the source code, if there is none. Remove it otherwise.
19118 If there is no fragment at point, display all fragments in the
19119 current section.
19121 With prefix ARG, preview or clear image for all fragments in the
19122 current subtree or in the whole buffer when used before the first
19123 headline. With a prefix ARG `\\[universal-argument] \
19124 \\[universal-argument]' preview or clear images
19125 for all fragments in the buffer."
19126 (interactive "P")
19127 (when (display-graphic-p)
19128 (catch 'exit
19129 (save-excursion
19130 (let (beg end msg)
19131 (cond
19132 ((or (equal arg '(16))
19133 (and (equal arg '(4))
19134 (org-with-limited-levels (org-before-first-heading-p))))
19135 (if (org-remove-latex-fragment-image-overlays)
19136 (progn (message "LaTeX fragments images removed from buffer")
19137 (throw 'exit nil))
19138 (setq msg "Creating images for buffer...")))
19139 ((equal arg '(4))
19140 (org-with-limited-levels (org-back-to-heading t))
19141 (setq beg (point))
19142 (setq end (progn (org-end-of-subtree t) (point)))
19143 (if (org-remove-latex-fragment-image-overlays beg end)
19144 (progn
19145 (message "LaTeX fragment images removed from subtree")
19146 (throw 'exit nil))
19147 (setq msg "Creating images for subtree...")))
19148 ((let ((datum (org-element-context)))
19149 (when (memq (org-element-type datum)
19150 '(latex-environment latex-fragment))
19151 (setq beg (org-element-property :begin datum))
19152 (setq end (org-element-property :end datum))
19153 (if (org-remove-latex-fragment-image-overlays beg end)
19154 (progn (message "LaTeX fragment image removed")
19155 (throw 'exit nil))
19156 (setq msg "Creating image...")))))
19158 (org-with-limited-levels
19159 (setq beg (if (org-at-heading-p) (line-beginning-position)
19160 (outline-previous-heading)
19161 (point)))
19162 (setq end (progn (outline-next-heading) (point)))
19163 (if (org-remove-latex-fragment-image-overlays beg end)
19164 (progn
19165 (message "LaTeX fragment images removed from section")
19166 (throw 'exit nil))
19167 (setq msg "Creating images for section...")))))
19168 (let ((file (buffer-file-name (buffer-base-buffer))))
19169 (org-format-latex
19170 (concat org-preview-latex-image-directory "org-ltximg")
19171 beg end
19172 ;; Emacs cannot overlay images from remote hosts. Create
19173 ;; it in `temporary-file-directory' instead.
19174 (if (or (not file) (file-remote-p file))
19175 temporary-file-directory
19176 default-directory)
19177 'overlays msg 'forbuffer org-preview-latex-default-process))
19178 (message (concat msg "done")))))))
19180 (defun org-format-latex
19181 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19182 "Replace LaTeX fragments with links to an image.
19184 The function takes care of creating the replacement image.
19186 Only consider fragments between BEG and END when those are
19187 provided.
19189 When optional argument OVERLAYS is non-nil, display the image on
19190 top of the fragment instead of replacing it.
19192 PROCESSING-TYPE is the conversion method to use, as a symbol.
19194 Some of the options can be changed using the variable
19195 `org-format-latex-options', which see."
19196 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19197 (unless (eq processing-type 'verbatim)
19198 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19199 (cnt 0)
19200 checkdir-flag)
19201 (goto-char (or beg (point-min)))
19202 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19203 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19204 (overlay-recenter (or end (point-max))))
19205 (while (re-search-forward math-regexp end t)
19206 (unless (and overlays
19207 (eq (get-char-property (point) 'org-overlay-type)
19208 'org-latex-overlay))
19209 (let* ((context (org-element-context))
19210 (type (org-element-type context)))
19211 (when (memq type '(latex-environment latex-fragment))
19212 (let ((block-type (eq type 'latex-environment))
19213 (value (org-element-property :value context))
19214 (beg (org-element-property :begin context))
19215 (end (save-excursion
19216 (goto-char (org-element-property :end context))
19217 (skip-chars-backward " \r\t\n")
19218 (point))))
19219 (cond
19220 ((eq processing-type 'mathjax)
19221 ;; Prepare for MathJax processing.
19222 (if (not (string-match "\\`\\$\\$?" value))
19223 (goto-char end)
19224 (delete-region beg end)
19225 (if (string= (match-string 0 value) "$$")
19226 (insert "\\[" (substring value 2 -2) "\\]")
19227 (insert "\\(" (substring value 1 -1) "\\)"))))
19228 ((assq processing-type org-preview-latex-process-alist)
19229 ;; Process to an image.
19230 (cl-incf cnt)
19231 (goto-char beg)
19232 (let* ((processing-info
19233 (cdr (assq processing-type org-preview-latex-process-alist)))
19234 (face (face-at-point))
19235 ;; Get the colors from the face at point.
19237 (let ((color (plist-get org-format-latex-options
19238 :foreground)))
19239 (if (and forbuffer (eq color 'auto))
19240 (face-attribute face :foreground nil 'default)
19241 color)))
19243 (let ((color (plist-get org-format-latex-options
19244 :background)))
19245 (if (and forbuffer (eq color 'auto))
19246 (face-attribute face :background nil 'default)
19247 color)))
19248 (hash (sha1 (prin1-to-string
19249 (list org-format-latex-header
19250 org-latex-default-packages-alist
19251 org-latex-packages-alist
19252 org-format-latex-options
19253 forbuffer value fg bg))))
19254 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19255 (absprefix (expand-file-name prefix dir))
19256 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19257 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19258 (sep (and block-type "\n\n"))
19259 (link (concat sep "[[file:" linkfile "]]" sep))
19260 (options
19261 (org-combine-plists
19262 org-format-latex-options
19263 `(:foreground ,fg :background ,bg))))
19264 (when msg (message msg cnt))
19265 (unless checkdir-flag ; Ensure the directory exists.
19266 (setq checkdir-flag t)
19267 (let ((todir (file-name-directory absprefix)))
19268 (unless (file-directory-p todir)
19269 (make-directory todir t))))
19270 (unless (file-exists-p movefile)
19271 (org-create-formula-image
19272 value movefile options forbuffer processing-type))
19273 (if overlays
19274 (progn
19275 (dolist (o (overlays-in beg end))
19276 (when (eq (overlay-get o 'org-overlay-type)
19277 'org-latex-overlay)
19278 (delete-overlay o)))
19279 (org--format-latex-make-overlay beg end movefile imagetype)
19280 (goto-char end))
19281 (delete-region beg end)
19282 (insert
19283 (org-add-props link
19284 (list 'org-latex-src
19285 (replace-regexp-in-string "\"" "" value)
19286 'org-latex-src-embed-type
19287 (if block-type 'paragraph 'character)))))))
19288 ((eq processing-type 'mathml)
19289 ;; Process to MathML.
19290 (unless (org-format-latex-mathml-available-p)
19291 (user-error "LaTeX to MathML converter not configured"))
19292 (cl-incf cnt)
19293 (when msg (message msg cnt))
19294 (goto-char beg)
19295 (delete-region beg end)
19296 (insert (org-format-latex-as-mathml
19297 value block-type prefix dir)))
19299 (error "Unknown conversion process %s for LaTeX fragments"
19300 processing-type)))))))))))
19302 (defun org-create-math-formula (latex-frag &optional mathml-file)
19303 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19304 Use `org-latex-to-mathml-convert-command'. If the conversion is
19305 sucessful, return the portion between \"<math...> </math>\"
19306 elements otherwise return nil. When MATHML-FILE is specified,
19307 write the results in to that file. When invoked as an
19308 interactive command, prompt for LATEX-FRAG, with initial value
19309 set to the current active region and echo the results for user
19310 inspection."
19311 (interactive (list (let ((frag (when (org-region-active-p)
19312 (buffer-substring-no-properties
19313 (region-beginning) (region-end)))))
19314 (read-string "LaTeX Fragment: " frag nil frag))))
19315 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19316 (let* ((tmp-in-file
19317 (let ((file (file-relative-name
19318 (make-temp-name (expand-file-name "ltxmathml-in")))))
19319 (write-region latex-frag nil file)
19320 file))
19321 (tmp-out-file (file-relative-name
19322 (make-temp-name (expand-file-name "ltxmathml-out"))))
19323 (cmd (format-spec
19324 org-latex-to-mathml-convert-command
19325 `((?j . ,(and org-latex-to-mathml-jar-file
19326 (shell-quote-argument
19327 (expand-file-name
19328 org-latex-to-mathml-jar-file))))
19329 (?I . ,(shell-quote-argument tmp-in-file))
19330 (?i . ,latex-frag)
19331 (?o . ,(shell-quote-argument tmp-out-file)))))
19332 mathml shell-command-output)
19333 (when (called-interactively-p 'any)
19334 (unless (org-format-latex-mathml-available-p)
19335 (user-error "LaTeX to MathML converter not configured")))
19336 (message "Running %s" cmd)
19337 (setq shell-command-output (shell-command-to-string cmd))
19338 (setq mathml
19339 (when (file-readable-p tmp-out-file)
19340 (with-current-buffer (find-file-noselect tmp-out-file t)
19341 (goto-char (point-min))
19342 (when (re-search-forward
19343 (concat
19344 (regexp-quote
19345 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19346 "[^>]*?>"
19347 "\\(.\\|\n\\)*"
19348 "</math>")
19349 nil t)
19350 (prog1 (match-string 0) (kill-buffer))))))
19351 (cond
19352 (mathml
19353 (setq mathml
19354 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19355 (when mathml-file
19356 (write-region mathml nil mathml-file))
19357 (when (called-interactively-p 'any)
19358 (message mathml)))
19359 ((message "LaTeX to MathML conversion failed")
19360 (message shell-command-output)))
19361 (delete-file tmp-in-file)
19362 (when (file-exists-p tmp-out-file)
19363 (delete-file tmp-out-file))
19364 mathml))
19366 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19367 prefix &optional dir)
19368 "Use `org-create-math-formula' but check local cache first."
19369 (let* ((absprefix (expand-file-name prefix dir))
19370 (print-length nil) (print-level nil)
19371 (formula-id (concat
19372 "formula-"
19373 (sha1
19374 (prin1-to-string
19375 (list latex-frag
19376 org-latex-to-mathml-convert-command)))))
19377 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19378 (formula-cache-dir (file-name-directory formula-cache)))
19380 (unless (file-directory-p formula-cache-dir)
19381 (make-directory formula-cache-dir t))
19383 (unless (file-exists-p formula-cache)
19384 (org-create-math-formula latex-frag formula-cache))
19386 (if (file-exists-p formula-cache)
19387 ;; Successful conversion. Return the link to MathML file.
19388 (org-add-props
19389 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19390 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19391 'org-latex-src-embed-type (if latex-frag-type
19392 'paragraph 'character)))
19393 ;; Failed conversion. Return the LaTeX fragment verbatim
19394 latex-frag)))
19396 (declare-function org-export-get-backend "ox" (name))
19397 (declare-function org-export--get-global-options "ox" (&optional backend))
19398 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19399 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19400 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19401 (defun org-create-formula--latex-header ()
19402 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19403 (let ((info (org-combine-plists (org-export--get-global-options
19404 (org-export-get-backend 'latex))
19405 (org-export--get-inbuffer-options
19406 (org-export-get-backend 'latex)))))
19407 (org-latex-guess-babel-language
19408 (org-latex-guess-inputenc
19409 (org-splice-latex-header
19410 org-format-latex-header
19411 org-latex-default-packages-alist
19412 org-latex-packages-alist t
19413 (plist-get info :latex-header)))
19414 info)))
19416 (defun org--get-display-dpi ()
19417 "Get the DPI of the display.
19419 Assumes that the display has the same pixel width in the
19420 horizontal and vertical directions."
19421 (if (display-graphic-p)
19422 (round (/ (display-pixel-height)
19423 (/ (display-mm-height) 25.4)))
19424 (error "Attempt to calculate the dpi of a non-graphic display")))
19426 (defun org-create-formula-image
19427 (string tofile options buffer &optional processing-type)
19428 "Create an image from LaTeX source using external processes.
19430 The LaTeX STRING is saved to a temporary LaTeX file, then
19431 converted to an image file by process PROCESSING-TYPE defined in
19432 `org-preview-latex-process-alist'. A nil value defaults to
19433 `org-preview-latex-default-process'.
19435 The generated image file is eventually moved to TOFILE.
19437 The OPTIONS argument controls the size, foreground color and
19438 background color of the generated image.
19440 When BUFFER non-nil, this function is used for LaTeX previewing.
19441 Otherwise, it is used to deal with LaTeX snippets showed in
19442 a HTML file."
19443 (let* ((processing-type (or processing-type
19444 org-preview-latex-default-process))
19445 (processing-info
19446 (cdr (assq processing-type org-preview-latex-process-alist)))
19447 (programs (plist-get processing-info :programs))
19448 (error-message (or (plist-get processing-info :message) ""))
19449 (use-xcolor (plist-get processing-info :use-xcolor))
19450 (image-input-type (plist-get processing-info :image-input-type))
19451 (image-output-type (plist-get processing-info :image-output-type))
19452 (post-clean (or (plist-get processing-info :post-clean)
19453 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19454 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19455 (latex-header (or (plist-get processing-info :latex-header)
19456 (org-create-formula--latex-header)))
19457 (latex-compiler (plist-get processing-info :latex-compiler))
19458 (image-converter (plist-get processing-info :image-converter))
19459 (tmpdir temporary-file-directory)
19460 (texfilebase (make-temp-name
19461 (expand-file-name "orgtex" tmpdir)))
19462 (texfile (concat texfilebase ".tex"))
19463 (font-height (face-attribute 'default :height nil))
19464 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19465 '(1.0 . 1.0)))
19466 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19467 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19468 (dpi (* scale (floor (if buffer font-height 140.0))))
19469 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19470 "Black"))
19471 (bg (or (plist-get options (if buffer :background :html-background))
19472 "Transparent"))
19473 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19474 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19475 (dolist (program programs)
19476 (org-check-external-command program error-message))
19477 (if use-xcolor
19478 (progn (if (eq fg 'default)
19479 (setq fg (org-latex-color :foreground))
19480 (setq fg (org-latex-color-format fg)))
19481 (if (eq bg 'default)
19482 (setq bg (org-latex-color :background))
19483 (setq bg (org-latex-color-format
19484 (if (string= bg "Transparent") "white" bg))))
19485 (with-temp-file texfile
19486 (insert latex-header)
19487 (insert "\n\\begin{document}\n"
19488 "\\definecolor{fg}{rgb}{" fg "}\n"
19489 "\\definecolor{bg}{rgb}{" bg "}\n"
19490 "\n\\pagecolor{bg}\n"
19491 "\n{\\color{fg}\n"
19492 string
19493 "\n}\n"
19494 "\n\\end{document}\n")))
19495 (if (eq fg 'default)
19496 (setq fg (org-dvipng-color :foreground))
19497 (unless (string= fg "Transparent")
19498 (setq fg (org-dvipng-color-format fg))))
19499 (if (eq bg 'default)
19500 (setq bg (org-dvipng-color :background))
19501 (unless (string= bg "Transparent")
19502 (setq bg (org-dvipng-color-format bg))))
19503 (with-temp-file texfile
19504 (insert latex-header)
19505 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19507 (let* ((err-msg (format "Please adjust '%s' part of \
19508 `org-preview-latex-process-alist'."
19509 processing-type))
19510 (image-input-file
19511 (org-compile-file
19512 texfile latex-compiler image-input-type err-msg log-buf))
19513 (image-output-file
19514 (org-compile-file
19515 image-input-file image-converter image-output-type err-msg log-buf
19516 `((?F . ,(shell-quote-argument fg))
19517 (?B . ,(shell-quote-argument bg))
19518 (?D . ,(shell-quote-argument (format "%s" dpi)))
19519 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19520 (copy-file image-output-file tofile 'replace)
19521 (dolist (e post-clean)
19522 (when (file-exists-p (concat texfilebase e))
19523 (delete-file (concat texfilebase e))))
19524 image-output-file)))
19526 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19527 "Fill a LaTeX header template TPL.
19528 In the template, the following place holders will be recognized:
19530 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19531 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19532 [PACKAGES] \\usepackage statements for PKG
19533 [NO-PACKAGES] do not include PKG
19534 [EXTRA] the string EXTRA
19535 [NO-EXTRA] do not include EXTRA
19537 For backward compatibility, if both the positive and the negative place
19538 holder is missing, the positive one (without the \"NO-\") will be
19539 assumed to be present at the end of the template.
19540 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19541 EXTRA is a string.
19542 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19543 (let (rpl (end ""))
19544 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19545 (setq rpl (if (or (match-end 1) (not def-pkg))
19546 "" (org-latex-packages-to-string def-pkg snippets-p t))
19547 tpl (replace-match rpl t t tpl))
19548 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19550 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19551 (setq rpl (if (or (match-end 1) (not pkg))
19552 "" (org-latex-packages-to-string pkg snippets-p t))
19553 tpl (replace-match rpl t t tpl))
19554 (when pkg (setq end
19555 (concat end "\n"
19556 (org-latex-packages-to-string pkg snippets-p)))))
19558 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19559 (setq rpl (if (or (match-end 1) (not extra))
19560 "" (concat extra "\n"))
19561 tpl (replace-match rpl t t tpl))
19562 (when (and extra (string-match "\\S-" extra))
19563 (setq end (concat end "\n" extra))))
19565 (if (string-match "\\S-" end)
19566 (concat tpl "\n" end)
19567 tpl)))
19569 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19570 "Turn an alist of packages into a string with the \\usepackage macros."
19571 (setq pkg (mapconcat (lambda(p)
19572 (cond
19573 ((stringp p) p)
19574 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19575 (format "%% Package %s omitted" (cadr p)))
19576 ((equal "" (car p))
19577 (format "\\usepackage{%s}" (cadr p)))
19579 (format "\\usepackage[%s]{%s}"
19580 (car p) (cadr p)))))
19582 "\n"))
19583 (if newline (concat pkg "\n") pkg))
19585 (defun org-dvipng-color (attr)
19586 "Return a RGB color specification for dvipng."
19587 (org-dvipng-color-format (face-attribute 'default attr nil)))
19589 (defun org-dvipng-color-format (color-name)
19590 "Convert COLOR-NAME to a RGB color value for dvipng."
19591 (apply #'format "rgb %s %s %s"
19592 (mapcar 'org-normalize-color
19593 (color-values color-name))))
19595 (defun org-latex-color (attr)
19596 "Return a RGB color for the LaTeX color package."
19597 (org-latex-color-format (face-attribute 'default attr nil)))
19599 (defun org-latex-color-format (color-name)
19600 "Convert COLOR-NAME to a RGB color value."
19601 (apply #'format "%s,%s,%s"
19602 (mapcar 'org-normalize-color
19603 (color-values color-name))))
19605 (defun org-normalize-color (value)
19606 "Return string to be used as color value for an RGB component."
19607 (format "%g" (/ value 65535.0)))
19611 ;; Image display
19613 (defvar-local org-inline-image-overlays nil)
19615 (defun org-toggle-inline-images (&optional include-linked)
19616 "Toggle the display of inline images.
19617 INCLUDE-LINKED is passed to `org-display-inline-images'."
19618 (interactive "P")
19619 (if org-inline-image-overlays
19620 (progn
19621 (org-remove-inline-images)
19622 (when (called-interactively-p 'interactive)
19623 (message "Inline image display turned off")))
19624 (org-display-inline-images include-linked)
19625 (when (called-interactively-p 'interactive)
19626 (message (if org-inline-image-overlays
19627 (format "%d images displayed inline"
19628 (length org-inline-image-overlays))
19629 "No images to display inline")))))
19631 (defun org-redisplay-inline-images ()
19632 "Refresh the display of inline images."
19633 (interactive)
19634 (if (not org-inline-image-overlays)
19635 (org-toggle-inline-images)
19636 (org-toggle-inline-images)
19637 (org-toggle-inline-images)))
19639 (defun org-display-inline-images (&optional include-linked refresh beg end)
19640 "Display inline images.
19642 An inline image is a link which follows either of these
19643 conventions:
19645 1. Its path is a file with an extension matching return value
19646 from `image-file-name-regexp' and it has no contents.
19648 2. Its description consists in a single link of the previous
19649 type.
19651 When optional argument INCLUDE-LINKED is non-nil, also links with
19652 a text description part will be inlined. This can be nice for
19653 a quick look at those images, but it does not reflect what
19654 exported files will look like.
19656 When optional argument REFRESH is non-nil, refresh existing
19657 images between BEG and END. This will create new image displays
19658 only if necessary. BEG and END default to the buffer
19659 boundaries."
19660 (interactive "P")
19661 (when (display-graphic-p)
19662 (unless refresh
19663 (org-remove-inline-images)
19664 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19665 (org-with-wide-buffer
19666 (goto-char (or beg (point-min)))
19667 (let ((case-fold-search t)
19668 (file-extension-re (image-file-name-regexp)))
19669 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19670 (let ((link (save-match-data (org-element-context))))
19671 ;; Check if we're at an inline image.
19672 (when (and (equal (org-element-property :type link) "file")
19673 (or include-linked
19674 (not (org-element-property :contents-begin link)))
19675 (let ((parent (org-element-property :parent link)))
19676 (or (not (eq (org-element-type parent) 'link))
19677 (not (cdr (org-element-contents parent)))))
19678 (string-match-p file-extension-re
19679 (org-element-property :path link)))
19680 (let ((file (expand-file-name
19681 (org-link-unescape
19682 (org-element-property :path link)))))
19683 (when (file-exists-p file)
19684 (let ((width
19685 ;; Apply `org-image-actual-width' specifications.
19686 (cond
19687 ((not (image-type-available-p 'imagemagick)) nil)
19688 ((eq org-image-actual-width t) nil)
19689 ((listp org-image-actual-width)
19691 ;; First try to find a width among
19692 ;; attributes associated to the paragraph
19693 ;; containing link.
19694 (let ((paragraph
19695 (let ((e link))
19696 (while (and (setq e (org-element-property
19697 :parent e))
19698 (not (eq (org-element-type e)
19699 'paragraph))))
19700 e)))
19701 (when paragraph
19702 (save-excursion
19703 (goto-char (org-element-property :begin paragraph))
19704 (when
19705 (re-search-forward
19706 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19707 (org-element-property
19708 :post-affiliated paragraph)
19710 (string-to-number (match-string 1))))))
19711 ;; Otherwise, fall-back to provided number.
19712 (car org-image-actual-width)))
19713 ((numberp org-image-actual-width)
19714 org-image-actual-width)))
19715 (old (get-char-property-and-overlay
19716 (org-element-property :begin link)
19717 'org-image-overlay)))
19718 (if (and (car-safe old) refresh)
19719 (image-refresh (overlay-get (cdr old) 'display))
19720 (let ((image (create-image file
19721 (and width 'imagemagick)
19723 :width width)))
19724 (when image
19725 (let* ((link
19726 ;; If inline image is the description
19727 ;; of another link, be sure to
19728 ;; consider the latter as the one to
19729 ;; apply the overlay on.
19730 (let ((parent
19731 (org-element-property :parent link)))
19732 (if (eq (org-element-type parent) 'link)
19733 parent
19734 link)))
19735 (ov (make-overlay
19736 (org-element-property :begin link)
19737 (progn
19738 (goto-char
19739 (org-element-property :end link))
19740 (skip-chars-backward " \t")
19741 (point)))))
19742 (overlay-put ov 'display image)
19743 (overlay-put ov 'face 'default)
19744 (overlay-put ov 'org-image-overlay t)
19745 (overlay-put
19746 ov 'modification-hooks
19747 (list 'org-display-inline-remove-overlay))
19748 (push ov org-inline-image-overlays)))))))))))))))
19750 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19751 "Remove inline-display overlay if a corresponding region is modified."
19752 (let ((inhibit-modification-hooks t))
19753 (when (and ov after)
19754 (delete ov org-inline-image-overlays)
19755 (delete-overlay ov))))
19757 (defun org-remove-inline-images ()
19758 "Remove inline display of images."
19759 (interactive)
19760 (mapc #'delete-overlay org-inline-image-overlays)
19761 (setq org-inline-image-overlays nil))
19763 ;;;; Key bindings
19765 ;; Outline functions from `outline-mode-prefix-map'
19766 ;; that can be remapped in Org:
19767 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19768 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19769 (define-key org-mode-map [remap outline-forward-same-level]
19770 'org-forward-heading-same-level)
19771 (define-key org-mode-map [remap outline-backward-same-level]
19772 'org-backward-heading-same-level)
19773 (define-key org-mode-map [remap outline-show-branches]
19774 'org-kill-note-or-show-branches)
19775 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19776 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19777 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19778 (define-key org-mode-map [remap outline-next-visible-heading]
19779 'org-next-visible-heading)
19780 (define-key org-mode-map [remap outline-previous-visible-heading]
19781 'org-previous-visible-heading)
19782 (define-key org-mode-map [remap show-children] 'org-show-children)
19784 ;; Outline functions from `outline-mode-prefix-map' that can not
19785 ;; be remapped in Org:
19787 ;; - the column "key binding" shows whether the Outline function is still
19788 ;; available in Org mode on the same key that it has been bound to in
19789 ;; Outline mode:
19790 ;; - "overridden": key used for a different functionality in Org mode
19791 ;; - else: key still bound to the same Outline function in Org mode
19793 ;; | Outline function | key binding | Org replacement |
19794 ;; |------------------------------------+-------------+--------------------------|
19795 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19796 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19797 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19798 ;; | `show-entry' | overridden | no replacement |
19799 ;; | `show-branches' | `C-c C-k' | still same function |
19800 ;; | `show-subtree' | overridden | visibility cycling |
19801 ;; | `show-all' | overridden | no replacement |
19802 ;; | `hide-subtree' | overridden | visibility cycling |
19803 ;; | `hide-body' | overridden | no replacement |
19804 ;; | `hide-entry' | overridden | visibility cycling |
19805 ;; | `hide-leaves' | overridden | no replacement |
19806 ;; | `hide-sublevels' | overridden | no replacement |
19807 ;; | `hide-other' | overridden | no replacement |
19809 ;; Make `C-c C-x' a prefix key
19810 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19812 ;; TAB key with modifiers
19813 (org-defkey org-mode-map "\C-i" 'org-cycle)
19814 (org-defkey org-mode-map [(tab)] 'org-cycle)
19815 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19816 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19817 ;; The following line is necessary under Suse GNU/Linux
19818 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19819 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19820 (define-key org-mode-map [backtab] 'org-shifttab)
19822 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19823 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19824 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19826 ;; Cursor keys with modifiers
19827 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19828 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19829 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19830 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19832 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19833 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19834 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19835 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19836 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19837 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19839 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19840 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19841 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19842 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19844 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19845 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19846 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19847 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19849 ;; Babel keys
19850 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19851 (dolist (pair org-babel-key-bindings)
19852 (define-key org-babel-map (car pair) (cdr pair)))
19854 ;;; Extra keys for tty access.
19855 ;; We only set them when really needed because otherwise the
19856 ;; menus don't show the simple keys
19858 (when (or org-use-extra-keys (not window-system))
19859 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19860 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19861 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19862 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19863 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19864 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19865 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19866 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19867 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19868 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19869 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19870 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19871 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19872 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19873 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19874 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19875 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19876 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19877 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19878 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19879 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19880 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19881 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19882 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19883 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19884 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19885 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19886 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19888 ;; All the other keys
19890 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19891 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19892 (if (boundp 'narrow-map)
19893 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19894 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19895 (if (boundp 'narrow-map)
19896 (org-defkey narrow-map "b" 'org-narrow-to-block)
19897 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19898 (if (boundp 'narrow-map)
19899 (org-defkey narrow-map "e" 'org-narrow-to-element)
19900 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19901 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19902 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19903 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19904 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19905 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19906 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19907 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19908 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19909 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19910 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19911 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19912 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19913 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19914 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19915 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19916 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19917 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19918 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19919 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19920 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19921 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19922 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19923 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19924 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19925 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19926 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19927 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19928 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19929 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19930 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19931 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19932 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19933 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19934 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19935 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19936 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19937 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19938 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19939 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19940 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19941 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19942 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19943 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19944 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19945 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19946 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19947 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19948 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19949 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19950 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19951 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19952 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19953 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19954 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19955 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19956 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19957 (org-defkey org-mode-map "\C-c^" 'org-sort)
19958 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19959 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19960 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19961 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19962 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19963 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19964 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19965 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19966 (org-defkey org-mode-map "\C-m" 'org-return)
19967 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19968 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19969 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19970 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19971 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19972 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19973 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19974 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19975 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19976 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19977 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19978 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19979 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19980 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19981 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19982 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19983 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19984 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19985 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19986 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19987 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19988 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19989 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19990 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19991 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19993 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19994 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19995 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19997 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19998 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19999 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
20000 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
20001 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
20002 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
20003 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
20004 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
20005 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
20006 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
20007 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
20008 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
20009 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
20010 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
20011 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
20012 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
20013 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
20014 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
20015 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
20016 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
20017 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
20018 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
20020 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
20021 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
20022 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
20023 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
20024 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
20026 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20028 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20030 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20031 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20033 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20036 (defconst org-speed-commands-default
20038 ("Outline Navigation")
20039 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20040 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20041 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20042 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20043 ("F" . org-next-block)
20044 ("B" . org-previous-block)
20045 ("u" . (org-speed-move-safe 'outline-up-heading))
20046 ("j" . org-goto)
20047 ("g" . (org-refile t))
20048 ("Outline Visibility")
20049 ("c" . org-cycle)
20050 ("C" . org-shifttab)
20051 (" " . org-display-outline-path)
20052 ("s" . org-narrow-to-subtree)
20053 ("=" . org-columns)
20054 ("Outline Structure Editing")
20055 ("U" . org-metaup)
20056 ("D" . org-metadown)
20057 ("r" . org-metaright)
20058 ("l" . org-metaleft)
20059 ("R" . org-shiftmetaright)
20060 ("L" . org-shiftmetaleft)
20061 ("i" . (progn (forward-char 1) (call-interactively
20062 'org-insert-heading-respect-content)))
20063 ("^" . org-sort)
20064 ("w" . org-refile)
20065 ("a" . org-archive-subtree-default-with-confirmation)
20066 ("@" . org-mark-subtree)
20067 ("#" . org-toggle-comment)
20068 ("Clock Commands")
20069 ("I" . org-clock-in)
20070 ("O" . org-clock-out)
20071 ("Meta Data Editing")
20072 ("t" . org-todo)
20073 ("," . (org-priority))
20074 ("0" . (org-priority ?\ ))
20075 ("1" . (org-priority ?A))
20076 ("2" . (org-priority ?B))
20077 ("3" . (org-priority ?C))
20078 (":" . org-set-tags-command)
20079 ("e" . org-set-effort)
20080 ("E" . org-inc-effort)
20081 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20082 (org-entry-put (point) "APPT_WARNTIME" m)))
20083 ("Agenda Views etc")
20084 ("v" . org-agenda)
20085 ("/" . org-sparse-tree)
20086 ("Misc")
20087 ("o" . org-open-at-point)
20088 ("?" . org-speed-command-help)
20089 ("<" . (org-agenda-set-restriction-lock 'subtree))
20090 (">" . (org-agenda-remove-restriction-lock))
20092 "The default speed commands.")
20094 (defun org-print-speed-command (e)
20095 (if (> (length (car e)) 1)
20096 (progn
20097 (princ "\n")
20098 (princ (car e))
20099 (princ "\n")
20100 (princ (make-string (length (car e)) ?-))
20101 (princ "\n"))
20102 (princ (car e))
20103 (princ " ")
20104 (if (symbolp (cdr e))
20105 (princ (symbol-name (cdr e)))
20106 (prin1 (cdr e)))
20107 (princ "\n")))
20109 (defun org-speed-command-help ()
20110 "Show the available speed commands."
20111 (interactive)
20112 (if (not org-use-speed-commands)
20113 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20114 (with-output-to-temp-buffer "*Help*"
20115 (princ "User-defined Speed commands\n===========================\n")
20116 (mapc #'org-print-speed-command org-speed-commands-user)
20117 (princ "\n")
20118 (princ "Built-in Speed commands\n=======================\n")
20119 (mapc #'org-print-speed-command org-speed-commands-default))
20120 (with-current-buffer "*Help*"
20121 (setq truncate-lines t))))
20123 (defun org-speed-move-safe (cmd)
20124 "Execute CMD, but make sure that the cursor always ends up in a headline.
20125 If not, return to the original position and throw an error."
20126 (interactive)
20127 (let ((pos (point)))
20128 (call-interactively cmd)
20129 (unless (and (bolp) (org-at-heading-p))
20130 (goto-char pos)
20131 (error "Boundary reached while executing %s" cmd))))
20133 (defvar org-self-insert-command-undo-counter 0)
20135 (defvar org-table-auto-blank-field) ; defined in org-table.el
20136 (defvar org-speed-command nil)
20138 (defun org-speed-command-activate (keys)
20139 "Hook for activating single-letter speed commands.
20140 `org-speed-commands-default' specifies a minimal command set.
20141 Use `org-speed-commands-user' for further customization."
20142 (when (or (and (bolp) (looking-at org-outline-regexp))
20143 (and (functionp org-use-speed-commands)
20144 (funcall org-use-speed-commands)))
20145 (cdr (assoc keys (append org-speed-commands-user
20146 org-speed-commands-default)))))
20148 (defun org-babel-speed-command-activate (keys)
20149 "Hook for activating single-letter code block commands."
20150 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20151 (cdr (assoc keys org-babel-key-bindings))))
20153 (defcustom org-speed-command-hook
20154 '(org-speed-command-default-hook org-babel-speed-command-hook)
20155 "Hook for activating speed commands at strategic locations.
20156 Hook functions are called in sequence until a valid handler is
20157 found.
20159 Each hook takes a single argument, a user-pressed command key
20160 which is also a `self-insert-command' from the global map.
20162 Within the hook, examine the cursor position and the command key
20163 and return nil or a valid handler as appropriate. Handler could
20164 be one of an interactive command, a function, or a form.
20166 Set `org-use-speed-commands' to non-nil value to enable this
20167 hook. The default setting is `org-speed-command-activate'."
20168 :group 'org-structure
20169 :version "24.1"
20170 :type 'hook)
20172 (defun org-self-insert-command (N)
20173 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20174 If the cursor is in a table looking at whitespace, the whitespace is
20175 overwritten, and the table is not marked as requiring realignment."
20176 (interactive "p")
20177 (org-check-before-invisible-edit 'insert)
20178 (cond
20179 ((and org-use-speed-commands
20180 (let ((kv (this-command-keys-vector)))
20181 (setq org-speed-command
20182 (run-hook-with-args-until-success
20183 'org-speed-command-hook
20184 (make-string 1 (aref kv (1- (length kv))))))))
20185 (cond
20186 ((commandp org-speed-command)
20187 (setq this-command org-speed-command)
20188 (call-interactively org-speed-command))
20189 ((functionp org-speed-command)
20190 (funcall org-speed-command))
20191 ((and org-speed-command (listp org-speed-command))
20192 (eval org-speed-command))
20193 (t (let (org-use-speed-commands)
20194 (call-interactively 'org-self-insert-command)))))
20195 ((and
20196 (org-at-table-p)
20197 (progn
20198 ;; Check if we blank the field, and if that triggers align.
20199 (and (featurep 'org-table) org-table-auto-blank-field
20200 (memq last-command
20201 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20202 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20203 ;; Got extra space, this field does not determine
20204 ;; column width.
20205 (let (org-table-may-need-update) (org-table-blank-field))
20206 ;; No extra space, this field may determine column
20207 ;; width.
20208 (org-table-blank-field)))
20210 (eq N 1)
20211 (looking-at "[^|\n]* \\( \\)|"))
20212 ;; There is room for insertion without re-aligning the table.
20213 (delete-region (match-beginning 1) (match-end 1))
20214 (self-insert-command N))
20216 (setq org-table-may-need-update t)
20217 (self-insert-command N)
20218 (org-fix-tags-on-the-fly)
20219 (when org-self-insert-cluster-for-undo
20220 (if (not (eq last-command 'org-self-insert-command))
20221 (setq org-self-insert-command-undo-counter 1)
20222 (if (>= org-self-insert-command-undo-counter 20)
20223 (setq org-self-insert-command-undo-counter 1)
20224 (and (> org-self-insert-command-undo-counter 0)
20225 buffer-undo-list (listp buffer-undo-list)
20226 (not (cadr buffer-undo-list)) ; remove nil entry
20227 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20228 (setq org-self-insert-command-undo-counter
20229 (1+ org-self-insert-command-undo-counter))))))))
20231 (defun org-check-before-invisible-edit (kind)
20232 "Check is editing if kind KIND would be dangerous with invisible text around.
20233 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20234 ;; First, try to get out of here as quickly as possible, to reduce overhead
20235 (when (and org-catch-invisible-edits
20236 (or (not (boundp 'visible-mode)) (not visible-mode))
20237 (or (get-char-property (point) 'invisible)
20238 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20239 ;; OK, we need to take a closer look
20240 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20241 (invisible-before-point (unless (bobp) (get-char-property
20242 (1- (point)) 'invisible)))
20243 (border-and-ok-direction
20245 ;; Check if we are acting predictably before invisible text
20246 (and invisible-at-point (not invisible-before-point)
20247 (memq kind '(insert delete-backward)))
20248 ;; Check if we are acting predictably after invisible text
20249 ;; This works not well, and I have turned it off. It seems
20250 ;; better to always show and stop after invisible text.
20251 ;; (and (not invisible-at-point) invisible-before-point
20252 ;; (memq kind '(insert delete)))
20254 (when (or (memq invisible-at-point '(outline org-hide-block t))
20255 (memq invisible-before-point '(outline org-hide-block t)))
20256 (when (eq org-catch-invisible-edits 'error)
20257 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20258 (if (and org-custom-properties-overlays
20259 (y-or-n-p "Display invisible properties in this buffer? "))
20260 (org-toggle-custom-properties-visibility)
20261 ;; Make the area visible
20262 (save-excursion
20263 (when invisible-before-point
20264 (goto-char (previous-single-char-property-change
20265 (point) 'invisible)))
20266 (outline-show-subtree))
20267 (cond
20268 ((eq org-catch-invisible-edits 'show)
20269 ;; That's it, we do the edit after showing
20270 (message
20271 "Unfolding invisible region around point before editing")
20272 (sit-for 1))
20273 ((and (eq org-catch-invisible-edits 'smart)
20274 border-and-ok-direction)
20275 (message "Unfolding invisible region around point before editing"))
20277 ;; Don't do the edit, make the user repeat it in full visibility
20278 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20280 (defun org-fix-tags-on-the-fly ()
20281 "Align tags in headline at point.
20282 Unlike to `org-set-tags', it ignores region and sorting."
20283 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20284 (org-at-heading-p))
20285 (let ((org-ignore-region t)
20286 (org-tags-sort-function nil))
20287 (org-set-tags nil t))))
20289 (defun org-delete-backward-char (N)
20290 "Like `delete-backward-char', insert whitespace at field end in tables.
20291 When deleting backwards, in tables this function will insert whitespace in
20292 front of the next \"|\" separator, to keep the table aligned. The table will
20293 still be marked for re-alignment if the field did fill the entire column,
20294 because, in this case the deletion might narrow the column."
20295 (interactive "p")
20296 (save-match-data
20297 (org-check-before-invisible-edit 'delete-backward)
20298 (if (and (org-at-table-p)
20299 (eq N 1)
20300 (string-match "|" (buffer-substring (point-at-bol) (point)))
20301 (looking-at ".*?|"))
20302 (let ((pos (point))
20303 (noalign (looking-at "[^|\n\r]* |"))
20304 (c org-table-may-need-update))
20305 (backward-delete-char N)
20306 (unless overwrite-mode
20307 (skip-chars-forward "^|")
20308 (insert " ")
20309 (goto-char (1- pos)))
20310 ;; noalign: if there were two spaces at the end, this field
20311 ;; does not determine the width of the column.
20312 (when noalign (setq org-table-may-need-update c)))
20313 (backward-delete-char N)
20314 (org-fix-tags-on-the-fly))))
20316 (defun org-delete-char (N)
20317 "Like `delete-char', but insert whitespace at field end in tables.
20318 When deleting characters, in tables this function will insert whitespace in
20319 front of the next \"|\" separator, to keep the table aligned. The table will
20320 still be marked for re-alignment if the field did fill the entire column,
20321 because, in this case the deletion might narrow the column."
20322 (interactive "p")
20323 (save-match-data
20324 (org-check-before-invisible-edit 'delete)
20325 (if (and (org-at-table-p)
20326 (not (bolp))
20327 (not (= (char-after) ?|))
20328 (eq N 1))
20329 (if (looking-at ".*?|")
20330 (let ((pos (point))
20331 (noalign (looking-at "[^|\n\r]* |"))
20332 (c org-table-may-need-update))
20333 (replace-match
20334 (concat (substring (match-string 0) 1 -1) " |") nil t)
20335 (goto-char pos)
20336 ;; noalign: if there were two spaces at the end, this field
20337 ;; does not determine the width of the column.
20338 (when noalign (setq org-table-may-need-update c)))
20339 (delete-char N))
20340 (delete-char N)
20341 (org-fix-tags-on-the-fly))))
20343 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20344 (put 'org-self-insert-command 'delete-selection
20345 (lambda ()
20346 (not (run-hook-with-args-until-success
20347 'self-insert-uses-region-functions))))
20348 (put 'orgtbl-self-insert-command 'delete-selection
20349 (lambda ()
20350 (not (run-hook-with-args-until-success
20351 'self-insert-uses-region-functions))))
20352 (put 'org-delete-char 'delete-selection 'supersede)
20353 (put 'org-delete-backward-char 'delete-selection 'supersede)
20354 (put 'org-yank 'delete-selection 'yank)
20356 ;; Make `flyspell-mode' delay after some commands
20357 (put 'org-self-insert-command 'flyspell-delayed t)
20358 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20359 (put 'org-delete-char 'flyspell-delayed t)
20360 (put 'org-delete-backward-char 'flyspell-delayed t)
20362 ;; Make pabbrev-mode expand after Org mode commands
20363 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20364 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20366 (defun org-remap (map &rest commands)
20367 "In MAP, remap the functions given in COMMANDS.
20368 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20369 (let (new old)
20370 (while commands
20371 (setq old (pop commands) new (pop commands))
20372 (org-defkey map (vector 'remap old) new))))
20374 (defun org-transpose-words ()
20375 "Transpose words for Org.
20376 This uses the `org-mode-transpose-word-syntax-table' syntax
20377 table, which interprets characters in `org-emphasis-alist' as
20378 word constituents."
20379 (interactive)
20380 (with-syntax-table org-mode-transpose-word-syntax-table
20381 (call-interactively 'transpose-words)))
20382 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20384 (when (eq org-enable-table-editor 'optimized)
20385 ;; If the user wants maximum table support, we need to hijack
20386 ;; some standard editing functions
20387 (org-remap org-mode-map
20388 'self-insert-command 'org-self-insert-command
20389 'delete-char 'org-delete-char
20390 'delete-backward-char 'org-delete-backward-char)
20391 (org-defkey org-mode-map "|" 'org-force-self-insert))
20393 (defvar org-ctrl-c-ctrl-c-hook nil
20394 "Hook for functions attaching themselves to `C-c C-c'.
20396 This can be used to add additional functionality to the C-c C-c
20397 key which executes context-dependent commands. This hook is run
20398 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20399 run after the last test.
20401 Each function will be called with no arguments. The function
20402 must check if the context is appropriate for it to act. If yes,
20403 it should do its thing and then return a non-nil value. If the
20404 context is wrong, just do nothing and return nil.")
20406 (defvar org-ctrl-c-ctrl-c-final-hook nil
20407 "Hook for functions attaching themselves to `C-c C-c'.
20409 This can be used to add additional functionality to the C-c C-c
20410 key which executes context-dependent commands. This hook is run
20411 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20412 before the first test.
20414 Each function will be called with no arguments. The function
20415 must check if the context is appropriate for it to act. If yes,
20416 it should do its thing and then return a non-nil value. If the
20417 context is wrong, just do nothing and return nil.")
20419 (defvar org-tab-first-hook nil
20420 "Hook for functions to attach themselves to TAB.
20421 See `org-ctrl-c-ctrl-c-hook' for more information.
20422 This hook runs as the first action when TAB is pressed, even before
20423 `org-cycle' messes around with the `outline-regexp' to cater for
20424 inline tasks and plain list item folding.
20425 If any function in this hook returns t, any other actions that
20426 would have been caused by TAB (such as table field motion or visibility
20427 cycling) will not occur.")
20429 (defvar org-tab-after-check-for-table-hook nil
20430 "Hook for functions to attach themselves to TAB.
20431 See `org-ctrl-c-ctrl-c-hook' for more information.
20432 This hook runs after it has been established that the cursor is not in a
20433 table, but before checking if the cursor is in a headline or if global cycling
20434 should be done.
20435 If any function in this hook returns t, not other actions like visibility
20436 cycling will be done.")
20438 (defvar org-tab-after-check-for-cycling-hook nil
20439 "Hook for functions to attach themselves to TAB.
20440 See `org-ctrl-c-ctrl-c-hook' for more information.
20441 This hook runs after it has been established that not table field motion and
20442 not visibility should be done because of current context. This is probably
20443 the place where a package like yasnippets can hook in.")
20445 (defvar org-tab-before-tab-emulation-hook nil
20446 "Hook for functions to attach themselves to TAB.
20447 See `org-ctrl-c-ctrl-c-hook' for more information.
20448 This hook runs after every other options for TAB have been exhausted, but
20449 before indentation and \t insertion takes place.")
20451 (defvar org-metaleft-hook nil
20452 "Hook for functions attaching themselves to `M-left'.
20453 See `org-ctrl-c-ctrl-c-hook' for more information.")
20454 (defvar org-metaright-hook nil
20455 "Hook for functions attaching themselves to `M-right'.
20456 See `org-ctrl-c-ctrl-c-hook' for more information.")
20457 (defvar org-metaup-hook nil
20458 "Hook for functions attaching themselves to `M-up'.
20459 See `org-ctrl-c-ctrl-c-hook' for more information.")
20460 (defvar org-metadown-hook nil
20461 "Hook for functions attaching themselves to `M-down'.
20462 See `org-ctrl-c-ctrl-c-hook' for more information.")
20463 (defvar org-shiftmetaleft-hook nil
20464 "Hook for functions attaching themselves to `M-S-left'.
20465 See `org-ctrl-c-ctrl-c-hook' for more information.")
20466 (defvar org-shiftmetaright-hook nil
20467 "Hook for functions attaching themselves to `M-S-right'.
20468 See `org-ctrl-c-ctrl-c-hook' for more information.")
20469 (defvar org-shiftmetaup-hook nil
20470 "Hook for functions attaching themselves to `M-S-up'.
20471 See `org-ctrl-c-ctrl-c-hook' for more information.")
20472 (defvar org-shiftmetadown-hook nil
20473 "Hook for functions attaching themselves to `M-S-down'.
20474 See `org-ctrl-c-ctrl-c-hook' for more information.")
20475 (defvar org-metareturn-hook nil
20476 "Hook for functions attaching themselves to `M-RET'.
20477 See `org-ctrl-c-ctrl-c-hook' for more information.")
20478 (defvar org-shiftup-hook nil
20479 "Hook for functions attaching themselves to `S-up'.
20480 See `org-ctrl-c-ctrl-c-hook' for more information.")
20481 (defvar org-shiftup-final-hook nil
20482 "Hook for functions attaching themselves to `S-up'.
20483 This one runs after all other options except shift-select have been excluded.
20484 See `org-ctrl-c-ctrl-c-hook' for more information.")
20485 (defvar org-shiftdown-hook nil
20486 "Hook for functions attaching themselves to `S-down'.
20487 See `org-ctrl-c-ctrl-c-hook' for more information.")
20488 (defvar org-shiftdown-final-hook nil
20489 "Hook for functions attaching themselves to `S-down'.
20490 This one runs after all other options except shift-select have been excluded.
20491 See `org-ctrl-c-ctrl-c-hook' for more information.")
20492 (defvar org-shiftleft-hook nil
20493 "Hook for functions attaching themselves to `S-left'.
20494 See `org-ctrl-c-ctrl-c-hook' for more information.")
20495 (defvar org-shiftleft-final-hook nil
20496 "Hook for functions attaching themselves to `S-left'.
20497 This one runs after all other options except shift-select have been excluded.
20498 See `org-ctrl-c-ctrl-c-hook' for more information.")
20499 (defvar org-shiftright-hook nil
20500 "Hook for functions attaching themselves to `S-right'.
20501 See `org-ctrl-c-ctrl-c-hook' for more information.")
20502 (defvar org-shiftright-final-hook nil
20503 "Hook for functions attaching themselves to `S-right'.
20504 This one runs after all other options except shift-select have been excluded.
20505 See `org-ctrl-c-ctrl-c-hook' for more information.")
20507 (defun org-modifier-cursor-error ()
20508 "Throw an error, a modified cursor command was applied in wrong context."
20509 (user-error "This command is active in special context like tables, headlines or items"))
20511 (defun org-shiftselect-error ()
20512 "Throw an error because Shift-Cursor command was applied in wrong context."
20513 (if (and (boundp 'shift-select-mode) shift-select-mode)
20514 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20515 (user-error "This command works only in special context like headlines or timestamps")))
20517 (defun org-call-for-shift-select (cmd)
20518 (let ((this-command-keys-shift-translated t))
20519 (call-interactively cmd)))
20521 (defun org-shifttab (&optional arg)
20522 "Global visibility cycling or move to previous table field.
20523 Call `org-table-previous-field' within a table.
20524 When ARG is nil, cycle globally through visibility states.
20525 When ARG is a numeric prefix, show contents of this level."
20526 (interactive "P")
20527 (cond
20528 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20529 ((integerp arg)
20530 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20531 (message "Content view to level: %d" arg)
20532 (org-content (prefix-numeric-value arg2))
20533 (org-cycle-show-empty-lines t)
20534 (setq org-cycle-global-status 'overview)))
20535 (t (call-interactively 'org-global-cycle))))
20537 (defun org-shiftmetaleft ()
20538 "Promote subtree or delete table column.
20539 Calls `org-promote-subtree', `org-outdent-item-tree', or
20540 `org-table-delete-column', depending on context. See the
20541 individual commands for more information."
20542 (interactive)
20543 (cond
20544 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20545 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20546 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20547 ((if (not (org-region-active-p)) (org-at-item-p)
20548 (save-excursion (goto-char (region-beginning))
20549 (org-at-item-p)))
20550 (call-interactively 'org-outdent-item-tree))
20551 (t (org-modifier-cursor-error))))
20553 (defun org-shiftmetaright ()
20554 "Demote subtree or insert table column.
20555 Calls `org-demote-subtree', `org-indent-item-tree', or
20556 `org-table-insert-column', depending on context. See the
20557 individual commands for more information."
20558 (interactive)
20559 (cond
20560 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20561 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20562 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20563 ((if (not (org-region-active-p)) (org-at-item-p)
20564 (save-excursion (goto-char (region-beginning))
20565 (org-at-item-p)))
20566 (call-interactively 'org-indent-item-tree))
20567 (t (org-modifier-cursor-error))))
20569 (defun org-shiftmetaup (&optional _arg)
20570 "Drag the line at point up.
20571 In a table, kill the current row.
20572 On a clock timestamp, update the value of the timestamp like `S-<up>'
20573 but also adjust the previous clocked item in the clock history.
20574 Everywhere else, drag the line at point up."
20575 (interactive "P")
20576 (cond
20577 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20578 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20579 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20580 (call-interactively 'org-timestamp-up)))
20581 (t (call-interactively 'org-drag-line-backward))))
20583 (defun org-shiftmetadown (&optional _arg)
20584 "Drag the line at point down.
20585 In a table, insert an empty row at the current line.
20586 On a clock timestamp, update the value of the timestamp like `S-<down>'
20587 but also adjust the previous clocked item in the clock history.
20588 Everywhere else, drag the line at point down."
20589 (interactive "P")
20590 (cond
20591 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20592 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20593 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20594 (call-interactively 'org-timestamp-down)))
20595 (t (call-interactively 'org-drag-line-forward))))
20597 (defsubst org-hidden-tree-error ()
20598 (user-error
20599 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20601 (defun org-metaleft (&optional _arg)
20602 "Promote heading, list item at point or move table column left.
20604 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20605 depending on context. With no specific context, calls the Emacs
20606 default `backward-word'. See the individual commands for more
20607 information.
20609 This function runs the hook `org-metaleft-hook' as a first step,
20610 and returns at first non-nil value."
20611 (interactive "P")
20612 (cond
20613 ((run-hook-with-args-until-success 'org-metaleft-hook))
20614 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20615 ((org-with-limited-levels
20616 (or (org-at-heading-p)
20617 (and (org-region-active-p)
20618 (save-excursion
20619 (goto-char (region-beginning))
20620 (org-at-heading-p)))))
20621 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20622 (call-interactively 'org-do-promote))
20623 ;; At an inline task.
20624 ((org-at-heading-p)
20625 (call-interactively 'org-inlinetask-promote))
20626 ((or (org-at-item-p)
20627 (and (org-region-active-p)
20628 (save-excursion
20629 (goto-char (region-beginning))
20630 (org-at-item-p))))
20631 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20632 (call-interactively 'org-outdent-item))
20633 (t (call-interactively 'backward-word))))
20635 (defun org-metaright (&optional _arg)
20636 "Demote heading, list item at point or move table column right.
20638 In front of a drawer or a block keyword, indent it correctly.
20640 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20641 `org-indent-drawer' or `org-indent-block' depending on context.
20642 With no specific context, calls the Emacs default `forward-word'.
20643 See the individual commands for more information.
20645 This function runs the hook `org-metaright-hook' as a first step,
20646 and returns at first non-nil value."
20647 (interactive "P")
20648 (cond
20649 ((run-hook-with-args-until-success 'org-metaright-hook))
20650 ((org-at-table-p) (call-interactively 'org-table-move-column))
20651 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20652 ((org-at-block-p) (call-interactively 'org-indent-block))
20653 ((org-with-limited-levels
20654 (or (org-at-heading-p)
20655 (and (org-region-active-p)
20656 (save-excursion
20657 (goto-char (region-beginning))
20658 (org-at-heading-p)))))
20659 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20660 (call-interactively 'org-do-demote))
20661 ;; At an inline task.
20662 ((org-at-heading-p)
20663 (call-interactively 'org-inlinetask-demote))
20664 ((or (org-at-item-p)
20665 (and (org-region-active-p)
20666 (save-excursion
20667 (goto-char (region-beginning))
20668 (org-at-item-p))))
20669 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20670 (call-interactively 'org-indent-item))
20671 (t (call-interactively 'forward-word))))
20673 (defun org-check-for-hidden (what)
20674 "Check if there are hidden headlines/items in the current visual line.
20675 WHAT can be either `headlines' or `items'. If the current line is
20676 an outline or item heading and it has a folded subtree below it,
20677 this function returns t, nil otherwise."
20678 (let ((re (cond
20679 ((eq what 'headlines) org-outline-regexp-bol)
20680 ((eq what 'items) (org-item-beginning-re))
20681 (t (error "This should not happen"))))
20682 beg end)
20683 (save-excursion
20684 (catch 'exit
20685 (unless (org-region-active-p)
20686 (setq beg (point-at-bol))
20687 (beginning-of-line 2)
20688 (while (and (not (eobp)) ;; this is like `next-line'
20689 (get-char-property (1- (point)) 'invisible))
20690 (beginning-of-line 2))
20691 (setq end (point))
20692 (goto-char beg)
20693 (goto-char (point-at-eol))
20694 (setq end (max end (point)))
20695 (while (re-search-forward re end t)
20696 (when (get-char-property (match-beginning 0) 'invisible)
20697 (throw 'exit t))))
20698 nil))))
20700 (defun org-metaup (&optional _arg)
20701 "Move subtree up or move table row up.
20702 Calls `org-move-subtree-up' or `org-table-move-row' or
20703 `org-move-item-up', depending on context. See the individual commands
20704 for more information."
20705 (interactive "P")
20706 (cond
20707 ((run-hook-with-args-until-success 'org-metaup-hook))
20708 ((org-region-active-p)
20709 (let* ((a (min (region-beginning) (region-end)))
20710 (b (1- (max (region-beginning) (region-end))))
20711 (c (save-excursion (goto-char a)
20712 (move-beginning-of-line 0)))
20713 (d (save-excursion (goto-char a)
20714 (move-end-of-line 0) (point))))
20715 (transpose-regions a b c d)
20716 (goto-char c)))
20717 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20718 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20719 ((org-at-item-p) (call-interactively 'org-move-item-up))
20720 (t (org-drag-element-backward))))
20722 (defun org-metadown (&optional _arg)
20723 "Move subtree down or move table row down.
20724 Calls `org-move-subtree-down' or `org-table-move-row' or
20725 `org-move-item-down', depending on context. See the individual
20726 commands for more information."
20727 (interactive "P")
20728 (cond
20729 ((run-hook-with-args-until-success 'org-metadown-hook))
20730 ((org-region-active-p)
20731 (let* ((a (min (region-beginning) (region-end)))
20732 (b (max (region-beginning) (region-end)))
20733 (c (save-excursion (goto-char b)
20734 (move-beginning-of-line 1)))
20735 (d (save-excursion (goto-char b)
20736 (move-end-of-line 1) (1+ (point)))))
20737 (transpose-regions a b c d)
20738 (goto-char d)))
20739 ((org-at-table-p) (call-interactively 'org-table-move-row))
20740 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20741 ((org-at-item-p) (call-interactively 'org-move-item-down))
20742 (t (org-drag-element-forward))))
20744 (defun org-shiftup (&optional arg)
20745 "Increase item in timestamp or increase priority of current headline.
20746 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20747 depending on context. See the individual commands for more information."
20748 (interactive "P")
20749 (cond
20750 ((run-hook-with-args-until-success 'org-shiftup-hook))
20751 ((and org-support-shift-select (org-region-active-p))
20752 (org-call-for-shift-select 'previous-line))
20753 ((org-at-timestamp-p t)
20754 (call-interactively (if org-edit-timestamp-down-means-later
20755 'org-timestamp-down 'org-timestamp-up)))
20756 ((and (not (eq org-support-shift-select 'always))
20757 org-enable-priority-commands
20758 (org-at-heading-p))
20759 (call-interactively 'org-priority-up))
20760 ((and (not org-support-shift-select) (org-at-item-p))
20761 (call-interactively 'org-previous-item))
20762 ((org-clocktable-try-shift 'up arg))
20763 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20764 (org-support-shift-select
20765 (org-call-for-shift-select 'previous-line))
20766 (t (org-shiftselect-error))))
20768 (defun org-shiftdown (&optional arg)
20769 "Decrease item in timestamp or decrease priority of current headline.
20770 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20771 depending on context. See the individual commands for more information."
20772 (interactive "P")
20773 (cond
20774 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20775 ((and org-support-shift-select (org-region-active-p))
20776 (org-call-for-shift-select 'next-line))
20777 ((org-at-timestamp-p t)
20778 (call-interactively (if org-edit-timestamp-down-means-later
20779 'org-timestamp-up 'org-timestamp-down)))
20780 ((and (not (eq org-support-shift-select 'always))
20781 org-enable-priority-commands
20782 (org-at-heading-p))
20783 (call-interactively 'org-priority-down))
20784 ((and (not org-support-shift-select) (org-at-item-p))
20785 (call-interactively 'org-next-item))
20786 ((org-clocktable-try-shift 'down arg))
20787 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20788 (org-support-shift-select
20789 (org-call-for-shift-select 'next-line))
20790 (t (org-shiftselect-error))))
20792 (defun org-shiftright (&optional arg)
20793 "Cycle the thing at point or in the current line, depending on context.
20794 Depending on context, this does one of the following:
20796 - switch a timestamp at point one day into the future
20797 - on a headline, switch to the next TODO keyword.
20798 - on an item, switch entire list to the next bullet type
20799 - on a property line, switch to the next allowed value
20800 - on a clocktable definition line, move time block into the future"
20801 (interactive "P")
20802 (cond
20803 ((run-hook-with-args-until-success 'org-shiftright-hook))
20804 ((and org-support-shift-select (org-region-active-p))
20805 (org-call-for-shift-select 'forward-char))
20806 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20807 ((and (not (eq org-support-shift-select 'always))
20808 (org-at-heading-p))
20809 (let ((org-inhibit-logging
20810 (not org-treat-S-cursor-todo-selection-as-state-change))
20811 (org-inhibit-blocking
20812 (not org-treat-S-cursor-todo-selection-as-state-change)))
20813 (org-call-with-arg 'org-todo 'right)))
20814 ((or (and org-support-shift-select
20815 (not (eq org-support-shift-select 'always))
20816 (org-at-item-bullet-p))
20817 (and (not org-support-shift-select) (org-at-item-p)))
20818 (org-call-with-arg 'org-cycle-list-bullet nil))
20819 ((and (not (eq org-support-shift-select 'always))
20820 (org-at-property-p))
20821 (call-interactively 'org-property-next-allowed-value))
20822 ((org-clocktable-try-shift 'right arg))
20823 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20824 (org-support-shift-select
20825 (org-call-for-shift-select 'forward-char))
20826 (t (org-shiftselect-error))))
20828 (defun org-shiftleft (&optional arg)
20829 "Cycle the thing at point or in the current line, depending on context.
20830 Depending on context, this does one of the following:
20832 - switch a timestamp at point one day into the past
20833 - on a headline, switch to the previous TODO keyword.
20834 - on an item, switch entire list to the previous bullet type
20835 - on a property line, switch to the previous allowed value
20836 - on a clocktable definition line, move time block into the past"
20837 (interactive "P")
20838 (cond
20839 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20840 ((and org-support-shift-select (org-region-active-p))
20841 (org-call-for-shift-select 'backward-char))
20842 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20843 ((and (not (eq org-support-shift-select 'always))
20844 (org-at-heading-p))
20845 (let ((org-inhibit-logging
20846 (not org-treat-S-cursor-todo-selection-as-state-change))
20847 (org-inhibit-blocking
20848 (not org-treat-S-cursor-todo-selection-as-state-change)))
20849 (org-call-with-arg 'org-todo 'left)))
20850 ((or (and org-support-shift-select
20851 (not (eq org-support-shift-select 'always))
20852 (org-at-item-bullet-p))
20853 (and (not org-support-shift-select) (org-at-item-p)))
20854 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20855 ((and (not (eq org-support-shift-select 'always))
20856 (org-at-property-p))
20857 (call-interactively 'org-property-previous-allowed-value))
20858 ((org-clocktable-try-shift 'left arg))
20859 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20860 (org-support-shift-select
20861 (org-call-for-shift-select 'backward-char))
20862 (t (org-shiftselect-error))))
20864 (defun org-shiftcontrolright ()
20865 "Switch to next TODO set."
20866 (interactive)
20867 (cond
20868 ((and org-support-shift-select (org-region-active-p))
20869 (org-call-for-shift-select 'forward-word))
20870 ((and (not (eq org-support-shift-select 'always))
20871 (org-at-heading-p))
20872 (org-call-with-arg 'org-todo 'nextset))
20873 (org-support-shift-select
20874 (org-call-for-shift-select 'forward-word))
20875 (t (org-shiftselect-error))))
20877 (defun org-shiftcontrolleft ()
20878 "Switch to previous TODO set."
20879 (interactive)
20880 (cond
20881 ((and org-support-shift-select (org-region-active-p))
20882 (org-call-for-shift-select 'backward-word))
20883 ((and (not (eq org-support-shift-select 'always))
20884 (org-at-heading-p))
20885 (org-call-with-arg 'org-todo 'previousset))
20886 (org-support-shift-select
20887 (org-call-for-shift-select 'backward-word))
20888 (t (org-shiftselect-error))))
20890 (defun org-shiftcontrolup (&optional n)
20891 "Change timestamps synchronously up in CLOCK log lines.
20892 Optional argument N tells to change by that many units."
20893 (interactive "P")
20894 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20895 (let (org-support-shift-select)
20896 (org-clock-timestamps-up n))
20897 (user-error "Not at a clock log")))
20899 (defun org-shiftcontroldown (&optional n)
20900 "Change timestamps synchronously down in CLOCK log lines.
20901 Optional argument N tells to change by that many units."
20902 (interactive "P")
20903 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20904 (let (org-support-shift-select)
20905 (org-clock-timestamps-down n))
20906 (user-error "Not at a clock log")))
20908 (defun org-increase-number-at-point (&optional inc)
20909 "Increment the number at point.
20910 With an optional prefix numeric argument INC, increment using
20911 this numeric value."
20912 (interactive "p")
20913 (if (not (number-at-point))
20914 (user-error "Not on a number")
20915 (unless inc (setq inc 1))
20916 (let ((pos (point))
20917 (beg (skip-chars-backward "-+^/*0-9eE."))
20918 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20919 (setq nap (buffer-substring-no-properties
20920 (+ pos beg) (+ pos beg end)))
20921 (delete-region (+ pos beg) (+ pos beg end))
20922 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20923 (when (org-at-table-p)
20924 (org-table-align)
20925 (org-table-end-of-field 1))))
20927 (defun org-decrease-number-at-point (&optional inc)
20928 "Decrement the number at point.
20929 With an optional prefix numeric argument INC, decrement using
20930 this numeric value."
20931 (interactive "p")
20932 (org-increase-number-at-point (- (or inc 1))))
20934 (defun org-ctrl-c-ret ()
20935 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20936 (interactive)
20937 (cond
20938 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20939 (t (call-interactively 'org-insert-heading))))
20941 (defun org-find-visible ()
20942 (let ((s (point)))
20943 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20944 (get-char-property s 'invisible)))
20946 (defun org-find-invisible ()
20947 (let ((s (point)))
20948 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20949 (not (get-char-property s 'invisible))))
20952 (defun org-copy-visible (beg end)
20953 "Copy the visible parts of the region."
20954 (interactive "r")
20955 (let (snippets s)
20956 (save-excursion
20957 (save-restriction
20958 (narrow-to-region beg end)
20959 (setq s (goto-char (point-min)))
20960 (while (not (= (point) (point-max)))
20961 (goto-char (org-find-invisible))
20962 (push (buffer-substring s (point)) snippets)
20963 (setq s (goto-char (org-find-visible))))))
20964 (kill-new (apply 'concat (nreverse snippets)))))
20966 (defun org-copy-special ()
20967 "Copy region in table or copy current subtree.
20968 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20969 context. See the individual commands for more information."
20970 (interactive)
20971 (call-interactively
20972 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20974 (defun org-cut-special ()
20975 "Cut region in table or cut current subtree.
20976 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20977 context. See the individual commands for more information."
20978 (interactive)
20979 (call-interactively
20980 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20982 (defun org-paste-special (arg)
20983 "Paste rectangular region into table, or past subtree relative to level.
20984 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20985 See the individual commands for more information."
20986 (interactive "P")
20987 (if (org-at-table-p)
20988 (org-table-paste-rectangle)
20989 (org-paste-subtree arg)))
20991 (defun org-edit-special (&optional arg)
20992 "Call a special editor for the element at point.
20993 When at a table, call the formula editor with `org-table-edit-formulas'.
20994 When in a source code block, call `org-edit-src-code'.
20995 When in a fixed-width region, call `org-edit-fixed-width-region'.
20996 When in an export block, call `org-edit-export-block'.
20997 When at an #+INCLUDE keyword, visit the included file.
20998 When at a footnote reference, call `org-edit-footnote-reference'
20999 On a link, call `ffap' to visit the link at point.
21000 Otherwise, return a user error."
21001 (interactive "P")
21002 (let ((element (org-element-at-point)))
21003 (barf-if-buffer-read-only)
21004 (pcase (org-element-type element)
21005 (`src-block
21006 (if (not arg) (org-edit-src-code)
21007 (let* ((info (org-babel-get-src-block-info))
21008 (lang (nth 0 info))
21009 (params (nth 2 info))
21010 (session (cdr (assq :session params))))
21011 (if (not session) (org-edit-src-code)
21012 ;; At a src-block with a session and function called with
21013 ;; an ARG: switch to the buffer related to the inferior
21014 ;; process.
21015 (switch-to-buffer
21016 (funcall (intern (concat "org-babel-prep-session:" lang))
21017 session params))))))
21018 (`keyword
21019 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21020 (org-open-link-from-string
21021 (format "[[%s]]"
21022 (expand-file-name
21023 (let ((value (org-element-property :value element)))
21024 (cond ((not (org-string-nw-p value))
21025 (user-error "No file to edit"))
21026 ((string-match "\\`\"\\(.*?\\)\"" value)
21027 (match-string 1 value))
21028 ((string-match "\\`[^ \t\"]\\S-*" value)
21029 (match-string 0 value))
21030 (t (user-error "No valid file specified")))))))
21031 (user-error "No special environment to edit here")))
21032 (`table
21033 (if (eq (org-element-property :type element) 'table.el)
21034 (org-edit-table.el)
21035 (call-interactively 'org-table-edit-formulas)))
21036 ;; Only Org tables contain `table-row' type elements.
21037 (`table-row (call-interactively 'org-table-edit-formulas))
21038 (`example-block (org-edit-src-code))
21039 (`export-block (org-edit-export-block))
21040 (`fixed-width (org-edit-fixed-width-region))
21042 ;; No notable element at point. Though, we may be at a link or
21043 ;; a footnote reference, which are objects. Thus, scan deeper.
21044 (let ((context (org-element-context element)))
21045 (pcase (org-element-type context)
21046 (`footnote-reference (org-edit-footnote-reference))
21047 (`inline-src-block (org-edit-inline-src-code))
21048 (`link (call-interactively #'ffap))
21049 (_ (user-error "No special environment to edit here"))))))))
21051 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21052 (defun org-ctrl-c-ctrl-c (&optional arg)
21053 "Set tags in headline, or update according to changed information at point.
21055 This command does many different things, depending on context:
21057 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21058 this is what we do.
21060 - If the cursor is on a statistics cookie, update it.
21062 - If the cursor is in a headline, prompt for tags and insert them
21063 into the current line, aligned to `org-tags-column'. When called
21064 with prefix arg, realign all tags in the current buffer.
21066 - If the cursor is in one of the special #+KEYWORD lines, this
21067 triggers scanning the buffer for these lines and updating the
21068 information.
21070 - If the cursor is inside a table, realign the table. This command
21071 works even if the automatic table editor has been turned off.
21073 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21074 the entire table.
21076 - If the cursor is at a footnote reference or definition, jump to
21077 the corresponding definition or references, respectively.
21079 - If the cursor is a the beginning of a dynamic block, update it.
21081 - If the current buffer is a capture buffer, close note and file it.
21083 - If the cursor is on a <<<target>>>, update radio targets and
21084 corresponding links in this buffer.
21086 - If the cursor is on a numbered item in a plain list, renumber the
21087 ordered list.
21089 - If the cursor is on a checkbox, toggle it.
21091 - If the cursor is on a code block, evaluate it. The variable
21092 `org-confirm-babel-evaluate' can be used to control prompting
21093 before code block evaluation, by default every code block
21094 evaluation requires confirmation. Code block evaluation can be
21095 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21096 (interactive "P")
21097 (cond
21098 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
21099 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21100 (org-remove-occur-highlights)
21101 (message "Temporary highlights/overlays removed from current buffer"))
21102 ((and (local-variable-p 'org-finish-function)
21103 (fboundp org-finish-function))
21104 (funcall org-finish-function))
21105 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21107 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21108 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21109 (user-error
21110 (substitute-command-keys
21111 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here")))
21112 (let* ((context (org-element-context))
21113 (type (org-element-type context)))
21114 (cl-case type
21115 ;; When at a link, act according to the parent instead.
21116 (link (setq context (org-element-property :parent context))
21117 (setq type (org-element-type context)))
21118 ;; Unsupported object types: refer to the first supported
21119 ;; element or object containing it.
21120 ((bold code entity export-snippet inline-babel-call inline-src-block
21121 italic latex-fragment line-break macro strike-through subscript
21122 superscript underline verbatim)
21123 (setq context
21124 (org-element-lineage
21125 context '(paragraph radio-target table-cell verse-block)))
21126 (setq type (org-element-type context))))
21127 ;; For convenience: at the first line of a paragraph on the
21128 ;; same line as an item, apply function on that item instead.
21129 (when (eq type 'paragraph)
21130 (let ((parent (org-element-property :parent context)))
21131 (when (and (eq (org-element-type parent) 'item)
21132 (= (line-beginning-position)
21133 (org-element-property :begin parent)))
21134 (setq context parent)
21135 (setq type 'item))))
21136 ;; Act according to type of element or object at point.
21137 (pcase type
21138 (`clock (org-clock-update-time-maybe))
21139 (`dynamic-block
21140 (save-excursion
21141 (goto-char (org-element-property :post-affiliated context))
21142 (org-update-dblock)))
21143 (`footnote-definition
21144 (goto-char (org-element-property :post-affiliated context))
21145 (call-interactively 'org-footnote-action))
21146 (`footnote-reference (call-interactively 'org-footnote-action))
21147 ((or `headline `inlinetask)
21148 (save-excursion (goto-char (org-element-property :begin context))
21149 (call-interactively #'org-set-tags)))
21150 (`item
21151 ;; At an item: a double C-u set checkbox to "[-]"
21152 ;; unconditionally, whereas a single one will toggle its
21153 ;; presence. Without a universal argument, if the item
21154 ;; has a checkbox, toggle it. Otherwise repair the list.
21155 (let* ((box (org-element-property :checkbox context))
21156 (struct (org-element-property :structure context))
21157 (old-struct (copy-tree struct))
21158 (parents (org-list-parents-alist struct))
21159 (prevs (org-list-prevs-alist struct))
21160 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21161 (org-list-set-checkbox
21162 (org-element-property :begin context) struct
21163 (cond ((equal arg '(16)) "[-]")
21164 ((and (not box) (equal arg '(4))) "[ ]")
21165 ((or (not box) (equal arg '(4))) nil)
21166 ((eq box 'on) "[ ]")
21167 (t "[X]")))
21168 ;; Mimic `org-list-write-struct' but with grabbing
21169 ;; a return value from `org-list-struct-fix-box'.
21170 (org-list-struct-fix-ind struct parents 2)
21171 (org-list-struct-fix-item-end struct)
21172 (org-list-struct-fix-bul struct prevs)
21173 (org-list-struct-fix-ind struct parents)
21174 (let ((block-item
21175 (org-list-struct-fix-box struct parents prevs orderedp)))
21176 (if (and box (equal struct old-struct))
21177 (if (equal arg '(16))
21178 (message "Checkboxes already reset")
21179 (user-error "Cannot toggle this checkbox: %s"
21180 (if (eq box 'on)
21181 "all subitems checked"
21182 "unchecked subitems")))
21183 (org-list-struct-apply-struct struct old-struct)
21184 (org-update-checkbox-count-maybe))
21185 (when block-item
21186 (message "Checkboxes were removed due to empty box at line %d"
21187 (org-current-line block-item))))))
21188 (`keyword
21189 (let ((org-inhibit-startup-visibility-stuff t)
21190 (org-startup-align-all-tables nil))
21191 (when (boundp 'org-table-coordinate-overlays)
21192 (mapc #'delete-overlay org-table-coordinate-overlays)
21193 (setq org-table-coordinate-overlays nil))
21194 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21195 (message "Local setup has been refreshed"))
21196 (`plain-list
21197 ;; At a plain list, with a double C-u argument, set
21198 ;; checkboxes of each item to "[-]", whereas a single one
21199 ;; will toggle their presence according to the state of the
21200 ;; first item in the list. Without an argument, repair the
21201 ;; list.
21202 (let* ((begin (org-element-property :contents-begin context))
21203 (beginm (move-marker (make-marker) begin))
21204 (struct (org-element-property :structure context))
21205 (old-struct (copy-tree struct))
21206 (first-box (save-excursion
21207 (goto-char begin)
21208 (looking-at org-list-full-item-re)
21209 (match-string-no-properties 3)))
21210 (new-box (cond ((equal arg '(16)) "[-]")
21211 ((equal arg '(4)) (unless first-box "[ ]"))
21212 ((equal first-box "[X]") "[ ]")
21213 (t "[X]"))))
21214 (cond
21215 (arg
21216 (dolist (pos
21217 (org-list-get-all-items
21218 begin struct (org-list-prevs-alist struct)))
21219 (org-list-set-checkbox pos struct new-box)))
21220 ((and first-box (eq (point) begin))
21221 ;; For convenience, when point is at bol on the first
21222 ;; item of the list and no argument is provided, simply
21223 ;; toggle checkbox of that item, if any.
21224 (org-list-set-checkbox begin struct new-box)))
21225 (org-list-write-struct
21226 struct (org-list-parents-alist struct) old-struct)
21227 (org-update-checkbox-count-maybe)
21228 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21229 ((or `property-drawer `node-property)
21230 (call-interactively #'org-property-action))
21231 ((or `radio-target `target)
21232 (call-interactively #'org-update-radio-target-regexp))
21233 (`statistics-cookie
21234 (call-interactively #'org-update-statistics-cookies))
21235 ((or `table `table-cell `table-row)
21236 ;; At a table, recalculate every field and align it. Also
21237 ;; send the table if necessary. If the table has
21238 ;; a `table.el' type, just give up. At a table row or
21239 ;; cell, maybe recalculate line but always align table.
21240 (if (eq (org-element-property :type context) 'table.el)
21241 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21242 Use `\\[org-edit-special]' to edit table.el tables"))
21243 (let ((org-enable-table-editor t))
21244 (if (or (eq type 'table)
21245 ;; Check if point is at a TBLFM line.
21246 (and (eq type 'table-row)
21247 (= (point) (org-element-property :end context))))
21248 (save-excursion
21249 (if (org-at-TBLFM-p)
21250 (progn (require 'org-table)
21251 (org-table-calc-current-TBLFM))
21252 (goto-char (org-element-property :contents-begin context))
21253 (org-call-with-arg 'org-table-recalculate (or arg t))
21254 (orgtbl-send-table 'maybe)))
21255 (org-table-maybe-eval-formula)
21256 (cond (arg (call-interactively 'org-table-recalculate))
21257 ((org-table-maybe-recalculate-line))
21258 (t (org-table-align)))))))
21259 (`timestamp (org-timestamp-change 0 'day))
21260 ((and `nil (guard (org-at-heading-p)))
21261 ;; When point is on an unsupported object type, we can miss
21262 ;; the fact that it also is at a heading. Handle it here.
21263 (call-interactively #'org-set-tags))
21265 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21266 (user-error
21267 (substitute-command-keys
21268 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))))
21270 (defun org-mode-restart ()
21271 (interactive)
21272 (let ((indent-status (bound-and-true-p org-indent-mode)))
21273 (funcall major-mode)
21274 (hack-local-variables)
21275 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21276 (org-indent-mode -1)))
21277 (message "%s restarted" major-mode))
21279 (defun org-kill-note-or-show-branches ()
21280 "Abort storing current note, or call `outline-show-branches'."
21281 (interactive)
21282 (if (not org-finish-function)
21283 (progn
21284 (outline-hide-subtree)
21285 (call-interactively 'outline-show-branches))
21286 (let ((org-note-abort t))
21287 (funcall org-finish-function))))
21289 (defun org-delete-indentation (&optional arg)
21290 "Join current line to previous and fix whitespace at join.
21292 If previous line is a headline add to headline title. Otherwise
21293 the function calls `delete-indentation'.
21295 With a non-nil optional argument, join it to the following one."
21296 (interactive "*P")
21297 (if (save-excursion
21298 (beginning-of-line (if arg 1 0))
21299 (looking-at org-complex-heading-regexp))
21300 ;; At headline.
21301 (let ((tags-column (when (match-beginning 5)
21302 (save-excursion (goto-char (match-beginning 5))
21303 (current-column))))
21304 (string (concat " " (progn (when arg (forward-line 1))
21305 (org-trim (delete-and-extract-region
21306 (line-beginning-position)
21307 (line-end-position)))))))
21308 (unless (bobp) (delete-region (point) (1- (point))))
21309 (goto-char (or (match-end 4)
21310 (match-beginning 5)
21311 (match-end 0)))
21312 (skip-chars-backward " \t")
21313 (save-excursion (insert string))
21314 ;; Adjust alignment of tags.
21315 (cond
21316 ((not tags-column)) ;no tags
21317 (org-auto-align-tags (org-set-tags nil t))
21318 (t (org--align-tags-here tags-column)))) ;preserve tags column
21319 (delete-indentation arg)))
21321 (defun org-open-line (n)
21322 "Insert a new row in tables, call `open-line' elsewhere.
21323 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21324 As a special case, when a document starts with a table, allow to
21325 call `open-line' on the very first character."
21326 (interactive "*p")
21327 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21328 (org-table-insert-row)
21329 (open-line n)))
21331 (defun org-return (&optional indent)
21332 "Goto next table row or insert a newline.
21334 Calls `org-table-next-row' or `newline', depending on context.
21336 When optional INDENT argument is non-nil, call
21337 `newline-and-indent' instead of `newline'.
21339 When `org-return-follows-link' is non-nil and point is on
21340 a timestamp or a link, call `org-open-at-point'. However, it
21341 will not happen if point is in a table or on a \"dead\"
21342 object (e.g., within a comment). In these case, you need to use
21343 `org-open-at-point' directly."
21344 (interactive)
21345 (let ((context (if org-return-follows-link (org-element-context)
21346 (org-element-at-point))))
21347 (cond
21348 ;; In a table, call `org-table-next-row'.
21349 ((or (and (eq (org-element-type context) 'table)
21350 (>= (point) (org-element-property :contents-begin context))
21351 (< (point) (org-element-property :contents-end context)))
21352 (org-element-lineage context '(table-row table-cell) t))
21353 (org-table-justify-field-maybe)
21354 (call-interactively #'org-table-next-row))
21355 ;; On a link or a timestamp, call `org-open-at-point' if
21356 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21357 ;; locations, e.g., in a comment, as `org-open-at-point'.
21358 ((and org-return-follows-link
21359 (or (org-in-regexp org-ts-regexp-both nil t)
21360 (org-in-regexp org-tsr-regexp-both nil t)
21361 (org-in-regexp org-any-link-re nil t)))
21362 (call-interactively #'org-open-at-point))
21363 ;; Insert newline in heading, but preserve tags.
21364 ((and (not (bolp))
21365 (save-excursion (beginning-of-line)
21366 (looking-at org-complex-heading-regexp)))
21367 ;; At headline. Split line. However, if point is on keyword,
21368 ;; priority cookie or tags, do not break any of them: add
21369 ;; a newline after the headline instead.
21370 (let ((tags-column (and (match-beginning 5)
21371 (save-excursion (goto-char (match-beginning 5))
21372 (current-column))))
21373 (string
21374 (when (and (match-end 4)
21375 (>= (point)
21376 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21377 (<= (point) (match-end 4)))
21378 (delete-and-extract-region (point) (match-end 4)))))
21379 ;; Adjust tag alignment.
21380 (cond
21381 ((not (and tags-column string)))
21382 (org-auto-align-tags (org-set-tags nil t))
21383 (t (org--align-tags-here tags-column))) ;preserve tags column
21384 (end-of-line)
21385 (org-show-entry)
21386 (if indent (newline-and-indent) (newline))
21387 (when string (save-excursion (insert (org-trim string))))))
21388 ;; In a list, make sure indenting keeps trailing text within.
21389 ((and indent
21390 (not (eolp))
21391 (org-element-lineage context '(item)))
21392 (let ((trailing-data
21393 (delete-and-extract-region (point) (line-end-position))))
21394 (newline-and-indent)
21395 (save-excursion (insert trailing-data))))
21396 (t (if indent (newline-and-indent) (newline))))))
21398 (defun org-return-indent ()
21399 "Goto next table row or insert a newline and indent.
21400 Calls `org-table-next-row' or `newline-and-indent', depending on
21401 context. See the individual commands for more information."
21402 (interactive)
21403 (org-return t))
21405 (defun org-ctrl-c-star ()
21406 "Compute table, or change heading status of lines.
21407 Calls `org-table-recalculate' or `org-toggle-heading',
21408 depending on context."
21409 (interactive)
21410 (cond
21411 ((org-at-table-p)
21412 (call-interactively 'org-table-recalculate))
21414 ;; Convert all lines in region to list items
21415 (call-interactively 'org-toggle-heading))))
21417 (defun org-ctrl-c-minus ()
21418 "Insert separator line in table or modify bullet status of line.
21419 Also turns a plain line or a region of lines into list items.
21420 Calls `org-table-insert-hline', `org-toggle-item', or
21421 `org-cycle-list-bullet', depending on context."
21422 (interactive)
21423 (cond
21424 ((org-at-table-p)
21425 (call-interactively 'org-table-insert-hline))
21426 ((org-region-active-p)
21427 (call-interactively 'org-toggle-item))
21428 ((org-in-item-p)
21429 (call-interactively 'org-cycle-list-bullet))
21431 (call-interactively 'org-toggle-item))))
21433 (defun org-toggle-heading (&optional nstars)
21434 "Convert headings to normal text, or items or text to headings.
21435 If there is no active region, only convert the current line.
21437 With a `\\[universal-argument]' prefix, convert the whole list at
21438 point into heading.
21440 In a region:
21442 - If the first non blank line is a headline, remove the stars
21443 from all headlines in the region.
21445 - If it is a normal line, turn each and every normal line (i.e.,
21446 not an heading or an item) in the region into headings. If you
21447 want to convert only the first line of this region, use one
21448 universal prefix argument.
21450 - If it is a plain list item, turn all plain list items into headings.
21452 When converting a line into a heading, the number of stars is chosen
21453 such that the lines become children of the current entry. However,
21454 when a numeric prefix argument is given, its value determines the
21455 number of stars to add."
21456 (interactive "P")
21457 (let ((skip-blanks
21458 (function
21459 ;; Return beginning of first non-blank line, starting from
21460 ;; line at POS.
21461 (lambda (pos)
21462 (save-excursion
21463 (goto-char pos)
21464 (while (org-at-comment-p) (forward-line))
21465 (skip-chars-forward " \r\t\n")
21466 (point-at-bol)))))
21467 beg end toggled)
21468 ;; Determine boundaries of changes. If a universal prefix has
21469 ;; been given, put the list in a region. If region ends at a bol,
21470 ;; do not consider the last line to be in the region.
21472 (when (and current-prefix-arg (org-at-item-p))
21473 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21474 (org-mark-element))
21476 (if (org-region-active-p)
21477 (setq beg (funcall skip-blanks (region-beginning))
21478 end (copy-marker (save-excursion
21479 (goto-char (region-end))
21480 (if (bolp) (point) (point-at-eol)))))
21481 (setq beg (funcall skip-blanks (point-at-bol))
21482 end (copy-marker (point-at-eol))))
21483 ;; Ensure inline tasks don't count as headings.
21484 (org-with-limited-levels
21485 (save-excursion
21486 (goto-char beg)
21487 (cond
21488 ;; Case 1. Started at an heading: de-star headings.
21489 ((org-at-heading-p)
21490 (while (< (point) end)
21491 (when (org-at-heading-p t)
21492 (looking-at org-outline-regexp) (replace-match "")
21493 (setq toggled t))
21494 (forward-line)))
21495 ;; Case 2. Started at an item: change items into headlines.
21496 ;; One star will be added by `org-list-to-subtree'.
21497 ((org-at-item-p)
21498 (while (< (point) end)
21499 (when (org-at-item-p)
21500 ;; Pay attention to cases when region ends before list.
21501 (let* ((struct (org-list-struct))
21502 (list-end
21503 (min (org-list-get-bottom-point struct) (1+ end))))
21504 (save-restriction
21505 (narrow-to-region (point) list-end)
21506 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21507 (setq toggled t))
21508 (forward-line)))
21509 ;; Case 3. Started at normal text: make every line an heading,
21510 ;; skipping headlines and items.
21511 (t (let* ((stars
21512 (make-string
21513 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21514 (add-stars
21515 (cond (nstars "") ; stars from prefix only
21516 ((equal stars "") "*") ; before first heading
21517 (org-odd-levels-only "**") ; inside heading, odd
21518 (t "*"))) ; inside heading, oddeven
21519 (rpl (concat stars add-stars " "))
21520 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21521 (while (< (point) (if (equal nstars '(4)) lend end))
21522 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21523 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21524 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21525 (forward-line)))))))
21526 (unless toggled (message "Cannot toggle heading from here"))))
21528 (defun org-meta-return (&optional _arg)
21529 "Insert a new heading or wrap a region in a table.
21530 Calls `org-insert-heading' or `org-table-wrap-region', depending
21531 on context. See the individual commands for more information."
21532 (interactive)
21533 (org-check-before-invisible-edit 'insert)
21534 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21535 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21536 #'org-insert-heading))))
21538 ;;; Menu entries
21540 (defsubst org-in-subtree-not-table-p ()
21541 "Are we in a subtree and not in a table?"
21542 (and (not (org-before-first-heading-p))
21543 (not (org-at-table-p))))
21545 ;; Define the Org mode menus
21546 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21547 '("Tbl"
21548 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21549 ["Next Field" org-cycle (org-at-table-p)]
21550 ["Previous Field" org-shifttab (org-at-table-p)]
21551 ["Next Row" org-return (org-at-table-p)]
21552 "--"
21553 ["Blank Field" org-table-blank-field (org-at-table-p)]
21554 ["Edit Field" org-table-edit-field (org-at-table-p)]
21555 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21556 "--"
21557 ("Column"
21558 ["Move Column Left" org-metaleft (org-at-table-p)]
21559 ["Move Column Right" org-metaright (org-at-table-p)]
21560 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21561 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21562 ("Row"
21563 ["Move Row Up" org-metaup (org-at-table-p)]
21564 ["Move Row Down" org-metadown (org-at-table-p)]
21565 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21566 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21567 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21568 "--"
21569 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21570 ("Rectangle"
21571 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21572 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21573 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21574 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21575 "--"
21576 ("Calculate"
21577 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21578 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21579 ["Edit Formulas" org-edit-special (org-at-table-p)]
21580 "--"
21581 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21582 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21583 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21584 "--"
21585 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21586 "--"
21587 ["Sum Column/Rectangle" org-table-sum
21588 (or (org-at-table-p) (org-region-active-p))]
21589 ["Which Column?" org-table-current-column (org-at-table-p)])
21590 ["Debug Formulas"
21591 org-table-toggle-formula-debugger
21592 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21593 ["Show Col/Row Numbers"
21594 org-table-toggle-coordinate-overlays
21595 :style toggle
21596 :selected (bound-and-true-p org-table-overlay-coordinates)]
21597 "--"
21598 ["Create" org-table-create (and (not (org-at-table-p))
21599 org-enable-table-editor)]
21600 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21601 ["Import from File" org-table-import (not (org-at-table-p))]
21602 ["Export to File" org-table-export (org-at-table-p)]
21603 "--"
21604 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21605 "--"
21606 ("Plot"
21607 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21608 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21610 (easy-menu-define org-org-menu org-mode-map "Org menu"
21611 '("Org"
21612 ("Show/Hide"
21613 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21614 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21615 ["Sparse Tree..." org-sparse-tree t]
21616 ["Reveal Context" org-reveal t]
21617 ["Show All" outline-show-all t]
21618 "--"
21619 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21620 "--"
21621 ["New Heading" org-insert-heading t]
21622 ("Navigate Headings"
21623 ["Up" outline-up-heading t]
21624 ["Next" outline-next-visible-heading t]
21625 ["Previous" outline-previous-visible-heading t]
21626 ["Next Same Level" outline-forward-same-level t]
21627 ["Previous Same Level" outline-backward-same-level t]
21628 "--"
21629 ["Jump" org-goto t])
21630 ("Edit Structure"
21631 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21632 "--"
21633 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21634 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21635 "--"
21636 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21637 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21638 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21639 "--"
21640 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21641 "--"
21642 ["Copy visible text" org-copy-visible t]
21643 "--"
21644 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21645 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21646 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21647 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21648 "--"
21649 ["Sort Region/Children" org-sort t]
21650 "--"
21651 ["Convert to odd levels" org-convert-to-odd-levels t]
21652 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21653 ("Editing"
21654 ["Emphasis..." org-emphasize t]
21655 ["Edit Source Example" org-edit-special t]
21656 "--"
21657 ["Footnote new/jump" org-footnote-action t]
21658 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21659 ("Archive"
21660 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21661 "--"
21662 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21663 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21664 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21666 "--"
21667 ("Hyperlinks"
21668 ["Store Link (Global)" org-store-link t]
21669 ["Find existing link to here" org-occur-link-in-agenda-files t]
21670 ["Insert Link" org-insert-link t]
21671 ["Follow Link" org-open-at-point t]
21672 "--"
21673 ["Next link" org-next-link t]
21674 ["Previous link" org-previous-link t]
21675 "--"
21676 ["Descriptive Links"
21677 org-toggle-link-display
21678 :style radio
21679 :selected org-descriptive-links
21681 ["Literal Links"
21682 org-toggle-link-display
21683 :style radio
21684 :selected (not org-descriptive-links)])
21685 "--"
21686 ("TODO Lists"
21687 ["TODO/DONE/-" org-todo t]
21688 ("Select keyword"
21689 ["Next keyword" org-shiftright (org-at-heading-p)]
21690 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21691 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21692 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21693 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21694 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21695 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21696 "--"
21697 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21698 :selected org-enforce-todo-dependencies :style toggle :active t]
21699 "Settings for tree at point"
21700 ["Do Children sequentially" org-toggle-ordered-property :style radio
21701 :selected (org-entry-get nil "ORDERED")
21702 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21703 ["Do Children parallel" org-toggle-ordered-property :style radio
21704 :selected (not (org-entry-get nil "ORDERED"))
21705 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21706 "--"
21707 ["Set Priority" org-priority t]
21708 ["Priority Up" org-shiftup t]
21709 ["Priority Down" org-shiftdown t]
21710 "--"
21711 ["Get news from all feeds" org-feed-update-all t]
21712 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21713 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21714 ("TAGS and Properties"
21715 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21716 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21717 "--"
21718 ["Set property" org-set-property (not (org-before-first-heading-p))]
21719 ["Column view of properties" org-columns t]
21720 ["Insert Column View DBlock" org-columns-insert-dblock t])
21721 ("Dates and Scheduling"
21722 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21723 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21724 ("Change Date"
21725 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21726 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21727 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21728 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21729 ["Compute Time Range" org-evaluate-time-range t]
21730 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21731 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21732 "--"
21733 ["Custom time format" org-toggle-time-stamp-overlays
21734 :style radio :selected org-display-custom-times]
21735 "--"
21736 ["Goto Calendar" org-goto-calendar t]
21737 ["Date from Calendar" org-date-from-calendar t]
21738 "--"
21739 ["Start/Restart Timer" org-timer-start t]
21740 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21741 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21742 ["Insert Timer String" org-timer t]
21743 ["Insert Timer Item" org-timer-item t])
21744 ("Logging work"
21745 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21746 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21747 ["Clock out" org-clock-out t]
21748 ["Clock cancel" org-clock-cancel t]
21749 "--"
21750 ["Mark as default task" org-clock-mark-default-task t]
21751 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21752 ["Goto running clock" org-clock-goto t]
21753 "--"
21754 ["Display times" org-clock-display t]
21755 ["Create clock table" org-clock-report t]
21756 "--"
21757 ["Record DONE time"
21758 (progn (setq org-log-done (not org-log-done))
21759 (message "Switching to %s will %s record a timestamp"
21760 (car org-done-keywords)
21761 (if org-log-done "automatically" "not")))
21762 :style toggle :selected org-log-done])
21763 "--"
21764 ["Agenda Command..." org-agenda t]
21765 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21766 ("File List for Agenda")
21767 ("Special views current file"
21768 ["TODO Tree" org-show-todo-tree t]
21769 ["Check Deadlines" org-check-deadlines t]
21770 ["Timeline" org-timeline t]
21771 ["Tags/Property tree" org-match-sparse-tree t])
21772 "--"
21773 ["Export/Publish..." org-export-dispatch t]
21774 ("LaTeX"
21775 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21776 :selected org-cdlatex-mode]
21777 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21778 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21779 ["Modify math symbol" org-cdlatex-math-modify
21780 (org-inside-LaTeX-fragment-p)]
21781 ["Insert citation" org-reftex-citation t])
21782 "--"
21783 ("MobileOrg"
21784 ["Push Files and Views" org-mobile-push t]
21785 ["Get Captured and Flagged" org-mobile-pull t]
21786 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21787 "--"
21788 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21789 "--"
21790 ("Documentation"
21791 ["Show Version" org-version t]
21792 ["Info Documentation" org-info t])
21793 ("Customize"
21794 ["Browse Org Group" org-customize t]
21795 "--"
21796 ["Expand This Menu" org-create-customize-menu
21797 (fboundp 'customize-menu-create)])
21798 ["Send bug report" org-submit-bug-report t]
21799 "--"
21800 ("Refresh/Reload"
21801 ["Refresh setup current buffer" org-mode-restart t]
21802 ["Reload Org (after update)" org-reload t]
21803 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21806 (defun org-info (&optional node)
21807 "Read documentation for Org in the info system.
21808 With optional NODE, go directly to that node."
21809 (interactive)
21810 (info (format "(org)%s" (or node ""))))
21812 ;;;###autoload
21813 (defun org-submit-bug-report ()
21814 "Submit a bug report on Org via mail.
21816 Don't hesitate to report any problems or inaccurate documentation.
21818 If you don't have setup sending mail from (X)Emacs, please copy the
21819 output buffer into your mail program, as it gives us important
21820 information about your Org version and configuration."
21821 (interactive)
21822 (require 'reporter)
21823 (defvar reporter-prompt-for-summary-p)
21824 (org-load-modules-maybe)
21825 (org-require-autoloaded-modules)
21826 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21827 (reporter-submit-bug-report
21828 "emacs-orgmode@gnu.org"
21829 (org-version nil 'full)
21830 (let (list)
21831 (save-window-excursion
21832 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21833 (delete-other-windows)
21834 (erase-buffer)
21835 (insert "You are about to submit a bug report to the Org mailing list.
21837 We would like to add your full Org and Outline configuration to the
21838 bug report. This greatly simplifies the work of the maintainer and
21839 other experts on the mailing list.
21841 HOWEVER, some variables you have customized may contain private
21842 information. The names of customers, colleagues, or friends, might
21843 appear in the form of file names, tags, todo states, or search strings.
21844 If you answer yes to the prompt, you might want to check and remove
21845 such private information before sending the email.")
21846 (add-text-properties (point-min) (point-max) '(face org-warning))
21847 (when (yes-or-no-p "Include your Org configuration ")
21848 (mapatoms
21849 (lambda (v)
21850 (and (boundp v)
21851 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21852 (or (and (symbol-value v)
21853 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21854 (and
21855 (get v 'custom-type) (get v 'standard-value)
21856 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21857 (push v list)))))
21858 (kill-buffer (get-buffer "*Warn about privacy*"))
21859 list))
21860 nil nil
21861 "Remember to cover the basics, that is, what you expected to happen and
21862 what in fact did happen. You don't know how to make a good report? See
21864 http://orgmode.org/manual/Feedback.html#Feedback
21866 Your bug report will be posted to the Org mailing list.
21867 ------------------------------------------------------------------------")
21868 (save-excursion
21869 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21870 (replace-match "\\1Bug: \\3 [\\2]")))))
21873 (defun org-install-agenda-files-menu ()
21874 (let ((bl (buffer-list)))
21875 (save-excursion
21876 (while bl
21877 (set-buffer (pop bl))
21878 (when (derived-mode-p 'org-mode) (setq bl nil)))
21879 (when (derived-mode-p 'org-mode)
21880 (easy-menu-change
21881 '("Org") "File List for Agenda"
21882 (append
21883 (list
21884 ["Edit File List" (org-edit-agenda-file-list) t]
21885 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21886 ["Remove Current File from List" org-remove-file t]
21887 ["Cycle through agenda files" org-cycle-agenda-files t]
21888 ["Occur in all agenda files" org-occur-in-agenda-files t]
21889 "--")
21890 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21892 ;;;; Documentation
21894 (defun org-require-autoloaded-modules ()
21895 (interactive)
21896 (mapc #'require
21897 '(org-agenda org-archive org-attach org-clock org-colview org-id
21898 org-table org-timer)))
21900 ;;;###autoload
21901 (defun org-reload (&optional uncompiled)
21902 "Reload all org lisp files.
21903 With prefix arg UNCOMPILED, load the uncompiled versions."
21904 (interactive "P")
21905 (require 'loadhist)
21906 (let* ((org-dir (org-find-library-dir "org"))
21907 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21908 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21909 (remove-re (format "\\`%s\\'"
21910 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21911 (feats (delete-dups
21912 (mapcar 'file-name-sans-extension
21913 (mapcar 'file-name-nondirectory
21914 (delq nil
21915 (mapcar 'feature-file
21916 features))))))
21917 (lfeat (append
21918 (sort
21919 (setq feats
21920 (delq nil (mapcar
21921 (lambda (f)
21922 (if (and (string-match feature-re f)
21923 (not (string-match remove-re f)))
21924 f nil))
21925 feats)))
21926 'string-lessp)
21927 (list "org-version" "org")))
21928 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21929 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21930 load-uncore load-misses)
21931 (setq load-misses
21932 (delq 't
21933 (mapcar (lambda (f)
21934 (or (org-load-noerror-mustsuffix (concat org-dir f))
21935 (and (string= org-dir contrib-dir)
21936 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21937 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21938 (add-to-list 'load-uncore f 'append)
21941 lfeat)))
21942 (when load-uncore
21943 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21944 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21945 (if load-misses
21946 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21947 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21948 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21950 ;;;###autoload
21951 (defun org-customize ()
21952 "Call the customize function with org as argument."
21953 (interactive)
21954 (org-load-modules-maybe)
21955 (org-require-autoloaded-modules)
21956 (customize-browse 'org))
21958 (defun org-create-customize-menu ()
21959 "Create a full customization menu for Org mode, insert it into the menu."
21960 (interactive)
21961 (org-load-modules-maybe)
21962 (org-require-autoloaded-modules)
21963 (if (fboundp 'customize-menu-create)
21964 (progn
21965 (easy-menu-change
21966 '("Org") "Customize"
21967 `(["Browse Org group" org-customize t]
21968 "--"
21969 ,(customize-menu-create 'org)
21970 ["Set" Custom-set t]
21971 ["Save" Custom-save t]
21972 ["Reset to Current" Custom-reset-current t]
21973 ["Reset to Saved" Custom-reset-saved t]
21974 ["Reset to Standard Settings" Custom-reset-standard t]))
21975 (message "\"Org\"-menu now contains full customization menu"))
21976 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21978 ;;;; Miscellaneous stuff
21980 ;;; Generally useful functions
21982 (defun org-get-at-eol (property n)
21983 "Get text property PROPERTY at the end of line less N characters."
21984 (get-text-property (- (point-at-eol) n) property))
21986 (defun org-find-text-property-in-string (prop s)
21987 "Return the first non-nil value of property PROP in string S."
21988 (or (get-text-property 0 prop s)
21989 (get-text-property (or (next-single-property-change 0 prop s) 0)
21990 prop s)))
21992 (defun org-display-warning (message)
21993 "Display the given MESSAGE as a warning."
21994 (display-warning 'org message :warning))
21996 (defun org-eval (form)
21997 "Eval FORM and return result."
21998 (condition-case error
21999 (eval form)
22000 (error (format "%%![Error: %s]" error))))
22002 (defun org-in-clocktable-p ()
22003 "Check if the cursor is in a clocktable."
22004 (let ((pos (point)) start)
22005 (save-excursion
22006 (end-of-line 1)
22007 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22008 (setq start (match-beginning 0))
22009 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22010 (>= (match-end 0) pos)
22011 start))))
22013 (defun org-in-verbatim-emphasis ()
22014 (save-match-data
22015 (and (org-in-regexp org-emph-re 2)
22016 (>= (point) (match-beginning 3))
22017 (<= (point) (match-end 4))
22018 (member (match-string 3) '("=" "~")))))
22020 (defun org-overlay-display (ovl text &optional face evap)
22021 "Make overlay OVL display TEXT with face FACE."
22022 (overlay-put ovl 'display text)
22023 (if face (overlay-put ovl 'face face))
22024 (if evap (overlay-put ovl 'evaporate t)))
22026 (defun org-overlay-before-string (ovl text &optional face evap)
22027 "Make overlay OVL display TEXT with face FACE."
22028 (if face (org-add-props text nil 'face face))
22029 (overlay-put ovl 'before-string text)
22030 (if evap (overlay-put ovl 'evaporate t)))
22032 (defun org-find-overlays (prop &optional pos delete)
22033 "Find all overlays specifying PROP at POS or point.
22034 If DELETE is non-nil, delete all those overlays."
22035 (let (found)
22036 (dolist (ov (overlays-at (or pos (point))) found)
22037 (cond ((not (overlay-get ov prop)))
22038 (delete (delete-overlay ov))
22039 (t (push ov found))))))
22041 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22042 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22043 (if (and marker (marker-buffer marker)
22044 (buffer-live-p (marker-buffer marker)))
22045 (progn
22046 (pop-to-buffer-same-window (marker-buffer marker))
22047 (when (or (> marker (point-max)) (< marker (point-min)))
22048 (widen))
22049 (goto-char marker)
22050 (org-show-context 'org-goto))
22051 (if bookmark
22052 (bookmark-jump bookmark)
22053 (error "Cannot find location"))))
22055 (defun org-quote-csv-field (s)
22056 "Quote field for inclusion in CSV material."
22057 (if (string-match "[\",]" s)
22058 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22061 (defun org-force-self-insert (N)
22062 "Needed to enforce self-insert under remapping."
22063 (interactive "p")
22064 (self-insert-command N))
22066 (defun org-string-width (s)
22067 "Compute width of string, ignoring invisible characters.
22068 This ignores character with invisibility property `org-link', and also
22069 characters with property `org-cwidth', because these will become invisible
22070 upon the next fontification round."
22071 (let (b l)
22072 (when (or (eq t buffer-invisibility-spec)
22073 (assq 'org-link buffer-invisibility-spec))
22074 (while (setq b (text-property-any 0 (length s)
22075 'invisible 'org-link s))
22076 (setq s (concat (substring s 0 b)
22077 (substring s (or (next-single-property-change
22078 b 'invisible s)
22079 (length s)))))))
22080 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22081 (setq s (concat (substring s 0 b)
22082 (substring s (or (next-single-property-change
22083 b 'org-cwidth s)
22084 (length s))))))
22085 (setq l (string-width s) b -1)
22086 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22087 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22090 (defun org-shorten-string (s maxlength)
22091 "Shorten string S so that it is no longer than MAXLENGTH characters.
22092 If the string is shorter or has length MAXLENGTH, just return the
22093 original string. If it is longer, the functions finds a space in the
22094 string, breaks this string off at that locations and adds three dots
22095 as ellipsis. Including the ellipsis, the string will not be longer
22096 than MAXLENGTH. If finding a good breaking point in the string does
22097 not work, the string is just chopped off in the middle of a word
22098 if necessary."
22099 (if (<= (length s) maxlength)
22101 (let* ((n (max (- maxlength 4) 1))
22102 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22103 (if (string-match re s)
22104 (concat (match-string 1 s) "...")
22105 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22107 (defun org-get-indentation (&optional line)
22108 "Get the indentation of the current line, interpreting tabs.
22109 When LINE is given, assume it represents a line and compute its indentation."
22110 (if line
22111 (when (string-match "^ *" (org-remove-tabs line))
22112 (match-end 0))
22113 (save-excursion
22114 (beginning-of-line 1)
22115 (skip-chars-forward " \t")
22116 (current-column))))
22118 (defun org-get-string-indentation (s)
22119 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22120 (let ((n -1) (i 0) (w tab-width) c)
22121 (catch 'exit
22122 (while (< (setq n (1+ n)) (length s))
22123 (setq c (aref s n))
22124 (cond ((= c ?\ ) (setq i (1+ i)))
22125 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22126 (t (throw 'exit t)))))
22129 (defun org-remove-tabs (s &optional width)
22130 "Replace tabulators in S with spaces.
22131 Assumes that s is a single line, starting in column 0."
22132 (setq width (or width tab-width))
22133 (while (string-match "\t" s)
22134 (setq s (replace-match
22135 (make-string
22136 (- (* width (/ (+ (match-beginning 0) width) width))
22137 (match-beginning 0)) ?\ )
22138 t t s)))
22141 (defun org-fix-indentation (line ind)
22142 "Fix indentation in LINE.
22143 IND is a cons cell with target and minimum indentation.
22144 If the current indentation in LINE is smaller than the minimum,
22145 leave it alone. If it is larger than ind, set it to the target."
22146 (let* ((l (org-remove-tabs line))
22147 (i (org-get-indentation l))
22148 (i1 (car ind)) (i2 (cdr ind)))
22149 (when (>= i i2) (setq l (substring line i2)))
22150 (if (> i1 0)
22151 (concat (make-string i1 ?\ ) l)
22152 l)))
22154 (defun org-remove-indentation (code &optional n)
22155 "Remove maximum common indentation in string CODE and return it.
22156 N may optionally be the number of columns to remove. Return CODE
22157 as-is if removal failed."
22158 (with-temp-buffer
22159 (insert code)
22160 (if (org-do-remove-indentation n) (buffer-string) code)))
22162 (defun org-do-remove-indentation (&optional n)
22163 "Remove the maximum common indentation from the buffer.
22164 When optional argument N is a positive integer, remove exactly
22165 that much characters from indentation, if possible. Return nil
22166 if it fails."
22167 (catch :exit
22168 (goto-char (point-min))
22169 ;; Find maximum common indentation, if not specified.
22170 (let ((n (or n
22171 (let ((min-ind (point-max)))
22172 (save-excursion
22173 (while (re-search-forward "^[ \t]*\\S-" nil t)
22174 (let ((ind (1- (current-column))))
22175 (if (zerop ind) (throw :exit nil)
22176 (setq min-ind (min min-ind ind))))))
22177 min-ind))))
22178 (if (zerop n) (throw :exit nil)
22179 ;; Remove exactly N indentation, but give up if not possible.
22180 (while (not (eobp))
22181 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22182 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22183 ((< ind n) (throw :exit nil))
22184 (t (indent-line-to (- ind n))))
22185 (forward-line)))
22186 ;; Signal success.
22187 t))))
22189 (defun org-fill-template (template alist)
22190 "Find each %key of ALIST in TEMPLATE and replace it."
22191 (let ((case-fold-search nil))
22192 (dolist (entry (sort (copy-sequence alist)
22193 (lambda (a b) (< (length (car a)) (length (car b))))))
22194 (setq template
22195 (replace-regexp-in-string
22196 (concat "%" (regexp-quote (car entry)))
22197 (or (cdr entry) "") template t t)))
22198 template))
22200 (defun org-base-buffer (buffer)
22201 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22202 (if (not buffer)
22203 buffer
22204 (or (buffer-base-buffer buffer)
22205 buffer)))
22207 (defun org-wrap (string &optional width lines)
22208 "Wrap string to either a number of lines, or a width in characters.
22209 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22210 that costs. If there is a word longer than WIDTH, the text is actually
22211 wrapped to the length of that word.
22212 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22213 many lines, whatever width that takes.
22214 The return value is a list of lines, without newlines at the end."
22215 (let* ((words (org-split-string string "[ \t\n]+"))
22216 (maxword (apply 'max (mapcar 'org-string-width words)))
22217 w ll)
22218 (cond (width
22219 (org-do-wrap words (max maxword width)))
22220 (lines
22221 (setq w maxword)
22222 (setq ll (org-do-wrap words maxword))
22223 (if (<= (length ll) lines)
22225 (setq ll words)
22226 (while (> (length ll) lines)
22227 (setq w (1+ w))
22228 (setq ll (org-do-wrap words w)))
22229 ll))
22230 (t (error "Cannot wrap this")))))
22232 (defun org-do-wrap (words width)
22233 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22234 (let (lines line)
22235 (while words
22236 (setq line (pop words))
22237 (while (and words (< (+ (length line) (length (car words))) width))
22238 (setq line (concat line " " (pop words))))
22239 (setq lines (push line lines)))
22240 (nreverse lines)))
22242 (defun org-split-string (string &optional separators)
22243 "Splits STRING into substrings at SEPARATORS.
22244 SEPARATORS is a regular expression.
22245 No empty strings are returned if there are matches at the beginning
22246 and end of string."
22247 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22248 (let ((start 0) notfirst list)
22249 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22250 (if (and notfirst
22251 (= start (match-beginning 0))
22252 (< start (length string)))
22253 (1+ start) start))
22254 (< (match-beginning 0) (length string)))
22255 (setq notfirst t)
22256 (or (eq (match-beginning 0) 0)
22257 (and (eq (match-beginning 0) (match-end 0))
22258 (eq (match-beginning 0) start))
22259 (push (substring string start (match-beginning 0)) list))
22260 (setq start (match-end 0)))
22261 (or (eq start (length string))
22262 (push (substring string start) list))
22263 (nreverse list)))
22265 (defun org-quote-vert (s)
22266 "Replace \"|\" with \"\\vert\"."
22267 (while (string-match "|" s)
22268 (setq s (replace-match "\\vert" t t s)))
22271 (defun org-uuidgen-p (s)
22272 "Is S an ID created by UUIDGEN?"
22273 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22275 (defun org-in-src-block-p (&optional inside)
22276 "Whether point is in a code source block.
22277 When INSIDE is non-nil, don't consider we are within a src block
22278 when point is at #+BEGIN_SRC or #+END_SRC."
22279 (let ((case-fold-search t))
22280 (or (and (eq (get-char-property (point) 'src-block) t))
22281 (and (not inside)
22282 (save-match-data
22283 (save-excursion
22284 (beginning-of-line)
22285 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22287 (defun org-context ()
22288 "Return a list of contexts of the current cursor position.
22289 If several contexts apply, all are returned.
22290 Each context entry is a list with a symbol naming the context, and
22291 two positions indicating start and end of the context. Possible
22292 contexts are:
22294 :headline anywhere in a headline
22295 :headline-stars on the leading stars in a headline
22296 :todo-keyword on a TODO keyword (including DONE) in a headline
22297 :tags on the TAGS in a headline
22298 :priority on the priority cookie in a headline
22299 :item on the first line of a plain list item
22300 :item-bullet on the bullet/number of a plain list item
22301 :checkbox on the checkbox in a plain list item
22302 :table in an Org table
22303 :table-special on a special filed in a table
22304 :table-table in a table.el table
22305 :clocktable in a clocktable
22306 :src-block in a source block
22307 :link on a hyperlink
22308 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22309 :target on a <<target>>
22310 :radio-target on a <<<radio-target>>>
22311 :latex-fragment on a LaTeX fragment
22312 :latex-preview on a LaTeX fragment with overlaid preview image
22314 This function expects the position to be visible because it uses font-lock
22315 faces as a help to recognize the following contexts: :table-special, :link,
22316 and :keyword."
22317 (let* ((f (get-text-property (point) 'face))
22318 (faces (if (listp f) f (list f)))
22319 (case-fold-search t)
22320 (p (point)) clist o)
22321 ;; First the large context
22322 (cond
22323 ((org-at-heading-p t)
22324 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22325 (when (progn
22326 (beginning-of-line 1)
22327 (looking-at org-todo-line-tags-regexp))
22328 (push (org-point-in-group p 1 :headline-stars) clist)
22329 (push (org-point-in-group p 2 :todo-keyword) clist)
22330 (push (org-point-in-group p 4 :tags) clist))
22331 (goto-char p)
22332 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22333 (when (looking-at "\\[#[A-Z0-9]\\]")
22334 (push (org-point-in-group p 0 :priority) clist)))
22336 ((org-at-item-p)
22337 (push (org-point-in-group p 2 :item-bullet) clist)
22338 (push (list :item (point-at-bol)
22339 (save-excursion (org-end-of-item) (point)))
22340 clist)
22341 (and (org-at-item-checkbox-p)
22342 (push (org-point-in-group p 0 :checkbox) clist)))
22344 ((org-at-table-p)
22345 (push (list :table (org-table-begin) (org-table-end)) clist)
22346 (when (memq 'org-formula faces)
22347 (push (list :table-special
22348 (previous-single-property-change p 'face)
22349 (next-single-property-change p 'face)) clist)))
22350 ((org-at-table-p 'any)
22351 (push (list :table-table) clist)))
22352 (goto-char p)
22354 (let ((case-fold-search t))
22355 ;; New the "medium" contexts: clocktables, source blocks
22356 (cond ((org-in-clocktable-p)
22357 (push (list :clocktable
22358 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22359 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22360 (match-beginning 1))
22361 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22362 (match-end 0))) clist))
22363 ((org-in-src-block-p)
22364 (push (list :src-block
22365 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22366 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22367 (match-beginning 1))
22368 (and (search-forward "#+END_SRC" nil t)
22369 (match-beginning 0))) clist))))
22370 (goto-char p)
22372 ;; Now the small context
22373 (cond
22374 ((org-at-timestamp-p)
22375 (push (org-point-in-group p 0 :timestamp) clist))
22376 ((memq 'org-link faces)
22377 (push (list :link
22378 (previous-single-property-change p 'face)
22379 (next-single-property-change p 'face)) clist))
22380 ((memq 'org-special-keyword faces)
22381 (push (list :keyword
22382 (previous-single-property-change p 'face)
22383 (next-single-property-change p 'face)) clist))
22384 ((org-at-target-p)
22385 (push (org-point-in-group p 0 :target) clist)
22386 (goto-char (1- (match-beginning 0)))
22387 (when (looking-at org-radio-target-regexp)
22388 (push (org-point-in-group p 0 :radio-target) clist))
22389 (goto-char p))
22390 ((setq o (cl-some
22391 (lambda (o)
22392 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22394 (overlays-at (point))))
22395 (push (list :latex-fragment
22396 (overlay-start o) (overlay-end o)) clist)
22397 (push (list :latex-preview
22398 (overlay-start o) (overlay-end o)) clist))
22399 ((org-inside-LaTeX-fragment-p)
22400 ;; FIXME: positions wrong.
22401 (push (list :latex-fragment (point) (point)) clist)))
22403 (setq clist (nreverse (delq nil clist)))
22404 clist))
22406 (defun org-in-regexp (regexp &optional nlines visually)
22407 "Check if point is inside a match of REGEXP.
22409 Normally only the current line is checked, but you can include
22410 NLINES extra lines around point into the search. If VISUALLY is
22411 set, require that the cursor is not after the match but really
22412 on, so that the block visually is on the match.
22414 Return nil or a cons cell (BEG . END) where BEG and END are,
22415 respectively, the positions at the beginning and the end of the
22416 match."
22417 (catch :exit
22418 (let ((pos (point))
22419 (eol (line-end-position (if nlines (1+ nlines) 1))))
22420 (save-excursion
22421 (beginning-of-line (- 1 (or nlines 0)))
22422 (while (and (re-search-forward regexp eol t)
22423 (<= (match-beginning 0) pos))
22424 (let ((end (match-end 0)))
22425 (when (or (> end pos) (and (= end pos) (not visually)))
22426 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22428 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22429 "Non-nil when point is between matches of START-RE and END-RE.
22431 Also return a non-nil value when point is on one of the matches.
22433 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22434 buffer positions. Default values are the positions of headlines
22435 surrounding the point.
22437 The functions returns a cons cell whose car (resp. cdr) is the
22438 position before START-RE (resp. after END-RE)."
22439 (save-match-data
22440 (let ((pos (point))
22441 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22442 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22443 beg end)
22444 (save-excursion
22445 ;; Point is on a block when on START-RE or if START-RE can be
22446 ;; found before it...
22447 (and (or (org-in-regexp start-re)
22448 (re-search-backward start-re limit-up t))
22449 (setq beg (match-beginning 0))
22450 ;; ... and END-RE after it...
22451 (goto-char (match-end 0))
22452 (re-search-forward end-re limit-down t)
22453 (> (setq end (match-end 0)) pos)
22454 ;; ... without another START-RE in-between.
22455 (goto-char (match-beginning 0))
22456 (not (re-search-backward start-re (1+ beg) t))
22457 ;; Return value.
22458 (cons beg end))))))
22460 (defun org-in-block-p (names)
22461 "Non-nil when point belongs to a block whose name belongs to NAMES.
22463 NAMES is a list of strings containing names of blocks.
22465 Return first block name matched, or nil. Beware that in case of
22466 nested blocks, the returned name may not belong to the closest
22467 block from point."
22468 (save-match-data
22469 (catch 'exit
22470 (let ((case-fold-search t)
22471 (lim-up (save-excursion (outline-previous-heading)))
22472 (lim-down (save-excursion (outline-next-heading))))
22473 (dolist (name names)
22474 (let ((n (regexp-quote name)))
22475 (when (org-between-regexps-p
22476 (concat "^[ \t]*#\\+begin_" n)
22477 (concat "^[ \t]*#\\+end_" n)
22478 lim-up lim-down)
22479 (throw 'exit n)))))
22480 nil)))
22482 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22483 "Call `multi-occur' with buffers for all agenda files."
22484 (interactive "sOrg-files matching: ")
22485 (let* ((files (org-agenda-files))
22486 (tnames (mapcar #'file-truename files))
22487 (extra org-agenda-text-search-extra-files))
22488 (when (eq (car extra) 'agenda-archives)
22489 (setq extra (cdr extra))
22490 (setq files (org-add-archive-files files)))
22491 (dolist (f extra)
22492 (unless (member (file-truename f) tnames)
22493 (unless (member f files) (setq files (append files (list f))))
22494 (setq tnames (append tnames (list (file-truename f))))))
22495 (multi-occur
22496 (mapcar (lambda (x)
22497 (with-current-buffer
22498 ;; FIXME: Why not just (find-file-noselect x)?
22499 ;; Is it to avoid the "revert buffer" prompt?
22500 (or (get-file-buffer x) (find-file-noselect x))
22501 (widen)
22502 (current-buffer)))
22503 files)
22504 regexp)))
22506 (add-hook 'occur-mode-find-occurrence-hook
22507 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22509 (defun org-occur-link-in-agenda-files ()
22510 "Create a link and search for it in the agendas.
22511 The link is not stored in `org-stored-links', it is just created
22512 for the search purpose."
22513 (interactive)
22514 (let ((link (condition-case nil
22515 (org-store-link nil)
22516 (error "Unable to create a link to here"))))
22517 (org-occur-in-agenda-files (regexp-quote link))))
22519 (defun org-reverse-string (string)
22520 "Return the reverse of STRING."
22521 (apply 'string (reverse (string-to-list string))))
22523 ;; defsubst org-uniquify must be defined before first use
22525 (defun org-uniquify-alist (alist)
22526 "Merge elements of ALIST with the same key.
22528 For example, in this alist:
22530 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22531 => \\='((a 1 3) (b 2))
22533 merge (a 1) and (a 3) into (a 1 3).
22535 The function returns the new ALIST."
22536 (let (rtn)
22537 (dolist (e alist rtn)
22538 (let (n)
22539 (if (not (assoc (car e) rtn))
22540 (push e rtn)
22541 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22542 (setq rtn (assq-delete-all (car e) rtn))
22543 (push n rtn))))))
22545 (defun org-delete-all (elts list)
22546 "Remove all elements in ELTS from LIST.
22547 Comparison is done with `equal'. It is a destructive operation
22548 that may remove elements by altering the list structure."
22549 (while elts
22550 (setq list (delete (pop elts) list)))
22551 list)
22553 (defun org-back-over-empty-lines ()
22554 "Move backwards over whitespace, to the beginning of the first empty line.
22555 Returns the number of empty lines passed."
22556 (let ((pos (point)))
22557 (if (cdr (assq 'heading org-blank-before-new-entry))
22558 (skip-chars-backward " \t\n\r")
22559 (unless (eobp)
22560 (forward-line -1)))
22561 (beginning-of-line 2)
22562 (goto-char (min (point) pos))
22563 (count-lines (point) pos)))
22565 (defun org-skip-whitespace ()
22566 (skip-chars-forward " \t\n\r"))
22568 (defun org-point-in-group (point group &optional context)
22569 "Check if POINT is in match-group GROUP.
22570 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22571 match. If the match group does not exist or point is not inside it,
22572 return nil."
22573 (and (match-beginning group)
22574 (>= point (match-beginning group))
22575 (<= point (match-end group))
22576 (if context
22577 (list context (match-beginning group) (match-end group))
22578 t)))
22580 (defun org-switch-to-buffer-other-window (&rest args)
22581 "Switch to buffer in a second window on the current frame.
22582 In particular, do not allow pop-up frames.
22583 Returns the newly created buffer."
22584 (org-no-popups
22585 (apply 'switch-to-buffer-other-window args)))
22587 (defun org-combine-plists (&rest plists)
22588 "Create a single property list from all plists in PLISTS.
22589 The process starts by copying the first list, and then setting properties
22590 from the other lists. Settings in the last list are the most significant
22591 ones and overrule settings in the other lists."
22592 (let ((rtn (copy-sequence (pop plists)))
22593 p v ls)
22594 (while plists
22595 (setq ls (pop plists))
22596 (while ls
22597 (setq p (pop ls) v (pop ls))
22598 (setq rtn (plist-put rtn p v))))
22599 rtn))
22601 (defun org-replace-escapes (string table)
22602 "Replace %-escapes in STRING with values in TABLE.
22603 TABLE is an association list with keys like \"%a\" and string values.
22604 The sequences in STRING may contain normal field width and padding information,
22605 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22606 so values can contain further %-escapes if they are define later in TABLE."
22607 (let ((tbl (copy-alist table))
22608 (case-fold-search nil)
22609 (pchg 0)
22610 re rpl)
22611 (dolist (e tbl)
22612 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22613 (when (and (cdr e) (string-match re (cdr e)))
22614 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22615 (safe "SREF"))
22616 (add-text-properties 0 3 (list 'sref sref) safe)
22617 (setcdr e (replace-match safe t t (cdr e)))))
22618 (while (string-match re string)
22619 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22620 (cdr e)))
22621 (setq string (replace-match rpl t t string))))
22622 (while (setq pchg (next-property-change pchg string))
22623 (let ((sref (get-text-property pchg 'sref string)))
22624 (when (and sref (string-match "SREF" string pchg))
22625 (setq string (replace-match sref t t string)))))
22626 string))
22628 (defun org-find-base-buffer-visiting (file)
22629 "Like `find-buffer-visiting' but always return the base buffer and
22630 not an indirect buffer."
22631 (let ((buf (or (get-file-buffer file)
22632 (find-buffer-visiting file))))
22633 (if buf
22634 (or (buffer-base-buffer buf) buf)
22635 nil)))
22637 ;;; TODO: Only called once, from ox-odt which should probably use
22638 ;;; org-export-inline-image-p or something.
22639 (defun org-file-image-p (file)
22640 "Return non-nil if FILE is an image."
22641 (save-match-data
22642 (string-match (image-file-name-regexp) file)))
22644 (defun org-get-cursor-date (&optional with-time)
22645 "Return the date at cursor in as a time.
22646 This works in the calendar and in the agenda, anywhere else it just
22647 returns the current time.
22648 If WITH-TIME is non-nil, returns the time of the event at point (in
22649 the agenda) or the current time of the day."
22650 (let (date day defd tp hod mod)
22651 (when with-time
22652 (setq tp (get-text-property (point) 'time))
22653 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22654 (setq hod (string-to-number (match-string 1 tp))
22655 mod (string-to-number (match-string 2 tp))))
22656 (or tp (let ((now (decode-time)))
22657 (setq hod (nth 2 now)
22658 mod (nth 1 now)))))
22659 (cond
22660 ((eq major-mode 'calendar-mode)
22661 (setq date (calendar-cursor-to-date)
22662 defd (encode-time 0 (or mod 0) (or hod 0)
22663 (nth 1 date) (nth 0 date) (nth 2 date))))
22664 ((eq major-mode 'org-agenda-mode)
22665 (setq day (get-text-property (point) 'day))
22666 (when day
22667 (setq date (calendar-gregorian-from-absolute day)
22668 defd (encode-time 0 (or mod 0) (or hod 0)
22669 (nth 1 date) (nth 0 date) (nth 2 date))))))
22670 (or defd (current-time))))
22672 (defun org-mark-subtree (&optional up)
22673 "Mark the current subtree.
22674 This puts point at the start of the current subtree, and mark at
22675 the end. If a numeric prefix UP is given, move up into the
22676 hierarchy of headlines by UP levels before marking the subtree."
22677 (interactive "P")
22678 (org-with-limited-levels
22679 (cond ((org-at-heading-p) (beginning-of-line))
22680 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22681 (t (outline-previous-visible-heading 1))))
22682 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22683 (if (called-interactively-p 'any)
22684 (call-interactively 'org-mark-element)
22685 (org-mark-element)))
22687 (defun org-file-newer-than-p (file time)
22688 "Non-nil if FILE is newer than TIME.
22689 FILE is a filename, as a string, TIME is a list of integers, as
22690 returned by, e.g., `current-time'."
22691 (and (file-exists-p file)
22692 ;; Only compare times up to whole seconds as some file-systems
22693 ;; (e.g. HFS+) do not retain any finer granularity. As
22694 ;; a consequence, make sure we return non-nil when the two
22695 ;; times are equal.
22696 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22697 (cl-subseq time 0 2)))))
22699 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22700 "Compile a SOURCE file using PROCESS.
22702 PROCESS is either a function or a list of shell commands, as
22703 strings. EXT is a file extension, without the leading dot, as
22704 a string. It is used to check if the process actually succeeded.
22706 PROCESS must create a file with the same base name and directory
22707 as SOURCE, but ending with EXT. The function then returns its
22708 filename. Otherwise, it raises an error. The error message can
22709 then be refined by providing string ERR-MSG, which is appended to
22710 the standard message.
22712 If PROCESS is a function, it is called with a single argument:
22713 the SOURCE file.
22715 If it is a list of commands, each of them is called using
22716 `shell-command'. By default, in each command, %b, %f, %F and %o
22717 are replaced with, respectively, SOURCE base name, name, full
22718 name and directory. It is possible, however, to use more
22719 place-holders by specifying them in optional argument SPEC, as an
22720 alist following the pattern (CHARACTER . REPLACEMENT-STRING).
22722 When PROCESS is a list of commands, optional argument LOG-BUF can
22723 be set to a buffer or a buffer name. `shell-command' then uses
22724 it for output.
22726 `default-directory' is set to SOURCE directory during the whole
22727 process."
22728 (let* ((source-name (file-name-nondirectory source))
22729 (base-name (file-name-sans-extension source-name))
22730 (full-name (file-truename source))
22731 (out-dir (file-name-directory source))
22732 (time (current-time))
22733 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22734 (save-window-excursion
22735 (let ((default-directory (file-name-directory full-name)))
22736 (pcase process
22737 ((pred functionp) (funcall process (shell-quote-argument source)))
22738 ((pred consp)
22739 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22740 (spec (append spec
22741 `((?b . ,(shell-quote-argument base-name))
22742 (?f . ,(shell-quote-argument source-name))
22743 (?F . ,(shell-quote-argument full-name))
22744 (?o . ,(shell-quote-argument out-dir))))))
22745 (dolist (command process)
22746 (shell-command (format-spec command spec) log-buf))))
22747 (_ (error "No valid command to process %S%s" source err-msg)))))
22748 ;; Check for process failure.
22749 (let ((output (concat out-dir base-name "." ext)))
22750 (unless (org-file-newer-than-p output time)
22751 (error (format "File %S wasn't produced%s" output err-msg)))
22752 output)))
22754 ;;; Indentation
22756 (defun org--get-expected-indentation (element contentsp)
22757 "Expected indentation column for current line, according to ELEMENT.
22758 ELEMENT is an element containing point. CONTENTSP is non-nil
22759 when indentation is to be computed according to contents of
22760 ELEMENT."
22761 (let ((type (org-element-type element))
22762 (start (org-element-property :begin element))
22763 (post-affiliated (org-element-property :post-affiliated element)))
22764 (org-with-wide-buffer
22765 (cond
22766 (contentsp
22767 (cl-case type
22768 ((diary-sexp footnote-definition) 0)
22769 ((headline inlinetask nil)
22770 (if (not org-adapt-indentation) 0
22771 (let ((level (org-current-level)))
22772 (if level (1+ level) 0))))
22773 ((item plain-list) (org-list-item-body-column post-affiliated))
22775 (goto-char start)
22776 (org-get-indentation))))
22777 ((memq type '(headline inlinetask nil))
22778 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22779 (org--get-expected-indentation element t)
22781 ((memq type '(diary-sexp footnote-definition)) 0)
22782 ;; First paragraph of a footnote definition or an item.
22783 ;; Indent like parent.
22784 ((< (line-beginning-position) start)
22785 (org--get-expected-indentation
22786 (org-element-property :parent element) t))
22787 ;; At first line: indent according to previous sibling, if any,
22788 ;; ignoring footnote definitions and inline tasks, or parent's
22789 ;; contents.
22790 ((= (line-beginning-position) start)
22791 (catch 'exit
22792 (while t
22793 (if (= (point-min) start) (throw 'exit 0)
22794 (goto-char (1- start))
22795 (let* ((previous (org-element-at-point))
22796 (parent previous))
22797 (while (and parent (<= (org-element-property :end parent) start))
22798 (setq previous parent
22799 parent (org-element-property :parent parent)))
22800 (cond
22801 ((not previous) (throw 'exit 0))
22802 ((> (org-element-property :end previous) start)
22803 (throw 'exit (org--get-expected-indentation previous t)))
22804 ((memq (org-element-type previous)
22805 '(footnote-definition inlinetask))
22806 (setq start (org-element-property :begin previous)))
22807 (t (goto-char (org-element-property :begin previous))
22808 (throw 'exit
22809 (if (bolp) (org-get-indentation)
22810 ;; At first paragraph in an item or
22811 ;; a footnote definition.
22812 (org--get-expected-indentation
22813 (org-element-property :parent previous) t))))))))))
22814 ;; Otherwise, move to the first non-blank line above.
22816 (beginning-of-line)
22817 (let ((pos (point)))
22818 (skip-chars-backward " \r\t\n")
22819 (cond
22820 ;; Two blank lines end a footnote definition or a plain
22821 ;; list. When we indent an empty line after them, the
22822 ;; containing list or footnote definition is over, so it
22823 ;; qualifies as a previous sibling. Therefore, we indent
22824 ;; like its first line.
22825 ((and (memq type '(footnote-definition plain-list))
22826 (> (count-lines (point) pos) 2))
22827 (goto-char start)
22828 (org-get-indentation))
22829 ;; Line above is the first one of a paragraph at the
22830 ;; beginning of an item or a footnote definition. Indent
22831 ;; like parent.
22832 ((< (line-beginning-position) start)
22833 (org--get-expected-indentation
22834 (org-element-property :parent element) t))
22835 ;; Line above is the beginning of an element, i.e., point
22836 ;; was originally on the blank lines between element's start
22837 ;; and contents.
22838 ((= (line-beginning-position) post-affiliated)
22839 (org--get-expected-indentation element t))
22840 ;; POS is after contents in a greater element. Indent like
22841 ;; the beginning of the element.
22843 ;; As a special case, if point is at the end of a footnote
22844 ;; definition or an item, indent like the very last element
22845 ;; within. If that last element is an item, indent like its
22846 ;; contents.
22847 ((and (not (eq type 'paragraph))
22848 (let ((cend (org-element-property :contents-end element)))
22849 (and cend (<= cend pos))))
22850 (if (memq type '(footnote-definition item plain-list))
22851 (let ((last (org-element-at-point)))
22852 (org--get-expected-indentation
22853 last (eq (org-element-type last) 'item)))
22854 (goto-char start)
22855 (org-get-indentation)))
22856 ;; In any other case, indent like the current line.
22857 (t (org-get-indentation)))))))))
22859 (defun org--align-node-property ()
22860 "Align node property at point.
22861 Alignment is done according to `org-property-format', which see."
22862 (when (save-excursion
22863 (beginning-of-line)
22864 (looking-at org-property-re))
22865 (replace-match
22866 (concat (match-string 4)
22867 (org-trim
22868 (format org-property-format (match-string 1) (match-string 3))))
22869 t t)))
22871 (defun org-indent-line ()
22872 "Indent line depending on context.
22874 Indentation is done according to the following rules:
22876 - Footnote definitions, diary sexps, headlines and inline tasks
22877 have to start at column 0.
22879 - On the very first line of an element, consider, in order, the
22880 next rules until one matches:
22882 1. If there's a sibling element before, ignoring footnote
22883 definitions and inline tasks, indent like its first line.
22885 2. If element has a parent, indent like its contents. More
22886 precisely, if parent is an item, indent after the
22887 description part, if any, or the bullet (see
22888 `org-list-description-max-indent'). Else, indent like
22889 parent's first line.
22891 3. Otherwise, indent relatively to current level, if
22892 `org-adapt-indentation' is non-nil, or to left margin.
22894 - On a blank line at the end of an element, indent according to
22895 the type of the element. More precisely
22897 1. If element is a plain list, an item, or a footnote
22898 definition, indent like the very last element within.
22900 2. If element is a paragraph, indent like its last non blank
22901 line.
22903 3. Otherwise, indent like its very first line.
22905 - In the code part of a source block, use language major mode
22906 to indent current line if `org-src-tab-acts-natively' is
22907 non-nil. If it is nil, do nothing.
22909 - Otherwise, indent like the first non-blank line above.
22911 The function doesn't indent an item as it could break the whole
22912 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22913 `\\[org-shiftmetaright]'.
22915 Also align node properties according to `org-property-format'."
22916 (interactive)
22917 (cond
22918 (orgstruct-is-++
22919 (let ((indent-line-function
22920 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22921 (indent-according-to-mode)))
22922 ((org-at-heading-p) 'noindent)
22924 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22925 (type (org-element-type element)))
22926 (cond ((and (memq type '(plain-list item))
22927 (= (line-beginning-position)
22928 (org-element-property :post-affiliated element)))
22929 'noindent)
22930 ((and (eq type 'src-block)
22931 org-src-tab-acts-natively
22932 (> (line-beginning-position)
22933 (org-element-property :post-affiliated element))
22934 (< (line-beginning-position)
22935 (org-with-wide-buffer
22936 (goto-char (org-element-property :end element))
22937 (skip-chars-backward " \r\t\n")
22938 (line-beginning-position))))
22939 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22941 (let ((column (org--get-expected-indentation element nil)))
22942 ;; Preserve current column.
22943 (if (<= (current-column) (current-indentation))
22944 (indent-line-to column)
22945 (save-excursion (indent-line-to column))))
22946 ;; Align node property. Also preserve current column.
22947 (when (eq type 'node-property)
22948 (let ((column (current-column)))
22949 (org--align-node-property)
22950 (org-move-to-column column)))))))))
22952 (defun org-indent-region (start end)
22953 "Indent each non-blank line in the region.
22954 Called from a program, START and END specify the region to
22955 indent. The function will not indent contents of example blocks,
22956 verse blocks and export blocks as leading white spaces are
22957 assumed to be significant there."
22958 (interactive "r")
22959 (save-excursion
22960 (goto-char start)
22961 (skip-chars-forward " \r\t\n")
22962 (unless (eobp) (beginning-of-line))
22963 (let ((indent-to
22964 (lambda (ind pos)
22965 ;; Set IND as indentation for all lines between point and
22966 ;; POS. Blank lines are ignored. Leave point after POS
22967 ;; once done.
22968 (let ((limit (copy-marker pos)))
22969 (while (< (point) limit)
22970 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22971 (forward-line))
22972 (set-marker limit nil))))
22973 (end (copy-marker end)))
22974 (while (< (point) end)
22975 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22976 (let* ((element (org-element-at-point))
22977 (type (org-element-type element))
22978 (element-end (copy-marker (org-element-property :end element)))
22979 (ind (org--get-expected-indentation element nil)))
22980 (cond
22981 ((or (memq type '(paragraph table table-row))
22982 (not (or (org-element-property :contents-begin element)
22983 (memq type
22984 '(example-block export-block src-block)))))
22985 ;; Elements here are indented as a single block. Also
22986 ;; align node properties.
22987 (when (eq type 'node-property)
22988 (org--align-node-property)
22989 (beginning-of-line))
22990 (funcall indent-to ind (min element-end end)))
22992 ;; Elements in this category consist of three parts:
22993 ;; before the contents, the contents, and after the
22994 ;; contents. The contents are treated specially,
22995 ;; according to the element type, or not indented at
22996 ;; all. Other parts are indented as a single block.
22997 (let* ((post (copy-marker
22998 (org-element-property :post-affiliated element)))
22999 (cbeg
23000 (copy-marker
23001 (cond
23002 ((not (org-element-property :contents-begin element))
23003 ;; Fake contents for source blocks.
23004 (org-with-wide-buffer
23005 (goto-char post)
23006 (forward-line)
23007 (point)))
23008 ((memq type '(footnote-definition item plain-list))
23009 ;; Contents in these elements could start on
23010 ;; the same line as the beginning of the
23011 ;; element. Make sure we start indenting
23012 ;; from the second line.
23013 (org-with-wide-buffer
23014 (goto-char post)
23015 (end-of-line)
23016 (skip-chars-forward " \r\t\n")
23017 (if (eobp) (point) (line-beginning-position))))
23018 (t (org-element-property :contents-begin element)))))
23019 (cend (copy-marker
23020 (or (org-element-property :contents-end element)
23021 ;; Fake contents for source blocks.
23022 (org-with-wide-buffer
23023 (goto-char element-end)
23024 (skip-chars-backward " \r\t\n")
23025 (line-beginning-position)))
23026 t)))
23027 ;; Do not change items indentation individually as it
23028 ;; might break the list as a whole. On the other
23029 ;; hand, when at a plain list, indent it as a whole.
23030 (cond ((eq type 'plain-list)
23031 (let ((offset (- ind (org-get-indentation))))
23032 (unless (zerop offset)
23033 (indent-rigidly (org-element-property :begin element)
23034 (org-element-property :end element)
23035 offset))
23036 (goto-char cbeg)))
23037 ((eq type 'item) (goto-char cbeg))
23038 (t (funcall indent-to ind (min cbeg end))))
23039 (when (< (point) end)
23040 (cl-case type
23041 ((example-block export-block verse-block))
23042 (src-block
23043 ;; In a source block, indent source code
23044 ;; according to language major mode, but only if
23045 ;; `org-src-tab-acts-natively' is non-nil.
23046 (when (and (< (point) end) org-src-tab-acts-natively)
23047 (ignore-errors
23048 (org-babel-do-in-edit-buffer
23049 (indent-region (point-min) (point-max))))))
23050 (t (org-indent-region (point) (min cend end))))
23051 (goto-char (min cend end))
23052 (when (< (point) end)
23053 (funcall indent-to ind (min element-end end))))
23054 (set-marker post nil)
23055 (set-marker cbeg nil)
23056 (set-marker cend nil))))
23057 (set-marker element-end nil))))
23058 (set-marker end nil))))
23060 (defun org-indent-drawer ()
23061 "Indent the drawer at point."
23062 (interactive)
23063 (unless (save-excursion
23064 (beginning-of-line)
23065 (looking-at-p org-drawer-regexp))
23066 (user-error "Not at a drawer"))
23067 (let ((element (org-element-at-point)))
23068 (unless (memq (org-element-type element) '(drawer property-drawer))
23069 (user-error "Not at a drawer"))
23070 (org-with-wide-buffer
23071 (org-indent-region (org-element-property :begin element)
23072 (org-element-property :end element))))
23073 (message "Drawer at point indented"))
23075 (defun org-indent-block ()
23076 "Indent the block at point."
23077 (interactive)
23078 (unless (save-excursion
23079 (beginning-of-line)
23080 (let ((case-fold-search t))
23081 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23082 (user-error "Not at a block"))
23083 (let ((element (org-element-at-point)))
23084 (unless (memq (org-element-type element)
23085 '(comment-block center-block dynamic-block example-block
23086 export-block quote-block special-block
23087 src-block verse-block))
23088 (user-error "Not at a block"))
23089 (org-with-wide-buffer
23090 (org-indent-region (org-element-property :begin element)
23091 (org-element-property :end element))))
23092 (message "Block at point indented"))
23095 ;;; Filling
23097 ;; We use our own fill-paragraph and auto-fill functions.
23099 ;; `org-fill-paragraph' relies on adaptive filling and context
23100 ;; checking. Appropriate `fill-prefix' is computed with
23101 ;; `org-adaptive-fill-function'.
23103 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23104 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23105 ;; `org-adaptive-fill-function' value. Internally,
23106 ;; `org-comment-line-break-function' breaks the line.
23108 ;; `org-setup-filling' installs filling and auto-filling related
23109 ;; variables during `org-mode' initialization.
23111 (defvar org-element-paragraph-separate) ; org-element.el
23112 (defun org-setup-filling ()
23113 (require 'org-element)
23114 ;; Prevent auto-fill from inserting unwanted new items.
23115 (when (boundp 'fill-nobreak-predicate)
23116 (setq-local
23117 fill-nobreak-predicate
23118 (org-uniquify
23119 (append fill-nobreak-predicate
23120 '(org-fill-line-break-nobreak-p
23121 org-fill-paragraph-with-timestamp-nobreak-p)))))
23122 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23123 (setq-local paragraph-start paragraph-ending)
23124 (setq-local paragraph-separate paragraph-ending))
23125 (setq-local fill-paragraph-function 'org-fill-paragraph)
23126 (setq-local auto-fill-inhibit-regexp nil)
23127 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23128 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23129 (setq-local comment-line-break-function 'org-comment-line-break-function))
23131 (defun org-fill-line-break-nobreak-p ()
23132 "Non-nil when a new line at point would create an Org line break."
23133 (save-excursion
23134 (skip-chars-backward "[ \t]")
23135 (skip-chars-backward "\\\\")
23136 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23138 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23139 "Non-nil when a new line at point would split a timestamp."
23140 (and (org-at-timestamp-p t)
23141 (not (looking-at org-ts-regexp-both))))
23143 (declare-function message-in-body-p "message" ())
23144 (defvar orgtbl-line-start-regexp) ; From org-table.el
23145 (defun org-adaptive-fill-function ()
23146 "Compute a fill prefix for the current line.
23147 Return fill prefix, as a string, or nil if current line isn't
23148 meant to be filled. For convenience, if `adaptive-fill-regexp'
23149 matches in paragraphs or comments, use it."
23150 (catch 'exit
23151 (when (derived-mode-p 'message-mode)
23152 (save-excursion
23153 (beginning-of-line)
23154 (cond ((not (message-in-body-p)) (throw 'exit nil))
23155 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23156 ((looking-at message-cite-prefix-regexp)
23157 (throw 'exit (match-string-no-properties 0)))
23158 ((looking-at org-outline-regexp)
23159 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23160 (org-with-wide-buffer
23161 (unless (org-at-heading-p)
23162 (let* ((p (line-beginning-position))
23163 (element (save-excursion
23164 (beginning-of-line)
23165 (org-element-at-point)))
23166 (type (org-element-type element))
23167 (post-affiliated (org-element-property :post-affiliated element)))
23168 (unless (< p post-affiliated)
23169 (cl-case type
23170 (comment
23171 (save-excursion
23172 (beginning-of-line)
23173 (looking-at "[ \t]*")
23174 (concat (match-string 0) "# ")))
23175 (footnote-definition "")
23176 ((item plain-list)
23177 (make-string (org-list-item-body-column post-affiliated) ?\s))
23178 (paragraph
23179 ;; Fill prefix is usually the same as the current line,
23180 ;; unless the paragraph is at the beginning of an item.
23181 (let ((parent (org-element-property :parent element)))
23182 (save-excursion
23183 (beginning-of-line)
23184 (cond ((eq (org-element-type parent) 'item)
23185 (make-string (org-list-item-body-column
23186 (org-element-property :begin parent))
23187 ?\s))
23188 ((and adaptive-fill-regexp
23189 ;; Locally disable
23190 ;; `adaptive-fill-function' to let
23191 ;; `fill-context-prefix' handle
23192 ;; `adaptive-fill-regexp' variable.
23193 (let (adaptive-fill-function)
23194 (fill-context-prefix
23195 post-affiliated
23196 (org-element-property :end element)))))
23197 ((looking-at "[ \t]+") (match-string 0))
23198 (t "")))))
23199 (comment-block
23200 ;; Only fill contents if P is within block boundaries.
23201 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23202 (forward-line)
23203 (point)))
23204 (cend (save-excursion
23205 (goto-char (org-element-property :end element))
23206 (skip-chars-backward " \r\t\n")
23207 (line-beginning-position))))
23208 (when (and (>= p cbeg) (< p cend))
23209 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23210 (match-string 0)
23211 "")))))))))))
23213 (declare-function message-goto-body "message" ())
23214 (defvar message-cite-prefix-regexp) ; From message.el
23215 (defun org-fill-paragraph (&optional justify)
23216 "Fill element at point, when applicable.
23218 This function only applies to comment blocks, comments, example
23219 blocks and paragraphs. Also, as a special case, re-align table
23220 when point is at one.
23222 If JUSTIFY is non-nil (interactively, with prefix argument),
23223 justify as well. If `sentence-end-double-space' is non-nil, then
23224 period followed by one space does not end a sentence, so don't
23225 break a line there. The variable `fill-column' controls the
23226 width for filling.
23228 For convenience, when point is at a plain list, an item or
23229 a footnote definition, try to fill the first paragraph within."
23230 (interactive)
23231 (if (and (derived-mode-p 'message-mode)
23232 (or (not (message-in-body-p))
23233 (save-excursion (move-beginning-of-line 1)
23234 (looking-at message-cite-prefix-regexp))))
23235 ;; First ensure filling is correct in message-mode.
23236 (let ((fill-paragraph-function
23237 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23238 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23239 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23240 (paragraph-separate
23241 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23242 (fill-paragraph nil))
23243 (with-syntax-table org-mode-transpose-word-syntax-table
23244 ;; Move to end of line in order to get the first paragraph
23245 ;; within a plain list or a footnote definition.
23246 (let ((element (save-excursion
23247 (end-of-line)
23248 (or (ignore-errors (org-element-at-point))
23249 (user-error "An element cannot be parsed line %d"
23250 (line-number-at-pos (point)))))))
23251 ;; First check if point is in a blank line at the beginning of
23252 ;; the buffer. In that case, ignore filling.
23253 (cl-case (org-element-type element)
23254 ;; Use major mode filling function is src blocks.
23255 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23256 ;; Align Org tables, leave table.el tables as-is.
23257 (table-row (org-table-align) t)
23258 (table
23259 (when (eq (org-element-property :type element) 'org)
23260 (save-excursion
23261 (goto-char (org-element-property :post-affiliated element))
23262 (org-table-align)))
23264 (paragraph
23265 ;; Paragraphs may contain `line-break' type objects.
23266 (let ((beg (max (point-min)
23267 (org-element-property :contents-begin element)))
23268 (end (min (point-max)
23269 (org-element-property :contents-end element))))
23270 ;; Do nothing if point is at an affiliated keyword.
23271 (if (< (line-end-position) beg) t
23272 (when (derived-mode-p 'message-mode)
23273 ;; In `message-mode', do not fill following citation
23274 ;; in current paragraph nor text before message body.
23275 (let ((body-start (save-excursion (message-goto-body))))
23276 (when body-start (setq beg (max body-start beg))))
23277 (when (save-excursion
23278 (re-search-forward
23279 (concat "^" message-cite-prefix-regexp) end t))
23280 (setq end (match-beginning 0))))
23281 ;; Fill paragraph, taking line breaks into account.
23282 (save-excursion
23283 (goto-char beg)
23284 (let ((cuts (list beg)))
23285 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23286 (when (eq 'line-break
23287 (org-element-type
23288 (save-excursion (backward-char)
23289 (org-element-context))))
23290 (push (point) cuts)))
23291 (dolist (c (delq end cuts))
23292 (fill-region-as-paragraph c end justify)
23293 (setq end c))))
23294 t)))
23295 ;; Contents of `comment-block' type elements should be
23296 ;; filled as plain text, but only if point is within block
23297 ;; markers.
23298 (comment-block
23299 (let* ((case-fold-search t)
23300 (beg (save-excursion
23301 (goto-char (org-element-property :begin element))
23302 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23303 (forward-line)
23304 (point)))
23305 (end (save-excursion
23306 (goto-char (org-element-property :end element))
23307 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23308 (line-beginning-position))))
23309 (if (or (< (point) beg) (> (point) end)) t
23310 (fill-region-as-paragraph
23311 (save-excursion (end-of-line)
23312 (re-search-backward "^[ \t]*$" beg 'move)
23313 (line-beginning-position))
23314 (save-excursion (beginning-of-line)
23315 (re-search-forward "^[ \t]*$" end 'move)
23316 (line-beginning-position))
23317 justify))))
23318 ;; Fill comments.
23319 (comment
23320 (let ((begin (org-element-property :post-affiliated element))
23321 (end (org-element-property :end element)))
23322 (when (and (>= (point) begin) (<= (point) end))
23323 (let ((begin (save-excursion
23324 (end-of-line)
23325 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23326 (progn (forward-line) (point))
23327 begin)))
23328 (end (save-excursion
23329 (end-of-line)
23330 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23331 (1- (line-beginning-position))
23332 (skip-chars-backward " \r\t\n")
23333 (line-end-position)))))
23334 ;; Do not fill comments when at a blank line.
23335 (when (> end begin)
23336 (let ((fill-prefix
23337 (save-excursion
23338 (beginning-of-line)
23339 (looking-at "[ \t]*#")
23340 (let ((comment-prefix (match-string 0)))
23341 (goto-char (match-end 0))
23342 (if (looking-at adaptive-fill-regexp)
23343 (concat comment-prefix (match-string 0))
23344 (concat comment-prefix " "))))))
23345 (save-excursion
23346 (fill-region-as-paragraph begin end justify))))))
23348 ;; Ignore every other element.
23349 (otherwise t))))))
23351 (defun org-auto-fill-function ()
23352 "Auto-fill function."
23353 ;; Check if auto-filling is meaningful.
23354 (let ((fc (current-fill-column)))
23355 (when (and fc (> (current-column) fc))
23356 (let* ((fill-prefix (org-adaptive-fill-function))
23357 ;; Enforce empty fill prefix, if required. Otherwise, it
23358 ;; will be computed again.
23359 (adaptive-fill-mode (not (equal fill-prefix ""))))
23360 (when fill-prefix (do-auto-fill))))))
23362 (defun org-comment-line-break-function (&optional soft)
23363 "Break line at point and indent, continuing comment if within one.
23364 The inserted newline is marked hard if variable
23365 `use-hard-newlines' is true, unless optional argument SOFT is
23366 non-nil."
23367 (if soft (insert-and-inherit ?\n) (newline 1))
23368 (save-excursion (forward-char -1) (delete-horizontal-space))
23369 (delete-horizontal-space)
23370 (indent-to-left-margin)
23371 (insert-before-markers-and-inherit fill-prefix))
23374 ;;; Fixed Width Areas
23376 (defun org-toggle-fixed-width ()
23377 "Toggle fixed-width markup.
23379 Add or remove fixed-width markup on current line, whenever it
23380 makes sense. Return an error otherwise.
23382 If a region is active and if it contains only fixed-width areas
23383 or blank lines, remove all fixed-width markup in it. If the
23384 region contains anything else, convert all non-fixed-width lines
23385 to fixed-width ones.
23387 Blank lines at the end of the region are ignored unless the
23388 region only contains such lines."
23389 (interactive)
23390 (if (not (org-region-active-p))
23391 ;; No region:
23393 ;; Remove fixed width marker only in a fixed-with element.
23395 ;; Add fixed width maker in paragraphs, in blank lines after
23396 ;; elements or at the beginning of a headline or an inlinetask,
23397 ;; and before any one-line elements (e.g., a clock).
23398 (progn
23399 (beginning-of-line)
23400 (let* ((element (org-element-at-point))
23401 (type (org-element-type element)))
23402 (cond
23403 ((and (eq type 'fixed-width)
23404 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23405 (replace-match
23406 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23407 ((and (memq type '(babel-call clock comment diary-sexp headline
23408 horizontal-rule keyword paragraph
23409 planning))
23410 (<= (org-element-property :post-affiliated element) (point)))
23411 (skip-chars-forward " \t")
23412 (insert ": "))
23413 ((and (looking-at-p "[ \t]*$")
23414 (or (eq type 'inlinetask)
23415 (save-excursion
23416 (skip-chars-forward " \r\t\n")
23417 (<= (org-element-property :end element) (point)))))
23418 (delete-region (point) (line-end-position))
23419 (org-indent-line)
23420 (insert ": "))
23421 (t (user-error "Cannot insert a fixed-width line here")))))
23422 ;; Region active.
23423 (let* ((begin (save-excursion
23424 (goto-char (region-beginning))
23425 (line-beginning-position)))
23426 (end (copy-marker
23427 (save-excursion
23428 (goto-char (region-end))
23429 (unless (eolp) (beginning-of-line))
23430 (if (save-excursion (re-search-backward "\\S-" begin t))
23431 (progn (skip-chars-backward " \r\t\n") (point))
23432 (point)))))
23433 (all-fixed-width-p
23434 (catch 'not-all-p
23435 (save-excursion
23436 (goto-char begin)
23437 (skip-chars-forward " \r\t\n")
23438 (when (eobp) (throw 'not-all-p nil))
23439 (while (< (point) end)
23440 (let ((element (org-element-at-point)))
23441 (if (eq (org-element-type element) 'fixed-width)
23442 (goto-char (org-element-property :end element))
23443 (throw 'not-all-p nil))))
23444 t))))
23445 (if all-fixed-width-p
23446 (save-excursion
23447 (goto-char begin)
23448 (while (< (point) end)
23449 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23450 (replace-match
23451 "" nil nil nil
23452 (if (= (line-end-position) (match-end 0)) 0 1)))
23453 (forward-line)))
23454 (let ((min-ind (point-max)))
23455 ;; Find minimum indentation across all lines.
23456 (save-excursion
23457 (goto-char begin)
23458 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23459 (setq min-ind 0)
23460 (catch 'zerop
23461 (while (< (point) end)
23462 (unless (looking-at-p "[ \t]*$")
23463 (let ((ind (org-get-indentation)))
23464 (setq min-ind (min min-ind ind))
23465 (when (zerop ind) (throw 'zerop t))))
23466 (forward-line)))))
23467 ;; Loop over all lines and add fixed-width markup everywhere
23468 ;; but in fixed-width lines.
23469 (save-excursion
23470 (goto-char begin)
23471 (while (< (point) end)
23472 (cond
23473 ((org-at-heading-p)
23474 (insert ": ")
23475 (forward-line)
23476 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23477 (insert ":")
23478 (forward-line)))
23479 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23480 (let* ((element (org-element-at-point))
23481 (element-end (org-element-property :end element)))
23482 (if (eq (org-element-type element) 'fixed-width)
23483 (progn (goto-char element-end)
23484 (skip-chars-backward " \r\t\n")
23485 (forward-line))
23486 (let ((limit (min end element-end)))
23487 (while (< (point) limit)
23488 (org-move-to-column min-ind t)
23489 (insert ": ")
23490 (forward-line))))))
23492 (org-move-to-column min-ind t)
23493 (insert ": ")
23494 (forward-line)))))))
23495 (set-marker end nil))))
23498 ;;; Comments
23500 ;; Org comments syntax is quite complex. It requires the entire line
23501 ;; to be just a comment. Also, even with the right syntax at the
23502 ;; beginning of line, some some elements (i.e. verse-block or
23503 ;; example-block) don't accept comments. Usual Emacs comment commands
23504 ;; cannot cope with those requirements. Therefore, Org replaces them.
23506 ;; Org still relies on `comment-dwim', but cannot trust
23507 ;; `comment-only-p'. So, `comment-region-function' and
23508 ;; `uncomment-region-function' both point
23509 ;; to`org-comment-or-uncomment-region'. Eventually,
23510 ;; `org-insert-comment' takes care of insertion of comments at the
23511 ;; beginning of line.
23513 ;; `org-setup-comments-handling' install comments related variables
23514 ;; during `org-mode' initialization.
23516 (defun org-setup-comments-handling ()
23517 (interactive)
23518 (setq-local comment-use-syntax nil)
23519 (setq-local comment-start "# ")
23520 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23521 (setq-local comment-insert-comment-function 'org-insert-comment)
23522 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23523 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23525 (defun org-insert-comment ()
23526 "Insert an empty comment above current line.
23527 If the line is empty, insert comment at its beginning. When
23528 point is within a source block, comment according to the related
23529 major mode."
23530 (if (let ((element (org-element-at-point)))
23531 (and (eq (org-element-type element) 'src-block)
23532 (< (save-excursion
23533 (goto-char (org-element-property :post-affiliated element))
23534 (line-end-position))
23535 (point))
23536 (> (save-excursion
23537 (goto-char (org-element-property :end element))
23538 (skip-chars-backward " \r\t\n")
23539 (line-beginning-position))
23540 (point))))
23541 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23542 (beginning-of-line)
23543 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23544 (open-line 1))
23545 (org-indent-line)
23546 (insert "# ")))
23548 (defvar comment-empty-lines) ; From newcomment.el.
23549 (defun org-comment-or-uncomment-region (beg end &rest _)
23550 "Comment or uncomment each non-blank line in the region.
23551 Uncomment each non-blank line between BEG and END if it only
23552 contains commented lines. Otherwise, comment them. If region is
23553 strictly within a source block, use appropriate comment syntax."
23554 (if (let ((element (org-element-at-point)))
23555 (and (eq (org-element-type element) 'src-block)
23556 (< (save-excursion
23557 (goto-char (org-element-property :post-affiliated element))
23558 (line-end-position))
23559 beg)
23560 (>= (save-excursion
23561 (goto-char (org-element-property :end element))
23562 (skip-chars-backward " \r\t\n")
23563 (line-beginning-position))
23564 end)))
23565 ;; Translate region boundaries for the Org buffer to the source
23566 ;; buffer.
23567 (let ((offset (- end beg)))
23568 (save-excursion
23569 (goto-char beg)
23570 (org-babel-do-in-edit-buffer
23571 (comment-or-uncomment-region (point) (+ offset (point))))))
23572 (save-restriction
23573 ;; Restrict region
23574 (narrow-to-region (save-excursion (goto-char beg)
23575 (skip-chars-forward " \r\t\n" end)
23576 (line-beginning-position))
23577 (save-excursion (goto-char end)
23578 (skip-chars-backward " \r\t\n" beg)
23579 (line-end-position)))
23580 (let ((uncommentp
23581 ;; UNCOMMENTP is non-nil when every non blank line between
23582 ;; BEG and END is a comment.
23583 (save-excursion
23584 (goto-char (point-min))
23585 (while (and (not (eobp))
23586 (let ((element (org-element-at-point)))
23587 (and (eq (org-element-type element) 'comment)
23588 (goto-char (min (point-max)
23589 (org-element-property
23590 :end element)))))))
23591 (eobp))))
23592 (if uncommentp
23593 ;; Only blank lines and comments in region: uncomment it.
23594 (save-excursion
23595 (goto-char (point-min))
23596 (while (not (eobp))
23597 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23598 (replace-match "" nil nil nil 1))
23599 (forward-line)))
23600 ;; Comment each line in region.
23601 (let ((min-indent (point-max)))
23602 ;; First find the minimum indentation across all lines.
23603 (save-excursion
23604 (goto-char (point-min))
23605 (while (and (not (eobp)) (not (zerop min-indent)))
23606 (unless (looking-at "[ \t]*$")
23607 (setq min-indent (min min-indent (current-indentation))))
23608 (forward-line)))
23609 ;; Then loop over all lines.
23610 (save-excursion
23611 (goto-char (point-min))
23612 (while (not (eobp))
23613 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23614 ;; Don't get fooled by invisible text (e.g. link path)
23615 ;; when moving to column MIN-INDENT.
23616 (let ((buffer-invisibility-spec nil))
23617 (org-move-to-column min-indent t))
23618 (insert comment-start))
23619 (forward-line)))))))))
23621 (defun org-comment-dwim (_arg)
23622 "Call `comment-dwim' within a source edit buffer if needed."
23623 (interactive "*P")
23624 (if (org-in-src-block-p)
23625 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23626 (call-interactively 'comment-dwim)))
23629 ;;; Timestamps API
23631 ;; This section contains tools to operate on timestamp objects, as
23632 ;; returned by, e.g. `org-element-context'.
23634 (defun org-timestamp--to-internal-time (timestamp &optional end)
23635 "Encode TIMESTAMP object into Emacs internal time.
23636 Use end of date range or time range when END is non-nil."
23637 (apply #'encode-time
23638 (cons 0
23639 (mapcar
23640 (lambda (prop) (or (org-element-property prop timestamp) 0))
23641 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23642 '(:minute-start :hour-start :day-start :month-start
23643 :year-start))))))
23645 (defun org-timestamp-has-time-p (timestamp)
23646 "Non-nil when TIMESTAMP has a time specified."
23647 (org-element-property :hour-start timestamp))
23649 (defun org-timestamp-format (timestamp format &optional end utc)
23650 "Format a TIMESTAMP object into a string.
23652 FORMAT is a format specifier to be passed to
23653 `format-time-string'.
23655 When optional argument END is non-nil, use end of date-range or
23656 time-range, if possible.
23658 When optional argument UTC is non-nil, time will be expressed as
23659 Universal Time."
23660 (format-time-string
23661 format (org-timestamp--to-internal-time timestamp end)
23662 (and utc t)))
23664 (defun org-timestamp-split-range (timestamp &optional end)
23665 "Extract a TIMESTAMP object from a date or time range.
23667 END, when non-nil, means extract the end of the range.
23668 Otherwise, extract its start.
23670 Return a new timestamp object."
23671 (let ((type (org-element-property :type timestamp)))
23672 (if (memq type '(active inactive diary)) timestamp
23673 (let ((split-ts (org-element-copy timestamp)))
23674 ;; Set new type.
23675 (org-element-put-property
23676 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23677 ;; Copy start properties over end properties if END is
23678 ;; non-nil. Otherwise, copy end properties over `start' ones.
23679 (let ((p-alist '((:minute-start . :minute-end)
23680 (:hour-start . :hour-end)
23681 (:day-start . :day-end)
23682 (:month-start . :month-end)
23683 (:year-start . :year-end))))
23684 (dolist (p-cell p-alist)
23685 (org-element-put-property
23686 split-ts
23687 (funcall (if end #'car #'cdr) p-cell)
23688 (org-element-property
23689 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23690 ;; Eventually refresh `:raw-value'.
23691 (org-element-put-property split-ts :raw-value nil)
23692 (org-element-put-property
23693 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23695 (defun org-timestamp-translate (timestamp &optional boundary)
23696 "Translate TIMESTAMP object to custom format.
23698 Format string is defined in `org-time-stamp-custom-formats',
23699 which see.
23701 When optional argument BOUNDARY is non-nil, it is either the
23702 symbol `start' or `end'. In this case, only translate the
23703 starting or ending part of TIMESTAMP if it is a date or time
23704 range. Otherwise, translate both parts.
23706 Return timestamp as-is if `org-display-custom-times' is nil or if
23707 it has a `diary' type."
23708 (let ((type (org-element-property :type timestamp)))
23709 (if (or (not org-display-custom-times) (eq type 'diary))
23710 (org-element-interpret-data timestamp)
23711 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23712 org-time-stamp-custom-formats)))
23713 (if (and (not boundary) (memq type '(active-range inactive-range)))
23714 (concat (org-timestamp-format timestamp fmt)
23715 "--"
23716 (org-timestamp-format timestamp fmt t))
23717 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23721 ;;; Other stuff.
23723 (defvar reftex-docstruct-symbol)
23724 (defvar org--rds)
23726 (defun org-reftex-citation ()
23727 "Use reftex-citation to insert a citation into the buffer.
23728 This looks for a line like
23730 #+BIBLIOGRAPHY: foo plain option:-d
23732 and derives from it that foo.bib is the bibliography file relevant
23733 for this document. It then installs the necessary environment for RefTeX
23734 to work in this buffer and calls `reftex-citation' to insert a citation
23735 into the buffer.
23737 Export of such citations to both LaTeX and HTML is handled by the contributed
23738 package ox-bibtex by Taru Karttunen."
23739 (interactive)
23740 (let ((reftex-docstruct-symbol 'org--rds)
23741 org--rds bib)
23742 (org-with-wide-buffer
23743 (let ((case-fold-search t)
23744 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23745 (if (not (save-excursion
23746 (or (re-search-forward re nil t)
23747 (re-search-backward re nil t))))
23748 (user-error "No bibliography defined in file")
23749 (setq bib (concat (match-string 1) ".bib")
23750 org--rds (list (list 'bib bib))))))
23751 (call-interactively 'reftex-citation)))
23753 ;;;; Functions extending outline functionality
23755 (defun org-beginning-of-line (&optional n)
23756 "Go to the beginning of the current visible line.
23758 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23759 tags on the first attempt, and only move to after the tags when
23760 the cursor is already beyond the end of the headline.
23762 With argument N not nil or 1, move forward N - 1 lines first."
23763 (interactive "^p")
23764 (let ((origin (point))
23765 (special (pcase org-special-ctrl-a/e
23766 (`(,C-a . _) C-a) (_ org-special-ctrl-a/e)))
23767 deactivate-mark)
23768 ;; First move to a visible line.
23769 (if (bound-and-true-p visual-line-mode)
23770 (beginning-of-visual-line n)
23771 (move-beginning-of-line n)
23772 ;; `move-beginning-of-line' may leave point after invisible
23773 ;; characters if line starts with such of these (e.g., with
23774 ;; a link at column 0). Really move to the beginning of the
23775 ;; current visible line.
23776 (beginning-of-line))
23777 (cond
23778 ;; No special behavior. Point is already at the beginning of
23779 ;; a line, logical or visual.
23780 ((not special))
23781 ;; `beginning-of-visual-line' left point before logical beginning
23782 ;; of line: point is at the beginning of a visual line. Bail
23783 ;; out.
23784 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23785 ((looking-at org-complex-heading-regexp)
23786 ;; At a headline, special position is before the title, but
23787 ;; after any TODO keyword or priority cookie.
23788 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23789 (line-end-position)))
23790 (bol (point)))
23791 (if (eq special 'reversed)
23792 (when (and (= origin bol) (eq last-command this-command))
23793 (goto-char refpos))
23794 (when (or (> origin refpos) (= origin bol))
23795 (goto-char refpos)))))
23796 ((and (looking-at org-list-full-item-re)
23797 (memq (org-element-type (save-match-data (org-element-at-point)))
23798 '(item plain-list)))
23799 ;; Set special position at first white space character after
23800 ;; bullet, and check-box, if any.
23801 (let ((after-bullet
23802 (let ((box (match-end 3)))
23803 (cond ((not box) (match-end 1))
23804 ((eq (char-after box) ?\s) (1+ box))
23805 (t box)))))
23806 (if (eq special 'reversed)
23807 (when (and (= (point) origin) (eq last-command this-command))
23808 (goto-char after-bullet))
23809 (when (or (> origin after-bullet) (= (point) origin))
23810 (goto-char after-bullet)))))
23811 ;; No special context. Point is already at beginning of line.
23812 (t nil))))
23814 (defun org-end-of-line (&optional n)
23815 "Go to the end of the line, but before ellipsis, if any.
23817 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23818 tags on the first attempt, and only move to after the tags when
23819 the cursor is already beyond the end of the headline.
23821 With argument N not nil or 1, move forward N - 1 lines first."
23822 (interactive "^p")
23823 (let ((origin (point))
23824 (special (pcase org-special-ctrl-a/e
23825 (`(_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23826 deactivate-mark)
23827 ;; First move to a visible line.
23828 (if (bound-and-true-p visual-line-mode)
23829 (beginning-of-visual-line n)
23830 (move-beginning-of-line n))
23831 (cond
23832 ;; At a headline, with tags.
23833 ((and special
23834 (save-excursion
23835 (beginning-of-line)
23836 (looking-at org-complex-heading-regexp))
23837 (match-end 5))
23838 (let ((tags (save-excursion
23839 (goto-char (match-beginning 5))
23840 (skip-chars-backward " \t")
23841 (point)))
23842 (visual-end (and (bound-and-true-p visual-line-mode)
23843 (save-excursion
23844 (end-of-visual-line)
23845 (point)))))
23846 ;; If `end-of-visual-line' brings us before end of line or
23847 ;; even tags, i.e., the headline spans over multiple visual
23848 ;; lines, move there.
23849 (cond ((and visual-end
23850 (< visual-end tags)
23851 (<= origin visual-end))
23852 (goto-char visual-end))
23853 ((eq special 'reversed)
23854 (if (and (= origin (line-end-position))
23855 (eq this-command last-command))
23856 (goto-char tags)
23857 (end-of-line)))
23859 (if (or (< origin tags) (= origin (line-end-position)))
23860 (goto-char tags)
23861 (end-of-line))))))
23862 ((bound-and-true-p visual-line-mode)
23863 (let ((bol (line-beginning-position)))
23864 (end-of-visual-line)
23865 ;; If `end-of-visual-line' gets us past the ellipsis at the
23866 ;; end of a line, backtrack and use `end-of-line' instead.
23867 (when (/= bol (line-beginning-position))
23868 (goto-char bol)
23869 (end-of-line))))
23870 (t (end-of-line)))))
23872 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23873 (define-key org-mode-map "\C-e" 'org-end-of-line)
23875 (defun org-backward-sentence (&optional _arg)
23876 "Go to beginning of sentence, or beginning of table field.
23877 This will call `backward-sentence' or `org-table-beginning-of-field',
23878 depending on context."
23879 (interactive)
23880 (let* ((element (org-element-at-point))
23881 (contents-begin (org-element-property :contents-begin element))
23882 (table (org-element-lineage element '(table) t)))
23883 (if (and table
23884 (> (point) contents-begin)
23885 (<= (point) (org-element-property :contents-end table)))
23886 (call-interactively #'org-table-beginning-of-field)
23887 (save-restriction
23888 (when (and contents-begin
23889 (< (point-min) contents-begin)
23890 (> (point) contents-begin))
23891 (narrow-to-region contents-begin
23892 (org-element-property :contents-end element)))
23893 (call-interactively #'backward-sentence)))))
23895 (defun org-forward-sentence (&optional _arg)
23896 "Go to end of sentence, or end of table field.
23897 This will call `forward-sentence' or `org-table-end-of-field',
23898 depending on context."
23899 (interactive)
23900 (let* ((element (org-element-at-point))
23901 (contents-end (org-element-property :contents-end element))
23902 (table (org-element-lineage element '(table) t)))
23903 (if (and table
23904 (>= (point) (org-element-property :contents-begin table))
23905 (< (point) contents-end))
23906 (call-interactively #'org-table-end-of-field)
23907 (save-restriction
23908 (when (and contents-end
23909 (> (point-max) contents-end)
23910 ;; Skip blank lines between elements.
23911 (< (org-element-property :end element)
23912 (save-excursion (goto-char contents-end)
23913 (skip-chars-forward " \r\t\n"))))
23914 (narrow-to-region (org-element-property :contents-begin element)
23915 contents-end))
23916 (call-interactively #'forward-sentence)))))
23918 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23919 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23921 (defun org-kill-line (&optional _arg)
23922 "Kill line, to tags or end of line."
23923 (interactive)
23924 (cond
23925 ((or (not org-special-ctrl-k)
23926 (bolp)
23927 (not (org-at-heading-p)))
23928 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23929 org-ctrl-k-protect-subtree
23930 (or (eq org-ctrl-k-protect-subtree 'error)
23931 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23932 (user-error "C-k aborted as it would kill a hidden subtree"))
23933 (call-interactively
23934 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23935 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23936 (kill-region (point) (match-beginning 1))
23937 (org-set-tags nil t))
23938 (t (kill-region (point) (point-at-eol)))))
23940 (define-key org-mode-map "\C-k" 'org-kill-line)
23942 (defun org-yank (&optional arg)
23943 "Yank. If the kill is a subtree, treat it specially.
23944 This command will look at the current kill and check if is a single
23945 subtree, or a series of subtrees[1]. If it passes the test, and if the
23946 cursor is at the beginning of a line or after the stars of a currently
23947 empty headline, then the yank is handled specially. How exactly depends
23948 on the value of the following variables.
23950 `org-yank-folded-subtrees'
23951 By default, this variable is non-nil, which results in
23952 subtree(s) being folded after insertion, except if doing so
23953 would swallow text after the yanked text.
23955 `org-yank-adjusted-subtrees'
23956 When non-nil (the default value is nil), the subtree will be
23957 promoted or demoted in order to fit into the local outline tree
23958 structure, which means that the level will be adjusted so that it
23959 becomes the smaller one of the two *visible* surrounding headings.
23961 Any prefix to this command will cause `yank' to be called directly with
23962 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23963 will just
23964 plainly yank the text as it is.
23966 \[1] The test checks if the first non-white line is a heading
23967 and if there are no other headings with fewer stars."
23968 (interactive "P")
23969 (org-yank-generic 'yank arg))
23971 (defun org-yank-generic (command arg)
23972 "Perform some yank-like command.
23974 This function implements the behavior described in the `org-yank'
23975 documentation. However, it has been generalized to work for any
23976 interactive command with similar behavior."
23978 ;; pretend to be command COMMAND
23979 (setq this-command command)
23981 (if arg
23982 (call-interactively command)
23984 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23985 (and (org-kill-is-subtree-p)
23986 (or (bolp)
23987 (and (looking-at "[ \t]*$")
23988 (string-match
23989 "\\`\\*+\\'"
23990 (buffer-substring (point-at-bol) (point)))))))
23991 swallowp)
23992 (cond
23993 ((and subtreep org-yank-folded-subtrees)
23994 (let ((beg (point))
23995 end)
23996 (if (and subtreep org-yank-adjusted-subtrees)
23997 (org-paste-subtree nil nil 'for-yank)
23998 (call-interactively command))
24000 (setq end (point))
24001 (goto-char beg)
24002 (when (and (bolp) subtreep
24003 (not (setq swallowp
24004 (org-yank-folding-would-swallow-text beg end))))
24005 (org-with-limited-levels
24006 (or (looking-at org-outline-regexp)
24007 (re-search-forward org-outline-regexp-bol end t))
24008 (while (and (< (point) end) (looking-at org-outline-regexp))
24009 (outline-hide-subtree)
24010 (org-cycle-show-empty-lines 'folded)
24011 (condition-case nil
24012 (outline-forward-same-level 1)
24013 (error (goto-char end))))))
24014 (when swallowp
24015 (message
24016 "Inserted text not folded because that would swallow text"))
24018 (goto-char end)
24019 (skip-chars-forward " \t\n\r")
24020 (beginning-of-line 1)
24021 (push-mark beg 'nomsg)))
24022 ((and subtreep org-yank-adjusted-subtrees)
24023 (let ((beg (point-at-bol)))
24024 (org-paste-subtree nil nil 'for-yank)
24025 (push-mark beg 'nomsg)))
24027 (call-interactively command))))))
24029 (defun org-yank-folding-would-swallow-text (beg end)
24030 "Would hide-subtree at BEG swallow any text after END?"
24031 (let (level)
24032 (org-with-limited-levels
24033 (save-excursion
24034 (goto-char beg)
24035 (when (or (looking-at org-outline-regexp)
24036 (re-search-forward org-outline-regexp-bol end t))
24037 (setq level (org-outline-level)))
24038 (goto-char end)
24039 (skip-chars-forward " \t\r\n\v\f")
24040 (not (or (eobp)
24041 (and (bolp) (looking-at-p org-outline-regexp)
24042 (<= (org-outline-level) level))))))))
24044 (define-key org-mode-map "\C-y" 'org-yank)
24046 (defun org-truely-invisible-p ()
24047 "Check if point is at a character currently not visible.
24048 This version does not only check the character property, but also
24049 `visible-mode'."
24050 ;; Early versions of noutline don't have `outline-invisible-p'.
24051 (unless (bound-and-true-p visible-mode)
24052 (outline-invisible-p)))
24054 (defun org-invisible-p2 ()
24055 "Check if point is at a character currently not visible."
24056 (save-excursion
24057 (when (and (eolp) (not (bobp))) (backward-char 1))
24058 ;; Early versions of noutline don't have `outline-invisible-p'.
24059 (outline-invisible-p)))
24061 (defun org-back-to-heading (&optional invisible-ok)
24062 "Call `outline-back-to-heading', but provide a better error message."
24063 (condition-case nil
24064 (outline-back-to-heading invisible-ok)
24065 (error (error "Before first headline at position %d in buffer %s"
24066 (point) (current-buffer)))))
24068 (defun org-before-first-heading-p ()
24069 "Before first heading?"
24070 (save-excursion
24071 (end-of-line)
24072 (null (re-search-backward org-outline-regexp-bol nil t))))
24074 (defun org-at-heading-p (&optional ignored)
24075 (outline-on-heading-p t))
24077 (defun org-in-commented-heading-p (&optional no-inheritance)
24078 "Non-nil if point is under a commented heading.
24079 This function also checks ancestors of the current headline,
24080 unless optional argument NO-INHERITANCE is non-nil."
24081 (cond
24082 ((org-before-first-heading-p) nil)
24083 ((let ((headline (nth 4 (org-heading-components))))
24084 (and headline
24085 (let ((case-fold-search nil))
24086 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24087 headline)))))
24088 (no-inheritance nil)
24090 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24092 (defun org-at-comment-p nil
24093 "Is cursor in a commented line?"
24094 (save-excursion
24095 (save-match-data
24096 (beginning-of-line)
24097 (looking-at "^[ \t]*# "))))
24099 (defun org-at-drawer-p nil
24100 "Is cursor at a drawer keyword?"
24101 (save-excursion
24102 (move-beginning-of-line 1)
24103 (looking-at org-drawer-regexp)))
24105 (defun org-at-block-p nil
24106 "Is cursor at a block keyword?"
24107 (save-excursion
24108 (move-beginning-of-line 1)
24109 (looking-at org-block-regexp)))
24111 (defun org-point-at-end-of-empty-headline ()
24112 "If point is at the end of an empty headline, return t, else nil.
24113 If the heading only contains a TODO keyword, it is still still considered
24114 empty."
24115 (and (looking-at "[ \t]*$")
24116 (when org-todo-line-regexp
24117 (save-excursion
24118 (beginning-of-line 1)
24119 (let ((case-fold-search nil))
24120 (looking-at org-todo-line-regexp)
24121 (string= (match-string 3) ""))))))
24123 (defun org-at-heading-or-item-p ()
24124 (or (org-at-heading-p) (org-at-item-p)))
24126 (defun org-at-target-p ()
24127 (or (org-in-regexp org-radio-target-regexp)
24128 (org-in-regexp org-target-regexp)))
24129 ;; Compatibility alias with Org versions < 7.8.03
24130 (defalias 'org-on-target-p 'org-at-target-p)
24132 (defun org-up-heading-all (arg)
24133 "Move to the heading line of which the present line is a subheading.
24134 This function considers both visible and invisible heading lines.
24135 With argument, move up ARG levels."
24136 (outline-up-heading arg t))
24138 (defun org-up-heading-safe ()
24139 "Move to the heading line of which the present line is a subheading.
24140 This version will not throw an error. It will return the level of the
24141 headline found, or nil if no higher level is found.
24143 Also, this function will be a lot faster than `outline-up-heading',
24144 because it relies on stars being the outline starters. This can really
24145 make a significant difference in outlines with very many siblings."
24146 (when (ignore-errors (org-back-to-heading t))
24147 (let ((level-up (1- (funcall outline-level))))
24148 (and (> level-up 0)
24149 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24150 (funcall outline-level)))))
24152 (defun org-first-sibling-p ()
24153 "Is this heading the first child of its parents?"
24154 (interactive)
24155 (let ((re org-outline-regexp-bol)
24156 level l)
24157 (unless (org-at-heading-p t)
24158 (user-error "Not at a heading"))
24159 (setq level (funcall outline-level))
24160 (save-excursion
24161 (if (not (re-search-backward re nil t))
24163 (setq l (funcall outline-level))
24164 (< l level)))))
24166 (defun org-goto-sibling (&optional previous)
24167 "Goto the next sibling, even if it is invisible.
24168 When PREVIOUS is set, go to the previous sibling instead. Returns t
24169 when a sibling was found. When none is found, return nil and don't
24170 move point."
24171 (let ((fun (if previous 're-search-backward 're-search-forward))
24172 (pos (point))
24173 (re org-outline-regexp-bol)
24174 level l)
24175 (when (ignore-errors (org-back-to-heading t))
24176 (setq level (funcall outline-level))
24177 (catch 'exit
24178 (or previous (forward-char 1))
24179 (while (funcall fun re nil t)
24180 (setq l (funcall outline-level))
24181 (when (< l level) (goto-char pos) (throw 'exit nil))
24182 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24183 (goto-char pos)
24184 nil))))
24186 (defun org-show-siblings ()
24187 "Show all siblings of the current headline."
24188 (save-excursion
24189 (while (org-goto-sibling) (org-flag-heading nil)))
24190 (save-excursion
24191 (while (org-goto-sibling 'previous)
24192 (org-flag-heading nil))))
24194 (defun org-goto-first-child ()
24195 "Goto the first child, even if it is invisible.
24196 Return t when a child was found. Otherwise don't move point and
24197 return nil."
24198 (let (level (pos (point)) (re org-outline-regexp-bol))
24199 (when (ignore-errors (org-back-to-heading t))
24200 (setq level (outline-level))
24201 (forward-char 1)
24202 (if (and (re-search-forward re nil t) (> (outline-level) level))
24203 (progn (goto-char (match-beginning 0)) t)
24204 (goto-char pos) nil))))
24206 (defun org-show-hidden-entry ()
24207 "Show an entry where even the heading is hidden."
24208 (save-excursion
24209 (org-show-entry)))
24211 (defun org-flag-heading (flag &optional entry)
24212 "Flag the current heading. FLAG non-nil means make invisible.
24213 When ENTRY is non-nil, show the entire entry."
24214 (save-excursion
24215 (org-back-to-heading t)
24216 ;; Check if we should show the entire entry
24217 (if entry
24218 (progn
24219 (org-show-entry)
24220 (save-excursion
24221 (and (outline-next-heading)
24222 (org-flag-heading nil))))
24223 (outline-flag-region (max (point-min) (1- (point)))
24224 (save-excursion (outline-end-of-heading) (point))
24225 flag))))
24227 (defun org-get-next-sibling ()
24228 "Move to next heading of the same level, and return point.
24229 If there is no such heading, return nil.
24230 This is like outline-next-sibling, but invisible headings are ok."
24231 (let ((level (funcall outline-level)))
24232 (outline-next-heading)
24233 (while (and (not (eobp)) (> (funcall outline-level) level))
24234 (outline-next-heading))
24235 (unless (or (eobp) (< (funcall outline-level) level))
24236 (point))))
24238 (defun org-get-last-sibling ()
24239 "Move to previous heading of the same level, and return point.
24240 If there is no such heading, return nil."
24241 (let ((opoint (point))
24242 (level (funcall outline-level)))
24243 (outline-previous-heading)
24244 (when (and (/= (point) opoint) (outline-on-heading-p t))
24245 (while (and (> (funcall outline-level) level)
24246 (not (bobp)))
24247 (outline-previous-heading))
24248 (unless (< (funcall outline-level) level)
24249 (point)))))
24251 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24252 "Goto to the end of a subtree."
24253 ;; This contains an exact copy of the original function, but it uses
24254 ;; `org-back-to-heading', to make it work also in invisible
24255 ;; trees. And is uses an invisible-ok argument.
24256 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24257 ;; Furthermore, when used inside Org, finding the end of a large subtree
24258 ;; with many children and grandchildren etc, this can be much faster
24259 ;; than the outline version.
24260 (org-back-to-heading invisible-ok)
24261 (let ((first t)
24262 (level (funcall outline-level)))
24263 (if (and (derived-mode-p 'org-mode) (< level 1000))
24264 ;; A true heading (not a plain list item), in Org
24265 ;; This means we can easily find the end by looking
24266 ;; only for the right number of stars. Using a regexp to do
24267 ;; this is so much faster than using a Lisp loop.
24268 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24269 (forward-char 1)
24270 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24271 ;; something else, do it the slow way
24272 (while (and (not (eobp))
24273 (or first (> (funcall outline-level) level)))
24274 (setq first nil)
24275 (outline-next-heading)))
24276 (unless to-heading
24277 (when (memq (preceding-char) '(?\n ?\^M))
24278 ;; Go to end of line before heading
24279 (forward-char -1)
24280 (when (memq (preceding-char) '(?\n ?\^M))
24281 ;; leave blank line before heading
24282 (forward-char -1)))))
24283 (point))
24285 (defun org-end-of-meta-data (&optional full)
24286 "Skip planning line and properties drawer in current entry.
24287 When optional argument FULL is non-nil, also skip empty lines,
24288 clocking lines and regular drawers at the beginning of the
24289 entry."
24290 (org-back-to-heading t)
24291 (forward-line)
24292 (when (looking-at-p org-planning-line-re) (forward-line))
24293 (when (looking-at org-property-drawer-re)
24294 (goto-char (match-end 0))
24295 (forward-line))
24296 (when (and full (not (org-at-heading-p)))
24297 (catch 'exit
24298 (let ((end (save-excursion (outline-next-heading) (point)))
24299 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24300 (while (not (eobp))
24301 (cond ((looking-at-p org-drawer-regexp)
24302 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24303 (forward-line)
24304 (throw 'exit t)))
24305 ((looking-at-p re) (forward-line))
24306 (t (throw 'exit t))))))))
24308 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24309 "Move forward to the ARG'th subheading at same level as this one.
24310 Stop at the first and last subheadings of a superior heading.
24311 Normally this only looks at visible headings, but when INVISIBLE-OK is
24312 non-nil it will also look at invisible ones."
24313 (interactive "p")
24314 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24315 (if (and arg (< arg 0))
24316 (goto-char (point-min))
24317 (outline-next-heading))
24318 (org-at-heading-p)
24319 (let ((level (- (match-end 0) (match-beginning 0) 1))
24320 (f (if (and arg (< arg 0))
24321 're-search-backward
24322 're-search-forward))
24323 (count (if arg (abs arg) 1))
24324 (result (point)))
24325 (while (and (prog1 (> count 0)
24326 (forward-char (if (and arg (< arg 0)) -1 1)))
24327 (funcall f org-outline-regexp-bol nil 'move))
24328 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24329 (cond ((< l level) (setq count 0))
24330 ((and (= l level)
24331 (or invisible-ok
24332 (progn
24333 (goto-char (line-beginning-position))
24334 (not (outline-invisible-p)))))
24335 (setq count (1- count))
24336 (when (eq l level)
24337 (setq result (point)))))))
24338 (goto-char result))
24339 (beginning-of-line 1)))
24341 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24342 "Move backward to the ARG'th subheading at same level as this one.
24343 Stop at the first and last subheadings of a superior heading."
24344 (interactive "p")
24345 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24347 (defun org-next-visible-heading (arg)
24348 "Move to the next visible heading.
24350 This function wraps `outline-next-visible-heading' with
24351 `org-with-limited-levels' in order to skip over inline tasks and
24352 respect customization of `org-odd-levels-only'."
24353 (interactive "p")
24354 (org-with-limited-levels
24355 (outline-next-visible-heading arg)))
24357 (defun org-previous-visible-heading (arg)
24358 "Move to the previous visible heading.
24360 This function wraps `outline-previous-visible-heading' with
24361 `org-with-limited-levels' in order to skip over inline tasks and
24362 respect customization of `org-odd-levels-only'."
24363 (interactive "p")
24364 (org-with-limited-levels
24365 (outline-previous-visible-heading arg)))
24367 (defun org-next-block (arg &optional backward block-regexp)
24368 "Jump to the next block.
24370 With a prefix argument ARG, jump forward ARG many blocks.
24372 When BACKWARD is non-nil, jump to the previous block.
24374 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24375 Match data is set according to this regexp when the function
24376 returns.
24378 Return point at beginning of the opening line of found block.
24379 Throw an error if no block is found."
24380 (interactive "p")
24381 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24382 (case-fold-search t)
24383 (search-fn (if backward #'re-search-backward #'re-search-forward))
24384 (count (or arg 1))
24385 (origin (point))
24386 last-element)
24387 (if backward (beginning-of-line) (end-of-line))
24388 (while (and (> count 0) (funcall search-fn re nil t))
24389 (let ((element (save-excursion
24390 (goto-char (match-beginning 0))
24391 (save-match-data (org-element-at-point)))))
24392 (when (and (memq (org-element-type element)
24393 '(center-block comment-block dynamic-block
24394 example-block export-block quote-block
24395 special-block src-block verse-block))
24396 (<= (match-beginning 0)
24397 (org-element-property :post-affiliated element)))
24398 (setq last-element element)
24399 (cl-decf count))))
24400 (if (= count 0)
24401 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24402 (save-match-data (org-show-context)))
24403 (goto-char origin)
24404 (user-error "No %s code blocks" (if backward "previous" "further")))))
24406 (defun org-previous-block (arg &optional block-regexp)
24407 "Jump to the previous block.
24408 With a prefix argument ARG, jump backward ARG many source blocks.
24409 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24410 (interactive "p")
24411 (org-next-block arg t block-regexp))
24413 (defun org-forward-paragraph ()
24414 "Move forward to beginning of next paragraph or equivalent.
24416 The function moves point to the beginning of the next visible
24417 structural element, which can be a paragraph, a table, a list
24418 item, etc. It also provides some special moves for convenience:
24420 - On an affiliated keyword, jump to the beginning of the
24421 relative element.
24422 - On an item or a footnote definition, move to the second
24423 element inside, if any.
24424 - On a table or a property drawer, jump after it.
24425 - On a verse or source block, stop after blank lines."
24426 (interactive)
24427 (when (eobp) (user-error "Cannot move further down"))
24428 (let* ((deactivate-mark nil)
24429 (element (org-element-at-point))
24430 (type (org-element-type element))
24431 (post-affiliated (org-element-property :post-affiliated element))
24432 (contents-begin (org-element-property :contents-begin element))
24433 (contents-end (org-element-property :contents-end element))
24434 (end (let ((end (org-element-property :end element)) (parent element))
24435 (while (and (setq parent (org-element-property :parent parent))
24436 (= (org-element-property :contents-end parent) end))
24437 (setq end (org-element-property :end parent)))
24438 end)))
24439 (cond ((not element)
24440 (skip-chars-forward " \r\t\n")
24441 (or (eobp) (beginning-of-line)))
24442 ;; On affiliated keywords, move to element's beginning.
24443 ((< (point) post-affiliated)
24444 (goto-char post-affiliated))
24445 ;; At a table row, move to the end of the table. Similarly,
24446 ;; at a node property, move to the end of the property
24447 ;; drawer.
24448 ((memq type '(node-property table-row))
24449 (goto-char (org-element-property
24450 :end (org-element-property :parent element))))
24451 ((memq type '(property-drawer table)) (goto-char end))
24452 ;; Consider blank lines as separators in verse and source
24453 ;; blocks to ease editing.
24454 ((memq type '(src-block verse-block))
24455 (when (eq type 'src-block)
24456 (setq contents-end
24457 (save-excursion (goto-char end)
24458 (skip-chars-backward " \r\t\n")
24459 (line-beginning-position))))
24460 (beginning-of-line)
24461 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24462 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24463 (goto-char end)
24464 (skip-chars-forward " \r\t\n")
24465 (if (= (point) contents-end) (goto-char end)
24466 (beginning-of-line))))
24467 ;; With no contents, just skip element.
24468 ((not contents-begin) (goto-char end))
24469 ;; If contents are invisible, skip the element altogether.
24470 ((outline-invisible-p (line-end-position))
24471 (cl-case type
24472 (headline
24473 (org-with-limited-levels (outline-next-visible-heading 1)))
24474 ;; At a plain list, make sure we move to the next item
24475 ;; instead of skipping the whole list.
24476 (plain-list (forward-char)
24477 (org-forward-paragraph))
24478 (otherwise (goto-char end))))
24479 ((>= (point) contents-end) (goto-char end))
24480 ((>= (point) contents-begin)
24481 ;; This can only happen on paragraphs and plain lists.
24482 (cl-case type
24483 (paragraph (goto-char end))
24484 ;; At a plain list, try to move to second element in
24485 ;; first item, if possible.
24486 (plain-list (end-of-line)
24487 (org-forward-paragraph))))
24488 ;; When contents start on the middle of a line (e.g. in
24489 ;; items and footnote definitions), try to reach first
24490 ;; element starting after current line.
24491 ((> (line-end-position) contents-begin)
24492 (end-of-line)
24493 (org-forward-paragraph))
24494 (t (goto-char contents-begin)))))
24496 (defun org-backward-paragraph ()
24497 "Move backward to start of previous paragraph or equivalent.
24499 The function moves point to the beginning of the current
24500 structural element, which can be a paragraph, a table, a list
24501 item, etc., or to the beginning of the previous visible one if
24502 point is already there. It also provides some special moves for
24503 convenience:
24505 - On an affiliated keyword, jump to the first one.
24506 - On a table or a property drawer, move to its beginning.
24507 - On a verse or source block, stop before blank lines."
24508 (interactive)
24509 (when (bobp) (user-error "Cannot move further up"))
24510 (let* ((deactivate-mark nil)
24511 (element (org-element-at-point))
24512 (type (org-element-type element))
24513 (contents-begin (org-element-property :contents-begin element))
24514 (contents-end (org-element-property :contents-end element))
24515 (post-affiliated (org-element-property :post-affiliated element))
24516 (begin (org-element-property :begin element)))
24517 (cond
24518 ((not element) (goto-char (point-min)))
24519 ((= (point) begin)
24520 (backward-char)
24521 (org-backward-paragraph))
24522 ((<= (point) post-affiliated) (goto-char begin))
24523 ((memq type '(node-property table-row))
24524 (goto-char (org-element-property
24525 :post-affiliated (org-element-property :parent element))))
24526 ((memq type '(property-drawer table)) (goto-char begin))
24527 ((memq type '(src-block verse-block))
24528 (when (eq type 'src-block)
24529 (setq contents-begin
24530 (save-excursion (goto-char begin) (forward-line) (point))))
24531 (if (= (point) contents-begin) (goto-char post-affiliated)
24532 ;; Inside a verse block, see blank lines as paragraph
24533 ;; separators.
24534 (let ((origin (point)))
24535 (skip-chars-backward " \r\t\n" contents-begin)
24536 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24537 (skip-chars-forward " \r\t\n" origin)
24538 (if (= (point) origin) (goto-char contents-begin)
24539 (beginning-of-line))))))
24540 ((not contents-begin) (goto-char (or post-affiliated begin)))
24541 ((eq type 'paragraph)
24542 (goto-char contents-begin)
24543 ;; When at first paragraph in an item or a footnote definition,
24544 ;; move directly to beginning of line.
24545 (let ((parent-contents
24546 (org-element-property
24547 :contents-begin (org-element-property :parent element))))
24548 (when (and parent-contents (= parent-contents contents-begin))
24549 (beginning-of-line))))
24550 ;; At the end of a greater element, move to the beginning of the
24551 ;; last element within.
24552 ((>= (point) contents-end)
24553 (goto-char (1- contents-end))
24554 (org-backward-paragraph))
24555 (t (goto-char (or post-affiliated begin))))
24556 ;; Ensure we never leave point invisible.
24557 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24559 (defun org-forward-element ()
24560 "Move forward by one element.
24561 Move to the next element at the same level, when possible."
24562 (interactive)
24563 (cond ((eobp) (user-error "Cannot move further down"))
24564 ((org-with-limited-levels (org-at-heading-p))
24565 (let ((origin (point)))
24566 (goto-char (org-end-of-subtree nil t))
24567 (unless (org-with-limited-levels (org-at-heading-p))
24568 (goto-char origin)
24569 (user-error "Cannot move further down"))))
24571 (let* ((elem (org-element-at-point))
24572 (end (org-element-property :end elem))
24573 (parent (org-element-property :parent elem)))
24574 (cond ((and parent (= (org-element-property :contents-end parent) end))
24575 (goto-char (org-element-property :end parent)))
24576 ((integer-or-marker-p end) (goto-char end))
24577 (t (message "No element at point")))))))
24579 (defun org-backward-element ()
24580 "Move backward by one element.
24581 Move to the previous element at the same level, when possible."
24582 (interactive)
24583 (cond ((bobp) (user-error "Cannot move further up"))
24584 ((org-with-limited-levels (org-at-heading-p))
24585 ;; At a headline, move to the previous one, if any, or stay
24586 ;; here.
24587 (let ((origin (point)))
24588 (org-with-limited-levels (org-backward-heading-same-level 1))
24589 ;; When current headline has no sibling above, move to its
24590 ;; parent.
24591 (when (= (point) origin)
24592 (or (org-with-limited-levels (org-up-heading-safe))
24593 (progn (goto-char origin)
24594 (user-error "Cannot move further up"))))))
24596 (let* ((elem (org-element-at-point))
24597 (beg (org-element-property :begin elem)))
24598 (cond
24599 ;; Move to beginning of current element if point isn't
24600 ;; there already.
24601 ((null beg) (message "No element at point"))
24602 ((/= (point) beg) (goto-char beg))
24603 (t (goto-char beg)
24604 (skip-chars-backward " \r\t\n")
24605 (unless (bobp)
24606 (let ((prev (org-element-at-point)))
24607 (goto-char (org-element-property :begin prev))
24608 (while (and (setq prev (org-element-property :parent prev))
24609 (<= (org-element-property :end prev) beg))
24610 (goto-char (org-element-property :begin prev)))))))))))
24612 (defun org-up-element ()
24613 "Move to upper element."
24614 (interactive)
24615 (if (org-with-limited-levels (org-at-heading-p))
24616 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24617 (let* ((elem (org-element-at-point))
24618 (parent (org-element-property :parent elem)))
24619 (if parent (goto-char (org-element-property :begin parent))
24620 (if (org-with-limited-levels (org-before-first-heading-p))
24621 (user-error "No surrounding element")
24622 (org-with-limited-levels (org-back-to-heading)))))))
24624 (defvar org-element-greater-elements)
24625 (defun org-down-element ()
24626 "Move to inner element."
24627 (interactive)
24628 (let ((element (org-element-at-point)))
24629 (cond
24630 ((memq (org-element-type element) '(plain-list table))
24631 (goto-char (org-element-property :contents-begin element))
24632 (forward-char))
24633 ((memq (org-element-type element) org-element-greater-elements)
24634 ;; If contents are hidden, first disclose them.
24635 (when (outline-invisible-p (line-end-position)) (org-cycle))
24636 (goto-char (or (org-element-property :contents-begin element)
24637 (user-error "No content for this element"))))
24638 (t (user-error "No inner element")))))
24640 (defun org-drag-element-backward ()
24641 "Move backward element at point."
24642 (interactive)
24643 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24644 (let* ((elem (org-element-at-point))
24645 (prev-elem
24646 (save-excursion
24647 (goto-char (org-element-property :begin elem))
24648 (skip-chars-backward " \r\t\n")
24649 (unless (bobp)
24650 (let* ((beg (org-element-property :begin elem))
24651 (prev (org-element-at-point))
24652 (up prev))
24653 (while (and (setq up (org-element-property :parent up))
24654 (<= (org-element-property :end up) beg))
24655 (setq prev up))
24656 prev)))))
24657 ;; Error out if no previous element or previous element is
24658 ;; a parent of the current one.
24659 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24660 (user-error "Cannot drag element backward")
24661 (let ((pos (point)))
24662 (org-element-swap-A-B prev-elem elem)
24663 (goto-char (+ (org-element-property :begin prev-elem)
24664 (- pos (org-element-property :begin elem)))))))))
24666 (defun org-drag-element-forward ()
24667 "Move forward element at point."
24668 (interactive)
24669 (let* ((pos (point))
24670 (elem (org-element-at-point)))
24671 (when (= (point-max) (org-element-property :end elem))
24672 (user-error "Cannot drag element forward"))
24673 (goto-char (org-element-property :end elem))
24674 (let ((next-elem (org-element-at-point)))
24675 (when (or (org-element-nested-p elem next-elem)
24676 (and (eq (org-element-type next-elem) 'headline)
24677 (not (eq (org-element-type elem) 'headline))))
24678 (goto-char pos)
24679 (user-error "Cannot drag element forward"))
24680 ;; Compute new position of point: it's shifted by NEXT-ELEM
24681 ;; body's length (without final blanks) and by the length of
24682 ;; blanks between ELEM and NEXT-ELEM.
24683 (let ((size-next (- (save-excursion
24684 (goto-char (org-element-property :end next-elem))
24685 (skip-chars-backward " \r\t\n")
24686 (forward-line)
24687 ;; Small correction if buffer doesn't end
24688 ;; with a newline character.
24689 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24690 (org-element-property :begin next-elem)))
24691 (size-blank (- (org-element-property :end elem)
24692 (save-excursion
24693 (goto-char (org-element-property :end elem))
24694 (skip-chars-backward " \r\t\n")
24695 (forward-line)
24696 (point)))))
24697 (org-element-swap-A-B elem next-elem)
24698 (goto-char (+ pos size-next size-blank))))))
24700 (defun org-drag-line-forward (arg)
24701 "Drag the line at point ARG lines forward."
24702 (interactive "p")
24703 (dotimes (_ (abs arg))
24704 (let ((c (current-column)))
24705 (if (< 0 arg)
24706 (progn
24707 (beginning-of-line 2)
24708 (transpose-lines 1)
24709 (beginning-of-line 0))
24710 (transpose-lines 1)
24711 (beginning-of-line -1))
24712 (org-move-to-column c))))
24714 (defun org-drag-line-backward (arg)
24715 "Drag the line at point ARG lines backward."
24716 (interactive "p")
24717 (org-drag-line-forward (- arg)))
24719 (defun org-mark-element ()
24720 "Put point at beginning of this element, mark at end.
24722 Interactively, if this command is repeated or (in Transient Mark
24723 mode) if the mark is active, it marks the next element after the
24724 ones already marked."
24725 (interactive)
24726 (let (deactivate-mark)
24727 (if (and (called-interactively-p 'any)
24728 (or (and (eq last-command this-command) (mark t))
24729 (and transient-mark-mode mark-active)))
24730 (set-mark
24731 (save-excursion
24732 (goto-char (mark))
24733 (goto-char (org-element-property :end (org-element-at-point)))))
24734 (let ((element (org-element-at-point)))
24735 (end-of-line)
24736 (push-mark (org-element-property :end element) t t)
24737 (goto-char (org-element-property :begin element))))))
24739 (defun org-narrow-to-element ()
24740 "Narrow buffer to current element."
24741 (interactive)
24742 (let ((elem (org-element-at-point)))
24743 (cond
24744 ((eq (car elem) 'headline)
24745 (narrow-to-region
24746 (org-element-property :begin elem)
24747 (org-element-property :end elem)))
24748 ((memq (car elem) org-element-greater-elements)
24749 (narrow-to-region
24750 (org-element-property :contents-begin elem)
24751 (org-element-property :contents-end elem)))
24753 (narrow-to-region
24754 (org-element-property :begin elem)
24755 (org-element-property :end elem))))))
24757 (defun org-transpose-element ()
24758 "Transpose current and previous elements, keeping blank lines between.
24759 Point is moved after both elements."
24760 (interactive)
24761 (org-skip-whitespace)
24762 (let ((end (org-element-property :end (org-element-at-point))))
24763 (org-drag-element-backward)
24764 (goto-char end)))
24766 (defun org-unindent-buffer ()
24767 "Un-indent the visible part of the buffer.
24768 Relative indentation (between items, inside blocks, etc.) isn't
24769 modified."
24770 (interactive)
24771 (unless (eq major-mode 'org-mode)
24772 (user-error "Cannot un-indent a buffer not in Org mode"))
24773 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24774 (unindent-tree
24775 (lambda (contents)
24776 (dolist (element (reverse contents))
24777 (if (memq (org-element-type element) '(headline section))
24778 (funcall unindent-tree (org-element-contents element))
24779 (save-excursion
24780 (save-restriction
24781 (narrow-to-region
24782 (org-element-property :begin element)
24783 (org-element-property :end element))
24784 (org-do-remove-indentation))))))))
24785 (funcall unindent-tree (org-element-contents parse-tree))))
24787 (defun org-show-children (&optional level)
24788 "Show all direct subheadings of this heading.
24789 Prefix arg LEVEL is how many levels below the current level
24790 should be shown. Default is enough to cause the following
24791 heading to appear."
24792 (interactive "p")
24793 ;; If `orgstruct-mode' is active, use the slower version.
24794 (if orgstruct-mode (call-interactively #'outline-show-children)
24795 (save-excursion
24796 (org-back-to-heading t)
24797 (let* ((current-level (funcall outline-level))
24798 (max-level (org-get-valid-level
24799 current-level
24800 (if level (prefix-numeric-value level) 1)))
24801 (end (save-excursion (org-end-of-subtree t t)))
24802 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24803 (past-first-child nil)
24804 ;; Make sure to skip inlinetasks.
24805 (re (format regexp-fmt
24806 current-level
24807 (cond
24808 ((not (featurep 'org-inlinetask)) "")
24809 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24811 (t (1- org-inlinetask-min-level))))))
24812 ;; Display parent heading.
24813 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24814 (forward-line)
24815 ;; Display children. First child may be deeper than expected
24816 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24817 ;; MAX-LEVEL accordingly.
24818 (while (re-search-forward re end t)
24819 (unless past-first-child
24820 (setq re (format regexp-fmt
24821 current-level
24822 (max (funcall outline-level) max-level)))
24823 (setq past-first-child t))
24824 (outline-flag-region
24825 (line-end-position 0) (line-end-position) nil))))))
24827 (defun org-show-subtree ()
24828 "Show everything after this heading at deeper levels."
24829 (interactive)
24830 (outline-flag-region
24831 (point)
24832 (save-excursion
24833 (org-end-of-subtree t t))
24834 nil))
24836 (defun org-show-entry ()
24837 "Show the body directly following this heading.
24838 Show the heading too, if it is currently invisible."
24839 (interactive)
24840 (save-excursion
24841 (ignore-errors
24842 (org-back-to-heading t)
24843 (outline-flag-region
24844 (max (point-min) (1- (point)))
24845 (save-excursion
24846 (if (re-search-forward
24847 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24848 (match-beginning 1)
24849 (point-max)))
24850 nil)
24851 (org-cycle-hide-drawers 'children))))
24853 (defun org-make-options-regexp (kwds &optional extra)
24854 "Make a regular expression for keyword lines.
24855 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24856 when non-nil, is a regexp matching keywords names."
24857 (concat "^[ \t]*#\\+\\("
24858 (regexp-opt kwds)
24859 (and extra (concat (and kwds "\\|") extra))
24860 "\\):[ \t]*\\(.*\\)"))
24862 ;;;; Integration with and fixes for other packages
24864 ;;; Imenu support
24866 (defvar-local org-imenu-markers nil
24867 "All markers currently used by Imenu.")
24869 (defun org-imenu-new-marker (&optional pos)
24870 "Return a new marker for use by Imenu, and remember the marker."
24871 (let ((m (make-marker)))
24872 (move-marker m (or pos (point)))
24873 (push m org-imenu-markers)
24876 (defun org-imenu-get-tree ()
24877 "Produce the index for Imenu."
24878 (dolist (x org-imenu-markers) (move-marker x nil))
24879 (setq org-imenu-markers nil)
24880 (let* ((case-fold-search nil)
24881 (n org-imenu-depth)
24882 (re (concat "^" (org-get-limited-outline-regexp)))
24883 (subs (make-vector (1+ n) nil))
24884 (last-level 0)
24885 m level head0 head)
24886 (org-with-wide-buffer
24887 (goto-char (point-max))
24888 (while (re-search-backward re nil t)
24889 (setq level (org-reduced-level (funcall outline-level)))
24890 (when (and (<= level n)
24891 (looking-at org-complex-heading-regexp)
24892 (setq head0 (match-string-no-properties 4)))
24893 (setq head (org-link-display-format head0)
24894 m (org-imenu-new-marker))
24895 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24896 (if (>= level last-level)
24897 (push (cons head m) (aref subs level))
24898 (push (cons head (aref subs (1+ level))) (aref subs level))
24899 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24900 (setq last-level level))))
24901 (aref subs 1)))
24903 (eval-after-load "imenu"
24904 '(progn
24905 (add-hook 'imenu-after-jump-hook
24906 (lambda ()
24907 (when (derived-mode-p 'org-mode)
24908 (org-show-context 'org-goto))))))
24910 (defun org-link-display-format (s)
24911 "Replace links in string S with their description.
24912 If there is no description, use the link target."
24913 (save-match-data
24914 (replace-regexp-in-string
24915 org-bracket-link-analytic-regexp
24916 (lambda (m)
24917 (if (match-end 5) (match-string 5 m)
24918 (concat (match-string 1 m) (match-string 3 m))))
24919 s nil t)))
24921 (defun org-toggle-link-display ()
24922 "Toggle the literal or descriptive display of links."
24923 (interactive)
24924 (if org-descriptive-links
24925 (progn (org-remove-from-invisibility-spec '(org-link))
24926 (org-restart-font-lock)
24927 (setq org-descriptive-links nil))
24928 (progn (add-to-invisibility-spec '(org-link))
24929 (org-restart-font-lock)
24930 (setq org-descriptive-links t))))
24932 ;; Speedbar support
24934 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24935 "Overlay marking the agenda restriction line in speedbar.")
24936 (overlay-put org-speedbar-restriction-lock-overlay
24937 'face 'org-agenda-restriction-lock)
24938 (overlay-put org-speedbar-restriction-lock-overlay
24939 'help-echo "Agendas are currently limited to this item.")
24940 (delete-overlay org-speedbar-restriction-lock-overlay)
24942 (defun org-speedbar-set-agenda-restriction ()
24943 "Restrict future agenda commands to the location at point in speedbar.
24944 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24945 (interactive)
24946 (require 'org-agenda)
24947 (let (p m tp np dir txt)
24948 (cond
24949 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24950 'org-imenu t))
24951 (setq m (get-text-property p 'org-imenu-marker))
24952 (with-current-buffer (marker-buffer m)
24953 (goto-char m)
24954 (org-agenda-set-restriction-lock 'subtree)))
24955 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24956 'speedbar-function 'speedbar-find-file))
24957 (setq tp (previous-single-property-change
24958 (1+ p) 'speedbar-function)
24959 np (next-single-property-change
24960 tp 'speedbar-function)
24961 dir (speedbar-line-directory)
24962 txt (buffer-substring-no-properties (or tp (point-min))
24963 (or np (point-max))))
24964 (with-current-buffer (find-file-noselect
24965 (let ((default-directory dir))
24966 (expand-file-name txt)))
24967 (unless (derived-mode-p 'org-mode)
24968 (user-error "Cannot restrict to non-Org mode file"))
24969 (org-agenda-set-restriction-lock 'file)))
24970 (t (user-error "Don't know how to restrict Org mode agenda")))
24971 (move-overlay org-speedbar-restriction-lock-overlay
24972 (point-at-bol) (point-at-eol))
24973 (setq current-prefix-arg nil)
24974 (org-agenda-maybe-redo)))
24976 (defvar speedbar-file-key-map)
24977 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24978 (eval-after-load "speedbar"
24979 '(progn
24980 (speedbar-add-supported-extension ".org")
24981 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24982 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24983 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24984 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24985 (add-hook 'speedbar-visiting-tag-hook
24986 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24988 ;;; Fixes and Hacks for problems with other packages
24990 (defun org--flyspell-object-check-p (element)
24991 "Non-nil when Flyspell can check object at point.
24992 ELEMENT is the element at point."
24993 (let ((object (save-excursion
24994 (when (looking-at-p "\\>") (backward-char))
24995 (org-element-context element))))
24996 (cl-case (org-element-type object)
24997 ;; Prevent checks in links due to keybinding conflict with
24998 ;; Flyspell.
24999 ((code entity export-snippet inline-babel-call
25000 inline-src-block line-break latex-fragment link macro
25001 statistics-cookie target timestamp verbatim)
25002 nil)
25003 (footnote-reference
25004 ;; Only in inline footnotes, within the definition.
25005 (and (eq (org-element-property :type object) 'inline)
25006 (< (save-excursion
25007 (goto-char (org-element-property :begin object))
25008 (search-forward ":" nil t 2))
25009 (point))))
25010 (otherwise t))))
25012 (defun org-mode-flyspell-verify ()
25013 "Function used for `flyspell-generic-check-word-predicate'."
25014 (if (org-at-heading-p)
25015 ;; At a headline or an inlinetask, check title only. This is
25016 ;; faster than relying on `org-element-at-point'.
25017 (and (save-excursion (beginning-of-line)
25018 (and (let ((case-fold-search t))
25019 (not (looking-at "\\*+ END[ \t]*$")))
25020 (looking-at org-complex-heading-regexp)))
25021 (match-beginning 4)
25022 (>= (point) (match-beginning 4))
25023 (or (not (match-beginning 5))
25024 (< (point) (match-beginning 5))))
25025 (let* ((element (org-element-at-point))
25026 (post-affiliated (org-element-property :post-affiliated element)))
25027 (cond
25028 ;; Ignore checks in all affiliated keywords but captions.
25029 ((< (point) post-affiliated)
25030 (and (save-excursion
25031 (beginning-of-line)
25032 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25033 (> (point) (match-end 0))
25034 (org--flyspell-object-check-p element)))
25035 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25036 ((let ((log (org-log-into-drawer)))
25037 (and log
25038 (let ((drawer (org-element-lineage element '(drawer))))
25039 (and drawer
25040 (eq (compare-strings
25041 log nil nil
25042 (org-element-property :drawer-name drawer) nil nil t)
25043 t)))))
25044 nil)
25046 (cl-case (org-element-type element)
25047 ((comment quote-section) t)
25048 (comment-block
25049 ;; Allow checks between block markers, not on them.
25050 (and (> (line-beginning-position) post-affiliated)
25051 (save-excursion
25052 (end-of-line)
25053 (skip-chars-forward " \r\t\n")
25054 (< (point) (org-element-property :end element)))))
25055 ;; Arbitrary list of keywords where checks are meaningful.
25056 ;; Make sure point is on the value part of the element.
25057 (keyword
25058 (and (member (org-element-property :key element)
25059 '("DESCRIPTION" "TITLE"))
25060 (save-excursion
25061 (search-backward ":" (line-beginning-position) t))))
25062 ;; Check is globally allowed in paragraphs verse blocks and
25063 ;; table rows (after affiliated keywords) but some objects
25064 ;; must not be affected.
25065 ((paragraph table-row verse-block)
25066 (let ((cbeg (org-element-property :contents-begin element))
25067 (cend (org-element-property :contents-end element)))
25068 (and cbeg (>= (point) cbeg) (< (point) cend)
25069 (org--flyspell-object-check-p element))))))))))
25070 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25072 (defun org-remove-flyspell-overlays-in (beg end)
25073 "Remove flyspell overlays in region."
25074 (and (bound-and-true-p flyspell-mode)
25075 (fboundp 'flyspell-delete-region-overlays)
25076 (flyspell-delete-region-overlays beg end)))
25078 (defvar flyspell-delayed-commands)
25079 (eval-after-load "flyspell"
25080 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25082 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25083 (eval-after-load "bookmark"
25084 '(if (boundp 'bookmark-after-jump-hook)
25085 ;; We can use the hook
25086 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25087 ;; Hook not available, use advice
25088 (defadvice bookmark-jump (after org-make-visible activate)
25089 "Make the position visible."
25090 (org-bookmark-jump-unhide))))
25092 ;; Make sure saveplace shows the location if it was hidden
25093 (eval-after-load "saveplace"
25094 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25095 "Make the position visible."
25096 (org-bookmark-jump-unhide)))
25098 ;; Make sure ecb shows the location if it was hidden
25099 (eval-after-load "ecb"
25100 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25101 "Make hierarchy visible when jumping into location from ECB tree buffer."
25102 (when (derived-mode-p 'org-mode)
25103 (org-show-context))))
25105 (defun org-bookmark-jump-unhide ()
25106 "Unhide the current position, to show the bookmark location."
25107 (and (derived-mode-p 'org-mode)
25108 (or (outline-invisible-p)
25109 (save-excursion (goto-char (max (point-min) (1- (point))))
25110 (outline-invisible-p)))
25111 (org-show-context 'bookmark-jump)))
25113 (defun org-mark-jump-unhide ()
25114 "Make the point visible with `org-show-context' after jumping to the mark."
25115 (when (and (derived-mode-p 'org-mode)
25116 (outline-invisible-p))
25117 (org-show-context 'mark-goto)))
25119 (eval-after-load "simple"
25120 '(defadvice pop-to-mark-command (after org-make-visible activate)
25121 "Make the point visible with `org-show-context'."
25122 (org-mark-jump-unhide)))
25124 (eval-after-load "simple"
25125 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25126 "Make the point visible with `org-show-context'."
25127 (org-mark-jump-unhide)))
25129 (eval-after-load "simple"
25130 '(defadvice pop-global-mark (after org-make-visible activate)
25131 "Make the point visible with `org-show-context'."
25132 (org-mark-jump-unhide)))
25134 ;; Make session.el ignore our circular variable
25135 (defvar session-globals-exclude)
25136 (eval-after-load "session"
25137 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25139 ;;;; Finish up
25141 (provide 'org)
25143 (run-hooks 'org-load-hook)
25145 ;;; org.el ends here