Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob2d7f5e1d52af027a5ed9a76593935a4dc47dc6b0
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda"
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-recalculate "org-table" (&optional all noalign))
171 (declare-function org-table-wrap-region "org-table" (arg))
172 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
173 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
174 (declare-function orgtbl-mode "org-table" (&optional arg))
176 (defsubst org-uniquify (list)
177 "Non-destructively remove duplicate elements from LIST."
178 (let ((res (copy-sequence list))) (delete-dups res)))
180 (defsubst org-get-at-bol (property)
181 "Get text property PROPERTY at the beginning of line."
182 (get-text-property (point-at-bol) property))
184 (defsubst org-trim (s &optional keep-lead)
185 "Remove whitespace at the beginning and the end of string S.
186 When optional argument KEEP-LEAD is non-nil, removing blank lines
187 at the beginning of the string does not affect leading indentation."
188 (replace-regexp-in-string
189 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
190 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
192 ;; load languages based on value of `org-babel-load-languages'
193 (defvar org-babel-load-languages)
195 ;;;###autoload
196 (defun org-babel-do-load-languages (sym value)
197 "Load the languages defined in `org-babel-load-languages'."
198 (set-default sym value)
199 (dolist (pair org-babel-load-languages)
200 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
201 (if active
202 (require (intern (concat "ob-" lang)))
203 (funcall 'fmakunbound
204 (intern (concat "org-babel-execute:" lang)))
205 (funcall 'fmakunbound
206 (intern (concat "org-babel-expand-body:" lang)))))))
208 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
209 ;;;###autoload
210 (defun org-babel-load-file (file &optional compile)
211 "Load Emacs Lisp source code blocks in the Org FILE.
212 This function exports the source code using `org-babel-tangle'
213 and then loads the resulting file using `load-file'. With prefix
214 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
215 file to byte-code before it is loaded."
216 (interactive "fFile to load: \nP")
217 (let* ((age (lambda (file)
218 (float-time
219 (time-subtract (current-time)
220 (nth 5 (or (file-attributes (file-truename file))
221 (file-attributes file)))))))
222 (base-name (file-name-sans-extension file))
223 (exported-file (concat base-name ".el")))
224 ;; tangle if the Org file is newer than the elisp file
225 (unless (and (file-exists-p exported-file)
226 (> (funcall age file) (funcall age exported-file)))
227 ;; Tangle-file traversal returns reversed list of tangled files
228 ;; and we want to evaluate the first target.
229 (setq exported-file
230 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
231 (message "%s %s"
232 (if compile
233 (progn (byte-compile-file exported-file 'load)
234 "Compiled and loaded")
235 (progn (load-file exported-file) "Loaded"))
236 exported-file)))
238 (defcustom org-babel-load-languages '((emacs-lisp . t))
239 "Languages which can be evaluated in Org buffers.
240 This list can be used to load support for any of the languages
241 below, note that each language will depend on a different set of
242 system executables and/or Emacs modes. When a language is
243 \"loaded\", then code blocks in that language can be evaluated
244 with `org-babel-execute-src-block' bound by default to C-c
245 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
246 be set to remove code block evaluation from the C-c C-c
247 keybinding. By default only Emacs Lisp (which has no
248 requirements) is loaded."
249 :group 'org-babel
250 :set 'org-babel-do-load-languages
251 :version "24.1"
252 :type '(alist :tag "Babel Languages"
253 :key-type
254 (choice
255 (const :tag "Awk" awk)
256 (const :tag "C" C)
257 (const :tag "R" R)
258 (const :tag "Asymptote" asymptote)
259 (const :tag "Calc" calc)
260 (const :tag "Clojure" clojure)
261 (const :tag "CSS" css)
262 (const :tag "Ditaa" ditaa)
263 (const :tag "Dot" dot)
264 (const :tag "Emacs Lisp" emacs-lisp)
265 (const :tag "Forth" forth)
266 (const :tag "Fortran" fortran)
267 (const :tag "Gnuplot" gnuplot)
268 (const :tag "Haskell" haskell)
269 (const :tag "IO" io)
270 (const :tag "J" J)
271 (const :tag "Java" java)
272 (const :tag "Javascript" js)
273 (const :tag "LaTeX" latex)
274 (const :tag "Ledger" ledger)
275 (const :tag "Lilypond" lilypond)
276 (const :tag "Lisp" lisp)
277 (const :tag "Makefile" makefile)
278 (const :tag "Maxima" maxima)
279 (const :tag "Matlab" matlab)
280 (const :tag "Mscgen" mscgen)
281 (const :tag "Ocaml" ocaml)
282 (const :tag "Octave" octave)
283 (const :tag "Org" org)
284 (const :tag "Perl" perl)
285 (const :tag "Pico Lisp" picolisp)
286 (const :tag "PlantUML" plantuml)
287 (const :tag "Python" python)
288 (const :tag "Ruby" ruby)
289 (const :tag "Sass" sass)
290 (const :tag "Scala" scala)
291 (const :tag "Scheme" scheme)
292 (const :tag "Screen" screen)
293 (const :tag "Shell Script" shell)
294 (const :tag "Shen" shen)
295 (const :tag "Sql" sql)
296 (const :tag "Sqlite" sqlite)
297 (const :tag "Stan" stan)
298 (const :tag "ebnf2ps" ebnf2ps))
299 :value-type (boolean :tag "Activate" :value t)))
301 ;;;; Customization variables
302 (defcustom org-clone-delete-id nil
303 "Remove ID property of clones of a subtree.
304 When non-nil, clones of a subtree don't inherit the ID property.
305 Otherwise they inherit the ID property with a new unique
306 identifier."
307 :type 'boolean
308 :version "24.1"
309 :group 'org-id)
311 ;;; Version
312 (org-check-version)
314 ;;;###autoload
315 (defun org-version (&optional here full message)
316 "Show the Org version.
317 Interactively, or when MESSAGE is non-nil, show it in echo area.
318 With prefix argument, or when HERE is non-nil, insert it at point.
319 In non-interactive uses, a reduced version string is output unless
320 FULL is given."
321 (interactive (list current-prefix-arg t (not current-prefix-arg)))
322 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
323 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
324 (load-suffixes (list ".el"))
325 (org-install-dir
326 (ignore-errors (org-find-library-dir "org-loaddefs"))))
327 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
328 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
329 (let* ((load-suffixes save-load-suffixes)
330 (release (org-release))
331 (git-version (org-git-version))
332 (version (format "Org mode version %s (%s @ %s)"
333 release
334 git-version
335 (if org-install-dir
336 (if (string= org-dir org-install-dir)
337 org-install-dir
338 (concat "mixed installation! "
339 org-install-dir
340 " and "
341 org-dir))
342 "org-loaddefs.el can not be found!")))
343 (version1 (if full version release)))
344 (when here (insert version1))
345 (when message (message "%s" version1))
346 version1)))
348 (defconst org-version (org-version))
351 ;;; Syntax Constants
353 ;;;; Block
355 (defconst org-block-regexp
356 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
357 "Regular expression for hiding blocks.")
359 (defconst org-dblock-start-re
360 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
361 "Matches the start line of a dynamic block, with parameters.")
363 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
364 "Matches the end of a dynamic block.")
366 ;;;; Clock and Planning
368 (defconst org-clock-string "CLOCK:"
369 "String used as prefix for timestamps clocking work hours on an item.")
371 (defvar org-closed-string "CLOSED:"
372 "String used as the prefix for timestamps logging closing a TODO entry.")
374 (defvar org-deadline-string "DEADLINE:"
375 "String to mark deadline entries.
376 \\<org-mode-map>
377 A deadline is this string, followed by a time stamp. It must be
378 a word, terminated by a colon. You can insert a schedule keyword
379 and a timestamp with `\\[org-deadline]'.")
381 (defvar org-scheduled-string "SCHEDULED:"
382 "String to mark scheduled TODO entries.
383 \\<org-mode-map>
384 A schedule is this string, followed by a time stamp. It must be
385 a word, terminated by a colon. You can insert a schedule keyword
386 and a timestamp with `\\[org-schedule]'.")
388 (defconst org-ds-keyword-length
389 (+ 2
390 (apply #'max
391 (mapcar #'length
392 (list org-deadline-string org-scheduled-string
393 org-clock-string org-closed-string))))
394 "Maximum length of the DEADLINE and SCHEDULED keywords.")
396 (defconst org-planning-line-re
397 (concat "^[ \t]*"
398 (regexp-opt
399 (list org-closed-string org-deadline-string org-scheduled-string)
401 "Matches a line with planning info.
402 Matched keyword is in group 1.")
404 (defconst org-clock-line-re
405 (concat "^[ \t]*" org-clock-string)
406 "Matches a line with clock info.")
408 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
409 "Matches the DEADLINE keyword.")
411 (defconst org-deadline-time-regexp
412 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
413 "Matches the DEADLINE keyword together with a time stamp.")
415 (defconst org-deadline-time-hour-regexp
416 (concat "\\<" org-deadline-string
417 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
418 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
420 (defconst org-deadline-line-regexp
421 (concat "\\<\\(" org-deadline-string "\\).*")
422 "Matches the DEADLINE keyword and the rest of the line.")
424 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
425 "Matches the SCHEDULED keyword.")
427 (defconst org-scheduled-time-regexp
428 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
429 "Matches the SCHEDULED keyword together with a time stamp.")
431 (defconst org-scheduled-time-hour-regexp
432 (concat "\\<" org-scheduled-string
433 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
434 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
436 (defconst org-closed-time-regexp
437 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
438 "Matches the CLOSED keyword together with a time stamp.")
440 (defconst org-keyword-time-regexp
441 (concat "\\<"
442 (regexp-opt
443 (list org-scheduled-string org-deadline-string org-closed-string
444 org-clock-string)
446 " *[[<]\\([^]>]+\\)[]>]")
447 "Matches any of the 4 keywords, together with the time stamp.")
449 (defconst org-keyword-time-not-clock-regexp
450 (concat
451 "\\<"
452 (regexp-opt
453 (list org-scheduled-string org-deadline-string org-closed-string) t)
454 " *[[<]\\([^]>]+\\)[]>]")
455 "Matches any of the 3 keywords, together with the time stamp.")
457 (defconst org-maybe-keyword-time-regexp
458 (concat "\\(\\<"
459 (regexp-opt
460 (list org-scheduled-string org-deadline-string org-closed-string
461 org-clock-string)
463 "\\)?"
464 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
465 "\\|"
466 "<%%([^\r\n>]*>\\)")
467 "Matches a timestamp, possibly preceded by a keyword.")
469 (defconst org-all-time-keywords
470 (mapcar (lambda (w) (substring w 0 -1))
471 (list org-scheduled-string org-deadline-string
472 org-clock-string org-closed-string))
473 "List of time keywords.")
475 ;;;; Drawer
477 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
478 "Matches first or last line of a hidden block.
479 Group 1 contains drawer's name or \"END\".")
481 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
482 "Regular expression matching the first line of a property drawer.")
484 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
485 "Regular expression matching the last line of a property drawer.")
487 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
488 "Regular expression matching the first line of a clock drawer.")
490 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
491 "Regular expression matching the last line of a clock drawer.")
493 (defconst org-property-drawer-re
494 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
495 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
496 "[ \t]*:END:[ \t]*$")
497 "Matches an entire property drawer.")
499 (defconst org-clock-drawer-re
500 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
501 org-clock-drawer-end-re "\\)\n?")
502 "Matches an entire clock drawer.")
504 ;;;; Headline
506 (defconst org-heading-keyword-regexp-format
507 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
508 "Printf format for a regexp matching a headline with some keyword.
509 This regexp will match the headline of any node which has the
510 exact keyword that is put into the format. The keyword isn't in
511 any group by default, but the stars and the body are.")
513 (defconst org-heading-keyword-maybe-regexp-format
514 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
515 "Printf format for a regexp matching a headline, possibly with some keyword.
516 This regexp can match any headline with the specified keyword, or
517 without a keyword. The keyword isn't in any group by default,
518 but the stars and the body are.")
520 (defconst org-archive-tag "ARCHIVE"
521 "The tag that marks a subtree as archived.
522 An archived subtree does not open during visibility cycling, and does
523 not contribute to the agenda listings.")
525 (defconst org-comment-string "COMMENT"
526 "Entries starting with this keyword will never be exported.
527 \\<org-mode-map>
528 An entry can be toggled between COMMENT and normal with
529 `\\[org-toggle-comment]'.")
532 ;;;; LaTeX Environments and Fragments
534 (defconst org-latex-regexps
535 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
536 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
537 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
538 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
539 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
540 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
541 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
542 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
543 "Regular expressions for matching embedded LaTeX.")
545 ;;;; Node Property
547 (defconst org-effort-property "Effort"
548 "The property that is being used to keep track of effort estimates.
549 Effort estimates given in this property need to have the format H:MM.")
551 ;;;; Table
553 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
554 "Detect an org-type or table-type table.")
556 (defconst org-table-line-regexp "^[ \t]*|"
557 "Detect an org-type table line.")
559 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
560 "Detect an org-type table line.")
562 (defconst org-table-hline-regexp "^[ \t]*|-"
563 "Detect an org-type table hline.")
565 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
566 "Detect a table-type table hline.")
568 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
569 "Detect the first line outside a table when searching from within it.
570 This works for both table types.")
572 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
573 "Detect a #+TBLFM line.")
575 ;;;; Timestamp
577 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
578 "Regular expression for fast time stamp matching.")
580 (defconst org-ts-regexp-inactive
581 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
582 "Regular expression for fast inactive time stamp matching.")
584 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
585 "Regular expression for fast time stamp matching.")
587 (defconst org-ts-regexp0
588 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
589 "Regular expression matching time strings for analysis.
590 This one does not require the space after the date, so it can be used
591 on a string that terminates immediately after the date.")
593 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
594 "Regular expression matching time strings for analysis.")
596 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
597 "Regular expression matching time stamps, with groups.")
599 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
600 "Regular expression matching time stamps (also [..]), with groups.")
602 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
603 "Regular expression matching a time stamp range.")
605 (defconst org-tr-regexp-both
606 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
607 "Regular expression matching a time stamp range.")
609 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
610 org-ts-regexp "\\)?")
611 "Regular expression matching a time stamp or time stamp range.")
613 (defconst org-tsr-regexp-both
614 (concat org-ts-regexp-both "\\(--?-?"
615 org-ts-regexp-both "\\)?")
616 "Regular expression matching a time stamp or time stamp range.
617 The time stamps may be either active or inactive.")
619 (defconst org-repeat-re
620 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
621 "Regular expression for specifying repeated events.
622 After a match, group 1 contains the repeat expression.")
624 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
625 "Formats for `format-time-string' which are used for time stamps.")
628 ;;; The custom variables
630 (defgroup org nil
631 "Outline-based notes management and organizer."
632 :tag "Org"
633 :group 'outlines
634 :group 'calendar)
636 (defcustom org-mode-hook nil
637 "Mode hook for Org mode, run after the mode was turned on."
638 :group 'org
639 :type 'hook)
641 (defcustom org-load-hook nil
642 "Hook that is run after org.el has been loaded."
643 :group 'org
644 :type 'hook)
646 (defcustom org-log-buffer-setup-hook nil
647 "Hook that is run after an Org log buffer is created."
648 :group 'org
649 :version "24.1"
650 :type 'hook)
652 (defvar org-modules) ; defined below
653 (defvar org-modules-loaded nil
654 "Have the modules been loaded already?")
656 (defun org-load-modules-maybe (&optional force)
657 "Load all extensions listed in `org-modules'."
658 (when (or force (not org-modules-loaded))
659 (dolist (ext org-modules)
660 (condition-case nil (require ext)
661 (error (message "Problems while trying to load feature `%s'" ext))))
662 (setq org-modules-loaded t)))
664 (defun org-set-modules (var value)
665 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
666 (set var value)
667 (when (featurep 'org)
668 (org-load-modules-maybe 'force)
669 (org-element-cache-reset 'all)))
671 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
672 "Modules that should always be loaded together with org.el.
674 If a description starts with <C>, the file is not part of Emacs
675 and loading it will require that you have downloaded and properly
676 installed the Org mode distribution.
678 You can also use this system to load external packages (i.e. neither Org
679 core modules, nor modules from the CONTRIB directory). Just add symbols
680 to the end of the list. If the package is called org-xyz.el, then you need
681 to add the symbol `xyz', and the package must have a call to:
683 (provide \\='org-xyz)
685 For export specific modules, see also `org-export-backends'."
686 :group 'org
687 :set 'org-set-modules
688 :version "24.4"
689 :package-version '(Org . "8.0")
690 :type
691 '(set :greedy t
692 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
693 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
694 (const :tag " crypt: Encryption of subtrees" org-crypt)
695 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
696 (const :tag " docview: Links to doc-view buffers" org-docview)
697 (const :tag " eww: Store link to url of eww" org-eww)
698 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
699 (const :tag " habit: Track your consistency with habits" org-habit)
700 (const :tag " id: Global IDs for identifying entries" org-id)
701 (const :tag " info: Links to Info nodes" org-info)
702 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
703 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
704 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
705 (const :tag " mouse: Additional mouse support" org-mouse)
706 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
707 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
708 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
710 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
711 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
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.
926 This can also be configured on a per-file basis by adding one of
927 the following lines anywhere in the buffer:
929 #+STARTUP: fold (or `overview', this is equivalent)
930 #+STARTUP: nofold (or `showall', this is equivalent)
931 #+STARTUP: content
932 #+STARTUP: showeverything
934 Set `org-agenda-inhibit-startup' to a non-nil value if you want
935 to ignore this option when Org opens agenda files for the first
936 time."
937 :group 'org-startup
938 :type '(choice
939 (const :tag "nofold: show all" nil)
940 (const :tag "fold: overview" t)
941 (const :tag "content: all headlines" content)
942 (const :tag "show everything, even drawers" showeverything)))
944 (defcustom org-startup-truncated t
945 "Non-nil means entering Org mode will set `truncate-lines'.
946 This is useful since some lines containing links can be very long and
947 uninteresting. Also tables look terrible when wrapped.
949 The variable `org-startup-truncated' allows to configure
950 truncation for Org mode different to the other modes that use the
951 variable `truncate-lines' and as a shortcut instead of putting
952 the variable `truncate-lines' into the `org-mode-hook'. If one
953 wants to configure truncation for Org mode not statically but
954 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
955 the variable `truncate-lines' has to be used because in such a
956 case it is too late to set the variable `org-startup-truncated'."
957 :group 'org-startup
958 :type 'boolean)
960 (defcustom org-startup-indented nil
961 "Non-nil means turn on `org-indent-mode' on startup.
962 This can also be configured on a per-file basis by adding one of
963 the following lines anywhere in the buffer:
965 #+STARTUP: indent
966 #+STARTUP: noindent"
967 :group 'org-structure
968 :type '(choice
969 (const :tag "Not" nil)
970 (const :tag "Globally (slow on startup in large files)" t)))
972 (defcustom org-use-sub-superscripts t
973 "Non-nil means interpret \"_\" and \"^\" for display.
975 If you want to control how Org exports those characters, see
976 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
977 used to be an alias for `org-export-with-sub-superscripts' in
978 Org <8.0, it is not anymore.
980 When this option is turned on, you can use TeX-like syntax for
981 sub- and superscripts within the buffer. Several characters after
982 \"_\" or \"^\" will be considered as a single item - so grouping
983 with {} is normally not needed. For example, the following things
984 will be parsed as single sub- or superscripts:
986 10^24 or 10^tau several digits will be considered 1 item.
987 10^-12 or 10^-tau a leading sign with digits or a word
988 x^2-y^3 will be read as x^2 - y^3, because items are
989 terminated by almost any nonword/nondigit char.
990 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
992 Still, ambiguity is possible. So when in doubt, use {} to enclose
993 the sub/superscript. If you set this variable to the symbol `{}',
994 the braces are *required* in order to trigger interpretations as
995 sub/superscript. This can be helpful in documents that need \"_\"
996 frequently in plain text."
997 :group 'org-startup
998 :version "24.4"
999 :package-version '(Org . "8.0")
1000 :type '(choice
1001 (const :tag "Always interpret" t)
1002 (const :tag "Only with braces" {})
1003 (const :tag "Never interpret" nil)))
1005 (defcustom org-startup-with-beamer-mode nil
1006 "Non-nil means turn on `org-beamer-mode' on startup.
1007 This can also be configured on a per-file basis by adding one of
1008 the following lines anywhere in the buffer:
1010 #+STARTUP: beamer"
1011 :group 'org-startup
1012 :version "24.1"
1013 :type 'boolean)
1015 (defcustom org-startup-align-all-tables nil
1016 "Non-nil means align all tables when visiting a file.
1017 This is useful when the column width in tables is forced with <N> cookies
1018 in table fields. Such tables will look correct only after the first re-align.
1019 This can also be configured on a per-file basis by adding one of
1020 the following lines anywhere in the buffer:
1021 #+STARTUP: align
1022 #+STARTUP: noalign"
1023 :group 'org-startup
1024 :type 'boolean)
1026 (defcustom org-startup-with-inline-images nil
1027 "Non-nil means show inline images when loading a new Org file.
1028 This can also be configured on a per-file basis by adding one of
1029 the following lines anywhere in the buffer:
1030 #+STARTUP: inlineimages
1031 #+STARTUP: noinlineimages"
1032 :group 'org-startup
1033 :version "24.1"
1034 :type 'boolean)
1036 (defcustom org-startup-with-latex-preview nil
1037 "Non-nil means preview LaTeX fragments when loading a new Org file.
1039 This can also be configured on a per-file basis by adding one of
1040 the following lines anywhere in the buffer:
1041 #+STARTUP: latexpreview
1042 #+STARTUP: nolatexpreview"
1043 :group 'org-startup
1044 :version "24.4"
1045 :package-version '(Org . "8.0")
1046 :type 'boolean)
1048 (defcustom org-insert-mode-line-in-empty-file nil
1049 "Non-nil means insert the first line setting Org mode in empty files.
1050 When the function `org-mode' is called interactively in an empty file, this
1051 normally means that the file name does not automatically trigger Org mode.
1052 To ensure that the file will always be in Org mode in the future, a
1053 line enforcing Org mode will be inserted into the buffer, if this option
1054 has been set."
1055 :group 'org-startup
1056 :type 'boolean)
1058 (defcustom org-replace-disputed-keys nil
1059 "Non-nil means use alternative key bindings for some keys.
1060 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1061 These keys are also used by other packages like shift-selection-mode'
1062 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1063 If you want to use Org mode together with one of these other modes,
1064 or more generally if you would like to move some Org mode commands to
1065 other keys, set this variable and configure the keys with the variable
1066 `org-disputed-keys'.
1068 This option is only relevant at load-time of Org mode, and must be set
1069 *before* org.el is loaded. Changing it requires a restart of Emacs to
1070 become effective."
1071 :group 'org-startup
1072 :type 'boolean)
1074 (defcustom org-use-extra-keys nil
1075 "Non-nil means use extra key sequence definitions for certain commands.
1076 This happens automatically if `window-system' is nil. This
1077 variable lets you do the same manually. You must set it before
1078 loading Org."
1079 :group 'org-startup
1080 :type 'boolean)
1082 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1084 (defcustom org-disputed-keys
1085 '(([(shift up)] . [(meta p)])
1086 ([(shift down)] . [(meta n)])
1087 ([(shift left)] . [(meta -)])
1088 ([(shift right)] . [(meta +)])
1089 ([(control shift right)] . [(meta shift +)])
1090 ([(control shift left)] . [(meta shift -)]))
1091 "Keys for which Org mode and other modes compete.
1092 This is an alist, cars are the default keys, second element specifies
1093 the alternative to use when `org-replace-disputed-keys' is t.
1095 Keys can be specified in any syntax supported by `define-key'.
1096 The value of this option takes effect only at Org mode startup,
1097 therefore you'll have to restart Emacs to apply it after changing."
1098 :group 'org-startup
1099 :type 'alist)
1101 (defun org-key (key)
1102 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1103 Or return the original if not disputed."
1104 (when org-replace-disputed-keys
1105 (let* ((nkey (key-description key))
1106 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1107 org-disputed-keys)))
1108 (setq key (if x (cdr x) key))))
1109 key)
1111 (defun org-defkey (keymap key def)
1112 "Define a key, possibly translated, as returned by `org-key'."
1113 (define-key keymap (org-key key) def))
1115 (defcustom org-ellipsis nil
1116 "The ellipsis to use in the Org mode outline.
1118 When nil, just use the standard three dots.
1119 When a string, use that string instead.
1121 The change affects only Org mode (which will then use its own display table).
1122 Changing this requires executing `\\[org-mode]' in a buffer to become
1123 effective."
1124 :group 'org-startup
1125 :type '(choice (const :tag "Default" nil)
1126 (string :tag "String" :value "...#"))
1127 :safe #'string-or-null-p)
1129 (defvar org-display-table nil
1130 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1132 (defgroup org-keywords nil
1133 "Keywords in Org mode."
1134 :tag "Org Keywords"
1135 :group 'org)
1137 (defcustom org-closed-keep-when-no-todo nil
1138 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1139 :group 'org-todo
1140 :group 'org-keywords
1141 :version "24.4"
1142 :package-version '(Org . "8.0")
1143 :type 'boolean)
1145 (defgroup org-structure nil
1146 "Options concerning the general structure of Org files."
1147 :tag "Org Structure"
1148 :group 'org)
1150 (defgroup org-reveal-location nil
1151 "Options about how to make context of a location visible."
1152 :tag "Org Reveal Location"
1153 :group 'org-structure)
1155 (defcustom org-show-context-detail '((agenda . local)
1156 (bookmark-jump . lineage)
1157 (isearch . lineage)
1158 (default . ancestors))
1159 "Alist between context and visibility span when revealing a location.
1161 \\<org-mode-map>Some actions may move point into invisible
1162 locations. As a consequence, Org always expose a neighborhood
1163 around point. How much is shown depends on the initial action,
1164 or context. Valid contexts are
1166 agenda when exposing an entry from the agenda
1167 org-goto when using the command `org-goto' (`\\[org-goto]')
1168 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1169 tags-tree when constructing a sparse tree based on tags matches
1170 link-search when exposing search matches associated with a link
1171 mark-goto when exposing the jump goal of a mark
1172 bookmark-jump when exposing a bookmark location
1173 isearch when exiting from an incremental search
1174 default default for all contexts not set explicitly
1176 Allowed visibility spans are
1178 minimal show current headline; if point is not on headline,
1179 also show entry
1181 local show current headline, entry and next headline
1183 ancestors show current headline and its direct ancestors; if
1184 point is not on headline, also show entry
1186 lineage show current headline, its direct ancestors and all
1187 their children; if point is not on headline, also show
1188 entry and first child
1190 tree show current headline, its direct ancestors and all
1191 their children; if point is not on headline, also show
1192 entry and all children
1194 canonical show current headline, its direct ancestors along with
1195 their entries and children; if point is not located on
1196 the headline, also show current entry and all children
1198 As special cases, a nil or t value means show all contexts in
1199 `minimal' or `canonical' view, respectively.
1201 Some views can make displayed information very compact, but also
1202 make it harder to edit the location of the match. In such
1203 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1204 more context."
1205 :group 'org-reveal-location
1206 :version "25.2"
1207 :package-version '(Org . "9.0")
1208 :type '(choice
1209 (const :tag "Canonical" t)
1210 (const :tag "Minimal" nil)
1211 (repeat :greedy t :tag "Individual contexts"
1212 (cons
1213 (choice :tag "Context"
1214 (const agenda)
1215 (const org-goto)
1216 (const occur-tree)
1217 (const tags-tree)
1218 (const link-search)
1219 (const mark-goto)
1220 (const bookmark-jump)
1221 (const isearch)
1222 (const default))
1223 (choice :tag "Detail level"
1224 (const minimal)
1225 (const local)
1226 (const ancestors)
1227 (const lineage)
1228 (const tree)
1229 (const canonical))))))
1231 (defcustom org-indirect-buffer-display 'other-window
1232 "How should indirect tree buffers be displayed?
1234 This applies to indirect buffers created with the commands
1235 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1237 Valid values are:
1238 current-window Display in the current window
1239 other-window Just display in another window.
1240 dedicated-frame Create one new frame, and re-use it each time.
1241 new-frame Make a new frame each time. Note that in this case
1242 previously-made indirect buffers are kept, and you need to
1243 kill these buffers yourself."
1244 :group 'org-structure
1245 :group 'org-agenda-windows
1246 :type '(choice
1247 (const :tag "In current window" current-window)
1248 (const :tag "In current frame, other window" other-window)
1249 (const :tag "Each time a new frame" new-frame)
1250 (const :tag "One dedicated frame" dedicated-frame)))
1252 (defcustom org-use-speed-commands nil
1253 "Non-nil means activate single letter commands at beginning of a headline.
1254 This may also be a function to test for appropriate locations where speed
1255 commands should be active.
1257 For example, to activate speed commands when the point is on any
1258 star at the beginning of the headline, you can do this:
1260 (setq org-use-speed-commands
1261 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1262 :group 'org-structure
1263 :type '(choice
1264 (const :tag "Never" nil)
1265 (const :tag "At beginning of headline stars" t)
1266 (function)))
1268 (defcustom org-speed-commands-user nil
1269 "Alist of additional speed commands.
1270 This list will be checked before `org-speed-commands-default'
1271 when the variable `org-use-speed-commands' is non-nil
1272 and when the cursor is at the beginning of a headline.
1273 The car if each entry is a string with a single letter, which must
1274 be assigned to `self-insert-command' in the global map.
1275 The cdr is either a command to be called interactively, a function
1276 to be called, or a form to be evaluated.
1277 An entry that is just a list with a single string will be interpreted
1278 as a descriptive headline that will be added when listing the speed
1279 commands in the Help buffer using the `?' speed command."
1280 :group 'org-structure
1281 :type '(repeat :value ("k" . ignore)
1282 (choice :value ("k" . ignore)
1283 (list :tag "Descriptive Headline" (string :tag "Headline"))
1284 (cons :tag "Letter and Command"
1285 (string :tag "Command letter")
1286 (choice
1287 (function)
1288 (sexp))))))
1290 (defcustom org-bookmark-names-plist
1291 '(:last-capture "org-capture-last-stored"
1292 :last-refile "org-refile-last-stored"
1293 :last-capture-marker "org-capture-last-stored-marker")
1294 "Names for bookmarks automatically set by some Org commands.
1295 This can provide strings as names for a number of bookmarks Org sets
1296 automatically. The following keys are currently implemented:
1297 :last-capture
1298 :last-capture-marker
1299 :last-refile
1300 When a key does not show up in the property list, the corresponding bookmark
1301 is not set."
1302 :group 'org-structure
1303 :type 'plist)
1305 (defgroup org-cycle nil
1306 "Options concerning visibility cycling in Org mode."
1307 :tag "Org Cycle"
1308 :group 'org-structure)
1310 (defcustom org-cycle-skip-children-state-if-no-children t
1311 "Non-nil means skip CHILDREN state in entries that don't have any."
1312 :group 'org-cycle
1313 :type 'boolean)
1315 (defcustom org-cycle-max-level nil
1316 "Maximum level which should still be subject to visibility cycling.
1317 Levels higher than this will, for cycling, be treated as text, not a headline.
1318 When `org-odd-levels-only' is set, a value of N in this variable actually
1319 means 2N-1 stars as the limiting headline.
1320 When nil, cycle all levels.
1321 Note that the limiting level of cycling is also influenced by
1322 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1323 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1324 than its value."
1325 :group 'org-cycle
1326 :type '(choice
1327 (const :tag "No limit" nil)
1328 (integer :tag "Maximum level")))
1330 (defcustom org-hide-block-startup nil
1331 "Non-nil means entering Org mode will fold all blocks.
1332 This can also be set in on a per-file basis with
1334 #+STARTUP: hideblocks
1335 #+STARTUP: showblocks"
1336 :group 'org-startup
1337 :group 'org-cycle
1338 :type 'boolean)
1340 (defcustom org-cycle-global-at-bob nil
1341 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1343 This makes it possible to do global cycling without having to use `S-TAB'
1344 or `\\[universal-argument] TAB'. For this special case to work, the first \
1345 line of the buffer
1346 must not be a headline -- it may be empty or some other text.
1348 When used in this way, `org-cycle-hook' is disabled temporarily to make
1349 sure the cursor stays at the beginning of the buffer.
1351 When this option is nil, don't do anything special at the beginning of
1352 the buffer."
1353 :group 'org-cycle
1354 :type 'boolean)
1356 (defcustom org-cycle-level-after-item/entry-creation t
1357 "Non-nil means cycle entry level or item indentation in new empty entries.
1359 When the cursor is at the end of an empty headline, i.e., with only stars
1360 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1361 and then all possible ancestor states, before returning to the original state.
1362 This makes data entry extremely fast: M-RET to create a new headline,
1363 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1365 When the cursor is at the end of an empty plain list item, one TAB will
1366 make it a subitem, two or more tabs will back up to make this an item
1367 higher up in the item hierarchy."
1368 :group 'org-cycle
1369 :type 'boolean)
1371 (defcustom org-cycle-emulate-tab t
1372 "Where should `org-cycle' emulate TAB.
1373 nil Never
1374 white Only in completely white lines
1375 whitestart Only at the beginning of lines, before the first non-white char
1376 t Everywhere except in headlines
1377 exc-hl-bol Everywhere except at the start of a headline
1378 If TAB is used in a place where it does not emulate TAB, the current subtree
1379 visibility is cycled."
1380 :group 'org-cycle
1381 :type '(choice (const :tag "Never" nil)
1382 (const :tag "Only in completely white lines" white)
1383 (const :tag "Before first char in a line" whitestart)
1384 (const :tag "Everywhere except in headlines" t)
1385 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1387 (defcustom org-cycle-separator-lines 2
1388 "Number of empty lines needed to keep an empty line between collapsed trees.
1389 If you leave an empty line between the end of a subtree and the following
1390 headline, this empty line is hidden when the subtree is folded.
1391 Org mode will leave (exactly) one empty line visible if the number of
1392 empty lines is equal or larger to the number given in this variable.
1393 So the default 2 means at least 2 empty lines after the end of a subtree
1394 are needed to produce free space between a collapsed subtree and the
1395 following headline.
1397 If the number is negative, and the number of empty lines is at least -N,
1398 all empty lines are shown.
1400 Special case: when 0, never leave empty lines in collapsed view."
1401 :group 'org-cycle
1402 :type 'integer)
1403 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1405 (defcustom org-pre-cycle-hook nil
1406 "Hook that is run before visibility cycling is happening.
1407 The function(s) in this hook must accept a single argument which indicates
1408 the new state that will be set right after running this hook. The
1409 argument is a symbol. Before a global state change, it can have the values
1410 `overview', `content', or `all'. Before a local state change, it can have
1411 the values `folded', `children', or `subtree'."
1412 :group 'org-cycle
1413 :type 'hook)
1415 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1416 org-cycle-hide-drawers
1417 org-cycle-show-empty-lines
1418 org-optimize-window-after-visibility-change)
1419 "Hook that is run after `org-cycle' has changed the buffer visibility.
1420 The function(s) in this hook must accept a single argument which indicates
1421 the new state that was set by the most recent `org-cycle' command. The
1422 argument is a symbol. After a global state change, it can have the values
1423 `overview', `contents', or `all'. After a local state change, it can have
1424 the values `folded', `children', or `subtree'."
1425 :group 'org-cycle
1426 :type 'hook
1427 :version "25.2"
1428 :package-version '(Org . "8.3"))
1430 (defgroup org-edit-structure nil
1431 "Options concerning structure editing in Org mode."
1432 :tag "Org Edit Structure"
1433 :group 'org-structure)
1435 (defcustom org-odd-levels-only nil
1436 "Non-nil means skip even levels and only use odd levels for the outline.
1437 This has the effect that two stars are being added/taken away in
1438 promotion/demotion commands. It also influences how levels are
1439 handled by the exporters.
1440 Changing it requires restart of `font-lock-mode' to become effective
1441 for fontification also in regions already fontified.
1442 You may also set this on a per-file basis by adding one of the following
1443 lines to the buffer:
1445 #+STARTUP: odd
1446 #+STARTUP: oddeven"
1447 :group 'org-edit-structure
1448 :group 'org-appearance
1449 :type 'boolean)
1451 (defcustom org-adapt-indentation t
1452 "Non-nil means adapt indentation to outline node level.
1454 When this variable is set, Org assumes that you write outlines by
1455 indenting text in each node to align with the headline (after the
1456 stars). The following issues are influenced by this variable:
1458 - The indentation is increased by one space in a demotion
1459 command, and decreased by one in a promotion command. However,
1460 in the latter case, if shifting some line in the entry body
1461 would alter document structure (e.g., insert a new headline),
1462 indentation is not changed at all.
1464 - Property drawers and planning information is inserted indented
1465 when this variable is set. When nil, they will not be indented.
1467 - TAB indents a line relative to current level. The lines below
1468 a headline will be indented when this variable is set.
1470 Note that this is all about true indentation, by adding and
1471 removing space characters. See also `org-indent.el' which does
1472 level-dependent indentation in a virtual way, i.e. at display
1473 time in Emacs."
1474 :group 'org-edit-structure
1475 :type 'boolean)
1477 (defcustom org-special-ctrl-a/e nil
1478 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1480 When t, `C-a' will bring back the cursor to the beginning of the
1481 headline text, i.e. after the stars and after a possible TODO
1482 keyword. In an item, this will be the position after bullet and
1483 check-box, if any. When the cursor is already at that position,
1484 another `C-a' will bring it to the beginning of the line.
1486 `C-e' will jump to the end of the headline, ignoring the presence
1487 of tags in the headline. A second `C-e' will then jump to the
1488 true end of the line, after any tags. This also means that, when
1489 this variable is non-nil, `C-e' also will never jump beyond the
1490 end of the heading of a folded section, i.e. not after the
1491 ellipses.
1493 When set to the symbol `reversed', the first `C-a' or `C-e' works
1494 normally, going to the true line boundary first. Only a directly
1495 following, identical keypress will bring the cursor to the
1496 special positions.
1498 This may also be a cons cell where the behavior for `C-a' and
1499 `C-e' is set separately."
1500 :group 'org-edit-structure
1501 :type '(choice
1502 (const :tag "off" nil)
1503 (const :tag "on: after stars/bullet and before tags first" t)
1504 (const :tag "reversed: true line boundary first" reversed)
1505 (cons :tag "Set C-a and C-e separately"
1506 (choice :tag "Special C-a"
1507 (const :tag "off" nil)
1508 (const :tag "on: after stars/bullet first" t)
1509 (const :tag "reversed: before stars/bullet first" reversed))
1510 (choice :tag "Special C-e"
1511 (const :tag "off" nil)
1512 (const :tag "on: before tags first" t)
1513 (const :tag "reversed: after tags first" reversed)))))
1514 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1516 (defcustom org-special-ctrl-k nil
1517 "Non-nil means `C-k' will behave specially in headlines.
1518 When nil, `C-k' will call the default `kill-line' command.
1519 When t, the following will happen while the cursor is in the headline:
1521 - When the cursor is at the beginning of a headline, kill the entire
1522 line and possible the folded subtree below the line.
1523 - When in the middle of the headline text, kill the headline up to the tags.
1524 - When after the headline text, kill the tags."
1525 :group 'org-edit-structure
1526 :type 'boolean)
1528 (defcustom org-ctrl-k-protect-subtree nil
1529 "Non-nil means, do not delete a hidden subtree with C-k.
1530 When set to the symbol `error', simply throw an error when C-k is
1531 used to kill (part-of) a headline that has hidden text behind it.
1532 Any other non-nil value will result in a query to the user, if it is
1533 OK to kill that hidden subtree. When nil, kill without remorse."
1534 :group 'org-edit-structure
1535 :version "24.1"
1536 :type '(choice
1537 (const :tag "Do not protect hidden subtrees" nil)
1538 (const :tag "Protect hidden subtrees with a security query" t)
1539 (const :tag "Never kill a hidden subtree with C-k" error)))
1541 (defcustom org-special-ctrl-o t
1542 "Non-nil means, make `C-o' insert a row in tables."
1543 :group 'org-edit-structure
1544 :type 'boolean)
1546 (defcustom org-catch-invisible-edits nil
1547 "Check if in invisible region before inserting or deleting a character.
1548 Valid values are:
1550 nil Do not check, so just do invisible edits.
1551 error Throw an error and do nothing.
1552 show Make point visible, and do the requested edit.
1553 show-and-error Make point visible, then throw an error and abort the edit.
1554 smart Make point visible, and do insertion/deletion if it is
1555 adjacent to visible text and the change feels predictable.
1556 Never delete a previously invisible character or add in the
1557 middle or right after an invisible region. Basically, this
1558 allows insertion and backward-delete right before ellipses.
1559 FIXME: maybe in this case we should not even show?"
1560 :group 'org-edit-structure
1561 :version "24.1"
1562 :type '(choice
1563 (const :tag "Do not check" nil)
1564 (const :tag "Throw error when trying to edit" error)
1565 (const :tag "Unhide, but do not do the edit" show-and-error)
1566 (const :tag "Show invisible part and do the edit" show)
1567 (const :tag "Be smart and do the right thing" smart)))
1569 (defcustom org-yank-folded-subtrees t
1570 "Non-nil means when yanking subtrees, fold them.
1571 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1572 it starts with a heading and all other headings in it are either children
1573 or siblings, then fold all the subtrees. However, do this only if no
1574 text after the yank would be swallowed into a folded tree by this action."
1575 :group 'org-edit-structure
1576 :type 'boolean)
1578 (defcustom org-yank-adjusted-subtrees nil
1579 "Non-nil means when yanking subtrees, adjust the level.
1580 With this setting, `org-paste-subtree' is used to insert the subtree, see
1581 this function for details."
1582 :group 'org-edit-structure
1583 :type 'boolean)
1585 (defcustom org-M-RET-may-split-line '((default . t))
1586 "Non-nil means M-RET will split the line at the cursor position.
1587 When nil, it will go to the end of the line before making a
1588 new line.
1589 You may also set this option in a different way for different
1590 contexts. Valid contexts are:
1592 headline when creating a new headline
1593 item when creating a new item
1594 table in a table field
1595 default the value to be used for all contexts not explicitly
1596 customized"
1597 :group 'org-structure
1598 :group 'org-table
1599 :type '(choice
1600 (const :tag "Always" t)
1601 (const :tag "Never" nil)
1602 (repeat :greedy t :tag "Individual contexts"
1603 (cons
1604 (choice :tag "Context"
1605 (const headline)
1606 (const item)
1607 (const table)
1608 (const default))
1609 (boolean)))))
1612 (defcustom org-insert-heading-respect-content nil
1613 "Non-nil means insert new headings after the current subtree.
1614 \\<org-mode-map>
1615 When nil, the new heading is created directly after the current line.
1616 The commands `\\[org-insert-heading-respect-content]' and \
1617 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1618 for the duration of the command."
1619 :group 'org-structure
1620 :type 'boolean)
1622 (defcustom org-blank-before-new-entry '((heading . auto)
1623 (plain-list-item . auto))
1624 "Should `org-insert-heading' leave a blank line before new heading/item?
1625 The value is an alist, with `heading' and `plain-list-item' as CAR,
1626 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1627 which case Org will look at the surrounding headings/items and try to
1628 make an intelligent decision whether to insert a blank line or not."
1629 :group 'org-edit-structure
1630 :type '(list
1631 (cons (const heading)
1632 (choice (const :tag "Never" nil)
1633 (const :tag "Always" t)
1634 (const :tag "Auto" auto)))
1635 (cons (const plain-list-item)
1636 (choice (const :tag "Never" nil)
1637 (const :tag "Always" t)
1638 (const :tag "Auto" auto)))))
1640 (defcustom org-insert-heading-hook nil
1641 "Hook being run after inserting a new heading."
1642 :group 'org-edit-structure
1643 :type 'hook)
1645 (defcustom org-enable-fixed-width-editor t
1646 "Non-nil means lines starting with \":\" are treated as fixed-width.
1647 This currently only means they are never auto-wrapped.
1648 When nil, such lines will be treated like ordinary lines."
1649 :group 'org-edit-structure
1650 :type 'boolean)
1652 (defcustom org-goto-auto-isearch t
1653 "Non-nil means typing characters in `org-goto' starts incremental search.
1654 When nil, you can use these keybindings to navigate the buffer:
1656 q Quit the org-goto interface
1657 n Go to the next visible heading
1658 p Go to the previous visible heading
1659 f Go one heading forward on same level
1660 b Go one heading backward on same level
1661 u Go one heading up"
1662 :group 'org-edit-structure
1663 :type 'boolean)
1665 (defgroup org-sparse-trees nil
1666 "Options concerning sparse trees in Org mode."
1667 :tag "Org Sparse Trees"
1668 :group 'org-structure)
1670 (defcustom org-highlight-sparse-tree-matches t
1671 "Non-nil means highlight all matches that define a sparse tree.
1672 The highlights will automatically disappear the next time the buffer is
1673 changed by an edit command."
1674 :group 'org-sparse-trees
1675 :type 'boolean)
1677 (defcustom org-remove-highlights-with-change t
1678 "Non-nil means any change to the buffer will remove temporary highlights.
1679 \\<org-mode-map>\
1680 Such highlights are created by `org-occur' and `org-clock-display'.
1681 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1682 to get rid of the highlights.
1683 The highlights created by `org-toggle-latex-fragment' always need
1684 `\\[org-toggle-latex-fragment]' to be removed."
1685 :group 'org-sparse-trees
1686 :group 'org-time
1687 :type 'boolean)
1689 (defcustom org-occur-case-fold-search t
1690 "Non-nil means `org-occur' should be case-insensitive.
1691 If set to `smart' the search will be case-insensitive only if it
1692 doesn't specify any upper case character."
1693 :group 'org-sparse-trees
1694 :version "25.2"
1695 :type '(choice
1696 (const :tag "Case-sensitive" nil)
1697 (const :tag "Case-insensitive" t)
1698 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1700 (defcustom org-occur-hook '(org-first-headline-recenter)
1701 "Hook that is run after `org-occur' has constructed a sparse tree.
1702 This can be used to recenter the window to show as much of the structure
1703 as possible."
1704 :group 'org-sparse-trees
1705 :type 'hook)
1707 (defgroup org-imenu-and-speedbar nil
1708 "Options concerning imenu and speedbar in Org mode."
1709 :tag "Org Imenu and Speedbar"
1710 :group 'org-structure)
1712 (defcustom org-imenu-depth 2
1713 "The maximum level for Imenu access to Org headlines.
1714 This also applied for speedbar access."
1715 :group 'org-imenu-and-speedbar
1716 :type 'integer)
1718 (defgroup org-table nil
1719 "Options concerning tables in Org mode."
1720 :tag "Org Table"
1721 :group 'org)
1723 (defcustom org-enable-table-editor 'optimized
1724 "Non-nil means lines starting with \"|\" are handled by the table editor.
1725 When nil, such lines will be treated like ordinary lines.
1727 When equal to the symbol `optimized', the table editor will be optimized to
1728 do the following:
1729 - Automatic overwrite mode in front of whitespace in table fields.
1730 This makes the structure of the table stay in tact as long as the edited
1731 field does not exceed the column width.
1732 - Minimize the number of realigns. Normally, the table is aligned each time
1733 TAB or RET are pressed to move to another field. With optimization this
1734 happens only if changes to a field might have changed the column width.
1735 Optimization requires replacing the functions `self-insert-command',
1736 `delete-char', and `backward-delete-char' in Org buffers, with a
1737 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1738 good at guessing when a re-align will be necessary, but you can always
1739 force one with `\\[org-ctrl-c-ctrl-c]'.
1741 If you would like to use the optimized version in Org mode, but the
1742 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1744 This variable can be used to turn on and off the table editor during a session,
1745 but in order to toggle optimization, a restart is required.
1747 See also the variable `org-table-auto-blank-field'."
1748 :group 'org-table
1749 :type '(choice
1750 (const :tag "off" nil)
1751 (const :tag "on" t)
1752 (const :tag "on, optimized" optimized)))
1754 (defcustom org-self-insert-cluster-for-undo nil
1755 "Non-nil means cluster self-insert commands for undo when possible.
1756 If this is set, then, like in the Emacs command loop, 20 consecutive
1757 characters will be undone together.
1758 This is configurable, because there is some impact on typing performance."
1759 :group 'org-table
1760 :type 'boolean)
1762 (defcustom org-table-tab-recognizes-table.el t
1763 "Non-nil means TAB will automatically notice a table.el table.
1764 When it sees such a table, it moves point into it and - if necessary -
1765 calls `table-recognize-table'."
1766 :group 'org-table-editing
1767 :type 'boolean)
1769 (defgroup org-link nil
1770 "Options concerning links in Org mode."
1771 :tag "Org Link"
1772 :group 'org)
1774 (defvar-local org-link-abbrev-alist-local nil
1775 "Buffer-local version of `org-link-abbrev-alist', which see.
1776 The value of this is taken from the #+LINK lines.")
1778 (defcustom org-link-parameters
1779 '(("doi" :follow org--open-doi-link)
1780 ("elisp" :follow org--open-elisp-link)
1781 ("file" :complete org-file-complete-link)
1782 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1783 ("help" :follow org--open-help-link)
1784 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1785 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1786 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1787 ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
1788 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1789 ("shell" :follow org--open-shell-link))
1790 "An alist of properties that defines all the links in Org mode.
1791 The key in each association is a string of the link type.
1792 Subsequent optional elements make up a p-list of link properties.
1794 :follow - A function that takes the link path as an argument.
1796 :export - A function that takes the link path, description and
1797 export-backend as arguments.
1799 :store - A function responsible for storing the link. See the
1800 function `org-store-link-functions'.
1802 :complete - A function that inserts a link with completion. The
1803 function takes one optional prefix arg.
1805 :face - A face for the link, or a function that returns a face.
1806 The function takes one argument which is the link path. The
1807 default face is `org-link'.
1809 :mouse-face - The mouse-face. The default is `highlight'.
1811 :display - `full' will not fold the link in descriptive
1812 display. Default is `org-link'.
1814 :help-echo - A string or function that takes (window object position)
1815 as arguments and returns a string.
1817 :keymap - A keymap that is active on the link. The default is
1818 `org-mouse-map'.
1820 :htmlize-link - A function for the htmlize-link. Defaults
1821 to (list :uri \"type:path\")
1823 :activate-func - A function to run at the end of font-lock
1824 activation. The function must accept (link-start link-end path bracketp)
1825 as arguments."
1826 :group 'org-link
1827 :type '(alist :tag "Link display parameters"
1828 :value-type plist))
1830 (defun org-link-get-parameter (type key)
1831 "Get TYPE link property for KEY.
1832 TYPE is a string and KEY is a plist keyword."
1833 (plist-get
1834 (cdr (assoc type org-link-parameters))
1835 key))
1837 (defun org-link-set-parameters (type &rest parameters)
1838 "Set link TYPE properties to PARAMETERS.
1839 PARAMETERS should be :key val pairs."
1840 (let ((data (assoc type org-link-parameters)))
1841 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1842 (push (cons type parameters) org-link-parameters)
1843 (org-make-link-regexps)
1844 (org-element-update-syntax))))
1846 (defun org-link-types ()
1847 "Return a list of known link types."
1848 (mapcar #'car org-link-parameters))
1850 (defcustom org-link-abbrev-alist nil
1851 "Alist of link abbreviations.
1852 The car of each element is a string, to be replaced at the start of a link.
1853 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1854 links in Org buffers can have an optional tag after a double colon, e.g.,
1856 [[linkkey:tag][description]]
1858 The `linkkey' must be a single word, starting with a letter, followed
1859 by letters, numbers, `-' or `_'.
1861 If REPLACE is a string, the tag will simply be appended to create the link.
1862 If the string contains \"%s\", the tag will be inserted there. If the string
1863 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1864 at that point (see the function `url-hexify-string'). If the string contains
1865 the specifier \"%(my-function)\", then the custom function `my-function' will
1866 be invoked: this function takes the tag as its only argument and must return
1867 a string.
1869 REPLACE may also be a function that will be called with the tag as the
1870 only argument to create the link, which should be returned as a string.
1872 See the manual for examples."
1873 :group 'org-link
1874 :type '(repeat
1875 (cons
1876 (string :tag "Protocol")
1877 (choice
1878 (string :tag "Format")
1879 (function)))))
1881 (defcustom org-descriptive-links t
1882 "Non-nil means Org will display descriptive links.
1883 E.g. [[http://orgmode.org][Org website]] will be displayed as
1884 \"Org Website\", hiding the link itself and just displaying its
1885 description. When set to nil, Org will display the full links
1886 literally.
1888 You can interactively set the value of this variable by calling
1889 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1890 :group 'org-link
1891 :type 'boolean)
1893 (defcustom org-link-file-path-type 'adaptive
1894 "How the path name in file links should be stored.
1895 Valid values are:
1897 relative Relative to the current directory, i.e. the directory of the file
1898 into which the link is being inserted.
1899 absolute Absolute path, if possible with ~ for home directory.
1900 noabbrev Absolute path, no abbreviation of home directory.
1901 adaptive Use relative path for files in the current directory and sub-
1902 directories of it. For other files, use an absolute path."
1903 :group 'org-link
1904 :type '(choice
1905 (const relative)
1906 (const absolute)
1907 (const noabbrev)
1908 (const adaptive)))
1910 (defvaralias 'org-activate-links 'org-highlight-links)
1911 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1912 "Types of links that should be highlighted in Org files.
1914 This is a list of symbols, each one of them leading to the
1915 highlighting of a certain link type.
1917 You can still open links that are not highlighted.
1919 In principle, it does not hurt to turn on highlighting for all
1920 link types. There may be a small gain when turning off unused
1921 link types. The types are:
1923 bracket The recommended [[link][description]] or [[link]] links with hiding.
1924 angle Links in angular brackets that may contain whitespace like
1925 <bbdb:Carsten Dominik>.
1926 plain Plain links in normal text, no whitespace, like http://google.com.
1927 radio Text that is matched by a radio target, see manual for details.
1928 tag Tag settings in a headline (link to tag search).
1929 date Time stamps (link to calendar).
1930 footnote Footnote labels.
1932 If you set this variable during an Emacs session, use `org-mode-restart'
1933 in the Org buffer so that the change takes effect."
1934 :group 'org-link
1935 :group 'org-appearance
1936 :type '(set :greedy t
1937 (const :tag "Double bracket links" bracket)
1938 (const :tag "Angular bracket links" angle)
1939 (const :tag "Plain text links" plain)
1940 (const :tag "Radio target matches" radio)
1941 (const :tag "Tags" tag)
1942 (const :tag "Timestamps" date)
1943 (const :tag "Footnotes" footnote)))
1945 (defcustom org-make-link-description-function nil
1946 "Function to use for generating link descriptions from links.
1947 When nil, the link location will be used. This function must take
1948 two parameters: the first one is the link, the second one is the
1949 description generated by `org-insert-link'. The function should
1950 return the description to use."
1951 :group 'org-link
1952 :type '(choice (const nil) (function)))
1954 (defgroup org-link-store nil
1955 "Options concerning storing links in Org mode."
1956 :tag "Org Store Link"
1957 :group 'org-link)
1959 (defcustom org-url-hexify-p t
1960 "When non-nil, hexify URL when creating a link."
1961 :type 'boolean
1962 :version "24.3"
1963 :group 'org-link-store)
1965 (defcustom org-email-link-description-format "Email %c: %.30s"
1966 "Format of the description part of a link to an email or usenet message.
1967 The following %-escapes will be replaced by corresponding information:
1969 %F full \"From\" field
1970 %f name, taken from \"From\" field, address if no name
1971 %T full \"To\" field
1972 %t first name in \"To\" field, address if no name
1973 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1974 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1975 %s subject
1976 %d date
1977 %m message-id.
1979 You may use normal field width specification between the % and the letter.
1980 This is for example useful to limit the length of the subject.
1982 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1983 :group 'org-link-store
1984 :type 'string)
1986 (defcustom org-from-is-user-regexp
1987 (let (r1 r2)
1988 (when (and user-mail-address (not (string= user-mail-address "")))
1989 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1990 (when (and user-full-name (not (string= user-full-name "")))
1991 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1992 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1993 "Regexp matched against the \"From:\" header of an email or usenet message.
1994 It should match if the message is from the user him/herself."
1995 :group 'org-link-store
1996 :type 'regexp)
1998 (defcustom org-context-in-file-links t
1999 "Non-nil means file links from `org-store-link' contain context.
2000 \\<org-mode-map>
2001 A search string will be added to the file name with :: as separator
2002 and used to find the context when the link is activated by the command
2003 `org-open-at-point'. When this option is t, the entire active region
2004 will be placed in the search string of the file link. If set to a
2005 positive integer, only the first n lines of context will be stored.
2007 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2008 \\[org-store-link]')
2009 negates this setting for the duration of the command."
2010 :group 'org-link-store
2011 :type '(choice boolean integer))
2013 (defcustom org-keep-stored-link-after-insertion nil
2014 "Non-nil means keep link in list for entire session.
2015 \\<org-mode-map>
2016 The command `org-store-link' adds a link pointing to the current
2017 location to an internal list. These links accumulate during a session.
2018 The command `org-insert-link' can be used to insert links into any
2019 Org file (offering completion for all stored links).
2021 When this option is nil, every link which has been inserted once using
2022 `\\[org-insert-link]' will be removed from the list, to make completing the \
2023 unused
2024 links more efficient."
2025 :group 'org-link-store
2026 :type 'boolean)
2028 (defgroup org-link-follow nil
2029 "Options concerning following links in Org mode."
2030 :tag "Org Follow Link"
2031 :group 'org-link)
2033 (defcustom org-link-translation-function nil
2034 "Function to translate links with different syntax to Org syntax.
2035 This can be used to translate links created for example by the Planner
2036 or emacs-wiki packages to Org syntax.
2037 The function must accept two parameters, a TYPE containing the link
2038 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2039 which is everything after the link protocol. It should return a cons
2040 with possibly modified values of type and path.
2041 Org contains a function for this, so if you set this variable to
2042 `org-translate-link-from-planner', you should be able follow many
2043 links created by planner."
2044 :group 'org-link-follow
2045 :type '(choice (const nil) (function)))
2047 (defcustom org-follow-link-hook nil
2048 "Hook that is run after a link has been followed."
2049 :group 'org-link-follow
2050 :type 'hook)
2052 (defcustom org-tab-follows-link nil
2053 "Non-nil means on links TAB will follow the link.
2054 Needs to be set before org.el is loaded.
2055 This really should not be used, it does not make sense, and the
2056 implementation is bad."
2057 :group 'org-link-follow
2058 :type 'boolean)
2060 (defcustom org-return-follows-link nil
2061 "Non-nil means on links RET will follow the link.
2062 In tables, the special behavior of RET has precedence."
2063 :group 'org-link-follow
2064 :type 'boolean)
2066 (defcustom org-mouse-1-follows-link
2067 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2068 "Non-nil means mouse-1 on a link will follow the link.
2069 A longer mouse click will still set point. Needs to be set
2070 before org.el is loaded."
2071 :group 'org-link-follow
2072 :version "24.4"
2073 :package-version '(Org . "8.3")
2074 :type '(choice
2075 (const :tag "A double click follows the link" double)
2076 (const :tag "Unconditionally follow the link with mouse-1" t)
2077 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2079 (defcustom org-mark-ring-length 4
2080 "Number of different positions to be recorded in the ring.
2081 Changing this requires a restart of Emacs to work correctly."
2082 :group 'org-link-follow
2083 :type 'integer)
2085 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2086 "Non-nil means internal fuzzy links can only match headlines.
2088 When nil, the a fuzzy link may point to a target or a named
2089 construct in the document. When set to the special value
2090 `query-to-create', offer to create a new headline when none
2091 matched.
2093 Spaces and statistics cookies are ignored during heading searches."
2094 :group 'org-link-follow
2095 :version "24.1"
2096 :type '(choice
2097 (const :tag "Use fuzzy text search" nil)
2098 (const :tag "Match only exact headline" t)
2099 (const :tag "Match exact headline or query to create it"
2100 query-to-create))
2101 :safe #'symbolp)
2103 (defcustom org-link-frame-setup
2104 '((vm . vm-visit-folder-other-frame)
2105 (vm-imap . vm-visit-imap-folder-other-frame)
2106 (gnus . org-gnus-no-new-news)
2107 (file . find-file-other-window)
2108 (wl . wl-other-frame))
2109 "Setup the frame configuration for following links.
2110 When following a link with Emacs, it may often be useful to display
2111 this link in another window or frame. This variable can be used to
2112 set this up for the different types of links.
2113 For VM, use any of
2114 `vm-visit-folder'
2115 `vm-visit-folder-other-window'
2116 `vm-visit-folder-other-frame'
2117 For Gnus, use any of
2118 `gnus'
2119 `gnus-other-frame'
2120 `org-gnus-no-new-news'
2121 For FILE, use any of
2122 `find-file'
2123 `find-file-other-window'
2124 `find-file-other-frame'
2125 For Wanderlust use any of
2126 `wl'
2127 `wl-other-frame'
2128 For the calendar, use the variable `calendar-setup'.
2129 For BBDB, it is currently only possible to display the matches in
2130 another window."
2131 :group 'org-link-follow
2132 :type '(list
2133 (cons (const vm)
2134 (choice
2135 (const vm-visit-folder)
2136 (const vm-visit-folder-other-window)
2137 (const vm-visit-folder-other-frame)))
2138 (cons (const vm-imap)
2139 (choice
2140 (const vm-visit-imap-folder)
2141 (const vm-visit-imap-folder-other-window)
2142 (const vm-visit-imap-folder-other-frame)))
2143 (cons (const gnus)
2144 (choice
2145 (const gnus)
2146 (const gnus-other-frame)
2147 (const org-gnus-no-new-news)))
2148 (cons (const file)
2149 (choice
2150 (const find-file)
2151 (const find-file-other-window)
2152 (const find-file-other-frame)))
2153 (cons (const wl)
2154 (choice
2155 (const wl)
2156 (const wl-other-frame)))))
2158 (defcustom org-display-internal-link-with-indirect-buffer nil
2159 "Non-nil means use indirect buffer to display infile links.
2160 Activating internal links (from one location in a file to another location
2161 in the same file) normally just jumps to the location. When the link is
2162 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2163 is displayed in
2164 another window. When this option is set, the other window actually displays
2165 an indirect buffer clone of the current buffer, to avoid any visibility
2166 changes to the current buffer."
2167 :group 'org-link-follow
2168 :type 'boolean)
2170 (defcustom org-open-non-existing-files nil
2171 "Non-nil means `org-open-file' will open non-existing files.
2172 When nil, an error will be generated.
2173 This variable applies only to external applications because they
2174 might choke on non-existing files. If the link is to a file that
2175 will be opened in Emacs, the variable is ignored."
2176 :group 'org-link-follow
2177 :type 'boolean)
2179 (defcustom org-open-directory-means-index-dot-org nil
2180 "Non-nil means a link to a directory really means to index.org.
2181 When nil, following a directory link will run dired or open a finder/explorer
2182 window on that directory."
2183 :group 'org-link-follow
2184 :type 'boolean)
2186 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2187 "Non-nil means ask for confirmation before executing shell links.
2188 Shell links can be dangerous: just think about a link
2190 [[shell:rm -rf ~/*][Google Search]]
2192 This link would show up in your Org document as \"Google Search\",
2193 but really it would remove your entire home directory.
2194 Therefore we advise against setting this variable to nil.
2195 Just change it to `y-or-n-p' if you want to confirm with a
2196 single keystroke rather than having to type \"yes\"."
2197 :group 'org-link-follow
2198 :type '(choice
2199 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2200 (const :tag "with y-or-n (faster)" y-or-n-p)
2201 (const :tag "no confirmation (dangerous)" nil)))
2202 (put 'org-confirm-shell-link-function
2203 'safe-local-variable
2204 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2206 (defcustom org-confirm-shell-link-not-regexp ""
2207 "A regexp to skip confirmation for shell links."
2208 :group 'org-link-follow
2209 :version "24.1"
2210 :type 'regexp)
2212 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2213 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2214 Elisp links can be dangerous: just think about a link
2216 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2218 This link would show up in your Org document as \"Google Search\",
2219 but really it would remove your entire home directory.
2220 Therefore we advise against setting this variable to nil.
2221 Just change it to `y-or-n-p' if you want to confirm with a
2222 single keystroke rather than having to type \"yes\"."
2223 :group 'org-link-follow
2224 :type '(choice
2225 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2226 (const :tag "with y-or-n (faster)" y-or-n-p)
2227 (const :tag "no confirmation (dangerous)" nil)))
2228 (put 'org-confirm-shell-link-function
2229 'safe-local-variable
2230 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2232 (defcustom org-confirm-elisp-link-not-regexp ""
2233 "A regexp to skip confirmation for Elisp links."
2234 :group 'org-link-follow
2235 :version "24.1"
2236 :type 'regexp)
2238 (defconst org-file-apps-defaults-gnu
2239 '((remote . emacs)
2240 (system . mailcap)
2241 (t . mailcap))
2242 "Default file applications on a UNIX or GNU/Linux system.
2243 See `org-file-apps'.")
2245 (defconst org-file-apps-defaults-macosx
2246 '((remote . emacs)
2247 (system . "open %s")
2248 ("ps.gz" . "gv %s")
2249 ("eps.gz" . "gv %s")
2250 ("dvi" . "xdvi %s")
2251 ("fig" . "xfig %s")
2252 (t . "open %s"))
2253 "Default file applications on a macOS system.
2254 The system \"open\" is known as a default, but we use X11 applications
2255 for some files for which the OS does not have a good default.
2256 See `org-file-apps'.")
2258 (defconst org-file-apps-defaults-windowsnt
2259 (list '(remote . emacs)
2260 (cons 'system (lambda (file _path)
2261 (with-no-warnings (w32-shell-execute "open" file))))
2262 (cons t (lambda (file _path)
2263 (with-no-warnings (w32-shell-execute "open" file)))))
2264 "Default file applications on a Windows NT system.
2265 The system \"open\" is used for most files.
2266 See `org-file-apps'.")
2268 (defcustom org-file-apps
2269 '((auto-mode . emacs)
2270 ("\\.mm\\'" . default)
2271 ("\\.x?html?\\'" . default)
2272 ("\\.pdf\\'" . default))
2273 "External applications for opening `file:path' items in a document.
2274 \\<org-mode-map>\
2276 Org mode uses system defaults for different file types, but
2277 you can use this variable to set the application for a given file
2278 extension. The entries in this list are cons cells where the car identifies
2279 files and the cdr the corresponding command.
2281 Possible values for the file identifier are:
2283 \"string\" A string as a file identifier can be interpreted in different
2284 ways, depending on its contents:
2286 - Alphanumeric characters only:
2287 Match links with this file extension.
2288 Example: (\"pdf\" . \"evince %s\")
2289 to open PDFs with evince.
2291 - Regular expression: Match links where the
2292 filename matches the regexp. If you want to
2293 use groups here, use shy groups.
2295 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2296 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2297 to open *.html and *.xhtml with firefox.
2299 - Regular expression which contains (non-shy) groups:
2300 Match links where the whole link, including \"::\", and
2301 anything after that, matches the regexp.
2302 In a custom command string, %1, %2, etc. are replaced with
2303 the parts of the link that were matched by the groups.
2304 For backwards compatibility, if a command string is given
2305 that does not use any of the group matches, this case is
2306 handled identically to the second one (i.e. match against
2307 file name only).
2308 In a custom function, you can access the group matches with
2309 (match-string n link).
2311 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2312 \"evince -p %1 %s\")
2313 to open [[file:document.pdf::5]] with evince at page 5.
2315 `directory' Matches a directory
2316 `remote' Matches a remote file, accessible through tramp or efs.
2317 Remote files most likely should be visited through Emacs
2318 because external applications cannot handle such paths.
2319 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2320 so all files Emacs knows how to handle. Using this with
2321 command `emacs' will open most files in Emacs. Beware that this
2322 will also open html files inside Emacs, unless you add
2323 (\"html\" . default) to the list as well.
2324 `system' The system command to open files, like `open' on Windows
2325 and macOS, and mailcap under GNU/Linux. This is the command
2326 that will be selected if you call `org-open-at-point' with a
2327 double prefix argument (`\\[universal-argument] \
2328 \\[universal-argument] \\[org-open-at-point]').
2329 t Default for files not matched by any of the other options.
2331 Possible values for the command are:
2333 `emacs' The file will be visited by the current Emacs process.
2334 `default' Use the default application for this file type, which is the
2335 association for t in the list, most likely in the system-specific
2336 part. This can be used to overrule an unwanted setting in the
2337 system-specific variable.
2338 `system' Use the system command for opening files, like \"open\".
2339 This command is specified by the entry whose car is `system'.
2340 Most likely, the system-specific version of this variable
2341 does define this command, but you can overrule/replace it
2342 here.
2343 `mailcap' Use command specified in the mailcaps.
2344 string A command to be executed by a shell; %s will be replaced
2345 by the path to the file.
2346 function A Lisp function, which will be called with two arguments:
2347 the file path and the original link string, without the
2348 \"file:\" prefix.
2350 For more examples, see the system specific constants
2351 `org-file-apps-defaults-macosx'
2352 `org-file-apps-defaults-windowsnt'
2353 `org-file-apps-defaults-gnu'."
2354 :group 'org-link-follow
2355 :type '(repeat
2356 (cons (choice :value ""
2357 (string :tag "Extension")
2358 (const :tag "System command to open files" system)
2359 (const :tag "Default for unrecognized files" t)
2360 (const :tag "Remote file" remote)
2361 (const :tag "Links to a directory" directory)
2362 (const :tag "Any files that have Emacs modes"
2363 auto-mode))
2364 (choice :value ""
2365 (const :tag "Visit with Emacs" emacs)
2366 (const :tag "Use default" default)
2367 (const :tag "Use the system command" system)
2368 (string :tag "Command")
2369 (function :tag "Function")))))
2371 (defcustom org-doi-server-url "http://dx.doi.org/"
2372 "The URL of the DOI server."
2373 :type 'string
2374 :version "24.3"
2375 :group 'org-link-follow)
2377 (defgroup org-refile nil
2378 "Options concerning refiling entries in Org mode."
2379 :tag "Org Refile"
2380 :group 'org)
2382 (defcustom org-directory "~/org"
2383 "Directory with Org files.
2384 This is just a default location to look for Org files. There is no need
2385 at all to put your files into this directory. It is used in the
2386 following situations:
2388 1. When a capture template specifies a target file that is not an
2389 absolute path. The path will then be interpreted relative to
2390 `org-directory'
2391 2. When the value of variable `org-agenda-files' is a single file, any
2392 relative paths in this file will be taken as relative to
2393 `org-directory'."
2394 :group 'org-refile
2395 :group 'org-capture
2396 :type 'directory)
2398 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2399 "Default target for storing notes.
2400 Used as a fall back file for org-capture.el, for templates that
2401 do not specify a target file."
2402 :group 'org-refile
2403 :group 'org-capture
2404 :type 'file)
2406 (defcustom org-goto-interface 'outline
2407 "The default interface to be used for `org-goto'.
2408 Allowed values are:
2409 outline The interface shows an outline of the relevant file
2410 and the correct heading is found by moving through
2411 the outline or by searching with incremental search.
2412 outline-path-completion Headlines in the current buffer are offered via
2413 completion. This is the interface also used by
2414 the refile command."
2415 :group 'org-refile
2416 :type '(choice
2417 (const :tag "Outline" outline)
2418 (const :tag "Outline-path-completion" outline-path-completion)))
2420 (defcustom org-goto-max-level 5
2421 "Maximum target level when running `org-goto' with refile interface."
2422 :group 'org-refile
2423 :type 'integer)
2425 (defcustom org-reverse-note-order nil
2426 "Non-nil means store new notes at the beginning of a file or entry.
2427 When nil, new notes will be filed to the end of a file or entry.
2428 This can also be a list with cons cells of regular expressions that
2429 are matched against file names, and values."
2430 :group 'org-capture
2431 :group 'org-refile
2432 :type '(choice
2433 (const :tag "Reverse always" t)
2434 (const :tag "Reverse never" nil)
2435 (repeat :tag "By file name regexp"
2436 (cons regexp boolean))))
2438 (defcustom org-log-refile nil
2439 "Information to record when a task is refiled.
2441 Possible values are:
2443 nil Don't add anything
2444 time Add a time stamp to the task
2445 note Prompt for a note and add it with template `org-log-note-headings'
2447 This option can also be set with on a per-file-basis with
2449 #+STARTUP: nologrefile
2450 #+STARTUP: logrefile
2451 #+STARTUP: lognoterefile
2453 You can have local logging settings for a subtree by setting the LOGGING
2454 property to one or more of these keywords.
2456 When bulk-refiling from the agenda, the value `note' is forbidden and
2457 will temporarily be changed to `time'."
2458 :group 'org-refile
2459 :group 'org-progress
2460 :version "24.1"
2461 :type '(choice
2462 (const :tag "No logging" nil)
2463 (const :tag "Record timestamp" time)
2464 (const :tag "Record timestamp with note." note)))
2466 (defcustom org-refile-targets nil
2467 "Targets for refiling entries with `\\[org-refile]'.
2468 This is a list of cons cells. Each cell contains:
2469 - a specification of the files to be considered, either a list of files,
2470 or a symbol whose function or variable value will be used to retrieve
2471 a file name or a list of file names. If you use `org-agenda-files' for
2472 that, all agenda files will be scanned for targets. Nil means consider
2473 headings in the current buffer.
2474 - A specification of how to find candidate refile targets. This may be
2475 any of:
2476 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2477 This tag has to be present in all target headlines, inheritance will
2478 not be considered.
2479 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2480 todo keyword.
2481 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2482 headlines that are refiling targets.
2483 - a cons cell (:level . N). Any headline of level N is considered a target.
2484 Note that, when `org-odd-levels-only' is set, level corresponds to
2485 order in hierarchy, not to the number of stars.
2486 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2487 Note that, when `org-odd-levels-only' is set, level corresponds to
2488 order in hierarchy, not to the number of stars.
2490 Each element of this list generates a set of possible targets.
2491 The union of these sets is presented (with completion) to
2492 the user by `org-refile'.
2494 You can set the variable `org-refile-target-verify-function' to a function
2495 to verify each headline found by the simple criteria above.
2497 When this variable is nil, all top-level headlines in the current buffer
2498 are used, equivalent to the value `((nil . (:level . 1))'."
2499 :group 'org-refile
2500 :type '(repeat
2501 (cons
2502 (choice :value org-agenda-files
2503 (const :tag "All agenda files" org-agenda-files)
2504 (const :tag "Current buffer" nil)
2505 (function) (variable) (file))
2506 (choice :tag "Identify target headline by"
2507 (cons :tag "Specific tag" (const :value :tag) (string))
2508 (cons :tag "TODO keyword" (const :value :todo) (string))
2509 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2510 (cons :tag "Level number" (const :value :level) (integer))
2511 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2513 (defcustom org-refile-target-verify-function nil
2514 "Function to verify if the headline at point should be a refile target.
2515 The function will be called without arguments, with point at the
2516 beginning of the headline. It should return t and leave point
2517 where it is if the headline is a valid target for refiling.
2519 If the target should not be selected, the function must return nil.
2520 In addition to this, it may move point to a place from where the search
2521 should be continued. For example, the function may decide that the entire
2522 subtree of the current entry should be excluded and move point to the end
2523 of the subtree."
2524 :group 'org-refile
2525 :type '(choice
2526 (const nil)
2527 (function)))
2529 (defcustom org-refile-use-cache nil
2530 "Non-nil means cache refile targets to speed up the process.
2531 \\<org-mode-map>\
2532 The cache for a particular file will be updated automatically when
2533 the buffer has been killed, or when any of the marker used for flagging
2534 refile targets no longer points at a live buffer.
2535 If you have added new entries to a buffer that might themselves be targets,
2536 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2537 if you find that easier, \
2538 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2539 \\[org-refile]'."
2540 :group 'org-refile
2541 :version "24.1"
2542 :type 'boolean)
2544 (defcustom org-refile-use-outline-path nil
2545 "Non-nil means provide refile targets as paths.
2546 So a level 3 headline will be available as level1/level2/level3.
2548 When the value is `file', also include the file name (without directory)
2549 into the path. In this case, you can also stop the completion after
2550 the file name, to get entries inserted as top level in the file.
2552 When `full-file-path', include the full file path."
2553 :group 'org-refile
2554 :type '(choice
2555 (const :tag "Not" nil)
2556 (const :tag "Yes" t)
2557 (const :tag "Start with file name" file)
2558 (const :tag "Start with full file path" full-file-path)))
2560 (defcustom org-outline-path-complete-in-steps t
2561 "Non-nil means complete the outline path in hierarchical steps.
2562 When Org uses the refile interface to select an outline path (see
2563 `org-refile-use-outline-path'), the completion of the path can be
2564 done in a single go, or it can be done in steps down the headline
2565 hierarchy. Going in steps is probably the best if you do not use
2566 a special completion package like `ido' or `icicles'. However,
2567 when using these packages, going in one step can be very fast,
2568 while still showing the whole path to the entry."
2569 :group 'org-refile
2570 :type 'boolean)
2572 (defcustom org-refile-allow-creating-parent-nodes nil
2573 "Non-nil means allow the creation of new nodes as refile targets.
2574 New nodes are then created by adding \"/new node name\" to the completion
2575 of an existing node. When the value of this variable is `confirm',
2576 new node creation must be confirmed by the user (recommended).
2577 When nil, the completion must match an existing entry.
2579 Note that, if the new heading is not seen by the criteria
2580 listed in `org-refile-targets', multiple instances of the same
2581 heading would be created by trying again to file under the new
2582 heading."
2583 :group 'org-refile
2584 :type '(choice
2585 (const :tag "Never" nil)
2586 (const :tag "Always" t)
2587 (const :tag "Prompt for confirmation" confirm)))
2589 (defcustom org-refile-active-region-within-subtree nil
2590 "Non-nil means also refile active region within a subtree.
2592 By default `org-refile' doesn't allow refiling regions if they
2593 don't contain a set of subtrees, but it might be convenient to
2594 do so sometimes: in that case, the first line of the region is
2595 converted to a headline before refiling."
2596 :group 'org-refile
2597 :version "24.1"
2598 :type 'boolean)
2600 (defgroup org-todo nil
2601 "Options concerning TODO items in Org mode."
2602 :tag "Org TODO"
2603 :group 'org)
2605 (defgroup org-progress nil
2606 "Options concerning Progress logging in Org mode."
2607 :tag "Org Progress"
2608 :group 'org-time)
2610 (defvar org-todo-interpretation-widgets
2611 '((:tag "Sequence (cycling hits every state)" sequence)
2612 (:tag "Type (cycling directly to DONE)" type))
2613 "The available interpretation symbols for customizing `org-todo-keywords'.
2614 Interested libraries should add to this list.")
2616 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2617 "List of TODO entry keyword sequences and their interpretation.
2618 \\<org-mode-map>This is a list of sequences.
2620 Each sequence starts with a symbol, either `sequence' or `type',
2621 indicating if the keywords should be interpreted as a sequence of
2622 action steps, or as different types of TODO items. The first
2623 keywords are states requiring action - these states will select a headline
2624 for inclusion into the global TODO list Org produces. If one of the
2625 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2626 signify that no further action is necessary. If \"|\" is not found,
2627 the last keyword is treated as the only DONE state of the sequence.
2629 The command `\\[org-todo]' cycles an entry through these states, and one
2630 additional state where no keyword is present. For details about this
2631 cycling, see the manual.
2633 TODO keywords and interpretation can also be set on a per-file basis with
2634 the special #+SEQ_TODO and #+TYP_TODO lines.
2636 Each keyword can optionally specify a character for fast state selection
2637 \(in combination with the variable `org-use-fast-todo-selection')
2638 and specifiers for state change logging, using the same syntax that
2639 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2640 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2641 indicates to record a time stamp each time this state is selected.
2643 Each keyword may also specify if a timestamp or a note should be
2644 recorded when entering or leaving the state, by adding additional
2645 characters in the parenthesis after the keyword. This looks like this:
2646 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2647 record only the time of the state change. With X and Y being either
2648 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2649 Y when leaving the state if and only if the *target* state does not
2650 define X. You may omit any of the fast-selection key or X or /Y,
2651 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2653 For backward compatibility, this variable may also be just a list
2654 of keywords. In this case the interpretation (sequence or type) will be
2655 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2656 :group 'org-todo
2657 :group 'org-keywords
2658 :type '(choice
2659 (repeat :tag "Old syntax, just keywords"
2660 (string :tag "Keyword"))
2661 (repeat :tag "New syntax"
2662 (cons
2663 (choice
2664 :tag "Interpretation"
2665 ;;Quick and dirty way to see
2666 ;;`org-todo-interpretations'. This takes the
2667 ;;place of item arguments
2668 :convert-widget
2669 (lambda (widget)
2670 (widget-put widget
2671 :args (mapcar
2672 (lambda (x)
2673 (widget-convert
2674 (cons 'const x)))
2675 org-todo-interpretation-widgets))
2676 widget))
2677 (repeat
2678 (string :tag "Keyword"))))))
2680 (defvar-local org-todo-keywords-1 nil
2681 "All TODO and DONE keywords active in a buffer.")
2682 (defvar org-todo-keywords-for-agenda nil)
2683 (defvar org-done-keywords-for-agenda nil)
2684 (defvar org-todo-keyword-alist-for-agenda nil)
2685 (defvar org-tag-alist-for-agenda nil
2686 "Alist of all tags from all agenda files.")
2687 (defvar org-tag-groups-alist-for-agenda nil
2688 "Alist of all groups tags from all current agenda files.")
2689 (defvar-local org-tag-groups-alist nil)
2690 (defvar org-agenda-contributing-files nil)
2691 (defvar-local org-current-tag-alist nil
2692 "Alist of all tag groups in current buffer.
2693 This variable takes into consideration `org-tag-alist',
2694 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2695 (defvar-local org-not-done-keywords nil)
2696 (defvar-local org-done-keywords nil)
2697 (defvar-local org-todo-heads nil)
2698 (defvar-local org-todo-sets nil)
2699 (defvar-local org-todo-log-states nil)
2700 (defvar-local org-todo-kwd-alist nil)
2701 (defvar-local org-todo-key-alist nil)
2702 (defvar-local org-todo-key-trigger nil)
2704 (defcustom org-todo-interpretation 'sequence
2705 "Controls how TODO keywords are interpreted.
2706 This variable is in principle obsolete and is only used for
2707 backward compatibility, if the interpretation of todo keywords is
2708 not given already in `org-todo-keywords'. See that variable for
2709 more information."
2710 :group 'org-todo
2711 :group 'org-keywords
2712 :type '(choice (const sequence)
2713 (const type)))
2715 (defcustom org-use-fast-todo-selection t
2716 "\\<org-mode-map>\
2717 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2718 This variable describes if and under what circumstances the cycling
2719 mechanism for TODO keywords will be replaced by a single-key, direct
2720 selection scheme.
2722 When nil, fast selection is never used.
2724 When the symbol `prefix', it will be used when `org-todo' is called
2725 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2726 in an Org buffer, and
2727 `\\[universal-argument] t' in an agenda buffer.
2729 When t, fast selection is used by default. In this case, the prefix
2730 argument forces cycling instead.
2732 In all cases, the special interface is only used if access keys have
2733 actually been assigned by the user, i.e. if keywords in the configuration
2734 are followed by a letter in parenthesis, like TODO(t)."
2735 :group 'org-todo
2736 :type '(choice
2737 (const :tag "Never" nil)
2738 (const :tag "By default" t)
2739 (const :tag "Only with C-u C-c C-t" prefix)))
2741 (defcustom org-provide-todo-statistics t
2742 "Non-nil means update todo statistics after insert and toggle.
2743 ALL-HEADLINES means update todo statistics by including headlines
2744 with no TODO keyword as well, counting them as not done.
2745 A list of TODO keywords means the same, but skip keywords that are
2746 not in this list.
2747 When set to a list of two lists, the first list contains keywords
2748 to consider as TODO keywords, the second list contains keywords
2749 to consider as DONE keywords.
2751 When this is set, todo statistics is updated in the parent of the
2752 current entry each time a todo state is changed."
2753 :group 'org-todo
2754 :type '(choice
2755 (const :tag "Yes, only for TODO entries" t)
2756 (const :tag "Yes, including all entries" all-headlines)
2757 (repeat :tag "Yes, for TODOs in this list"
2758 (string :tag "TODO keyword"))
2759 (list :tag "Yes, for TODOs and DONEs in these lists"
2760 (repeat (string :tag "TODO keyword"))
2761 (repeat (string :tag "DONE keyword")))
2762 (other :tag "No TODO statistics" nil)))
2764 (defcustom org-hierarchical-todo-statistics t
2765 "Non-nil means TODO statistics covers just direct children.
2766 When nil, all entries in the subtree are considered.
2767 This has only an effect if `org-provide-todo-statistics' is set.
2768 To set this to nil for only a single subtree, use a COOKIE_DATA
2769 property and include the word \"recursive\" into the value."
2770 :group 'org-todo
2771 :type 'boolean)
2773 (defcustom org-after-todo-state-change-hook nil
2774 "Hook which is run after the state of a TODO item was changed.
2775 The new state (a string with a TODO keyword, or nil) is available in the
2776 Lisp variable `org-state'."
2777 :group 'org-todo
2778 :type 'hook)
2780 (defvar org-blocker-hook nil
2781 "Hook for functions that are allowed to block a state change.
2783 Functions in this hook should not modify the buffer.
2784 Each function gets as its single argument a property list,
2785 see `org-trigger-hook' for more information about this list.
2787 If any of the functions in this hook returns nil, the state change
2788 is blocked.")
2790 (defvar org-trigger-hook nil
2791 "Hook for functions that are triggered by a state change.
2793 Each function gets as its single argument a property list with at
2794 least the following elements:
2796 (:type type-of-change :position pos-at-entry-start
2797 :from old-state :to new-state)
2799 Depending on the type, more properties may be present.
2801 This mechanism is currently implemented for:
2803 TODO state changes
2804 ------------------
2805 :type todo-state-change
2806 :from previous state (keyword as a string), or nil, or a symbol
2807 `todo' or `done', to indicate the general type of state.
2808 :to new state, like in :from")
2810 (defcustom org-enforce-todo-dependencies nil
2811 "Non-nil means undone TODO entries will block switching the parent to DONE.
2812 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2813 be blocked if any prior sibling is not yet done.
2814 Finally, if the parent is blocked because of ordered siblings of its own,
2815 the child will also be blocked."
2816 :set (lambda (var val)
2817 (set var val)
2818 (if val
2819 (add-hook 'org-blocker-hook
2820 'org-block-todo-from-children-or-siblings-or-parent)
2821 (remove-hook 'org-blocker-hook
2822 'org-block-todo-from-children-or-siblings-or-parent)))
2823 :group 'org-todo
2824 :type 'boolean)
2826 (defcustom org-enforce-todo-checkbox-dependencies nil
2827 "Non-nil means unchecked boxes will block switching the parent to DONE.
2828 When this is nil, checkboxes have no influence on switching TODO states.
2829 When non-nil, you first need to check off all check boxes before the TODO
2830 entry can be switched to DONE.
2831 This variable needs to be set before org.el is loaded, and you need to
2832 restart Emacs after a change to make the change effective. The only way
2833 to change is while Emacs is running is through the customize interface."
2834 :set (lambda (var val)
2835 (set var val)
2836 (if val
2837 (add-hook 'org-blocker-hook
2838 'org-block-todo-from-checkboxes)
2839 (remove-hook 'org-blocker-hook
2840 'org-block-todo-from-checkboxes)))
2841 :group 'org-todo
2842 :type 'boolean)
2844 (defcustom org-treat-insert-todo-heading-as-state-change nil
2845 "Non-nil means inserting a TODO heading is treated as state change.
2846 So when the command `\\[org-insert-todo-heading]' is used, state change
2847 logging will apply if appropriate. When nil, the new TODO item will
2848 be inserted directly, and no logging will take place."
2849 :group 'org-todo
2850 :type 'boolean)
2852 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2853 "Non-nil means switching TODO states with S-cursor counts as state change.
2854 This is the default behavior. However, setting this to nil allows a
2855 convenient way to select a TODO state and bypass any logging associated
2856 with that."
2857 :group 'org-todo
2858 :type 'boolean)
2860 (defcustom org-todo-state-tags-triggers nil
2861 "Tag changes that should be triggered by TODO state changes.
2862 This is a list. Each entry is
2864 (state-change (tag . flag) .......)
2866 State-change can be a string with a state, and empty string to indicate the
2867 state that has no TODO keyword, or it can be one of the symbols `todo'
2868 or `done', meaning any not-done or done state, respectively."
2869 :group 'org-todo
2870 :group 'org-tags
2871 :type '(repeat
2872 (cons (choice :tag "When changing to"
2873 (const :tag "Not-done state" todo)
2874 (const :tag "Done state" done)
2875 (string :tag "State"))
2876 (repeat
2877 (cons :tag "Tag action"
2878 (string :tag "Tag")
2879 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2881 (defcustom org-log-done nil
2882 "Information to record when a task moves to the DONE state.
2884 Possible values are:
2886 nil Don't add anything, just change the keyword
2887 time Add a time stamp to the task
2888 note Prompt for a note and add it with template `org-log-note-headings'
2890 This option can also be set with on a per-file-basis with
2892 #+STARTUP: nologdone
2893 #+STARTUP: logdone
2894 #+STARTUP: lognotedone
2896 You can have local logging settings for a subtree by setting the LOGGING
2897 property to one or more of these keywords."
2898 :group 'org-todo
2899 :group 'org-progress
2900 :type '(choice
2901 (const :tag "No logging" nil)
2902 (const :tag "Record CLOSED timestamp" time)
2903 (const :tag "Record CLOSED timestamp with note." note)))
2905 ;; Normalize old uses of org-log-done.
2906 (cond
2907 ((eq org-log-done t) (setq org-log-done 'time))
2908 ((and (listp org-log-done) (memq 'done org-log-done))
2909 (setq org-log-done 'note)))
2911 (defcustom org-log-reschedule nil
2912 "Information to record when the scheduling date of a tasks is modified.
2914 Possible values are:
2916 nil Don't add anything, just change the date
2917 time Add a time stamp to the task
2918 note Prompt for a note and add it with template `org-log-note-headings'
2920 This option can also be set with on a per-file-basis with
2922 #+STARTUP: nologreschedule
2923 #+STARTUP: logreschedule
2924 #+STARTUP: lognotereschedule"
2925 :group 'org-todo
2926 :group 'org-progress
2927 :type '(choice
2928 (const :tag "No logging" nil)
2929 (const :tag "Record timestamp" time)
2930 (const :tag "Record timestamp with note." note)))
2932 (defcustom org-log-redeadline nil
2933 "Information to record when the deadline date of a tasks is modified.
2935 Possible values are:
2937 nil Don't add anything, just change the date
2938 time Add a time stamp to the task
2939 note Prompt for a note and add it with template `org-log-note-headings'
2941 This option can also be set with on a per-file-basis with
2943 #+STARTUP: nologredeadline
2944 #+STARTUP: logredeadline
2945 #+STARTUP: lognoteredeadline
2947 You can have local logging settings for a subtree by setting the LOGGING
2948 property to one or more of these keywords."
2949 :group 'org-todo
2950 :group 'org-progress
2951 :type '(choice
2952 (const :tag "No logging" nil)
2953 (const :tag "Record timestamp" time)
2954 (const :tag "Record timestamp with note." note)))
2956 (defcustom org-log-note-clock-out nil
2957 "Non-nil means record a note when clocking out of an item.
2958 This can also be configured on a per-file basis by adding one of
2959 the following lines anywhere in the buffer:
2961 #+STARTUP: lognoteclock-out
2962 #+STARTUP: nolognoteclock-out"
2963 :group 'org-todo
2964 :group 'org-progress
2965 :type 'boolean)
2967 (defcustom org-log-done-with-time t
2968 "Non-nil means the CLOSED time stamp will contain date and time.
2969 When nil, only the date will be recorded."
2970 :group 'org-progress
2971 :type 'boolean)
2973 (defcustom org-log-note-headings
2974 '((done . "CLOSING NOTE %t")
2975 (state . "State %-12s from %-12S %t")
2976 (note . "Note taken on %t")
2977 (reschedule . "Rescheduled from %S on %t")
2978 (delschedule . "Not scheduled, was %S on %t")
2979 (redeadline . "New deadline from %S on %t")
2980 (deldeadline . "Removed deadline, was %S on %t")
2981 (refile . "Refiled on %t")
2982 (clock-out . ""))
2983 "Headings for notes added to entries.
2985 The value is an alist, with the car being a symbol indicating the
2986 note context, and the cdr is the heading to be used. The heading
2987 may also be the empty string. The following placeholders can be
2988 used:
2990 %t a time stamp.
2991 %T an active time stamp instead the default inactive one
2992 %d a short-format time stamp.
2993 %D an active short-format time stamp.
2994 %s the new TODO state or time stamp (inactive), in double quotes.
2995 %S the old TODO state or time stamp (inactive), in double quotes.
2996 %u the user name.
2997 %U full user name.
2999 In fact, it is not a good idea to change the `state' entry,
3000 because Agenda Log mode depends on the format of these entries."
3001 :group 'org-todo
3002 :group 'org-progress
3003 :type '(list :greedy t
3004 (cons (const :tag "Heading when closing an item" done) string)
3005 (cons (const :tag
3006 "Heading when changing todo state (todo sequence only)"
3007 state) string)
3008 (cons (const :tag "Heading when just taking a note" note) string)
3009 (cons (const :tag "Heading when rescheduling" reschedule) string)
3010 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3011 (cons (const :tag "Heading when changing deadline" redeadline) string)
3012 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3013 (cons (const :tag "Heading when refiling" refile) string)
3014 (cons (const :tag "Heading when clocking out" clock-out) string)))
3016 (unless (assq 'note org-log-note-headings)
3017 (push '(note . "%t") org-log-note-headings))
3019 (defcustom org-log-into-drawer nil
3020 "Non-nil means insert state change notes and time stamps into a drawer.
3021 When nil, state changes notes will be inserted after the headline and
3022 any scheduling and clock lines, but not inside a drawer.
3024 The value of this variable should be the name of the drawer to use.
3025 LOGBOOK is proposed as the default drawer for this purpose, you can
3026 also set this to a string to define the drawer of your choice.
3028 A value of t is also allowed, representing \"LOGBOOK\".
3030 A value of t or nil can also be set with on a per-file-basis with
3032 #+STARTUP: logdrawer
3033 #+STARTUP: nologdrawer
3035 If this variable is set, `org-log-state-notes-insert-after-drawers'
3036 will be ignored.
3038 You can set the property LOG_INTO_DRAWER to overrule this setting for
3039 a subtree.
3041 Do not check directly this variable in a Lisp program. Call
3042 function `org-log-into-drawer' instead."
3043 :group 'org-todo
3044 :group 'org-progress
3045 :type '(choice
3046 (const :tag "Not into a drawer" nil)
3047 (const :tag "LOGBOOK" t)
3048 (string :tag "Other")))
3050 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3052 (defun org-log-into-drawer ()
3053 "Name of the log drawer, as a string, or nil.
3054 This is the value of `org-log-into-drawer'. However, if the
3055 current entry has or inherits a LOG_INTO_DRAWER property, it will
3056 be used instead of the default value."
3057 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3058 (cond ((equal p "nil") nil)
3059 ((equal p "t") "LOGBOOK")
3060 ((stringp p) p)
3061 (p "LOGBOOK")
3062 ((stringp org-log-into-drawer) org-log-into-drawer)
3063 (org-log-into-drawer "LOGBOOK"))))
3065 (defcustom org-log-state-notes-insert-after-drawers nil
3066 "Non-nil means insert state change notes after any drawers in entry.
3067 Only the drawers that *immediately* follow the headline and the
3068 deadline/scheduled line are skipped.
3069 When nil, insert notes right after the heading and perhaps the line
3070 with deadline/scheduling if present.
3072 This variable will have no effect if `org-log-into-drawer' is
3073 set."
3074 :group 'org-todo
3075 :group 'org-progress
3076 :type 'boolean)
3078 (defcustom org-log-states-order-reversed t
3079 "Non-nil means the latest state note will be directly after heading.
3080 When nil, the state change notes will be ordered according to time.
3082 This option can also be set with on a per-file-basis with
3084 #+STARTUP: logstatesreversed
3085 #+STARTUP: nologstatesreversed"
3086 :group 'org-todo
3087 :group 'org-progress
3088 :type 'boolean)
3090 (defcustom org-todo-repeat-to-state nil
3091 "The TODO state to which a repeater should return the repeating task.
3092 By default this is the first task in a TODO sequence, or the previous state
3093 in a TODO_TYP set. But you can specify another task here.
3094 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3095 :group 'org-todo
3096 :version "24.1"
3097 :type '(choice (const :tag "Head of sequence" nil)
3098 (string :tag "Specific state")))
3100 (defcustom org-log-repeat 'time
3101 "Non-nil means record moving through the DONE state when triggering repeat.
3102 An auto-repeating task is immediately switched back to TODO when
3103 marked DONE. If you are not logging state changes (by adding \"@\"
3104 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3105 record a closing note, there will be no record of the task moving
3106 through DONE. This variable forces taking a note anyway.
3108 nil Don't force a record
3109 time Record a time stamp
3110 note Prompt for a note and add it with template `org-log-note-headings'
3112 This option can also be set with on a per-file-basis with
3114 #+STARTUP: nologrepeat
3115 #+STARTUP: logrepeat
3116 #+STARTUP: lognoterepeat
3118 You can have local logging settings for a subtree by setting the LOGGING
3119 property to one or more of these keywords."
3120 :group 'org-todo
3121 :group 'org-progress
3122 :type '(choice
3123 (const :tag "Don't force a record" nil)
3124 (const :tag "Force recording the DONE state" time)
3125 (const :tag "Force recording a note with the DONE state" note)))
3128 (defgroup org-priorities nil
3129 "Priorities in Org mode."
3130 :tag "Org Priorities"
3131 :group 'org-todo)
3133 (defcustom org-enable-priority-commands t
3134 "Non-nil means priority commands are active.
3135 When nil, these commands will be disabled, so that you never accidentally
3136 set a priority."
3137 :group 'org-priorities
3138 :type 'boolean)
3140 (defcustom org-highest-priority ?A
3141 "The highest priority of TODO items. A character like ?A, ?B etc.
3142 Must have a smaller ASCII number than `org-lowest-priority'."
3143 :group 'org-priorities
3144 :type 'character)
3146 (defcustom org-lowest-priority ?C
3147 "The lowest priority of TODO items. A character like ?A, ?B etc.
3148 Must have a larger ASCII number than `org-highest-priority'."
3149 :group 'org-priorities
3150 :type 'character)
3152 (defcustom org-default-priority ?B
3153 "The default priority of TODO items.
3154 This is the priority an item gets if no explicit priority is given.
3155 When starting to cycle on an empty priority the first step in the cycle
3156 depends on `org-priority-start-cycle-with-default'. The resulting first
3157 step priority must not exceed the range from `org-highest-priority' to
3158 `org-lowest-priority' which means that `org-default-priority' has to be
3159 in this range exclusive or inclusive the range boundaries. Else the
3160 first step refuses to set the default and the second will fall back
3161 to (depending on the command used) the highest or lowest priority."
3162 :group 'org-priorities
3163 :type 'character)
3165 (defcustom org-priority-start-cycle-with-default t
3166 "Non-nil means start with default priority when starting to cycle.
3167 When this is nil, the first step in the cycle will be (depending on the
3168 command used) one higher or lower than the default priority.
3169 See also `org-default-priority'."
3170 :group 'org-priorities
3171 :type 'boolean)
3173 (defcustom org-get-priority-function nil
3174 "Function to extract the priority from a string.
3175 The string is normally the headline. If this is nil Org computes the
3176 priority from the priority cookie like [#A] in the headline. It returns
3177 an integer, increasing by 1000 for each priority level.
3178 The user can set a different function here, which should take a string
3179 as an argument and return the numeric priority."
3180 :group 'org-priorities
3181 :version "24.1"
3182 :type '(choice
3183 (const nil)
3184 (function)))
3186 (defgroup org-time nil
3187 "Options concerning time stamps and deadlines in Org mode."
3188 :tag "Org Time"
3189 :group 'org)
3191 (defcustom org-time-stamp-rounding-minutes '(0 5)
3192 "Number of minutes to round time stamps to.
3193 \\<org-mode-map>\
3194 These are two values, the first applies when first creating a time stamp.
3195 The second applies when changing it with the commands `S-up' and `S-down'.
3196 When changing the time stamp, this means that it will change in steps
3197 of N minutes, as given by the second value.
3199 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3200 numbers should be factors of 60, so for example 5, 10, 15.
3202 When this is larger than 1, you can still force an exact time stamp by using
3203 a double prefix argument to a time stamp command like \
3204 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3205 and by using a prefix arg to `S-up/down' to specify the exact number
3206 of minutes to shift."
3207 :group 'org-time
3208 :get (lambda (var) ; Make sure both elements are there
3209 (if (integerp (default-value var))
3210 (list (default-value var) 5)
3211 (default-value var)))
3212 :type '(list
3213 (integer :tag "when inserting times")
3214 (integer :tag "when modifying times")))
3216 ;; Normalize old customizations of this variable.
3217 (when (integerp org-time-stamp-rounding-minutes)
3218 (setq org-time-stamp-rounding-minutes
3219 (list org-time-stamp-rounding-minutes
3220 org-time-stamp-rounding-minutes)))
3222 (defcustom org-display-custom-times nil
3223 "Non-nil means overlay custom formats over all time stamps.
3224 The formats are defined through the variable `org-time-stamp-custom-formats'.
3225 To turn this on on a per-file basis, insert anywhere in the file:
3226 #+STARTUP: customtime"
3227 :group 'org-time
3228 :set 'set-default
3229 :type 'sexp)
3230 (make-variable-buffer-local 'org-display-custom-times)
3232 (defcustom org-time-stamp-custom-formats
3233 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3234 "Custom formats for time stamps. See `format-time-string' for the syntax.
3235 These are overlaid over the default ISO format if the variable
3236 `org-display-custom-times' is set. Time like %H:%M should be at the
3237 end of the second format. The custom formats are also honored by export
3238 commands, if custom time display is turned on at the time of export."
3239 :group 'org-time
3240 :type 'sexp)
3242 (defun org-time-stamp-format (&optional long inactive)
3243 "Get the right format for a time string."
3244 (let ((f (if long (cdr org-time-stamp-formats)
3245 (car org-time-stamp-formats))))
3246 (if inactive
3247 (concat "[" (substring f 1 -1) "]")
3248 f)))
3250 (defcustom org-time-clocksum-format
3251 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3252 "The format string used when creating CLOCKSUM lines.
3253 This is also used when Org mode generates a time duration.
3255 The value can be a single format string containing two
3256 %-sequences, which will be filled with the number of hours and
3257 minutes in that order.
3259 Alternatively, the value can be a plist associating any of the
3260 keys :years, :months, :weeks, :days, :hours or :minutes with
3261 format strings. The time duration is formatted using only the
3262 time components that are needed and concatenating the results.
3263 If a time unit in absent, it falls back to the next smallest
3264 unit.
3266 The keys :require-years, :require-months, :require-days,
3267 :require-weeks, :require-hours, :require-minutes are also
3268 meaningful. A non-nil value for these keys indicates that the
3269 corresponding time component should always be included, even if
3270 its value is 0.
3273 For example,
3275 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3276 :require-minutes t)
3278 means durations longer than a day will be expressed in days,
3279 hours and minutes, and durations less than a day will always be
3280 expressed in hours and minutes (even for durations less than an
3281 hour).
3283 The value
3285 (:days \"%dd\" :minutes \"%dm\")
3287 means durations longer than a day will be expressed in days and
3288 minutes, and durations less than a day will be expressed entirely
3289 in minutes (even for durations longer than an hour)."
3290 :group 'org-time
3291 :group 'org-clock
3292 :version "24.4"
3293 :package-version '(Org . "8.0")
3294 :type '(choice (string :tag "Format string")
3295 (set :tag "Plist"
3296 (group :inline t (const :tag "Years" :years)
3297 (string :tag "Format string"))
3298 (group :inline t
3299 (const :tag "Always show years" :require-years)
3300 (const t))
3301 (group :inline t (const :tag "Months" :months)
3302 (string :tag "Format string"))
3303 (group :inline t
3304 (const :tag "Always show months" :require-months)
3305 (const t))
3306 (group :inline t (const :tag "Weeks" :weeks)
3307 (string :tag "Format string"))
3308 (group :inline t
3309 (const :tag "Always show weeks" :require-weeks)
3310 (const t))
3311 (group :inline t (const :tag "Days" :days)
3312 (string :tag "Format string"))
3313 (group :inline t
3314 (const :tag "Always show days" :require-days)
3315 (const t))
3316 (group :inline t (const :tag "Hours" :hours)
3317 (string :tag "Format string"))
3318 (group :inline t
3319 (const :tag "Always show hours" :require-hours)
3320 (const t))
3321 (group :inline t (const :tag "Minutes" :minutes)
3322 (string :tag "Format string"))
3323 (group :inline t
3324 (const :tag "Always show minutes" :require-minutes)
3325 (const t)))))
3327 (defcustom org-time-clocksum-use-fractional nil
3328 "When non-nil, `\\[org-clock-display]' uses fractional times.
3329 See `org-time-clocksum-format' for more on time clock formats."
3330 :group 'org-time
3331 :group 'org-clock
3332 :version "24.3"
3333 :type 'boolean)
3335 (defcustom org-time-clocksum-use-effort-durations nil
3336 "When non-nil, `\\[org-clock-display]' uses effort durations.
3337 E.g. by default, one day is considered to be a 8 hours effort,
3338 so a task that has been clocked for 16 hours will be displayed
3339 as during 2 days in the clock display or in the clocktable.
3341 See `org-effort-durations' on how to set effort durations
3342 and `org-time-clocksum-format' for more on time clock formats."
3343 :group 'org-time
3344 :group 'org-clock
3345 :version "24.4"
3346 :package-version '(Org . "8.0")
3347 :type 'boolean)
3349 (defcustom org-time-clocksum-fractional-format "%.2f"
3350 "The format string used when creating CLOCKSUM lines,
3351 or when Org mode generates a time duration, if
3352 `org-time-clocksum-use-fractional' is enabled.
3354 The value can be a single format string containing one
3355 %-sequence, which will be filled with the number of hours as
3356 a float.
3358 Alternatively, the value can be a plist associating any of the
3359 keys :years, :months, :weeks, :days, :hours or :minutes with
3360 a format string. The time duration is formatted using the
3361 largest time unit which gives a non-zero integer part. If all
3362 specified formats have zero integer part, the smallest time unit
3363 is used."
3364 :group 'org-time
3365 :type '(choice (string :tag "Format string")
3366 (set (group :inline t (const :tag "Years" :years)
3367 (string :tag "Format string"))
3368 (group :inline t (const :tag "Months" :months)
3369 (string :tag "Format string"))
3370 (group :inline t (const :tag "Weeks" :weeks)
3371 (string :tag "Format string"))
3372 (group :inline t (const :tag "Days" :days)
3373 (string :tag "Format string"))
3374 (group :inline t (const :tag "Hours" :hours)
3375 (string :tag "Format string"))
3376 (group :inline t (const :tag "Minutes" :minutes)
3377 (string :tag "Format string")))))
3379 (defcustom org-deadline-warning-days 14
3380 "Number of days before expiration during which a deadline becomes active.
3381 This variable governs the display in sparse trees and in the agenda.
3382 When 0 or negative, it means use this number (the absolute value of it)
3383 even if a deadline has a different individual lead time specified.
3385 Custom commands can set this variable in the options section."
3386 :group 'org-time
3387 :group 'org-agenda-daily/weekly
3388 :type 'integer)
3390 (defcustom org-scheduled-delay-days 0
3391 "Number of days before a scheduled item becomes active.
3392 This variable governs the display in sparse trees and in the agenda.
3393 The default value (i.e. 0) means: don't delay scheduled item.
3394 When negative, it means use this number (the absolute value of it)
3395 even if a scheduled item has a different individual delay time
3396 specified.
3398 Custom commands can set this variable in the options section."
3399 :group 'org-time
3400 :group 'org-agenda-daily/weekly
3401 :version "24.4"
3402 :package-version '(Org . "8.0")
3403 :type 'integer)
3405 (defcustom org-read-date-prefer-future t
3406 "Non-nil means assume future for incomplete date input from user.
3407 This affects the following situations:
3408 1. The user gives a month but not a year.
3409 For example, if it is April and you enter \"feb 2\", this will be read
3410 as Feb 2, *next* year. \"May 5\", however, will be this year.
3411 2. The user gives a day, but no month.
3412 For example, if today is the 15th, and you enter \"3\", Org will read
3413 this as the third of *next* month. However, if you enter \"17\",
3414 it will be considered as *this* month.
3416 If you set this variable to the symbol `time', then also the following
3417 will work:
3419 3. If the user gives a time.
3420 If the time is before now, it will be interpreted as tomorrow.
3422 Currently none of this works for ISO week specifications.
3424 When this option is nil, the current day, month and year will always be
3425 used as defaults.
3427 See also `org-agenda-jump-prefer-future'."
3428 :group 'org-time
3429 :type '(choice
3430 (const :tag "Never" nil)
3431 (const :tag "Check month and day" t)
3432 (const :tag "Check month, day, and time" time)))
3434 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3435 "Should the agenda jump command prefer the future for incomplete dates?
3436 The default is to do the same as configured in `org-read-date-prefer-future'.
3437 But you can also set a deviating value here.
3438 This may t or nil, or the symbol `org-read-date-prefer-future'."
3439 :group 'org-agenda
3440 :group 'org-time
3441 :version "24.1"
3442 :type '(choice
3443 (const :tag "Use org-read-date-prefer-future"
3444 org-read-date-prefer-future)
3445 (const :tag "Never" nil)
3446 (const :tag "Always" t)))
3448 (defcustom org-read-date-force-compatible-dates t
3449 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3451 Depending on the system Emacs is running on, certain dates cannot
3452 be represented with the type used internally to represent time.
3453 Dates between 1970-1-1 and 2038-1-1 can always be represented
3454 correctly. Some systems allow for earlier dates, some for later,
3455 some for both. One way to find out it to insert any date into an
3456 Org buffer, putting the cursor on the year and hitting S-up and
3457 S-down to test the range.
3459 When this variable is set to t, the date/time prompt will not let
3460 you specify dates outside the 1970-2037 range, so it is certain that
3461 these dates will work in whatever version of Emacs you are
3462 running, and also that you can move a file from one Emacs implementation
3463 to another. WHenever Org is forcing the year for you, it will display
3464 a message and beep.
3466 When this variable is nil, Org will check if the date is
3467 representable in the specific Emacs implementation you are using.
3468 If not, it will force a year, usually the current year, and beep
3469 to remind you. Currently this setting is not recommended because
3470 the likelihood that you will open your Org files in an Emacs that
3471 has limited date range is not negligible.
3473 A workaround for this problem is to use diary sexp dates for time
3474 stamps outside of this range."
3475 :group 'org-time
3476 :version "24.1"
3477 :type 'boolean)
3479 (defcustom org-read-date-display-live t
3480 "Non-nil means display current interpretation of date prompt live.
3481 This display will be in an overlay, in the minibuffer."
3482 :group 'org-time
3483 :type 'boolean)
3485 (defcustom org-read-date-popup-calendar t
3486 "Non-nil means pop up a calendar when prompting for a date.
3487 In the calendar, the date can be selected with mouse-1. However, the
3488 minibuffer will also be active, and you can simply enter the date as well.
3489 When nil, only the minibuffer will be available."
3490 :group 'org-time
3491 :type 'boolean)
3492 (defvaralias 'org-popup-calendar-for-date-prompt
3493 'org-read-date-popup-calendar)
3495 (defcustom org-extend-today-until 0
3496 "The hour when your day really ends. Must be an integer.
3497 This has influence for the following applications:
3498 - When switching the agenda to \"today\". It it is still earlier than
3499 the time given here, the day recognized as TODAY is actually yesterday.
3500 - When a date is read from the user and it is still before the time given
3501 here, the current date and time will be assumed to be yesterday, 23:59.
3502 Also, timestamps inserted in capture templates follow this rule.
3504 IMPORTANT: This is a feature whose implementation is and likely will
3505 remain incomplete. Really, it is only here because past midnight seems to
3506 be the favorite working time of John Wiegley :-)"
3507 :group 'org-time
3508 :type 'integer)
3510 (defcustom org-use-effective-time nil
3511 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3512 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3513 \"effective time\" of any timestamps between midnight and 8am will be
3514 23:59 of the previous day."
3515 :group 'org-time
3516 :version "24.1"
3517 :type 'boolean)
3519 (defcustom org-use-last-clock-out-time-as-effective-time nil
3520 "When non-nil, use the last clock out time for `org-todo'.
3521 Note that this option has precedence over the combined use of
3522 `org-use-effective-time' and `org-extend-today-until'."
3523 :group 'org-time
3524 :version "24.4"
3525 :package-version '(Org . "8.0")
3526 :type 'boolean)
3528 (defcustom org-edit-timestamp-down-means-later nil
3529 "Non-nil means S-down will increase the time in a time stamp.
3530 When nil, S-up will increase."
3531 :group 'org-time
3532 :type 'boolean)
3534 (defcustom org-calendar-follow-timestamp-change t
3535 "Non-nil means make the calendar window follow timestamp changes.
3536 When a timestamp is modified and the calendar window is visible, it will be
3537 moved to the new date."
3538 :group 'org-time
3539 :type 'boolean)
3541 (defgroup org-tags nil
3542 "Options concerning tags in Org mode."
3543 :tag "Org Tags"
3544 :group 'org)
3546 (defcustom org-tag-alist nil
3547 "Default tags available in Org files.
3549 The value of this variable is an alist. Associations either:
3551 (TAG)
3552 (TAG . SELECT)
3553 (SPECIAL)
3555 where TAG is a tag as a string, SELECT is character, used to
3556 select that tag through the fast tag selection interface, and
3557 SPECIAL is one of the following keywords: `:startgroup',
3558 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3559 `:newline'. These keywords are used to define a hierarchy of
3560 tags. See manual for details.
3562 When this variable is nil, Org mode bases tag input on what is
3563 already in the buffer. The value can be overridden locally by
3564 using a TAGS keyword, e.g.,
3566 #+TAGS: tag1 tag2
3568 See also `org-tag-persistent-alist' to sidestep this behavior."
3569 :group 'org-tags
3570 :type '(repeat
3571 (choice
3572 (cons (string :tag "Tag name")
3573 (character :tag "Access char"))
3574 (const :tag "Start radio group" (:startgroup))
3575 (const :tag "Start tag group, non distinct" (:startgrouptag))
3576 (const :tag "Group tags delimiter" (:grouptags))
3577 (const :tag "End radio group" (:endgroup))
3578 (const :tag "End tag group, non distinct" (:endgrouptag))
3579 (const :tag "New line" (:newline)))))
3581 (defcustom org-tag-persistent-alist nil
3582 "Tags always available in Org files.
3584 The value of this variable is an alist. Associations either:
3586 (TAG)
3587 (TAG . SELECT)
3588 (SPECIAL)
3590 where TAG is a tag as a string, SELECT is a character, used to
3591 select that tag through the fast tag selection interface, and
3592 SPECIAL is one of the following keywords: `:startgroup',
3593 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3594 `:newline'. These keywords are used to define a hierarchy of
3595 tags. See manual for details.
3597 Unlike to `org-tag-alist', tags defined in this variable do not
3598 depend on a local TAGS keyword. Instead, to disable these tags
3599 on a per-file basis, insert anywhere in the file:
3601 #+STARTUP: noptag"
3602 :group 'org-tags
3603 :type '(repeat
3604 (choice
3605 (cons (string :tag "Tag name")
3606 (character :tag "Access char"))
3607 (const :tag "Start radio group" (:startgroup))
3608 (const :tag "Start tag group, non distinct" (:startgrouptag))
3609 (const :tag "Group tags delimiter" (:grouptags))
3610 (const :tag "End radio group" (:endgroup))
3611 (const :tag "End tag group, non distinct" (:endgrouptag))
3612 (const :tag "New line" (:newline)))))
3614 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3615 "If non-nil, always offer completion for all tags of all agenda files.
3616 Instead of customizing this variable directly, you might want to
3617 set it locally for capture buffers, because there no list of
3618 tags in that file can be created dynamically (there are none).
3620 (add-hook \\='org-capture-mode-hook
3621 (lambda ()
3622 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3623 :group 'org-tags
3624 :version "24.1"
3625 :type 'boolean)
3627 (defvar org-file-tags nil
3628 "List of tags that can be inherited by all entries in the file.
3629 The tags will be inherited if the variable `org-use-tag-inheritance'
3630 says they should be.
3631 This variable is populated from #+FILETAGS lines.")
3633 (defcustom org-use-fast-tag-selection 'auto
3634 "Non-nil means use fast tag selection scheme.
3635 This is a special interface to select and deselect tags with single keys.
3636 When nil, fast selection is never used.
3637 When the symbol `auto', fast selection is used if and only if selection
3638 characters for tags have been configured, either through the variable
3639 `org-tag-alist' or through a #+TAGS line in the buffer.
3640 When t, fast selection is always used and selection keys are assigned
3641 automatically if necessary."
3642 :group 'org-tags
3643 :type '(choice
3644 (const :tag "Always" t)
3645 (const :tag "Never" nil)
3646 (const :tag "When selection characters are configured" auto)))
3648 (defcustom org-fast-tag-selection-single-key nil
3649 "Non-nil means fast tag selection exits after first change.
3650 When nil, you have to press RET to exit it.
3651 During fast tag selection, you can toggle this flag with `C-c'.
3652 This variable can also have the value `expert'. In this case, the window
3653 displaying the tags menu is not even shown, until you press C-c again."
3654 :group 'org-tags
3655 :type '(choice
3656 (const :tag "No" nil)
3657 (const :tag "Yes" t)
3658 (const :tag "Expert" expert)))
3660 (defvar org-fast-tag-selection-include-todo nil
3661 "Non-nil means fast tags selection interface will also offer TODO states.
3662 This is an undocumented feature, you should not rely on it.")
3664 (defcustom org-tags-column -77
3665 "The column to which tags should be indented in a headline.
3666 If this number is positive, it specifies the column. If it is negative,
3667 it means that the tags should be flushright to that column. For example,
3668 -80 works well for a normal 80 character screen.
3669 When 0, place tags directly after headline text, with only one space in
3670 between."
3671 :group 'org-tags
3672 :type 'integer)
3674 (defcustom org-auto-align-tags t
3675 "Non-nil keeps tags aligned when modifying headlines.
3676 Some operations (i.e. demoting) change the length of a headline and
3677 therefore shift the tags around. With this option turned on, after
3678 each such operation the tags are again aligned to `org-tags-column'."
3679 :group 'org-tags
3680 :type 'boolean)
3682 (defcustom org-use-tag-inheritance t
3683 "Non-nil means tags in levels apply also for sublevels.
3684 When nil, only the tags directly given in a specific line apply there.
3685 This may also be a list of tags that should be inherited, or a regexp that
3686 matches tags that should be inherited. Additional control is possible
3687 with the variable `org-tags-exclude-from-inheritance' which gives an
3688 explicit list of tags to be excluded from inheritance, even if the value of
3689 `org-use-tag-inheritance' would select it for inheritance.
3691 If this option is t, a match early-on in a tree can lead to a large
3692 number of matches in the subtree when constructing the agenda or creating
3693 a sparse tree. If you only want to see the first match in a tree during
3694 a search, check out the variable `org-tags-match-list-sublevels'."
3695 :group 'org-tags
3696 :type '(choice
3697 (const :tag "Not" nil)
3698 (const :tag "Always" t)
3699 (repeat :tag "Specific tags" (string :tag "Tag"))
3700 (regexp :tag "Tags matched by regexp")))
3702 (defcustom org-tags-exclude-from-inheritance nil
3703 "List of tags that should never be inherited.
3704 This is a way to exclude a few tags from inheritance. For way to do
3705 the opposite, to actively allow inheritance for selected tags,
3706 see the variable `org-use-tag-inheritance'."
3707 :group 'org-tags
3708 :type '(repeat (string :tag "Tag")))
3710 (defun org-tag-inherit-p (tag)
3711 "Check if TAG is one that should be inherited."
3712 (cond
3713 ((member tag org-tags-exclude-from-inheritance) nil)
3714 ((eq org-use-tag-inheritance t) t)
3715 ((not org-use-tag-inheritance) nil)
3716 ((stringp org-use-tag-inheritance)
3717 (string-match org-use-tag-inheritance tag))
3718 ((listp org-use-tag-inheritance)
3719 (member tag org-use-tag-inheritance))
3720 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3722 (defcustom org-tags-match-list-sublevels t
3723 "Non-nil means list also sublevels of headlines matching a search.
3724 This variable applies to tags/property searches, and also to stuck
3725 projects because this search is based on a tags match as well.
3727 When set to the symbol `indented', sublevels are indented with
3728 leading dots.
3730 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3731 the sublevels of a headline matching a tag search often also match
3732 the same search. Listing all of them can create very long lists.
3733 Setting this variable to nil causes subtrees of a match to be skipped.
3735 This variable is semi-obsolete and probably should always be true. It
3736 is better to limit inheritance to certain tags using the variables
3737 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3738 :group 'org-tags
3739 :type '(choice
3740 (const :tag "No, don't list them" nil)
3741 (const :tag "Yes, do list them" t)
3742 (const :tag "List them, indented with leading dots" indented)))
3744 (defcustom org-tags-sort-function nil
3745 "When set, tags are sorted using this function as a comparator."
3746 :group 'org-tags
3747 :type '(choice
3748 (const :tag "No sorting" nil)
3749 (const :tag "Alphabetical" string<)
3750 (const :tag "Reverse alphabetical" string>)
3751 (function :tag "Custom function" nil)))
3753 (defvar org-tags-history nil
3754 "History of minibuffer reads for tags.")
3755 (defvar org-last-tags-completion-table nil
3756 "The last used completion table for tags.")
3757 (defvar org-after-tags-change-hook nil
3758 "Hook that is run after the tags in a line have changed.")
3760 (defgroup org-properties nil
3761 "Options concerning properties in Org mode."
3762 :tag "Org Properties"
3763 :group 'org)
3765 (defcustom org-property-format "%-10s %s"
3766 "How property key/value pairs should be formatted by `indent-line'.
3767 When `indent-line' hits a property definition, it will format the line
3768 according to this format, mainly to make sure that the values are
3769 lined-up with respect to each other."
3770 :group 'org-properties
3771 :type 'string)
3773 (defcustom org-properties-postprocess-alist nil
3774 "Alist of properties and functions to adjust inserted values.
3775 Elements of this alist must be of the form
3777 ([string] [function])
3779 where [string] must be a property name and [function] must be a
3780 lambda expression: this lambda expression must take one argument,
3781 the value to adjust, and return the new value as a string.
3783 For example, this element will allow the property \"Remaining\"
3784 to be updated wrt the relation between the \"Effort\" property
3785 and the clock summary:
3787 ((\"Remaining\" (lambda(value)
3788 (let ((clocksum (org-clock-sum-current-item))
3789 (effort (org-duration-string-to-minutes
3790 (org-entry-get (point) \"Effort\"))))
3791 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3792 :group 'org-properties
3793 :version "24.1"
3794 :type '(alist :key-type (string :tag "Property")
3795 :value-type (function :tag "Function")))
3797 (defcustom org-use-property-inheritance nil
3798 "Non-nil means properties apply also for sublevels.
3800 This setting is chiefly used during property searches. Turning it on can
3801 cause significant overhead when doing a search, which is why it is not
3802 on by default.
3804 When nil, only the properties directly given in the current entry count.
3805 When t, every property is inherited. The value may also be a list of
3806 properties that should have inheritance, or a regular expression matching
3807 properties that should be inherited.
3809 However, note that some special properties use inheritance under special
3810 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3811 and the properties ending in \"_ALL\" when they are used as descriptor
3812 for valid values of a property.
3814 Note for programmers:
3815 When querying an entry with `org-entry-get', you can control if inheritance
3816 should be used. By default, `org-entry-get' looks only at the local
3817 properties. You can request inheritance by setting the inherit argument
3818 to t (to force inheritance) or to `selective' (to respect the setting
3819 in this variable)."
3820 :group 'org-properties
3821 :type '(choice
3822 (const :tag "Not" nil)
3823 (const :tag "Always" t)
3824 (repeat :tag "Specific properties" (string :tag "Property"))
3825 (regexp :tag "Properties matched by regexp")))
3827 (defun org-property-inherit-p (property)
3828 "Check if PROPERTY is one that should be inherited."
3829 (cond
3830 ((eq org-use-property-inheritance t) t)
3831 ((not org-use-property-inheritance) nil)
3832 ((stringp org-use-property-inheritance)
3833 (string-match org-use-property-inheritance property))
3834 ((listp org-use-property-inheritance)
3835 (member property org-use-property-inheritance))
3836 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3838 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3839 "The default column format, if no other format has been defined.
3840 This variable can be set on the per-file basis by inserting a line
3842 #+COLUMNS: %25ITEM ....."
3843 :group 'org-properties
3844 :type 'string)
3846 (defcustom org-columns-ellipses ".."
3847 "The ellipses to be used when a field in column view is truncated.
3848 When this is the empty string, as many characters as possible are shown,
3849 but then there will be no visual indication that the field has been truncated.
3850 When this is a string of length N, the last N characters of a truncated
3851 field are replaced by this string. If the column is narrower than the
3852 ellipses string, only part of the ellipses string will be shown."
3853 :group 'org-properties
3854 :type 'string)
3856 (defconst org-global-properties-fixed
3857 '(("VISIBILITY_ALL" . "folded children content all")
3858 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3859 "List of property/value pairs that can be inherited by any entry.
3861 These are fixed values, for the preset properties. The user variable
3862 that can be used to add to this list is `org-global-properties'.
3864 The entries in this list are cons cells where the car is a property
3865 name and cdr is a string with the value. If the value represents
3866 multiple items like an \"_ALL\" property, separate the items by
3867 spaces.")
3869 (defcustom org-global-properties nil
3870 "List of property/value pairs that can be inherited by any entry.
3872 This list will be combined with the constant `org-global-properties-fixed'.
3874 The entries in this list are cons cells where the car is a property
3875 name and cdr is a string with the value.
3877 You can set buffer-local values for the same purpose in the variable
3878 `org-file-properties' this by adding lines like
3880 #+PROPERTY: NAME VALUE"
3881 :group 'org-properties
3882 :type '(repeat
3883 (cons (string :tag "Property")
3884 (string :tag "Value"))))
3886 (defvar-local org-file-properties nil
3887 "List of property/value pairs that can be inherited by any entry.
3888 Valid for the current buffer.
3889 This variable is populated from #+PROPERTY lines.")
3891 (defgroup org-agenda nil
3892 "Options concerning agenda views in Org mode."
3893 :tag "Org Agenda"
3894 :group 'org)
3896 (defvar-local org-category nil
3897 "Variable used by org files to set a category for agenda display.
3898 Such files should use a file variable to set it, for example
3900 # -*- mode: org; org-category: \"ELisp\"
3902 or contain a special line
3904 #+CATEGORY: ELisp
3906 If the file does not specify a category, then file's base name
3907 is used instead.")
3908 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3910 (defcustom org-agenda-files nil
3911 "The files to be used for agenda display.
3913 If an entry is a directory, all files in that directory that are matched
3914 by `org-agenda-file-regexp' will be part of the file list.
3916 If the value of the variable is not a list but a single file name, then
3917 the list of agenda files is actually stored and maintained in that file,
3918 one agenda file per line. In this file paths can be given relative to
3919 `org-directory'. Tilde expansion and environment variable substitution
3920 are also made.
3922 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3923 and removed with `\\[org-remove-file]'."
3924 :group 'org-agenda
3925 :type '(choice
3926 (repeat :tag "List of files and directories" file)
3927 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3929 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3930 "Regular expression to match files for `org-agenda-files'.
3931 If any element in the list in that variable contains a directory instead
3932 of a normal file, all files in that directory that are matched by this
3933 regular expression will be included."
3934 :group 'org-agenda
3935 :type 'regexp)
3937 (defcustom org-agenda-text-search-extra-files nil
3938 "List of extra files to be searched by text search commands.
3939 These files will be searched in addition to the agenda files by the
3940 commands `org-search-view' (`\\[org-agenda] s') \
3941 and `org-occur-in-agenda-files'.
3942 Note that these files will only be searched for text search commands,
3943 not for the other agenda views like todo lists, tag searches or the weekly
3944 agenda. This variable is intended to list notes and possibly archive files
3945 that should also be searched by these two commands.
3946 In fact, if the first element in the list is the symbol `agenda-archives',
3947 then all archive files of all agenda files will be added to the search
3948 scope."
3949 :group 'org-agenda
3950 :type '(set :greedy t
3951 (const :tag "Agenda Archives" agenda-archives)
3952 (repeat :inline t (file))))
3954 (defvaralias 'org-agenda-multi-occur-extra-files
3955 'org-agenda-text-search-extra-files)
3957 (defcustom org-agenda-skip-unavailable-files nil
3958 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3959 A nil value means to remove them, after a query, from the list."
3960 :group 'org-agenda
3961 :type 'boolean)
3963 (defcustom org-calendar-to-agenda-key [?c]
3964 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3965 The command `org-calendar-goto-agenda' will be bound to this key. The
3966 default is the character `c' because then `c' can be used to switch back and
3967 forth between agenda and calendar."
3968 :group 'org-agenda
3969 :type 'sexp)
3971 (defcustom org-calendar-insert-diary-entry-key [?i]
3972 "The key to be installed in `calendar-mode-map' for adding diary entries.
3973 This option is irrelevant until `org-agenda-diary-file' has been configured
3974 to point to an Org file. When that is the case, the command
3975 `org-agenda-diary-entry' will be bound to the key given here, by default
3976 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3977 if you want to continue doing this, you need to change this to a different
3978 key."
3979 :group 'org-agenda
3980 :type 'sexp)
3982 (defcustom org-agenda-diary-file 'diary-file
3983 "File to which to add new entries with the `i' key in agenda and calendar.
3984 When this is the symbol `diary-file', the functionality in the Emacs
3985 calendar will be used to add entries to the `diary-file'. But when this
3986 points to a file, `org-agenda-diary-entry' will be used instead."
3987 :group 'org-agenda
3988 :type '(choice
3989 (const :tag "The standard Emacs diary file" diary-file)
3990 (file :tag "Special Org file diary entries")))
3992 (eval-after-load "calendar"
3993 '(progn
3994 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3995 'org-calendar-goto-agenda)
3996 (add-hook 'calendar-mode-hook
3997 (lambda ()
3998 (unless (eq org-agenda-diary-file 'diary-file)
3999 (define-key calendar-mode-map
4000 org-calendar-insert-diary-entry-key
4001 'org-agenda-diary-entry))))))
4003 (defgroup org-latex nil
4004 "Options for embedding LaTeX code into Org mode."
4005 :tag "Org LaTeX"
4006 :group 'org)
4008 (defcustom org-format-latex-options
4009 '(:foreground default :background default :scale 1.0
4010 :html-foreground "Black" :html-background "Transparent"
4011 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
4012 "Options for creating images from LaTeX fragments.
4013 This is a property list with the following properties:
4014 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
4015 `default' means use the foreground of the default face.
4016 `auto' means use the foreground from the text face.
4017 :background the background color, or \"Transparent\".
4018 `default' means use the background of the default face.
4019 `auto' means use the background from the text face.
4020 :scale a scaling factor for the size of the images, to get more pixels
4021 :html-foreground, :html-background, :html-scale
4022 the same numbers for HTML export.
4023 :matchers a list indicating which matchers should be used to
4024 find LaTeX fragments. Valid members of this list are:
4025 \"begin\" find environments
4026 \"$1\" find single characters surrounded by $.$
4027 \"$\" find math expressions surrounded by $...$
4028 \"$$\" find math expressions surrounded by $$....$$
4029 \"\\(\" find math expressions surrounded by \\(...\\)
4030 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4031 :group 'org-latex
4032 :type 'plist)
4034 (defcustom org-format-latex-signal-error t
4035 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4036 When nil, just push out a message."
4037 :group 'org-latex
4038 :version "24.1"
4039 :type 'boolean)
4041 (defcustom org-latex-to-mathml-jar-file nil
4042 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4043 Use this to specify additional executable file say a jar file.
4045 When using MathToWeb as the converter, specify the full-path to
4046 your mathtoweb.jar file."
4047 :group 'org-latex
4048 :version "24.1"
4049 :type '(choice
4050 (const :tag "None" nil)
4051 (file :tag "JAR file" :must-match t)))
4053 (defcustom org-latex-to-mathml-convert-command nil
4054 "Command to convert LaTeX fragments to MathML.
4055 Replace format-specifiers in the command as noted below and use
4056 `shell-command' to convert LaTeX to MathML.
4057 %j: Executable file in fully expanded form as specified by
4058 `org-latex-to-mathml-jar-file'.
4059 %I: Input LaTeX file in fully expanded form.
4060 %i: The latex fragment to be converted.
4061 %o: Output MathML file.
4063 This command is used by `org-create-math-formula'.
4065 When using MathToWeb as the converter, set this option to
4066 \"java -jar %j -unicode -force -df %o %I\".
4068 When using LaTeXML set this option to
4069 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4070 :group 'org-latex
4071 :version "24.1"
4072 :type '(choice
4073 (const :tag "None" nil)
4074 (string :tag "\nShell command")))
4076 (defcustom org-preview-latex-default-process 'dvipng
4077 "The default process to convert LaTeX fragments to image files.
4078 All available processes and theirs documents can be found in
4079 `org-preview-latex-process-alist', which see."
4080 :group 'org-latex
4081 :version "25.2"
4082 :package-version '(Org . "9.0")
4083 :type 'symbol)
4085 (defcustom org-preview-latex-process-alist
4086 '((dvipng
4087 :programs ("latex" "dvipng")
4088 :description "dvi > png"
4089 :message "you need to install the programs: latex and dvipng."
4090 :image-input-type "dvi"
4091 :image-output-type "png"
4092 :image-size-adjust (1.0 . 1.0)
4093 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4094 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
4095 (dvisvgm
4096 :programs ("latex" "dvisvgm")
4097 :description "dvi > svg"
4098 :message "you need to install the programs: latex and dvisvgm."
4099 :use-xcolor t
4100 :image-input-type "dvi"
4101 :image-output-type "svg"
4102 :image-size-adjust (1.7 . 1.5)
4103 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4104 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
4105 (imagemagick
4106 :programs ("latex" "convert")
4107 :description "pdf > png"
4108 :message "you need to install the programs: latex and imagemagick."
4109 :use-xcolor t
4110 :image-input-type "pdf"
4111 :image-output-type "png"
4112 :image-size-adjust (1.0 . 1.0)
4113 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4114 :image-converter
4115 ("convert -density %D -trim -antialias %f -quality 100 %O")))
4116 "Definitions of external processes for LaTeX previewing.
4117 Org mode can use some external commands to generate TeX snippet's images for
4118 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4119 `org-create-formula-image' how to call them.
4121 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4122 PROPERTIES accepts the following attributes:
4124 :programs list of strings, required programs.
4125 :description string, describe the process.
4126 :message string, message it when required programs cannot be found.
4127 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4128 :image-output-type string, output file type of image converter (e.g., \"png\").
4129 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4130 deal with background and foreground color of image.
4131 Otherwise, dvipng style background and foregroud color
4132 format are generated. You may then refer to them in
4133 command options with \"%F\" and \"%B\".
4134 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4135 image size showed in buffer and the cdr element is for
4136 HTML file. This option is only useful for process
4137 developers, users should use variable
4138 `org-format-latex-options' instead.
4139 :post-clean list of strings, files matched are to be cleaned up once
4140 the image is generated. When nil, the files with \".dvi\",
4141 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4142 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4143 be cleaned up.
4144 :latex-header list of strings, the LaTeX header of the snippet file.
4145 When nil, the fallback value is used instead, which is
4146 controlled by `org-format-latex-header',
4147 `org-latex-default-packages-alist' and
4148 `org-latex-packages-alist', which see.
4149 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4150 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4151 replaced with values defined below.
4152 :image-converter list of image converter commands strings. Each of them is
4153 given to the shell and supports any of the following
4154 place-holders defined below.
4156 Place-holders used by `:image-converter' and `:latex-compiler':
4158 %f input file name
4159 %b base name of input file
4160 %o base directory of input file
4161 %O absolute output file name
4163 Place-holders only used by `:image-converter':
4165 %F foreground of image
4166 %B background of image
4167 %D dpi, which is used to adjust image size by some processing commands.
4168 %S the image size scale ratio, which is used to adjust image size by some
4169 processing commands."
4170 :group 'org-latex
4171 :version "25.2"
4172 :package-version '(Org . "9.0")
4173 :type '(alist :tag "LaTeX to image backends"
4174 :value-type (plist)))
4176 (defcustom org-preview-latex-image-directory "ltximg/"
4177 "Path to store latex preview images.
4178 A relative path here creates many directories relative to the
4179 processed org files paths. An absolute path puts all preview
4180 images at the same place."
4181 :group 'org-latex
4182 :version "25.2"
4183 :package-version '(Org . "9.0")
4184 :type 'string)
4186 (defun org-format-latex-mathml-available-p ()
4187 "Return t if `org-latex-to-mathml-convert-command' is usable."
4188 (save-match-data
4189 (when (and (boundp 'org-latex-to-mathml-convert-command)
4190 org-latex-to-mathml-convert-command)
4191 (let ((executable (car (split-string
4192 org-latex-to-mathml-convert-command))))
4193 (when (executable-find executable)
4194 (if (string-match
4195 "%j" org-latex-to-mathml-convert-command)
4196 (file-readable-p org-latex-to-mathml-jar-file)
4197 t))))))
4199 (defcustom org-format-latex-header "\\documentclass{article}
4200 \\usepackage[usenames]{color}
4201 \[PACKAGES]
4202 \[DEFAULT-PACKAGES]
4203 \\pagestyle{empty} % do not remove
4204 % The settings below are copied from fullpage.sty
4205 \\setlength{\\textwidth}{\\paperwidth}
4206 \\addtolength{\\textwidth}{-3cm}
4207 \\setlength{\\oddsidemargin}{1.5cm}
4208 \\addtolength{\\oddsidemargin}{-2.54cm}
4209 \\setlength{\\evensidemargin}{\\oddsidemargin}
4210 \\setlength{\\textheight}{\\paperheight}
4211 \\addtolength{\\textheight}{-\\headheight}
4212 \\addtolength{\\textheight}{-\\headsep}
4213 \\addtolength{\\textheight}{-\\footskip}
4214 \\addtolength{\\textheight}{-3cm}
4215 \\setlength{\\topmargin}{1.5cm}
4216 \\addtolength{\\topmargin}{-2.54cm}"
4217 "The document header used for processing LaTeX fragments.
4218 It is imperative that this header make sure that no page number
4219 appears on the page. The package defined in the variables
4220 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4221 will either replace the placeholder \"[PACKAGES]\" in this
4222 header, or they will be appended."
4223 :group 'org-latex
4224 :type 'string)
4226 (defun org-set-packages-alist (var val)
4227 "Set the packages alist and make sure it has 3 elements per entry."
4228 (set var (mapcar (lambda (x)
4229 (if (and (consp x) (= (length x) 2))
4230 (list (car x) (nth 1 x) t)
4232 val)))
4234 (defun org-get-packages-alist (var)
4235 "Get the packages alist and make sure it has 3 elements per entry."
4236 (mapcar (lambda (x)
4237 (if (and (consp x) (= (length x) 2))
4238 (list (car x) (nth 1 x) t)
4240 (default-value var)))
4242 (defcustom org-latex-default-packages-alist
4243 '(("AUTO" "inputenc" t ("pdflatex"))
4244 ("T1" "fontenc" t ("pdflatex"))
4245 ("" "graphicx" t)
4246 ("" "grffile" t)
4247 ("" "longtable" nil)
4248 ("" "wrapfig" nil)
4249 ("" "rotating" nil)
4250 ("normalem" "ulem" t)
4251 ("" "amsmath" t)
4252 ("" "textcomp" t)
4253 ("" "amssymb" t)
4254 ("" "capt-of" nil)
4255 ("" "hyperref" nil))
4256 "Alist of default packages to be inserted in the header.
4258 Change this only if one of the packages here causes an
4259 incompatibility with another package you are using.
4261 The packages in this list are needed by one part or another of
4262 Org mode to function properly:
4264 - inputenc, fontenc: for basic font and character selection
4265 - graphicx: for including images
4266 - grffile: allow periods and spaces in graphics file names
4267 - longtable: For multipage tables
4268 - wrapfig: for figure placement
4269 - rotating: for sideways figures and tables
4270 - ulem: for underline and strike-through
4271 - amsmath: for subscript and superscript and math environments
4272 - textcomp, amssymb: for various symbols used
4273 for interpreting the entities in `org-entities'. You can skip
4274 some of these packages if you don't use any of their symbols.
4275 - capt-of: for captions outside of floats
4276 - hyperref: for cross references
4278 Therefore you should not modify this variable unless you know
4279 what you are doing. The one reason to change it anyway is that
4280 you might be loading some other package that conflicts with one
4281 of the default packages. Each element is either a cell or
4282 a string.
4284 A cell is of the format
4286 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4288 If SNIPPET-FLAG is non-nil, the package also needs to be included
4289 when compiling LaTeX snippets into images for inclusion into
4290 non-LaTeX output. COMPILERS is a list of compilers that should
4291 include the package, see `org-latex-compiler'. If the document
4292 compiler is not in the list, and the list is non-nil, the package
4293 will not be inserted in the final document.
4295 A string will be inserted as-is in the header of the document."
4296 :group 'org-latex
4297 :group 'org-export-latex
4298 :set 'org-set-packages-alist
4299 :get 'org-get-packages-alist
4300 :version "25.2"
4301 :package-version '(Org . "8.3")
4302 :type '(repeat
4303 (choice
4304 (list :tag "options/package pair"
4305 (string :tag "options")
4306 (string :tag "package")
4307 (boolean :tag "Snippet"))
4308 (string :tag "A line of LaTeX"))))
4310 (defcustom org-latex-packages-alist nil
4311 "Alist of packages to be inserted in every LaTeX header.
4313 These will be inserted after `org-latex-default-packages-alist'.
4314 Each element is either a cell or a string.
4316 A cell is of the format:
4318 (\"options\" \"package\" SNIPPET-FLAG)
4320 SNIPPET-FLAG, when non-nil, indicates that this package is also
4321 needed when turning LaTeX snippets into images for inclusion into
4322 non-LaTeX output.
4324 A string will be inserted as-is in the header of the document.
4326 Make sure that you only list packages here which:
4328 - you want in every file;
4329 - do not conflict with the setup in `org-format-latex-header';
4330 - do not conflict with the default packages in
4331 `org-latex-default-packages-alist'."
4332 :group 'org-latex
4333 :group 'org-export-latex
4334 :set 'org-set-packages-alist
4335 :get 'org-get-packages-alist
4336 :type '(repeat
4337 (choice
4338 (list :tag "options/package pair"
4339 (string :tag "options")
4340 (string :tag "package")
4341 (boolean :tag "Snippet"))
4342 (string :tag "A line of LaTeX"))))
4344 (defgroup org-appearance nil
4345 "Settings for Org mode appearance."
4346 :tag "Org Appearance"
4347 :group 'org)
4349 (defcustom org-level-color-stars-only nil
4350 "Non-nil means fontify only the stars in each headline.
4351 When nil, the entire headline is fontified.
4352 Changing it requires restart of `font-lock-mode' to become effective
4353 also in regions already fontified."
4354 :group 'org-appearance
4355 :type 'boolean)
4357 (defcustom org-hide-leading-stars nil
4358 "Non-nil means hide the first N-1 stars in a headline.
4359 This works by using the face `org-hide' for these stars. This
4360 face is white for a light background, and black for a dark
4361 background. You may have to customize the face `org-hide' to
4362 make this work.
4363 Changing it requires restart of `font-lock-mode' to become effective
4364 also in regions already fontified.
4365 You may also set this on a per-file basis by adding one of the following
4366 lines to the buffer:
4368 #+STARTUP: hidestars
4369 #+STARTUP: showstars"
4370 :group 'org-appearance
4371 :type 'boolean)
4373 (defcustom org-hidden-keywords nil
4374 "List of symbols corresponding to keywords to be hidden the org buffer.
4375 For example, a value \\='(title) for this list will make the document's title
4376 appear in the buffer without the initial #+TITLE: keyword."
4377 :group 'org-appearance
4378 :version "24.1"
4379 :type '(set (const :tag "#+AUTHOR" author)
4380 (const :tag "#+DATE" date)
4381 (const :tag "#+EMAIL" email)
4382 (const :tag "#+TITLE" title)))
4384 (defcustom org-custom-properties nil
4385 "List of properties (as strings) with a special meaning.
4386 The default use of these custom properties is to let the user
4387 hide them with `org-toggle-custom-properties-visibility'."
4388 :group 'org-properties
4389 :group 'org-appearance
4390 :version "24.3"
4391 :type '(repeat (string :tag "Property Name")))
4393 (defcustom org-fontify-done-headline nil
4394 "Non-nil means change the face of a headline if it is marked DONE.
4395 Normally, only the TODO/DONE keyword indicates the state of a headline.
4396 When this is non-nil, the headline after the keyword is set to the
4397 `org-headline-done' as an additional indication."
4398 :group 'org-appearance
4399 :type 'boolean)
4401 (defcustom org-fontify-emphasized-text t
4402 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4403 Changing this variable requires a restart of Emacs to take effect."
4404 :group 'org-appearance
4405 :type 'boolean)
4407 (defcustom org-fontify-whole-heading-line nil
4408 "Non-nil means fontify the whole line for headings.
4409 This is useful when setting a background color for the
4410 org-level-* faces."
4411 :group 'org-appearance
4412 :type 'boolean)
4414 (defcustom org-highlight-latex-and-related nil
4415 "Non-nil means highlight LaTeX related syntax in the buffer.
4416 When non nil, the value should be a list containing any of the
4417 following symbols:
4418 `latex' Highlight LaTeX snippets and environments.
4419 `script' Highlight subscript and superscript.
4420 `entities' Highlight entities."
4421 :group 'org-appearance
4422 :version "24.4"
4423 :package-version '(Org . "8.0")
4424 :type '(choice
4425 (const :tag "No highlighting" nil)
4426 (set :greedy t :tag "Highlight"
4427 (const :tag "LaTeX snippets and environments" latex)
4428 (const :tag "Subscript and superscript" script)
4429 (const :tag "Entities" entities))))
4431 (defcustom org-hide-emphasis-markers nil
4432 "Non-nil mean font-lock should hide the emphasis marker characters."
4433 :group 'org-appearance
4434 :type 'boolean)
4436 (defcustom org-hide-macro-markers nil
4437 "Non-nil mean font-lock should hide the brackets marking macro calls."
4438 :group 'org-appearance
4439 :type 'boolean)
4441 (defcustom org-pretty-entities nil
4442 "Non-nil means show entities as UTF8 characters.
4443 When nil, the \\name form remains in the buffer."
4444 :group 'org-appearance
4445 :version "24.1"
4446 :type 'boolean)
4448 (defcustom org-pretty-entities-include-sub-superscripts t
4449 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4450 :group 'org-appearance
4451 :version "24.1"
4452 :type 'boolean)
4454 (defvar org-emph-re nil
4455 "Regular expression for matching emphasis.
4456 After a match, the match groups contain these elements:
4457 0 The match of the full regular expression, including the characters
4458 before and after the proper match
4459 1 The character before the proper match, or empty at beginning of line
4460 2 The proper match, including the leading and trailing markers
4461 3 The leading marker like * or /, indicating the type of highlighting
4462 4 The text between the emphasis markers, not including the markers
4463 5 The character after the match, empty at the end of a line")
4465 (defvar org-verbatim-re nil
4466 "Regular expression for matching verbatim text.")
4468 (defvar org-emphasis-regexp-components) ; defined just below
4469 (defvar org-emphasis-alist) ; defined just below
4470 (defun org-set-emph-re (var val)
4471 "Set variable and compute the emphasis regular expression."
4472 (set var val)
4473 (when (and (boundp 'org-emphasis-alist)
4474 (boundp 'org-emphasis-regexp-components)
4475 org-emphasis-alist org-emphasis-regexp-components)
4476 (pcase-let*
4477 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4478 (body (if (<= nl 0) body
4479 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4480 (template
4481 (format (concat "\\([%s]\\|^\\)" ;before markers
4482 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4483 "\\([%s]\\|$\\)") ;after markers
4484 pre border border body border post)))
4485 (setq org-emph-re (format template "*/_+"))
4486 (setq org-verbatim-re (format template "=~")))))
4488 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4489 ;; set this option proved cumbersome. See this message/thread:
4490 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4491 (defvar org-emphasis-regexp-components
4492 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4493 "Components used to build the regular expression for emphasis.
4494 This is a list with five entries. Terminology: In an emphasis string
4495 like \" *strong word* \", we call the initial space PREMATCH, the final
4496 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4497 and \"trong wor\" is the body. The different components in this variable
4498 specify what is allowed/forbidden in each part:
4500 pre Chars allowed as prematch. Beginning of line will be allowed too.
4501 post Chars allowed as postmatch. End of line will be allowed too.
4502 border The chars *forbidden* as border characters.
4503 body-regexp A regexp like \".\" to match a body character. Don't use
4504 non-shy groups here, and don't allow newline here.
4505 newline The maximum number of newlines allowed in an emphasis exp.
4507 You need to reload Org or to restart Emacs after customizing this.")
4509 (defcustom org-emphasis-alist
4510 '(("*" bold)
4511 ("/" italic)
4512 ("_" underline)
4513 ("=" org-verbatim verbatim)
4514 ("~" org-code verbatim)
4515 ("+" (:strike-through t)))
4516 "Alist of characters and faces to emphasize text.
4517 Text starting and ending with a special character will be emphasized,
4518 for example *bold*, _underlined_ and /italic/. This variable sets the
4519 marker characters and the face to be used by font-lock for highlighting
4520 in Org buffers.
4522 You need to reload Org or to restart Emacs after customizing this."
4523 :group 'org-appearance
4524 :set 'org-set-emph-re
4525 :version "24.4"
4526 :package-version '(Org . "8.0")
4527 :type '(repeat
4528 (list
4529 (string :tag "Marker character")
4530 (choice
4531 (face :tag "Font-lock-face")
4532 (plist :tag "Face property list"))
4533 (option (const verbatim)))))
4535 (defvar org-protecting-blocks '("src" "example" "export")
4536 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4537 This is needed for font-lock setup.")
4539 ;;; Functions and variables from their packages
4540 ;; Declared here to avoid compiler warnings
4541 (defvar mark-active)
4543 ;; Various packages
4544 (declare-function calc-eval "calc" (str &optional separator &rest args))
4545 (declare-function calendar-forward-day "cal-move" (arg))
4546 (declare-function calendar-goto-date "cal-move" (date))
4547 (declare-function calendar-goto-today "cal-move" ())
4548 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4549 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4550 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4551 (declare-function cdlatex-tab "ext:cdlatex" ())
4552 (declare-function dired-get-filename
4553 "dired"
4554 (&optional localp no-error-if-not-filep))
4555 (declare-function iswitchb-read-buffer
4556 "iswitchb"
4557 (prompt &optional
4558 default require-match _predicate start matches-set))
4559 (declare-function org-agenda-change-all-lines
4560 "org-agenda"
4561 (newhead hdmarker &optional fixface just-this))
4562 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4563 "org-agenda"
4564 (&optional end))
4565 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4566 (declare-function org-agenda-format-item
4567 "org-agenda"
4568 (extra txt &optional level category tags dotime
4569 remove-re habitp))
4570 (declare-function org-agenda-maybe-redo "org-agenda" ())
4571 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4572 (declare-function org-agenda-save-markers-for-cut-and-paste
4573 "org-agenda"
4574 (beg end))
4575 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4576 (declare-function org-agenda-skip "org-agenda" ())
4577 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4578 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4579 (declare-function org-indent-mode "org-indent" (&optional arg))
4580 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4581 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4582 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4583 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4584 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4585 (declare-function parse-time-string "parse-time" (string))
4586 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4588 (defvar align-mode-rules-list)
4589 (defvar calc-embedded-close-formula)
4590 (defvar calc-embedded-open-formula)
4591 (defvar calc-embedded-open-mode)
4592 (defvar font-lock-unfontify-region-function)
4593 (defvar iswitchb-temp-buflist)
4594 (defvar org-agenda-tags-todo-honor-ignore-options)
4595 (defvar remember-data-file)
4596 (defvar texmathp-why)
4598 ;;;###autoload
4599 (defun turn-on-orgtbl ()
4600 "Unconditionally turn on `orgtbl-mode'."
4601 (require 'org-table)
4602 (orgtbl-mode 1))
4604 (defun org-at-table-p (&optional table-type)
4605 "Non-nil if the cursor is inside an Org table.
4606 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4607 If `org-enable-table-editor' is nil, return nil unconditionally."
4608 (and
4609 org-enable-table-editor
4610 (save-excursion
4611 (beginning-of-line)
4612 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4613 (or (not (derived-mode-p 'org-mode))
4614 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4615 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4617 (defun org-at-table.el-p ()
4618 "Non-nil when point is at a table.el table."
4619 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4620 (let ((element (org-element-at-point)))
4621 (and (eq (org-element-type element) 'table)
4622 (eq (org-element-property :type element) 'table.el)))))
4624 (defun org-at-table-hline-p ()
4625 "Non-nil when point is inside a hline in a table.
4626 Assume point is already in a table. If `org-enable-table-editor'
4627 is nil, return nil unconditionally."
4628 (and org-enable-table-editor
4629 (save-excursion
4630 (beginning-of-line)
4631 (looking-at org-table-hline-regexp))))
4633 (defun org-table-map-tables (function &optional quietly)
4634 "Apply FUNCTION to the start of all tables in the buffer."
4635 (org-with-wide-buffer
4636 (goto-char (point-min))
4637 (while (re-search-forward org-table-any-line-regexp nil t)
4638 (unless quietly
4639 (message "Mapping tables: %d%%"
4640 (floor (* 100.0 (point)) (buffer-size))))
4641 (beginning-of-line 1)
4642 (when (and (looking-at org-table-line-regexp)
4643 ;; Exclude tables in src/example/verbatim/clocktable blocks
4644 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4645 (save-excursion (funcall function))
4646 (or (looking-at org-table-line-regexp)
4647 (forward-char 1)))
4648 (re-search-forward org-table-any-border-regexp nil 1)))
4649 (unless quietly (message "Mapping tables: done")))
4651 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4652 (declare-function org-clock-update-mode-line "org-clock" ())
4653 (declare-function org-resolve-clocks "org-clock"
4654 (&optional also-non-dangling-p prompt last-valid))
4656 (defun org-at-TBLFM-p (&optional pos)
4657 "Non-nil when point (or POS) is in #+TBLFM line."
4658 (save-excursion
4659 (goto-char (or pos (point)))
4660 (beginning-of-line)
4661 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4662 (eq (org-element-type (org-element-at-point)) 'table))))
4664 (defvar org-clock-start-time)
4665 (defvar org-clock-marker (make-marker)
4666 "Marker recording the last clock-in.")
4667 (defvar org-clock-hd-marker (make-marker)
4668 "Marker recording the last clock-in, but the headline position.")
4669 (defvar org-clock-heading ""
4670 "The heading of the current clock entry.")
4671 (defun org-clock-is-active ()
4672 "Return the buffer where the clock is currently running.
4673 Return nil if no clock is running."
4674 (marker-buffer org-clock-marker))
4676 (defun org-check-running-clock ()
4677 "Check if the current buffer contains the running clock.
4678 If yes, offer to stop it and to save the buffer with the changes."
4679 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4680 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4681 (buffer-name))))
4682 (org-clock-out)
4683 (when (y-or-n-p "Save changed buffer?")
4684 (save-buffer))))
4686 (defun org-clocktable-try-shift (dir n)
4687 "Check if this line starts a clock table, if yes, shift the time block."
4688 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4689 (org-clocktable-shift dir n)))
4691 ;;;###autoload
4692 (defun org-clock-persistence-insinuate ()
4693 "Set up hooks for clock persistence."
4694 (require 'org-clock)
4695 (add-hook 'org-mode-hook 'org-clock-load)
4696 (add-hook 'kill-emacs-hook 'org-clock-save))
4698 (defgroup org-archive nil
4699 "Options concerning archiving in Org mode."
4700 :tag "Org Archive"
4701 :group 'org-structure)
4703 (defcustom org-archive-location "%s_archive::"
4704 "The location where subtrees should be archived.
4706 The value of this variable is a string, consisting of two parts,
4707 separated by a double-colon. The first part is a filename and
4708 the second part is a headline.
4710 When the filename is omitted, archiving happens in the same file.
4711 %s in the filename will be replaced by the current file
4712 name (without the directory part). Archiving to a different file
4713 is useful to keep archived entries from contributing to the
4714 Org Agenda.
4716 The archived entries will be filed as subtrees of the specified
4717 headline. When the headline is omitted, the subtrees are simply
4718 filed away at the end of the file, as top-level entries. Also in
4719 the heading you can use %s to represent the file name, this can be
4720 useful when using the same archive for a number of different files.
4722 Here are a few examples:
4723 \"%s_archive::\"
4724 If the current file is Projects.org, archive in file
4725 Projects.org_archive, as top-level trees. This is the default.
4727 \"::* Archived Tasks\"
4728 Archive in the current file, under the top-level headline
4729 \"* Archived Tasks\".
4731 \"~/org/archive.org::\"
4732 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4734 \"~/org/archive.org::* From %s\"
4735 Archive in file ~/org/archive.org (absolute path), under headlines
4736 \"From FILENAME\" where file name is the current file name.
4738 \"~/org/datetree.org::datetree/* Finished Tasks\"
4739 The \"datetree/\" string is special, signifying to archive
4740 items to the datetree. Items are placed in either the CLOSED
4741 date of the item, or the current date if there is no CLOSED date.
4742 The heading will be a subentry to the current date. There doesn't
4743 need to be a heading, but there always needs to be a slash after
4744 datetree. For example, to store archived items directly in the
4745 datetree, use \"~/org/datetree.org::datetree/\".
4747 \"basement::** Finished Tasks\"
4748 Archive in file ./basement (relative path), as level 3 trees
4749 below the level 2 heading \"** Finished Tasks\".
4751 You may set this option on a per-file basis by adding to the buffer a
4752 line like
4754 #+ARCHIVE: basement::** Finished Tasks
4756 You may also define it locally for a subtree by setting an ARCHIVE property
4757 in the entry. If such a property is found in an entry, or anywhere up
4758 the hierarchy, it will be used."
4759 :group 'org-archive
4760 :type 'string)
4762 (defcustom org-agenda-skip-archived-trees t
4763 "Non-nil means the agenda will skip any items located in archived trees.
4764 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4765 variable is no longer recommended, you should leave it at the value t.
4766 Instead, use the key `v' to cycle the archives-mode in the agenda."
4767 :group 'org-archive
4768 :group 'org-agenda-skip
4769 :type 'boolean)
4771 (defcustom org-columns-skip-archived-trees t
4772 "Non-nil means ignore archived trees when creating column view."
4773 :group 'org-archive
4774 :group 'org-properties
4775 :type 'boolean)
4777 (defcustom org-cycle-open-archived-trees nil
4778 "Non-nil means `org-cycle' will open archived trees.
4779 An archived tree is a tree marked with the tag ARCHIVE.
4780 When nil, archived trees will stay folded. You can still open them with
4781 normal outline commands like `show-all', but not with the cycling commands."
4782 :group 'org-archive
4783 :group 'org-cycle
4784 :type 'boolean)
4786 (defcustom org-sparse-tree-open-archived-trees nil
4787 "Non-nil means sparse tree construction shows matches in archived trees.
4788 When nil, matches in these trees are highlighted, but the trees are kept in
4789 collapsed state."
4790 :group 'org-archive
4791 :group 'org-sparse-trees
4792 :type 'boolean)
4794 (defcustom org-sparse-tree-default-date-type nil
4795 "The default date type when building a sparse tree.
4796 When this is nil, a date is a scheduled or a deadline timestamp.
4797 Otherwise, these types are allowed:
4799 all: all timestamps
4800 active: only active timestamps (<...>)
4801 inactive: only inactive timestamps ([...])
4802 scheduled: only scheduled timestamps
4803 deadline: only deadline timestamps"
4804 :type '(choice (const :tag "Scheduled or deadline" nil)
4805 (const :tag "All timestamps" all)
4806 (const :tag "Only active timestamps" active)
4807 (const :tag "Only inactive timestamps" inactive)
4808 (const :tag "Only scheduled timestamps" scheduled)
4809 (const :tag "Only deadline timestamps" deadline)
4810 (const :tag "Only closed timestamps" closed))
4811 :version "25.2"
4812 :package-version '(Org . "8.3")
4813 :group 'org-sparse-trees)
4815 (defun org-cycle-hide-archived-subtrees (state)
4816 "Re-hide all archived subtrees after a visibility state change."
4817 (when (and (not org-cycle-open-archived-trees)
4818 (not (memq state '(overview folded))))
4819 (save-excursion
4820 (let* ((globalp (memq state '(contents all)))
4821 (beg (if globalp (point-min) (point)))
4822 (end (if globalp (point-max) (org-end-of-subtree t))))
4823 (org-hide-archived-subtrees beg end)
4824 (goto-char beg)
4825 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4826 (message "%s" (substitute-command-keys
4827 "Subtree is archived and stays closed. Use \
4828 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4830 (defun org-force-cycle-archived ()
4831 "Cycle subtree even if it is archived."
4832 (interactive)
4833 (setq this-command 'org-cycle)
4834 (let ((org-cycle-open-archived-trees t))
4835 (call-interactively 'org-cycle)))
4837 (defun org-hide-archived-subtrees (beg end)
4838 "Re-hide all archived subtrees after a visibility state change."
4839 (org-with-wide-buffer
4840 (let ((case-fold-search nil)
4841 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4842 (goto-char beg)
4843 ;; Include headline point is currently on.
4844 (beginning-of-line)
4845 (while (and (< (point) end) (re-search-forward re end t))
4846 (when (member org-archive-tag (org-get-tags))
4847 (org-flag-subtree t)
4848 (org-end-of-subtree t))))))
4850 (declare-function outline-end-of-heading "outline" ())
4851 (declare-function outline-flag-region "outline" (from to flag))
4852 (defun org-flag-subtree (flag)
4853 (save-excursion
4854 (org-back-to-heading t)
4855 (outline-end-of-heading)
4856 (outline-flag-region (point)
4857 (progn (org-end-of-subtree t) (point))
4858 flag)))
4860 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4862 ;; Declare Column View Code
4864 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4865 (declare-function org-columns-compute "org-colview" (property))
4867 ;; Declare ID code
4869 (declare-function org-id-store-link "org-id")
4870 (declare-function org-id-locations-load "org-id")
4871 (declare-function org-id-locations-save "org-id")
4872 (defvar org-id-track-globally)
4874 ;;; Variables for pre-computed regular expressions, all buffer local
4876 (defvar-local org-todo-regexp nil
4877 "Matches any of the TODO state keywords.
4878 Since TODO keywords are case-sensitive, `case-fold-search' is
4879 expected to be bound to nil when matching against this regexp.")
4881 (defvar-local org-not-done-regexp nil
4882 "Matches any of the TODO state keywords except the last one.
4883 Since TODO keywords are case-sensitive, `case-fold-search' is
4884 expected to be bound to nil when matching against this regexp.")
4886 (defvar-local org-not-done-heading-regexp nil
4887 "Matches a TODO headline that is not done.
4888 Since TODO keywords are case-sensitive, `case-fold-search' is
4889 expected to be bound to nil when matching against this regexp.")
4891 (defvar-local org-todo-line-regexp nil
4892 "Matches a headline and puts TODO state into group 2 if present.
4893 Since TODO keywords are case-sensitive, `case-fold-search' is
4894 expected to be bound to nil when matching against this regexp.")
4896 (defvar-local org-complex-heading-regexp nil
4897 "Matches a headline and puts everything into groups:
4899 group 1: Stars
4900 group 2: The TODO keyword, maybe
4901 group 3: Priority cookie
4902 group 4: True headline
4903 group 5: Tags
4905 Since TODO keywords are case-sensitive, `case-fold-search' is
4906 expected to be bound to nil when matching against this regexp.")
4908 (defvar-local org-complex-heading-regexp-format nil
4909 "Printf format to make regexp to match an exact headline.
4910 This regexp will match the headline of any node which has the
4911 exact headline text that is put into the format, but may have any
4912 TODO state, priority and tags.")
4914 (defvar-local org-todo-line-tags-regexp nil
4915 "Matches a headline and puts TODO state into group 2 if present.
4916 Also put tags into group 4 if tags are present.")
4918 (defconst org-plain-time-of-day-regexp
4919 (concat
4920 "\\(\\<[012]?[0-9]"
4921 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4922 "\\(--?"
4923 "\\(\\<[012]?[0-9]"
4924 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4925 "\\)?")
4926 "Regular expression to match a plain time or time range.
4927 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4928 groups carry important information:
4929 0 the full match
4930 1 the first time, range or not
4931 8 the second time, if it is a range.")
4933 (defconst org-plain-time-extension-regexp
4934 (concat
4935 "\\(\\<[012]?[0-9]"
4936 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4937 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4938 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4939 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4940 groups carry important information:
4941 0 the full match
4942 7 hours of duration
4943 9 minutes of duration")
4945 (defconst org-stamp-time-of-day-regexp
4946 (concat
4947 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4948 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4949 "\\(--?"
4950 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4951 "Regular expression to match a timestamp time or time range.
4952 After a match, the following groups carry important information:
4953 0 the full match
4954 1 date plus weekday, for back referencing to make sure both times are on the same day
4955 2 the first time, range or not
4956 4 the second time, if it is a range.")
4958 (defconst org-startup-options
4959 '(("fold" org-startup-folded t)
4960 ("overview" org-startup-folded t)
4961 ("nofold" org-startup-folded nil)
4962 ("showall" org-startup-folded nil)
4963 ("showeverything" org-startup-folded showeverything)
4964 ("content" org-startup-folded content)
4965 ("indent" org-startup-indented t)
4966 ("noindent" org-startup-indented nil)
4967 ("hidestars" org-hide-leading-stars t)
4968 ("showstars" org-hide-leading-stars nil)
4969 ("odd" org-odd-levels-only t)
4970 ("oddeven" org-odd-levels-only nil)
4971 ("align" org-startup-align-all-tables t)
4972 ("noalign" org-startup-align-all-tables nil)
4973 ("inlineimages" org-startup-with-inline-images t)
4974 ("noinlineimages" org-startup-with-inline-images nil)
4975 ("latexpreview" org-startup-with-latex-preview t)
4976 ("nolatexpreview" org-startup-with-latex-preview nil)
4977 ("customtime" org-display-custom-times t)
4978 ("logdone" org-log-done time)
4979 ("lognotedone" org-log-done note)
4980 ("nologdone" org-log-done nil)
4981 ("lognoteclock-out" org-log-note-clock-out t)
4982 ("nolognoteclock-out" org-log-note-clock-out nil)
4983 ("logrepeat" org-log-repeat state)
4984 ("lognoterepeat" org-log-repeat note)
4985 ("logdrawer" org-log-into-drawer t)
4986 ("nologdrawer" org-log-into-drawer nil)
4987 ("logstatesreversed" org-log-states-order-reversed t)
4988 ("nologstatesreversed" org-log-states-order-reversed nil)
4989 ("nologrepeat" org-log-repeat nil)
4990 ("logreschedule" org-log-reschedule time)
4991 ("lognotereschedule" org-log-reschedule note)
4992 ("nologreschedule" org-log-reschedule nil)
4993 ("logredeadline" org-log-redeadline time)
4994 ("lognoteredeadline" org-log-redeadline note)
4995 ("nologredeadline" org-log-redeadline nil)
4996 ("logrefile" org-log-refile time)
4997 ("lognoterefile" org-log-refile note)
4998 ("nologrefile" org-log-refile nil)
4999 ("fninline" org-footnote-define-inline t)
5000 ("nofninline" org-footnote-define-inline nil)
5001 ("fnlocal" org-footnote-section nil)
5002 ("fnauto" org-footnote-auto-label t)
5003 ("fnprompt" org-footnote-auto-label nil)
5004 ("fnconfirm" org-footnote-auto-label confirm)
5005 ("fnplain" org-footnote-auto-label plain)
5006 ("fnadjust" org-footnote-auto-adjust t)
5007 ("nofnadjust" org-footnote-auto-adjust nil)
5008 ("constcgs" constants-unit-system cgs)
5009 ("constSI" constants-unit-system SI)
5010 ("noptag" org-tag-persistent-alist nil)
5011 ("hideblocks" org-hide-block-startup t)
5012 ("nohideblocks" org-hide-block-startup nil)
5013 ("beamer" org-startup-with-beamer-mode t)
5014 ("entitiespretty" org-pretty-entities t)
5015 ("entitiesplain" org-pretty-entities nil))
5016 "Variable associated with STARTUP options for org-mode.
5017 Each element is a list of three items: the startup options (as written
5018 in the #+STARTUP line), the corresponding variable, and the value to set
5019 this variable to if the option is found. An optional forth element PUSH
5020 means to push this value onto the list in the variable.")
5022 (defcustom org-group-tags t
5023 "When non-nil (the default), use group tags.
5024 This can be turned on/off through `org-toggle-tags-groups'."
5025 :group 'org-tags
5026 :group 'org-startup
5027 :type 'boolean)
5029 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5031 (defun org-toggle-tags-groups ()
5032 "Toggle support for group tags.
5033 Support for group tags is controlled by the option
5034 `org-group-tags', which is non-nil by default."
5035 (interactive)
5036 (setq org-group-tags (not org-group-tags))
5037 (cond ((and (derived-mode-p 'org-agenda-mode)
5038 org-group-tags)
5039 (org-agenda-redo))
5040 ((derived-mode-p 'org-mode)
5041 (let ((org-inhibit-startup t)) (org-mode))))
5042 (message "Groups tags support has been turned %s"
5043 (if org-group-tags "on" "off")))
5045 (defun org-set-regexps-and-options (&optional tags-only)
5046 "Precompute regular expressions used in the current buffer.
5047 When optional argument TAGS-ONLY is non-nil, only compute tags
5048 related expressions."
5049 (when (derived-mode-p 'org-mode)
5050 (let ((alist (org--setup-collect-keywords
5051 (org-make-options-regexp
5052 (append '("FILETAGS" "TAGS" "SETUPFILE")
5053 (and (not tags-only)
5054 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5055 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5056 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5057 ;; Startup options. Get this early since it does change
5058 ;; behavior for other options (e.g., tags).
5059 (let ((startup (cdr (assq 'startup alist))))
5060 (dolist (option startup)
5061 (let ((entry (assoc-string option org-startup-options t)))
5062 (when entry
5063 (let ((var (nth 1 entry))
5064 (val (nth 2 entry)))
5065 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5066 (unless (listp (symbol-value var))
5067 (set (make-local-variable var) nil))
5068 (add-to-list var val)))))))
5069 (setq-local org-file-tags
5070 (mapcar #'org-add-prop-inherited
5071 (cdr (assq 'filetags alist))))
5072 (setq org-current-tag-alist
5073 (append org-tag-persistent-alist
5074 (let ((tags (cdr (assq 'tags alist))))
5075 (if tags (org-tag-string-to-alist tags)
5076 org-tag-alist))))
5077 (setq org-tag-groups-alist
5078 (org-tag-alist-to-groups org-current-tag-alist))
5079 (unless tags-only
5080 ;; File properties.
5081 (setq-local org-file-properties (cdr (assq 'property alist)))
5082 ;; Archive location.
5083 (let ((archive (cdr (assq 'archive alist))))
5084 (when archive (setq-local org-archive-location archive)))
5085 ;; Category.
5086 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5087 (when cat
5088 (setq-local org-category (intern cat))
5089 (setq-local org-file-properties
5090 (org--update-property-plist
5091 "CATEGORY" cat org-file-properties))))
5092 ;; Columns.
5093 (let ((column (cdr (assq 'columns alist))))
5094 (when column (setq-local org-columns-default-format column)))
5095 ;; Constants.
5096 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5097 ;; Link abbreviations.
5098 (let ((links (cdr (assq 'link alist))))
5099 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5100 ;; Priorities.
5101 (let ((priorities (cdr (assq 'priorities alist))))
5102 (when priorities
5103 (setq-local org-highest-priority (nth 0 priorities))
5104 (setq-local org-lowest-priority (nth 1 priorities))
5105 (setq-local org-default-priority (nth 2 priorities))))
5106 ;; Scripts.
5107 (let ((scripts (assq 'scripts alist)))
5108 (when scripts
5109 (setq-local org-use-sub-superscripts (cdr scripts))))
5110 ;; TODO keywords.
5111 (setq-local org-todo-kwd-alist nil)
5112 (setq-local org-todo-key-alist nil)
5113 (setq-local org-todo-key-trigger nil)
5114 (setq-local org-todo-keywords-1 nil)
5115 (setq-local org-done-keywords nil)
5116 (setq-local org-todo-heads nil)
5117 (setq-local org-todo-sets nil)
5118 (setq-local org-todo-log-states nil)
5119 (let ((todo-sequences
5120 (or (nreverse (cdr (assq 'todo alist)))
5121 (let ((d (default-value 'org-todo-keywords)))
5122 (if (not (stringp (car d))) d
5123 ;; XXX: Backward compatibility code.
5124 (list (cons org-todo-interpretation d)))))))
5125 (dolist (sequence todo-sequences)
5126 (let* ((sequence (or (run-hook-with-args-until-success
5127 'org-todo-setup-filter-hook sequence)
5128 sequence))
5129 (sequence-type (car sequence))
5130 (keywords (cdr sequence))
5131 (sep (member "|" keywords))
5132 names alist)
5133 (dolist (k (remove "|" keywords))
5134 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5136 (error "Invalid TODO keyword %s" k))
5137 (let ((name (match-string 1 k))
5138 (key (match-string 2 k))
5139 (log (org-extract-log-state-settings k)))
5140 (push name names)
5141 (push (cons name (and key (string-to-char key))) alist)
5142 (when log (push log org-todo-log-states))))
5143 (let* ((names (nreverse names))
5144 (done (if sep (org-remove-keyword-keys (cdr sep))
5145 (last names)))
5146 (head (car names))
5147 (tail (list sequence-type head (car done) (org-last done))))
5148 (add-to-list 'org-todo-heads head 'append)
5149 (push names org-todo-sets)
5150 (setq org-done-keywords (append org-done-keywords done nil))
5151 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5152 (setq org-todo-key-alist
5153 (append org-todo-key-alist
5154 (and alist
5155 (append '((:startgroup))
5156 (nreverse alist)
5157 '((:endgroup))))))
5158 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5159 (setq org-todo-sets (nreverse org-todo-sets)
5160 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5161 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5162 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5163 ;; Compute the regular expressions and other local variables.
5164 ;; Using `org-outline-regexp-bol' would complicate them much,
5165 ;; because of the fixed white space at the end of that string.
5166 (unless org-done-keywords
5167 (setq org-done-keywords
5168 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5169 (setq org-not-done-keywords
5170 (org-delete-all org-done-keywords
5171 (copy-sequence org-todo-keywords-1))
5172 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5173 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5174 org-not-done-heading-regexp
5175 (format org-heading-keyword-regexp-format org-not-done-regexp)
5176 org-todo-line-regexp
5177 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5178 org-complex-heading-regexp
5179 (concat "^\\(\\*+\\)"
5180 "\\(?: +" org-todo-regexp "\\)?"
5181 "\\(?: +\\(\\[#.\\]\\)\\)?"
5182 "\\(?: +\\(.*?\\)\\)??"
5183 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5184 "[ \t]*$")
5185 org-complex-heading-regexp-format
5186 (concat "^\\(\\*+\\)"
5187 "\\(?: +" org-todo-regexp "\\)?"
5188 "\\(?: +\\(\\[#.\\]\\)\\)?"
5189 "\\(?: +"
5190 ;; Stats cookies can be stuck to body.
5191 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5192 "\\(%s\\)"
5193 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5194 "\\)"
5195 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5196 "[ \t]*$")
5197 org-todo-line-tags-regexp
5198 (concat "^\\(\\*+\\)"
5199 "\\(?: +" org-todo-regexp "\\)?"
5200 "\\(?: +\\(.*?\\)\\)??"
5201 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5202 "[ \t]*$"))
5203 (org-compute-latex-and-related-regexp)))))
5205 (defun org--setup-collect-keywords (regexp &optional files alist)
5206 "Return setup keywords values as an alist.
5208 REGEXP matches a subset of setup keywords. FILES is a list of
5209 file names already visited. It is used to avoid circular setup
5210 files. ALIST, when non-nil, is the alist computed so far.
5212 Return value contains the following keys: `archive', `category',
5213 `columns', `constants', `filetags', `link', `priorities',
5214 `property', `scripts', `startup', `tags' and `todo'."
5215 (org-with-wide-buffer
5216 (goto-char (point-min))
5217 (let ((case-fold-search t))
5218 (while (re-search-forward regexp nil t)
5219 (let ((element (org-element-at-point)))
5220 (when (eq (org-element-type element) 'keyword)
5221 (let ((key (org-element-property :key element))
5222 (value (org-element-property :value element)))
5223 (cond
5224 ((equal key "ARCHIVE")
5225 (when (org-string-nw-p value)
5226 (push (cons 'archive value) alist)))
5227 ((equal key "CATEGORY") (push (cons 'category value) alist))
5228 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5229 ((equal key "CONSTANTS")
5230 (let* ((constants (assq 'constants alist))
5231 (store (cdr constants)))
5232 (dolist (pair (org-split-string value))
5233 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5234 pair)
5235 (let* ((name (match-string 1 pair))
5236 (value (match-string 2 pair))
5237 (old (assoc name store)))
5238 (if old (setcdr old value)
5239 (push (cons name value) store)))))
5240 (if constants (setcdr constants store)
5241 (push (cons 'constants store) alist))))
5242 ((equal key "FILETAGS")
5243 (when (org-string-nw-p value)
5244 (let ((old (assq 'filetags alist))
5245 (new (apply #'nconc
5246 (mapcar (lambda (x) (org-split-string x ":"))
5247 (org-split-string value)))))
5248 (if old (setcdr old (append new (cdr old)))
5249 (push (cons 'filetags new) alist)))))
5250 ((equal key "LINK")
5251 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5252 (let ((links (assq 'link alist))
5253 (pair (cons (match-string-no-properties 1 value)
5254 (match-string-no-properties 2 value))))
5255 (if links (push pair (cdr links))
5256 (push (list 'link pair) alist)))))
5257 ((equal key "OPTIONS")
5258 (when (and (org-string-nw-p value)
5259 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5260 (push (cons 'scripts (read (match-string 1 value))) alist)))
5261 ((equal key "PRIORITIES")
5262 (push (cons 'priorities
5263 (let ((prio (org-split-string value)))
5264 (if (< (length prio) 3) '(?A ?C ?B)
5265 (mapcar #'string-to-char prio))))
5266 alist))
5267 ((equal key "PROPERTY")
5268 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5269 (let* ((property (assq 'property alist))
5270 (value (org--update-property-plist
5271 (match-string-no-properties 1 value)
5272 (match-string-no-properties 2 value)
5273 (cdr property))))
5274 (if property (setcdr property value)
5275 (push (cons 'property value) alist)))))
5276 ((equal key "STARTUP")
5277 (let ((startup (assq 'startup alist)))
5278 (if startup
5279 (setcdr startup
5280 (append (cdr startup) (org-split-string value)))
5281 (push (cons 'startup (org-split-string value)) alist))))
5282 ((equal key "TAGS")
5283 (let ((tag-cell (assq 'tags alist)))
5284 (if tag-cell
5285 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5286 (push (cons 'tags value) alist))))
5287 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5288 (let ((todo (assq 'todo alist))
5289 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5290 (org-split-string value))))
5291 (if todo (push value (cdr todo))
5292 (push (list 'todo value) alist))))
5293 ((equal key "SETUPFILE")
5294 (unless buffer-read-only ; Do not check in Gnus messages.
5295 (let ((f (and (org-string-nw-p value)
5296 (expand-file-name
5297 (org-unbracket-string "\"" "\"" value)))))
5298 (when (and f (file-readable-p f) (not (member f files)))
5299 (with-temp-buffer
5300 (setq default-directory (file-name-directory f))
5301 (insert-file-contents f)
5302 (setq alist
5303 ;; Fake Org mode to benefit from cache
5304 ;; without recurring needlessly.
5305 (let ((major-mode 'org-mode))
5306 (org--setup-collect-keywords
5307 regexp (cons f files) alist)))))))))))))))
5308 alist)
5310 (defun org-tag-string-to-alist (s)
5311 "Return tag alist associated to string S.
5312 S is a value for TAGS keyword or produced with
5313 `org-tag-alist-to-string'. Return value is an alist suitable for
5314 `org-tag-alist' or `org-tag-persistent-alist'."
5315 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5316 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5317 "\\|{.+?}\\)" ; regular expression
5318 "\\(?:(\\(.\\))\\)?\\'"))
5319 alist group-flag)
5320 (dolist (tokens lines (cdr (nreverse alist)))
5321 (push '(:newline) alist)
5322 (while tokens
5323 (let ((token (pop tokens)))
5324 (pcase token
5325 ("{"
5326 (push '(:startgroup) alist)
5327 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5328 ("}"
5329 (push '(:endgroup) alist)
5330 (setq group-flag nil))
5331 ("["
5332 (push '(:startgrouptag) alist)
5333 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5334 ("]"
5335 (push '(:endgrouptag) alist)
5336 (setq group-flag nil))
5337 (":"
5338 (push '(:grouptags) alist))
5339 ((guard (string-match tag-re token))
5340 (let ((tag (match-string 1 token))
5341 (key (and (match-beginning 2)
5342 (string-to-char (match-string 2 token)))))
5343 ;; Push all tags in groups, no matter if they already
5344 ;; appear somewhere else in the list.
5345 (when (or group-flag (not (assoc tag alist)))
5346 (push (cons tag key) alist))))))))))
5348 (defun org-tag-alist-to-string (alist &optional skip-key)
5349 "Return tag string associated to ALIST.
5351 ALIST is an alist, as defined in `org-tag-alist' or
5352 `org-tag-persistent-alist', or produced with
5353 `org-tag-string-to-alist'.
5355 Return value is a string suitable as a value for \"TAGS\"
5356 keyword.
5358 When optional argument SKIP-KEY is non-nil, skip selection keys
5359 next to tags."
5360 (mapconcat (lambda (token)
5361 (pcase token
5362 (`(:startgroup) "{")
5363 (`(:endgroup) "}")
5364 (`(:startgrouptag) "[")
5365 (`(:endgrouptag) "]")
5366 (`(:grouptags) ":")
5367 (`(:newline) "\\n")
5368 ((and
5369 (guard (not skip-key))
5370 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5371 (format "%s(%c)" tag key))
5372 (`(,(and tag (pred stringp)) . ,_) tag)
5373 (_ (user-error "Invalid tag token: %S" token))))
5374 alist
5375 " "))
5377 (defun org-tag-alist-to-groups (alist)
5378 "Return group alist from tag ALIST.
5379 ALIST is an alist, as defined in `org-tag-alist' or
5380 `org-tag-persistent-alist', or produced with
5381 `org-tag-string-to-alist'. Return value is an alist following
5382 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5383 a string, summarizing TAGS, as a list of strings."
5384 (let (groups group-status current-group)
5385 (dolist (token alist (nreverse groups))
5386 (pcase token
5387 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5388 (`(,(or :endgroup :endgrouptag))
5389 (when (eq group-status 'append)
5390 (push (nreverse current-group) groups))
5391 (setq group-status nil))
5392 (`(:grouptags) (setq group-status 'append))
5393 ((and `(,tag . ,_) (guard group-status))
5394 (if (eq group-status 'append) (push tag current-group)
5395 (setq current-group (list tag))))
5396 (_ nil)))))
5398 (defun org-file-contents (file &optional noerror)
5399 "Return the contents of FILE, as a string."
5400 (if (and file (file-readable-p file))
5401 (with-temp-buffer
5402 (insert-file-contents file)
5403 (buffer-string))
5404 (funcall (if noerror 'message 'error)
5405 "Cannot read file \"%s\"%s"
5406 file
5407 (let ((from (buffer-file-name (buffer-base-buffer))))
5408 (if from (concat " (referenced in file \"" from "\")") "")))))
5410 (defun org-extract-log-state-settings (x)
5411 "Extract the log state setting from a TODO keyword string.
5412 This will extract info from a string like \"WAIT(w@/!)\"."
5413 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5414 (let ((kw (match-string 1 x))
5415 (log1 (and (match-end 3) (match-string 3 x)))
5416 (log2 (and (match-end 4) (match-string 4 x))))
5417 (and (or log1 log2)
5418 (list kw
5419 (and log1 (if (equal log1 "!") 'time 'note))
5420 (and log2 (if (equal log2 "!") 'time 'note)))))))
5422 (defun org-remove-keyword-keys (list)
5423 "Remove a pair of parenthesis at the end of each string in LIST."
5424 (mapcar (lambda (x)
5425 (if (string-match "(.*)$" x)
5426 (substring x 0 (match-beginning 0))
5428 list))
5430 (defun org-assign-fast-keys (alist)
5431 "Assign fast keys to a keyword-key alist.
5432 Respect keys that are already there."
5433 (let (new e (alt ?0))
5434 (while (setq e (pop alist))
5435 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5436 (cdr e)) ;; Key already assigned.
5437 (push e new)
5438 (let ((clist (string-to-list (downcase (car e))))
5439 (used (append new alist)))
5440 (when (= (car clist) ?@)
5441 (pop clist))
5442 (while (and clist (rassoc (car clist) used))
5443 (pop clist))
5444 (unless clist
5445 (while (rassoc alt used)
5446 (cl-incf alt)))
5447 (push (cons (car e) (or (car clist) alt)) new))))
5448 (nreverse new)))
5450 ;;; Some variables used in various places
5452 (defvar org-window-configuration nil
5453 "Used in various places to store a window configuration.")
5454 (defvar org-selected-window nil
5455 "Used in various places to store a window configuration.")
5456 (defvar org-finish-function nil
5457 "Function to be called when `C-c C-c' is used.
5458 This is for getting out of special buffers like capture.")
5459 (defvar org-last-state)
5461 ;; Defined somewhere in this file, but used before definition.
5462 (defvar org-entities) ;; defined in org-entities.el
5463 (defvar org-struct-menu)
5464 (defvar org-org-menu)
5465 (defvar org-tbl-menu)
5467 ;;;; Define the Org mode
5469 ;; We use a before-change function to check if a table might need
5470 ;; an update.
5471 (defvar org-table-may-need-update t
5472 "Indicates that a table might need an update.
5473 This variable is set by `org-before-change-function'.
5474 `org-table-align' sets it back to nil.")
5475 (defun org-before-change-function (_beg _end)
5476 "Every change indicates that a table might need an update."
5477 (setq org-table-may-need-update t))
5478 (defvar org-mode-map)
5479 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5480 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5481 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5482 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5483 (defvar org-table-buffer-is-an nil)
5485 (defvar bidi-paragraph-direction)
5486 (defvar buffer-face-mode-face)
5488 (require 'outline)
5490 ;; Other stuff we need.
5491 (require 'time-date)
5492 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5493 (require 'easymenu)
5494 (autoload 'easy-menu-add "easymenu")
5495 (require 'overlay)
5497 ;; (require 'org-macs) moved higher up in the file before it is first used
5498 (require 'org-entities)
5499 ;; (require 'org-compat) moved higher up in the file before it is first used
5500 (require 'org-faces)
5501 (require 'org-list)
5502 (require 'org-pcomplete)
5503 (require 'org-src)
5504 (require 'org-footnote)
5505 (require 'org-macro)
5507 ;; babel
5508 (require 'ob)
5510 ;;;###autoload
5511 (define-derived-mode org-mode outline-mode "Org"
5512 "Outline-based notes management and organizer, alias
5513 \"Carsten's outline-mode for keeping track of everything.\"
5515 Org mode develops organizational tasks around a NOTES file which
5516 contains information about projects as plain text. Org mode is
5517 implemented on top of Outline mode, which is ideal to keep the content
5518 of large files well structured. It supports ToDo items, deadlines and
5519 time stamps, which magically appear in the diary listing of the Emacs
5520 calendar. Tables are easily created with a built-in table editor.
5521 Plain text URL-like links connect to websites, emails (VM), Usenet
5522 messages (Gnus), BBDB entries, and any files related to the project.
5523 For printing and sharing of notes, an Org file (or a part of it)
5524 can be exported as a structured ASCII or HTML file.
5526 The following commands are available:
5528 \\{org-mode-map}"
5530 ;; Get rid of Outline menus, they are not needed
5531 ;; Need to do this here because define-derived-mode sets up
5532 ;; the keymap so late. Still, it is a waste to call this each time
5533 ;; we switch another buffer into Org mode.
5534 (define-key org-mode-map [menu-bar headings] 'undefined)
5535 (define-key org-mode-map [menu-bar hide] 'undefined)
5536 (define-key org-mode-map [menu-bar show] 'undefined)
5538 (org-load-modules-maybe)
5539 (org-install-agenda-files-menu)
5540 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5541 (add-to-invisibility-spec '(org-cwidth))
5542 (add-to-invisibility-spec '(org-hide-block . t))
5543 (setq-local outline-regexp org-outline-regexp)
5544 (setq-local outline-level 'org-outline-level)
5545 (setq bidi-paragraph-direction 'left-to-right)
5546 (when (and org-ellipsis
5547 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5548 (fboundp 'make-glyph-code))
5549 (unless org-display-table
5550 (setq org-display-table (make-display-table)))
5551 (set-display-table-slot
5552 org-display-table 4
5553 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5554 (if (stringp org-ellipsis) org-ellipsis "..."))))
5555 (setq buffer-display-table org-display-table))
5556 (org-set-regexps-and-options)
5557 (org-set-font-lock-defaults)
5558 (when (and org-tag-faces (not org-tags-special-faces-re))
5559 ;; tag faces set outside customize.... force initialization.
5560 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5561 ;; Calc embedded
5562 (setq-local calc-embedded-open-mode "# ")
5563 ;; Modify a few syntax entries
5564 (modify-syntax-entry ?@ "w")
5565 (modify-syntax-entry ?\" "\"")
5566 (modify-syntax-entry ?\\ "_")
5567 (modify-syntax-entry ?~ "_")
5568 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5569 ;; Activate before-change-function
5570 (setq-local org-table-may-need-update t)
5571 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5572 ;; Check for running clock before killing a buffer
5573 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5574 ;; Initialize macros templates.
5575 (org-macro-initialize-templates)
5576 ;; Initialize radio targets.
5577 (org-update-radio-target-regexp)
5578 ;; Indentation.
5579 (setq-local indent-line-function 'org-indent-line)
5580 (setq-local indent-region-function 'org-indent-region)
5581 ;; Filling and auto-filling.
5582 (org-setup-filling)
5583 ;; Comments.
5584 (org-setup-comments-handling)
5585 ;; Initialize cache.
5586 (org-element-cache-reset)
5587 ;; Beginning/end of defun
5588 (setq-local beginning-of-defun-function 'org-backward-element)
5589 (setq-local end-of-defun-function
5590 (lambda ()
5591 (if (not (org-at-heading-p))
5592 (org-forward-element)
5593 (org-forward-element)
5594 (forward-char -1))))
5595 ;; Next error for sparse trees
5596 (setq-local next-error-function 'org-occur-next-match)
5597 ;; Make sure dependence stuff works reliably, even for users who set it
5598 ;; too late :-(
5599 (if org-enforce-todo-dependencies
5600 (add-hook 'org-blocker-hook
5601 'org-block-todo-from-children-or-siblings-or-parent)
5602 (remove-hook 'org-blocker-hook
5603 'org-block-todo-from-children-or-siblings-or-parent))
5604 (if org-enforce-todo-checkbox-dependencies
5605 (add-hook 'org-blocker-hook
5606 'org-block-todo-from-checkboxes)
5607 (remove-hook 'org-blocker-hook
5608 'org-block-todo-from-checkboxes))
5610 ;; Align options lines
5611 (setq-local
5612 align-mode-rules-list
5613 '((org-in-buffer-settings
5614 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5615 (modes . '(org-mode)))))
5617 ;; Imenu
5618 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5620 ;; Make isearch reveal context
5621 (setq-local outline-isearch-open-invisible-function
5622 (lambda (&rest _) (org-show-context 'isearch)))
5624 ;; Setup the pcomplete hooks
5625 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5626 (setq-local pcomplete-command-name-function 'org-command-at-point)
5627 (setq-local pcomplete-default-completion-function 'ignore)
5628 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5629 (setq-local pcomplete-termination-string "")
5630 (setq-local buffer-face-mode-face 'org-default)
5632 ;; If empty file that did not turn on Org mode automatically, make
5633 ;; it to.
5634 (when (and org-insert-mode-line-in-empty-file
5635 (called-interactively-p 'any)
5636 (= (point-min) (point-max)))
5637 (insert "# -*- mode: org -*-\n\n"))
5638 (unless org-inhibit-startup
5639 (org-unmodified
5640 (when org-startup-with-beamer-mode (org-beamer-mode))
5641 (when org-startup-align-all-tables
5642 (org-table-map-tables #'org-table-align t))
5643 (when org-startup-with-inline-images (org-display-inline-images))
5644 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5645 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5646 (when org-startup-truncated (setq truncate-lines t))
5647 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5648 (org-refresh-effort-properties)))
5649 ;; Try to set `org-hide' face correctly.
5650 (let ((foreground (org-find-invisible-foreground)))
5651 (when foreground
5652 (set-face-foreground 'org-hide foreground))))
5654 ;; Update `customize-package-emacs-version-alist'
5655 (add-to-list 'customize-package-emacs-version-alist
5656 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5657 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5658 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5659 ("9.0" . "25.2")))
5661 (defvar org-mode-transpose-word-syntax-table
5662 (let ((st (make-syntax-table text-mode-syntax-table)))
5663 (dolist (c org-emphasis-alist st)
5664 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5666 (when (fboundp 'abbrev-table-put)
5667 (abbrev-table-put org-mode-abbrev-table
5668 :parents (list text-mode-abbrev-table)))
5670 (defun org-find-invisible-foreground ()
5671 (let ((candidates (remove
5672 "unspecified-bg"
5673 (nconc
5674 (list (face-background 'default)
5675 (face-background 'org-default))
5676 (mapcar
5677 (lambda (alist)
5678 (when (boundp alist)
5679 (cdr (assq 'background-color (symbol-value alist)))))
5680 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5681 (list (face-foreground 'org-hide))))))
5682 (car (remove nil candidates))))
5684 (defun org-current-time (&optional rounding-minutes past)
5685 "Current time, possibly rounded to ROUNDING-MINUTES.
5686 When ROUNDING-MINUTES is not an integer, fall back on the car of
5687 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5688 the rounding returns a past time."
5689 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5690 (car org-time-stamp-rounding-minutes)))
5691 (time (decode-time)) res)
5692 (if (< r 1)
5693 (current-time)
5694 (setq res
5695 (apply 'encode-time
5696 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5697 (nthcdr 2 time))))
5698 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5699 (seconds-to-time (- (float-time res) (* r 60)))
5700 res))))
5702 (defun org-today ()
5703 "Return today date, considering `org-extend-today-until'."
5704 (time-to-days
5705 (time-subtract (current-time)
5706 (list 0 (* 3600 org-extend-today-until) 0))))
5708 ;;;; Font-Lock stuff, including the activators
5710 (defvar org-mouse-map (make-sparse-keymap))
5711 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5712 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5713 (when org-mouse-1-follows-link
5714 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5715 (when org-tab-follows-link
5716 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5717 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5719 (require 'font-lock)
5721 (defconst org-non-link-chars "]\t\n\r<>")
5722 (defvar org-link-types-re nil
5723 "Matches a link that has a url-like prefix like \"http:\"")
5724 (defvar org-link-re-with-space nil
5725 "Matches a link with spaces, optional angular brackets around it.")
5726 (defvar org-link-re-with-space2 nil
5727 "Matches a link with spaces, optional angular brackets around it.")
5728 (defvar org-link-re-with-space3 nil
5729 "Matches a link with spaces, only for internal part in bracket links.")
5730 (defvar org-angle-link-re nil
5731 "Matches link with angular brackets, spaces are allowed.")
5732 (defvar org-plain-link-re nil
5733 "Matches plain link, without spaces.")
5734 (defvar org-bracket-link-regexp nil
5735 "Matches a link in double brackets.")
5736 (defvar org-bracket-link-analytic-regexp nil
5737 "Regular expression used to analyze links.
5738 Here is what the match groups contain after a match:
5739 1: http:
5740 2: http
5741 3: path
5742 4: [desc]
5743 5: desc")
5744 (defvar org-bracket-link-analytic-regexp++ nil
5745 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5746 (defvar org-any-link-re nil
5747 "Regular expression matching any link.")
5749 (defconst org-match-sexp-depth 3
5750 "Number of stacked braces for sub/superscript matching.")
5752 (defun org-create-multibrace-regexp (left right n)
5753 "Create a regular expression which will match a balanced sexp.
5754 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5755 as single character strings.
5756 The regexp returned will match the entire expression including the
5757 delimiters. It will also define a single group which contains the
5758 match except for the outermost delimiters. The maximum depth of
5759 stacked delimiters is N. Escaping delimiters is not possible."
5760 (let* ((nothing (concat "[^" left right "]*?"))
5761 (or "\\|")
5762 (re nothing)
5763 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5764 (while (> n 1)
5765 (setq n (1- n)
5766 re (concat re or next)
5767 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5768 (concat left "\\(" re "\\)" right)))
5770 (defconst org-match-substring-regexp
5771 (concat
5772 "\\(\\S-\\)\\([_^]\\)\\("
5773 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5774 "\\|"
5775 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5776 "\\|"
5777 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5778 "The regular expression matching a sub- or superscript.")
5780 (defconst org-match-substring-with-braces-regexp
5781 (concat
5782 "\\(\\S-\\)\\([_^]\\)"
5783 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5784 "The regular expression matching a sub- or superscript, forcing braces.")
5786 (defun org-make-link-regexps ()
5787 "Update the link regular expressions.
5788 This should be called after the variable `org-link-parameters' has changed."
5789 (let ((types-re (regexp-opt (org-link-types) t)))
5790 (setq org-link-types-re
5791 (concat "\\`" types-re ":")
5792 org-link-re-with-space
5793 (concat "<?" types-re ":"
5794 "\\([^" org-non-link-chars " ]"
5795 "[^" org-non-link-chars "]*"
5796 "[^" org-non-link-chars " ]\\)>?")
5797 org-link-re-with-space2
5798 (concat "<?" types-re ":"
5799 "\\([^" org-non-link-chars " ]"
5800 "[^\t\n\r]*"
5801 "[^" org-non-link-chars " ]\\)>?")
5802 org-link-re-with-space3
5803 (concat "<?" types-re ":"
5804 "\\([^" org-non-link-chars " ]"
5805 "[^\t\n\r]*\\)")
5806 org-angle-link-re
5807 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5808 types-re)
5809 org-plain-link-re
5810 (concat
5811 "\\<" types-re ":"
5812 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5813 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5814 org-bracket-link-regexp
5815 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5816 org-bracket-link-analytic-regexp
5817 (concat
5818 "\\[\\["
5819 "\\(" types-re ":\\)?"
5820 "\\([^]]+\\)"
5821 "\\]"
5822 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5823 "\\]")
5824 org-bracket-link-analytic-regexp++
5825 (concat
5826 "\\[\\["
5827 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5828 "\\([^]]+\\)"
5829 "\\]"
5830 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5831 "\\]")
5832 org-any-link-re
5833 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5834 org-angle-link-re "\\)\\|\\("
5835 org-plain-link-re "\\)"))))
5837 (org-make-link-regexps)
5839 (defvar org-emph-face nil)
5841 (defun org-do-emphasis-faces (limit)
5842 "Run through the buffer and emphasize strings."
5843 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5844 (car org-emphasis-regexp-components))))
5845 (catch :exit
5846 (while (re-search-forward quick-re limit t)
5847 (let* ((marker (match-string 2))
5848 (verbatim? (member marker '("~" "="))))
5849 (when (save-excursion
5850 (goto-char (match-beginning 0))
5851 ;; Do not match headline stars. Do not consider
5852 ;; stars of a headline as closing marker for bold
5853 ;; markup either.
5854 (and (not (looking-at-p org-outline-regexp-bol))
5855 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5856 (not (string-match-p
5857 (concat org-outline-regexp-bol "\\'")
5858 (match-string 0)))))
5859 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5860 (font-lock-prepend-text-property
5861 (match-beginning 2) (match-end 2) 'face face)
5862 (when verbatim?
5863 (org-remove-flyspell-overlays-in
5864 (match-beginning 0) (match-end 0)))
5865 (add-text-properties (match-beginning 2) (match-end 2)
5866 '(font-lock-multiline t org-emphasis t))
5867 (when org-hide-emphasis-markers
5868 (add-text-properties (match-end 4) (match-beginning 5)
5869 '(invisible org-link))
5870 (add-text-properties (match-beginning 3) (match-end 3)
5871 '(invisible org-link)))
5872 (throw :exit t))))))))
5874 (defun org-emphasize (&optional char)
5875 "Insert or change an emphasis, i.e. a font like bold or italic.
5876 If there is an active region, change that region to a new emphasis.
5877 If there is no region, just insert the marker characters and position
5878 the cursor between them.
5879 CHAR should be the marker character. If it is a space, it means to
5880 remove the emphasis of the selected region.
5881 If CHAR is not given (for example in an interactive call) it will be
5882 prompted for."
5883 (interactive)
5884 (let ((erc org-emphasis-regexp-components)
5885 (string "") beg end move s)
5886 (if (org-region-active-p)
5887 (setq beg (region-beginning)
5888 end (region-end)
5889 string (buffer-substring beg end))
5890 (setq move t))
5892 (unless char
5893 (message "Emphasis marker or tag: [%s]"
5894 (mapconcat #'car org-emphasis-alist ""))
5895 (setq char (read-char-exclusive)))
5896 (if (equal char ?\s)
5897 (setq s ""
5898 move nil)
5899 (unless (assoc (char-to-string char) org-emphasis-alist)
5900 (user-error "No such emphasis marker: \"%c\"" char))
5901 (setq s (char-to-string char)))
5902 (while (and (> (length string) 1)
5903 (equal (substring string 0 1) (substring string -1))
5904 (assoc (substring string 0 1) org-emphasis-alist))
5905 (setq string (substring string 1 -1)))
5906 (setq string (concat s string s))
5907 (when beg (delete-region beg end))
5908 (unless (or (bolp)
5909 (string-match (concat "[" (nth 0 erc) "\n]")
5910 (char-to-string (char-before (point)))))
5911 (insert " "))
5912 (unless (or (eobp)
5913 (string-match (concat "[" (nth 1 erc) "\n]")
5914 (char-to-string (char-after (point)))))
5915 (insert " ") (backward-char 1))
5916 (insert string)
5917 (and move (backward-char 1))))
5919 (defconst org-nonsticky-props
5920 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5922 (defsubst org-rear-nonsticky-at (pos)
5923 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5925 (defun org-activate-plain-links (limit)
5926 "Add link properties for plain links."
5927 (when (and (re-search-forward org-plain-link-re limit t)
5928 (not (org-in-src-block-p)))
5930 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5931 'face))
5932 (link (match-string-no-properties 0))
5933 (type (match-string-no-properties 1))
5934 (path (match-string-no-properties 2))
5935 (link-start (match-beginning 0))
5936 (link-end (match-end 0))
5937 (link-face (org-link-get-parameter type :face))
5938 (help-echo (org-link-get-parameter type :help-echo))
5939 (htmlize-link (org-link-get-parameter type :htmlize-link))
5940 (activate-func (org-link-get-parameter type :activate-func)))
5941 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5942 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5943 (add-text-properties (match-beginning 0) (match-end 0)
5944 (list
5945 'mouse-face (or (org-link-get-parameter type :mouse-face)
5946 'highlight)
5947 'face (cond
5948 ;; A function that returns a face
5949 ((functionp link-face)
5950 (funcall link-face path))
5951 ;; a face
5952 ((facep link-face)
5953 link-face)
5954 ;; An anonymous face
5955 ((consp link-face)
5956 link-face)
5957 ;; default
5959 'org-link))
5960 'help-echo (cond
5961 ((stringp help-echo)
5962 help-echo)
5963 ((functionp help-echo)
5964 help-echo)
5966 (concat "LINK: "
5967 (save-match-data
5968 (org-link-unescape link)))))
5969 'htmlize-link (cond
5970 ((functionp htmlize-link)
5971 (funcall htmlize-link path))
5973 `(:uri ,link)))
5974 'keymap (or (org-link-get-parameter type :keymap)
5975 org-mouse-map)
5976 'org-link-start (match-beginning 0)))
5977 (org-rear-nonsticky-at (match-end 0))
5978 (when activate-func
5979 (funcall activate-func link-start link-end path nil))
5980 t))))
5982 (defun org-activate-code (limit)
5983 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5984 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5985 (remove-text-properties (match-beginning 0) (match-end 0)
5986 '(display t invisible t intangible t))
5989 (defcustom org-src-fontify-natively t
5990 "When non-nil, fontify code in code blocks.
5991 See also the `org-block' face."
5992 :type 'boolean
5993 :version "24.4"
5994 :package-version '(Org . "8.3")
5995 :group 'org-appearance
5996 :group 'org-babel)
5998 (defcustom org-allow-promoting-top-level-subtree nil
5999 "When non-nil, allow promoting a top level subtree.
6000 The leading star of the top level headline will be replaced
6001 by a #."
6002 :type 'boolean
6003 :version "24.1"
6004 :group 'org-appearance)
6006 (defun org-fontify-meta-lines-and-blocks (limit)
6007 (condition-case nil
6008 (org-fontify-meta-lines-and-blocks-1 limit)
6009 (error (message "org-mode fontification error in %S at %d"
6010 (current-buffer)
6011 (line-number-at-pos)))))
6013 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6014 "Fontify #+ lines and blocks."
6015 (let ((case-fold-search t))
6016 (when (re-search-forward
6017 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6018 limit t)
6019 (let ((beg (match-beginning 0))
6020 (block-start (match-end 0))
6021 (block-end nil)
6022 (lang (match-string 7))
6023 (beg1 (line-beginning-position 2))
6024 (dc1 (downcase (match-string 2)))
6025 (dc3 (downcase (match-string 3)))
6026 end end1 quoting block-type)
6027 (cond
6028 ((and (match-end 4) (equal dc3 "+begin"))
6029 ;; Truly a block
6030 (setq block-type (downcase (match-string 5))
6031 quoting (member block-type org-protecting-blocks))
6032 (when (re-search-forward
6033 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6034 nil t) ;; on purpose, we look further than LIMIT
6035 (setq end (min (point-max) (match-end 0))
6036 end1 (min (point-max) (1- (match-beginning 0))))
6037 (setq block-end (match-beginning 0))
6038 (when quoting
6039 (org-remove-flyspell-overlays-in beg1 end1)
6040 (remove-text-properties beg end
6041 '(display t invisible t intangible t)))
6042 (add-text-properties
6043 beg end '(font-lock-fontified t font-lock-multiline t))
6044 (add-text-properties beg beg1 '(face org-meta-line))
6045 (org-remove-flyspell-overlays-in beg beg1)
6046 (add-text-properties ; For end_src
6047 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6048 (org-remove-flyspell-overlays-in end1 end)
6049 (cond
6050 ((and lang (not (string= lang "")) org-src-fontify-natively)
6051 (org-src-font-lock-fontify-block lang block-start block-end)
6052 (add-text-properties beg1 block-end '(src-block t)))
6053 (quoting
6054 (add-text-properties beg1 (min (point-max) (1+ end1))
6055 (list 'face
6056 (list :inherit
6057 (let ((face-name
6058 (intern (format "org-block-%s" lang))))
6059 (append (and (facep face-name) (list face-name))
6060 '(org-block))))))) ; end of source block
6061 ((not org-fontify-quote-and-verse-blocks))
6062 ((string= block-type "quote")
6063 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
6064 ((string= block-type "verse")
6065 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
6066 (add-text-properties beg beg1 '(face org-block-begin-line))
6067 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6068 '(face org-block-end-line))
6070 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6071 (org-remove-flyspell-overlays-in
6072 (match-beginning 0)
6073 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6074 (add-text-properties
6075 beg (match-end 3)
6076 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6077 '(font-lock-fontified t invisible t)
6078 '(font-lock-fontified t face org-document-info-keyword)))
6079 (add-text-properties
6080 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6081 (if (string-equal dc1 "+title:")
6082 '(font-lock-fontified t face org-document-title)
6083 '(font-lock-fontified t face org-document-info))))
6084 ((string-prefix-p "+caption" dc1)
6085 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6086 (remove-text-properties (match-beginning 0) (match-end 0)
6087 '(display t invisible t intangible t))
6088 ;; Handle short captions.
6089 (save-excursion
6090 (beginning-of-line)
6091 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6092 (add-text-properties (line-beginning-position) (match-end 1)
6093 '(font-lock-fontified t face org-meta-line))
6094 (add-text-properties (match-end 0) (line-end-position)
6095 '(font-lock-fontified t face org-block))
6097 ((member dc3 '(" " ""))
6098 (org-remove-flyspell-overlays-in beg (match-end 0))
6099 (add-text-properties
6100 beg (match-end 0)
6101 '(font-lock-fontified t face font-lock-comment-face)))
6102 (t ;; just any other in-buffer setting, but not indented
6103 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6104 (remove-text-properties (match-beginning 0) (match-end 0)
6105 '(display t invisible t intangible t))
6106 (add-text-properties beg (match-end 0)
6107 '(font-lock-fontified t face org-meta-line))
6108 t))))))
6110 (defun org-fontify-drawers (limit)
6111 "Fontify drawers."
6112 (when (re-search-forward org-drawer-regexp limit t)
6113 (add-text-properties
6114 (match-beginning 0) (match-end 0)
6115 '(font-lock-fontified t face org-special-keyword))
6116 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6119 (defun org-fontify-macros (limit)
6120 "Fontify macros."
6121 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6122 (add-text-properties
6123 (match-beginning 0) (match-end 0)
6124 '(font-lock-fontified t face org-macro))
6125 (when org-hide-macro-markers
6126 (add-text-properties (match-end 2) (match-beginning 2)
6127 '(invisible t))
6128 (add-text-properties (match-beginning 1) (match-end 1)
6129 '(invisible t)))
6130 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6133 (defun org-activate-angle-links (limit)
6134 "Add text properties for angle links."
6135 (when (and (re-search-forward org-angle-link-re limit t)
6136 (not (org-in-src-block-p)))
6137 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6138 (add-text-properties (match-beginning 0) (match-end 0)
6139 (list 'mouse-face 'highlight
6140 'keymap org-mouse-map
6141 'font-lock-multiline t))
6142 (org-rear-nonsticky-at (match-end 0))
6145 (defun org-activate-footnote-links (limit)
6146 "Add text properties for footnotes."
6147 (let ((fn (org-footnote-next-reference-or-definition limit)))
6148 (when fn
6149 (let* ((beg (nth 1 fn))
6150 (end (nth 2 fn))
6151 (label (car fn))
6152 (referencep (/= (line-beginning-position) beg)))
6153 (when (and referencep (nth 3 fn))
6154 (save-excursion
6155 (goto-char beg)
6156 (search-forward (or label "fn:"))
6157 (org-remove-flyspell-overlays-in beg (match-end 0))))
6158 (add-text-properties beg end
6159 (list 'mouse-face 'highlight
6160 'keymap org-mouse-map
6161 'help-echo
6162 (if referencep "Footnote reference"
6163 "Footnote definition")
6164 'font-lock-fontified t
6165 'font-lock-multiline t
6166 'face 'org-footnote))))))
6168 (defun org-activate-bracket-links (limit)
6169 "Add text properties for bracketed links."
6170 (when (and (re-search-forward org-bracket-link-regexp limit t)
6171 (not (org-in-src-block-p)))
6172 (let* ((hl (save-match-data
6173 (org-link-expand-abbrev (match-string-no-properties 1))))
6174 (type (save-match-data
6175 (and (string-match org-plain-link-re hl)
6176 (match-string-no-properties 1 hl))))
6177 (path (save-match-data
6178 (and (string-match org-plain-link-re hl)
6179 (match-string-no-properties 2 hl))))
6180 (link-start (match-beginning 0))
6181 (link-end (match-end 0))
6182 (bracketp t)
6183 (help-echo (org-link-get-parameter type :help-echo))
6184 (help (cond
6185 ((stringp help-echo)
6186 help-echo)
6187 ((functionp help-echo)
6188 help-echo)
6190 (concat "LINK: "
6191 (save-match-data
6192 (org-link-unescape hl))))))
6193 (link-face (org-link-get-parameter type :face))
6194 (face (cond
6195 ;; A function that returns a face
6196 ((functionp link-face)
6197 (funcall link-face path))
6198 ;; a face
6199 ((facep link-face)
6200 link-face)
6201 ;; An anonymous face
6202 ((consp link-face)
6203 link-face)
6204 ;; default
6206 'org-link)))
6207 (keymap (or (org-link-get-parameter type :keymap)
6208 org-mouse-map))
6209 (mouse-face (or (org-link-get-parameter type :mouse-face)
6210 'highlight))
6211 (htmlize (org-link-get-parameter type :htmlize-link))
6212 (htmlize-link (cond
6213 ((functionp htmlize)
6214 (funcall htmlize))
6216 `(:uri ,(format "%s:%s" type path)))))
6217 (activate-func (org-link-get-parameter type :activate-func))
6218 ;; invisible part
6219 (ip (list 'invisible (or
6220 (org-link-get-parameter type :display)
6221 'org-link)
6222 'face face
6223 'keymap keymap
6224 'mouse-face mouse-face
6225 'font-lock-multiline t
6226 'help-echo help
6227 'htmlize-link htmlize-link))
6228 ;; visible part
6229 (vp (list 'keymap keymap
6230 'face face
6231 'mouse-face mouse-face
6232 'font-lock-multiline t
6233 'help-echo help
6234 'htmlize-link htmlize-link)))
6235 ;; We need to remove the invisible property here. Table narrowing
6236 ;; may have made some of this invisible.
6237 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6238 (remove-text-properties (match-beginning 0) (match-end 0)
6239 '(invisible nil))
6240 (if (match-end 3)
6241 (progn
6242 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6243 (org-rear-nonsticky-at (match-beginning 3))
6244 (add-text-properties (match-beginning 3) (match-end 3) vp)
6245 (org-rear-nonsticky-at (match-end 3))
6246 (add-text-properties (match-end 3) (match-end 0) ip)
6247 (org-rear-nonsticky-at (match-end 0)))
6248 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6249 (org-rear-nonsticky-at (match-beginning 1))
6250 (add-text-properties (match-beginning 1) (match-end 1) vp)
6251 (org-rear-nonsticky-at (match-end 1))
6252 (add-text-properties (match-end 1) (match-end 0) ip)
6253 (org-rear-nonsticky-at (match-end 0)))
6254 (when activate-func
6255 (funcall activate-func link-start link-end path bracketp))
6256 t)))
6258 (defun org-activate-dates (limit)
6259 "Add text properties for dates."
6260 (when (and (re-search-forward org-tsr-regexp-both limit t)
6261 (not (equal (char-before (match-beginning 0)) 91)))
6262 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6263 (add-text-properties (match-beginning 0) (match-end 0)
6264 (list 'mouse-face 'highlight
6265 'keymap org-mouse-map))
6266 (org-rear-nonsticky-at (match-end 0))
6267 (when org-display-custom-times
6268 (if (match-end 3)
6269 (org-display-custom-time (match-beginning 3) (match-end 3))
6270 (org-display-custom-time (match-beginning 1) (match-end 1))))
6273 (defvar-local org-target-link-regexp nil
6274 "Regular expression matching radio targets in plain text.")
6276 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6277 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6278 border border border))
6279 "Regular expression matching a link target.")
6281 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6282 "Regular expression matching a radio target.")
6284 (defconst org-any-target-regexp
6285 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6286 "Regular expression matching any target.")
6288 (defun org-activate-target-links (limit)
6289 "Add text properties for target matches."
6290 (when org-target-link-regexp
6291 (let ((case-fold-search t))
6292 (when (re-search-forward org-target-link-regexp limit t)
6293 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6294 (add-text-properties (match-beginning 1) (match-end 1)
6295 (list 'mouse-face 'highlight
6296 'keymap org-mouse-map
6297 'help-echo "Radio target link"
6298 'org-linked-text t))
6299 (org-rear-nonsticky-at (match-end 1))
6300 t))))
6302 (defun org-update-radio-target-regexp ()
6303 "Find all radio targets in this file and update the regular expression.
6304 Also refresh fontification if needed."
6305 (interactive)
6306 (let ((old-regexp org-target-link-regexp)
6307 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6308 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6309 (targets
6310 (org-with-wide-buffer
6311 (goto-char (point-min))
6312 (let (rtn)
6313 (while (re-search-forward org-radio-target-regexp nil t)
6314 ;; Make sure point is really within the object.
6315 (backward-char)
6316 (let ((obj (org-element-context)))
6317 (when (eq (org-element-type obj) 'radio-target)
6318 (cl-pushnew (org-element-property :value obj) rtn
6319 :test #'equal))))
6320 rtn))))
6321 (setq org-target-link-regexp
6322 (and targets
6323 (concat before-re
6324 (mapconcat
6325 (lambda (x)
6326 (replace-regexp-in-string
6327 " +" "\\s-+" (regexp-quote x) t t))
6328 targets
6329 "\\|")
6330 after-re)))
6331 (unless (equal old-regexp org-target-link-regexp)
6332 ;; Clean-up cache.
6333 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6334 ((not org-target-link-regexp) old-regexp)
6336 (concat before-re
6337 (mapconcat
6338 (lambda (re)
6339 (substring re (length before-re)
6340 (- (length after-re))))
6341 (list old-regexp org-target-link-regexp)
6342 "\\|")
6343 after-re)))))
6344 (org-with-wide-buffer
6345 (goto-char (point-min))
6346 (while (re-search-forward regexp nil t)
6347 (org-element-cache-refresh (match-beginning 1)))))
6348 ;; Re fontify buffer.
6349 (when (memq 'radio org-highlight-links)
6350 (org-restart-font-lock)))))
6352 (defun org-hide-wide-columns (limit)
6353 (let (s e)
6354 (setq s (text-property-any (point) (or limit (point-max))
6355 'org-cwidth t))
6356 (when s
6357 (setq e (next-single-property-change s 'org-cwidth))
6358 (add-text-properties s e '(invisible org-cwidth))
6359 (goto-char e)
6360 t)))
6362 (defvar org-latex-and-related-regexp nil
6363 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6365 (defun org-compute-latex-and-related-regexp ()
6366 "Compute regular expression for LaTeX, entities and sub/superscript.
6367 Result depends on variable `org-highlight-latex-and-related'."
6368 (setq-local
6369 org-latex-and-related-regexp
6370 (let* ((re-sub
6371 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6372 ((eq org-use-sub-superscripts '{})
6373 (list org-match-substring-with-braces-regexp))
6374 (org-use-sub-superscripts (list org-match-substring-regexp))))
6375 (re-latex
6376 (when (memq 'latex org-highlight-latex-and-related)
6377 (let ((matchers (plist-get org-format-latex-options :matchers)))
6378 (delq nil
6379 (mapcar (lambda (x)
6380 (and (member (car x) matchers) (nth 1 x)))
6381 org-latex-regexps)))))
6382 (re-entities
6383 (when (memq 'entities org-highlight-latex-and-related)
6384 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6385 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6387 (defun org-do-latex-and-related (limit)
6388 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6389 LIMIT bounds the search for syntax to highlight. Stop at first
6390 highlighted object, if any. Return t if some highlighting was
6391 done, nil otherwise."
6392 (when (org-string-nw-p org-latex-and-related-regexp)
6393 (catch 'found
6394 (while (re-search-forward org-latex-and-related-regexp limit t)
6395 (unless
6396 (cl-some
6397 (lambda (f)
6398 (memq f '(org-code org-verbatim underline org-special-keyword)))
6399 (save-excursion
6400 (goto-char (1+ (match-beginning 0)))
6401 (face-at-point nil t)))
6402 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6403 '(?_ ?^))
6405 0)))
6406 (font-lock-prepend-text-property
6407 (+ offset (match-beginning 0)) (match-end 0)
6408 'face 'org-latex-and-related)
6409 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6410 '(font-lock-multiline t)))
6411 (throw 'found t)))
6412 nil)))
6414 (defun org-restart-font-lock ()
6415 "Restart `font-lock-mode', to force refontification."
6416 (when (and (boundp 'font-lock-mode) font-lock-mode)
6417 (font-lock-mode -1)
6418 (font-lock-mode 1)))
6420 (defun org-activate-tags (limit)
6421 (when (re-search-forward
6422 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6423 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6424 (add-text-properties (match-beginning 1) (match-end 1)
6425 (list 'mouse-face 'highlight
6426 'keymap org-mouse-map))
6427 (org-rear-nonsticky-at (match-end 1))
6430 (defun org-outline-level ()
6431 "Compute the outline level of the heading at point.
6433 If this is called at a normal headline, the level is the number
6434 of stars. Use `org-reduced-level' to remove the effect of
6435 `org-odd-levels'. Unlike to `org-current-level', this function
6436 takes into consideration inlinetasks."
6437 (org-with-wide-buffer
6438 (end-of-line)
6439 (if (re-search-backward org-outline-regexp-bol nil t)
6440 (1- (- (match-end 0) (match-beginning 0)))
6441 0)))
6443 (defvar org-font-lock-keywords nil)
6445 (defsubst org-re-property (property &optional literal allow-null value)
6446 "Return a regexp matching a PROPERTY line.
6448 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6449 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6450 non-nil, match properties even without a value.
6452 Match group 3 is set to the value when it exists. If there is no
6453 value and ALLOW-NULL is non-nil, it is set to the empty string.
6455 With optional argument VALUE, match only property lines with
6456 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6457 unless LITERAL is non-nil."
6458 (concat
6459 "^\\(?4:[ \t]*\\)"
6460 (format "\\(?1::\\(?2:%s\\):\\)"
6461 (if literal property (regexp-quote property)))
6462 (cond (value
6463 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6464 (if literal value (regexp-quote value))))
6465 (allow-null
6466 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6468 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6470 (defconst org-property-re
6471 (org-re-property "\\S-+" 'literal t)
6472 "Regular expression matching a property line.
6473 There are four matching groups:
6474 1: :PROPKEY: including the leading and trailing colon,
6475 2: PROPKEY without the leading and trailing colon,
6476 3: PROPVAL without leading or trailing spaces,
6477 4: the indentation of the current line,
6478 5: trailing whitespace.")
6480 (defvar org-font-lock-hook nil
6481 "Functions to be called for special font lock stuff.")
6483 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6485 (defvar org-font-lock-set-keywords-hook nil
6486 "Functions that can manipulate `org-font-lock-extra-keywords'.
6487 This is called after `org-font-lock-extra-keywords' is defined, but before
6488 it is installed to be used by font lock. This can be useful if something
6489 needs to be inserted at a specific position in the font-lock sequence.")
6491 (defun org-font-lock-hook (limit)
6492 "Run `org-font-lock-hook' within LIMIT."
6493 (run-hook-with-args 'org-font-lock-hook limit))
6495 (defun org-set-font-lock-defaults ()
6496 "Set font lock defaults for the current buffer."
6497 (let* ((em org-fontify-emphasized-text)
6498 (lk org-highlight-links)
6499 (org-font-lock-extra-keywords
6500 (list
6501 ;; Call the hook
6502 '(org-font-lock-hook)
6503 ;; Headlines
6504 `(,(if org-fontify-whole-heading-line
6505 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6506 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6507 (1 (org-get-level-face 1))
6508 (2 (org-get-level-face 2))
6509 (3 (org-get-level-face 3)))
6510 ;; Table lines
6511 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6512 (1 'org-table t))
6513 ;; Table internals
6514 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6515 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6516 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6517 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6518 ;; Drawers
6519 '(org-fontify-drawers)
6520 ;; Properties
6521 (list org-property-re
6522 '(1 'org-special-keyword t)
6523 '(3 'org-property-value t))
6524 ;; Links
6525 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6526 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6527 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6528 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6529 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6530 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6531 (when (memq 'footnote lk) '(org-activate-footnote-links))
6532 ;; Targets.
6533 (list org-any-target-regexp '(0 'org-target t))
6534 ;; Diary sexps.
6535 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6536 ;; Macro
6537 '(org-fontify-macros)
6538 '(org-hide-wide-columns (0 nil append))
6539 ;; TODO keyword
6540 (list (format org-heading-keyword-regexp-format
6541 org-todo-regexp)
6542 '(2 (org-get-todo-face 2) t))
6543 ;; DONE
6544 (if org-fontify-done-headline
6545 (list (format org-heading-keyword-regexp-format
6546 (concat
6547 "\\(?:"
6548 (mapconcat 'regexp-quote org-done-keywords "\\|")
6549 "\\)"))
6550 '(2 'org-headline-done t))
6551 nil)
6552 ;; Priorities
6553 '(org-font-lock-add-priority-faces)
6554 ;; Tags
6555 '(org-font-lock-add-tag-faces)
6556 ;; Tags groups
6557 (when (and org-group-tags org-tag-groups-alist)
6558 (list (concat org-outline-regexp-bol ".+\\(:"
6559 (regexp-opt (mapcar 'car org-tag-groups-alist))
6560 ":\\).*$")
6561 '(1 'org-tag-group prepend)))
6562 ;; Special keywords
6563 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6564 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6565 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6566 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6567 ;; Emphasis
6568 (when em '(org-do-emphasis-faces))
6569 ;; Checkboxes
6570 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6571 1 'org-checkbox prepend)
6572 (when (cdr (assq 'checkbox org-list-automatic-rules))
6573 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6574 (0 (org-get-checkbox-statistics-face) t)))
6575 ;; Description list items
6576 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6577 1 'org-list-dt prepend)
6578 ;; ARCHIVEd headings
6579 (list (concat
6580 org-outline-regexp-bol
6581 "\\(.*:" org-archive-tag ":.*\\)")
6582 '(1 'org-archived prepend))
6583 ;; Specials
6584 '(org-do-latex-and-related)
6585 '(org-fontify-entities)
6586 '(org-raise-scripts)
6587 ;; Code
6588 '(org-activate-code (1 'org-code t))
6589 ;; COMMENT
6590 (list (format
6591 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6592 org-todo-regexp
6593 org-comment-string)
6594 '(9 'org-special-keyword t))
6595 ;; Blocks and meta lines
6596 '(org-fontify-meta-lines-and-blocks))))
6597 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6598 (run-hooks 'org-font-lock-set-keywords-hook)
6599 ;; Now set the full font-lock-keywords
6600 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6601 (setq-local font-lock-defaults
6602 '(org-font-lock-keywords t nil nil backward-paragraph))
6603 (kill-local-variable 'font-lock-keywords)
6604 nil))
6606 (defun org-toggle-pretty-entities ()
6607 "Toggle the composition display of entities as UTF8 characters."
6608 (interactive)
6609 (setq-local org-pretty-entities (not org-pretty-entities))
6610 (org-restart-font-lock)
6611 (if org-pretty-entities
6612 (message "Entities are now displayed as UTF8 characters")
6613 (save-restriction
6614 (widen)
6615 (decompose-region (point-min) (point-max))
6616 (message "Entities are now displayed as plain text"))))
6618 (defvar-local org-custom-properties-overlays nil
6619 "List of overlays used for custom properties.")
6621 (defun org-toggle-custom-properties-visibility ()
6622 "Display or hide properties in `org-custom-properties'."
6623 (interactive)
6624 (if org-custom-properties-overlays
6625 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6626 (setq org-custom-properties-overlays nil))
6627 (when org-custom-properties
6628 (org-with-wide-buffer
6629 (goto-char (point-min))
6630 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6631 (while (re-search-forward regexp nil t)
6632 (let ((end (cdr (save-match-data (org-get-property-block)))))
6633 (when (and end (< (point) end))
6634 ;; Hide first custom property in current drawer.
6635 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6636 (overlay-put o 'invisible t)
6637 (overlay-put o 'org-custom-property t)
6638 (push o org-custom-properties-overlays))
6639 ;; Hide additional custom properties in the same drawer.
6640 (while (re-search-forward regexp end t)
6641 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6642 (overlay-put o 'invisible t)
6643 (overlay-put o 'org-custom-property t)
6644 (push o org-custom-properties-overlays)))))
6645 ;; Each entry is limited to a single property drawer.
6646 (outline-next-heading)))))))
6648 (defun org-fontify-entities (limit)
6649 "Find an entity to fontify."
6650 (let (ee)
6651 (when org-pretty-entities
6652 (catch 'match
6653 ;; "\_ "-family is left out on purpose. Only the first one,
6654 ;; i.e., "\_ ", could be fontified anyway, and it would be
6655 ;; confusing when adding a second white space character.
6656 (while (re-search-forward
6657 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6658 limit t)
6659 (when (and (not (org-at-comment-p))
6660 (setq ee (org-entity-get (match-string 1)))
6661 (= (length (nth 6 ee)) 1))
6662 (let* ((end (if (equal (match-string 2) "{}")
6663 (match-end 2)
6664 (match-end 1))))
6665 (add-text-properties
6666 (match-beginning 0) end
6667 (list 'font-lock-fontified t))
6668 (compose-region (match-beginning 0) end
6669 (nth 6 ee) nil)
6670 (backward-char 1)
6671 (throw 'match t))))
6672 nil))))
6674 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6675 "Fontify string S like in Org mode."
6676 (with-temp-buffer
6677 (insert s)
6678 (let ((org-odd-levels-only odd-levels))
6679 (org-mode)
6680 (org-font-lock-ensure)
6681 (buffer-string))))
6683 (defvar org-m nil)
6684 (defvar org-l nil)
6685 (defvar org-f nil)
6686 (defun org-get-level-face (n)
6687 "Get the right face for match N in font-lock matching of headlines."
6688 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6689 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6690 (if org-cycle-level-faces
6691 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6692 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6693 (cond
6694 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6695 ((eq n 2) org-f)
6696 (t (unless org-level-color-stars-only org-f))))
6698 (defun org-face-from-face-or-color (context inherit face-or-color)
6699 "Create a face list that inherits INHERIT, but sets the foreground color.
6700 When FACE-OR-COLOR is not a string, just return it."
6701 (if (stringp face-or-color)
6702 (list :inherit inherit
6703 (cdr (assoc context org-faces-easy-properties))
6704 face-or-color)
6705 face-or-color))
6707 (defun org-get-todo-face (kwd)
6708 "Get the right face for a TODO keyword KWD.
6709 If KWD is a number, get the corresponding match group."
6710 (when (numberp kwd) (setq kwd (match-string kwd)))
6711 (or (org-face-from-face-or-color
6712 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6713 (and (member kwd org-done-keywords) 'org-done)
6714 'org-todo))
6716 (defun org-get-priority-face (priority)
6717 "Get the right face for PRIORITY.
6718 PRIORITY is a character."
6719 (or (org-face-from-face-or-color
6720 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6721 'org-priority))
6723 (defun org-get-tag-face (tag)
6724 "Get the right face for TAG.
6725 If TAG is a number, get the corresponding match group."
6726 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6727 (or (org-face-from-face-or-color
6728 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6729 'org-tag)))
6731 (defun org-font-lock-add-priority-faces (limit)
6732 "Add the special priority faces."
6733 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6734 (add-text-properties
6735 (match-beginning 1) (match-end 1)
6736 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6737 'font-lock-fontified t))))
6739 (defun org-font-lock-add-tag-faces (limit)
6740 "Add the special tag faces."
6741 (when (and org-tag-faces org-tags-special-faces-re)
6742 (while (re-search-forward org-tags-special-faces-re limit t)
6743 (add-text-properties (match-beginning 1) (match-end 1)
6744 (list 'face (org-get-tag-face 1)
6745 'font-lock-fontified t))
6746 (backward-char 1))))
6748 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6749 "Remove fontification and activation overlays from links."
6750 (font-lock-default-unfontify-region beg end)
6751 (let* ((buffer-undo-list t)
6752 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6753 (inhibit-modification-hooks t)
6754 deactivate-mark buffer-file-name buffer-file-truename)
6755 (decompose-region beg end)
6756 (remove-text-properties beg end
6757 '(mouse-face t keymap t org-linked-text t
6758 invisible t intangible t
6759 org-emphasis t))
6760 (org-remove-font-lock-display-properties beg end)))
6762 (defconst org-script-display '(((raise -0.3) (height 0.7))
6763 ((raise 0.3) (height 0.7))
6764 ((raise -0.5))
6765 ((raise 0.5)))
6766 "Display properties for showing superscripts and subscripts.")
6768 (defun org-remove-font-lock-display-properties (beg end)
6769 "Remove specific display properties that have been added by font lock.
6770 The will remove the raise properties that are used to show superscripts
6771 and subscripts."
6772 (let (next prop)
6773 (while (< beg end)
6774 (setq next (next-single-property-change beg 'display nil end)
6775 prop (get-text-property beg 'display))
6776 (when (member prop org-script-display)
6777 (put-text-property beg next 'display nil))
6778 (setq beg next))))
6780 (defun org-raise-scripts (limit)
6781 "Add raise properties to sub/superscripts."
6782 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6783 (re-search-forward
6784 (if (eq org-use-sub-superscripts t)
6785 org-match-substring-regexp
6786 org-match-substring-with-braces-regexp)
6787 limit t))
6788 (let* ((pos (point)) table-p comment-p
6789 (mpos (match-beginning 3))
6790 (emph-p (get-text-property mpos 'org-emphasis))
6791 (link-p (get-text-property mpos 'mouse-face))
6792 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6793 (goto-char (point-at-bol))
6794 (setq table-p (looking-at-p org-table-dataline-regexp)
6795 comment-p (looking-at-p "^[ \t]*#[ +]"))
6796 (goto-char pos)
6797 ;; Handle a_b^c
6798 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6799 (unless (or comment-p emph-p link-p keyw-p)
6800 (put-text-property (match-beginning 3) (match-end 0)
6801 'display
6802 (if (equal (char-after (match-beginning 2)) ?^)
6803 (nth (if table-p 3 1) org-script-display)
6804 (nth (if table-p 2 0) org-script-display)))
6805 (add-text-properties (match-beginning 2) (match-end 2)
6806 (list 'invisible t
6807 'org-dwidth t 'org-dwidth-n 1))
6808 (if (and (eq (char-after (match-beginning 3)) ?{)
6809 (eq (char-before (match-end 3)) ?}))
6810 (progn
6811 (add-text-properties
6812 (match-beginning 3) (1+ (match-beginning 3))
6813 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6814 (add-text-properties
6815 (1- (match-end 3)) (match-end 3)
6816 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6817 t)))
6819 ;;;; Visibility cycling, including org-goto and indirect buffer
6821 ;;; Cycling
6823 (defvar-local org-cycle-global-status nil)
6824 (put 'org-cycle-global-status 'org-state t)
6825 (defvar-local org-cycle-subtree-status nil)
6826 (put 'org-cycle-subtree-status 'org-state t)
6828 (defvar org-inlinetask-min-level)
6830 (defun org-unlogged-message (&rest args)
6831 "Display a message, but avoid logging it in the *Messages* buffer."
6832 (let ((message-log-max nil))
6833 (apply 'message args)))
6835 ;;;###autoload
6836 (defun org-cycle (&optional arg)
6837 "TAB-action and visibility cycling for Org mode.
6839 This is the command invoked in Org mode by the `TAB' key. Its main
6840 purpose is outline visibility cycling, but it also invokes other actions
6841 in special contexts.
6843 When this function is called with a `\\[universal-argument]' prefix, rotate \
6844 the entire
6845 buffer through 3 states (global cycling)
6846 1. OVERVIEW: Show only top-level headlines.
6847 2. CONTENTS: Show all headlines of all levels, but no body text.
6848 3. SHOW ALL: Show everything.
6850 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6851 switch to the startup visibility,
6852 determined by the variable `org-startup-folded', and by any VISIBILITY
6853 properties in the buffer.
6855 With a `\\[universal-argument] \\[universal-argument] \
6856 \\[universal-argument]' prefix argument, show the entire buffer, including
6857 any drawers.
6859 When inside a table, re-align the table and move to the next field.
6861 When point is at the beginning of a headline, rotate the subtree started
6862 by this line through 3 different states (local cycling)
6863 1. FOLDED: Only the main headline is shown.
6864 2. CHILDREN: The main headline and the direct children are shown.
6865 From this state, you can move to one of the children
6866 and zoom in further.
6867 3. SUBTREE: Show the entire subtree, including body text.
6868 If there is no subtree, switch directly from CHILDREN to FOLDED.
6870 When point is at the beginning of an empty headline and the variable
6871 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6872 of the headline by demoting and promoting it to likely levels. This
6873 speeds up creation document structure by pressing `TAB' once or several
6874 times right after creating a new headline.
6876 When there is a numeric prefix, go up to a heading with level ARG, do
6877 a `show-subtree' and return to the previous cursor position. If ARG
6878 is negative, go up that many levels.
6880 When point is not at the beginning of a headline, execute the global
6881 binding for `TAB', which is re-indenting the line. See the option
6882 `org-cycle-emulate-tab' for details.
6884 As a special case, if point is at the beginning of the buffer and there is
6885 no headline in line 1, this function will act as if called with prefix arg
6886 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6887 prefix arg, but only
6888 if the variable `org-cycle-global-at-bob' is t."
6889 (interactive "P")
6890 (org-load-modules-maybe)
6891 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6892 (and org-cycle-level-after-item/entry-creation
6893 (or (org-cycle-level)
6894 (org-cycle-item-indentation))))
6895 (let* ((limit-level
6896 (or org-cycle-max-level
6897 (and (boundp 'org-inlinetask-min-level)
6898 org-inlinetask-min-level
6899 (1- org-inlinetask-min-level))))
6900 (nstars (and limit-level
6901 (if org-odd-levels-only
6902 (and limit-level (1- (* limit-level 2)))
6903 limit-level)))
6904 (org-outline-regexp
6905 (if (not (derived-mode-p 'org-mode))
6906 outline-regexp
6907 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6908 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6909 (not (looking-at org-outline-regexp))))
6910 (org-cycle-hook
6911 (if bob-special
6912 (delq 'org-optimize-window-after-visibility-change
6913 (copy-sequence org-cycle-hook))
6914 org-cycle-hook))
6915 (pos (point)))
6917 (cond
6919 ((equal arg '(16))
6920 (setq last-command 'dummy)
6921 (org-set-startup-visibility)
6922 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6924 ((equal arg '(64))
6925 (outline-show-all)
6926 (org-unlogged-message "Entire buffer visible, including drawers"))
6928 ((equal arg '(4)) (org-cycle-internal-global))
6930 ;; Try hiding block at point.
6931 ((org-hide-block-toggle-maybe))
6933 ;; Try cdlatex TAB completion
6934 ((org-try-cdlatex-tab))
6936 ;; Table: enter it or move to the next field.
6937 ((org-at-table-p 'any)
6938 (if (org-at-table.el-p)
6939 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6940 Use `\\[org-edit-special]' to edit table.el tables"))
6941 (if arg (org-table-edit-field t)
6942 (org-table-justify-field-maybe)
6943 (call-interactively 'org-table-next-field))))
6945 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6947 ;; Global cycling: delegate to `org-cycle-internal-global'.
6948 (bob-special (org-cycle-internal-global))
6950 ;; Drawers: delegate to `org-flag-drawer'.
6951 ((save-excursion
6952 (beginning-of-line 1)
6953 (looking-at org-drawer-regexp))
6954 (org-flag-drawer ; toggle block visibility
6955 (not (get-char-property (match-end 0) 'invisible))))
6957 ;; Show-subtree, ARG levels up from here.
6958 ((integerp arg)
6959 (save-excursion
6960 (org-back-to-heading)
6961 (outline-up-heading (if (< arg 0) (- arg)
6962 (- (funcall outline-level) arg)))
6963 (org-show-subtree)))
6965 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6966 ((and (featurep 'org-inlinetask)
6967 (org-inlinetask-at-task-p)
6968 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6969 (org-inlinetask-toggle-visibility))
6971 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6972 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6973 (save-excursion (move-beginning-of-line 1)
6974 (looking-at org-outline-regexp)))
6975 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6976 (org-cycle-internal-local))
6978 ;; From there: TAB emulation and template completion.
6979 (buffer-read-only (org-back-to-heading))
6981 ((run-hook-with-args-until-success
6982 'org-tab-after-check-for-cycling-hook))
6984 ((org-try-structure-completion))
6986 ((run-hook-with-args-until-success
6987 'org-tab-before-tab-emulation-hook))
6989 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6990 (or (not (bolp))
6991 (not (looking-at org-outline-regexp))))
6992 (call-interactively (global-key-binding "\t")))
6994 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6995 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6996 (or (and (eq org-cycle-emulate-tab 'white)
6997 (= (match-end 0) (point-at-eol)))
6998 (and (eq org-cycle-emulate-tab 'whitestart)
6999 (>= (match-end 0) pos))))
7001 (eq org-cycle-emulate-tab t))
7002 (call-interactively (global-key-binding "\t")))
7004 (t (save-excursion
7005 (org-back-to-heading)
7006 (org-cycle)))))))
7008 (defun org-cycle-internal-global ()
7009 "Do the global cycling action."
7010 ;; Hack to avoid display of messages for .org attachments in Gnus
7011 (let ((ga (string-match "\\*fontification" (buffer-name))))
7012 (cond
7013 ((and (eq last-command this-command)
7014 (eq org-cycle-global-status 'overview))
7015 ;; We just created the overview - now do table of contents
7016 ;; This can be slow in very large buffers, so indicate action
7017 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7018 (unless ga (org-unlogged-message "CONTENTS..."))
7019 (org-content)
7020 (unless ga (org-unlogged-message "CONTENTS...done"))
7021 (setq org-cycle-global-status 'contents)
7022 (run-hook-with-args 'org-cycle-hook 'contents))
7024 ((and (eq last-command this-command)
7025 (eq org-cycle-global-status 'contents))
7026 ;; We just showed the table of contents - now show everything
7027 (run-hook-with-args 'org-pre-cycle-hook 'all)
7028 (outline-show-all)
7029 (unless ga (org-unlogged-message "SHOW ALL"))
7030 (setq org-cycle-global-status 'all)
7031 (run-hook-with-args 'org-cycle-hook 'all))
7034 ;; Default action: go to overview
7035 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7036 (org-overview)
7037 (unless ga (org-unlogged-message "OVERVIEW"))
7038 (setq org-cycle-global-status 'overview)
7039 (run-hook-with-args 'org-cycle-hook 'overview)))))
7041 (defvar org-called-with-limited-levels nil
7042 "Non-nil when `org-with-limited-levels' is currently active.")
7044 (defun org-cycle-internal-local ()
7045 "Do the local cycling action."
7046 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7047 ;; First, determine end of headline (EOH), end of subtree or item
7048 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7049 (save-excursion
7050 (if (org-at-item-p)
7051 (progn
7052 (beginning-of-line)
7053 (setq struct (org-list-struct))
7054 (setq eoh (point-at-eol))
7055 (setq eos (org-list-get-item-end-before-blank (point) struct))
7056 (setq has-children (org-list-has-child-p (point) struct)))
7057 (org-back-to-heading)
7058 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7059 (setq eos (save-excursion (org-end-of-subtree t t)
7060 (when (bolp) (backward-char)) (point)))
7061 (setq has-children
7062 (or (save-excursion
7063 (let ((level (funcall outline-level)))
7064 (outline-next-heading)
7065 (and (org-at-heading-p t)
7066 (> (funcall outline-level) level))))
7067 (save-excursion
7068 (org-list-search-forward (org-item-beginning-re) eos t)))))
7069 ;; Determine end invisible part of buffer (EOL)
7070 (beginning-of-line 2)
7071 (while (and (not (eobp)) ;This is like `next-line'.
7072 (get-char-property (1- (point)) 'invisible))
7073 (goto-char (next-single-char-property-change (point) 'invisible))
7074 (and (eolp) (beginning-of-line 2)))
7075 (setq eol (point)))
7076 ;; Find out what to do next and set `this-command'
7077 (cond
7078 ((= eos eoh)
7079 ;; Nothing is hidden behind this heading
7080 (unless (org-before-first-heading-p)
7081 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7082 (org-unlogged-message "EMPTY ENTRY")
7083 (setq org-cycle-subtree-status nil)
7084 (save-excursion
7085 (goto-char eos)
7086 (outline-next-heading)
7087 (when (outline-invisible-p) (org-flag-heading nil))))
7088 ((and (or (>= eol eos)
7089 (not (string-match "\\S-" (buffer-substring eol eos))))
7090 (or has-children
7091 (not (setq children-skipped
7092 org-cycle-skip-children-state-if-no-children))))
7093 ;; Entire subtree is hidden in one line: children view
7094 (unless (org-before-first-heading-p)
7095 (run-hook-with-args 'org-pre-cycle-hook 'children))
7096 (if (org-at-item-p)
7097 (org-list-set-item-visibility (point-at-bol) struct 'children)
7098 (org-show-entry)
7099 (org-with-limited-levels (org-show-children))
7100 ;; FIXME: This slows down the func way too much.
7101 ;; How keep drawers hidden in subtree anyway?
7102 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7103 ;; (org-cycle-hide-drawers 'subtree))
7105 ;; Fold every list in subtree to top-level items.
7106 (when (eq org-cycle-include-plain-lists 'integrate)
7107 (save-excursion
7108 (org-back-to-heading)
7109 (while (org-list-search-forward (org-item-beginning-re) eos t)
7110 (beginning-of-line 1)
7111 (let* ((struct (org-list-struct))
7112 (prevs (org-list-prevs-alist struct))
7113 (end (org-list-get-bottom-point struct)))
7114 (dolist (e (org-list-get-all-items (point) struct prevs))
7115 (org-list-set-item-visibility e struct 'folded))
7116 (goto-char (if (< end eos) end eos)))))))
7117 (org-unlogged-message "CHILDREN")
7118 (save-excursion
7119 (goto-char eos)
7120 (outline-next-heading)
7121 (when (outline-invisible-p) (org-flag-heading nil)))
7122 (setq org-cycle-subtree-status 'children)
7123 (unless (org-before-first-heading-p)
7124 (run-hook-with-args 'org-cycle-hook 'children)))
7125 ((or children-skipped
7126 (and (eq last-command this-command)
7127 (eq org-cycle-subtree-status 'children)))
7128 ;; We just showed the children, or no children are there,
7129 ;; now show everything.
7130 (unless (org-before-first-heading-p)
7131 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7132 (outline-flag-region eoh eos nil)
7133 (org-unlogged-message
7134 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7135 (setq org-cycle-subtree-status 'subtree)
7136 (unless (org-before-first-heading-p)
7137 (run-hook-with-args 'org-cycle-hook 'subtree)))
7139 ;; Default action: hide the subtree.
7140 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7141 (outline-flag-region eoh eos t)
7142 (org-unlogged-message "FOLDED")
7143 (setq org-cycle-subtree-status 'folded)
7144 (unless (org-before-first-heading-p)
7145 (run-hook-with-args 'org-cycle-hook 'folded))))))
7147 ;;;###autoload
7148 (defun org-global-cycle (&optional arg)
7149 "Cycle the global visibility. For details see `org-cycle'.
7150 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7151 With a numeric prefix, show all headlines up to that level."
7152 (interactive "P")
7153 (let ((org-cycle-include-plain-lists
7154 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7155 (cond
7156 ((integerp arg)
7157 (outline-show-all)
7158 (outline-hide-sublevels arg)
7159 (setq org-cycle-global-status 'contents))
7160 ((equal arg '(4))
7161 (org-set-startup-visibility)
7162 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7164 (org-cycle '(4))))))
7166 (defun org-set-startup-visibility ()
7167 "Set the visibility required by startup options and properties."
7168 (cond
7169 ((eq org-startup-folded t)
7170 (org-overview))
7171 ((eq org-startup-folded 'content)
7172 (org-content))
7173 ((or (eq org-startup-folded 'showeverything)
7174 (eq org-startup-folded nil))
7175 (outline-show-all)))
7176 (unless (eq org-startup-folded 'showeverything)
7177 (when org-hide-block-startup (org-hide-block-all))
7178 (org-set-visibility-according-to-property 'no-cleanup)
7179 (org-cycle-hide-archived-subtrees 'all)
7180 (org-cycle-hide-drawers 'all)
7181 (org-cycle-show-empty-lines t)))
7183 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7184 "Switch subtree visibilities according to :VISIBILITY: property."
7185 (interactive)
7186 (org-with-wide-buffer
7187 (goto-char (point-min))
7188 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7189 (if (not (org-at-property-p)) (outline-next-heading)
7190 (let ((state (match-string 3)))
7191 (save-excursion
7192 (org-back-to-heading t)
7193 (outline-hide-subtree)
7194 (org-reveal)
7195 (cond
7196 ((equal state "folded")
7197 (outline-hide-subtree))
7198 ((equal state "children")
7199 (org-show-hidden-entry)
7200 (org-show-children))
7201 ((equal state "content")
7202 (save-excursion
7203 (save-restriction
7204 (org-narrow-to-subtree)
7205 (org-content))))
7206 ((member state '("all" "showall"))
7207 (outline-show-subtree)))))))
7208 (unless no-cleanup
7209 (org-cycle-hide-archived-subtrees 'all)
7210 (org-cycle-hide-drawers 'all)
7211 (org-cycle-show-empty-lines 'all))))
7213 ;; This function uses outline-regexp instead of the more fundamental
7214 ;; org-outline-regexp so that org-cycle-global works outside of Org
7215 ;; buffers, where outline-regexp is needed.
7216 (defun org-overview ()
7217 "Switch to overview mode, showing only top-level headlines.
7218 This shows all headlines with a level equal or greater than the level
7219 of the first headline in the buffer. This is important, because if the
7220 first headline is not level one, then (hide-sublevels 1) gives confusing
7221 results."
7222 (interactive)
7223 (save-excursion
7224 (let ((level
7225 (save-excursion
7226 (goto-char (point-min))
7227 (when (re-search-forward (concat "^" outline-regexp) nil t)
7228 (goto-char (match-beginning 0))
7229 (funcall outline-level)))))
7230 (and level (outline-hide-sublevels level)))))
7232 (defun org-content (&optional arg)
7233 "Show all headlines in the buffer, like a table of contents.
7234 With numerical argument N, show content up to level N."
7235 (interactive "P")
7236 (org-overview)
7237 (save-excursion
7238 ;; Visit all headings and show their offspring
7239 (and (integerp arg) (org-overview))
7240 (goto-char (point-max))
7241 (catch 'exit
7242 (while (and (progn (condition-case nil
7243 (outline-previous-visible-heading 1)
7244 (error (goto-char (point-min))))
7246 (looking-at org-outline-regexp))
7247 (if (integerp arg)
7248 (org-show-children (1- arg))
7249 (outline-show-branches))
7250 (when (bobp) (throw 'exit nil))))))
7252 (defun org-optimize-window-after-visibility-change (state)
7253 "Adjust the window after a change in outline visibility.
7254 This function is the default value of the hook `org-cycle-hook'."
7255 (when (get-buffer-window (current-buffer))
7256 (cond
7257 ((eq state 'content) nil)
7258 ((eq state 'all) nil)
7259 ((eq state 'folded) nil)
7260 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7261 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7263 (defun org-remove-empty-overlays-at (pos)
7264 "Remove outline overlays that do not contain non-white stuff."
7265 (dolist (o (overlays-at pos))
7266 (and (eq 'outline (overlay-get o 'invisible))
7267 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7268 (overlay-end o))))
7269 (delete-overlay o))))
7271 (defun org-clean-visibility-after-subtree-move ()
7272 "Fix visibility issues after moving a subtree."
7273 ;; First, find a reasonable region to look at:
7274 ;; Start two siblings above, end three below
7275 (let* ((beg (save-excursion
7276 (and (org-get-last-sibling)
7277 (org-get-last-sibling))
7278 (point)))
7279 (end (save-excursion
7280 (and (org-get-next-sibling)
7281 (org-get-next-sibling)
7282 (org-get-next-sibling))
7283 (if (org-at-heading-p)
7284 (point-at-eol)
7285 (point))))
7286 (level (looking-at "\\*+"))
7287 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7288 (save-excursion
7289 (save-restriction
7290 (narrow-to-region beg end)
7291 (when re
7292 ;; Properly fold already folded siblings
7293 (goto-char (point-min))
7294 (while (re-search-forward re nil t)
7295 (when (and (not (outline-invisible-p))
7296 (save-excursion
7297 (goto-char (point-at-eol)) (outline-invisible-p)))
7298 (outline-hide-entry))))
7299 (org-cycle-show-empty-lines 'overview)
7300 (org-cycle-hide-drawers 'overview)))))
7302 (defun org-cycle-show-empty-lines (state)
7303 "Show empty lines above all visible headlines.
7304 The region to be covered depends on STATE when called through
7305 `org-cycle-hook'. Lisp program can use t for STATE to get the
7306 entire buffer covered. Note that an empty line is only shown if there
7307 are at least `org-cycle-separator-lines' empty lines before the headline."
7308 (when (/= org-cycle-separator-lines 0)
7309 (save-excursion
7310 (let* ((n (abs org-cycle-separator-lines))
7311 (re (cond
7312 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7313 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7314 (t (let ((ns (number-to-string (- n 2))))
7315 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7316 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7317 beg end)
7318 (cond
7319 ((memq state '(overview contents t))
7320 (setq beg (point-min) end (point-max)))
7321 ((memq state '(children folded))
7322 (setq beg (point)
7323 end (progn (org-end-of-subtree t t)
7324 (line-beginning-position 2)))))
7325 (when beg
7326 (goto-char beg)
7327 (while (re-search-forward re end t)
7328 (unless (get-char-property (match-end 1) 'invisible)
7329 (let ((e (match-end 1))
7330 (b (if (>= org-cycle-separator-lines 0)
7331 (match-beginning 1)
7332 (save-excursion
7333 (goto-char (match-beginning 0))
7334 (skip-chars-backward " \t\n")
7335 (line-end-position)))))
7336 (outline-flag-region b e nil))))))))
7337 ;; Never hide empty lines at the end of the file.
7338 (save-excursion
7339 (goto-char (point-max))
7340 (outline-previous-heading)
7341 (outline-end-of-heading)
7342 (when (and (looking-at "[ \t\n]+")
7343 (= (match-end 0) (point-max)))
7344 (outline-flag-region (point) (match-end 0) nil))))
7346 (defun org-show-empty-lines-in-parent ()
7347 "Move to the parent and re-show empty lines before visible headlines."
7348 (save-excursion
7349 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7350 (org-cycle-show-empty-lines context))))
7352 (defun org-files-list ()
7353 "Return `org-agenda-files' list, plus all open Org files.
7354 This is useful for operations that need to scan all of a user's
7355 open and agenda-wise Org files."
7356 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7357 (dolist (buf (buffer-list))
7358 (with-current-buffer buf
7359 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7360 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7361 files))
7363 (defsubst org-entry-beginning-position ()
7364 "Return the beginning position of the current entry."
7365 (save-excursion (org-back-to-heading t) (point)))
7367 (defsubst org-entry-end-position ()
7368 "Return the end position of the current entry."
7369 (save-excursion (outline-next-heading) (point)))
7371 (defun org-cycle-hide-drawers (state &optional exceptions)
7372 "Re-hide all drawers after a visibility state change.
7373 When non-nil, optional argument EXCEPTIONS is a list of strings
7374 specifying which drawers should not be hidden."
7375 (when (and (derived-mode-p 'org-mode)
7376 (not (memq state '(overview folded contents))))
7377 (save-excursion
7378 (let* ((globalp (memq state '(contents all)))
7379 (beg (if globalp (point-min) (point)))
7380 (end (if globalp (point-max)
7381 (if (eq state 'children)
7382 (save-excursion (outline-next-heading) (point))
7383 (org-end-of-subtree t)))))
7384 (goto-char beg)
7385 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7386 (unless (member-ignore-case (match-string 1) exceptions)
7387 (let ((drawer (org-element-at-point)))
7388 (when (memq (org-element-type drawer) '(drawer property-drawer))
7389 (org-flag-drawer t drawer)
7390 ;; Make sure to skip drawer entirely or we might flag
7391 ;; it another time when matching its ending line with
7392 ;; `org-drawer-regexp'.
7393 (goto-char (org-element-property :end drawer))))))))))
7395 (defun org-flag-drawer (flag &optional element)
7396 "When FLAG is non-nil, hide the drawer we are at.
7397 Otherwise make it visible. When optional argument ELEMENT is
7398 a parsed drawer, as returned by `org-element-at-point', hide or
7399 show that drawer instead."
7400 (let ((drawer (or element
7401 (and (save-excursion
7402 (beginning-of-line)
7403 (looking-at-p org-drawer-regexp))
7404 (org-element-at-point)))))
7405 (when (memq (org-element-type drawer) '(drawer property-drawer))
7406 (let ((post (org-element-property :post-affiliated drawer)))
7407 (save-excursion
7408 (outline-flag-region
7409 (progn (goto-char post) (line-end-position))
7410 (progn (goto-char (org-element-property :end drawer))
7411 (skip-chars-backward " \r\t\n")
7412 (line-end-position))
7413 flag))
7414 ;; When the drawer is hidden away, make sure point lies in
7415 ;; a visible part of the buffer.
7416 (when (and flag (> (line-beginning-position) post))
7417 (goto-char post))))))
7419 (defun org-subtree-end-visible-p ()
7420 "Is the end of the current subtree visible?"
7421 (pos-visible-in-window-p
7422 (save-excursion (org-end-of-subtree t) (point))))
7424 (defun org-first-headline-recenter ()
7425 "Move cursor to the first headline and recenter the headline."
7426 (let ((window (get-buffer-window)))
7427 (when window
7428 (goto-char (point-min))
7429 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7430 (set-window-start window (line-beginning-position))))))
7432 ;;; Saving and restoring visibility
7434 (defun org-outline-overlay-data (&optional use-markers)
7435 "Return a list of the locations of all outline overlays.
7436 These are overlays with the `invisible' property value `outline'.
7437 The return value is a list of cons cells, with start and stop
7438 positions for each overlay.
7439 If USE-MARKERS is set, return the positions as markers."
7440 (let (beg end)
7441 (org-with-wide-buffer
7442 (delq nil
7443 (mapcar (lambda (o)
7444 (when (eq (overlay-get o 'invisible) 'outline)
7445 (setq beg (overlay-start o)
7446 end (overlay-end o))
7447 (and beg end (> end beg)
7448 (if use-markers
7449 (cons (copy-marker beg)
7450 (copy-marker end t))
7451 (cons beg end)))))
7452 (overlays-in (point-min) (point-max)))))))
7454 (defun org-set-outline-overlay-data (data)
7455 "Create visibility overlays for all positions in DATA.
7456 DATA should have been made by `org-outline-overlay-data'."
7457 (org-with-wide-buffer
7458 (outline-show-all)
7459 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7461 ;;; Folding of blocks
7463 (defvar-local org-hide-block-overlays nil
7464 "Overlays hiding blocks.")
7466 (defun org-block-map (function &optional start end)
7467 "Call FUNCTION at the head of all source blocks in the current buffer.
7468 Optional arguments START and END can be used to limit the range."
7469 (let ((start (or start (point-min)))
7470 (end (or end (point-max))))
7471 (save-excursion
7472 (goto-char start)
7473 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7474 (save-excursion
7475 (save-match-data
7476 (goto-char (match-beginning 0))
7477 (funcall function)))))))
7479 (defun org-hide-block-toggle-all ()
7480 "Toggle the visibility of all blocks in the current buffer."
7481 (org-block-map 'org-hide-block-toggle))
7483 (defun org-hide-block-all ()
7484 "Fold all blocks in the current buffer."
7485 (interactive)
7486 (org-show-block-all)
7487 (org-block-map 'org-hide-block-toggle-maybe))
7489 (defun org-show-block-all ()
7490 "Unfold all blocks in the current buffer."
7491 (interactive)
7492 (mapc #'delete-overlay org-hide-block-overlays)
7493 (setq org-hide-block-overlays nil))
7495 (defun org-hide-block-toggle-maybe ()
7496 "Toggle visibility of block at point.
7497 Unlike to `org-hide-block-toggle', this function does not throw
7498 an error. Return a non-nil value when toggling is successful."
7499 (interactive)
7500 (ignore-errors (org-hide-block-toggle)))
7502 (defun org-hide-block-toggle (&optional force)
7503 "Toggle the visibility of the current block.
7504 When optional argument FORCE is `off', make block visible. If it
7505 is non-nil, hide it unconditionally. Throw an error when not at
7506 a block. Return a non-nil value when toggling is successful."
7507 (interactive)
7508 (let ((element (org-element-at-point)))
7509 (unless (memq (org-element-type element)
7510 '(center-block comment-block dynamic-block example-block
7511 export-block quote-block special-block
7512 src-block verse-block))
7513 (user-error "Not at a block"))
7514 (let* ((start (save-excursion
7515 (goto-char (org-element-property :post-affiliated element))
7516 (line-end-position)))
7517 (end (save-excursion
7518 (goto-char (org-element-property :end element))
7519 (skip-chars-backward " \r\t\n")
7520 (line-end-position)))
7521 (overlays (overlays-at start)))
7522 (cond
7523 ;; Do nothing when not before or at the block opening line or
7524 ;; at the block closing line.
7525 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7526 ((and (not (eq force 'off))
7527 (not (memq t (mapcar
7528 (lambda (o)
7529 (eq (overlay-get o 'invisible) 'org-hide-block))
7530 overlays))))
7531 (let ((ov (make-overlay start end)))
7532 (overlay-put ov 'invisible 'org-hide-block)
7533 ;; Make the block accessible to `isearch'.
7534 (overlay-put
7535 ov 'isearch-open-invisible
7536 (lambda (ov)
7537 (when (memq ov org-hide-block-overlays)
7538 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7539 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7540 (delete-overlay ov))))
7541 (push ov org-hide-block-overlays)
7542 ;; When the block is hidden away, make sure point is left in
7543 ;; a visible part of the buffer.
7544 (when (> (line-beginning-position) start)
7545 (goto-char start)
7546 (beginning-of-line))
7547 ;; Signal successful toggling.
7549 ((or (not force) (eq force 'off))
7550 (dolist (ov overlays t)
7551 (when (memq ov org-hide-block-overlays)
7552 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7553 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7554 (delete-overlay ov))))))))
7556 ;; Remove overlays when changing major mode
7557 (add-hook 'org-mode-hook
7558 (lambda () (add-hook 'change-major-mode-hook
7559 'org-show-block-all 'append 'local)))
7561 ;;; Org-goto
7563 (defvar org-goto-window-configuration nil)
7564 (defvar org-goto-marker nil)
7565 (defvar org-goto-map)
7566 (defun org-goto-map ()
7567 "Set the keymap `org-goto'."
7568 (setq org-goto-map
7569 (let ((map (make-sparse-keymap)))
7570 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7571 mouse-drag-region universal-argument org-occur)))
7572 (dolist (cmd cmds)
7573 (substitute-key-definition cmd cmd map global-map)))
7574 (suppress-keymap map)
7575 (org-defkey map "\C-m" 'org-goto-ret)
7576 (org-defkey map [(return)] 'org-goto-ret)
7577 (org-defkey map [(left)] 'org-goto-left)
7578 (org-defkey map [(right)] 'org-goto-right)
7579 (org-defkey map [(control ?g)] 'org-goto-quit)
7580 (org-defkey map "\C-i" 'org-cycle)
7581 (org-defkey map [(tab)] 'org-cycle)
7582 (org-defkey map [(down)] 'outline-next-visible-heading)
7583 (org-defkey map [(up)] 'outline-previous-visible-heading)
7584 (if org-goto-auto-isearch
7585 (if (fboundp 'define-key-after)
7586 (define-key-after map [t] 'org-goto-local-auto-isearch)
7587 nil)
7588 (org-defkey map "q" 'org-goto-quit)
7589 (org-defkey map "n" 'outline-next-visible-heading)
7590 (org-defkey map "p" 'outline-previous-visible-heading)
7591 (org-defkey map "f" 'outline-forward-same-level)
7592 (org-defkey map "b" 'outline-backward-same-level)
7593 (org-defkey map "u" 'outline-up-heading))
7594 (org-defkey map "/" 'org-occur)
7595 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7596 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7597 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7598 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7599 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7600 map)))
7602 (defconst org-goto-help
7603 "Browse buffer copy, to find location or copy text.%s
7604 RET=jump to location C-g=quit and return to previous location
7605 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7607 (defvar org-goto-start-pos) ; dynamically scoped parameter
7609 (defun org-goto (&optional alternative-interface)
7610 "Look up a different location in the current file, keeping current visibility.
7612 When you want look-up or go to a different location in a
7613 document, the fastest way is often to fold the entire buffer and
7614 then dive into the tree. This method has the disadvantage, that
7615 the previous location will be folded, which may not be what you
7616 want.
7618 This command works around this by showing a copy of the current
7619 buffer in an indirect buffer, in overview mode. You can dive
7620 into the tree in that copy, use org-occur and incremental search
7621 to find a location. When pressing RET or `Q', the command
7622 returns to the original buffer in which the visibility is still
7623 unchanged. After RET it will also jump to the location selected
7624 in the indirect buffer and expose the headline hierarchy above.
7626 With a prefix argument, use the alternative interface: e.g., if
7627 `org-goto-interface' is `outline' use `outline-path-completion'."
7628 (interactive "P")
7629 (org-goto-map)
7630 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7631 (org-refile-use-outline-path t)
7632 (org-refile-target-verify-function nil)
7633 (interface
7634 (if (not alternative-interface)
7635 org-goto-interface
7636 (if (eq org-goto-interface 'outline)
7637 'outline-path-completion
7638 'outline)))
7639 (org-goto-start-pos (point))
7640 (selected-point
7641 (if (eq interface 'outline)
7642 (car (org-get-location (current-buffer) org-goto-help))
7643 (let ((pa (org-refile-get-location "Goto")))
7644 (org-refile-check-position pa)
7645 (nth 3 pa)))))
7646 (if selected-point
7647 (progn
7648 (org-mark-ring-push org-goto-start-pos)
7649 (goto-char selected-point)
7650 (when (or (outline-invisible-p) (org-invisible-p2))
7651 (org-show-context 'org-goto)))
7652 (message "Quit"))))
7654 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7655 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7656 (defvar org-goto-local-auto-isearch-map) ; defined below
7658 (defun org-get-location (_buf help)
7659 "Let the user select a location in current buffer.
7660 This function uses a recursive edit. It returns the selected position
7661 or nil."
7662 (org-no-popups
7663 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7664 (isearch-hide-immediately nil)
7665 (isearch-search-fun-function
7666 (lambda () 'org-goto-local-search-headings))
7667 (org-goto-selected-point org-goto-exit-command))
7668 (save-excursion
7669 (save-window-excursion
7670 (delete-other-windows)
7671 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7672 (pop-to-buffer-same-window
7673 (condition-case nil
7674 (make-indirect-buffer (current-buffer) "*org-goto*")
7675 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7676 (with-output-to-temp-buffer "*Org Help*"
7677 (princ (format help (if org-goto-auto-isearch
7678 " Just type for auto-isearch."
7679 " n/p/f/b/u to navigate, q to quit."))))
7680 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7681 (setq buffer-read-only nil)
7682 (let ((org-startup-truncated t)
7683 (org-startup-folded nil)
7684 (org-startup-align-all-tables nil))
7685 (org-mode)
7686 (org-overview))
7687 (setq buffer-read-only t)
7688 (if (and (boundp 'org-goto-start-pos)
7689 (integer-or-marker-p org-goto-start-pos))
7690 (progn (goto-char org-goto-start-pos)
7691 (when (outline-invisible-p)
7692 (org-show-set-visibility 'lineage)))
7693 (goto-char (point-min)))
7694 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7695 (message "Select location and press RET")
7696 (use-local-map org-goto-map)
7697 (recursive-edit)))
7698 (kill-buffer "*org-goto*")
7699 (cons org-goto-selected-point org-goto-exit-command))))
7701 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7702 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7703 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7704 (if (fboundp 'isearch-other-control-char)
7705 (progn
7706 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7707 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7708 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7709 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7710 (define-key org-goto-local-auto-isearch-map [return] nil))
7712 (defun org-goto-local-search-headings (string bound noerror)
7713 "Search and make sure that any matches are in headlines."
7714 (catch 'return
7715 (while (if isearch-forward
7716 (search-forward string bound noerror)
7717 (search-backward string bound noerror))
7718 (when (save-match-data
7719 (and (save-excursion
7720 (beginning-of-line)
7721 (looking-at org-complex-heading-regexp))
7722 (or (not (match-beginning 5))
7723 (< (point) (match-beginning 5)))))
7724 (throw 'return (point))))))
7726 (defun org-goto-local-auto-isearch ()
7727 "Start isearch."
7728 (interactive)
7729 (goto-char (point-min))
7730 (let ((keys (this-command-keys)))
7731 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7732 (isearch-mode t)
7733 (isearch-process-search-char (string-to-char keys)))))
7735 (defun org-goto-ret (&optional _arg)
7736 "Finish `org-goto' by going to the new location."
7737 (interactive "P")
7738 (setq org-goto-selected-point (point))
7739 (setq org-goto-exit-command 'return)
7740 (throw 'exit nil))
7742 (defun org-goto-left ()
7743 "Finish `org-goto' by going to the new location."
7744 (interactive)
7745 (if (org-at-heading-p)
7746 (progn
7747 (beginning-of-line 1)
7748 (setq org-goto-selected-point (point)
7749 org-goto-exit-command 'left)
7750 (throw 'exit nil))
7751 (user-error "Not on a heading")))
7753 (defun org-goto-right ()
7754 "Finish `org-goto' by going to the new location."
7755 (interactive)
7756 (if (org-at-heading-p)
7757 (progn
7758 (setq org-goto-selected-point (point)
7759 org-goto-exit-command 'right)
7760 (throw 'exit nil))
7761 (user-error "Not on a heading")))
7763 (defun org-goto-quit ()
7764 "Finish `org-goto' without cursor motion."
7765 (interactive)
7766 (setq org-goto-selected-point nil)
7767 (setq org-goto-exit-command 'quit)
7768 (throw 'exit nil))
7770 ;;; Indirect buffer display of subtrees
7772 (defvar org-indirect-dedicated-frame nil
7773 "This is the frame being used for indirect tree display.")
7774 (defvar org-last-indirect-buffer nil)
7776 (defun org-tree-to-indirect-buffer (&optional arg)
7777 "Create indirect buffer and narrow it to current subtree.
7779 With a numerical prefix ARG, go up to this level and then take that tree.
7780 If ARG is negative, go up that many levels.
7782 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7783 indirect buffer previously made with this command, to avoid proliferation of
7784 indirect buffers. However, when you call the command with a \
7785 `\\[universal-argument]' prefix, or
7786 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7787 so that you can work with several indirect buffers at the same time. If
7788 `org-indirect-buffer-display' is `dedicated-frame', the \
7789 `\\[universal-argument]' prefix also
7790 requests that a new frame be made for the new buffer, so that the dedicated
7791 frame is not changed."
7792 (interactive "P")
7793 (let ((cbuf (current-buffer))
7794 (cwin (selected-window))
7795 (pos (point))
7796 beg end level heading ibuf)
7797 (save-excursion
7798 (org-back-to-heading t)
7799 (when (numberp arg)
7800 (setq level (org-outline-level))
7801 (when (< arg 0) (setq arg (+ level arg)))
7802 (while (> (setq level (org-outline-level)) arg)
7803 (org-up-heading-safe)))
7804 (setq beg (point)
7805 heading (org-get-heading 'no-tags))
7806 (org-end-of-subtree t t)
7807 (when (org-at-heading-p) (backward-char 1))
7808 (setq end (point)))
7809 (when (and (buffer-live-p org-last-indirect-buffer)
7810 (not (eq org-indirect-buffer-display 'new-frame))
7811 (not arg))
7812 (kill-buffer org-last-indirect-buffer))
7813 (setq ibuf (org-get-indirect-buffer cbuf heading)
7814 org-last-indirect-buffer ibuf)
7815 (cond
7816 ((or (eq org-indirect-buffer-display 'new-frame)
7817 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7818 (select-frame (make-frame))
7819 (delete-other-windows)
7820 (pop-to-buffer-same-window ibuf)
7821 (org-set-frame-title heading))
7822 ((eq org-indirect-buffer-display 'dedicated-frame)
7823 (raise-frame
7824 (select-frame (or (and org-indirect-dedicated-frame
7825 (frame-live-p org-indirect-dedicated-frame)
7826 org-indirect-dedicated-frame)
7827 (setq org-indirect-dedicated-frame (make-frame)))))
7828 (delete-other-windows)
7829 (pop-to-buffer-same-window ibuf)
7830 (org-set-frame-title (concat "Indirect: " heading)))
7831 ((eq org-indirect-buffer-display 'current-window)
7832 (pop-to-buffer-same-window ibuf))
7833 ((eq org-indirect-buffer-display 'other-window)
7834 (pop-to-buffer ibuf))
7835 (t (error "Invalid value")))
7836 (narrow-to-region beg end)
7837 (outline-show-all)
7838 (goto-char pos)
7839 (run-hook-with-args 'org-cycle-hook 'all)
7840 (and (window-live-p cwin) (select-window cwin))))
7842 (defun org-get-indirect-buffer (&optional buffer heading)
7843 (setq buffer (or buffer (current-buffer)))
7844 (let ((n 1) (base (buffer-name buffer)) bname)
7845 (while (buffer-live-p
7846 (get-buffer
7847 (setq bname
7848 (concat base "-"
7849 (if heading (concat heading "-" (number-to-string n))
7850 (number-to-string n))))))
7851 (setq n (1+ n)))
7852 (condition-case nil
7853 (make-indirect-buffer buffer bname 'clone)
7854 (error (make-indirect-buffer buffer bname)))))
7856 (defun org-set-frame-title (title)
7857 "Set the title of the current frame to the string TITLE."
7858 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7860 ;;;; Structure editing
7862 ;;; Inserting headlines
7864 (defun org--line-empty-p (n)
7865 "Is the Nth next line empty?
7867 Counts the current line as N = 1 and the previous line as N = 0;
7868 see `beginning-of-line'."
7869 (save-excursion
7870 (and (not (bobp))
7871 (or (beginning-of-line n) t)
7872 (save-match-data
7873 (looking-at "[ \t]*$")))))
7875 (defun org-previous-line-empty-p ()
7876 "Is the previous line a blank line?
7877 When NEXT is non-nil, check the next line instead."
7878 (org--line-empty-p 0))
7880 (defun org-next-line-empty-p ()
7881 "Is the previous line a blank line?
7882 When NEXT is non-nil, check the next line instead."
7883 (org--line-empty-p 2))
7885 (defun org--blank-before-heading-p (&optional parent)
7886 "Non-nil when an empty line should precede a new heading here.
7887 When optional argument PARENT is non-nil, consider parent
7888 headline instead of current one."
7889 (pcase (assq 'heading org-blank-before-new-entry)
7890 (`(heading . auto)
7891 (save-excursion
7892 (org-with-limited-levels
7893 (unless (and (org-before-first-heading-p)
7894 (not (outline-next-heading)))
7895 (org-back-to-heading t)
7896 (when parent (org-up-heading-safe))
7897 (cond ((not (bobp))
7898 (org-previous-line-empty-p))
7899 ((outline-next-heading)
7900 (org-previous-line-empty-p))
7901 ;; Ignore trailing spaces on last buffer line.
7902 ((progn (skip-chars-backward " \t") (bolp))
7903 (org-previous-line-empty-p))
7904 (t nil))))))
7905 (`(heading . ,value) value)
7906 (_ nil)))
7908 (defun org-insert-heading (&optional arg invisible-ok top)
7909 "Insert a new heading or an item with the same depth at point.
7911 If point is at the beginning of a heading, insert a new heading
7912 or a new headline above the current one. When at the beginning
7913 of a regular line of text, turn it into a heading.
7915 If point is in the middle of a line, split it and create a new
7916 headline with the text in the current line after point (see
7917 `org-M-RET-may-split-line' on how to modify this behavior). As
7918 a special case, on a headline, splitting can only happen on the
7919 title itself. E.g., this excludes breaking stars or tags.
7921 With a `\\[universal-argument]' prefix, set \
7922 `org-insert-heading-respect-content' to
7923 a non-nil value for the duration of the command. This forces the
7924 insertion of a heading after the current subtree, independently
7925 on the location of point.
7927 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7928 insert the heading at the end of the tree
7929 above the current heading. For example, if point is within a
7930 2nd-level heading, then it will insert a 2nd-level heading at
7931 the end of the 1st-level parent subtree.
7933 When INVISIBLE-OK is set, stop at invisible headlines when going
7934 back. This is important for non-interactive uses of the
7935 command.
7937 When optional argument TOP is non-nil, insert a level 1 heading,
7938 unconditionally."
7939 (interactive "P")
7940 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7941 (level (org-current-level))
7942 (stars (make-string (if (and level (not top)) level 1) ?*)))
7943 (cond
7944 ((or org-insert-heading-respect-content
7945 (member arg '((4) (16)))
7946 (and (not invisible-ok)
7947 (invisible-p (max (1- (point)) (point-min)))))
7948 ;; Position point at the location of insertion.
7949 (if (not level) ;before first headline
7950 (org-with-limited-levels (outline-next-heading))
7951 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7952 ;; is nil.
7953 (org-with-limited-levels (org-back-to-heading invisible-ok))
7954 (cond ((equal arg '(16))
7955 (org-up-heading-safe)
7956 (org-end-of-subtree t t))
7958 (org-end-of-subtree t t))))
7959 (unless (bolp) (insert "\n")) ;ensure final newline
7960 (unless (and blank? (org-previous-line-empty-p))
7961 (org-N-empty-lines-before-current (if blank? 1 0)))
7962 (insert stars " \n")
7963 (forward-char -1))
7964 ;; At a headline...
7965 ((org-at-heading-p)
7966 (cond ((bolp)
7967 (when blank? (save-excursion (insert "\n")))
7968 (save-excursion (insert stars " \n"))
7969 (unless (and blank? (org-previous-line-empty-p))
7970 (org-N-empty-lines-before-current (if blank? 1 0)))
7971 (end-of-line))
7972 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7973 (org-match-line org-complex-heading-regexp)
7974 (org-pos-in-match-range (point) 4))
7975 ;; Grab the text that should moved to the new headline.
7976 ;; Preserve tags.
7977 (let ((split (delete-and-extract-region (point) (match-end 4))))
7978 (if (looking-at "[ \t]*$") (replace-match "")
7979 (org-set-tags nil t))
7980 (end-of-line)
7981 (when blank? (insert "\n"))
7982 (insert "\n" stars " ")
7983 (when (org-string-nw-p split) (insert split))
7984 (insert "\n")
7985 (forward-char -1)))
7987 (end-of-line)
7988 (when blank? (insert "\n"))
7989 (insert "\n" stars " \n")
7990 (forward-char -1))))
7991 ;; On regular text, turn line into a headline or split, if
7992 ;; appropriate.
7993 ((bolp)
7994 (insert stars " ")
7995 (unless (and blank? (org-previous-line-empty-p))
7996 (org-N-empty-lines-before-current (if blank? 1 0))))
7998 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7999 (end-of-line))
8000 (insert "\n" stars " ")
8001 (unless (and blank? (org-previous-line-empty-p))
8002 (org-N-empty-lines-before-current (if blank? 1 0))))))
8003 (run-hooks 'org-insert-heading-hook))
8005 (defun org-N-empty-lines-before-current (n)
8006 "Make the number of empty lines before current exactly N.
8007 So this will delete or add empty lines."
8008 (let ((column (current-column))
8009 (empty-lines (make-string n ?\n)))
8010 (beginning-of-line)
8011 (let ((p (point)))
8012 (skip-chars-backward " \r\t\n")
8013 (unless (bolp) (forward-line))
8014 (delete-region (point) p))
8015 (insert empty-lines)
8016 (move-to-column column)))
8018 (defun org-get-heading (&optional no-tags no-todo)
8019 "Return the heading of the current entry, without the stars.
8020 When NO-TAGS is non-nil, don't include tags.
8021 When NO-TODO is non-nil, don't include TODO keywords."
8022 (save-excursion
8023 (org-back-to-heading t)
8024 (let ((case-fold-search nil))
8025 (cond
8026 ((and no-tags no-todo)
8027 (looking-at org-complex-heading-regexp)
8028 ;; Return value has to be a string, but match group 4 is
8029 ;; optional.
8030 (or (match-string 4) ""))
8031 (no-tags
8032 (looking-at (concat org-outline-regexp
8033 "\\(.*?\\)"
8034 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8035 (match-string 1))
8036 (no-todo
8037 (looking-at org-todo-line-regexp)
8038 (match-string 3))
8039 (t (looking-at org-heading-regexp)
8040 (match-string 2))))))
8042 (defvar orgstruct-mode) ; defined below
8044 (defun org-heading-components ()
8045 "Return the components of the current heading.
8046 This is a list with the following elements:
8047 - the level as an integer
8048 - the reduced level, different if `org-odd-levels-only' is set.
8049 - the TODO keyword, or nil
8050 - the priority character, like ?A, or nil if no priority is given
8051 - the headline text itself, or the tags string if no headline text
8052 - the tags string, or nil."
8053 (save-excursion
8054 (org-back-to-heading t)
8055 (when (let (case-fold-search)
8056 (looking-at
8057 (if orgstruct-mode
8058 org-heading-regexp
8059 org-complex-heading-regexp)))
8060 (if orgstruct-mode
8061 (list (length (match-string 1))
8062 (org-reduced-level (length (match-string 1)))
8065 (match-string 2)
8066 nil)
8067 (list (length (match-string 1))
8068 (org-reduced-level (length (match-string 1)))
8069 (match-string-no-properties 2)
8070 (and (match-end 3) (aref (match-string 3) 2))
8071 (match-string-no-properties 4)
8072 (match-string-no-properties 5))))))
8074 (defun org-get-entry ()
8075 "Get the entry text, after heading, entire subtree."
8076 (save-excursion
8077 (org-back-to-heading t)
8078 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8080 (defun org-edit-headline (&optional heading)
8081 "Edit the current headline.
8082 Set it to HEADING when provided."
8083 (interactive)
8084 (org-with-wide-buffer
8085 (org-back-to-heading t)
8086 (let ((case-fold-search nil))
8087 (when (looking-at org-complex-heading-regexp)
8088 (let* ((old (match-string-no-properties 4))
8089 (new (save-match-data
8090 (org-trim (or heading (read-string "Edit: " old))))))
8091 (unless (equal old new)
8092 (if old (replace-match new t t nil 4)
8093 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8094 (insert " " new))
8095 (org-set-tags nil t)
8096 (when (looking-at "[ \t]*$") (replace-match ""))))))))
8098 (defun org-insert-heading-after-current ()
8099 "Insert a new heading with same level as current, after current subtree."
8100 (interactive)
8101 (org-back-to-heading)
8102 (org-insert-heading)
8103 (org-move-subtree-down)
8104 (end-of-line 1))
8106 (defun org-insert-heading-respect-content (&optional invisible-ok)
8107 "Insert heading with `org-insert-heading-respect-content' set to t."
8108 (interactive)
8109 (org-insert-heading '(4) invisible-ok))
8111 (defun org-insert-todo-heading-respect-content (&optional force-state)
8112 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8113 (interactive)
8114 (org-insert-todo-heading force-state '(4)))
8116 (defun org-insert-todo-heading (arg &optional force-heading)
8117 "Insert a new heading with the same level and TODO state as current heading.
8119 If the heading has no TODO state, or if the state is DONE, use
8120 the first state (TODO by default). Also with one prefix arg,
8121 force first state. With two prefix args, force inserting at the
8122 end of the parent subtree.
8124 When called at a plain list item, insert a new item with an
8125 unchecked check box."
8126 (interactive "P")
8127 (when (or force-heading (not (org-insert-item 'checkbox)))
8128 (org-insert-heading (or (and (equal arg '(16)) '(16))
8129 force-heading))
8130 (save-excursion
8131 (org-back-to-heading)
8132 (outline-previous-heading)
8133 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
8134 (let* ((new-mark-x
8135 (if (or (equal arg '(4))
8136 (not (match-beginning 2))
8137 (member (match-string 2) org-done-keywords))
8138 (car org-todo-keywords-1)
8139 (match-string 2)))
8140 (new-mark
8142 (run-hook-with-args-until-success
8143 'org-todo-get-default-hook new-mark-x nil)
8144 new-mark-x)))
8145 (beginning-of-line 1)
8146 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8147 (if org-treat-insert-todo-heading-as-state-change
8148 (org-todo new-mark)
8149 (insert new-mark " "))))
8150 (when org-provide-todo-statistics
8151 (org-update-parent-todo-statistics))))
8153 (defun org-insert-subheading (arg)
8154 "Insert a new subheading and demote it.
8155 Works for outline headings and for plain lists alike."
8156 (interactive "P")
8157 (org-insert-heading arg)
8158 (cond
8159 ((org-at-heading-p) (org-do-demote))
8160 ((org-at-item-p) (org-indent-item))))
8162 (defun org-insert-todo-subheading (arg)
8163 "Insert a new subheading with TODO keyword or checkbox and demote it.
8164 Works for outline headings and for plain lists alike."
8165 (interactive "P")
8166 (org-insert-todo-heading arg)
8167 (cond
8168 ((org-at-heading-p) (org-do-demote))
8169 ((org-at-item-p) (org-indent-item))))
8171 ;;; Promotion and Demotion
8173 (defvar org-after-demote-entry-hook nil
8174 "Hook run after an entry has been demoted.
8175 The cursor will be at the beginning of the entry.
8176 When a subtree is being demoted, the hook will be called for each node.")
8178 (defvar org-after-promote-entry-hook nil
8179 "Hook run after an entry has been promoted.
8180 The cursor will be at the beginning of the entry.
8181 When a subtree is being promoted, the hook will be called for each node.")
8183 (defun org-promote-subtree ()
8184 "Promote the entire subtree.
8185 See also `org-promote'."
8186 (interactive)
8187 (save-excursion
8188 (org-with-limited-levels (org-map-tree 'org-promote)))
8189 (org-fix-position-after-promote))
8191 (defun org-demote-subtree ()
8192 "Demote the entire subtree.
8193 See `org-demote' and `org-promote'."
8194 (interactive)
8195 (save-excursion
8196 (org-with-limited-levels (org-map-tree 'org-demote)))
8197 (org-fix-position-after-promote))
8199 (defun org-do-promote ()
8200 "Promote the current heading higher up the tree.
8201 If the region is active in `transient-mark-mode', promote all
8202 headings in the region."
8203 (interactive)
8204 (save-excursion
8205 (if (org-region-active-p)
8206 (org-map-region 'org-promote (region-beginning) (region-end))
8207 (org-promote)))
8208 (org-fix-position-after-promote))
8210 (defun org-do-demote ()
8211 "Demote the current heading lower down the tree.
8212 If the region is active in `transient-mark-mode', demote all
8213 headings in the region."
8214 (interactive)
8215 (save-excursion
8216 (if (org-region-active-p)
8217 (org-map-region 'org-demote (region-beginning) (region-end))
8218 (org-demote)))
8219 (org-fix-position-after-promote))
8221 (defun org-fix-position-after-promote ()
8222 "Fix cursor position and indentation after demoting/promoting."
8223 (let ((pos (point)))
8224 (when (save-excursion
8225 (beginning-of-line)
8226 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8227 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8228 (cond ((eobp) (insert " "))
8229 ((eolp) (insert " "))
8230 ((equal (char-after) ?\s) (forward-char 1))))))
8232 (defun org-current-level ()
8233 "Return the level of the current entry, or nil if before the first headline.
8234 The level is the number of stars at the beginning of the
8235 headline. Use `org-reduced-level' to remove the effect of
8236 `org-odd-levels'. Unlike to `org-outline-level', this function
8237 ignores inlinetasks."
8238 (let ((level (org-with-limited-levels (org-outline-level))))
8239 (and (> level 0) level)))
8241 (defun org-get-previous-line-level ()
8242 "Return the outline depth of the last headline before the current line.
8243 Returns 0 for the first headline in the buffer, and nil if before the
8244 first headline."
8245 (and (org-current-level)
8246 (or (and (/= (line-beginning-position) (point-min))
8247 (save-excursion (beginning-of-line 0) (org-current-level)))
8248 0)))
8250 (defun org-reduced-level (l)
8251 "Compute the effective level of a heading.
8252 This takes into account the setting of `org-odd-levels-only'."
8253 (cond
8254 ((zerop l) 0)
8255 (org-odd-levels-only (1+ (floor (/ l 2))))
8256 (t l)))
8258 (defun org-level-increment ()
8259 "Return the number of stars that will be added or removed at a
8260 time to headlines when structure editing, based on the value of
8261 `org-odd-levels-only'."
8262 (if org-odd-levels-only 2 1))
8264 (defun org-get-valid-level (level &optional change)
8265 "Rectify a level change under the influence of `org-odd-levels-only'
8266 LEVEL is a current level, CHANGE is by how much the level should be
8267 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8268 even level numbers will become the next higher odd number."
8269 (if org-odd-levels-only
8270 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8271 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8272 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8273 (max 1 (+ level (or change 0)))))
8275 (defun org-promote ()
8276 "Promote the current heading higher up the tree."
8277 (org-with-wide-buffer
8278 (org-back-to-heading t)
8279 (let* ((after-change-functions (remq 'flyspell-after-change-function
8280 after-change-functions))
8281 (level (save-match-data (funcall outline-level)))
8282 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8283 (diff (abs (- level (length up-head) -1))))
8284 (cond
8285 ((and (= level 1) org-allow-promoting-top-level-subtree)
8286 (replace-match "# " nil t))
8287 ((= level 1)
8288 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8289 (t (replace-match up-head nil t)))
8290 (unless (= level 1)
8291 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8292 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8293 (run-hooks 'org-after-promote-entry-hook))))
8295 (defun org-demote ()
8296 "Demote the current heading lower down the tree."
8297 (org-with-wide-buffer
8298 (org-back-to-heading t)
8299 (let* ((after-change-functions (remq 'flyspell-after-change-function
8300 after-change-functions))
8301 (level (save-match-data (funcall outline-level)))
8302 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8303 (diff (abs (- level (length down-head) -1))))
8304 (replace-match down-head nil t)
8305 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8306 (when org-adapt-indentation (org-fixup-indentation diff))
8307 (run-hooks 'org-after-demote-entry-hook))))
8309 (defun org-cycle-level ()
8310 "Cycle the level of an empty headline through possible states.
8311 This goes first to child, then to parent, level, then up the hierarchy.
8312 After top level, it switches back to sibling level."
8313 (interactive)
8314 (let ((org-adapt-indentation nil))
8315 (when (org-point-at-end-of-empty-headline)
8316 (setq this-command 'org-cycle-level) ; Only needed for caching
8317 (let ((cur-level (org-current-level))
8318 (prev-level (org-get-previous-line-level)))
8319 (cond
8320 ;; If first headline in file, promote to top-level.
8321 ((= prev-level 0)
8322 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8323 do (org-do-promote)))
8324 ;; If same level as prev, demote one.
8325 ((= prev-level cur-level)
8326 (org-do-demote))
8327 ;; If parent is top-level, promote to top level if not already.
8328 ((= prev-level 1)
8329 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8330 do (org-do-promote)))
8331 ;; If top-level, return to prev-level.
8332 ((= cur-level 1)
8333 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8334 do (org-do-demote)))
8335 ;; If less than prev-level, promote one.
8336 ((< cur-level prev-level)
8337 (org-do-promote))
8338 ;; If deeper than prev-level, promote until higher than
8339 ;; prev-level.
8340 ((> cur-level prev-level)
8341 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8342 do (org-do-promote))))
8343 t))))
8345 (defun org-map-tree (fun)
8346 "Call FUN for every heading underneath the current one."
8347 (org-back-to-heading t)
8348 (let ((level (funcall outline-level)))
8349 (save-excursion
8350 (funcall fun)
8351 (while (and (progn
8352 (outline-next-heading)
8353 (> (funcall outline-level) level))
8354 (not (eobp)))
8355 (funcall fun)))))
8357 (defun org-map-region (fun beg end)
8358 "Call FUN for every heading between BEG and END."
8359 (let ((org-ignore-region t))
8360 (save-excursion
8361 (setq end (copy-marker end))
8362 (goto-char beg)
8363 (when (and (re-search-forward org-outline-regexp-bol nil t)
8364 (< (point) end))
8365 (funcall fun))
8366 (while (and (progn
8367 (outline-next-heading)
8368 (< (point) end))
8369 (not (eobp)))
8370 (funcall fun)))))
8372 (defun org-fixup-indentation (diff)
8373 "Change the indentation in the current entry by DIFF.
8375 DIFF is an integer. Indentation is done according to the
8376 following rules:
8378 - Planning information and property drawers are always indented
8379 according to the new level of the headline;
8381 - Footnote definitions and their contents are ignored;
8383 - Inlinetasks' boundaries are not shifted;
8385 - Empty lines are ignored;
8387 - Other lines' indentation are shifted by DIFF columns, unless
8388 it would introduce a structural change in the document, in
8389 which case no shifting is done at all.
8391 Assume point is at a heading or an inlinetask beginning."
8392 (org-with-wide-buffer
8393 (narrow-to-region (line-beginning-position)
8394 (save-excursion
8395 (if (org-with-limited-levels (org-at-heading-p))
8396 (org-with-limited-levels (outline-next-heading))
8397 (org-inlinetask-goto-end))
8398 (point)))
8399 (forward-line)
8400 ;; Indent properly planning info and property drawer.
8401 (when (looking-at-p org-planning-line-re)
8402 (org-indent-line)
8403 (forward-line))
8404 (when (looking-at org-property-drawer-re)
8405 (goto-char (match-end 0))
8406 (forward-line)
8407 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8408 (catch 'no-shift
8409 (when (zerop diff) (throw 'no-shift nil))
8410 ;; If DIFF is negative, first check if a shift is possible at all
8411 ;; (e.g., it doesn't break structure). This can only happen if
8412 ;; some contents are not properly indented.
8413 (let ((case-fold-search t))
8414 (when (< diff 0)
8415 (let ((diff (- diff))
8416 (forbidden-re (concat org-outline-regexp
8417 "\\|"
8418 (substring org-footnote-definition-re 1))))
8419 (save-excursion
8420 (while (not (eobp))
8421 (cond
8422 ((looking-at-p "[ \t]*$") (forward-line))
8423 ((and (looking-at-p org-footnote-definition-re)
8424 (let ((e (org-element-at-point)))
8425 (and (eq (org-element-type e) 'footnote-definition)
8426 (goto-char (org-element-property :end e))))))
8427 ((looking-at-p org-outline-regexp) (forward-line))
8428 ;; Give up if shifting would move before column 0 or
8429 ;; if it would introduce a headline or a footnote
8430 ;; definition.
8432 (skip-chars-forward " \t")
8433 (let ((ind (current-column)))
8434 (when (or (< ind diff)
8435 (and (= ind diff) (looking-at-p forbidden-re)))
8436 (throw 'no-shift nil)))
8437 ;; Ignore contents of example blocks and source
8438 ;; blocks if their indentation is meant to be
8439 ;; preserved. Jump to block's closing line.
8440 (beginning-of-line)
8441 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8442 (let ((e (org-element-at-point)))
8443 (and (memq (org-element-type e)
8444 '(example-block src-block))
8445 (or org-src-preserve-indentation
8446 (org-element-property :preserve-indent e))
8447 (goto-char (org-element-property :end e))
8448 (progn (skip-chars-backward " \r\t\n")
8449 (beginning-of-line)
8450 t))))
8451 (forward-line))))))))
8452 ;; Shift lines but footnote definitions, inlinetasks boundaries
8453 ;; by DIFF. Also skip contents of source or example blocks
8454 ;; when indentation is meant to be preserved.
8455 (while (not (eobp))
8456 (cond
8457 ((and (looking-at-p org-footnote-definition-re)
8458 (let ((e (org-element-at-point)))
8459 (and (eq (org-element-type e) 'footnote-definition)
8460 (goto-char (org-element-property :end e))))))
8461 ((looking-at-p org-outline-regexp) (forward-line))
8462 ((looking-at-p "[ \t]*$") (forward-line))
8464 (indent-line-to (+ (org-get-indentation) diff))
8465 (beginning-of-line)
8466 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8467 (let ((e (org-element-at-point)))
8468 (and (memq (org-element-type e)
8469 '(example-block src-block))
8470 (or org-src-preserve-indentation
8471 (org-element-property :preserve-indent e))
8472 (goto-char (org-element-property :end e))
8473 (progn (skip-chars-backward " \r\t\n")
8474 (beginning-of-line)
8475 t))))
8476 (forward-line)))))))))
8478 (defun org-convert-to-odd-levels ()
8479 "Convert an Org file with all levels allowed to one with odd levels.
8480 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8481 level 5 etc."
8482 (interactive)
8483 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8484 (let ((outline-level 'org-outline-level)
8485 (org-odd-levels-only nil) n)
8486 (save-excursion
8487 (goto-char (point-min))
8488 (while (re-search-forward "^\\*\\*+ " nil t)
8489 (setq n (- (length (match-string 0)) 2))
8490 (while (>= (setq n (1- n)) 0)
8491 (org-demote))
8492 (end-of-line 1))))))
8494 (defun org-convert-to-oddeven-levels ()
8495 "Convert an Org file with only odd levels to one with odd/even levels.
8496 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8497 file contains a section with an even level, conversion would
8498 destroy the structure of the file. An error is signaled in this
8499 case."
8500 (interactive)
8501 (goto-char (point-min))
8502 ;; First check if there are no even levels
8503 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8504 (org-show-set-visibility 'canonical)
8505 (error "Not all levels are odd in this file. Conversion not possible"))
8506 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8507 (let ((outline-regexp org-outline-regexp)
8508 (outline-level 'org-outline-level)
8509 (org-odd-levels-only nil) n)
8510 (save-excursion
8511 (goto-char (point-min))
8512 (while (re-search-forward "^\\*\\*+ " nil t)
8513 (setq n (/ (1- (length (match-string 0))) 2))
8514 (while (>= (setq n (1- n)) 0)
8515 (org-promote))
8516 (end-of-line 1))))))
8518 (defun org-tr-level (n)
8519 "Make N odd if required."
8520 (if org-odd-levels-only (1+ (/ n 2)) n))
8522 ;;; Vertical tree motion, cutting and pasting of subtrees
8524 (defun org-move-subtree-up (&optional arg)
8525 "Move the current subtree up past ARG headlines of the same level."
8526 (interactive "p")
8527 (org-move-subtree-down (- (prefix-numeric-value arg))))
8529 (defun org-move-subtree-down (&optional arg)
8530 "Move the current subtree down past ARG headlines of the same level."
8531 (interactive "p")
8532 (setq arg (prefix-numeric-value arg))
8533 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8534 'org-get-last-sibling))
8535 (ins-point (make-marker))
8536 (cnt (abs arg))
8537 (col (current-column))
8538 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8539 ;; Select the tree
8540 (org-back-to-heading)
8541 (setq beg0 (point))
8542 (save-excursion
8543 (setq ne-beg (org-back-over-empty-lines))
8544 (setq beg (point)))
8545 (save-match-data
8546 (save-excursion (outline-end-of-heading)
8547 (setq folded (outline-invisible-p)))
8548 (progn (org-end-of-subtree nil t)
8549 (unless (eobp) (backward-char))))
8550 (outline-next-heading)
8551 (setq ne-end (org-back-over-empty-lines))
8552 (setq end (point))
8553 (goto-char beg0)
8554 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8555 ;; include less whitespace
8556 (save-excursion
8557 (goto-char beg)
8558 (forward-line (- ne-beg ne-end))
8559 (setq beg (point))))
8560 ;; Find insertion point, with error handling
8561 (while (> cnt 0)
8562 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8563 (progn (goto-char beg0)
8564 (user-error "Cannot move past superior level or buffer limit")))
8565 (setq cnt (1- cnt)))
8566 (when (> arg 0)
8567 ;; Moving forward - still need to move over subtree
8568 (org-end-of-subtree t t)
8569 (save-excursion
8570 (org-back-over-empty-lines)
8571 (or (bolp) (newline))))
8572 (setq ne-ins (org-back-over-empty-lines))
8573 (move-marker ins-point (point))
8574 (setq txt (buffer-substring beg end))
8575 (org-save-markers-in-region beg end)
8576 (delete-region beg end)
8577 (org-remove-empty-overlays-at beg)
8578 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8579 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8580 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8581 (let ((bbb (point)))
8582 (insert-before-markers txt)
8583 (org-reinstall-markers-in-region bbb)
8584 (move-marker ins-point bbb))
8585 (or (bolp) (insert "\n"))
8586 (setq ins-end (point))
8587 (goto-char ins-point)
8588 (org-skip-whitespace)
8589 (when (and (< arg 0)
8590 (org-first-sibling-p)
8591 (> ne-ins ne-beg))
8592 ;; Move whitespace back to beginning
8593 (save-excursion
8594 (goto-char ins-end)
8595 (let ((kill-whole-line t))
8596 (kill-line (- ne-ins ne-beg)) (point)))
8597 (insert (make-string (- ne-ins ne-beg) ?\n)))
8598 (move-marker ins-point nil)
8599 (if folded
8600 (outline-hide-subtree)
8601 (org-show-entry)
8602 (org-show-children)
8603 (org-cycle-hide-drawers 'children))
8604 (org-clean-visibility-after-subtree-move)
8605 ;; move back to the initial column we were at
8606 (move-to-column col)))
8608 (defvar org-subtree-clip ""
8609 "Clipboard for cut and paste of subtrees.
8610 This is actually only a copy of the kill, because we use the normal kill
8611 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8613 (defvar org-subtree-clip-folded nil
8614 "Was the last copied subtree folded?
8615 This is used to fold the tree back after pasting.")
8617 (defun org-cut-subtree (&optional n)
8618 "Cut the current subtree into the clipboard.
8619 With prefix arg N, cut this many sequential subtrees.
8620 This is a short-hand for marking the subtree and then cutting it."
8621 (interactive "p")
8622 (org-copy-subtree n 'cut))
8624 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8625 "Copy the current subtree it in the clipboard.
8626 With prefix arg N, copy this many sequential subtrees.
8627 This is a short-hand for marking the subtree and then copying it.
8628 If CUT is non-nil, actually cut the subtree.
8629 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8630 of some markers in the region, even if CUT is non-nil. This is
8631 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8632 (interactive "p")
8633 (let (beg end folded (beg0 (point)))
8634 (if (called-interactively-p 'any)
8635 (org-back-to-heading nil) ; take what looks like a subtree
8636 (org-back-to-heading t)) ; take what is really there
8637 (setq beg (point))
8638 (skip-chars-forward " \t\r\n")
8639 (save-match-data
8640 (if nosubtrees
8641 (outline-next-heading)
8642 (save-excursion (outline-end-of-heading)
8643 (setq folded (outline-invisible-p)))
8644 (ignore-errors (org-forward-heading-same-level (1- n) t))
8645 (org-end-of-subtree t t)))
8646 ;; Include the end of an inlinetask
8647 (when (and (featurep 'org-inlinetask)
8648 (looking-at-p (concat (org-inlinetask-outline-regexp)
8649 "END[ \t]*$")))
8650 (end-of-line))
8651 (setq end (point))
8652 (goto-char beg0)
8653 (when (> end beg)
8654 (setq org-subtree-clip-folded folded)
8655 (when (or cut force-store-markers)
8656 (org-save-markers-in-region beg end))
8657 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8658 (setq org-subtree-clip (current-kill 0))
8659 (message "%s: Subtree(s) with %d characters"
8660 (if cut "Cut" "Copied")
8661 (length org-subtree-clip)))))
8663 (defun org-paste-subtree (&optional level tree for-yank remove)
8664 "Paste the clipboard as a subtree, with modification of headline level.
8665 The entire subtree is promoted or demoted in order to match a new headline
8666 level.
8668 If the cursor is at the beginning of a headline, the same level as
8669 that headline is used to paste the tree.
8671 If not, the new level is derived from the *visible* headings
8672 before and after the insertion point, and taken to be the inferior headline
8673 level of the two. So if the previous visible heading is level 3 and the
8674 next is level 4 (or vice versa), level 4 will be used for insertion.
8675 This makes sure that the subtree remains an independent subtree and does
8676 not swallow low level entries.
8678 You can also force a different level, either by using a numeric prefix
8679 argument, or by inserting the heading marker by hand. For example, if the
8680 cursor is after \"*****\", then the tree will be shifted to level 5.
8682 If optional TREE is given, use this text instead of the kill ring.
8684 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8685 move back over whitespace before inserting, and move point to the end of
8686 the inserted text when done.
8688 When REMOVE is non-nil, remove the subtree from the clipboard."
8689 (interactive "P")
8690 (setq tree (or tree (and kill-ring (current-kill 0))))
8691 (unless (org-kill-is-subtree-p tree)
8692 (user-error "%s"
8693 (substitute-command-keys
8694 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8695 (org-with-limited-levels
8696 (let* ((visp (not (outline-invisible-p)))
8697 (txt tree)
8698 (^re_ "\\(\\*+\\)[ \t]*")
8699 (old-level (if (string-match org-outline-regexp-bol txt)
8700 (- (match-end 0) (match-beginning 0) 1)
8701 -1))
8702 (force-level (cond (level (prefix-numeric-value level))
8703 ((and (looking-at "[ \t]*$")
8704 (string-match
8705 "^\\*+$" (buffer-substring
8706 (point-at-bol) (point))))
8707 (- (match-end 0) (match-beginning 0)))
8708 ((and (bolp)
8709 (looking-at org-outline-regexp))
8710 (- (match-end 0) (point) 1))))
8711 (previous-level (save-excursion
8712 (condition-case nil
8713 (progn
8714 (outline-previous-visible-heading 1)
8715 (if (looking-at ^re_)
8716 (- (match-end 0) (match-beginning 0) 1)
8718 (error 1))))
8719 (next-level (save-excursion
8720 (condition-case nil
8721 (progn
8722 (or (looking-at org-outline-regexp)
8723 (outline-next-visible-heading 1))
8724 (if (looking-at ^re_)
8725 (- (match-end 0) (match-beginning 0) 1)
8727 (error 1))))
8728 (new-level (or force-level (max previous-level next-level)))
8729 (shift (if (or (= old-level -1)
8730 (= new-level -1)
8731 (= old-level new-level))
8733 (- new-level old-level)))
8734 (delta (if (> shift 0) -1 1))
8735 (func (if (> shift 0) 'org-demote 'org-promote))
8736 (org-odd-levels-only nil)
8737 beg end newend)
8738 ;; Remove the forced level indicator
8739 (when force-level
8740 (delete-region (point-at-bol) (point)))
8741 ;; Paste
8742 (beginning-of-line (if (bolp) 1 2))
8743 (setq beg (point))
8744 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8745 (insert-before-markers txt)
8746 (unless (string-suffix-p "\n" txt) (insert "\n"))
8747 (setq newend (point))
8748 (org-reinstall-markers-in-region beg)
8749 (setq end (point))
8750 (goto-char beg)
8751 (skip-chars-forward " \t\n\r")
8752 (setq beg (point))
8753 (when (and (outline-invisible-p) visp)
8754 (save-excursion (outline-show-heading)))
8755 ;; Shift if necessary
8756 (unless (= shift 0)
8757 (save-restriction
8758 (narrow-to-region beg end)
8759 (while (not (= shift 0))
8760 (org-map-region func (point-min) (point-max))
8761 (setq shift (+ delta shift)))
8762 (goto-char (point-min))
8763 (setq newend (point-max))))
8764 (when (or (called-interactively-p 'interactive) for-yank)
8765 (message "Clipboard pasted as level %d subtree" new-level))
8766 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8767 kill-ring
8768 (eq org-subtree-clip (current-kill 0))
8769 org-subtree-clip-folded)
8770 ;; The tree was folded before it was killed/copied
8771 (outline-hide-subtree))
8772 (and for-yank (goto-char newend))
8773 (and remove (setq kill-ring (cdr kill-ring))))))
8775 (defun org-kill-is-subtree-p (&optional txt)
8776 "Check if the current kill is an outline subtree, or a set of trees.
8777 Returns nil if kill does not start with a headline, or if the first
8778 headline level is not the largest headline level in the tree.
8779 So this will actually accept several entries of equal levels as well,
8780 which is OK for `org-paste-subtree'.
8781 If optional TXT is given, check this string instead of the current kill."
8782 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8783 (re (org-get-limited-outline-regexp))
8784 (^re (concat "^" re))
8785 (start-level (and kill
8786 (string-match
8787 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8788 kill)
8789 (- (match-end 2) (match-beginning 2) 1)))
8790 (start (1+ (or (match-beginning 2) -1))))
8791 (if (not start-level)
8792 (progn
8793 nil) ;; does not even start with a heading
8794 (catch 'exit
8795 (while (setq start (string-match ^re kill (1+ start)))
8796 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8797 (throw 'exit nil)))
8798 t))))
8800 (defvar org-markers-to-move nil
8801 "Markers that should be moved with a cut-and-paste operation.
8802 Those markers are stored together with their positions relative to
8803 the start of the region.")
8805 (defun org-save-markers-in-region (beg end)
8806 "Check markers in region.
8807 If these markers are between BEG and END, record their position relative
8808 to BEG, so that after moving the block of text, we can put the markers back
8809 into place.
8810 This function gets called just before an entry or tree gets cut from the
8811 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8812 called immediately, to move the markers with the entries."
8813 (setq org-markers-to-move nil)
8814 (when (featurep 'org-clock)
8815 (org-clock-save-markers-for-cut-and-paste beg end))
8816 (when (featurep 'org-agenda)
8817 (org-agenda-save-markers-for-cut-and-paste beg end)))
8819 (defun org-check-and-save-marker (marker beg end)
8820 "Check if MARKER is between BEG and END.
8821 If yes, remember the marker and the distance to BEG."
8822 (when (and (marker-buffer marker)
8823 (equal (marker-buffer marker) (current-buffer))
8824 (>= marker beg) (< marker end))
8825 (push (cons marker (- marker beg)) org-markers-to-move)))
8827 (defun org-reinstall-markers-in-region (beg)
8828 "Move all remembered markers to their position relative to BEG."
8829 (dolist (x org-markers-to-move)
8830 (move-marker (car x) (+ beg (cdr x))))
8831 (setq org-markers-to-move nil))
8833 (defun org-narrow-to-subtree ()
8834 "Narrow buffer to the current subtree."
8835 (interactive)
8836 (save-excursion
8837 (save-match-data
8838 (org-with-limited-levels
8839 (narrow-to-region
8840 (progn (org-back-to-heading t) (point))
8841 (progn (org-end-of-subtree t t)
8842 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8843 (point)))))))
8845 (defun org-narrow-to-block ()
8846 "Narrow buffer to the current block."
8847 (interactive)
8848 (let* ((case-fold-search t)
8849 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8850 "^[ \t]*#\\+end_.*")))
8851 (if blockp
8852 (narrow-to-region (car blockp) (cdr blockp))
8853 (user-error "Not in a block"))))
8855 (defun org-clone-subtree-with-time-shift (n &optional shift)
8856 "Clone the task (subtree) at point N times.
8857 The clones will be inserted as siblings.
8859 In interactive use, the user will be prompted for the number of
8860 clones to be produced. If the entry has a timestamp, the user
8861 will also be prompted for a time shift, which may be a repeater
8862 as used in time stamps, for example `+3d'. To disable this,
8863 you can call the function with a universal prefix argument.
8865 When a valid repeater is given and the entry contains any time
8866 stamps, the clones will become a sequence in time, with time
8867 stamps in the subtree shifted for each clone produced. If SHIFT
8868 is nil or the empty string, time stamps will be left alone. The
8869 ID property of the original subtree is removed.
8871 In each clone, all the CLOCK entries will be removed. This
8872 prevents Org from considering that the clocked times overlap.
8874 If the original subtree did contain time stamps with a repeater,
8875 the following will happen:
8876 - the repeater will be removed in each clone
8877 - an additional clone will be produced, with the current, unshifted
8878 date(s) in the entry.
8879 - the original entry will be placed *after* all the clones, with
8880 repeater intact.
8881 - the start days in the repeater in the original entry will be shifted
8882 to past the last clone.
8883 In this way you can spell out a number of instances of a repeating task,
8884 and still retain the repeater to cover future instances of the task.
8886 As described above, N+1 clones are produced when the original
8887 subtree has a repeater. Setting N to 0, then, can be used to
8888 remove the repeater from a subtree and create a shifted clone
8889 with the original repeater."
8890 (interactive "nNumber of clones to produce: ")
8891 (let ((shift
8892 (or shift
8893 (if (and (not (equal current-prefix-arg '(4)))
8894 (save-excursion
8895 (re-search-forward org-ts-regexp-both
8896 (save-excursion
8897 (org-end-of-subtree t)
8898 (point)) t)))
8899 (read-from-minibuffer
8900 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8901 ""))) ;; No time shift
8902 (n-no-remove -1)
8903 (drawer-re org-drawer-regexp)
8904 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8905 beg end template task idprop
8906 shift-n shift-what doshift nmin nmax)
8907 (unless (wholenump n)
8908 (user-error "Invalid number of replications %s" n))
8909 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8910 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8911 shift)))
8912 (user-error "Invalid shift specification %s" shift))
8913 (when doshift
8914 (setq shift-n (string-to-number (match-string 1 shift))
8915 shift-what (cdr (assoc (match-string 2 shift)
8916 '(("d" . day) ("w" . week)
8917 ("m" . month) ("y" . year))))))
8918 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8919 (setq nmin 1 nmax n)
8920 (org-back-to-heading t)
8921 (setq beg (point))
8922 (setq idprop (org-entry-get nil "ID"))
8923 (org-end-of-subtree t t)
8924 (or (bolp) (insert "\n"))
8925 (setq end (point))
8926 (setq template (buffer-substring beg end))
8927 (when (and doshift
8928 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8929 (delete-region beg end)
8930 (setq end beg)
8931 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8932 (goto-char end)
8933 (cl-loop for n from nmin to nmax do
8934 ;; prepare clone
8935 (with-temp-buffer
8936 (insert template)
8937 (org-mode)
8938 (goto-char (point-min))
8939 (org-show-subtree)
8940 (and idprop (if org-clone-delete-id
8941 (org-entry-delete nil "ID")
8942 (org-id-get-create t)))
8943 (unless (= n 0)
8944 (while (re-search-forward org-clock-re nil t)
8945 (kill-whole-line))
8946 (goto-char (point-min))
8947 (while (re-search-forward drawer-re nil t)
8948 (org-remove-empty-drawer-at (point))))
8949 (goto-char (point-min))
8950 (when doshift
8951 (while (re-search-forward org-ts-regexp-both nil t)
8952 (org-timestamp-change (* n shift-n) shift-what))
8953 (unless (= n n-no-remove)
8954 (goto-char (point-min))
8955 (while (re-search-forward org-ts-regexp nil t)
8956 (save-excursion
8957 (goto-char (match-beginning 0))
8958 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8959 (delete-region (match-beginning 1) (match-end 1)))))))
8960 (setq task (buffer-string)))
8961 (insert task))
8962 (goto-char beg)))
8964 ;;; Outline Sorting
8966 (defun org-sort (with-case)
8967 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8968 Optional argument WITH-CASE means sort case-sensitively."
8969 (interactive "P")
8970 (cond
8971 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8972 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8974 (org-call-with-arg 'org-sort-entries with-case))))
8976 (defun org-sort-remove-invisible (s)
8977 "Remove invisible part of links and emphasis markers from string S."
8978 (remove-text-properties 0 (length s) org-rm-props s)
8979 (replace-regexp-in-string
8980 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8981 (replace-regexp-in-string
8982 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8983 (org-link-display-format s)
8984 t t) t t))
8986 (defvar org-priority-regexp) ; defined later in the file
8988 (defvar org-after-sorting-entries-or-items-hook nil
8989 "Hook that is run after a bunch of entries or items have been sorted.
8990 When children are sorted, the cursor is in the parent line when this
8991 hook gets called. When a region or a plain list is sorted, the cursor
8992 will be in the first entry of the sorted region/list.")
8994 (defun org-sort-entries
8995 (&optional with-case sorting-type getkey-func compare-func property)
8996 "Sort entries on a certain level of an outline tree.
8997 If there is an active region, the entries in the region are sorted.
8998 Else, if the cursor is before the first entry, sort the top-level items.
8999 Else, the children of the entry at point are sorted.
9001 Sorting can be alphabetically, numerically, by date/time as given by
9002 a time stamp, by a property, by priority order, or by a custom function.
9004 The command prompts for the sorting type unless it has been given to the
9005 function through the SORTING-TYPE argument, which needs to be a character,
9006 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9007 the precise meaning of each character:
9009 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9010 c By creation time, which is assumed to be the first inactive time stamp
9011 at the beginning of a line.
9012 d By deadline date/time.
9013 k By clocking time.
9014 n Numerically, by converting the beginning of the entry/item to a number.
9015 o By order of TODO keywords.
9016 p By priority according to the cookie.
9017 r By the value of a property.
9018 s By scheduled date/time.
9019 t By date/time, either the first active time stamp in the entry, or, if
9020 none exist, by the first inactive one.
9022 Capital letters will reverse the sort order.
9024 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9025 called with point at the beginning of the record. It must return either
9026 a string or a number that should serve as the sorting key for that record.
9028 Comparing entries ignores case by default. However, with an optional argument
9029 WITH-CASE, the sorting considers case as well.
9031 Sorting is done against the visible part of the headlines, it ignores hidden
9032 links.
9034 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
9035 (interactive "P")
9036 (let ((case-func (if with-case 'identity 'downcase))
9037 (cmstr
9038 ;; The clock marker is lost when using `sort-subr', let's
9039 ;; store the clocking string.
9040 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9041 (save-excursion
9042 (goto-char org-clock-marker)
9043 (buffer-substring-no-properties (line-beginning-position)
9044 (point)))))
9045 start beg end stars re re2
9046 txt what tmp)
9047 ;; Find beginning and end of region to sort
9048 (cond
9049 ((org-region-active-p)
9050 ;; we will sort the region
9051 (setq end (region-end)
9052 what "region")
9053 (goto-char (region-beginning))
9054 (unless (org-at-heading-p) (outline-next-heading))
9055 (setq start (point)))
9056 ((or (org-at-heading-p)
9057 (ignore-errors (progn (org-back-to-heading) t)))
9058 ;; we will sort the children of the current headline
9059 (org-back-to-heading)
9060 (setq start (point)
9061 end (progn (org-end-of-subtree t t)
9062 (or (bolp) (insert "\n"))
9063 (when (>= (org-back-over-empty-lines) 1)
9064 (forward-line 1))
9065 (point))
9066 what "children")
9067 (goto-char start)
9068 (outline-show-subtree)
9069 (outline-next-heading))
9071 ;; we will sort the top-level entries in this file
9072 (goto-char (point-min))
9073 (or (org-at-heading-p) (outline-next-heading))
9074 (setq start (point))
9075 (goto-char (point-max))
9076 (beginning-of-line 1)
9077 (when (looking-at ".*?\\S-")
9078 ;; File ends in a non-white line
9079 (end-of-line 1)
9080 (insert "\n"))
9081 (setq end (point-max))
9082 (setq what "top-level")
9083 (goto-char start)
9084 (outline-show-all)))
9086 (setq beg (point))
9087 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9089 (looking-at "\\(\\*+\\)")
9090 (setq stars (match-string 1)
9091 re (concat "^" (regexp-quote stars) " +")
9092 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9093 txt (buffer-substring beg end))
9094 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9095 (when (and (not (equal stars "*")) (string-match re2 txt))
9096 (user-error "Region to sort contains a level above the first entry"))
9098 (unless sorting-type
9099 (message
9100 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9101 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9102 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9103 what)
9104 (setq sorting-type (read-char-exclusive))
9106 (unless getkey-func
9107 (and (= (downcase sorting-type) ?f)
9108 (setq getkey-func
9109 (completing-read "Sort using function: "
9110 obarray 'fboundp t nil nil))
9111 (setq getkey-func (intern getkey-func))))
9113 (and (= (downcase sorting-type) ?r)
9114 (not property)
9115 (setq property
9116 (completing-read "Property: "
9117 (mapcar #'list (org-buffer-property-keys t))
9118 nil t))))
9120 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9121 (message "Sorting entries...")
9123 (save-restriction
9124 (narrow-to-region start end)
9125 (let ((dcst (downcase sorting-type))
9126 (case-fold-search nil)
9127 (now (current-time)))
9128 (sort-subr
9129 (/= dcst sorting-type)
9130 ;; This function moves to the beginning character of the "record" to
9131 ;; be sorted.
9132 (lambda nil
9133 (if (re-search-forward re nil t)
9134 (goto-char (match-beginning 0))
9135 (goto-char (point-max))))
9136 ;; This function moves to the last character of the "record" being
9137 ;; sorted.
9138 (lambda nil
9139 (save-match-data
9140 (condition-case nil
9141 (outline-forward-same-level 1)
9142 (error
9143 (goto-char (point-max))))))
9144 ;; This function returns the value that gets sorted against.
9145 (lambda nil
9146 (cond
9147 ((= dcst ?n)
9148 (if (looking-at org-complex-heading-regexp)
9149 (string-to-number (org-sort-remove-invisible (match-string 4)))
9150 nil))
9151 ((= dcst ?a)
9152 (if (looking-at org-complex-heading-regexp)
9153 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9154 nil))
9155 ((= dcst ?k)
9156 (or (get-text-property (point) :org-clock-minutes) 0))
9157 ((= dcst ?t)
9158 (let ((end (save-excursion (outline-next-heading) (point))))
9159 (if (or (re-search-forward org-ts-regexp end t)
9160 (re-search-forward org-ts-regexp-both end t))
9161 (org-time-string-to-seconds (match-string 0))
9162 (float-time now))))
9163 ((= dcst ?c)
9164 (let ((end (save-excursion (outline-next-heading) (point))))
9165 (if (re-search-forward
9166 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9167 end t)
9168 (org-time-string-to-seconds (match-string 0))
9169 (float-time now))))
9170 ((= dcst ?s)
9171 (let ((end (save-excursion (outline-next-heading) (point))))
9172 (if (re-search-forward org-scheduled-time-regexp end t)
9173 (org-time-string-to-seconds (match-string 1))
9174 (float-time now))))
9175 ((= dcst ?d)
9176 (let ((end (save-excursion (outline-next-heading) (point))))
9177 (if (re-search-forward org-deadline-time-regexp end t)
9178 (org-time-string-to-seconds (match-string 1))
9179 (float-time now))))
9180 ((= dcst ?p)
9181 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9182 (string-to-char (match-string 2))
9183 org-default-priority))
9184 ((= dcst ?r)
9185 (or (org-entry-get nil property) ""))
9186 ((= dcst ?o)
9187 (when (looking-at org-complex-heading-regexp)
9188 (let* ((m (match-string 2))
9189 (s (if (member m org-done-keywords) '- '+)))
9190 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9191 ((= dcst ?f)
9192 (if getkey-func
9193 (progn
9194 (setq tmp (funcall getkey-func))
9195 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9196 tmp)
9197 (error "Invalid key function `%s'" getkey-func)))
9198 (t (error "Invalid sorting type `%c'" sorting-type))))
9200 (cond
9201 ((= dcst ?a) 'string<)
9202 ((= dcst ?f) compare-func)
9203 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9204 (run-hooks 'org-after-sorting-entries-or-items-hook)
9205 ;; Reset the clock marker if needed
9206 (when cmstr
9207 (save-excursion
9208 (goto-char start)
9209 (search-forward cmstr nil t)
9210 (move-marker org-clock-marker (point))))
9211 (message "Sorting entries...done")))
9213 ;;; The orgstruct minor mode
9215 ;; Define a minor mode which can be used in other modes in order to
9216 ;; integrate the Org mode structure editing commands.
9218 ;; This is really a hack, because the Org mode structure commands use
9219 ;; keys which normally belong to the major mode. Here is how it
9220 ;; works: The minor mode defines all the keys necessary to operate the
9221 ;; structure commands, but wraps the commands into a function which
9222 ;; tests if the cursor is currently at a headline or a plain list
9223 ;; item. If that is the case, the structure command is used,
9224 ;; temporarily setting many Org mode variables like regular
9225 ;; expressions for filling etc. However, when any of those keys is
9226 ;; used at a different location, function uses `key-binding' to look
9227 ;; up if the key has an associated command in another currently active
9228 ;; keymap (minor modes, major mode, global), and executes that
9229 ;; command. There might be problems if any of the keys is otherwise
9230 ;; used as a prefix key.
9232 (defcustom orgstruct-heading-prefix-regexp ""
9233 "Regexp that matches the custom prefix of Org headlines in
9234 orgstruct(++)-mode."
9235 :group 'org
9236 :version "24.4"
9237 :package-version '(Org . "8.3")
9238 :type 'regexp)
9239 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9241 (defcustom orgstruct-setup-hook nil
9242 "Hook run after orgstruct-mode-map is filled."
9243 :group 'org
9244 :version "24.4"
9245 :package-version '(Org . "8.0")
9246 :type 'hook)
9248 (defvar orgstruct-initialized nil)
9250 (defvar org-local-vars nil
9251 "List of local variables, for use by `orgstruct-mode'.")
9253 ;;;###autoload
9254 (define-minor-mode orgstruct-mode
9255 "Toggle the minor mode `orgstruct-mode'.
9256 This mode is for using Org mode structure commands in other
9257 modes. The following keys behave as if Org mode were active, if
9258 the cursor is on a headline, or on a plain list item (both as
9259 defined by Org mode)."
9260 nil " OrgStruct" (make-sparse-keymap)
9261 (funcall (if orgstruct-mode
9262 'add-to-invisibility-spec
9263 'remove-from-invisibility-spec)
9264 '(outline . t))
9265 (when orgstruct-mode
9266 (org-load-modules-maybe)
9267 (unless orgstruct-initialized
9268 (orgstruct-setup)
9269 (setq orgstruct-initialized t))))
9271 ;;;###autoload
9272 (defun turn-on-orgstruct ()
9273 "Unconditionally turn on `orgstruct-mode'."
9274 (orgstruct-mode 1))
9276 (defvar-local orgstruct-is-++ nil
9277 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9278 (defvar-local org-fb-vars nil)
9279 (defun orgstruct++-mode (&optional arg)
9280 "Toggle `orgstruct-mode', the enhanced version of it.
9281 In addition to setting orgstruct-mode, this also exports all
9282 indentation and autofilling variables from Org mode into the
9283 buffer. It will also recognize item context in multiline items."
9284 (interactive "P")
9285 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9286 (if (< arg 1)
9287 (progn (orgstruct-mode -1)
9288 (dolist (v org-fb-vars)
9289 (set (make-local-variable (car v))
9290 (if (eq (car-safe (cadr v)) 'quote)
9291 (cl-cadadr v)
9292 (nth 1 v)))))
9293 (orgstruct-mode 1)
9294 (setq org-fb-vars nil)
9295 (unless org-local-vars
9296 (setq org-local-vars (org-get-local-variables)))
9297 (let (var val)
9298 (dolist (x org-local-vars)
9299 (when (string-match
9300 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9301 \\|fill-prefix\\|indent-\\)"
9302 (symbol-name (car x)))
9303 (setq var (car x) val (nth 1 x))
9304 (push (list var `(quote ,(eval var))) org-fb-vars)
9305 (set (make-local-variable var)
9306 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9307 (setq-local orgstruct-is-++ t))))
9309 ;;;###autoload
9310 (defun turn-on-orgstruct++ ()
9311 "Unconditionally turn on `orgstruct++-mode'."
9312 (orgstruct++-mode 1))
9314 (defun orgstruct-error ()
9315 "Error when there is no default binding for a structure key."
9316 (interactive)
9317 (funcall (if (fboundp 'user-error)
9318 'user-error
9319 'error)
9320 "This key has no function outside structure elements"))
9322 (defun orgstruct-setup ()
9323 "Setup orgstruct keymap."
9324 (dolist (cell '((org-demote . t)
9325 (org-metaleft . t)
9326 (org-metaright . t)
9327 (org-promote . t)
9328 (org-shiftmetaleft . t)
9329 (org-shiftmetaright . t)
9330 org-backward-element
9331 org-backward-heading-same-level
9332 org-ctrl-c-ret
9333 org-ctrl-c-minus
9334 org-ctrl-c-star
9335 org-cycle
9336 org-force-cycle-archived
9337 org-forward-heading-same-level
9338 org-insert-heading
9339 org-insert-heading-respect-content
9340 org-kill-note-or-show-branches
9341 org-mark-subtree
9342 org-meta-return
9343 org-metadown
9344 org-metaup
9345 org-narrow-to-subtree
9346 org-promote-subtree
9347 org-reveal
9348 org-shiftdown
9349 org-shiftleft
9350 org-shiftmetadown
9351 org-shiftmetaup
9352 org-shiftright
9353 org-shifttab
9354 org-shifttab
9355 org-shiftup
9356 org-show-children
9357 org-show-subtree
9358 org-sort
9359 org-up-element
9360 outline-demote
9361 outline-next-visible-heading
9362 outline-previous-visible-heading
9363 outline-promote
9364 outline-up-heading))
9365 (let ((f (or (car-safe cell) cell))
9366 (disable-when-heading-prefix (cdr-safe cell)))
9367 (when (fboundp f)
9368 (let ((new-bindings))
9369 (dolist (binding (nconc (where-is-internal f org-mode-map)
9370 (where-is-internal f outline-mode-map)))
9371 (push binding new-bindings)
9372 ;; TODO use local-function-key-map
9373 (dolist (rep '(("<tab>" . "TAB")
9374 ("<return>" . "RET")
9375 ("<escape>" . "ESC")
9376 ("<delete>" . "DEL")))
9377 (setq binding (read-kbd-macro
9378 (let ((case-fold-search))
9379 (replace-regexp-in-string
9380 (regexp-quote (cdr rep))
9381 (car rep)
9382 (key-description binding)))))
9383 (cl-pushnew binding new-bindings :test 'equal)))
9384 (dolist (binding new-bindings)
9385 (let ((key (lookup-key orgstruct-mode-map binding)))
9386 (when (or (not key) (numberp key))
9387 (ignore-errors
9388 (org-defkey orgstruct-mode-map
9389 binding
9390 (orgstruct-make-binding
9391 f binding disable-when-heading-prefix))))))))))
9392 (run-hooks 'orgstruct-setup-hook))
9394 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9395 "Create a function for binding in the structure minor mode.
9396 FUN is the command to call inside a table. KEY is the key that
9397 should be checked in for a command to execute outside of tables.
9398 Non-nil `disable-when-heading-prefix' means to disable the command
9399 if `orgstruct-heading-prefix-regexp' is not empty."
9400 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9401 (let ((nname name)
9402 (i 0))
9403 (while (fboundp (intern nname))
9404 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9405 (setq name (intern nname)))
9406 (eval
9407 (let ((bindings '((org-heading-regexp
9408 (concat "^"
9409 orgstruct-heading-prefix-regexp
9410 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9411 (org-outline-regexp
9412 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9413 (org-outline-regexp-bol
9414 (concat "^" org-outline-regexp))
9415 (outline-regexp org-outline-regexp)
9416 (outline-heading-end-regexp "\n")
9417 (outline-level 'org-outline-level)
9418 (outline-heading-alist))))
9419 `(defun ,name (arg)
9420 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9421 "Outside of structure, run the binding of `"
9422 (key-description key) "'."
9423 (when disable-when-heading-prefix
9424 (concat
9425 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9426 "back to the default binding due to limitations of Org's implementation of\n"
9427 "`" (symbol-name fun) "'.")))
9428 (interactive "p")
9429 (let* ((disable
9430 ,(and disable-when-heading-prefix
9431 '(not (string= orgstruct-heading-prefix-regexp ""))))
9432 (fallback
9433 (or disable
9434 (not
9435 (let* ,bindings
9436 (org-context-p 'headline 'item
9437 ,(when (memq fun
9438 '(org-insert-heading
9439 org-insert-heading-respect-content
9440 org-meta-return))
9441 '(when orgstruct-is-++
9442 'item-body))))))))
9443 (if fallback
9444 (let* ((orgstruct-mode)
9445 (binding
9446 (let ((key ,key))
9447 (catch 'exit
9448 (dolist
9449 (rep
9450 '(nil
9451 ("<\\([^>]*\\)tab>" . "\\1TAB")
9452 ("<\\([^>]*\\)return>" . "\\1RET")
9453 ("<\\([^>]*\\)escape>" . "\\1ESC")
9454 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9455 nil)
9456 (when rep
9457 (setq key (read-kbd-macro
9458 (let ((case-fold-search))
9459 (replace-regexp-in-string
9460 (car rep)
9461 (cdr rep)
9462 (key-description key))))))
9463 (when (key-binding key)
9464 (throw 'exit (key-binding key))))))))
9465 (if (keymapp binding)
9466 (org-set-transient-map binding)
9467 (let ((func (or binding
9468 (unless disable
9469 'orgstruct-error))))
9470 (when func
9471 (call-interactively func)))))
9472 (org-run-like-in-org-mode
9473 (lambda ()
9474 (interactive)
9475 (let* ,bindings
9476 (call-interactively ',fun)))))))))
9477 name))
9479 (defun org-contextualize-keys (alist contexts)
9480 "Return valid elements in ALIST depending on CONTEXTS.
9482 `org-agenda-custom-commands' or `org-capture-templates' are the
9483 values used for ALIST, and `org-agenda-custom-commands-contexts'
9484 or `org-capture-templates-contexts' are the associated contexts
9485 definitions."
9486 (let ((contexts
9487 ;; normalize contexts
9488 (mapcar
9489 (lambda(c) (cond ((listp (cadr c))
9490 (list (car c) (car c) (nth 1 c)))
9491 ((string= "" (cadr c))
9492 (list (car c) (car c) (nth 2 c)))
9493 (t c)))
9494 contexts))
9495 (a alist) r s)
9496 ;; loop over all commands or templates
9497 (dolist (c a)
9498 (let (vrules repl)
9499 (cond
9500 ((not (assoc (car c) contexts))
9501 (push c r))
9502 ((and (assoc (car c) contexts)
9503 (setq vrules (org-contextualize-validate-key
9504 (car c) contexts)))
9505 (mapc (lambda (vr)
9506 (unless (equal (car vr) (cadr vr))
9507 (setq repl vr)))
9508 vrules)
9509 (if (not repl) (push c r)
9510 (push (cadr repl) s)
9511 (push
9512 (cons (car c)
9513 (cdr (or (assoc (cadr repl) alist)
9514 (error "Undefined key `%s' as contextual replacement for `%s'"
9515 (cadr repl) (car c)))))
9516 r))))))
9517 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9518 (delq
9520 (delete-dups
9521 (mapcar (lambda (x)
9522 (let ((tpl (car x)))
9523 (unless (delq
9525 (mapcar (lambda (y)
9526 (equal y tpl))
9528 x)))
9529 (reverse r))))))
9531 (defun org-contextualize-validate-key (key contexts)
9532 "Check CONTEXTS for agenda or capture KEY."
9533 (let (res)
9534 (dolist (r contexts)
9535 (dolist (rr (car (last r)))
9536 (when
9537 (and (equal key (car r))
9538 (if (functionp rr) (funcall rr)
9539 (or (and (eq (car rr) 'in-file)
9540 (buffer-file-name)
9541 (string-match (cdr rr) (buffer-file-name)))
9542 (and (eq (car rr) 'in-mode)
9543 (string-match (cdr rr) (symbol-name major-mode)))
9544 (and (eq (car rr) 'in-buffer)
9545 (string-match (cdr rr) (buffer-name)))
9546 (when (and (eq (car rr) 'not-in-file)
9547 (buffer-file-name))
9548 (not (string-match (cdr rr) (buffer-file-name))))
9549 (when (eq (car rr) 'not-in-mode)
9550 (not (string-match (cdr rr) (symbol-name major-mode))))
9551 (when (eq (car rr) 'not-in-buffer)
9552 (not (string-match (cdr rr) (buffer-name)))))))
9553 (push r res))))
9554 (delete-dups (delq nil res))))
9556 (defun org-context-p (&rest contexts)
9557 "Check if local context is any of CONTEXTS.
9558 Possible values in the list of contexts are `table', `headline', and `item'."
9559 (let ((pos (point)))
9560 (goto-char (point-at-bol))
9561 (prog1 (or (and (memq 'table contexts)
9562 (looking-at "[ \t]*|"))
9563 (and (memq 'headline contexts)
9564 (looking-at org-outline-regexp))
9565 (and (memq 'item contexts)
9566 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9567 (and (memq 'item-body contexts)
9568 (org-in-item-p)))
9569 (goto-char pos))))
9571 (defconst org-unique-local-variables
9572 '(org-element--cache
9573 org-element--cache-objects
9574 org-element--cache-sync-keys
9575 org-element--cache-sync-requests
9576 org-element--cache-sync-timer)
9577 "List of local variables that cannot be transferred to another buffer.")
9579 (defun org-get-local-variables ()
9580 "Return a list of all local variables in an Org mode buffer."
9581 (delq nil
9582 (mapcar
9583 (lambda (x)
9584 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9585 (name (car binding)))
9586 (and (not (get name 'org-state))
9587 (not (memq name org-unique-local-variables))
9588 (string-match-p
9589 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9590 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9591 (symbol-name name))
9592 binding)))
9593 (with-temp-buffer
9594 (org-mode)
9595 (buffer-local-variables)))))
9597 (defun org-clone-local-variables (from-buffer &optional regexp)
9598 "Clone local variables from FROM-BUFFER.
9599 Optional argument REGEXP selects variables to clone."
9600 (dolist (pair (buffer-local-variables from-buffer))
9601 (let ((name (car pair)))
9602 (when (and (symbolp name)
9603 (not (memq name org-unique-local-variables))
9604 (or (null regexp) (string-match regexp (symbol-name name))))
9605 (set (make-local-variable name) (cdr pair))))))
9607 ;;;###autoload
9608 (defun org-run-like-in-org-mode (cmd)
9609 "Run a command, pretending that the current buffer is in Org mode.
9610 This will temporarily bind local variables that are typically bound in
9611 Org mode to the values they have in Org mode, and then interactively
9612 call CMD."
9613 (org-load-modules-maybe)
9614 (unless org-local-vars
9615 (setq org-local-vars (org-get-local-variables)))
9616 (let (binds)
9617 (dolist (var org-local-vars)
9618 (when (or (not (boundp (car var)))
9619 (eq (symbol-value (car var))
9620 (default-value (car var))))
9621 (push (list (car var) `(quote ,(cadr var))) binds)))
9622 (eval `(let ,binds
9623 (call-interactively (quote ,cmd))))))
9625 (defun org-get-category (&optional pos force-refresh)
9626 "Get the category applying to position POS."
9627 (save-match-data
9628 (when force-refresh (org-refresh-category-properties))
9629 (let ((pos (or pos (point))))
9630 (or (get-text-property pos 'org-category)
9631 (progn (org-refresh-category-properties)
9632 (get-text-property pos 'org-category))))))
9634 ;;; Refresh properties
9636 (defun org-refresh-properties (dprop tprop)
9637 "Refresh buffer text properties.
9638 DPROP is the drawer property and TPROP is either the
9639 corresponding text property to set, or an alist with each element
9640 being a text property (as a symbol) and a function to apply to
9641 the value of the drawer property."
9642 (let ((case-fold-search t)
9643 (inhibit-read-only t))
9644 (org-with-silent-modifications
9645 (org-with-wide-buffer
9646 (goto-char (point-min))
9647 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9648 (org-refresh-property tprop (match-string-no-properties 1)))))))
9650 (defun org-refresh-property (tprop p)
9651 "Refresh the buffer text property TPROP from the drawer property P.
9652 The refresh happens only for the current tree (not subtree)."
9653 (unless (org-before-first-heading-p)
9654 (save-excursion
9655 (org-back-to-heading t)
9656 (if (symbolp tprop)
9657 ;; TPROP is a text property symbol
9658 (put-text-property
9659 (point) (or (outline-next-heading) (point-max)) tprop p)
9660 ;; TPROP is an alist with (properties . function) elements
9661 (dolist (al tprop)
9662 (save-excursion
9663 (put-text-property
9664 (line-beginning-position) (or (outline-next-heading) (point-max))
9665 (car al)
9666 (funcall (cdr al) p))))))))
9668 (defun org-refresh-category-properties ()
9669 "Refresh category text properties in the buffer."
9670 (let ((case-fold-search t)
9671 (inhibit-read-only t)
9672 (default-category
9673 (cond ((null org-category)
9674 (if buffer-file-name
9675 (file-name-sans-extension
9676 (file-name-nondirectory buffer-file-name))
9677 "???"))
9678 ((symbolp org-category) (symbol-name org-category))
9679 (t org-category))))
9680 (org-with-silent-modifications
9681 (org-with-wide-buffer
9682 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9683 ;; This is the default category for the buffer. If none is
9684 ;; found, fall-back to `org-category' or buffer file name.
9685 (put-text-property
9686 (point-min) (point-max)
9687 'org-category
9688 (catch 'buffer-category
9689 (goto-char (point-max))
9690 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9691 (let ((element (org-element-at-point)))
9692 (when (eq (org-element-type element) 'keyword)
9693 (throw 'buffer-category
9694 (org-element-property :value element)))))
9695 default-category))
9696 ;; Set sub-tree specific categories.
9697 (goto-char (point-min))
9698 (let ((regexp (org-re-property "CATEGORY")))
9699 (while (re-search-forward regexp nil t)
9700 (let ((value (match-string-no-properties 3)))
9701 (when (org-at-property-p)
9702 (put-text-property
9703 (save-excursion (org-back-to-heading t) (point))
9704 (save-excursion (org-end-of-subtree t t) (point))
9705 'org-category
9706 value)))))))))
9708 (defun org-refresh-stats-properties ()
9709 "Refresh stats text properties in the buffer."
9710 (let (stats)
9711 (org-with-silent-modifications
9712 (org-with-wide-buffer
9713 (goto-char (point-min))
9714 (while (re-search-forward
9715 (concat org-outline-regexp-bol ".*"
9716 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9717 nil t)
9718 (setq stats (cond ((equal (match-string 3) "0") 0)
9719 ((match-string 2)
9720 (/ (* (string-to-number (match-string 2)) 100)
9721 (string-to-number (match-string 3))))
9722 (t (string-to-number (match-string 1)))))
9723 (org-back-to-heading t)
9724 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9725 'org-stats stats))))))
9727 (defun org-refresh-effort-properties ()
9728 "Refresh effort properties"
9729 (org-refresh-properties
9730 org-effort-property
9731 '((effort . identity)
9732 (effort-minutes . org-duration-string-to-minutes))))
9734 ;;;; Link Stuff
9736 ;;; Link abbreviations
9738 (defun org-link-expand-abbrev (link)
9739 "Apply replacements as defined in `org-link-abbrev-alist'."
9740 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9741 (let* ((key (match-string 1 link))
9742 (as (or (assoc key org-link-abbrev-alist-local)
9743 (assoc key org-link-abbrev-alist)))
9744 (tag (and (match-end 2) (match-string 3 link)))
9745 rpl)
9746 (if (not as)
9747 link
9748 (setq rpl (cdr as))
9749 (cond
9750 ((symbolp rpl) (funcall rpl tag))
9751 ((string-match "%(\\([^)]+\\))" rpl)
9752 (replace-match
9753 (save-match-data
9754 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9755 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9756 ((string-match "%h" rpl)
9757 (replace-match (url-hexify-string (or tag "")) t t rpl))
9758 (t (concat rpl tag)))))
9759 link))
9761 ;;; Storing and inserting links
9763 (defvar org-insert-link-history nil
9764 "Minibuffer history for links inserted with `org-insert-link'.")
9766 (defvar org-stored-links nil
9767 "Contains the links stored with `org-store-link'.")
9769 (defvar org-store-link-plist nil
9770 "Plist with info about the most recently link created with `org-store-link'.")
9772 (defun org-store-link-functions ()
9773 "Return a list of functions that are called to create and store a link.
9774 The functions defined in the :store property of
9775 `org-link-parameters'.
9777 Each function will be called in turn until one returns a non-nil
9778 value. Each function should check if it is responsible for
9779 creating this link (for example by looking at the major mode).
9780 If not, it must exit and return nil. If yes, it should return
9781 a non-nil value after calling `org-store-link-props' with a list
9782 of properties and values. Special properties are:
9784 :type The link prefix, like \"http\". This must be given.
9785 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9786 This is obligatory as well.
9787 :description Optional default description for the second pair
9788 of brackets in an Org mode link. The user can still change
9789 this when inserting this link into an Org mode buffer.
9791 In addition to these, any additional properties can be specified
9792 and then used in capture templates."
9793 (cl-loop for link in org-link-parameters
9794 with store-func
9795 do (setq store-func (org-link-get-parameter (car link) :store))
9796 if store-func
9797 collect store-func))
9799 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9800 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9802 ;;;###autoload
9803 (defun org-store-link (arg)
9804 "Store an org-link to the current location.
9805 \\<org-mode-map>
9806 This link is added to `org-stored-links' and can later be inserted
9807 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9809 For some link types, a `\\[universal-argument]' prefix ARG is interpreted.
9810 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9811 For file links, ARG negates `org-context-in-file-links'.
9813 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9814 skipping storing functions that are not
9815 part of Org core.
9817 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9818 prefix ARG forces storing a link for each line in the
9819 active region."
9820 (interactive "P")
9821 (org-load-modules-maybe)
9822 (if (and (equal arg '(64)) (org-region-active-p))
9823 (save-excursion
9824 (let ((end (region-end)))
9825 (goto-char (region-beginning))
9826 (set-mark (point))
9827 (while (< (point-at-eol) end)
9828 (move-end-of-line 1) (activate-mark)
9829 (let (current-prefix-arg)
9830 (call-interactively 'org-store-link))
9831 (move-beginning-of-line 2)
9832 (set-mark (point)))))
9833 (setq org-store-link-plist nil)
9834 (let (link cpltxt desc description search
9835 txt custom-id agenda-link sfuns sfunsn)
9836 (cond
9838 ;; Store a link using an external link type
9839 ((and (not (equal arg '(16)))
9840 (setq sfuns
9841 (delq
9842 nil (mapcar (lambda (f)
9843 (let (fs) (if (funcall f) (push f fs))))
9844 (org-store-link-functions)))
9845 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9846 (or (and (cdr sfuns)
9847 (funcall (intern
9848 (completing-read
9849 "Which function for creating the link? "
9850 sfunsn nil t (car sfunsn)))))
9851 (funcall (caar sfuns)))
9852 (setq link (plist-get org-store-link-plist :link)
9853 desc (or (plist-get org-store-link-plist
9854 :description)
9855 link))))
9857 ;; Store a link from a source code buffer.
9858 ((org-src-edit-buffer-p)
9859 (let ((coderef-format (org-src-coderef-format)))
9860 (cond ((save-excursion
9861 (beginning-of-line)
9862 (looking-at (org-src-coderef-regexp coderef-format)))
9863 (setq link (format "(%s)" (match-string-no-properties 3))))
9864 ((called-interactively-p 'any)
9865 (let ((label (read-string "Code line label: ")))
9866 (end-of-line)
9867 (setq link (format coderef-format label))
9868 (let ((gc (- 79 (length link))))
9869 (if (< (current-column) gc)
9870 (org-move-to-column gc t)
9871 (insert " ")))
9872 (insert link)
9873 (setq link (concat "(" label ")"))
9874 (setq desc nil)))
9875 (t (setq link nil)))))
9877 ;; We are in the agenda, link to referenced location
9878 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9879 (let ((m (or (get-text-property (point) 'org-hd-marker)
9880 (get-text-property (point) 'org-marker))))
9881 (when m
9882 (org-with-point-at m
9883 (setq agenda-link
9884 (if (called-interactively-p 'any)
9885 (call-interactively 'org-store-link)
9886 (org-store-link nil)))))))
9888 ((eq major-mode 'calendar-mode)
9889 (let ((cd (calendar-cursor-to-date)))
9890 (setq link
9891 (format-time-string
9892 (car org-time-stamp-formats)
9893 (apply 'encode-time
9894 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9895 nil nil nil))))
9896 (org-store-link-props :type "calendar" :date cd)))
9898 ((eq major-mode 'help-mode)
9899 (setq link (concat "help:" (save-excursion
9900 (goto-char (point-min))
9901 (looking-at "^[^ ]+")
9902 (match-string 0))))
9903 (org-store-link-props :type "help"))
9905 ((eq major-mode 'w3-mode)
9906 (setq cpltxt (if (and (buffer-name)
9907 (not (string-match "Untitled" (buffer-name))))
9908 (buffer-name)
9909 (url-view-url t))
9910 link (url-view-url t))
9911 (org-store-link-props :type "w3" :url (url-view-url t)))
9913 ((eq major-mode 'image-mode)
9914 (setq cpltxt (concat "file:"
9915 (abbreviate-file-name buffer-file-name))
9916 link cpltxt)
9917 (org-store-link-props :type "image" :file buffer-file-name))
9919 ;; In dired, store a link to the file of the current line
9920 ((derived-mode-p 'dired-mode)
9921 (let ((file (dired-get-filename nil t)))
9922 (setq file (if file
9923 (abbreviate-file-name
9924 (expand-file-name (dired-get-filename nil t)))
9925 ;; otherwise, no file so use current directory.
9926 default-directory))
9927 (setq cpltxt (concat "file:" file)
9928 link cpltxt)))
9930 ((setq search (run-hook-with-args-until-success
9931 'org-create-file-search-functions))
9932 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9933 "::" search))
9934 (setq cpltxt (or description link)))
9936 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9937 (org-with-limited-levels
9938 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9939 (cond
9940 ;; Store a link using the target at point
9941 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9942 (setq cpltxt
9943 (concat "file:"
9944 (abbreviate-file-name
9945 (buffer-file-name (buffer-base-buffer)))
9946 "::" (match-string 1))
9947 link cpltxt))
9948 ((and (featurep 'org-id)
9949 (or (eq org-id-link-to-org-use-id t)
9950 (and (called-interactively-p 'any)
9951 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9952 (and (eq org-id-link-to-org-use-id
9953 'create-if-interactive-and-no-custom-id)
9954 (not custom-id))))
9955 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9956 ;; Store a link using the ID at point
9957 (setq link (condition-case nil
9958 (prog1 (org-id-store-link)
9959 (setq desc (or (plist-get org-store-link-plist
9960 :description)
9961 "")))
9962 (error
9963 ;; Probably before first headline, link only to file
9964 (concat "file:"
9965 (abbreviate-file-name
9966 (buffer-file-name (buffer-base-buffer))))))))
9968 ;; Just link to current headline
9969 (setq cpltxt (concat "file:"
9970 (abbreviate-file-name
9971 (buffer-file-name (buffer-base-buffer)))))
9972 ;; Add a context search string
9973 (when (org-xor org-context-in-file-links arg)
9974 (let* ((element (org-element-at-point))
9975 (name (org-element-property :name element)))
9976 (setq txt (cond
9977 ((org-at-heading-p) nil)
9978 (name)
9979 ((org-region-active-p)
9980 (buffer-substring (region-beginning) (region-end)))))
9981 (when (or (null txt) (string-match "\\S-" txt))
9982 (setq cpltxt
9983 (concat cpltxt "::"
9984 (condition-case nil
9985 (org-make-org-heading-search-string txt)
9986 (error "")))
9987 desc (or name
9988 (nth 4 (ignore-errors (org-heading-components)))
9989 "NONE")))))
9990 (when (string-match "::\\'" cpltxt)
9991 (setq cpltxt (substring cpltxt 0 -2)))
9992 (setq link cpltxt)))))
9994 ((buffer-file-name (buffer-base-buffer))
9995 ;; Just link to this file here.
9996 (setq cpltxt (concat "file:"
9997 (abbreviate-file-name
9998 (buffer-file-name (buffer-base-buffer)))))
9999 ;; Add a context string.
10000 (when (org-xor org-context-in-file-links arg)
10001 (setq txt (if (org-region-active-p)
10002 (buffer-substring (region-beginning) (region-end))
10003 (buffer-substring (point-at-bol) (point-at-eol))))
10004 ;; Only use search option if there is some text.
10005 (when (string-match "\\S-" txt)
10006 (setq cpltxt
10007 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10008 desc "NONE")))
10009 (setq link cpltxt))
10011 ((called-interactively-p 'interactive)
10012 (user-error "No method for storing a link from this buffer"))
10014 (t (setq link nil)))
10016 ;; We're done setting link and desc, clean up
10017 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10018 (setq link (or link cpltxt)
10019 desc (or desc cpltxt))
10020 (cond ((not desc))
10021 ((equal desc "NONE") (setq desc nil))
10022 (t (setq desc
10023 (replace-regexp-in-string
10024 org-bracket-link-analytic-regexp
10025 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10026 desc))))
10027 ;; Return the link
10028 (if (not (and (or (called-interactively-p 'any)
10029 executing-kbd-macro)
10030 link))
10031 (or agenda-link (and link (org-make-link-string link desc)))
10032 (push (list link desc) org-stored-links)
10033 (message "Stored: %s" (or desc link))
10034 (when custom-id
10035 (setq link (concat "file:" (abbreviate-file-name
10036 (buffer-file-name)) "::#" custom-id))
10037 (push (list link desc) org-stored-links))
10038 (car org-stored-links)))))
10040 (defun org-store-link-props (&rest plist)
10041 "Store link properties, extract names, addresses and dates."
10042 (let ((x (plist-get plist :from)))
10043 (when x
10044 (let ((adr (mail-extract-address-components x)))
10045 (setq plist (plist-put plist :fromname (car adr)))
10046 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10047 (let ((x (plist-get plist :to)))
10048 (when x
10049 (let ((adr (mail-extract-address-components x)))
10050 (setq plist (plist-put plist :toname (car adr)))
10051 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10052 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10053 (when x
10054 (setq plist (plist-put plist :date-timestamp
10055 (format-time-string
10056 (org-time-stamp-format t) x)))
10057 (setq plist (plist-put plist :date-timestamp-inactive
10058 (format-time-string
10059 (org-time-stamp-format t t) x)))))
10060 (let ((from (plist-get plist :from))
10061 (to (plist-get plist :to)))
10062 (when (and from to org-from-is-user-regexp)
10063 (setq plist
10064 (plist-put plist :fromto
10065 (if (string-match org-from-is-user-regexp from)
10066 (concat "to %t")
10067 (concat "from %f"))))))
10068 (setq org-store-link-plist plist))
10070 (defun org-add-link-props (&rest plist)
10071 "Add these properties to the link property list."
10072 (let (key value)
10073 (while plist
10074 (setq key (pop plist) value (pop plist))
10075 (setq org-store-link-plist
10076 (plist-put org-store-link-plist key value)))))
10078 (defun org-email-link-description (&optional fmt)
10079 "Return the description part of an email link.
10080 This takes information from `org-store-link-plist' and formats it
10081 according to FMT (default from `org-email-link-description-format')."
10082 (setq fmt (or fmt org-email-link-description-format))
10083 (let* ((p org-store-link-plist)
10084 (to (plist-get p :toaddress))
10085 (from (plist-get p :fromaddress))
10086 (table
10087 (list
10088 (cons "%c" (plist-get p :fromto))
10089 (cons "%F" (plist-get p :from))
10090 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10091 (cons "%T" (plist-get p :to))
10092 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10093 (cons "%s" (plist-get p :subject))
10094 (cons "%d" (plist-get p :date))
10095 (cons "%m" (plist-get p :message-id)))))
10096 (when (string-match "%c" fmt)
10097 ;; Check if the user wrote this message
10098 (if (and org-from-is-user-regexp from to
10099 (save-match-data (string-match org-from-is-user-regexp from)))
10100 (setq fmt (replace-match "to %t" t t fmt))
10101 (setq fmt (replace-match "from %f" t t fmt))))
10102 (org-replace-escapes fmt table)))
10104 (defun org-make-org-heading-search-string (&optional string)
10105 "Make search string for the current headline or STRING."
10106 (let ((s (or string
10107 (and (derived-mode-p 'org-mode)
10108 (save-excursion
10109 (org-back-to-heading t)
10110 (org-element-property :raw-value (org-element-at-point))))))
10111 (lines org-context-in-file-links))
10112 (or string (setq s (concat "*" s))) ; Add * for headlines
10113 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10114 (when (and string (integerp lines) (> lines 0))
10115 (let ((slines (org-split-string s "\n")))
10116 (when (< lines (length slines))
10117 (setq s (mapconcat
10118 'identity
10119 (reverse (nthcdr (- (length slines) lines)
10120 (reverse slines))) "\n")))))
10121 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10123 (defun org-make-link-string (link &optional description)
10124 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10125 (unless (org-string-nw-p link) (error "Empty link"))
10126 (let ((uri (cond ((string-match org-link-types-re link)
10127 (concat (match-string 1 link)
10128 (org-link-escape (substring link (match-end 1)))))
10129 ;; For readability, url-encode internal links only
10130 ;; when absolutely needed (i.e, when they contain
10131 ;; square brackets). File links however, are
10132 ;; encoded since, e.g., spaces are significant.
10133 ((or (file-name-absolute-p link)
10134 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10135 (org-link-escape link))
10136 (t link)))
10137 (description
10138 (and (org-string-nw-p description)
10139 ;; Remove brackets from description, as they are fatal.
10140 (replace-regexp-in-string
10141 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10142 (org-trim description)))))
10143 (format "[[%s]%s]"
10145 (if description (format "[%s]" description) ""))))
10147 (defconst org-link-escape-chars
10148 ;;%20 %5B %5D %25
10149 '(?\s ?\[ ?\] ?%)
10150 "List of characters that should be escaped in a link when stored to Org.
10151 This is the list that is used for internal purposes.")
10153 (defun org-link-escape (text &optional table merge)
10154 "Return percent escaped representation of TEXT.
10155 TEXT is a string with the text to escape.
10156 Optional argument TABLE is a list with characters that should be
10157 escaped. When nil, `org-link-escape-chars' is used.
10158 If optional argument MERGE is set, merge TABLE into
10159 `org-link-escape-chars'."
10160 (let ((characters-to-encode
10161 (cond ((null table) org-link-escape-chars)
10162 (merge (append org-link-escape-chars table))
10163 (t table))))
10164 (mapconcat
10165 (lambda (c)
10166 (if (or (memq c characters-to-encode)
10167 (and org-url-hexify-p (or (< c 32) (> c 126))))
10168 (mapconcat (lambda (e) (format "%%%.2X" e))
10169 (or (encode-coding-char c 'utf-8)
10170 (error "Unable to percent escape character: %c" c))
10172 (char-to-string c)))
10173 text "")))
10175 (defun org-link-unescape (str)
10176 "Unhex hexified Unicode parts in string STR.
10177 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10178 reciprocal of `org-link-escape', which see."
10179 (if (org-string-nw-p str)
10180 (replace-regexp-in-string
10181 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10182 str))
10184 (defun org-link-unescape-compound (hex)
10185 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10186 Note: this function also decodes single byte encodings like
10187 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10188 (save-match-data
10189 (let* ((bytes (cdr (split-string hex "%")))
10190 (ret "")
10191 (eat 0)
10192 (sum 0))
10193 (while bytes
10194 (let* ((val (string-to-number (pop bytes) 16))
10195 (shift-xor
10196 (if (= 0 eat)
10197 (cond
10198 ((>= val 252) (cons 6 252))
10199 ((>= val 248) (cons 5 248))
10200 ((>= val 240) (cons 4 240))
10201 ((>= val 224) (cons 3 224))
10202 ((>= val 192) (cons 2 192))
10203 (t (cons 0 0)))
10204 (cons 6 128))))
10205 (when (>= val 192) (setq eat (car shift-xor)))
10206 (setq val (logxor val (cdr shift-xor)))
10207 (setq sum (+ (lsh sum (car shift-xor)) val))
10208 (when (> eat 0) (setq eat (- eat 1)))
10209 (cond
10210 ((= 0 eat) ;multi byte
10211 (setq ret (concat ret (char-to-string sum)))
10212 (setq sum 0))
10213 ((not bytes) ; single byte(s)
10214 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10215 ret)))
10217 (defun org-link-unescape-single-byte-sequence (hex)
10218 "Unhexify hex-encoded single byte character sequences."
10219 (mapconcat (lambda (byte)
10220 (char-to-string (string-to-number byte 16)))
10221 (cdr (split-string hex "%")) ""))
10223 (defun org-xor (a b)
10224 "Exclusive or."
10225 (if a (not b) b))
10227 (defun org-fixup-message-id-for-http (s)
10228 "Replace special characters in a message id, so it can be used in an http query."
10229 (when (string-match "%" s)
10230 (setq s (mapconcat (lambda (c)
10231 (if (eq c ?%)
10232 "%25"
10233 (char-to-string c)))
10234 s "")))
10235 (while (string-match "<" s)
10236 (setq s (replace-match "%3C" t t s)))
10237 (while (string-match ">" s)
10238 (setq s (replace-match "%3E" t t s)))
10239 (while (string-match "@" s)
10240 (setq s (replace-match "%40" t t s)))
10243 (defun org-link-prettify (link)
10244 "Return a human-readable representation of LINK.
10245 The car of LINK must be a raw link.
10246 The cdr of LINK must be either a link description or nil."
10247 (let ((desc (or (cadr link) "<no description>")))
10248 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10249 "<" (car link) ">")))
10251 ;;;###autoload
10252 (defun org-insert-link-global ()
10253 "Insert a link like Org mode does.
10254 This command can be called in any mode to insert a link in Org syntax."
10255 (interactive)
10256 (org-load-modules-maybe)
10257 (org-run-like-in-org-mode 'org-insert-link))
10259 (defun org-insert-all-links (arg &optional pre post)
10260 "Insert all links in `org-stored-links'.
10261 When a universal prefix, do not delete the links from `org-stored-links'.
10262 When `ARG' is a number, insert the last N link(s).
10263 `PRE' and `POST' are optional arguments to define a string to
10264 prepend or to append."
10265 (interactive "P")
10266 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10267 (links (copy-sequence org-stored-links))
10268 (pr (or pre "- "))
10269 (po (or post "\n"))
10270 (cnt 1) l)
10271 (if (null org-stored-links)
10272 (message "No link to insert")
10273 (while (and (or (listp arg) (>= arg cnt))
10274 (setq l (if (listp arg)
10275 (pop links)
10276 (pop org-stored-links))))
10277 (setq cnt (1+ cnt))
10278 (insert pr)
10279 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10280 (insert po)))))
10282 (defun org-insert-last-stored-link (arg)
10283 "Insert the last link stored in `org-stored-links'."
10284 (interactive "p")
10285 (org-insert-all-links arg "" "\n"))
10287 (defun org-link-fontify-links-to-this-file ()
10288 "Fontify links to the current file in `org-stored-links'."
10289 (let ((f (buffer-file-name)) a b)
10290 (setq a (mapcar (lambda(l)
10291 (let ((ll (car l)))
10292 (when (and (string-match "^file:\\(.+\\)::" ll)
10293 (equal f (expand-file-name (match-string 1 ll))))
10294 ll)))
10295 org-stored-links))
10296 (when (featurep 'org-id)
10297 (setq b (mapcar (lambda(l)
10298 (let ((ll (car l)))
10299 (when (and (string-match "^id:\\(.+\\)$" ll)
10300 (equal f (expand-file-name
10301 (or (org-id-find-id-file
10302 (match-string 1 ll)) ""))))
10303 ll)))
10304 org-stored-links)))
10305 (mapcar (lambda(l)
10306 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10307 (delq nil (append a b)))))
10309 (defvar org--links-history nil)
10310 (defun org-insert-link (&optional complete-file link-location default-description)
10311 "Insert a link. At the prompt, enter the link.
10313 Completion can be used to insert any of the link protocol prefixes in use.
10315 The history can be used to select a link previously stored with
10316 `org-store-link'. When the empty string is entered (i.e. if you just
10317 press `RET' at the prompt), the link defaults to the most recently
10318 stored link. As `SPC' triggers completion in the minibuffer, you need to
10319 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10321 You will also be prompted for a description, and if one is given, it will
10322 be displayed in the buffer instead of the link.
10324 If there is already a link at point, this command will allow you to edit
10325 link and description parts.
10327 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10328 file name can be
10329 selected using completion. The path to the file will be relative to the
10330 current directory if the file is in the current directory or a subdirectory.
10331 Otherwise, the link will be the absolute path as completed in the minibuffer
10332 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10333 option `org-link-file-path-type'.
10335 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10336 absolute path even if the file is in
10337 the current directory or below.
10339 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10340 prefix negates `org-keep-stored-link-after-insertion'.
10342 If `org-make-link-description-function' is non-nil, this function will be
10343 called with the link target, and the result will be the default
10344 link description.
10346 If the LINK-LOCATION parameter is non-nil, this value will be used as
10347 the link location instead of reading one interactively.
10349 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10350 as the default description."
10351 (interactive "P")
10352 (let* ((wcf (current-window-configuration))
10353 (origbuf (current-buffer))
10354 (region (when (org-region-active-p)
10355 (buffer-substring (region-beginning) (region-end))))
10356 (remove (and region (list (region-beginning) (region-end))))
10357 (desc region)
10358 (link link-location)
10359 (abbrevs org-link-abbrev-alist-local)
10360 entry all-prefixes auto-desc)
10361 (cond
10362 (link-location) ; specified by arg, just use it.
10363 ((org-in-regexp org-bracket-link-regexp 1)
10364 ;; We do have a link at point, and we are going to edit it.
10365 (setq remove (list (match-beginning 0) (match-end 0)))
10366 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10367 (setq link (read-string "Link: "
10368 (org-link-unescape
10369 (match-string-no-properties 1)))))
10370 ((or (org-in-regexp org-angle-link-re)
10371 (org-in-regexp org-plain-link-re))
10372 ;; Convert to bracket link
10373 (setq remove (list (match-beginning 0) (match-end 0))
10374 link (read-string "Link: "
10375 (org-unbracket-string "<" ">" (match-string 0)))))
10376 ((member complete-file '((4) (16)))
10377 ;; Completing read for file names.
10378 (setq link (org-file-complete-link complete-file)))
10380 ;; Read link, with completion for stored links.
10381 (org-link-fontify-links-to-this-file)
10382 (org-switch-to-buffer-other-window "*Org Links*")
10383 (with-current-buffer "*Org Links*"
10384 (erase-buffer)
10385 (insert "Insert a link.
10386 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10387 (when org-stored-links
10388 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10389 (insert (mapconcat 'org-link-prettify
10390 (reverse org-stored-links) "\n")))
10391 (goto-char (point-min)))
10392 (let ((cw (selected-window)))
10393 (select-window (get-buffer-window "*Org Links*" 'visible))
10394 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10395 (unless (pos-visible-in-window-p (point-max))
10396 (org-fit-window-to-buffer))
10397 (and (window-live-p cw) (select-window cw)))
10398 (setq all-prefixes (append (mapcar 'car abbrevs)
10399 (mapcar 'car org-link-abbrev-alist)
10400 (org-link-types)))
10401 (unwind-protect
10402 ;; Fake a link history, containing the stored links.
10403 (let ((org--links-history
10404 (append (mapcar #'car org-stored-links)
10405 org-insert-link-history)))
10406 (setq link
10407 (org-completing-read
10408 "Link: "
10409 (append
10410 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10411 (mapcar #'car org-stored-links))
10412 nil nil nil
10413 'org--links-history
10414 (caar org-stored-links)))
10415 (unless (org-string-nw-p link) (user-error "No link selected"))
10416 (dolist (l org-stored-links)
10417 (when (equal link (cadr l))
10418 (setq link (car l))
10419 (setq auto-desc t)))
10420 (when (or (member link all-prefixes)
10421 (and (equal ":" (substring link -1))
10422 (member (substring link 0 -1) all-prefixes)
10423 (setq link (substring link 0 -1))))
10424 (setq link (with-current-buffer origbuf
10425 (org-link-try-special-completion link)))))
10426 (set-window-configuration wcf)
10427 (kill-buffer "*Org Links*"))
10428 (setq entry (assoc link org-stored-links))
10429 (or entry (push link org-insert-link-history))
10430 (setq desc (or desc (nth 1 entry)))))
10432 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10433 (not org-keep-stored-link-after-insertion))
10434 (setq org-stored-links (delq (assoc link org-stored-links)
10435 org-stored-links)))
10437 (when (and (string-match org-plain-link-re link)
10438 (not (string-match org-ts-regexp link)))
10439 ;; URL-like link, normalize the use of angular brackets.
10440 (setq link (org-unbracket-string "<" ">" link)))
10442 ;; Check if we are linking to the current file with a search
10443 ;; option If yes, simplify the link by using only the search
10444 ;; option.
10445 (when (and buffer-file-name
10446 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10447 (let* ((path (match-string 1 link))
10448 (case-fold-search nil)
10449 (search (match-string 2 link)))
10450 (save-match-data
10451 (when (equal (file-truename buffer-file-name) (file-truename path))
10452 ;; We are linking to this same file, with a search option
10453 (setq link search)))))
10455 ;; Check if we can/should use a relative path. If yes, simplify the link
10456 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10457 (let* ((type (match-string 1 link))
10458 (path (match-string 2 link))
10459 (origpath path)
10460 (case-fold-search nil))
10461 (cond
10462 ((or (eq org-link-file-path-type 'absolute)
10463 (equal complete-file '(16)))
10464 (setq path (abbreviate-file-name (expand-file-name path))))
10465 ((eq org-link-file-path-type 'noabbrev)
10466 (setq path (expand-file-name path)))
10467 ((eq org-link-file-path-type 'relative)
10468 (setq path (file-relative-name path)))
10470 (save-match-data
10471 (if (string-match (concat "^" (regexp-quote
10472 (expand-file-name
10473 (file-name-as-directory
10474 default-directory))))
10475 (expand-file-name path))
10476 ;; We are linking a file with relative path name.
10477 (setq path (substring (expand-file-name path)
10478 (match-end 0)))
10479 (setq path (abbreviate-file-name (expand-file-name path)))))))
10480 (setq link (concat type path))
10481 (when (equal desc origpath)
10482 (setq desc path))))
10484 (if org-make-link-description-function
10485 (setq desc
10486 (or (condition-case nil
10487 (funcall org-make-link-description-function link desc)
10488 (error (progn (message "Can't get link description from `%s'"
10489 (symbol-name org-make-link-description-function))
10490 (sit-for 2) nil)))
10491 (read-string "Description: " default-description)))
10492 (if default-description (setq desc default-description)
10493 (setq desc (or (and auto-desc desc)
10494 (read-string "Description: " desc)))))
10496 (unless (string-match "\\S-" desc) (setq desc nil))
10497 (when remove (apply 'delete-region remove))
10498 (insert (org-make-link-string link desc))
10499 ;; Redisplay so as the new link has proper invisible characters.
10500 (sit-for 0)))
10502 (defun org-link-try-special-completion (type)
10503 "If there is completion support for link type TYPE, offer it."
10504 (let ((fun (org-link-get-parameter type :complete)))
10505 (if (functionp fun)
10506 (funcall fun)
10507 (read-string "Link (no completion support): " (concat type ":")))))
10509 (defun org-file-complete-link (&optional arg)
10510 "Create a file link using completion."
10511 (let ((file (read-file-name "File: "))
10512 (pwd (file-name-as-directory (expand-file-name ".")))
10513 (pwd1 (file-name-as-directory (abbreviate-file-name
10514 (expand-file-name ".")))))
10515 (cond ((equal arg '(16))
10516 (concat "file:"
10517 (abbreviate-file-name (expand-file-name file))))
10518 ((string-match
10519 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10520 (concat "file:" (match-string 1 file)))
10521 ((string-match
10522 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10523 (expand-file-name file))
10524 (concat "file:"
10525 (match-string 1 (expand-file-name file))))
10526 (t (concat "file:" file)))))
10528 (defun org-completing-read (&rest args)
10529 "Completing-read with SPACE being a normal character."
10530 (let ((enable-recursive-minibuffers t)
10531 (minibuffer-local-completion-map
10532 (copy-keymap minibuffer-local-completion-map)))
10533 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10534 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10535 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10536 'org-time-stamp-inactive)
10537 (apply #'completing-read args)))
10539 ;;; Opening/following a link
10541 (defvar org-link-search-failed nil)
10543 (defvar org-open-link-functions nil
10544 "Hook for functions finding a plain text link.
10545 These functions must take a single argument, the link content.
10546 They will be called for links that look like [[link text][description]]
10547 when LINK TEXT does not have a protocol like \"http:\" and does not look
10548 like a filename (e.g. \"./blue.png\").
10550 These functions will be called *before* Org attempts to resolve the
10551 link by doing text searches in the current buffer - so if you want a
10552 link \"[[target]]\" to still find \"<<target>>\", your function should
10553 handle this as a special case.
10555 When the function does handle the link, it must return a non-nil value.
10556 If it decides that it is not responsible for this link, it must return
10557 nil to indicate that that Org can continue with other options like
10558 exact and fuzzy text search.")
10560 (defun org-next-link (&optional search-backward)
10561 "Move forward to the next link.
10562 If the link is in hidden text, expose it."
10563 (interactive "P")
10564 (when (and org-link-search-failed (eq this-command last-command))
10565 (goto-char (point-min))
10566 (message "Link search wrapped back to beginning of buffer"))
10567 (setq org-link-search-failed nil)
10568 (let* ((pos (point))
10569 (ct (org-context))
10570 (a (assq :link ct))
10571 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10572 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10573 ((looking-at org-any-link-re)
10574 ;; Don't stay stuck at link without an org-link face
10575 (forward-char (if search-backward -1 1))))
10576 (if (funcall srch-fun org-any-link-re nil t)
10577 (progn
10578 (goto-char (match-beginning 0))
10579 (when (outline-invisible-p) (org-show-context)))
10580 (goto-char pos)
10581 (setq org-link-search-failed t)
10582 (message "No further link found"))))
10584 (defun org-previous-link ()
10585 "Move backward to the previous link.
10586 If the link is in hidden text, expose it."
10587 (interactive)
10588 (funcall 'org-next-link t))
10590 (defun org-translate-link (s)
10591 "Translate a link string if a translation function has been defined."
10592 (with-temp-buffer
10593 (insert (org-trim s))
10594 (org-trim (org-element-interpret-data (org-element-context)))))
10596 (defun org-translate-link-from-planner (type path)
10597 "Translate a link from Emacs Planner syntax so that Org can follow it.
10598 This is still an experimental function, your mileage may vary."
10599 (cond
10600 ((member type '("http" "https" "news" "ftp"))
10601 ;; standard Internet links are the same.
10602 nil)
10603 ((and (equal type "irc") (string-match "^//" path))
10604 ;; Planner has two / at the beginning of an irc link, we have 1.
10605 ;; We should have zero, actually....
10606 (setq path (substring path 1)))
10607 ((and (equal type "lisp") (string-match "^/" path))
10608 ;; Planner has a slash, we do not.
10609 (setq type "elisp" path (substring path 1)))
10610 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10611 ;; A typical message link. Planner has the id after the final slash,
10612 ;; we separate it with a hash mark
10613 (setq path (concat (match-string 1 path) "#"
10614 (org-unbracket-string "<" ">" (match-string 2 path))))))
10615 (cons type path))
10617 (defun org-find-file-at-mouse (ev)
10618 "Open file link or URL at mouse."
10619 (interactive "e")
10620 (mouse-set-point ev)
10621 (org-open-at-point 'in-emacs))
10623 (defun org-open-at-mouse (ev)
10624 "Open file link or URL at mouse.
10625 See the docstring of `org-open-file' for details."
10626 (interactive "e")
10627 (mouse-set-point ev)
10628 (when (eq major-mode 'org-agenda-mode)
10629 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10630 (org-open-at-point))
10632 (defvar org-window-config-before-follow-link nil
10633 "The window configuration before following a link.
10634 This is saved in case the need arises to restore it.")
10636 ;;;###autoload
10637 (defun org-open-at-point-global ()
10638 "Follow a link or time-stamp like Org mode does.
10639 This command can be called in any mode to follow an external link
10640 or a time-stamp that has Org mode syntax. Its behavior is
10641 undefined when called on internal links (e.g., fuzzy links).
10642 Raise an error when there is nothing to follow. "
10643 (interactive)
10644 (cond ((org-in-regexp org-any-link-re)
10645 (org-open-link-from-string (match-string-no-properties 0)))
10646 ((or (org-in-regexp org-ts-regexp-both nil t)
10647 (org-in-regexp org-tsr-regexp-both nil t))
10648 (org-follow-timestamp-link))
10649 (t (user-error "No link found"))))
10651 ;;;###autoload
10652 (defun org-open-link-from-string (s &optional arg reference-buffer)
10653 "Open a link in the string S, as if it was in Org mode."
10654 (interactive "sLink: \nP")
10655 (let ((reference-buffer (or reference-buffer (current-buffer))))
10656 (with-temp-buffer
10657 (let ((org-inhibit-startup (not reference-buffer)))
10658 (org-mode)
10659 (insert s)
10660 (goto-char (point-min))
10661 (when reference-buffer
10662 (setq org-link-abbrev-alist-local
10663 (with-current-buffer reference-buffer
10664 org-link-abbrev-alist-local)))
10665 (org-open-at-point arg reference-buffer)))))
10667 (defvar org-open-at-point-functions nil
10668 "Hook that is run when following a link at point.
10670 Functions in this hook must return t if they identify and follow
10671 a link at point. If they don't find anything interesting at point,
10672 they must return nil.")
10674 (defvar org-link-search-inhibit-query nil)
10675 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10676 (defun org--open-doi-link (path)
10677 "Open a \"doi\" type link.
10678 PATH is a the path to search for, as a string."
10679 (browse-url (url-encode-url (concat org-doi-server-url path))))
10681 (defun org--open-elisp-link (path)
10682 "Open a \"elisp\" type link.
10683 PATH is the sexp to evaluate, as a string."
10684 (let ((cmd path))
10685 (if (or (and (org-string-nw-p
10686 org-confirm-elisp-link-not-regexp)
10687 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10688 (not org-confirm-elisp-link-function)
10689 (funcall org-confirm-elisp-link-function
10690 (format "Execute \"%s\" as elisp? "
10691 (org-add-props cmd nil 'face 'org-warning))))
10692 (message "%s => %s" cmd
10693 (if (eq (string-to-char cmd) ?\()
10694 (eval (read cmd))
10695 (call-interactively (read cmd))))
10696 (user-error "Abort"))))
10698 (defun org--open-help-link (path)
10699 "Open a \"help\" type link.
10700 PATH is a symbol name, as a string."
10701 (pcase (intern path)
10702 ((and (pred fboundp) variable) (describe-function variable))
10703 ((and (pred boundp) function) (describe-variable function))
10704 (name (user-error "Unknown function or variable: %s" name))))
10706 (defun org--open-shell-link (path)
10707 "Open a \"shell\" type link.
10708 PATH is the command to execute, as a string."
10709 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10710 (cmd path))
10711 (if (or (and (org-string-nw-p
10712 org-confirm-shell-link-not-regexp)
10713 (string-match
10714 org-confirm-shell-link-not-regexp cmd))
10715 (not org-confirm-shell-link-function)
10716 (funcall org-confirm-shell-link-function
10717 (format "Execute \"%s\" in shell? "
10718 (org-add-props cmd nil
10719 'face 'org-warning))))
10720 (progn
10721 (message "Executing %s" cmd)
10722 (shell-command cmd buf)
10723 (when (featurep 'midnight)
10724 (setq clean-buffer-list-kill-buffer-names
10725 (cons (buffer-name buf)
10726 clean-buffer-list-kill-buffer-names))))
10727 (user-error "Abort"))))
10729 (defun org-open-at-point (&optional arg reference-buffer)
10730 "Open link, timestamp, footnote or tags at point.
10732 When point is on a link, follow it. Normally, files will be
10733 opened by an appropriate application. If the optional prefix
10734 argument ARG is non-nil, Emacs will visit the file. With
10735 a double prefix argument, try to open outside of Emacs, in the
10736 application the system uses for this file type.
10738 When point is on a timestamp, open the agenda at the day
10739 specified.
10741 When point is a footnote definition, move to the first reference
10742 found. If it is on a reference, move to the associated
10743 definition.
10745 When point is on a headline, display a list of every link in the
10746 entry, so it is possible to pick one, or all, of them. If point
10747 is on a tag, call `org-tags-view' instead.
10749 When optional argument REFERENCE-BUFFER is non-nil, it should
10750 specify a buffer from where the link search should happen. This
10751 is used internally by `org-open-link-from-string'.
10753 On top of syntactically correct links, this function will open
10754 the link at point in comments or comment blocks and the first
10755 link in a property drawer line."
10756 (interactive "P")
10757 ;; On a code block, open block's results.
10758 (unless (call-interactively 'org-babel-open-src-block-result)
10759 (org-load-modules-maybe)
10760 (setq org-window-config-before-follow-link (current-window-configuration))
10761 (org-remove-occur-highlights nil nil t)
10762 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10763 (let* ((context
10764 ;; Only consider supported types, even if they are not
10765 ;; the closest one.
10766 (org-element-lineage
10767 (org-element-context)
10768 '(clock comment comment-block footnote-definition
10769 footnote-reference headline inlinetask keyword link
10770 node-property timestamp)
10772 (type (org-element-type context))
10773 (value (org-element-property :value context)))
10774 (cond
10775 ((not context) (user-error "No link found"))
10776 ;; Exception: open timestamps and links in properties
10777 ;; drawers, keywords and comments.
10778 ((memq type '(comment comment-block keyword node-property))
10779 (call-interactively #'org-open-at-point-global))
10780 ;; On a headline or an inlinetask, but not on a timestamp,
10781 ;; a link, a footnote reference or on tags.
10782 ((and (memq type '(headline inlinetask))
10783 ;; Not on tags.
10784 (let ((case-fold-search nil))
10785 (save-excursion
10786 (beginning-of-line)
10787 (looking-at org-complex-heading-regexp))
10788 (or (not (match-beginning 5))
10789 (< (point) (match-beginning 5)))))
10790 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10791 (links (car data))
10792 (links-end (cdr data)))
10793 (if links
10794 (dolist (link (if (stringp links) (list links) links))
10795 (search-forward link nil links-end)
10796 (goto-char (match-beginning 0))
10797 (org-open-at-point))
10798 (require 'org-attach)
10799 (org-attach-reveal 'if-exists))))
10800 ;; On a clock line, make sure point is on the timestamp
10801 ;; before opening it.
10802 ((and (eq type 'clock)
10803 value
10804 (>= (point) (org-element-property :begin value))
10805 (<= (point) (org-element-property :end value)))
10806 (org-follow-timestamp-link))
10807 ;; Do nothing on white spaces after an object.
10808 ((>= (point)
10809 (save-excursion
10810 (goto-char (org-element-property :end context))
10811 (skip-chars-backward " \t")
10812 (point)))
10813 (user-error "No link found"))
10814 ((eq type 'timestamp) (org-follow-timestamp-link))
10815 ;; On tags within a headline or an inlinetask.
10816 ((and (memq type '(headline inlinetask))
10817 (let ((case-fold-search nil))
10818 (save-excursion (beginning-of-line)
10819 (looking-at org-complex-heading-regexp))
10820 (and (match-beginning 5)
10821 (>= (point) (match-beginning 5)))))
10822 (org-tags-view arg (substring (match-string 5) 0 -1)))
10823 ((eq type 'link)
10824 (let ((type (org-element-property :type context))
10825 (path (org-link-unescape (org-element-property :path context))))
10826 ;; Switch back to REFERENCE-BUFFER needed when called in
10827 ;; a temporary buffer through `org-open-link-from-string'.
10828 (with-current-buffer (or reference-buffer (current-buffer))
10829 (cond
10830 ((equal type "file")
10831 (if (string-match "[*?{]" (file-name-nondirectory path))
10832 (dired path)
10833 ;; Look into `org-link-parameters' in order to find
10834 ;; a DEDICATED-FUNCTION to open file. The function
10835 ;; will be applied on raw link instead of parsed
10836 ;; link due to the limitation in `org-add-link-type'
10837 ;; ("open" function called with a single argument).
10838 ;; If no such function is found, fallback to
10839 ;; `org-open-file'.
10840 (let* ((option (org-element-property :search-option context))
10841 (app (org-element-property :application context))
10842 (dedicated-function
10843 (org-link-get-parameter
10844 (if app (concat type "+" app) type)
10845 :follow)))
10846 (if dedicated-function
10847 (funcall dedicated-function
10848 (concat path
10849 (and option (concat "::" option))))
10850 (apply #'org-open-file
10851 path
10852 (cond (arg)
10853 ((equal app "emacs") 'emacs)
10854 ((equal app "sys") 'system))
10855 (cond ((not option) nil)
10856 ((string-match-p "\\`[0-9]+\\'" option)
10857 (list (string-to-number option)))
10858 (t (list nil
10859 (org-link-unescape option)))))))))
10860 ((functionp (org-link-get-parameter type :follow))
10861 (funcall (org-link-get-parameter type :follow) path))
10862 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10863 (unless (run-hook-with-args-until-success
10864 'org-open-link-functions path)
10865 (if (not arg) (org-mark-ring-push)
10866 (switch-to-buffer-other-window
10867 (org-get-buffer-for-internal-link (current-buffer))))
10868 (let ((destination
10869 (org-with-wide-buffer
10870 (if (equal type "radio")
10871 (org-search-radio-target
10872 (org-element-property :path context))
10873 (org-link-search
10874 (if (member type '("custom-id" "coderef"))
10875 (org-element-property :raw-link context)
10876 path)
10877 ;; Prevent fuzzy links from matching
10878 ;; themselves.
10879 (and (equal type "fuzzy")
10880 (+ 2 (org-element-property :begin context)))))
10881 (point))))
10882 (unless (and (<= (point-min) destination)
10883 (>= (point-max) destination))
10884 (widen))
10885 (goto-char destination))))
10886 (t (browse-url-at-point))))))
10887 ;; On a footnote reference or at a footnote definition's label.
10888 ((or (eq type 'footnote-reference)
10889 (and (eq type 'footnote-definition)
10890 (save-excursion
10891 ;; Do not validate action when point is on the
10892 ;; spaces right after the footnote label, in
10893 ;; order to be on par with behaviour on links.
10894 (skip-chars-forward " \t")
10895 (let ((begin
10896 (org-element-property :contents-begin context)))
10897 (if begin (< (point) begin)
10898 (= (org-element-property :post-affiliated context)
10899 (line-beginning-position)))))))
10900 (org-footnote-action))
10901 (t (user-error "No link found")))))
10902 (run-hook-with-args 'org-follow-link-hook)))
10904 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10905 "Offer links in the current entry and return the selected link.
10906 If there is only one link, return it.
10907 If NTH is an integer, return the NTH link found.
10908 If ZERO is a string, check also this string for a link, and if
10909 there is one, return it."
10910 (with-current-buffer buffer
10911 (org-with-wide-buffer
10912 (goto-char marker)
10913 (let ((cnt ?0)
10914 have-zero end links link c)
10915 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10916 (push (match-string 0 zero) links)
10917 (setq cnt (1- cnt) have-zero t))
10918 (save-excursion
10919 (org-back-to-heading t)
10920 (setq end (save-excursion (outline-next-heading) (point)))
10921 (while (re-search-forward org-any-link-re end t)
10922 (push (match-string 0) links))
10923 (setq links (org-uniquify (reverse links))))
10924 (cond
10925 ((null links)
10926 (message "No links"))
10927 ((equal (length links) 1)
10928 (setq link (car links)))
10929 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10930 (setq link (nth (if have-zero nth (1- nth)) links)))
10931 (t ; we have to select a link
10932 (save-excursion
10933 (save-window-excursion
10934 (delete-other-windows)
10935 (with-output-to-temp-buffer "*Select Link*"
10936 (dolist (l links)
10937 (cond
10938 ((not (string-match org-bracket-link-regexp l))
10939 (princ (format "[%c] %s\n" (cl-incf cnt)
10940 (org-unbracket-string "<" ">" l))))
10941 ((match-end 3)
10942 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10943 (match-string 3 l) (match-string 1 l))))
10944 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10945 (match-string 1 l)))))))
10946 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10947 (message "Select link to open, RET to open all:")
10948 (setq c (read-char-exclusive))
10949 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10950 (when (equal c ?q) (user-error "Abort"))
10951 (if (equal c ?\C-m)
10952 (setq link links)
10953 (setq nth (- c ?0))
10954 (when have-zero (setq nth (1+ nth)))
10955 (unless (and (integerp nth) (>= (length links) nth))
10956 (user-error "Invalid link selection"))
10957 (setq link (nth (1- nth) links)))))
10958 (cons link end)))))
10960 ;; TODO: These functions are deprecated since `org-open-at-point'
10961 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10962 (defun org-open-file-with-system (path)
10963 "Open file at PATH using the system way of opening it."
10964 (org-open-file path 'system))
10965 (defun org-open-file-with-emacs (path)
10966 "Open file at PATH in Emacs."
10967 (org-open-file path 'emacs))
10970 ;;; File search
10972 (defvar org-create-file-search-functions nil
10973 "List of functions to construct the right search string for a file link.
10974 These functions are called in turn with point at the location to
10975 which the link should point.
10977 A function in the hook should first test if it would like to
10978 handle this file type, for example by checking the `major-mode'
10979 or the file extension. If it decides not to handle this file, it
10980 should just return nil to give other functions a chance. If it
10981 does handle the file, it must return the search string to be used
10982 when following the link. The search string will be part of the
10983 file link, given after a double colon, and `org-open-at-point'
10984 will automatically search for it. If special measures must be
10985 taken to make the search successful, another function should be
10986 added to the companion hook `org-execute-file-search-functions',
10987 which see.
10989 A function in this hook may also use `setq' to set the variable
10990 `description' to provide a suggestion for the descriptive text to
10991 be used for this link when it gets inserted into an Org buffer
10992 with \\[org-insert-link].")
10994 (defvar org-execute-file-search-functions nil
10995 "List of functions to execute a file search triggered by a link.
10997 Functions added to this hook must accept a single argument, the
10998 search string that was part of the file link, the part after the
10999 double colon. The function must first check if it would like to
11000 handle this search, for example by checking the `major-mode' or
11001 the file extension. If it decides not to handle this search, it
11002 should just return nil to give other functions a chance. If it
11003 does handle the search, it must return a non-nil value to keep
11004 other functions from trying.
11006 Each function can access the current prefix argument through the
11007 variable `current-prefix-arg'. Note that a single prefix is used
11008 to force opening a link in Emacs, so it may be good to only use a
11009 numeric or double prefix to guide the search function.
11011 In case this is needed, a function in this hook can also restore
11012 the window configuration before `org-open-at-point' was called using:
11014 (set-window-configuration org-window-config-before-follow-link)")
11016 (defun org-search-radio-target (target)
11017 "Search a radio target matching TARGET in current buffer.
11018 White spaces are not significant."
11019 (let ((re (format "<<<%s>>>"
11020 (mapconcat #'regexp-quote
11021 (org-split-string target "[ \t\n]+")
11022 "[ \t]+\\(?:\n[ \t]*\\)?")))
11023 (origin (point)))
11024 (goto-char (point-min))
11025 (catch :radio-match
11026 (while (re-search-forward re nil t)
11027 (backward-char)
11028 (let ((object (org-element-context)))
11029 (when (eq (org-element-type object) 'radio-target)
11030 (goto-char (org-element-property :begin object))
11031 (org-show-context 'link-search)
11032 (throw :radio-match nil))))
11033 (goto-char origin)
11034 (user-error "No match for radio target: %s" target))))
11036 (defun org-link-search (s &optional avoid-pos stealth)
11037 "Search for a search string S.
11039 If S starts with \"#\", it triggers a custom ID search.
11041 If S is enclosed within parenthesis, it initiates a coderef
11042 search.
11044 If S is surrounded by forward slashes, it is interpreted as
11045 a regular expression. In Org mode files, this will create an
11046 `org-occur' sparse tree. In ordinary files, `occur' will be used
11047 to list matches. If the current buffer is in `dired-mode', grep
11048 will be used to search in all files.
11050 When AVOID-POS is given, ignore matches near that position.
11052 When optional argument STEALTH is non-nil, do not modify
11053 visibility around point, thus ignoring `org-show-context-detail'
11054 variable.
11056 Search is case-insensitive and ignores white spaces. Return type
11057 of matched result, which is either `dedicated' or `fuzzy'."
11058 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11059 (let* ((case-fold-search t)
11060 (origin (point))
11061 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11062 (starred (eq (string-to-char normalized) ?*))
11063 (words (split-string (if starred (substring s 1) s)))
11064 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11065 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11066 type)
11067 (cond
11068 ;; Check if there are any special search functions.
11069 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11070 ((eq (string-to-char s) ?#)
11071 ;; Look for a custom ID S if S starts with "#".
11072 (let* ((id (substring normalized 1))
11073 (match (org-find-property "CUSTOM_ID" id)))
11074 (if match (progn (goto-char match) (setf type 'dedicated))
11075 (error "No match for custom ID: %s" id))))
11076 ((string-match "\\`(\\(.*\\))\\'" normalized)
11077 ;; Look for coderef targets if S is enclosed within parenthesis.
11078 (let ((coderef (match-string-no-properties 1 normalized))
11079 (re (substring s-single-re 1 -1)))
11080 (goto-char (point-min))
11081 (catch :coderef-match
11082 (while (re-search-forward re nil t)
11083 (let ((element (org-element-at-point)))
11084 (when (and (memq (org-element-type element)
11085 '(example-block src-block))
11086 ;; Build proper regexp according to current
11087 ;; block's label format.
11088 (let ((label-fmt
11089 (regexp-quote
11090 (or (org-element-property :label-fmt element)
11091 org-coderef-label-format))))
11092 (save-excursion
11093 (beginning-of-line)
11094 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11095 (format label-fmt coderef))))))
11096 (setq type 'dedicated)
11097 (goto-char (match-beginning 1))
11098 (throw :coderef-match nil))))
11099 (goto-char origin)
11100 (error "No match for coderef: %s" coderef))))
11101 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11102 ;; Look for a regular expression.
11103 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11104 (match-string 1 s)))
11105 ;; From here, we handle fuzzy links.
11107 ;; Look for targets, only if not in a headline search.
11108 ((and (not starred)
11109 (let ((target (format "<<%s>>" s-multi-re)))
11110 (catch :target-match
11111 (goto-char (point-min))
11112 (while (re-search-forward target nil t)
11113 (backward-char)
11114 (let ((context (org-element-context)))
11115 (when (eq (org-element-type context) 'target)
11116 (setq type 'dedicated)
11117 (goto-char (org-element-property :begin context))
11118 (throw :target-match t))))
11119 nil))))
11120 ;; Look for elements named after S, only if not in a headline
11121 ;; search.
11122 ((and (not starred)
11123 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11124 (catch :name-match
11125 (goto-char (point-min))
11126 (while (re-search-forward name nil t)
11127 (let ((element (org-element-at-point)))
11128 (when (equal words
11129 (split-string
11130 (org-element-property :name element)))
11131 (setq type 'dedicated)
11132 (beginning-of-line)
11133 (throw :name-match t))))
11134 nil))))
11135 ;; Regular text search. Prefer headlines in Org mode buffers.
11136 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11137 ;; statistics cookies and tags.
11138 ((and (derived-mode-p 'org-mode)
11139 (let ((title-re
11140 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11141 org-outline-regexp-bol
11142 org-comment-string
11143 (mapconcat #'regexp-quote words ".+")))
11144 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11145 (comment-re (format "\\`%s[ \t]+" org-comment-string)))
11146 (goto-char (point-min))
11147 (catch :found
11148 (while (re-search-forward title-re nil t)
11149 (when (equal words
11150 (split-string
11151 (replace-regexp-in-string
11152 cookie-re ""
11153 (replace-regexp-in-string
11154 comment-re "" (org-get-heading t t)))))
11155 (throw :found t)))
11156 nil)))
11157 (beginning-of-line)
11158 (setq type 'dedicated))
11159 ;; Offer to create non-existent headline depending on
11160 ;; `org-link-search-must-match-exact-headline'.
11161 ((and (derived-mode-p 'org-mode)
11162 (not org-link-search-inhibit-query)
11163 (eq org-link-search-must-match-exact-headline 'query-to-create)
11164 (yes-or-no-p "No match - create this as a new heading? "))
11165 (goto-char (point-max))
11166 (unless (bolp) (newline))
11167 (org-insert-heading nil t t)
11168 (insert s "\n")
11169 (beginning-of-line 0))
11170 ;; Only headlines are looked after. No need to process
11171 ;; further: throw an error.
11172 ((and (derived-mode-p 'org-mode)
11173 (or starred org-link-search-must-match-exact-headline))
11174 (goto-char origin)
11175 (error "No match for fuzzy expression: %s" normalized))
11176 ;; Regular text search.
11177 ((catch :fuzzy-match
11178 (goto-char (point-min))
11179 (while (re-search-forward s-multi-re nil t)
11180 ;; Skip match if it contains AVOID-POS or it is included in
11181 ;; a link with a description but outside the description.
11182 (unless (or (and avoid-pos
11183 (<= (match-beginning 0) avoid-pos)
11184 (> (match-end 0) avoid-pos))
11185 (and (save-match-data
11186 (org-in-regexp org-bracket-link-regexp))
11187 (match-beginning 3)
11188 (or (> (match-beginning 3) (point))
11189 (<= (match-end 3) (point)))
11190 (org-element-lineage
11191 (save-match-data (org-element-context))
11192 '(link) t)))
11193 (goto-char (match-beginning 0))
11194 (setq type 'fuzzy)
11195 (throw :fuzzy-match t)))
11196 nil))
11197 ;; All failed. Throw an error.
11198 (t (goto-char origin)
11199 (error "No match for fuzzy expression: %s" normalized)))
11200 ;; Disclose surroundings of match, if appropriate.
11201 (when (and (derived-mode-p 'org-mode) (not stealth))
11202 (org-show-context 'link-search))
11203 type))
11205 (defun org-get-buffer-for-internal-link (buffer)
11206 "Return a buffer to be used for displaying the link target of internal links."
11207 (cond
11208 ((not org-display-internal-link-with-indirect-buffer)
11209 buffer)
11210 ((string-suffix-p "(Clone)" (buffer-name buffer))
11211 (message "Buffer is already a clone, not making another one")
11212 ;; we also do not modify visibility in this case
11213 buffer)
11214 (t ; make a new indirect buffer for displaying the link
11215 (let* ((bn (buffer-name buffer))
11216 (ibn (concat bn "(Clone)"))
11217 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11218 (with-current-buffer ib (org-overview))
11219 ib))))
11221 (defun org-do-occur (regexp &optional cleanup)
11222 "Call the Emacs command `occur'.
11223 If CLEANUP is non-nil, remove the printout of the regular expression
11224 in the *Occur* buffer. This is useful if the regex is long and not useful
11225 to read."
11226 (occur regexp)
11227 (when cleanup
11228 (let ((cwin (selected-window)) win beg end)
11229 (when (setq win (get-buffer-window "*Occur*"))
11230 (select-window win))
11231 (goto-char (point-min))
11232 (when (re-search-forward "match[a-z]+" nil t)
11233 (setq beg (match-end 0))
11234 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11235 (setq end (1- (match-beginning 0)))))
11236 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11237 (goto-char (point-min))
11238 (select-window cwin))))
11240 ;;; The mark ring for links jumps
11242 (defvar org-mark-ring nil
11243 "Mark ring for positions before jumps in Org mode.")
11244 (defvar org-mark-ring-last-goto nil
11245 "Last position in the mark ring used to go back.")
11246 ;; Fill and close the ring
11247 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11248 (dotimes (_ org-mark-ring-length)
11249 (push (make-marker) org-mark-ring))
11250 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11251 org-mark-ring)
11253 (defun org-mark-ring-push (&optional pos buffer)
11254 "Put the current position or POS into the mark ring and rotate it."
11255 (interactive)
11256 (setq pos (or pos (point)))
11257 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11258 (move-marker (car org-mark-ring)
11259 (or pos (point))
11260 (or buffer (current-buffer)))
11261 (message "%s"
11262 (substitute-command-keys
11263 "Position saved to mark ring, go back with \
11264 `\\[org-mark-ring-goto]'.")))
11266 (defun org-mark-ring-goto (&optional n)
11267 "Jump to the previous position in the mark ring.
11268 With prefix arg N, jump back that many stored positions. When
11269 called several times in succession, walk through the entire ring.
11270 Org mode commands jumping to a different position in the current file,
11271 or to another Org file, automatically push the old position onto the ring."
11272 (interactive "p")
11273 (let (p m)
11274 (if (eq last-command this-command)
11275 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11276 (setq p org-mark-ring))
11277 (setq org-mark-ring-last-goto p)
11278 (setq m (car p))
11279 (pop-to-buffer-same-window (marker-buffer m))
11280 (goto-char m)
11281 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11283 (defun org-add-angle-brackets (s)
11284 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11285 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11288 ;;; Following specific links
11290 (defvar org-agenda-buffer-tmp-name)
11291 (defvar org-agenda-start-on-weekday)
11292 (defun org-follow-timestamp-link ()
11293 "Open an agenda view for the time-stamp date/range at point."
11294 (cond
11295 ((org-at-date-range-p t)
11296 (let ((org-agenda-start-on-weekday)
11297 (t1 (match-string 1))
11298 (t2 (match-string 2)) tt1 tt2)
11299 (setq tt1 (time-to-days (org-time-string-to-time t1))
11300 tt2 (time-to-days (org-time-string-to-time t2)))
11301 (let ((org-agenda-buffer-tmp-name
11302 (format "*Org Agenda(a:%s)"
11303 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11304 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11305 ((org-at-timestamp-p t)
11306 (let ((org-agenda-buffer-tmp-name
11307 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11308 (org-agenda-list nil (time-to-days (org-time-string-to-time
11309 (substring (match-string 1) 0 10)))
11310 1)))
11311 (t (error "This should not happen"))))
11314 ;;; Following file links
11315 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11316 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11317 (declare-function mailcap-mime-info
11318 "mailcap" (string &optional request no-decode))
11319 (defvar org-wait nil)
11320 (defun org-open-file (path &optional in-emacs line search)
11321 "Open the file at PATH.
11322 First, this expands any special file name abbreviations. Then the
11323 configuration variable `org-file-apps' is checked if it contains an
11324 entry for this file type, and if yes, the corresponding command is launched.
11326 If no application is found, Emacs simply visits the file.
11328 With optional prefix argument IN-EMACS, Emacs will visit the file.
11329 With a double \\[universal-argument] \\[universal-argument] \
11330 prefix arg, Org tries to avoid opening in Emacs
11331 and to use an external application to visit the file.
11333 Optional LINE specifies a line to go to, optional SEARCH a string
11334 to search for. If LINE or SEARCH is given, the file will be
11335 opened in Emacs, unless an entry from org-file-apps that makes
11336 use of groups in a regexp matches.
11338 If you want to change the way frames are used when following a
11339 link, please customize `org-link-frame-setup'.
11341 If the file does not exist, an error is thrown."
11342 (let* ((file (if (equal path "")
11343 buffer-file-name
11344 (substitute-in-file-name (expand-file-name path))))
11345 (file-apps (append org-file-apps (org-default-apps)))
11346 (apps (cl-remove-if
11347 'org-file-apps-entry-match-against-dlink-p file-apps))
11348 (apps-dlink (cl-remove-if-not
11349 'org-file-apps-entry-match-against-dlink-p file-apps))
11350 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11351 (dirp (unless remp (file-directory-p file)))
11352 (file (if (and dirp org-open-directory-means-index-dot-org)
11353 (concat (file-name-as-directory file) "index.org")
11354 file))
11355 (a-m-a-p (assq 'auto-mode apps))
11356 (dfile (downcase file))
11357 ;; Reconstruct the original link from the PATH, LINE and
11358 ;; SEARCH args.
11359 (link (cond (line (concat file "::" (number-to-string line)))
11360 (search (concat file "::" search))
11361 (t file)))
11362 (dlink (downcase link))
11363 (old-buffer (current-buffer))
11364 (old-pos (point))
11365 (old-mode major-mode)
11366 (ext
11367 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11368 (match-string 1 dfile)))
11369 cmd link-match-data)
11370 (cond
11371 ((member in-emacs '((16) system))
11372 (setq cmd (cdr (assq 'system apps))))
11373 (in-emacs (setq cmd 'emacs))
11375 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11376 (and dirp (cdr (assq 'directory apps)))
11377 ;; First, try matching against apps-dlink if we
11378 ;; get a match here, store the match data for
11379 ;; later.
11380 (let ((match (assoc-default dlink apps-dlink
11381 'string-match)))
11382 (if match
11383 (progn (setq link-match-data (match-data))
11384 match)
11385 (progn (setq in-emacs (or in-emacs line search))
11386 nil))) ; if we have no match in apps-dlink,
11387 ; always open the file in emacs if line or search
11388 ; is given (for backwards compatibility)
11389 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11390 'string-match)
11391 (cdr (assoc ext apps))
11392 (cdr (assq t apps))))))
11393 (when (eq cmd 'system)
11394 (setq cmd (cdr (assq 'system apps))))
11395 (when (eq cmd 'default)
11396 (setq cmd (cdr (assoc t apps))))
11397 (when (eq cmd 'mailcap)
11398 (require 'mailcap)
11399 (mailcap-parse-mailcaps)
11400 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11401 (command (mailcap-mime-info mime-type)))
11402 (if (stringp command)
11403 (setq cmd command)
11404 (setq cmd 'emacs))))
11405 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11406 (not (file-exists-p file))
11407 (not org-open-non-existing-files))
11408 (user-error "No such file: %s" file))
11409 (cond
11410 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11411 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11412 (while (string-match "['\"]%s['\"]" cmd)
11413 (setq cmd (replace-match "%s" t t cmd)))
11414 (setq cmd (replace-regexp-in-string
11415 "%s"
11416 (shell-quote-argument (convert-standard-filename file))
11418 nil t))
11420 ;; Replace "%1", "%2" etc. in command with group matches from regex
11421 (save-match-data
11422 (let ((match-index 1)
11423 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11424 (set-match-data link-match-data)
11425 (while (<= match-index number-of-groups)
11426 (let ((regex (concat "%" (number-to-string match-index)))
11427 (replace-with (match-string match-index dlink)))
11428 (while (string-match regex cmd)
11429 (setq cmd (replace-match replace-with t t cmd))))
11430 (setq match-index (+ match-index 1)))))
11432 (save-window-excursion
11433 (message "Running %s...done" cmd)
11434 (start-process-shell-command cmd nil cmd)
11435 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11436 ((or (stringp cmd)
11437 (eq cmd 'emacs))
11438 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11439 (widen)
11440 (cond (line (org-goto-line line)
11441 (when (derived-mode-p 'org-mode) (org-reveal)))
11442 (search (org-link-search search))))
11443 ((functionp cmd)
11444 (save-match-data
11445 (set-match-data link-match-data)
11446 (condition-case nil
11447 (funcall cmd file link)
11448 ;; FIXME: Remove this check when most default installations
11449 ;; of Emacs have at least Org 9.0.
11450 ((debug wrong-number-of-arguments wrong-type-argument
11451 invalid-function)
11452 (user-error "Please see Org News for version 9.0 about \
11453 `org-file-apps'--Lisp error: %S" cmd)))))
11454 ((consp cmd)
11455 ;; FIXME: Remove this check when most default installations of
11456 ;; Emacs have at least Org 9.0.
11457 ;; Heads-up instead of silently fall back to
11458 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11459 ;; with sexp instead of a function for `cmd'.
11460 (user-error "Please see Org News for version 9.0 about \
11461 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11462 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11463 (and (derived-mode-p 'org-mode)
11464 (eq old-mode 'org-mode)
11465 (or (not (eq old-buffer (current-buffer)))
11466 (not (eq old-pos (point))))
11467 (org-mark-ring-push old-pos old-buffer))))
11469 (defun org-file-apps-entry-match-against-dlink-p (entry)
11470 "This function returns non-nil if `entry' uses a regular
11471 expression which should be matched against the whole link by
11472 org-open-file.
11474 It assumes that is the case when the entry uses a regular
11475 expression which has at least one grouping construct and the
11476 action is either a lisp form or a command string containing
11477 `%1', i.e. using at least one subexpression match as a
11478 parameter."
11479 (let ((selector (car entry))
11480 (action (cdr entry)))
11481 (if (stringp selector)
11482 (and (> (regexp-opt-depth selector) 0)
11483 (or (and (stringp action)
11484 (string-match "%[0-9]" action))
11485 (consp action)))
11486 nil)))
11488 (defun org-default-apps ()
11489 "Return the default applications for this operating system."
11490 (cond
11491 ((eq system-type 'darwin)
11492 org-file-apps-defaults-macosx)
11493 ((eq system-type 'windows-nt)
11494 org-file-apps-defaults-windowsnt)
11495 (t org-file-apps-defaults-gnu)))
11497 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11498 "Convert extensions to regular expressions in the cars of LIST.
11499 Also, weed out any non-string entries, because the return value is used
11500 only for regexp matching.
11501 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11502 point to the symbol `emacs', indicating that the file should
11503 be opened in Emacs."
11504 (append
11505 (delq nil
11506 (mapcar (lambda (x)
11507 (unless (not (stringp (car x)))
11508 (if (string-match "\\W" (car x))
11510 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11511 list))
11512 (when add-auto-mode
11513 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11515 (defvar ange-ftp-name-format)
11516 (defun org-file-remote-p (file)
11517 "Test whether FILE specifies a location on a remote system.
11518 Return non-nil if the location is indeed remote.
11520 For example, the filename \"/user@host:/foo\" specifies a location
11521 on the system \"/user@host:\"."
11522 (cond ((fboundp 'file-remote-p)
11523 (file-remote-p file))
11524 ((fboundp 'tramp-handle-file-remote-p)
11525 (tramp-handle-file-remote-p file))
11526 ((and (boundp 'ange-ftp-name-format)
11527 (string-match (car ange-ftp-name-format) file))
11528 t)))
11531 ;;;; Refiling
11533 (defun org-get-org-file ()
11534 "Read a filename, with default directory `org-directory'."
11535 (let ((default (or org-default-notes-file remember-data-file)))
11536 (read-file-name (format "File name [%s]: " default)
11537 (file-name-as-directory org-directory)
11538 default)))
11540 (defun org-notes-order-reversed-p ()
11541 "Check if the current file should receive notes in reversed order."
11542 (cond
11543 ((not org-reverse-note-order) nil)
11544 ((eq t org-reverse-note-order) t)
11545 ((not (listp org-reverse-note-order)) nil)
11546 (t (catch 'exit
11547 (dolist (entry org-reverse-note-order)
11548 (when (string-match (car entry) buffer-file-name)
11549 (throw 'exit (cdr entry))))))))
11551 (defvar org-refile-target-table nil
11552 "The list of refile targets, created by `org-refile'.")
11554 (defvar org-agenda-new-buffers nil
11555 "Buffers created to visit agenda files.")
11557 (defvar org-refile-cache nil
11558 "Cache for refile targets.")
11560 (defvar org-refile-markers nil
11561 "All the markers used for caching refile locations.")
11563 (defun org-refile-marker (pos)
11564 "Get a new refile marker, but only if caching is in use."
11565 (if (not org-refile-use-cache)
11567 (let ((m (make-marker)))
11568 (move-marker m pos)
11569 (push m org-refile-markers)
11570 m)))
11572 (defun org-refile-cache-clear ()
11573 "Clear the refile cache and disable all the markers."
11574 (dolist (m org-refile-markers) (move-marker m nil))
11575 (setq org-refile-markers nil)
11576 (setq org-refile-cache nil)
11577 (message "Refile cache has been cleared"))
11579 (defun org-refile-cache-check-set (set)
11580 "Check if all the markers in the cache still have live buffers."
11581 (let (marker)
11582 (catch 'exit
11583 (while (and set (setq marker (nth 3 (pop set))))
11584 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11585 (when (and marker (null (marker-buffer marker)))
11586 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11587 (sit-for 3)
11588 (throw 'exit nil)))
11589 t)))
11591 (defun org-refile-cache-put (set &rest identifiers)
11592 "Push the refile targets SET into the cache, under IDENTIFIERS."
11593 (let* ((key (sha1 (prin1-to-string identifiers)))
11594 (entry (assoc key org-refile-cache)))
11595 (if entry
11596 (setcdr entry set)
11597 (push (cons key set) org-refile-cache))))
11599 (defun org-refile-cache-get (&rest identifiers)
11600 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11601 (cond
11602 ((not org-refile-cache) nil)
11603 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11605 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11606 org-refile-cache))))
11607 (and set (org-refile-cache-check-set set) set)))))
11609 (defvar org-outline-path-cache nil
11610 "Alist between buffer positions and outline paths.
11611 It value is an alist (POSITION . PATH) where POSITION is the
11612 buffer position at the beginning of an entry and PATH is a list
11613 of strings describing the outline path for that entry, in reverse
11614 order.")
11616 (defun org-refile-get-targets (&optional default-buffer)
11617 "Produce a table with refile targets."
11618 (let ((case-fold-search nil)
11619 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11620 (entries (or org-refile-targets '((nil . (:level . 1)))))
11621 targets tgs files desc descre)
11622 (message "Getting targets...")
11623 (with-current-buffer (or default-buffer (current-buffer))
11624 (dolist (entry entries)
11625 (setq files (car entry) desc (cdr entry))
11626 (cond
11627 ((null files) (setq files (list (current-buffer))))
11628 ((eq files 'org-agenda-files)
11629 (setq files (org-agenda-files 'unrestricted)))
11630 ((and (symbolp files) (fboundp files))
11631 (setq files (funcall files)))
11632 ((and (symbolp files) (boundp files))
11633 (setq files (symbol-value files))))
11634 (when (stringp files) (setq files (list files)))
11635 (cond
11636 ((eq (car desc) :tag)
11637 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11638 ((eq (car desc) :todo)
11639 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11640 ((eq (car desc) :regexp)
11641 (setq descre (cdr desc)))
11642 ((eq (car desc) :level)
11643 (setq descre (concat "^\\*\\{" (number-to-string
11644 (if org-odd-levels-only
11645 (1- (* 2 (cdr desc)))
11646 (cdr desc)))
11647 "\\}[ \t]")))
11648 ((eq (car desc) :maxlevel)
11649 (setq descre (concat "^\\*\\{1," (number-to-string
11650 (if org-odd-levels-only
11651 (1- (* 2 (cdr desc)))
11652 (cdr desc)))
11653 "\\}[ \t]")))
11654 (t (error "Bad refiling target description %s" desc)))
11655 (dolist (f files)
11656 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11658 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11659 (progn
11660 (when (bufferp f)
11661 (setq f (buffer-file-name (buffer-base-buffer f))))
11662 (setq f (and f (expand-file-name f)))
11663 (when (eq org-refile-use-outline-path 'file)
11664 (push (list (file-name-nondirectory f) f nil nil) tgs))
11665 (org-with-wide-buffer
11666 (goto-char (point-min))
11667 (setq org-outline-path-cache nil)
11668 (while (re-search-forward descre nil t)
11669 (beginning-of-line)
11670 (let ((case-fold-search nil))
11671 (looking-at org-complex-heading-regexp))
11672 (let ((begin (point))
11673 (heading (match-string-no-properties 4)))
11674 (unless (or (and
11675 org-refile-target-verify-function
11676 (not
11677 (funcall org-refile-target-verify-function)))
11678 (not heading))
11679 (let ((re (format org-complex-heading-regexp-format
11680 (regexp-quote heading)))
11681 (target
11682 (if (not org-refile-use-outline-path) heading
11683 (mapconcat
11684 #'org-protect-slash
11685 (append
11686 (pcase org-refile-use-outline-path
11687 (`file (list (file-name-nondirectory
11688 (buffer-file-name
11689 (buffer-base-buffer)))))
11690 (`full-file-path
11691 (list (buffer-file-name
11692 (buffer-base-buffer))))
11693 (_ nil))
11694 (org-get-outline-path t t))
11695 "/"))))
11696 (push (list target f re (org-refile-marker (point)))
11697 tgs)))
11698 (when (= (point) begin)
11699 ;; Verification function has not moved point.
11700 (end-of-line)))))))
11701 (when org-refile-use-cache
11702 (org-refile-cache-put tgs (buffer-file-name) descre))
11703 (setq targets (append tgs targets))))))
11704 (message "Getting targets...done")
11705 (nreverse targets)))
11707 (defun org-protect-slash (s)
11708 (replace-regexp-in-string "/" "\\/" s nil t))
11710 (defun org--get-outline-path-1 (&optional use-cache)
11711 "Return outline path to current headline.
11713 Outline path is a list of strings, in reverse order. When
11714 optional argument USE-CACHE is non-nil, make use of a cache. See
11715 `org-get-outline-path' for details.
11717 Assume buffer is widened and point is on a headline."
11718 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11719 (let ((p (point))
11720 (heading (let ((case-fold-search nil))
11721 (looking-at org-complex-heading-regexp)
11722 (if (not (match-end 4)) ""
11723 ;; Remove statistics cookies.
11724 (org-trim
11725 (org-link-display-format
11726 (replace-regexp-in-string
11727 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11728 (match-string-no-properties 4))))))))
11729 (if (org-up-heading-safe)
11730 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11731 (when use-cache
11732 (push (cons p path) org-outline-path-cache))
11733 path)
11734 ;; This is a new root node. Since we assume we are moving
11735 ;; forward, we can drop previous cache so as to limit number
11736 ;; of associations there.
11737 (let ((path (list heading)))
11738 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11739 path)))))
11741 (defun org-get-outline-path (&optional with-self use-cache)
11742 "Return the outline path to the current entry.
11744 An outline path is a list of ancestors for current headline, as
11745 a list of strings. Statistics cookies are removed and links are
11746 replaced with their description, if any, or their path otherwise.
11748 When optional argument WITH-SELF is non-nil, the path also
11749 includes the current headline.
11751 When optional argument USE-CACHE is non-nil, cache outline paths
11752 between calls to this function so as to avoid backtracking. This
11753 argument is useful when planning to find more than one outline
11754 path in the same document. In that case, there are two
11755 conditions to satisfy:
11756 - `org-outline-path-cache' is set to nil before starting the
11757 process;
11758 - outline paths are computed by increasing buffer positions."
11759 (org-with-wide-buffer
11760 (and (or (and with-self (org-back-to-heading t))
11761 (org-up-heading-safe))
11762 (reverse (org--get-outline-path-1 use-cache)))))
11764 (defun org-format-outline-path (path &optional width prefix separator)
11765 "Format the outline path PATH for display.
11766 WIDTH is the maximum number of characters that is available.
11767 PREFIX is a prefix to be included in the returned string,
11768 such as the file name.
11769 SEPARATOR is inserted between the different parts of the path,
11770 the default is \"/\"."
11771 (setq width (or width 79))
11772 (setq path (delq nil path))
11773 (unless (> width 0)
11774 (user-error "Argument `width' must be positive"))
11775 (setq separator (or separator "/"))
11776 (let* ((org-odd-levels-only nil)
11777 (fpath (concat
11778 prefix (and prefix path separator)
11779 (mapconcat
11780 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11781 (cl-loop for head in path
11782 for n from 0
11783 collect (org-add-props
11784 head nil 'face
11785 (nth (% n org-n-level-faces) org-level-faces)))
11786 separator))))
11787 (when (> (length fpath) width)
11788 (if (< width 7)
11789 ;; It's unlikely that `width' will be this small, but don't
11790 ;; waste characters by adding ".." if it is.
11791 (setq fpath (substring fpath 0 width))
11792 (setf (substring fpath (- width 2)) "..")))
11793 fpath))
11795 (defun org-display-outline-path (&optional file current separator just-return-string)
11796 "Display the current outline path in the echo area.
11798 If FILE is non-nil, prepend the output with the file name.
11799 If CURRENT is non-nil, append the current heading to the output.
11800 SEPARATOR is passed through to `org-format-outline-path'. It separates
11801 the different parts of the path and defaults to \"/\".
11802 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11803 (interactive "P")
11804 (let* (case-fold-search
11805 (bfn (buffer-file-name (buffer-base-buffer)))
11806 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11807 res)
11808 (when current (setq path (append path
11809 (save-excursion
11810 (org-back-to-heading t)
11811 (when (looking-at org-complex-heading-regexp)
11812 (list (match-string 4)))))))
11813 (setq res
11814 (org-format-outline-path
11815 path
11816 (1- (frame-width))
11817 (and file bfn (concat (file-name-nondirectory bfn) separator))
11818 separator))
11819 (if just-return-string
11820 (org-no-properties res)
11821 (org-unlogged-message "%s" res))))
11823 (defvar org-refile-history nil
11824 "History for refiling operations.")
11826 (defvar org-after-refile-insert-hook nil
11827 "Hook run after `org-refile' has inserted its stuff at the new location.
11828 Note that this is still *before* the stuff will be removed from
11829 the *old* location.")
11831 (defvar org-capture-last-stored-marker)
11832 (defvar org-refile-keep nil
11833 "Non-nil means `org-refile' will copy instead of refile.")
11835 (defun org-copy ()
11836 "Like `org-refile', but copy."
11837 (interactive)
11838 (let ((org-refile-keep t))
11839 (funcall 'org-refile nil nil nil "Copy")))
11841 (defun org-refile (&optional arg default-buffer rfloc msg)
11842 "Move the entry or entries at point to another heading.
11844 The list of target headings is compiled using the information in
11845 `org-refile-targets', which see.
11847 At the target location, the entry is filed as a subitem of the
11848 target heading. Depending on `org-reverse-note-order', the new
11849 subitem will either be the first or the last subitem.
11851 If there is an active region, all entries in that region will be
11852 refiled. However, the region must fulfill the requirement that
11853 the first heading sets the top-level of the moved text.
11855 With a `\\[universal-argument]' ARG, the command will only visit the target \
11856 location
11857 and not actually move anything.
11859 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11860 location where the last
11861 refiling operation has put the subtree.
11863 With a numeric prefix argument of `2', refile to the running clock.
11865 With a numeric prefix argument of `3', emulate `org-refile-keep'
11866 being set to t and copy to the target location, don't move it.
11867 Beware that keeping refiled entries may result in duplicated ID
11868 properties.
11870 RFLOC can be a refile location obtained in a different way.
11872 MSG is a string to replace \"Refile\" in the default prompt with
11873 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11875 See also `org-refile-use-outline-path'.
11877 If you are using target caching (see `org-refile-use-cache'), you
11878 have to clear the target cache in order to find new targets.
11879 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11880 prefix argument (`C-u C-u C-u C-c C-w')."
11881 (interactive "P")
11882 (if (member arg '(0 (64)))
11883 (org-refile-cache-clear)
11884 (let* ((actionmsg (cond (msg msg)
11885 ((equal arg 3) "Refile (and keep)")
11886 (t "Refile")))
11887 (regionp (org-region-active-p))
11888 (region-start (and regionp (region-beginning)))
11889 (region-end (and regionp (region-end)))
11890 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11891 pos it nbuf file level reversed)
11892 (setq last-command nil)
11893 (when regionp
11894 (goto-char region-start)
11895 (or (bolp) (goto-char (point-at-bol)))
11896 (setq region-start (point))
11897 (unless (or (org-kill-is-subtree-p
11898 (buffer-substring region-start region-end))
11899 (prog1 org-refile-active-region-within-subtree
11900 (let ((s (point-at-eol)))
11901 (org-toggle-heading)
11902 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11903 (user-error "The region is not a (sequence of) subtree(s)")))
11904 (if (equal arg '(16))
11905 (org-refile-goto-last-stored)
11906 (when (or
11907 (and (equal arg 2)
11908 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11909 (prog1
11910 (setq it (list (or org-clock-heading "running clock")
11911 (buffer-file-name
11912 (marker-buffer org-clock-hd-marker))
11914 (marker-position org-clock-hd-marker)))
11915 (setq arg nil)))
11916 (setq it
11917 (or rfloc
11918 (let (heading-text)
11919 (save-excursion
11920 (unless (and arg (listp arg))
11921 (org-back-to-heading t)
11922 (setq heading-text
11923 (replace-regexp-in-string
11924 org-bracket-link-regexp
11925 "\\3"
11926 (or (nth 4 (org-heading-components))
11927 ""))))
11928 (org-refile-get-location
11929 (cond ((and arg (listp arg)) "Goto")
11930 (regionp (concat actionmsg " region to"))
11931 (t (concat actionmsg " subtree \""
11932 heading-text "\" to")))
11933 default-buffer
11934 (and (not (equal '(4) arg))
11935 org-refile-allow-creating-parent-nodes)))))))
11936 (setq file (nth 1 it)
11937 pos (nth 3 it))
11938 (when (and (not arg)
11940 (equal (buffer-file-name) file)
11941 (if regionp
11942 (and (>= pos region-start)
11943 (<= pos region-end))
11944 (and (>= pos (point))
11945 (< pos (save-excursion
11946 (org-end-of-subtree t t))))))
11947 (error "Cannot refile to position inside the tree or region"))
11948 (setq nbuf (or (find-buffer-visiting file)
11949 (find-file-noselect file)))
11950 (if (and arg (not (equal arg 3)))
11951 (progn
11952 (pop-to-buffer-same-window nbuf)
11953 (goto-char pos)
11954 (org-show-context 'org-goto))
11955 (if regionp
11956 (progn
11957 (org-kill-new (buffer-substring region-start region-end))
11958 (org-save-markers-in-region region-start region-end))
11959 (org-copy-subtree 1 nil t))
11960 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11961 (find-file-noselect file)))
11962 (setq reversed (org-notes-order-reversed-p))
11963 (org-with-wide-buffer
11964 (if pos
11965 (progn
11966 (goto-char pos)
11967 (looking-at org-outline-regexp)
11968 (setq level (org-get-valid-level (funcall outline-level) 1))
11969 (goto-char
11970 (if reversed
11971 (or (outline-next-heading) (point-max))
11972 (or (save-excursion (org-get-next-sibling))
11973 (org-end-of-subtree t t)
11974 (point-max)))))
11975 (setq level 1)
11976 (if (not reversed)
11977 (goto-char (point-max))
11978 (goto-char (point-min))
11979 (or (outline-next-heading) (goto-char (point-max)))))
11980 (unless (bolp) (newline))
11981 (org-paste-subtree level nil nil t)
11982 (when org-log-refile
11983 (org-add-log-setup 'refile nil nil org-log-refile)
11984 (unless (eq org-log-refile 'note)
11985 (save-excursion (org-add-log-note))))
11986 (and org-auto-align-tags
11987 (let ((org-loop-over-headlines-in-active-region nil))
11988 (org-set-tags nil t)))
11989 (let ((bookmark-name (plist-get org-bookmark-names-plist
11990 :last-refile)))
11991 (when bookmark-name
11992 (with-demoted-errors
11993 (bookmark-set bookmark-name))))
11994 ;; If we are refiling for capture, make sure that the
11995 ;; last-capture pointers point here
11996 (when (bound-and-true-p org-capture-is-refiling)
11997 (let ((bookmark-name (plist-get org-bookmark-names-plist
11998 :last-capture-marker)))
11999 (when bookmark-name
12000 (with-demoted-errors
12001 (bookmark-set bookmark-name))))
12002 (move-marker org-capture-last-stored-marker (point)))
12003 (when (fboundp 'deactivate-mark) (deactivate-mark))
12004 (run-hooks 'org-after-refile-insert-hook)))
12005 (unless org-refile-keep
12006 (if regionp
12007 (delete-region (point) (+ (point) (- region-end region-start)))
12008 (delete-region
12009 (and (org-back-to-heading t) (point))
12010 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12011 (when (featurep 'org-inlinetask)
12012 (org-inlinetask-remove-END-maybe))
12013 (setq org-markers-to-move nil)
12014 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12016 (defun org-refile-goto-last-stored ()
12017 "Go to the location where the last refile was stored."
12018 (interactive)
12019 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12020 (message "This is the location of the last refile"))
12022 (defun org-refile--get-location (refloc tbl)
12023 "When user refile to REFLOC, find the associated target in TBL.
12024 Also check `org-refile-target-table'."
12025 (car (delq
12027 (mapcar
12028 (lambda (r) (or (assoc r tbl)
12029 (assoc r org-refile-target-table)))
12030 (list (replace-regexp-in-string "/$" "" refloc)
12031 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12033 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12034 "Prompt the user for a refile location, using PROMPT.
12035 PROMPT should not be suffixed with a colon and a space, because
12036 this function appends the default value from
12037 `org-refile-history' automatically, if that is not empty."
12038 (let ((org-refile-targets org-refile-targets)
12039 (org-refile-use-outline-path org-refile-use-outline-path))
12040 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12041 (unless org-refile-target-table
12042 (user-error "No refile targets"))
12043 (let* ((cbuf (current-buffer))
12044 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12045 (cfunc (if (and org-refile-use-outline-path
12046 org-outline-path-complete-in-steps)
12047 #'org-olpath-completing-read
12048 #'completing-read))
12049 (extra (if org-refile-use-outline-path "/" ""))
12050 (cbnex (concat (buffer-name) extra))
12051 (filename (and cfn (expand-file-name cfn)))
12052 (tbl (mapcar
12053 (lambda (x)
12054 (if (and (not (member org-refile-use-outline-path
12055 '(file full-file-path)))
12056 (not (equal filename (nth 1 x))))
12057 (cons (concat (car x) extra " ("
12058 (file-name-nondirectory (nth 1 x)) ")")
12059 (cdr x))
12060 (cons (concat (car x) extra) (cdr x))))
12061 org-refile-target-table))
12062 (completion-ignore-case t)
12063 cdef
12064 (prompt (concat prompt
12065 (or (and (car org-refile-history)
12066 (concat " (default " (car org-refile-history) ")"))
12067 (and (assoc cbnex tbl) (setq cdef cbnex)
12068 (concat " (default " cbnex ")"))) ": "))
12069 pa answ parent-target child parent old-hist)
12070 (setq old-hist org-refile-history)
12071 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12072 nil 'org-refile-history (or cdef (car org-refile-history))))
12073 (if (setq pa (org-refile--get-location answ tbl))
12074 (progn
12075 (org-refile-check-position pa)
12076 (when (or (not org-refile-history)
12077 (not (eq old-hist org-refile-history))
12078 (not (equal (car pa) (car org-refile-history))))
12079 (setq org-refile-history
12080 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12081 org-refile-history
12082 (cdr org-refile-history))))
12083 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12084 (pop org-refile-history)))
12086 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12087 (progn
12088 (setq parent (match-string 1 answ)
12089 child (match-string 2 answ))
12090 (setq parent-target (org-refile--get-location parent tbl))
12091 (when (and parent-target
12092 (or (eq new-nodes t)
12093 (and (eq new-nodes 'confirm)
12094 (y-or-n-p (format "Create new node \"%s\"? "
12095 child)))))
12096 (org-refile-new-child parent-target child)))
12097 (user-error "Invalid target location")))))
12099 (declare-function org-string-nw-p "org-macs" (s))
12100 (defun org-refile-check-position (refile-pointer)
12101 "Check if the refile pointer matches the headline to which it points."
12102 (let* ((file (nth 1 refile-pointer))
12103 (re (nth 2 refile-pointer))
12104 (pos (nth 3 refile-pointer))
12105 buffer)
12106 (if (and (not (markerp pos)) (not file))
12107 (user-error "Please indicate a target file in the refile path")
12108 (when (org-string-nw-p re)
12109 (setq buffer (if (markerp pos)
12110 (marker-buffer pos)
12111 (or (find-buffer-visiting file)
12112 (find-file-noselect file))))
12113 (with-current-buffer buffer
12114 (org-with-wide-buffer
12115 (goto-char pos)
12116 (beginning-of-line 1)
12117 (unless (looking-at-p re)
12118 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12120 (defun org-refile-new-child (parent-target child)
12121 "Use refile target PARENT-TARGET to add new CHILD below it."
12122 (unless parent-target
12123 (error "Cannot find parent for new node"))
12124 (let ((file (nth 1 parent-target))
12125 (pos (nth 3 parent-target))
12126 level)
12127 (with-current-buffer (or (find-buffer-visiting file)
12128 (find-file-noselect file))
12129 (org-with-wide-buffer
12130 (if pos
12131 (goto-char pos)
12132 (goto-char (point-max))
12133 (unless (bolp) (newline)))
12134 (when (looking-at org-outline-regexp)
12135 (setq level (funcall outline-level))
12136 (org-end-of-subtree t t))
12137 (org-back-over-empty-lines)
12138 (insert "\n" (make-string
12139 (if pos (org-get-valid-level level 1) 1) ?*)
12140 " " child "\n")
12141 (beginning-of-line 0)
12142 (list (concat (car parent-target) "/" child) file "" (point))))))
12144 (defun org-olpath-completing-read (prompt collection &rest args)
12145 "Read an outline path like a file name."
12146 (let ((thetable collection))
12147 (apply #'completing-read
12148 prompt
12149 (lambda (string predicate &optional flag)
12150 (cond
12151 ((eq flag nil) (try-completion string thetable))
12152 ((eq flag t)
12153 (let ((l (length string)))
12154 (mapcar (lambda (x)
12155 (let ((r (substring x l))
12156 (f (if (string-match " ([^)]*)$" x)
12157 (match-string 0 x)
12158 "")))
12159 (if (string-match "/" r)
12160 (concat string (substring r 0 (match-end 0)) f)
12161 x)))
12162 (all-completions string thetable predicate))))
12163 ;; Exact match?
12164 ((eq flag 'lambda) (assoc string thetable))))
12165 args)))
12167 ;;;; Dynamic blocks
12169 (defun org-find-dblock (name)
12170 "Find the first dynamic block with name NAME in the buffer.
12171 If not found, stay at current position and return nil."
12172 (let ((case-fold-search t) pos)
12173 (save-excursion
12174 (goto-char (point-min))
12175 (setq pos (and (re-search-forward
12176 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12177 (match-beginning 0))))
12178 (when pos (goto-char pos))
12179 pos))
12181 (defun org-create-dblock (plist)
12182 "Create a dynamic block section, with parameters taken from PLIST.
12183 PLIST must contain a :name entry which is used as the name of the block."
12184 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12185 (end-of-line 1)
12186 (newline))
12187 (let ((col (current-column))
12188 (name (plist-get plist :name)))
12189 (insert "#+BEGIN: " name)
12190 (while plist
12191 (if (eq (car plist) :name)
12192 (setq plist (cddr plist))
12193 (insert " " (prin1-to-string (pop plist)))))
12194 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12195 (beginning-of-line -2)))
12197 (defun org-prepare-dblock ()
12198 "Prepare dynamic block for refresh.
12199 This empties the block, puts the cursor at the insert position and returns
12200 the property list including an extra property :name with the block name."
12201 (unless (looking-at org-dblock-start-re)
12202 (user-error "Not at a dynamic block"))
12203 (let* ((begdel (1+ (match-end 0)))
12204 (name (org-no-properties (match-string 1)))
12205 (params (append (list :name name)
12206 (read (concat "(" (match-string 3) ")")))))
12207 (save-excursion
12208 (beginning-of-line 1)
12209 (skip-chars-forward " \t")
12210 (setq params (plist-put params :indentation-column (current-column))))
12211 (unless (re-search-forward org-dblock-end-re nil t)
12212 (error "Dynamic block not terminated"))
12213 (setq params
12214 (append params
12215 (list :content (buffer-substring
12216 begdel (match-beginning 0)))))
12217 (delete-region begdel (match-beginning 0))
12218 (goto-char begdel)
12219 (open-line 1)
12220 params))
12222 (defun org-map-dblocks (&optional command)
12223 "Apply COMMAND to all dynamic blocks in the current buffer.
12224 If COMMAND is not given, use `org-update-dblock'."
12225 (let ((cmd (or command 'org-update-dblock)))
12226 (save-excursion
12227 (goto-char (point-min))
12228 (while (re-search-forward org-dblock-start-re nil t)
12229 (goto-char (match-beginning 0))
12230 (save-excursion
12231 (condition-case nil
12232 (funcall cmd)
12233 (error (message "Error during update of dynamic block"))))
12234 (unless (re-search-forward org-dblock-end-re nil t)
12235 (error "Dynamic block not terminated"))))))
12237 (defun org-dblock-update (&optional arg)
12238 "User command for updating dynamic blocks.
12239 Update the dynamic block at point. With prefix ARG, update all dynamic
12240 blocks in the buffer."
12241 (interactive "P")
12242 (if arg
12243 (org-update-all-dblocks)
12244 (or (looking-at org-dblock-start-re)
12245 (org-beginning-of-dblock))
12246 (org-update-dblock)))
12248 (defun org-update-dblock ()
12249 "Update the dynamic block at point.
12250 This means to empty the block, parse for parameters and then call
12251 the correct writing function."
12252 (interactive)
12253 (save-excursion
12254 (let* ((win (selected-window))
12255 (pos (point))
12256 (line (org-current-line))
12257 (params (org-prepare-dblock))
12258 (name (plist-get params :name))
12259 (indent (plist-get params :indentation-column))
12260 (cmd (intern (concat "org-dblock-write:" name))))
12261 (message "Updating dynamic block `%s' at line %d..." name line)
12262 (funcall cmd params)
12263 (message "Updating dynamic block `%s' at line %d...done" name line)
12264 (goto-char pos)
12265 (when (and indent (> indent 0))
12266 (setq indent (make-string indent ?\ ))
12267 (save-excursion
12268 (select-window win)
12269 (org-beginning-of-dblock)
12270 (forward-line 1)
12271 (while (not (looking-at org-dblock-end-re))
12272 (insert indent)
12273 (beginning-of-line 2))
12274 (when (looking-at org-dblock-end-re)
12275 (and (looking-at "[ \t]+")
12276 (replace-match ""))
12277 (insert indent)))))))
12279 (defun org-beginning-of-dblock ()
12280 "Find the beginning of the dynamic block at point.
12281 Error if there is no such block at point."
12282 (let ((pos (point))
12283 beg)
12284 (end-of-line 1)
12285 (if (and (re-search-backward org-dblock-start-re nil t)
12286 (setq beg (match-beginning 0))
12287 (re-search-forward org-dblock-end-re nil t)
12288 (> (match-end 0) pos))
12289 (goto-char beg)
12290 (goto-char pos)
12291 (error "Not in a dynamic block"))))
12293 (defun org-update-all-dblocks ()
12294 "Update all dynamic blocks in the buffer.
12295 This function can be used in a hook."
12296 (interactive)
12297 (when (derived-mode-p 'org-mode)
12298 (org-map-dblocks 'org-update-dblock)))
12301 ;;;; Completion
12303 (declare-function org-export-backend-options "ox" (cl-x) t)
12304 (defun org-get-export-keywords ()
12305 "Return a list of all currently understood export keywords.
12306 Export keywords include options, block names, attributes and
12307 keywords relative to each registered export back-end."
12308 (let (keywords)
12309 (dolist (backend
12310 (bound-and-true-p org-export-registered-backends)
12311 (delq nil keywords))
12312 ;; Back-end name (for keywords, like #+LATEX:)
12313 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12314 (dolist (option-entry (org-export-backend-options backend))
12315 ;; Back-end options.
12316 (push (nth 1 option-entry) keywords)))))
12318 (defconst org-options-keywords
12319 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12320 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12321 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12322 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12323 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12325 (defcustom org-structure-template-alist
12326 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12327 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12328 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12329 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12330 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12331 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12332 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12333 ("L" "#+LaTeX: ")
12334 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12335 ("H" "#+HTML: ")
12336 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12337 ("A" "#+ASCII: ")
12338 ("i" "#+INDEX: ?")
12339 ("I" "#+INCLUDE: %file ?"))
12340 "Structure completion elements.
12341 This is a list of abbreviation keys and values. The value gets inserted
12342 if you type `<' followed by the key and then press the completion key,
12343 usually `TAB'. %file will be replaced by a file name after prompting
12344 for the file using completion. The cursor will be placed at the position
12345 of the `?' in the template.
12346 There are two templates for each key, the first uses the original Org syntax,
12347 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12348 the default when the /org-mtags.el/ module has been loaded. See also the
12349 variable `org-mtags-prefer-muse-templates'."
12350 :group 'org-completion
12351 :type '(repeat
12352 (list
12353 (string :tag "Key")
12354 (string :tag "Template")))
12355 :version "25.2"
12356 :package-version '(Org . "8.3"))
12358 (defun org-try-structure-completion ()
12359 "Try to complete a structure template before point.
12360 This looks for strings like \"<e\" on an otherwise empty line and
12361 expands them."
12362 (let ((l (buffer-substring (point-at-bol) (point)))
12364 (when (and (looking-at "[ \t]*$")
12365 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12366 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12367 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12368 (match-beginning 1)) a)
12369 t)))
12371 (defun org-complete-expand-structure-template (start cell)
12372 "Expand a structure template."
12373 (let ((rpl (nth 1 cell))
12374 (ind ""))
12375 (delete-region start (point))
12376 (when (string-match "\\`[ \t]*#\\+" rpl)
12377 (cond
12378 ((bolp))
12379 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12380 (setq ind (buffer-substring (point-at-bol) (point))))
12381 (t (newline))))
12382 (setq start (point))
12383 (when (string-match "%file" rpl)
12384 (setq rpl (replace-match
12385 (concat
12386 "\""
12387 (save-match-data
12388 (abbreviate-file-name (read-file-name "Include file: ")))
12389 "\"")
12390 t t rpl)))
12391 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12392 (concat "\n" ind)))
12393 (insert rpl)
12394 (when (re-search-backward "\\?" start t) (delete-char 1))))
12396 ;;;; TODO, DEADLINE, Comments
12398 (defun org-toggle-comment ()
12399 "Change the COMMENT state of an entry."
12400 (interactive)
12401 (save-excursion
12402 (org-back-to-heading)
12403 (let ((case-fold-search nil))
12404 (looking-at org-complex-heading-regexp))
12405 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12406 (skip-chars-forward " \t")
12407 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12408 (if (org-in-commented-heading-p t)
12409 (delete-region (point)
12410 (progn (search-forward " " (line-end-position) 'move)
12411 (skip-chars-forward " \t")
12412 (point)))
12413 (insert org-comment-string)
12414 (unless (eolp) (insert " ")))))
12416 (defvar org-last-todo-state-is-todo nil
12417 "This is non-nil when the last TODO state change led to a TODO state.
12418 If the last change removed the TODO tag or switched to DONE, then
12419 this is nil.")
12421 (defvar org-setting-tags nil) ; dynamically skipped
12423 (defvar org-todo-setup-filter-hook nil
12424 "Hook for functions that pre-filter todo specs.
12425 Each function takes a todo spec and returns either nil or the spec
12426 transformed into canonical form." )
12428 (defvar org-todo-get-default-hook nil
12429 "Hook for functions that get a default item for todo.
12430 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12431 nil or a string to be used for the todo mark." )
12433 (defvar org-agenda-headline-snapshot-before-repeat)
12435 (defun org-current-effective-time ()
12436 "Return current time adjusted for `org-extend-today-until' variable."
12437 (let* ((ct (org-current-time))
12438 (dct (decode-time ct))
12439 (ct1
12440 (cond
12441 (org-use-last-clock-out-time-as-effective-time
12442 (or (org-clock-get-last-clock-out-time) ct))
12443 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12444 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12445 (t ct))))
12446 ct1))
12448 (defun org-todo-yesterday (&optional arg)
12449 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12450 (interactive "P")
12451 (if (eq major-mode 'org-agenda-mode)
12452 (apply 'org-agenda-todo-yesterday arg)
12453 (let* ((org-use-effective-time t)
12454 (hour (nth 2 (decode-time (org-current-time))))
12455 (org-extend-today-until (1+ hour)))
12456 (org-todo arg))))
12458 (defvar org-block-entry-blocking ""
12459 "First entry preventing the TODO state change.")
12461 (defun org-cancel-repeater ()
12462 "Cancel a repeater by setting its numeric value to zero."
12463 (interactive)
12464 (save-excursion
12465 (org-back-to-heading t)
12466 (let ((bound1 (point))
12467 (bound0 (save-excursion (outline-next-heading) (point))))
12468 (when (and (re-search-forward
12469 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12470 org-deadline-time-regexp "\\)\\|\\("
12471 org-ts-regexp "\\)")
12472 bound0 t)
12473 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12474 bound1 t))
12475 (replace-match "0" t nil nil 1)))))
12477 (defvar org-state) ;; dynamically scoped into this function
12478 (defun org-todo (&optional arg)
12479 "Change the TODO state of an item.
12481 The state of an item is given by a keyword at the start of the heading,
12482 like
12483 *** TODO Write paper
12484 *** DONE Call mom
12486 The different keywords are specified in the variable `org-todo-keywords'.
12487 By default the available states are \"TODO\" and \"DONE\". So, for this
12488 example: when the item starts with TODO, it is changed to DONE.
12489 When it starts with DONE, the DONE is removed. And when neither TODO nor
12490 DONE are present, add TODO at the beginning of the heading.
12492 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12493 state.
12494 With numeric prefix ARG, switch to that state.
12495 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12496 next set of TODO \
12497 keywords (nextset).
12498 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12499 prefix, circumvent any state blocking.
12500 With a numeric prefix arg of 0, inhibit note taking for the change.
12501 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12503 When called through ELisp, arg is also interpreted in the following way:
12504 `none' -> empty state
12505 \"\" -> switch to empty state
12506 `done' -> switch to DONE
12507 `nextset' -> switch to the next set of keywords
12508 `previousset' -> switch to the previous set of keywords
12509 \"WAITING\" -> switch to the specified keyword, but only if it
12510 really is a member of `org-todo-keywords'."
12511 (interactive "P")
12512 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12513 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12514 'region-start-level 'region))
12515 org-loop-over-headlines-in-active-region)
12516 (org-map-entries
12517 `(org-todo ,arg)
12518 org-loop-over-headlines-in-active-region
12519 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12520 (when (equal arg '(16)) (setq arg 'nextset))
12521 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12522 (let ((org-blocker-hook org-blocker-hook)
12523 commentp
12524 case-fold-search)
12525 (when (equal arg '(64))
12526 (setq arg nil org-blocker-hook nil))
12527 (when (and org-blocker-hook
12528 (or org-inhibit-blocking
12529 (org-entry-get nil "NOBLOCKING")))
12530 (setq org-blocker-hook nil))
12531 (save-excursion
12532 (catch 'exit
12533 (org-back-to-heading t)
12534 (when (org-in-commented-heading-p t)
12535 (org-toggle-comment)
12536 (setq commentp t))
12537 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12538 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12539 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12540 (let* ((match-data (match-data))
12541 (startpos (point-at-bol))
12542 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12543 (org-log-done org-log-done)
12544 (org-log-repeat org-log-repeat)
12545 (org-todo-log-states org-todo-log-states)
12546 (org-inhibit-logging
12547 (if (equal arg 0)
12548 (progn (setq arg nil) 'note) org-inhibit-logging))
12549 (this (match-string 1))
12550 (hl-pos (match-beginning 0))
12551 (head (org-get-todo-sequence-head this))
12552 (ass (assoc head org-todo-kwd-alist))
12553 (interpret (nth 1 ass))
12554 (done-word (nth 3 ass))
12555 (final-done-word (nth 4 ass))
12556 (org-last-state (or this ""))
12557 (completion-ignore-case t)
12558 (member (member this org-todo-keywords-1))
12559 (tail (cdr member))
12560 (org-state (cond
12561 ((and org-todo-key-trigger
12562 (or (and (equal arg '(4))
12563 (eq org-use-fast-todo-selection 'prefix))
12564 (and (not arg) org-use-fast-todo-selection
12565 (not (eq org-use-fast-todo-selection
12566 'prefix)))))
12567 ;; Use fast selection
12568 (org-fast-todo-selection))
12569 ((and (equal arg '(4))
12570 (or (not org-use-fast-todo-selection)
12571 (not org-todo-key-trigger)))
12572 ;; Read a state with completion
12573 (completing-read
12574 "State: " (mapcar #'list org-todo-keywords-1)
12575 nil t))
12576 ((eq arg 'right)
12577 (if this
12578 (if tail (car tail) nil)
12579 (car org-todo-keywords-1)))
12580 ((eq arg 'left)
12581 (unless (equal member org-todo-keywords-1)
12582 (if this
12583 (nth (- (length org-todo-keywords-1)
12584 (length tail) 2)
12585 org-todo-keywords-1)
12586 (org-last org-todo-keywords-1))))
12587 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12588 (setq arg nil))) ; hack to fall back to cycling
12589 (arg
12590 ;; user or caller requests a specific state
12591 (cond
12592 ((equal arg "") nil)
12593 ((eq arg 'none) nil)
12594 ((eq arg 'done) (or done-word (car org-done-keywords)))
12595 ((eq arg 'nextset)
12596 (or (car (cdr (member head org-todo-heads)))
12597 (car org-todo-heads)))
12598 ((eq arg 'previousset)
12599 (let ((org-todo-heads (reverse org-todo-heads)))
12600 (or (car (cdr (member head org-todo-heads)))
12601 (car org-todo-heads))))
12602 ((car (member arg org-todo-keywords-1)))
12603 ((stringp arg)
12604 (user-error "State `%s' not valid in this file" arg))
12605 ((nth (1- (prefix-numeric-value arg))
12606 org-todo-keywords-1))))
12607 ((null member) (or head (car org-todo-keywords-1)))
12608 ((equal this final-done-word) nil) ;; -> make empty
12609 ((null tail) nil) ;; -> first entry
12610 ((memq interpret '(type priority))
12611 (if (eq this-command last-command)
12612 (car tail)
12613 (if (> (length tail) 0)
12614 (or done-word (car org-done-keywords))
12615 nil)))
12617 (car tail))))
12618 (org-state (or
12619 (run-hook-with-args-until-success
12620 'org-todo-get-default-hook org-state org-last-state)
12621 org-state))
12622 (next (if org-state (concat " " org-state " ") " "))
12623 (change-plist (list :type 'todo-state-change :from this :to org-state
12624 :position startpos))
12625 dolog now-done-p)
12626 (when org-blocker-hook
12627 (setq org-last-todo-state-is-todo
12628 (not (member this org-done-keywords)))
12629 (unless (save-excursion
12630 (save-match-data
12631 (org-with-wide-buffer
12632 (run-hook-with-args-until-failure
12633 'org-blocker-hook change-plist))))
12634 (if (called-interactively-p 'interactive)
12635 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12636 this org-state org-block-entry-blocking)
12637 ;; fail silently
12638 (message "TODO state change from %s to %s blocked (by \"%s\")"
12639 this org-state org-block-entry-blocking)
12640 (throw 'exit nil))))
12641 (store-match-data match-data)
12642 (replace-match next t t)
12643 (cond ((equal this org-state)
12644 (message "TODO state was already %s" (org-trim next)))
12645 ((pos-visible-in-window-p hl-pos)
12646 (message "TODO state changed to %s" (org-trim next))))
12647 (unless head
12648 (setq head (org-get-todo-sequence-head org-state)
12649 ass (assoc head org-todo-kwd-alist)
12650 interpret (nth 1 ass)
12651 done-word (nth 3 ass)
12652 final-done-word (nth 4 ass)))
12653 (when (memq arg '(nextset previousset))
12654 (message "Keyword-Set %d/%d: %s"
12655 (- (length org-todo-sets) -1
12656 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12657 (length org-todo-sets)
12658 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12659 (setq org-last-todo-state-is-todo
12660 (not (member org-state org-done-keywords)))
12661 (setq now-done-p (and (member org-state org-done-keywords)
12662 (not (member this org-done-keywords))))
12663 (and logging (org-local-logging logging))
12664 (when (and (or org-todo-log-states org-log-done)
12665 (not (eq org-inhibit-logging t))
12666 (not (memq arg '(nextset previousset))))
12667 ;; we need to look at recording a time and note
12668 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12669 (nth 2 (assoc this org-todo-log-states))))
12670 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12671 (setq dolog 'time))
12672 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12673 (and org-state
12674 (member org-state org-not-done-keywords)
12675 (not (member this org-not-done-keywords))))
12676 ;; This is now a todo state and was not one before
12677 ;; If there was a CLOSED time stamp, get rid of it.
12678 (org-add-planning-info nil nil 'closed))
12679 (when (and now-done-p org-log-done)
12680 ;; It is now done, and it was not done before
12681 (org-add-planning-info 'closed (org-current-effective-time))
12682 (when (and (not dolog) (eq 'note org-log-done))
12683 (org-add-log-setup 'done org-state this 'note)))
12684 (when (and org-state dolog)
12685 ;; This is a non-nil state, and we need to log it
12686 (org-add-log-setup 'state org-state this dolog)))
12687 ;; Fixup tag positioning
12688 (org-todo-trigger-tag-changes org-state)
12689 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12690 (when org-provide-todo-statistics
12691 (org-update-parent-todo-statistics))
12692 (run-hooks 'org-after-todo-state-change-hook)
12693 (when (and arg (not (member org-state org-done-keywords)))
12694 (setq head (org-get-todo-sequence-head org-state)))
12695 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12696 ;; Do we need to trigger a repeat?
12697 (when now-done-p
12698 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12699 ;; This is for the agenda, take a snapshot of the headline.
12700 (save-match-data
12701 (setq org-agenda-headline-snapshot-before-repeat
12702 (org-get-heading))))
12703 (org-auto-repeat-maybe org-state))
12704 ;; Fixup cursor location if close to the keyword
12705 (when (and (outline-on-heading-p)
12706 (not (bolp))
12707 (save-excursion (beginning-of-line 1)
12708 (looking-at org-todo-line-regexp))
12709 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12710 (goto-char (or (match-end 2) (match-end 1)))
12711 (and (looking-at " ") (just-one-space)))
12712 (when org-trigger-hook
12713 (save-excursion
12714 (run-hook-with-args 'org-trigger-hook change-plist)))
12715 (when commentp (org-toggle-comment))))))))
12717 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12718 "Block turning an entry into a TODO, using the hierarchy.
12719 This checks whether the current task should be blocked from state
12720 changes. Such blocking occurs when:
12722 1. The task has children which are not all in a completed state.
12724 2. A task has a parent with the property :ORDERED:, and there
12725 are siblings prior to the current task with incomplete
12726 status.
12728 3. The parent of the task is blocked because it has siblings that should
12729 be done first, or is child of a block grandparent TODO entry."
12731 (if (not org-enforce-todo-dependencies)
12732 t ; if locally turned off don't block
12733 (catch 'dont-block
12734 ;; If this is not a todo state change, or if this entry is already DONE,
12735 ;; do not block
12736 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12737 (member (plist-get change-plist :from)
12738 (cons 'done org-done-keywords))
12739 (member (plist-get change-plist :to)
12740 (cons 'todo org-not-done-keywords))
12741 (not (plist-get change-plist :to)))
12742 (throw 'dont-block t))
12743 ;; If this task has children, and any are undone, it's blocked
12744 (save-excursion
12745 (org-back-to-heading t)
12746 (let ((this-level (funcall outline-level)))
12747 (outline-next-heading)
12748 (let ((child-level (funcall outline-level)))
12749 (while (and (not (eobp))
12750 (> child-level this-level))
12751 ;; this todo has children, check whether they are all
12752 ;; completed
12753 (when (and (not (org-entry-is-done-p))
12754 (org-entry-is-todo-p))
12755 (setq org-block-entry-blocking (org-get-heading))
12756 (throw 'dont-block nil))
12757 (outline-next-heading)
12758 (setq child-level (funcall outline-level))))))
12759 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12760 ;; any previous siblings are undone, it's blocked
12761 (save-excursion
12762 (org-back-to-heading t)
12763 (let* ((pos (point))
12764 (parent-pos (and (org-up-heading-safe) (point)))
12765 (case-fold-search nil))
12766 (unless parent-pos (throw 'dont-block t)) ; no parent
12767 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12768 (forward-line 1)
12769 (re-search-forward org-not-done-heading-regexp pos t))
12770 (setq org-block-entry-blocking (match-string 0))
12771 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12772 ;; Search further up the hierarchy, to see if an ancestor is blocked
12773 (while t
12774 (goto-char parent-pos)
12775 (unless (looking-at org-not-done-heading-regexp)
12776 (throw 'dont-block t)) ; do not block, parent is not a TODO
12777 (setq pos (point))
12778 (setq parent-pos (and (org-up-heading-safe) (point)))
12779 (unless parent-pos (throw 'dont-block t)) ; no parent
12780 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12781 (forward-line 1)
12782 (re-search-forward org-not-done-heading-regexp pos t)
12783 (setq org-block-entry-blocking (org-get-heading)))
12784 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12786 (defcustom org-track-ordered-property-with-tag nil
12787 "Should the ORDERED property also be shown as a tag?
12788 The ORDERED property decides if an entry should require subtasks to be
12789 completed in sequence. Since a property is not very visible, setting
12790 this option means that toggling the ORDERED property with the command
12791 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12792 not relevant for the behavior, but it makes things more visible.
12794 Note that toggling the tag with tags commands will not change the property
12795 and therefore not influence behavior!
12797 This can be t, meaning the tag ORDERED should be used, It can also be a
12798 string to select a different tag for this task."
12799 :group 'org-todo
12800 :type '(choice
12801 (const :tag "No tracking" nil)
12802 (const :tag "Track with ORDERED tag" t)
12803 (string :tag "Use other tag")))
12805 (defun org-toggle-ordered-property ()
12806 "Toggle the ORDERED property of the current entry.
12807 For better visibility, you can track the value of this property with a tag.
12808 See variable `org-track-ordered-property-with-tag'."
12809 (interactive)
12810 (let* ((t1 org-track-ordered-property-with-tag)
12811 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12812 (save-excursion
12813 (org-back-to-heading)
12814 (if (org-entry-get nil "ORDERED")
12815 (progn
12816 (org-delete-property "ORDERED")
12817 (and tag (org-toggle-tag tag 'off))
12818 (message "Subtasks can be completed in arbitrary order"))
12819 (org-entry-put nil "ORDERED" "t")
12820 (and tag (org-toggle-tag tag 'on))
12821 (message "Subtasks must be completed in sequence")))))
12823 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12824 (defun org-block-todo-from-checkboxes (change-plist)
12825 "Block turning an entry into a TODO, using checkboxes.
12826 This checks whether the current task should be blocked from state
12827 changes because there are unchecked boxes in this entry."
12828 (if (not org-enforce-todo-checkbox-dependencies)
12829 t ; if locally turned off don't block
12830 (catch 'dont-block
12831 ;; If this is not a todo state change, or if this entry is already DONE,
12832 ;; do not block
12833 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12834 (member (plist-get change-plist :from)
12835 (cons 'done org-done-keywords))
12836 (member (plist-get change-plist :to)
12837 (cons 'todo org-not-done-keywords))
12838 (not (plist-get change-plist :to)))
12839 (throw 'dont-block t))
12840 ;; If this task has checkboxes that are not checked, it's blocked
12841 (save-excursion
12842 (org-back-to-heading t)
12843 (let ((beg (point)) end)
12844 (outline-next-heading)
12845 (setq end (point))
12846 (goto-char beg)
12847 (when (org-list-search-forward
12848 (concat (org-item-beginning-re)
12849 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12850 "\\[[- ]\\]")
12851 end t)
12852 (when (boundp 'org-blocked-by-checkboxes)
12853 (setq org-blocked-by-checkboxes t))
12854 (throw 'dont-block nil))))
12855 t))) ; do not block
12857 (defun org-entry-blocked-p ()
12858 "Non-nil if entry at point is blocked."
12859 (and (not (org-entry-get nil "NOBLOCKING"))
12860 (member (org-entry-get nil "TODO") org-not-done-keywords)
12861 (not (run-hook-with-args-until-failure
12862 'org-blocker-hook
12863 (list :type 'todo-state-change
12864 :position (point)
12865 :from 'todo
12866 :to 'done)))))
12868 (defun org-update-statistics-cookies (all)
12869 "Update the statistics cookie, either from TODO or from checkboxes.
12870 This should be called with the cursor in a line with a statistics
12871 cookie. When called with a \\[universal-argument] prefix, update
12872 all statistics cookies in the buffer."
12873 (interactive "P")
12874 (if all
12875 (progn
12876 (org-update-checkbox-count 'all)
12877 (org-map-entries 'org-update-parent-todo-statistics))
12878 (if (not (org-at-heading-p))
12879 (org-update-checkbox-count)
12880 (let ((pos (point-marker))
12881 end l1 l2)
12882 (ignore-errors (org-back-to-heading t))
12883 (if (not (org-at-heading-p))
12884 (org-update-checkbox-count)
12885 (setq l1 (org-outline-level))
12886 (setq end (save-excursion
12887 (outline-next-heading)
12888 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12889 (point)))
12890 (if (and (save-excursion
12891 (re-search-forward
12892 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12893 (not (save-excursion (re-search-forward
12894 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12895 (org-update-checkbox-count)
12896 (if (and l2 (> l2 l1))
12897 (progn
12898 (goto-char end)
12899 (org-update-parent-todo-statistics))
12900 (goto-char pos)
12901 (beginning-of-line 1)
12902 (while (re-search-forward
12903 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12904 (point-at-eol) t)
12905 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12906 (goto-char pos)
12907 (move-marker pos nil)))))
12909 (defvar org-entry-property-inherited-from) ;; defined below
12910 (defun org-update-parent-todo-statistics ()
12911 "Update any statistics cookie in the parent of the current headline.
12912 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12913 the entire subtree and this will travel up the hierarchy and update
12914 statistics everywhere."
12915 (let* ((prop (save-excursion (org-up-heading-safe)
12916 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12917 (recursive (or (not org-hierarchical-todo-statistics)
12918 (and prop (string-match "\\<recursive\\>" prop))))
12919 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12921 (first t)
12922 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12923 level ltoggle l1 new ndel
12924 (cnt-all 0) (cnt-done 0) is-percent kwd
12925 checkbox-beg cookie-present)
12926 (catch 'exit
12927 (save-excursion
12928 (beginning-of-line 1)
12929 (setq ltoggle (funcall outline-level))
12930 ;; Three situations are to consider:
12932 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12933 ;; to the top-level ancestor on the headline;
12935 ;; 2. If parent has "recursive" property, repeat up to the
12936 ;; headline setting that property, taking inheritance into
12937 ;; account;
12939 ;; 3. Else, move up to direct parent and proceed only once.
12940 (while (and (setq level (org-up-heading-safe))
12941 (or recursive first)
12942 (>= (point) lim))
12943 (setq first nil cookie-present nil)
12944 (unless (and level
12945 (not (string-match
12946 "\\<checkbox\\>"
12947 (downcase (or (org-entry-get nil "COOKIE_DATA")
12948 "")))))
12949 (throw 'exit nil))
12950 (while (re-search-forward box-re (point-at-eol) t)
12951 (setq cnt-all 0 cnt-done 0 cookie-present t)
12952 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12953 (save-match-data
12954 (unless (outline-next-heading) (throw 'exit nil))
12955 (while (and (looking-at org-complex-heading-regexp)
12956 (> (setq l1 (length (match-string 1))) level))
12957 (setq kwd (and (or recursive (= l1 ltoggle))
12958 (match-string 2)))
12959 (if (or (eq org-provide-todo-statistics 'all-headlines)
12960 (and (eq org-provide-todo-statistics t)
12961 (or (member kwd org-done-keywords)))
12962 (and (listp org-provide-todo-statistics)
12963 (stringp (car org-provide-todo-statistics))
12964 (or (member kwd org-provide-todo-statistics)
12965 (member kwd org-done-keywords)))
12966 (and (listp org-provide-todo-statistics)
12967 (listp (car org-provide-todo-statistics))
12968 (or (member kwd (car org-provide-todo-statistics))
12969 (and (member kwd org-done-keywords)
12970 (member kwd (cadr org-provide-todo-statistics))))))
12971 (setq cnt-all (1+ cnt-all))
12972 (and (eq org-provide-todo-statistics t)
12974 (setq cnt-all (1+ cnt-all))))
12975 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12976 (member kwd org-done-keywords))
12977 (and (listp org-provide-todo-statistics)
12978 (listp (car org-provide-todo-statistics))
12979 (member kwd org-done-keywords)
12980 (member kwd (cadr org-provide-todo-statistics)))
12981 (and (listp org-provide-todo-statistics)
12982 (stringp (car org-provide-todo-statistics))
12983 (member kwd org-done-keywords)))
12984 (setq cnt-done (1+ cnt-done)))
12985 (outline-next-heading)))
12986 (setq new
12987 (if is-percent
12988 (format "[%d%%]" (floor (* 100.0 cnt-done)
12989 (max 1 cnt-all)))
12990 (format "[%d/%d]" cnt-done cnt-all))
12991 ndel (- (match-end 0) checkbox-beg))
12992 (goto-char checkbox-beg)
12993 (insert new)
12994 (delete-region (point) (+ (point) ndel))
12995 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12996 (when cookie-present
12997 (run-hook-with-args 'org-after-todo-statistics-hook
12998 cnt-done (- cnt-all cnt-done))))))
12999 (run-hooks 'org-todo-statistics-hook)))
13001 (defvar org-after-todo-statistics-hook nil
13002 "Hook that is called after a TODO statistics cookie has been updated.
13003 Each function is called with two arguments: the number of not-done entries
13004 and the number of done entries.
13006 For example, the following function, when added to this hook, will switch
13007 an entry to DONE when all children are done, and back to TODO when new
13008 entries are set to a TODO status. Note that this hook is only called
13009 when there is a statistics cookie in the headline!
13011 (defun org-summary-todo (n-done n-not-done)
13012 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13013 (let (org-log-done org-log-states) ; turn off logging
13014 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13017 (defvar org-todo-statistics-hook nil
13018 "Hook that is run whenever Org thinks TODO statistics should be updated.
13019 This hook runs even if there is no statistics cookie present, in which case
13020 `org-after-todo-statistics-hook' would not run.")
13022 (defun org-todo-trigger-tag-changes (state)
13023 "Apply the changes defined in `org-todo-state-tags-triggers'."
13024 (let ((l org-todo-state-tags-triggers)
13025 changes)
13026 (when (or (not state) (equal state ""))
13027 (setq changes (append changes (cdr (assoc "" l)))))
13028 (when (and (stringp state) (> (length state) 0))
13029 (setq changes (append changes (cdr (assoc state l)))))
13030 (when (member state org-not-done-keywords)
13031 (setq changes (append changes (cdr (assq 'todo l)))))
13032 (when (member state org-done-keywords)
13033 (setq changes (append changes (cdr (assq 'done l)))))
13034 (dolist (c changes)
13035 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13037 (defun org-local-logging (value)
13038 "Get logging settings from a property VALUE."
13039 ;; Directly set the variables, they are already local.
13040 (setq org-log-done nil
13041 org-log-repeat nil
13042 org-todo-log-states nil)
13043 (dolist (w (org-split-string value))
13044 (let (a)
13045 (cond
13046 ((setq a (assoc w org-startup-options))
13047 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13048 (set (nth 1 a) (nth 2 a))))
13049 ((setq a (org-extract-log-state-settings w))
13050 (and (member (car a) org-todo-keywords-1)
13051 (push a org-todo-log-states)))))))
13053 (defun org-get-todo-sequence-head (kwd)
13054 "Return the head of the TODO sequence to which KWD belongs.
13055 If KWD is not set, check if there is a text property remembering the
13056 right sequence."
13057 (let (p)
13058 (cond
13059 ((not kwd)
13060 (or (get-text-property (point-at-bol) 'org-todo-head)
13061 (progn
13062 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13063 nil (point-at-eol)))
13064 (get-text-property p 'org-todo-head))))
13065 ((not (member kwd org-todo-keywords-1))
13066 (car org-todo-keywords-1))
13067 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13069 (defun org-fast-todo-selection ()
13070 "Fast TODO keyword selection with single keys.
13071 Returns the new TODO keyword, or nil if no state change should occur."
13072 (let* ((fulltable org-todo-key-alist)
13073 (done-keywords org-done-keywords) ;; needed for the faces.
13074 (maxlen (apply 'max (mapcar
13075 (lambda (x)
13076 (if (stringp (car x)) (string-width (car x)) 0))
13077 fulltable)))
13078 (expert nil)
13079 (fwidth (+ maxlen 3 1 3))
13080 (ncol (/ (- (window-width) 4) fwidth))
13081 tg cnt e c tbl
13082 groups ingroup)
13083 (save-excursion
13084 (save-window-excursion
13085 (if expert
13086 (set-buffer (get-buffer-create " *Org todo*"))
13087 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13088 (erase-buffer)
13089 (setq-local org-done-keywords done-keywords)
13090 (setq tbl fulltable cnt 0)
13091 (while (setq e (pop tbl))
13092 (cond
13093 ((equal e '(:startgroup))
13094 (push '() groups) (setq ingroup t)
13095 (unless (= cnt 0)
13096 (setq cnt 0)
13097 (insert "\n"))
13098 (insert "{ "))
13099 ((equal e '(:endgroup))
13100 (setq ingroup nil cnt 0)
13101 (insert "}\n"))
13102 ((equal e '(:newline))
13103 (unless (= cnt 0)
13104 (setq cnt 0)
13105 (insert "\n")
13106 (setq e (car tbl))
13107 (while (equal (car tbl) '(:newline))
13108 (insert "\n")
13109 (setq tbl (cdr tbl)))))
13111 (setq tg (car e) c (cdr e))
13112 (when ingroup (push tg (car groups)))
13113 (setq tg (org-add-props tg nil 'face
13114 (org-get-todo-face tg)))
13115 (when (and (= cnt 0) (not ingroup)) (insert " "))
13116 (insert "[" c "] " tg (make-string
13117 (- fwidth 4 (length tg)) ?\ ))
13118 (when (= (setq cnt (1+ cnt)) ncol)
13119 (insert "\n")
13120 (when ingroup (insert " "))
13121 (setq cnt 0)))))
13122 (insert "\n")
13123 (goto-char (point-min))
13124 (unless expert (org-fit-window-to-buffer))
13125 (message "[a-z..]:Set [SPC]:clear")
13126 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13127 (cond
13128 ((or (= c ?\C-g)
13129 (and (= c ?q) (not (rassoc c fulltable))))
13130 (setq quit-flag t))
13131 ((= c ?\ ) nil)
13132 ((setq e (rassoc c fulltable) tg (car e))
13134 (t (setq quit-flag t)))))))
13136 (defun org-entry-is-todo-p ()
13137 (member (org-get-todo-state) org-not-done-keywords))
13139 (defun org-entry-is-done-p ()
13140 (member (org-get-todo-state) org-done-keywords))
13142 (defun org-get-todo-state ()
13143 "Return the TODO keyword of the current subtree."
13144 (save-excursion
13145 (org-back-to-heading t)
13146 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13147 (match-end 2)
13148 (match-string 2))))
13150 (defun org-at-date-range-p (&optional inactive-ok)
13151 "Non-nil if point is inside a date range.
13153 When optional argument INACTIVE-OK is non-nil, also consider
13154 inactive time ranges.
13156 When this function returns a non-nil value, match data is set
13157 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13158 on INACTIVE-OK."
13159 (interactive)
13160 (save-excursion
13161 (catch 'exit
13162 (let ((pos (point)))
13163 (skip-chars-backward "^[<\r\n")
13164 (skip-chars-backward "<[")
13165 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13166 (>= (match-end 0) pos)
13167 (throw 'exit t))
13168 (skip-chars-backward "^<[\r\n")
13169 (skip-chars-backward "<[")
13170 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13171 (>= (match-end 0) pos)
13172 (throw 'exit t)))
13173 nil)))
13175 (defun org-get-repeat (&optional tagline)
13176 "Check if there is a deadline/schedule with repeater in this entry."
13177 (save-match-data
13178 (save-excursion
13179 (org-back-to-heading t)
13180 (and (re-search-forward (if tagline
13181 (concat tagline "\\s-*" org-repeat-re)
13182 org-repeat-re)
13183 (org-entry-end-position) t)
13184 (match-string-no-properties 1)))))
13186 (defvar org-last-changed-timestamp)
13187 (defvar org-last-inserted-timestamp)
13188 (defvar org-log-post-message)
13189 (defvar org-log-note-purpose)
13190 (defvar org-log-note-how nil)
13191 (defvar org-log-note-extra)
13192 (defun org-auto-repeat-maybe (done-word)
13193 "Check if the current headline contains a repeated time-stamp.
13195 If yes, set TODO state back to what it was and change the base date
13196 of repeating deadline/scheduled time stamps to new date.
13198 This function is run automatically after each state change to a DONE state."
13199 (let* ((repeat (org-get-repeat))
13200 (aa (assoc org-last-state org-todo-kwd-alist))
13201 (interpret (nth 1 aa))
13202 (head (nth 2 aa))
13203 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13204 (msg "Entry repeats: ")
13205 (org-log-done nil)
13206 (org-todo-log-states nil))
13207 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13208 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13209 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13210 org-todo-repeat-to-state)))
13211 (unless (and to-state (member to-state org-todo-keywords-1))
13212 (setq to-state (if (eq interpret 'type) org-last-state head)))
13213 (org-todo to-state))
13214 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13215 (org-entry-put nil "LAST_REPEAT" (format-time-string
13216 (org-time-stamp-format t t))))
13217 (when org-log-repeat
13218 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13219 (memq 'org-add-log-note post-command-hook))
13220 ;; We are already setup for some record.
13221 (when (eq org-log-repeat 'note)
13222 ;; Make sure we take a note, not only a time stamp.
13223 (setq org-log-note-how 'note))
13224 ;; Set up for taking a record.
13225 (org-add-log-setup 'state
13226 (or done-word (car org-done-keywords))
13227 org-last-state
13228 org-log-repeat)))
13229 (org-back-to-heading t)
13230 (org-add-planning-info nil nil 'closed)
13231 (let ((end (save-excursion (outline-next-heading) (point)))
13232 (planning-re (regexp-opt
13233 (list org-scheduled-string org-deadline-string))))
13234 (while (re-search-forward org-ts-regexp end t)
13235 (let* ((ts (match-string 0))
13236 (planning? (org-at-planning-p))
13237 (type (if (not planning?) "Plain:"
13238 (save-excursion
13239 (re-search-backward
13240 planning-re (line-beginning-position) t)
13241 (match-string 0)))))
13242 (cond
13243 ;; Ignore fake time-stamps (e.g., within comments).
13244 ((and (not planning?)
13245 (not (org-at-property-p))
13246 (not (eq 'timestamp
13247 (org-element-type (save-excursion
13248 (backward-char)
13249 (org-element-context)))))))
13250 ;; Time-stamps without a repeater are usually skipped.
13251 ;; However, a SCHEDULED time-stamp without one is
13252 ;; removed, as it is considered as no longer relevant.
13253 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13254 (when (equal type org-scheduled-string)
13255 (org-remove-timestamp-with-keyword type)))
13257 (let ((n (string-to-number (match-string 2 ts)))
13258 (what (match-string 3 ts)))
13259 (when (equal what "w") (setq n (* n 7) what "d"))
13260 (when (and (equal what "h")
13261 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13262 ts)))
13263 (user-error
13264 "Cannot repeat in Repeat in %d hour(s) because no hour \
13265 has been set"
13267 ;; Preparation, see if we need to modify the start
13268 ;; date for the change.
13269 (when (match-end 1)
13270 (let ((time (save-match-data (org-time-string-to-time ts))))
13271 (cond
13272 ((equal (match-string 1 ts) ".")
13273 ;; Shift starting date to today
13274 (org-timestamp-change
13275 (- (org-today) (time-to-days time))
13276 'day))
13277 ((equal (match-string 1 ts) "+")
13278 (let ((nshiftmax 10)
13279 (nshift 0))
13280 (while (or (= nshift 0)
13281 (not (time-less-p (current-time) time)))
13282 (when (= (cl-incf nshift) nshiftmax)
13283 (or (y-or-n-p
13284 (format "%d repeater intervals were not \
13285 enough to shift date past today. Continue? "
13286 nshift))
13287 (user-error "Abort")))
13288 (org-timestamp-change n (cdr (assoc what whata)))
13289 (org-at-timestamp-p t)
13290 (setq ts (match-string 1))
13291 (setq time
13292 (save-match-data
13293 (org-time-string-to-time ts)))))
13294 (org-timestamp-change (- n) (cdr (assoc what whata)))
13295 ;; Rematch, so that we have everything in place
13296 ;; for the real shift.
13297 (org-at-timestamp-p t)
13298 (setq ts (match-string 1))
13299 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13300 ts)))))
13301 (save-excursion
13302 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13303 (setq msg
13304 (concat
13305 msg type " " org-last-changed-timestamp " "))))))))
13306 (setq org-log-post-message msg)
13307 (message "%s" msg))))
13309 (defun org-show-todo-tree (arg)
13310 "Make a compact tree which shows all headlines marked with TODO.
13311 The tree will show the lines where the regexp matches, and all higher
13312 headlines above the match.
13313 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13314 With a numeric prefix N, construct a sparse tree for the Nth element
13315 of `org-todo-keywords-1'."
13316 (interactive "P")
13317 (let ((case-fold-search nil)
13318 (kwd-re
13319 (cond ((null arg) org-not-done-regexp)
13320 ((equal arg '(4))
13321 (let ((kwd
13322 (completing-read "Keyword (or KWD1|KWD2|...): "
13323 (mapcar #'list org-todo-keywords-1))))
13324 (concat "\\("
13325 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13326 "\\)\\>")))
13327 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13328 (regexp-quote (nth (1- (prefix-numeric-value arg))
13329 org-todo-keywords-1)))
13330 (t (user-error "Invalid prefix argument: %s" arg)))))
13331 (message "%d TODO entries found"
13332 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13334 (defun org-deadline (arg &optional time)
13335 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13336 With one universal prefix argument, remove any deadline from the item.
13337 With two universal prefix arguments, prompt for a warning delay.
13338 With argument TIME, set the deadline at the corresponding date. TIME
13339 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13340 (interactive "P")
13341 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13342 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13343 'region-start-level 'region))
13344 org-loop-over-headlines-in-active-region)
13345 (org-map-entries
13346 `(org-deadline ',arg ,time)
13347 org-loop-over-headlines-in-active-region
13348 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13349 (let* ((old-date (org-entry-get nil "DEADLINE"))
13350 (old-date-time (when old-date (org-time-string-to-time old-date)))
13351 (repeater (and old-date
13352 (string-match
13353 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13354 old-date)
13355 (match-string 1 old-date))))
13356 (cond
13357 ((equal arg '(4))
13358 (when (and old-date org-log-redeadline)
13359 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13360 (org-remove-timestamp-with-keyword org-deadline-string)
13361 (message "Item no longer has a deadline."))
13362 ((equal arg '(16))
13363 (save-excursion
13364 (org-back-to-heading t)
13365 (if (re-search-forward
13366 org-deadline-time-regexp
13367 (save-excursion (outline-next-heading) (point)) t)
13368 (let* ((rpl0 (match-string 1))
13369 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13370 (replace-match
13371 (concat org-deadline-string
13372 " <" rpl
13373 (format " -%dd"
13374 (abs
13375 (- (time-to-days
13376 (save-match-data
13377 (org-read-date nil t nil "Warn starting from" old-date-time)))
13378 (time-to-days old-date-time))))
13379 ">") t t))
13380 (user-error "No deadline information to update"))))
13382 (org-add-planning-info 'deadline time 'closed)
13383 (when (and old-date
13384 org-log-redeadline
13385 (not (equal old-date org-last-inserted-timestamp)))
13386 (org-add-log-setup
13387 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13388 (when repeater
13389 (save-excursion
13390 (org-back-to-heading t)
13391 (when (re-search-forward (concat org-deadline-string " "
13392 org-last-inserted-timestamp)
13393 (save-excursion
13394 (outline-next-heading) (point)) t)
13395 (goto-char (1- (match-end 0)))
13396 (insert " " repeater)
13397 (setq org-last-inserted-timestamp
13398 (concat (substring org-last-inserted-timestamp 0 -1)
13399 " " repeater
13400 (substring org-last-inserted-timestamp -1))))))
13401 (message "Deadline on %s" org-last-inserted-timestamp))))))
13403 (defun org-schedule (arg &optional time)
13404 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13405 With one universal prefix argument, remove any scheduling date from the item.
13406 With two universal prefix arguments, prompt for a delay cookie.
13407 With argument TIME, scheduled at the corresponding date. TIME can
13408 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13409 (interactive "P")
13410 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13411 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13412 'region-start-level 'region))
13413 org-loop-over-headlines-in-active-region)
13414 (org-map-entries
13415 `(org-schedule ',arg ,time)
13416 org-loop-over-headlines-in-active-region
13417 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13418 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13419 (old-date-time (when old-date (org-time-string-to-time old-date)))
13420 (repeater (and old-date
13421 (string-match
13422 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13423 old-date)
13424 (match-string 1 old-date))))
13425 (cond
13426 ((equal arg '(4))
13427 (progn
13428 (when (and old-date org-log-reschedule)
13429 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13430 (org-remove-timestamp-with-keyword org-scheduled-string)
13431 (message "Item is no longer scheduled.")))
13432 ((equal arg '(16))
13433 (save-excursion
13434 (org-back-to-heading t)
13435 (if (re-search-forward
13436 org-scheduled-time-regexp
13437 (save-excursion (outline-next-heading) (point)) t)
13438 (let* ((rpl0 (match-string 1))
13439 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13440 (replace-match
13441 (concat org-scheduled-string
13442 " <" rpl
13443 (format " -%dd"
13444 (abs
13445 (- (time-to-days
13446 (save-match-data
13447 (org-read-date nil t nil "Delay until" old-date-time)))
13448 (time-to-days old-date-time))))
13449 ">") t t))
13450 (user-error "No scheduled information to update"))))
13452 (org-add-planning-info 'scheduled time 'closed)
13453 (when (and old-date
13454 org-log-reschedule
13455 (not (equal old-date org-last-inserted-timestamp)))
13456 (org-add-log-setup
13457 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13458 (when repeater
13459 (save-excursion
13460 (org-back-to-heading t)
13461 (when (re-search-forward (concat org-scheduled-string " "
13462 org-last-inserted-timestamp)
13463 (save-excursion
13464 (outline-next-heading) (point)) t)
13465 (goto-char (1- (match-end 0)))
13466 (insert " " repeater)
13467 (setq org-last-inserted-timestamp
13468 (concat (substring org-last-inserted-timestamp 0 -1)
13469 " " repeater
13470 (substring org-last-inserted-timestamp -1))))))
13471 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13473 (defun org-get-scheduled-time (pom &optional inherit)
13474 "Get the scheduled time as a time tuple, of a format suitable
13475 for calling org-schedule with, or if there is no scheduling,
13476 returns nil."
13477 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13478 (when time
13479 (apply 'encode-time (org-parse-time-string time)))))
13481 (defun org-get-deadline-time (pom &optional inherit)
13482 "Get the deadline as a time tuple, of a format suitable for
13483 calling org-deadline with, or if there is no scheduling, returns
13484 nil."
13485 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13486 (when time
13487 (apply 'encode-time (org-parse-time-string time)))))
13489 (defun org-remove-timestamp-with-keyword (keyword)
13490 "Remove all time stamps with KEYWORD in the current entry."
13491 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13492 beg)
13493 (save-excursion
13494 (org-back-to-heading t)
13495 (setq beg (point))
13496 (outline-next-heading)
13497 (while (re-search-backward re beg t)
13498 (replace-match "")
13499 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13500 (equal (char-before) ?\ ))
13501 (backward-delete-char 1)
13502 (when (string-match "^[ \t]*$" (buffer-substring
13503 (point-at-bol) (point-at-eol)))
13504 (delete-region (point-at-bol)
13505 (min (point-max) (1+ (point-at-eol))))))))))
13507 (defvar org-time-was-given) ; dynamically scoped parameter
13508 (defvar org-end-time-was-given) ; dynamically scoped parameter
13510 (defun org-at-planning-p ()
13511 "Non-nil when point is on a planning info line."
13512 ;; This is as accurate and faster than `org-element-at-point' since
13513 ;; planning info location is fixed in the section.
13514 (org-with-wide-buffer
13515 (beginning-of-line)
13516 (and (looking-at-p org-planning-line-re)
13517 (eq (point)
13518 (ignore-errors
13519 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13520 (org-back-to-heading t)
13521 (org-with-limited-levels (org-back-to-heading t)))
13522 (line-beginning-position 2))))))
13524 (defun org-add-planning-info (what &optional time &rest remove)
13525 "Insert new timestamp with keyword in the planning line.
13526 WHAT indicates what kind of time stamp to add. It is a symbol
13527 among `closed', `deadline', `scheduled' and nil. TIME indicates
13528 the time to use. If none is given, the user is prompted for
13529 a date. REMOVE indicates what kind of entries to remove. An old
13530 WHAT entry will also be removed."
13531 (let (org-time-was-given org-end-time-was-given default-time default-input)
13532 (catch 'exit
13533 (when (and (memq what '(scheduled deadline))
13534 (or (not time)
13535 (and (stringp time)
13536 (string-match "^[-+]+[0-9]" time))))
13537 ;; Try to get a default date/time from existing timestamp
13538 (save-excursion
13539 (org-back-to-heading t)
13540 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13541 (when (re-search-forward (if (eq what 'scheduled)
13542 org-scheduled-time-regexp
13543 org-deadline-time-regexp)
13544 end t)
13545 (setq ts (match-string 1)
13546 default-time (apply 'encode-time (org-parse-time-string ts))
13547 default-input (and ts (org-get-compact-tod ts)))))))
13548 (when what
13549 (setq time
13550 (if (stringp time)
13551 ;; This is a string (relative or absolute), set
13552 ;; proper date.
13553 (apply #'encode-time
13554 (org-read-date-analyze
13555 time default-time (decode-time default-time)))
13556 ;; If necessary, get the time from the user
13557 (or time (org-read-date nil 'to-time nil nil
13558 default-time default-input)))))
13560 (org-with-wide-buffer
13561 (org-back-to-heading t)
13562 (forward-line)
13563 (unless (bolp) (insert "\n"))
13564 (cond ((looking-at-p org-planning-line-re)
13565 ;; Move to current indentation.
13566 (skip-chars-forward " \t")
13567 ;; Check if we have to remove something.
13568 (dolist (type (if what (cons what remove) remove))
13569 (save-excursion
13570 (when (re-search-forward
13571 (cl-case type
13572 (closed org-closed-time-regexp)
13573 (deadline org-deadline-time-regexp)
13574 (scheduled org-scheduled-time-regexp)
13575 (otherwise
13576 (error "Invalid planning type: %s" type)))
13577 (line-end-position) t)
13578 ;; Delete until next keyword or end of line.
13579 (delete-region
13580 (match-beginning 0)
13581 (if (re-search-forward org-keyword-time-not-clock-regexp
13582 (line-end-position)
13584 (match-beginning 0)
13585 (line-end-position))))))
13586 ;; If there is nothing more to add and no more keyword
13587 ;; is left, remove the line completely.
13588 (if (and (looking-at-p "[ \t]*$") (not what))
13589 (delete-region (line-beginning-position)
13590 (line-beginning-position 2))
13591 ;; If we removed last keyword, do not leave trailing
13592 ;; white space at the end of line.
13593 (let ((p (point)))
13594 (save-excursion
13595 (end-of-line)
13596 (unless (= (skip-chars-backward " \t" p) 0)
13597 (delete-region (point) (line-end-position)))))))
13598 ((not what) (throw 'exit nil)) ; Nothing to do.
13599 (t (insert-before-markers "\n")
13600 (backward-char 1)
13601 (when org-adapt-indentation
13602 (indent-to-column (1+ (org-outline-level))))))
13603 (when what
13604 ;; Insert planning keyword.
13605 (insert (cl-case what
13606 (closed org-closed-string)
13607 (deadline org-deadline-string)
13608 (scheduled org-scheduled-string)
13609 (otherwise (error "Invalid planning type: %s" what)))
13610 " ")
13611 ;; Insert associated timestamp.
13612 (let ((ts (org-insert-time-stamp
13613 time
13614 (or org-time-was-given
13615 (and (eq what 'closed) org-log-done-with-time))
13616 (eq what 'closed)
13617 nil nil (list org-end-time-was-given))))
13618 (unless (eolp) (insert " "))
13619 ts))))))
13621 (defvar org-log-note-marker (make-marker)
13622 "Marker pointing at the entry where the note is to be inserted.")
13623 (defvar org-log-note-purpose nil)
13624 (defvar org-log-note-state nil)
13625 (defvar org-log-note-previous-state nil)
13626 (defvar org-log-note-extra nil)
13627 (defvar org-log-note-window-configuration nil)
13628 (defvar org-log-note-return-to (make-marker))
13629 (defvar org-log-note-effective-time nil
13630 "Remembered current time so that dynamically scoped
13631 `org-extend-today-until' affects timestamps in state change log")
13633 (defvar org-log-post-message nil
13634 "Message to be displayed after a log note has been stored.
13635 The auto-repeater uses this.")
13637 (defun org-add-note ()
13638 "Add a note to the current entry.
13639 This is done in the same way as adding a state change note."
13640 (interactive)
13641 (org-add-log-setup 'note))
13643 (defun org-log-beginning (&optional create)
13644 "Return expected start of log notes in current entry.
13645 When optional argument CREATE is non-nil, the function creates
13646 a drawer to store notes, if necessary. Returned position ignores
13647 narrowing."
13648 (org-with-wide-buffer
13649 (let ((drawer (org-log-into-drawer)))
13650 (cond
13651 (drawer
13652 (org-end-of-meta-data)
13653 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13654 (end (if (org-at-heading-p) (point)
13655 (save-excursion (outline-next-heading) (point))))
13656 (case-fold-search t))
13657 (catch 'exit
13658 ;; Try to find existing drawer.
13659 (while (re-search-forward regexp end t)
13660 (let ((element (org-element-at-point)))
13661 (when (eq (org-element-type element) 'drawer)
13662 (let ((cend (org-element-property :contents-end element)))
13663 (when (and (not org-log-states-order-reversed) cend)
13664 (goto-char cend)))
13665 (throw 'exit nil))))
13666 ;; No drawer found. Create one, if permitted.
13667 (when create
13668 (unless (bolp) (insert "\n"))
13669 (let ((beg (point)))
13670 (insert ":" drawer ":\n:END:\n")
13671 (org-indent-region beg (point)))
13672 (end-of-line -1)))))
13674 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13675 (skip-chars-forward " \t\n")
13676 (beginning-of-line)
13677 (unless org-log-states-order-reversed
13678 (org-skip-over-state-notes)
13679 (skip-chars-backward " \t\n")
13680 (forward-line)))))
13681 (if (bolp) (point) (line-beginning-position 2))))
13683 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13684 "Set up the post command hook to take a note.
13685 If this is about to TODO state change, the new state is expected in STATE.
13686 HOW is an indicator what kind of note should be created.
13687 EXTRA is additional text that will be inserted into the notes buffer."
13688 (move-marker org-log-note-marker (point))
13689 (setq org-log-note-purpose purpose
13690 org-log-note-state state
13691 org-log-note-previous-state prev-state
13692 org-log-note-how how
13693 org-log-note-extra extra
13694 org-log-note-effective-time (org-current-effective-time))
13695 (add-hook 'post-command-hook 'org-add-log-note 'append))
13697 (defun org-skip-over-state-notes ()
13698 "Skip past the list of State notes in an entry."
13699 (when (ignore-errors (goto-char (org-in-item-p)))
13700 (let* ((struct (org-list-struct))
13701 (prevs (org-list-prevs-alist struct))
13702 (regexp
13703 (concat "[ \t]*- +"
13704 (replace-regexp-in-string
13705 " +" " +"
13706 (org-replace-escapes
13707 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13708 `(("%d" . ,org-ts-regexp-inactive)
13709 ("%D" . ,org-ts-regexp)
13710 ("%s" . "\"\\S-+\"")
13711 ("%S" . "\"\\S-+\"")
13712 ("%t" . ,org-ts-regexp-inactive)
13713 ("%T" . ,org-ts-regexp)
13714 ("%u" . ".*?")
13715 ("%U" . ".*?")))))))
13716 (while (looking-at-p regexp)
13717 (goto-char (or (org-list-get-next-item (point) struct prevs)
13718 (org-list-get-item-end (point) struct)))))))
13720 (defun org-add-log-note (&optional _purpose)
13721 "Pop up a window for taking a note, and add this note later."
13722 (remove-hook 'post-command-hook 'org-add-log-note)
13723 (setq org-log-note-window-configuration (current-window-configuration))
13724 (delete-other-windows)
13725 (move-marker org-log-note-return-to (point))
13726 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13727 (goto-char org-log-note-marker)
13728 (org-switch-to-buffer-other-window "*Org Note*")
13729 (erase-buffer)
13730 (if (memq org-log-note-how '(time state))
13731 (let (current-prefix-arg) (org-store-log-note))
13732 (let ((org-inhibit-startup t)) (org-mode))
13733 (insert (format "# Insert note for %s.
13734 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13735 (cond
13736 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13737 ((eq org-log-note-purpose 'done) "closed todo item")
13738 ((eq org-log-note-purpose 'state)
13739 (format "state change from \"%s\" to \"%s\""
13740 (or org-log-note-previous-state "")
13741 (or org-log-note-state "")))
13742 ((eq org-log-note-purpose 'reschedule)
13743 "rescheduling")
13744 ((eq org-log-note-purpose 'delschedule)
13745 "no longer scheduled")
13746 ((eq org-log-note-purpose 'redeadline)
13747 "changing deadline")
13748 ((eq org-log-note-purpose 'deldeadline)
13749 "removing deadline")
13750 ((eq org-log-note-purpose 'refile)
13751 "refiling")
13752 ((eq org-log-note-purpose 'note)
13753 "this entry")
13754 (t (error "This should not happen")))))
13755 (when org-log-note-extra (insert org-log-note-extra))
13756 (setq-local org-finish-function 'org-store-log-note)
13757 (run-hooks 'org-log-buffer-setup-hook)))
13759 (defvar org-note-abort nil) ; dynamically scoped
13760 (defun org-store-log-note ()
13761 "Finish taking a log note, and insert it to where it belongs."
13762 (let ((txt (prog1 (buffer-string)
13763 (kill-buffer)))
13764 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13765 lines)
13766 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13767 (setq txt (replace-match "" t t txt)))
13768 (when (string-match "\\s-+\\'" txt)
13769 (setq txt (replace-match "" t t txt)))
13770 (setq lines (org-split-string txt "\n"))
13771 (when (org-string-nw-p note)
13772 (setq note
13773 (org-replace-escapes
13774 note
13775 (list (cons "%u" (user-login-name))
13776 (cons "%U" user-full-name)
13777 (cons "%t" (format-time-string
13778 (org-time-stamp-format 'long 'inactive)
13779 org-log-note-effective-time))
13780 (cons "%T" (format-time-string
13781 (org-time-stamp-format 'long nil)
13782 org-log-note-effective-time))
13783 (cons "%d" (format-time-string
13784 (org-time-stamp-format nil 'inactive)
13785 org-log-note-effective-time))
13786 (cons "%D" (format-time-string
13787 (org-time-stamp-format nil nil)
13788 org-log-note-effective-time))
13789 (cons "%s" (cond
13790 ((not org-log-note-state) "")
13791 ((string-match-p org-ts-regexp
13792 org-log-note-state)
13793 (format "\"[%s]\""
13794 (substring org-log-note-state 1 -1)))
13795 (t (format "\"%s\"" org-log-note-state))))
13796 (cons "%S"
13797 (cond
13798 ((not org-log-note-previous-state) "")
13799 ((string-match-p org-ts-regexp
13800 org-log-note-previous-state)
13801 (format "\"[%s]\""
13802 (substring
13803 org-log-note-previous-state 1 -1)))
13804 (t (format "\"%s\""
13805 org-log-note-previous-state)))))))
13806 (when lines (setq note (concat note " \\\\")))
13807 (push note lines))
13808 (when (and lines (not (or current-prefix-arg org-note-abort)))
13809 (with-current-buffer (marker-buffer org-log-note-marker)
13810 (org-with-wide-buffer
13811 ;; Find location for the new note.
13812 (goto-char org-log-note-marker)
13813 (set-marker org-log-note-marker nil)
13814 (goto-char (org-log-beginning t))
13815 ;; Make sure point is at the beginning of an empty line.
13816 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13817 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13818 ;; In an existing list, add a new item at the top level.
13819 ;; Otherwise, indent line like a regular one.
13820 (let ((itemp (org-in-item-p)))
13821 (if itemp
13822 (indent-line-to
13823 (let ((struct (save-excursion
13824 (goto-char itemp) (org-list-struct))))
13825 (org-list-get-ind (org-list-get-top-point struct) struct)))
13826 (org-indent-line)))
13827 (insert (org-list-bullet-string "-") (pop lines))
13828 (let ((ind (org-list-item-body-column (line-beginning-position))))
13829 (dolist (line lines)
13830 (insert "\n")
13831 (indent-line-to ind)
13832 (insert line)))
13833 (message "Note stored")
13834 (org-back-to-heading t)
13835 (org-cycle-hide-drawers 'children))
13836 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13837 ;; from within `org-add-log-note' because `buffer-undo-list'
13838 ;; is then modified outside of `org-with-remote-undo'.
13839 (when (eq this-command 'org-agenda-todo)
13840 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13841 ;; Don't add undo information when called from `org-agenda-todo'.
13842 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13843 (set-window-configuration org-log-note-window-configuration)
13844 (with-current-buffer (marker-buffer org-log-note-return-to)
13845 (goto-char org-log-note-return-to))
13846 (move-marker org-log-note-return-to nil)
13847 (when org-log-post-message (message "%s" org-log-post-message))))
13849 (defun org-remove-empty-drawer-at (pos)
13850 "Remove an empty drawer at position POS.
13851 POS may also be a marker."
13852 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13853 (org-with-wide-buffer
13854 (goto-char pos)
13855 (let ((drawer (org-element-at-point)))
13856 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13857 (not (org-element-property :contents-begin drawer)))
13858 (delete-region (org-element-property :begin drawer)
13859 (progn (goto-char (org-element-property :end drawer))
13860 (skip-chars-backward " \r\t\n")
13861 (forward-line)
13862 (point))))))))
13864 (defvar org-ts-type nil)
13865 (defun org-sparse-tree (&optional arg type)
13866 "Create a sparse tree, prompt for the details.
13867 This command can create sparse trees. You first need to select the type
13868 of match used to create the tree:
13870 t Show all TODO entries.
13871 T Show entries with a specific TODO keyword.
13872 m Show entries selected by a tags/property match.
13873 p Enter a property name and its value (both with completion on existing
13874 names/values) and show entries with that property.
13875 r Show entries matching a regular expression (`/' can be used as well).
13876 b Show deadlines and scheduled items before a date.
13877 a Show deadlines and scheduled items after a date.
13878 d Show deadlines due within `org-deadline-warning-days'.
13879 D Show deadlines and scheduled items between a date range."
13880 (interactive "P")
13881 (setq type (or type org-sparse-tree-default-date-type))
13882 (setq org-ts-type type)
13883 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13884 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13885 \[c]ycle through date types: %s"
13886 (cl-case type
13887 (all "all timestamps")
13888 (scheduled "only scheduled")
13889 (deadline "only deadline")
13890 (active "only active timestamps")
13891 (inactive "only inactive timestamps")
13892 (closed "with a closed time-stamp")
13893 (otherwise "scheduled/deadline")))
13894 (let ((answer (read-char-exclusive)))
13895 (cl-case answer
13897 (org-sparse-tree
13899 (cadr
13900 (memq type '(nil all scheduled deadline active inactive closed)))))
13901 (?d (call-interactively 'org-check-deadlines))
13902 (?b (call-interactively 'org-check-before-date))
13903 (?a (call-interactively 'org-check-after-date))
13904 (?D (call-interactively 'org-check-dates-range))
13905 (?t (call-interactively 'org-show-todo-tree))
13906 (?T (org-show-todo-tree '(4)))
13907 (?m (call-interactively 'org-match-sparse-tree))
13908 ((?p ?P)
13909 (let* ((kwd (completing-read
13910 "Property: " (mapcar #'list (org-buffer-property-keys))))
13911 (value (completing-read
13912 "Value: " (mapcar #'list (org-property-values kwd)))))
13913 (unless (string-match "\\`{.*}\\'" value)
13914 (setq value (concat "\"" value "\"")))
13915 (org-match-sparse-tree arg (concat kwd "=" value))))
13916 ((?r ?R ?/) (call-interactively 'org-occur))
13917 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13919 (defvar-local org-occur-highlights nil
13920 "List of overlays used for occur matches.")
13921 (defvar-local org-occur-parameters nil
13922 "Parameters of the active org-occur calls.
13923 This is a list, each call to org-occur pushes as cons cell,
13924 containing the regular expression and the callback, onto the list.
13925 The list can contain several entries if `org-occur' has been called
13926 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13927 will only contain one set of parameters. When the highlights are
13928 removed (for example with `C-c C-c', or with the next edit (depending
13929 on `org-remove-highlights-with-change'), this variable is emptied
13930 as well.")
13932 (defun org-occur (regexp &optional keep-previous callback)
13933 "Make a compact tree which shows all matches of REGEXP.
13935 The tree will show the lines where the regexp matches, and any other context
13936 defined in `org-show-context-detail', which see.
13938 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13939 done by a previous call to `org-occur' will be kept, to allow stacking of
13940 calls to this command.
13942 Optional argument CALLBACK can be a function of no argument. In this case,
13943 it is called with point at the end of the match, match data being set
13944 accordingly. Current match is shown only if the return value is non-nil.
13945 The function must neither move point nor alter narrowing."
13946 (interactive "sRegexp: \nP")
13947 (when (equal regexp "")
13948 (user-error "Regexp cannot be empty"))
13949 (unless keep-previous
13950 (org-remove-occur-highlights nil nil t))
13951 (push (cons regexp callback) org-occur-parameters)
13952 (let ((cnt 0))
13953 (save-excursion
13954 (goto-char (point-min))
13955 (when (or (not keep-previous) ; do not want to keep
13956 (not org-occur-highlights)) ; no previous matches
13957 ;; hide everything
13958 (org-overview))
13959 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13960 (isearch-no-upper-case-p regexp t)
13961 org-occur-case-fold-search)))
13962 (while (re-search-forward regexp nil t)
13963 (when (or (not callback)
13964 (save-match-data (funcall callback)))
13965 (setq cnt (1+ cnt))
13966 (when org-highlight-sparse-tree-matches
13967 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13968 (org-show-context 'occur-tree)))))
13969 (when org-remove-highlights-with-change
13970 (add-hook 'before-change-functions 'org-remove-occur-highlights
13971 nil 'local))
13972 (unless org-sparse-tree-open-archived-trees
13973 (org-hide-archived-subtrees (point-min) (point-max)))
13974 (run-hooks 'org-occur-hook)
13975 (when (called-interactively-p 'interactive)
13976 (message "%d match(es) for regexp %s" cnt regexp))
13977 cnt))
13979 (defun org-occur-next-match (&optional n _reset)
13980 "Function for `next-error-function' to find sparse tree matches.
13981 N is the number of matches to move, when negative move backwards.
13982 This function always goes back to the starting point when no
13983 match is found."
13984 (let* ((limit (if (< n 0) (point-min) (point-max)))
13985 (search-func (if (< n 0)
13986 'previous-single-char-property-change
13987 'next-single-char-property-change))
13988 (n (abs n))
13989 (pos (point))
13991 (catch 'exit
13992 (while (setq p1 (funcall search-func (point) 'org-type))
13993 (when (equal p1 limit)
13994 (goto-char pos)
13995 (user-error "No more matches"))
13996 (when (equal (get-char-property p1 'org-type) 'org-occur)
13997 (setq n (1- n))
13998 (when (= n 0)
13999 (goto-char p1)
14000 (throw 'exit (point))))
14001 (goto-char p1))
14002 (goto-char p1)
14003 (user-error "No more matches"))))
14005 (defun org-show-context (&optional key)
14006 "Make sure point and context are visible.
14007 Optional argument KEY, when non-nil, is a symbol. See
14008 `org-show-context-detail' for allowed values and how much is to
14009 be shown."
14010 (org-show-set-visibility
14011 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14012 ((cdr (assq key org-show-context-detail)))
14013 (t (cdr (assq 'default org-show-context-detail))))))
14015 (defun org-show-set-visibility (detail)
14016 "Set visibility around point according to DETAIL.
14017 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14018 `tree', `canonical' or t. See `org-show-context-detail' for more
14019 information."
14020 ;; Show current heading and possibly its entry, following headline
14021 ;; or all children.
14022 (if (and (org-at-heading-p) (not (eq detail 'local)))
14023 (org-flag-heading nil)
14024 (org-show-entry)
14025 ;; If point is hidden within a drawer or a block, make sure to
14026 ;; expose it.
14027 (dolist (o (overlays-at (point)))
14028 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14029 (delete-overlay o)))
14030 (unless (org-before-first-heading-p)
14031 (org-with-limited-levels
14032 (cl-case detail
14033 ((tree canonical t) (org-show-children))
14034 ((nil minimal ancestors))
14035 (t (save-excursion
14036 (outline-next-heading)
14037 (org-flag-heading nil)))))))
14038 ;; Show all siblings.
14039 (when (eq detail 'lineage) (org-show-siblings))
14040 ;; Show ancestors, possibly with their children.
14041 (when (memq detail '(ancestors lineage tree canonical t))
14042 (save-excursion
14043 (while (org-up-heading-safe)
14044 (org-flag-heading nil)
14045 (when (memq detail '(canonical t)) (org-show-entry))
14046 (when (memq detail '(tree canonical t)) (org-show-children))))))
14048 (defvar org-reveal-start-hook nil
14049 "Hook run before revealing a location.")
14051 (defun org-reveal (&optional siblings)
14052 "Show current entry, hierarchy above it, and the following headline.
14054 This can be used to show a consistent set of context around
14055 locations exposed with `org-show-context'.
14057 With optional argument SIBLINGS, on each level of the hierarchy all
14058 siblings are shown. This repairs the tree structure to what it would
14059 look like when opened with hierarchical calls to `org-cycle'.
14061 With a \\[universal-argument] \\[universal-argument] prefix, \
14062 go to the parent and show the entire tree."
14063 (interactive "P")
14064 (run-hooks 'org-reveal-start-hook)
14065 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14066 ((equal siblings '(16))
14067 (save-excursion
14068 (when (org-up-heading-safe)
14069 (org-show-subtree)
14070 (run-hook-with-args 'org-cycle-hook 'subtree))))
14071 (t (org-show-set-visibility 'lineage))))
14073 (defun org-highlight-new-match (beg end)
14074 "Highlight from BEG to END and mark the highlight is an occur headline."
14075 (let ((ov (make-overlay beg end)))
14076 (overlay-put ov 'face 'secondary-selection)
14077 (overlay-put ov 'org-type 'org-occur)
14078 (push ov org-occur-highlights)))
14080 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14081 "Remove the occur highlights from the buffer.
14082 BEG and END are ignored. If NOREMOVE is nil, remove this function
14083 from the `before-change-functions' in the current buffer."
14084 (interactive)
14085 (unless org-inhibit-highlight-removal
14086 (mapc #'delete-overlay org-occur-highlights)
14087 (setq org-occur-highlights nil)
14088 (setq org-occur-parameters nil)
14089 (unless noremove
14090 (remove-hook 'before-change-functions
14091 'org-remove-occur-highlights 'local))))
14093 ;;;; Priorities
14095 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14096 "Regular expression matching the priority indicator.")
14098 (defvar org-remove-priority-next-time nil)
14100 (defun org-priority-up ()
14101 "Increase the priority of the current item."
14102 (interactive)
14103 (org-priority 'up))
14105 (defun org-priority-down ()
14106 "Decrease the priority of the current item."
14107 (interactive)
14108 (org-priority 'down))
14110 (defun org-priority (&optional action _show)
14111 "Change the priority of an item.
14112 ACTION can be `set', `up', `down', or a character."
14113 (interactive "P")
14114 (if (equal action '(4))
14115 (org-show-priority)
14116 (unless org-enable-priority-commands
14117 (user-error "Priority commands are disabled"))
14118 (setq action (or action 'set))
14119 (let (current new news have remove)
14120 (save-excursion
14121 (org-back-to-heading t)
14122 (when (looking-at org-priority-regexp)
14123 (setq current (string-to-char (match-string 2))
14124 have t))
14125 (cond
14126 ((eq action 'remove)
14127 (setq remove t new ?\ ))
14128 ((or (eq action 'set)
14129 (integerp action))
14130 (if (not (eq action 'set))
14131 (setq new action)
14132 (message "Priority %c-%c, SPC to remove: "
14133 org-highest-priority org-lowest-priority)
14134 (save-match-data
14135 (setq new (read-char-exclusive))))
14136 (when (and (= (upcase org-highest-priority) org-highest-priority)
14137 (= (upcase org-lowest-priority) org-lowest-priority))
14138 (setq new (upcase new)))
14139 (cond ((equal new ?\ ) (setq remove t))
14140 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14141 (user-error "Priority must be between `%c' and `%c'"
14142 org-highest-priority org-lowest-priority))))
14143 ((eq action 'up)
14144 (setq new (if have
14145 (1- current) ; normal cycling
14146 ;; last priority was empty
14147 (if (eq last-command this-command)
14148 org-lowest-priority ; wrap around empty to lowest
14149 ;; default
14150 (if org-priority-start-cycle-with-default
14151 org-default-priority
14152 (1- org-default-priority))))))
14153 ((eq action 'down)
14154 (setq new (if have
14155 (1+ current) ; normal cycling
14156 ;; last priority was empty
14157 (if (eq last-command this-command)
14158 org-highest-priority ; wrap around empty to highest
14159 ;; default
14160 (if org-priority-start-cycle-with-default
14161 org-default-priority
14162 (1+ org-default-priority))))))
14163 (t (user-error "Invalid action")))
14164 (when (or (< (upcase new) org-highest-priority)
14165 (> (upcase new) org-lowest-priority))
14166 (if (and (memq action '(up down))
14167 (not have) (not (eq last-command this-command)))
14168 ;; `new' is from default priority
14169 (error
14170 "The default can not be set, see `org-default-priority' why")
14171 ;; normal cycling: `new' is beyond highest/lowest priority
14172 ;; and is wrapped around to the empty priority
14173 (setq remove t)))
14174 (setq news (format "%c" new))
14175 (if have
14176 (if remove
14177 (replace-match "" t t nil 1)
14178 (replace-match news t t nil 2))
14179 (if remove
14180 (user-error "No priority cookie found in line")
14181 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14182 (if (match-end 2)
14183 (progn
14184 (goto-char (match-end 2))
14185 (insert " [#" news "]"))
14186 (goto-char (match-beginning 3))
14187 (insert "[#" news "] "))))
14188 (org-set-tags nil 'align))
14189 (if remove
14190 (message "Priority removed")
14191 (message "Priority of current item set to %s" news)))))
14193 (defun org-show-priority ()
14194 "Show the priority of the current item.
14195 This priority is composed of the main priority given with the [#A] cookies,
14196 and by additional input from the age of a schedules or deadline entry."
14197 (interactive)
14198 (let ((pri (if (eq major-mode 'org-agenda-mode)
14199 (org-get-at-bol 'priority)
14200 (save-excursion
14201 (save-match-data
14202 (beginning-of-line)
14203 (and (looking-at org-heading-regexp)
14204 (org-get-priority (match-string 0))))))))
14205 (message "Priority is %d" (if pri pri -1000))))
14207 (defun org-get-priority (s)
14208 "Find priority cookie and return priority."
14209 (save-match-data
14210 (if (functionp org-get-priority-function)
14211 (funcall org-get-priority-function)
14212 (if (not (string-match org-priority-regexp s))
14213 (* 1000 (- org-lowest-priority org-default-priority))
14214 (* 1000 (- org-lowest-priority
14215 (string-to-char (match-string 2 s))))))))
14217 ;;;; Tags
14219 (defvar org-agenda-archives-mode)
14220 (defvar org-map-continue-from nil
14221 "Position from where mapping should continue.
14222 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14224 (defvar org-scanner-tags nil
14225 "The current tag list while the tags scanner is running.")
14227 (defvar org-trust-scanner-tags nil
14228 "Should `org-get-tags-at' use the tags for the scanner.
14229 This is for internal dynamical scoping only.
14230 When this is non-nil, the function `org-get-tags-at' will return the value
14231 of `org-scanner-tags' instead of building the list by itself. This
14232 can lead to large speed-ups when the tags scanner is used in a file with
14233 many entries, and when the list of tags is retrieved, for example to
14234 obtain a list of properties. Building the tags list for each entry in such
14235 a file becomes an N^2 operation - but with this variable set, it scales
14236 as N.")
14238 (defvar org--matcher-tags-todo-only nil)
14240 (defun org-scan-tags (action matcher todo-only &optional start-level)
14241 "Scan headline tags with inheritance and produce output ACTION.
14243 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14244 or `agenda' to produce an entry list for an agenda view. It can also be
14245 a Lisp form or a function that should be called at each matched headline, in
14246 this case the return value is a list of all return values from these calls.
14248 MATCHER is a function accepting three arguments, returning
14249 a non-nil value whenever a given set of tags qualifies a headline
14250 for inclusion. See `org-make-tags-matcher' for more information.
14251 As a special case, it can also be set to t (respectively nil) in
14252 order to match all (respectively none) headline.
14254 When TODO-ONLY is non-nil, only lines with a not-done TODO
14255 keyword are included in the output.
14257 START-LEVEL can be a string with asterisks, reducing the scope to
14258 headlines matching this string."
14259 (require 'org-agenda)
14260 (let* ((re (concat "^"
14261 (if start-level
14262 ;; Get the correct level to match
14263 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14264 org-outline-regexp)
14265 " *\\(\\<\\("
14266 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14267 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14268 (props (list 'face 'default
14269 'done-face 'org-agenda-done
14270 'undone-face 'default
14271 'mouse-face 'highlight
14272 'org-not-done-regexp org-not-done-regexp
14273 'org-todo-regexp org-todo-regexp
14274 'org-complex-heading-regexp org-complex-heading-regexp
14275 'help-echo
14276 (format "mouse-2 or RET jump to org file %s"
14277 (abbreviate-file-name
14278 (or (buffer-file-name (buffer-base-buffer))
14279 (buffer-name (buffer-base-buffer)))))))
14280 (org-map-continue-from nil)
14281 lspos tags tags-list
14282 (tags-alist (list (cons 0 org-file-tags)))
14283 (llast 0) rtn rtn1 level category i txt
14284 todo marker entry priority
14285 ts-date ts-date-type ts-date-pair)
14286 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14287 (setq action (list 'lambda nil action)))
14288 (save-excursion
14289 (goto-char (point-min))
14290 (when (eq action 'sparse-tree)
14291 (org-overview)
14292 (org-remove-occur-highlights))
14293 (while (let (case-fold-search)
14294 (re-search-forward re nil t))
14295 (setq org-map-continue-from nil)
14296 (catch :skip
14297 (setq todo
14298 ;; TODO: is the 1-2 difference a bug?
14299 (when (match-end 1) (match-string-no-properties 2))
14300 tags (when (match-end 4) (match-string-no-properties 4)))
14301 (goto-char (setq lspos (match-beginning 0)))
14302 (setq level (org-reduced-level (org-outline-level))
14303 category (org-get-category))
14304 (when (eq action 'agenda)
14305 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14306 ts-date (car ts-date-pair)
14307 ts-date-type (cdr ts-date-pair)))
14308 (setq i llast llast level)
14309 ;; remove tag lists from same and sublevels
14310 (while (>= i level)
14311 (when (setq entry (assoc i tags-alist))
14312 (setq tags-alist (delete entry tags-alist)))
14313 (setq i (1- i)))
14314 ;; add the next tags
14315 (when tags
14316 (setq tags (org-split-string tags ":")
14317 tags-alist
14318 (cons (cons level tags) tags-alist)))
14319 ;; compile tags for current headline
14320 (setq tags-list
14321 (if org-use-tag-inheritance
14322 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14323 tags)
14324 org-scanner-tags tags-list)
14325 (when org-use-tag-inheritance
14326 (setcdr (car tags-alist)
14327 (mapcar (lambda (x)
14328 (setq x (copy-sequence x))
14329 (org-add-prop-inherited x))
14330 (cdar tags-alist))))
14331 (when (and tags org-use-tag-inheritance
14332 (or (not (eq t org-use-tag-inheritance))
14333 org-tags-exclude-from-inheritance))
14334 ;; Selective inheritance, remove uninherited ones.
14335 (setcdr (car tags-alist)
14336 (org-remove-uninherited-tags (cdar tags-alist))))
14337 (when (and
14339 ;; eval matcher only when the todo condition is OK
14340 (and (or (not todo-only) (member todo org-not-done-keywords))
14341 (if (functionp matcher)
14342 (let ((case-fold-search t) (org-trust-scanner-tags t))
14343 (funcall matcher todo tags-list level))
14344 matcher))
14346 ;; Call the skipper, but return t if it does not
14347 ;; skip, so that the `and' form continues evaluating.
14348 (progn
14349 (unless (eq action 'sparse-tree) (org-agenda-skip))
14352 ;; Check if timestamps are deselecting this entry
14353 (or (not todo-only)
14354 (and (member todo org-not-done-keywords)
14355 (or (not org-agenda-tags-todo-honor-ignore-options)
14356 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14358 ;; select this headline
14359 (cond
14360 ((eq action 'sparse-tree)
14361 (and org-highlight-sparse-tree-matches
14362 (org-get-heading) (match-end 0)
14363 (org-highlight-new-match
14364 (match-beginning 1) (match-end 1)))
14365 (org-show-context 'tags-tree))
14366 ((eq action 'agenda)
14367 (setq txt (org-agenda-format-item
14369 (concat
14370 (if (eq org-tags-match-list-sublevels 'indented)
14371 (make-string (1- level) ?.) "")
14372 (org-get-heading))
14373 (make-string level ?\s)
14374 category
14375 tags-list)
14376 priority (org-get-priority txt))
14377 (goto-char lspos)
14378 (setq marker (org-agenda-new-marker))
14379 (org-add-props txt props
14380 'org-marker marker 'org-hd-marker marker 'org-category category
14381 'todo-state todo
14382 'ts-date ts-date
14383 'priority priority
14384 'type (concat "tagsmatch" ts-date-type))
14385 (push txt rtn))
14386 ((functionp action)
14387 (setq org-map-continue-from nil)
14388 (save-excursion
14389 (setq rtn1 (funcall action))
14390 (push rtn1 rtn)))
14391 (t (user-error "Invalid action")))
14393 ;; if we are to skip sublevels, jump to end of subtree
14394 (unless org-tags-match-list-sublevels
14395 (org-end-of-subtree t)
14396 (backward-char 1))))
14397 ;; Get the correct position from where to continue
14398 (if org-map-continue-from
14399 (goto-char org-map-continue-from)
14400 (and (= (point) lspos) (end-of-line 1)))))
14401 (when (and (eq action 'sparse-tree)
14402 (not org-sparse-tree-open-archived-trees))
14403 (org-hide-archived-subtrees (point-min) (point-max)))
14404 (nreverse rtn)))
14406 (defun org-remove-uninherited-tags (tags)
14407 "Remove all tags that are not inherited from the list TAGS."
14408 (cond
14409 ((eq org-use-tag-inheritance t)
14410 (if org-tags-exclude-from-inheritance
14411 (org-delete-all org-tags-exclude-from-inheritance tags)
14412 tags))
14413 ((not org-use-tag-inheritance) nil)
14414 ((stringp org-use-tag-inheritance)
14415 (delq nil (mapcar
14416 (lambda (x)
14417 (if (and (string-match org-use-tag-inheritance x)
14418 (not (member x org-tags-exclude-from-inheritance)))
14419 x nil))
14420 tags)))
14421 ((listp org-use-tag-inheritance)
14422 (delq nil (mapcar
14423 (lambda (x)
14424 (if (member x org-use-tag-inheritance) x nil))
14425 tags)))))
14427 (defun org-match-sparse-tree (&optional todo-only match)
14428 "Create a sparse tree according to tags string MATCH.
14430 MATCH is a string with match syntax. It can contain a selection
14431 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14432 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14433 those. See the manual for details.
14435 If optional argument TODO-ONLY is non-nil, only select lines that
14436 are also TODO tasks."
14437 (interactive "P")
14438 (org-agenda-prepare-buffers (list (current-buffer)))
14439 (let ((org--matcher-tags-todo-only todo-only))
14440 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14441 org--matcher-tags-todo-only)))
14443 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14445 (defvar org-cached-props nil)
14446 (defun org-cached-entry-get (pom property)
14447 (if (or (eq t org-use-property-inheritance)
14448 (and (stringp org-use-property-inheritance)
14449 (let ((case-fold-search t))
14450 (string-match-p org-use-property-inheritance property)))
14451 (and (listp org-use-property-inheritance)
14452 (member-ignore-case property org-use-property-inheritance)))
14453 ;; Caching is not possible, check it directly.
14454 (org-entry-get pom property 'inherit)
14455 ;; Get all properties, so we can do complicated checks easily.
14456 (cdr (assoc-string property
14457 (or org-cached-props
14458 (setq org-cached-props (org-entry-properties pom)))
14459 t))))
14461 (defun org-global-tags-completion-table (&optional files)
14462 "Return the list of all tags in all agenda buffer/files.
14463 Optional FILES argument is a list of files which can be used
14464 instead of the agenda files."
14465 (save-excursion
14466 (org-uniquify
14467 (delq nil
14468 (apply #'append
14469 (mapcar
14470 (lambda (file)
14471 (set-buffer (find-file-noselect file))
14472 (mapcar (lambda (x)
14473 (and (stringp (car-safe x))
14474 (list (car-safe x))))
14475 (or org-current-tag-alist (org-get-buffer-tags))))
14476 (if (car-safe files) files
14477 (org-agenda-files))))))))
14479 (defun org-make-tags-matcher (match)
14480 "Create the TAGS/TODO matcher form for the selection string MATCH.
14482 Returns a cons of the selection string MATCH and a function
14483 implementing the matcher.
14485 The matcher is to be called at an Org entry, with point on the
14486 headline, and returns non-nil if the entry matches the selection
14487 string MATCH. It must be called with three arguments: the TODO
14488 keyword at the entry (or nil if none), the list of all tags at
14489 the entry including inherited ones and the reduced level of the
14490 headline. Additionally, the category of the entry, if any, must
14491 be specified as the text property `org-category' on the headline.
14493 This function sets the variable `org--matcher-tags-todo-only' to
14494 a non-nil value if the matcher restricts matching to TODO
14495 entries, otherwise it is not touched.
14497 See also `org-scan-tags'."
14498 (unless match
14499 ;; Get a new match request, with completion against the global
14500 ;; tags table and the local tags in current buffer.
14501 (let ((org-last-tags-completion-table
14502 (org-uniquify
14503 (delq nil (append (org-get-buffer-tags)
14504 (org-global-tags-completion-table))))))
14505 (setq match
14506 (completing-read
14507 "Match: "
14508 'org-tags-completion-function nil nil nil 'org-tags-history))))
14510 (let ((match0 match)
14511 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14512 (start 0)
14513 tagsmatch todomatch tagsmatcher todomatcher)
14515 ;; Expand group tags.
14516 (setq match (org-tags-expand match))
14518 ;; Check if there is a TODO part of this match, which would be the
14519 ;; part after a "/". To make sure that this slash is not part of
14520 ;; a property value to be matched against, we also check that
14521 ;; there is no / after that slash. First, find the last slash.
14522 (let ((s 0))
14523 (while (string-match "/+" match s)
14524 (setq start (match-beginning 0))
14525 (setq s (match-end 0))))
14526 (if (and (string-match "/+" match start)
14527 (not (string-match-p "\"" match start)))
14528 ;; Match contains also a TODO-matching request.
14529 (progn
14530 (setq tagsmatch (substring match 0 (match-beginning 0)))
14531 (setq todomatch (substring match (match-end 0)))
14532 (when (string-prefix-p "!" todomatch)
14533 (setq org--matcher-tags-todo-only t)
14534 (setq todomatch (substring todomatch 1)))
14535 (when (string-match "\\`\\s-*\\'" todomatch)
14536 (setq todomatch nil)))
14537 ;; Only matching tags.
14538 (setq tagsmatch match)
14539 (setq todomatch nil))
14541 ;; Make the tags matcher.
14542 (when (org-string-nw-p tagsmatch)
14543 (let ((orlist nil)
14544 (orterms (org-split-string tagsmatch "|"))
14545 term)
14546 (while (setq term (pop orterms))
14547 (while (and (equal (substring term -1) "\\") orterms)
14548 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14549 (while (string-match re term)
14550 (let* ((rest (substring term (match-end 0)))
14551 (minus (and (match-end 1)
14552 (equal (match-string 1 term) "-")))
14553 (tag (save-match-data
14554 (replace-regexp-in-string
14555 "\\\\-" "-" (match-string 2 term))))
14556 (regexp (eq (string-to-char tag) ?{))
14557 (levelp (match-end 4))
14558 (propp (match-end 5))
14560 (cond
14561 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14562 (levelp
14563 `(,(org-op-to-function (match-string 3 term))
14564 level
14565 ,(string-to-number (match-string 4 term))))
14566 (propp
14567 (let* ((gv (pcase (upcase (match-string 5 term))
14568 ("CATEGORY"
14569 '(get-text-property (point) 'org-category))
14570 ("TODO" 'todo)
14571 (p `(org-cached-entry-get nil ,p))))
14572 (pv (match-string 7 term))
14573 (regexp (eq (string-to-char pv) ?{))
14574 (strp (eq (string-to-char pv) ?\"))
14575 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14576 (po (org-op-to-function (match-string 6 term)
14577 (if timep 'time strp))))
14578 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14579 (when timep (setq pv (org-matcher-time pv)))
14580 (cond ((and regexp (eq po 'org<>))
14581 `(not (string-match ,pv (or ,gv ""))))
14582 (regexp `(string-match ,pv (or ,gv "")))
14583 (strp `(,po (or ,gv "") ,pv))
14585 `(,po
14586 (string-to-number (or ,gv ""))
14587 ,(string-to-number pv))))))
14588 (t `(member ,tag tags-list)))))
14589 (push (if minus `(not ,mm) mm) tagsmatcher)
14590 (setq term rest)))
14591 (push `(and ,@tagsmatcher) orlist)
14592 (setq tagsmatcher nil))
14593 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14595 ;; Make the TODO matcher.
14596 (when (org-string-nw-p todomatch)
14597 (let ((orlist nil))
14598 (dolist (term (org-split-string todomatch "|"))
14599 (while (string-match re term)
14600 (let* ((minus (and (match-end 1)
14601 (equal (match-string 1 term) "-")))
14602 (kwd (match-string 2 term))
14603 (regexp (eq (string-to-char kwd) ?{))
14604 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14605 `(equal todo ,kwd))))
14606 (push (if minus `(not ,mm) mm) todomatcher))
14607 (setq term (substring term (match-end 0))))
14608 (push (if (> (length todomatcher) 1)
14609 (cons 'and todomatcher)
14610 (car todomatcher))
14611 orlist)
14612 (setq todomatcher nil))
14613 (setq todomatcher (cons 'or orlist))))
14615 ;; Return the string and function of the matcher. If no
14616 ;; tags-specific or todo-specific matcher exists, match
14617 ;; everything.
14618 (let ((matcher (if (and tagsmatcher todomatcher)
14619 `(and ,tagsmatcher ,todomatcher)
14620 (or tagsmatcher todomatcher t))))
14621 (when org--matcher-tags-todo-only
14622 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14623 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14625 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14626 "Expand group tags in MATCH.
14628 This replaces every group tag in MATCH with a regexp tag search.
14629 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14630 will be replaced like this:
14632 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14633 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14634 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14636 Replacing by a regexp preserves the structure of the match.
14637 E.g., this expansion
14639 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14641 will match anything tagged with \"Lab\" and \"Home\", or tagged
14642 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14644 A group tag in MATCH can contain regular expressions of its own.
14645 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14646 will be replaced like this:
14648 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14650 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14651 assumed to be a single group tag, and the function will return
14652 the list of tags in this group.
14654 When DOWNCASE is non-nil, expand downcased TAGS."
14655 (if org-group-tags
14656 (let* ((case-fold-search t)
14657 (stable org-mode-syntax-table)
14658 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14659 (taggroups (if downcased
14660 (mapcar (lambda (tg) (mapcar #'downcase tg))
14661 taggroups)
14662 taggroups))
14663 (taggroups-keys (mapcar #'car taggroups))
14664 (return-match (if downcased (downcase match) match))
14665 (count 0)
14666 (work-already-expanded tags-already-expanded)
14667 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14668 ;; @ and _ are allowed as word-components in tags.
14669 (modify-syntax-entry ?@ "w" stable)
14670 (modify-syntax-entry ?_ "w" stable)
14671 ;; Temporarily replace regexp-expressions in the match-expression.
14672 (while (string-match "{.+?}" return-match)
14673 (cl-incf count)
14674 (push (match-string 0 return-match) regexps-in-match)
14675 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14676 (while (and taggroups-keys
14677 (with-syntax-table stable
14678 (string-match
14679 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14680 (regexp-opt taggroups-keys) "\\>\\)")
14681 return-match)))
14682 (let* ((dir (match-string 1 return-match))
14683 (tag (match-string 2 return-match))
14684 (tag (if downcased (downcase tag) tag)))
14685 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14686 (member tag work-already-expanded))
14687 (setq tags-in-group (assoc tag taggroups))
14688 (push tag work-already-expanded)
14689 ;; Recursively expand each tag in the group, if the tag hasn't
14690 ;; already been expanded. Restore the match-data after all recursive calls.
14691 (save-match-data
14692 (let (tags-expanded)
14693 (dolist (x (cdr tags-in-group))
14694 (if (and (member x taggroups-keys)
14695 (not (member x work-already-expanded)))
14696 (setq tags-expanded
14697 (delete-dups
14698 (append
14699 (org-tags-expand x t downcased
14700 work-already-expanded)
14701 tags-expanded)))
14702 (setq tags-expanded
14703 (append (list x) tags-expanded)))
14704 (setq work-already-expanded
14705 (delete-dups
14706 (append tags-expanded
14707 work-already-expanded))))
14708 (setq tags-in-group
14709 (delete-dups (cons (car tags-in-group)
14710 tags-expanded)))))
14711 ;; Filter tag-regexps from tags.
14712 (setq regexp-in-group-escaped
14713 (delq nil (mapcar (lambda (x)
14714 (if (stringp x)
14715 (and (equal "{" (substring x 0 1))
14716 (equal "}" (substring x -1))
14719 tags-in-group))
14720 regexp-in-group
14721 (mapcar (lambda (x)
14722 (substring x 1 -1))
14723 regexp-in-group-escaped)
14724 tags-in-group
14725 (delq nil (mapcar (lambda (x)
14726 (if (stringp x)
14727 (and (not (equal "{" (substring x 0 1)))
14728 (not (equal "}" (substring x -1)))
14731 tags-in-group)))
14732 ;; If single-as-list, do no more in the while-loop.
14733 (if (not single-as-list)
14734 (progn
14735 (when regexp-in-group
14736 (setq regexp-in-group
14737 (concat "\\|"
14738 (mapconcat 'identity regexp-in-group
14739 "\\|"))))
14740 (setq tags-in-group
14741 (concat dir
14742 "{\\<"
14743 (regexp-opt tags-in-group)
14744 "\\>"
14745 regexp-in-group
14746 "}"))
14747 (when (stringp tags-in-group)
14748 (org-add-props tags-in-group '(grouptag t)))
14749 (setq return-match
14750 (replace-match tags-in-group t t return-match)))
14751 (setq tags-in-group
14752 (append regexp-in-group-escaped tags-in-group))))
14753 (setq taggroups-keys (delete tag taggroups-keys))))
14754 ;; Add the regular expressions back into the match-expression again.
14755 (while regexps-in-match
14756 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14757 (pop regexps-in-match)
14758 return-match t t))
14759 (cl-decf count))
14760 (if single-as-list
14761 (if tags-in-group tags-in-group (list return-match))
14762 return-match))
14763 (if single-as-list
14764 (list (if downcased (downcase match) match))
14765 match)))
14767 (defun org-op-to-function (op &optional stringp)
14768 "Turn an operator into the appropriate function."
14769 (setq op
14770 (cond
14771 ((equal op "<" ) '(< string< org-time<))
14772 ((equal op ">" ) '(> org-string> org-time>))
14773 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14774 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14775 ((member op '("=" "==")) '(= string= org-time=))
14776 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14777 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14779 (defun org<> (a b) (not (= a b)))
14780 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14781 (defun org-string>= (a b) (not (string< a b)))
14782 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14783 (defun org-string<> (a b) (not (string= a b)))
14784 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14785 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14786 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14787 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14788 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14789 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14790 (defun org-2ft (s)
14791 "Convert S to a floating point time.
14792 If S is already a number, just return it. If it is a string, parse
14793 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14794 (cond
14795 ((numberp s) s)
14796 ((stringp s)
14797 (condition-case nil
14798 (float-time (apply 'encode-time (org-parse-time-string s)))
14799 (error 0.)))
14800 (t 0.)))
14802 (defun org-time-today ()
14803 "Time in seconds today at 0:00.
14804 Returns the float number of seconds since the beginning of the
14805 epoch to the beginning of today (00:00)."
14806 (float-time (apply 'encode-time
14807 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14809 (defun org-matcher-time (s)
14810 "Interpret a time comparison value."
14811 (save-match-data
14812 (cond
14813 ((string= s "<now>") (float-time))
14814 ((string= s "<today>") (org-time-today))
14815 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14816 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14817 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14818 (+ (org-time-today)
14819 (* (string-to-number (match-string 1 s))
14820 (cdr (assoc (match-string 2 s)
14821 '(("d" . 86400.0) ("w" . 604800.0)
14822 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14823 (t (org-2ft s)))))
14825 (defun org-match-any-p (re list)
14826 "Does re match any element of list?"
14827 (setq list (mapcar (lambda (x) (string-match re x)) list))
14828 (delq nil list))
14830 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14831 (defvar org-tags-overlay (make-overlay 1 1))
14832 (delete-overlay org-tags-overlay)
14834 (defun org-get-local-tags-at (&optional pos)
14835 "Get a list of tags defined in the current headline."
14836 (org-get-tags-at pos 'local))
14838 (defun org-get-local-tags ()
14839 "Get a list of tags defined in the current headline."
14840 (org-get-tags-at nil 'local))
14842 (defun org-get-tags-at (&optional pos local)
14843 "Get a list of all headline tags applicable at POS.
14844 POS defaults to point. If tags are inherited, the list contains
14845 the targets in the same sequence as the headlines appear, i.e.
14846 the tags of the current headline come last.
14847 When LOCAL is non-nil, only return tags from the current headline,
14848 ignore inherited ones."
14849 (interactive)
14850 (if (and org-trust-scanner-tags
14851 (or (not pos) (equal pos (point)))
14852 (not local))
14853 org-scanner-tags
14854 (let (tags ltags lastpos parent)
14855 (save-excursion
14856 (save-restriction
14857 (widen)
14858 (goto-char (or pos (point)))
14859 (save-match-data
14860 (catch 'done
14861 (condition-case nil
14862 (progn
14863 (org-back-to-heading t)
14864 (while (not (equal lastpos (point)))
14865 (setq lastpos (point))
14866 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14867 (setq ltags (org-split-string
14868 (match-string-no-properties 1) ":"))
14869 (when parent
14870 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14871 (setq tags (append
14872 (if parent
14873 (org-remove-uninherited-tags ltags)
14874 ltags)
14875 tags)))
14876 (or org-use-tag-inheritance (throw 'done t))
14877 (when local (throw 'done t))
14878 (or (org-up-heading-safe) (error nil))
14879 (setq parent t)))
14880 (error nil)))))
14881 (if local
14882 tags
14883 (reverse (delete-dups
14884 (reverse (append
14885 (org-remove-uninherited-tags
14886 org-file-tags)
14887 tags)))))))))
14889 (defun org-add-prop-inherited (s)
14890 (add-text-properties 0 (length s) '(inherited t) s)
14893 (defun org-toggle-tag (tag &optional onoff)
14894 "Toggle the tag TAG for the current line.
14895 If ONOFF is `on' or `off', don't toggle but set to this state."
14896 (let (res current)
14897 (save-excursion
14898 (org-back-to-heading t)
14899 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14900 (point-at-eol) t)
14901 (progn
14902 (setq current (match-string 1))
14903 (replace-match ""))
14904 (setq current ""))
14905 (setq current (nreverse (org-split-string current ":")))
14906 (cond
14907 ((eq onoff 'on)
14908 (setq res t)
14909 (or (member tag current) (push tag current)))
14910 ((eq onoff 'off)
14911 (or (not (member tag current)) (setq current (delete tag current))))
14912 (t (if (member tag current)
14913 (setq current (delete tag current))
14914 (setq res t)
14915 (push tag current))))
14916 (end-of-line 1)
14917 (if current
14918 (progn
14919 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14920 (org-set-tags nil t))
14921 (delete-horizontal-space))
14922 (run-hooks 'org-after-tags-change-hook))
14923 res))
14925 (defun org--align-tags-here (to-col)
14926 "Align tags on the current headline to TO-COL.
14927 Assume point is on a headline."
14928 (let ((pos (point)))
14929 (beginning-of-line)
14930 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14931 (>= pos (match-beginning 2)))
14932 ;; No tags or point within tags: do not align.
14933 (goto-char pos)
14934 (goto-char (match-beginning 1))
14935 (let ((shift (max (- (if (>= to-col 0) to-col
14936 (- (abs to-col) (string-width (match-string 2))))
14937 (current-column))
14938 1)))
14939 (replace-match (make-string shift ?\s) nil nil nil 1)
14940 ;; Preserve initial position, if possible. In any case, stop
14941 ;; before tags.
14942 (when (< pos (point)) (goto-char pos))))))
14944 (defun org-set-tags-command (&optional arg just-align)
14945 "Call the set-tags command for the current entry."
14946 (interactive "P")
14947 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14948 (org-set-tags arg just-align)
14949 (save-excursion
14950 (unless (and (org-region-active-p)
14951 org-loop-over-headlines-in-active-region)
14952 (org-back-to-heading t))
14953 (org-set-tags arg just-align))))
14955 (defun org-set-tags-to (data)
14956 "Set the tags of the current entry to DATA, replacing the current tags.
14957 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14958 If DATA is nil or the empty string, any tags will be removed."
14959 (interactive "sTags: ")
14960 (setq data
14961 (cond
14962 ((eq data nil) "")
14963 ((equal data "") "")
14964 ((stringp data)
14965 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14966 ":"))
14967 ((listp data)
14968 (concat ":" (mapconcat 'identity data ":") ":"))))
14969 (when data
14970 (save-excursion
14971 (org-back-to-heading t)
14972 (when (let ((case-fold-search nil))
14973 (looking-at org-complex-heading-regexp))
14974 (if (match-end 5)
14975 (progn
14976 (goto-char (match-beginning 5))
14977 (insert data)
14978 (delete-region (point) (point-at-eol))
14979 (org-set-tags nil 'align))
14980 (goto-char (point-at-eol))
14981 (insert " " data)
14982 (org-set-tags nil 'align)))
14983 (beginning-of-line 1)
14984 (when (looking-at ".*?\\([ \t]+\\)$")
14985 (delete-region (match-beginning 1) (match-end 1))))))
14987 (defun org-align-all-tags ()
14988 "Align the tags in all headings."
14989 (interactive)
14990 (save-excursion
14991 (or (ignore-errors (org-back-to-heading t))
14992 (outline-next-heading))
14993 (if (org-at-heading-p)
14994 (org-set-tags t)
14995 (message "No headings"))))
14997 (defvar org-indent-indentation-per-level)
14998 (defun org-set-tags (&optional arg just-align)
14999 "Set the tags for the current headline.
15000 With prefix ARG, realign all tags in headings in the current buffer.
15001 When JUST-ALIGN is non-nil, only align tags."
15002 (interactive "P")
15003 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15004 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15005 'region-start-level
15006 'region))
15007 org-loop-over-headlines-in-active-region)
15008 (org-map-entries
15009 ;; We don't use ARG and JUST-ALIGN here because these args
15010 ;; are not useful when looping over headlines.
15011 #'org-set-tags
15012 org-loop-over-headlines-in-active-region
15014 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15015 (let ((org-setting-tags t))
15016 (if arg
15017 (save-excursion
15018 (goto-char (point-min))
15019 (while (re-search-forward org-outline-regexp-bol nil t)
15020 (org-set-tags nil t)
15021 (end-of-line))
15022 (message "All tags realigned to column %d" org-tags-column))
15023 (let* ((current (org-get-tags-string))
15024 (tags
15025 (if just-align current
15026 ;; Get a new set of tags from the user.
15027 (save-excursion
15028 (let* ((seen)
15029 (table
15030 (setq
15031 org-last-tags-completion-table
15032 ;; Uniquify tags in alists, yet preserve
15033 ;; structure (i.e., keywords).
15034 (delq nil
15035 (mapcar
15036 (lambda (pair)
15037 (let ((head (car pair)))
15038 (cond ((symbolp head) pair)
15039 ((member head seen) nil)
15040 (t (push head seen)
15041 pair))))
15042 (append
15043 (or org-current-tag-alist
15044 (org-get-buffer-tags))
15045 (and
15046 org-complete-tags-always-offer-all-agenda-tags
15047 (org-global-tags-completion-table
15048 (org-agenda-files))))))))
15049 (current-tags (org-split-string current ":"))
15050 (inherited-tags
15051 (nreverse (nthcdr (length current-tags)
15052 (nreverse (org-get-tags-at))))))
15053 (replace-regexp-in-string
15054 "\\([-+&]+\\|,\\)"
15056 (if (or (eq t org-use-fast-tag-selection)
15057 (and org-use-fast-tag-selection
15058 (delq nil (mapcar #'cdr table))))
15059 (org-fast-tag-selection
15060 current-tags inherited-tags table
15061 (and org-fast-tag-selection-include-todo
15062 org-todo-key-alist))
15063 (let ((org-add-colon-after-tag-completion
15064 (< 1 (length table))))
15065 (org-trim
15066 (completing-read
15067 "Tags: "
15068 #'org-tags-completion-function
15069 nil nil current 'org-tags-history))))))))))
15071 (when org-tags-sort-function
15072 (setq tags
15073 (mapconcat
15074 #'identity
15075 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15076 org-tags-sort-function)
15077 ":")))
15079 (if (not (org-string-nw-p tags)) (setq tags "")
15080 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15081 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15083 ;; Insert new tags at the correct column.
15084 (unless (equal current tags)
15085 (save-excursion
15086 (beginning-of-line)
15087 (let ((case-fold-search nil))
15088 (looking-at org-complex-heading-regexp))
15089 ;; Remove current tags, if any.
15090 (when (match-end 5) (replace-match "" nil nil nil 5))
15091 ;; Insert new tags, if any. Otherwise, remove trailing
15092 ;; white spaces.
15093 (end-of-line)
15094 (if (not (equal tags ""))
15095 ;; When text is being inserted on an invisible
15096 ;; region boundary, it can be inadvertently sucked
15097 ;; into invisibility.
15098 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
15099 (skip-chars-backward " \t")
15100 (delete-region (point) (line-end-position)))))
15101 ;; Align tags, if any. Fix tags column if `org-indent-mode'
15102 ;; is on.
15103 (unless (equal tags "")
15104 (let* ((level (save-excursion
15105 (beginning-of-line)
15106 (skip-chars-forward "\\*")))
15107 (offset (if (bound-and-true-p org-indent-mode)
15108 (* (1- org-indent-indentation-per-level)
15109 (1- level))
15111 (tags-column
15112 (+ org-tags-column
15113 (if (> org-tags-column 0) (- offset) offset))))
15114 (org--align-tags-here tags-column))))
15115 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15117 (defun org-change-tag-in-region (beg end tag off)
15118 "Add or remove TAG for each entry in the region.
15119 This works in the agenda, and also in an Org buffer."
15120 (interactive
15121 (list (region-beginning) (region-end)
15122 (let ((org-last-tags-completion-table
15123 (if (derived-mode-p 'org-mode)
15124 (org-uniquify
15125 (delq nil (append (org-get-buffer-tags)
15126 (org-global-tags-completion-table))))
15127 (org-global-tags-completion-table))))
15128 (completing-read
15129 "Tag: " 'org-tags-completion-function nil nil nil
15130 'org-tags-history))
15131 (progn
15132 (message "[s]et or [r]emove? ")
15133 (equal (read-char-exclusive) ?r))))
15134 (when (fboundp 'deactivate-mark) (deactivate-mark))
15135 (let ((agendap (equal major-mode 'org-agenda-mode))
15136 l1 l2 m buf pos newhead (cnt 0))
15137 (goto-char end)
15138 (setq l2 (1- (org-current-line)))
15139 (goto-char beg)
15140 (setq l1 (org-current-line))
15141 (cl-loop for l from l1 to l2 do
15142 (org-goto-line l)
15143 (setq m (get-text-property (point) 'org-hd-marker))
15144 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15145 (and agendap m))
15146 (setq buf (if agendap (marker-buffer m) (current-buffer))
15147 pos (if agendap m (point)))
15148 (with-current-buffer buf
15149 (save-excursion
15150 (save-restriction
15151 (goto-char pos)
15152 (setq cnt (1+ cnt))
15153 (org-toggle-tag tag (if off 'off 'on))
15154 (setq newhead (org-get-heading)))))
15155 (and agendap (org-agenda-change-all-lines newhead m))))
15156 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15158 (defun org-tags-completion-function (string _predicate &optional flag)
15159 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15160 (confirm (lambda (x) (stringp (car x)))))
15161 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15162 (setq s1 (match-string 1 string)
15163 s2 (match-string 2 string))
15164 (setq s1 "" s2 string))
15165 (cond
15166 ((eq flag nil)
15167 ;; try completion
15168 (setq rtn (try-completion s2 ctable confirm))
15169 (when (stringp rtn)
15170 (setq rtn
15171 (concat s1 s2 (substring rtn (length s2))
15172 (if (and org-add-colon-after-tag-completion
15173 (assoc rtn ctable))
15174 ":" ""))))
15175 rtn)
15176 ((eq flag t)
15177 ;; all-completions
15178 (all-completions s2 ctable confirm))
15179 ((eq flag 'lambda)
15180 ;; exact match?
15181 (assoc s2 ctable)))))
15183 (defun org-fast-tag-insert (kwd tags face &optional end)
15184 "Insert KDW, and the TAGS, the latter with face FACE.
15185 Also insert END."
15186 (insert (format "%-12s" (concat kwd ":"))
15187 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15188 (or end "")))
15190 (defun org-fast-tag-show-exit (flag)
15191 (save-excursion
15192 (org-goto-line 3)
15193 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15194 (replace-match ""))
15195 (when flag
15196 (end-of-line 1)
15197 (org-move-to-column (- (window-width) 19) t)
15198 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15200 (defun org-set-current-tags-overlay (current prefix)
15201 "Add an overlay to CURRENT tag with PREFIX."
15202 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15203 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15204 (org-overlay-display org-tags-overlay (concat prefix s))))
15206 (defvar org-last-tag-selection-key nil)
15207 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15208 "Fast tag selection with single keys.
15209 CURRENT is the current list of tags in the headline, INHERITED is the
15210 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15211 possibly with grouping information. TODO-TABLE is a similar table with
15212 TODO keywords, should these have keys assigned to them.
15213 If the keys are nil, a-z are automatically assigned.
15214 Returns the new tags string, or nil to not change the current settings."
15215 (let* ((fulltable (append table todo-table))
15216 (maxlen (apply 'max (mapcar
15217 (lambda (x)
15218 (if (stringp (car x)) (string-width (car x)) 0))
15219 fulltable)))
15220 (buf (current-buffer))
15221 (expert (eq org-fast-tag-selection-single-key 'expert))
15222 (buffer-tags nil)
15223 (fwidth (+ maxlen 3 1 3))
15224 (ncol (/ (- (window-width) 4) fwidth))
15225 (i-face 'org-done)
15226 (c-face 'org-todo)
15227 tg cnt e c char c1 c2 ntable tbl rtn
15228 ov-start ov-end ov-prefix
15229 (exit-after-next org-fast-tag-selection-single-key)
15230 (done-keywords org-done-keywords)
15231 groups ingroup intaggroup)
15232 (save-excursion
15233 (beginning-of-line 1)
15234 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15235 (setq ov-start (match-beginning 1)
15236 ov-end (match-end 1)
15237 ov-prefix "")
15238 (setq ov-start (1- (point-at-eol))
15239 ov-end (1+ ov-start))
15240 (skip-chars-forward "^\n\r")
15241 (setq ov-prefix
15242 (concat
15243 (buffer-substring (1- (point)) (point))
15244 (if (> (current-column) org-tags-column)
15246 (make-string (- org-tags-column (current-column)) ?\ ))))))
15247 (move-overlay org-tags-overlay ov-start ov-end)
15248 (save-window-excursion
15249 (if expert
15250 (set-buffer (get-buffer-create " *Org tags*"))
15251 (delete-other-windows)
15252 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15253 (org-switch-to-buffer-other-window " *Org tags*"))
15254 (erase-buffer)
15255 (setq-local org-done-keywords done-keywords)
15256 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15257 (org-fast-tag-insert "Current" current c-face "\n\n")
15258 (org-fast-tag-show-exit exit-after-next)
15259 (org-set-current-tags-overlay current ov-prefix)
15260 (setq tbl fulltable char ?a cnt 0)
15261 (while (setq e (pop tbl))
15262 (cond
15263 ((eq (car e) :startgroup)
15264 (push '() groups) (setq ingroup t)
15265 (unless (zerop cnt)
15266 (setq cnt 0)
15267 (insert "\n"))
15268 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15269 ((eq (car e) :endgroup)
15270 (setq ingroup nil cnt 0)
15271 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15272 ((eq (car e) :startgrouptag)
15273 (setq intaggroup t)
15274 (unless (zerop cnt)
15275 (setq cnt 0)
15276 (insert "\n"))
15277 (insert "[ "))
15278 ((eq (car e) :endgrouptag)
15279 (setq intaggroup nil cnt 0)
15280 (insert "]\n"))
15281 ((equal e '(:newline))
15282 (unless (zerop cnt)
15283 (setq cnt 0)
15284 (insert "\n")
15285 (setq e (car tbl))
15286 (while (equal (car tbl) '(:newline))
15287 (insert "\n")
15288 (setq tbl (cdr tbl)))))
15289 ((equal e '(:grouptags)) (insert " : "))
15291 (setq tg (copy-sequence (car e)) c2 nil)
15292 (if (cdr e)
15293 (setq c (cdr e))
15294 ;; automatically assign a character.
15295 (setq c1 (string-to-char
15296 (downcase (substring
15297 tg (if (= (string-to-char tg) ?@) 1 0)))))
15298 (if (or (rassoc c1 ntable) (rassoc c1 table))
15299 (while (or (rassoc char ntable) (rassoc char table))
15300 (setq char (1+ char)))
15301 (setq c2 c1))
15302 (setq c (or c2 char)))
15303 (when ingroup (push tg (car groups)))
15304 (setq tg (org-add-props tg nil 'face
15305 (cond
15306 ((not (assoc tg table))
15307 (org-get-todo-face tg))
15308 ((member tg current) c-face)
15309 ((member tg inherited) i-face))))
15310 (when (equal (caar tbl) :grouptags)
15311 (org-add-props tg nil 'face 'org-tag-group))
15312 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15313 (insert "[" c "] " tg (make-string
15314 (- fwidth 4 (length tg)) ?\ ))
15315 (push (cons tg c) ntable)
15316 (when (= (cl-incf cnt) ncol)
15317 (insert "\n")
15318 (when (or ingroup intaggroup) (insert " "))
15319 (setq cnt 0)))))
15320 (setq ntable (nreverse ntable))
15321 (insert "\n")
15322 (goto-char (point-min))
15323 (unless expert (org-fit-window-to-buffer))
15324 (setq rtn
15325 (catch 'exit
15326 (while t
15327 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15328 (if (not groups) "no " "")
15329 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15330 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15331 (setq org-last-tag-selection-key c)
15332 (cond
15333 ((= c ?\r) (throw 'exit t))
15334 ((= c ?!)
15335 (setq groups (not groups))
15336 (goto-char (point-min))
15337 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15338 ((= c ?\C-c)
15339 (if (not expert)
15340 (org-fast-tag-show-exit
15341 (setq exit-after-next (not exit-after-next)))
15342 (setq expert nil)
15343 (delete-other-windows)
15344 (set-window-buffer (split-window-vertically) " *Org tags*")
15345 (org-switch-to-buffer-other-window " *Org tags*")
15346 (org-fit-window-to-buffer)))
15347 ((or (= c ?\C-g)
15348 (and (= c ?q) (not (rassoc c ntable))))
15349 (delete-overlay org-tags-overlay)
15350 (setq quit-flag t))
15351 ((= c ?\ )
15352 (setq current nil)
15353 (when exit-after-next (setq exit-after-next 'now)))
15354 ((= c ?\t)
15355 (condition-case nil
15356 (setq tg (completing-read
15357 "Tag: "
15358 (or buffer-tags
15359 (with-current-buffer buf
15360 (setq buffer-tags
15361 (org-get-buffer-tags))))))
15362 (quit (setq tg "")))
15363 (when (string-match "\\S-" tg)
15364 (cl-pushnew (list tg) buffer-tags :test #'equal)
15365 (if (member tg current)
15366 (setq current (delete tg current))
15367 (push tg current)))
15368 (when exit-after-next (setq exit-after-next 'now)))
15369 ((setq e (rassoc c todo-table) tg (car e))
15370 (with-current-buffer buf
15371 (save-excursion (org-todo tg)))
15372 (when exit-after-next (setq exit-after-next 'now)))
15373 ((setq e (rassoc c ntable) tg (car e))
15374 (if (member tg current)
15375 (setq current (delete tg current))
15376 (cl-loop for g in groups do
15377 (when (member tg g)
15378 (dolist (x g) (setq current (delete x current)))))
15379 (push tg current))
15380 (when exit-after-next (setq exit-after-next 'now))))
15382 ;; Create a sorted list
15383 (setq current
15384 (sort current
15385 (lambda (a b)
15386 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15387 (when (eq exit-after-next 'now) (throw 'exit t))
15388 (goto-char (point-min))
15389 (beginning-of-line 2)
15390 (delete-region (point) (point-at-eol))
15391 (org-fast-tag-insert "Current" current c-face)
15392 (org-set-current-tags-overlay current ov-prefix)
15393 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15394 (setq tg (match-string 1))
15395 (add-text-properties
15396 (match-beginning 1) (match-end 1)
15397 (list 'face
15398 (cond
15399 ((member tg current) c-face)
15400 ((member tg inherited) i-face)
15401 (t (get-text-property (match-beginning 1) 'face))))))
15402 (goto-char (point-min)))))
15403 (delete-overlay org-tags-overlay)
15404 (if rtn
15405 (mapconcat 'identity current ":")
15406 nil))))
15408 (defun org-get-tags-string ()
15409 "Get the TAGS string in the current headline."
15410 (unless (org-at-heading-p t)
15411 (user-error "Not on a heading"))
15412 (save-excursion
15413 (beginning-of-line 1)
15414 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15415 (match-string-no-properties 1)
15416 "")))
15418 (defun org-get-tags ()
15419 "Get the list of tags specified in the current headline."
15420 (org-split-string (org-get-tags-string) ":"))
15422 (defun org-get-buffer-tags ()
15423 "Get a table of all tags used in the buffer, for completion."
15424 (org-with-wide-buffer
15425 (goto-char (point-min))
15426 (let ((tag-re (concat org-outline-regexp-bol
15427 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15428 tags)
15429 (while (re-search-forward tag-re nil t)
15430 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15431 (push tag tags)))
15432 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15434 ;;;; The mapping API
15436 (defvar org-agenda-skip-comment-trees)
15437 (defvar org-agenda-skip-function)
15438 (defun org-map-entries (func &optional match scope &rest skip)
15439 "Call FUNC at each headline selected by MATCH in SCOPE.
15441 FUNC is a function or a lisp form. The function will be called without
15442 arguments, with the cursor positioned at the beginning of the headline.
15443 The return values of all calls to the function will be collected and
15444 returned as a list.
15446 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15447 does not need to preserve point. After evaluation, the cursor will be
15448 moved to the end of the line (presumably of the headline of the
15449 processed entry) and search continues from there. Under some
15450 circumstances, this may not produce the wanted results. For example,
15451 if you have removed (e.g. archived) the current (sub)tree it could
15452 mean that the next entry will be skipped entirely. In such cases, you
15453 can specify the position from where search should continue by making
15454 FUNC set the variable `org-map-continue-from' to the desired buffer
15455 position.
15457 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15458 Only headlines that are matched by this query will be considered during
15459 the iteration. When MATCH is nil or t, all headlines will be
15460 visited by the iteration.
15462 SCOPE determines the scope of this command. It can be any of:
15464 nil The current buffer, respecting the restriction if any
15465 tree The subtree started with the entry at point
15466 region The entries within the active region, if any
15467 region-start-level
15468 The entries within the active region, but only those at
15469 the same level than the first one.
15470 file The current buffer, without restriction
15471 file-with-archives
15472 The current buffer, and any archives associated with it
15473 agenda All agenda files
15474 agenda-with-archives
15475 All agenda files with any archive files associated with them
15476 \(file1 file2 ...)
15477 If this is a list, all files in the list will be scanned
15479 The remaining args are treated as settings for the skipping facilities of
15480 the scanner. The following items can be given here:
15482 archive skip trees with the archive tag
15483 comment skip trees with the COMMENT keyword
15484 function or Emacs Lisp form:
15485 will be used as value for `org-agenda-skip-function', so
15486 whenever the function returns a position, FUNC will not be
15487 called for that entry and search will continue from the
15488 position returned
15490 If your function needs to retrieve the tags including inherited tags
15491 at the *current* entry, you can use the value of the variable
15492 `org-scanner-tags' which will be much faster than getting the value
15493 with `org-get-tags-at'. If your function gets properties with
15494 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15495 to t around the call to `org-entry-properties' to get the same speedup.
15496 Note that if your function moves around to retrieve tags and properties at
15497 a *different* entry, you cannot use these techniques."
15498 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15499 (not (org-region-active-p)))
15500 (let* ((org-agenda-archives-mode nil) ; just to make sure
15501 (org-agenda-skip-archived-trees (memq 'archive skip))
15502 (org-agenda-skip-comment-trees (memq 'comment skip))
15503 (org-agenda-skip-function
15504 (car (org-delete-all '(comment archive) skip)))
15505 (org-tags-match-list-sublevels t)
15506 (start-level (eq scope 'region-start-level))
15507 matcher res
15508 org-todo-keywords-for-agenda
15509 org-done-keywords-for-agenda
15510 org-todo-keyword-alist-for-agenda
15511 org-tag-alist-for-agenda
15512 org--matcher-tags-todo-only)
15514 (cond
15515 ((eq match t) (setq matcher t))
15516 ((eq match nil) (setq matcher t))
15517 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15519 (save-excursion
15520 (save-restriction
15521 (cond ((eq scope 'tree)
15522 (org-back-to-heading t)
15523 (org-narrow-to-subtree)
15524 (setq scope nil))
15525 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15526 (org-region-active-p))
15527 ;; If needed, set start-level to a string like "2"
15528 (when start-level
15529 (save-excursion
15530 (goto-char (region-beginning))
15531 (unless (org-at-heading-p) (outline-next-heading))
15532 (setq start-level (org-current-level))))
15533 (narrow-to-region (region-beginning)
15534 (save-excursion
15535 (goto-char (region-end))
15536 (unless (and (bolp) (org-at-heading-p))
15537 (outline-next-heading))
15538 (point)))
15539 (setq scope nil)))
15541 (if (not scope)
15542 (progn
15543 (org-agenda-prepare-buffers
15544 (and buffer-file-name (list buffer-file-name)))
15545 (setq res
15546 (org-scan-tags
15547 func matcher org--matcher-tags-todo-only start-level)))
15548 ;; Get the right scope
15549 (cond
15550 ((and scope (listp scope) (symbolp (car scope)))
15551 (setq scope (eval scope)))
15552 ((eq scope 'agenda)
15553 (setq scope (org-agenda-files t)))
15554 ((eq scope 'agenda-with-archives)
15555 (setq scope (org-agenda-files t))
15556 (setq scope (org-add-archive-files scope)))
15557 ((eq scope 'file)
15558 (setq scope (and buffer-file-name (list buffer-file-name))))
15559 ((eq scope 'file-with-archives)
15560 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15561 (org-agenda-prepare-buffers scope)
15562 (dolist (file scope)
15563 (with-current-buffer (org-find-base-buffer-visiting file)
15564 (org-with-wide-buffer
15565 (goto-char (point-min))
15566 (setq res
15567 (append
15569 (org-scan-tags
15570 func matcher org--matcher-tags-todo-only)))))))))
15571 res)))
15573 ;;; Properties API
15575 (defconst org-special-properties
15576 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15577 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15578 "The special properties valid in Org mode.
15579 These are properties that are not defined in the property drawer,
15580 but in some other way.")
15582 (defconst org-default-properties
15583 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15584 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15585 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15586 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15587 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15588 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15589 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15590 "Some properties that are used by Org mode for various purposes.
15591 Being in this list makes sure that they are offered for completion.")
15593 (defun org--valid-property-p (property)
15594 "Non nil when string PROPERTY is a valid property name."
15595 (not
15596 (or (equal property "")
15597 (string-match-p "\\s-" property))))
15599 (defun org--update-property-plist (key val props)
15600 "Associate KEY to VAL in alist PROPS.
15601 Modifications are made by side-effect. Return new alist."
15602 (let* ((appending (string= (substring key -1) "+"))
15603 (key (if appending (substring key 0 -1) key))
15604 (old (assoc-string key props t)))
15605 (if (not old) (cons (cons key val) props)
15606 (setcdr old (if appending (concat (cdr old) " " val) val))
15607 props)))
15609 (defun org-get-property-block (&optional beg force)
15610 "Return the (beg . end) range of the body of the property drawer.
15611 BEG is the beginning of the current subtree, or of the part
15612 before the first headline. If it is not given, it will be found.
15613 If the drawer does not exist, create it if FORCE is non-nil, or
15614 return nil."
15615 (org-with-wide-buffer
15616 (when beg (goto-char beg))
15617 (unless (org-before-first-heading-p)
15618 (let ((beg (cond (beg)
15619 ((or (not (featurep 'org-inlinetask))
15620 (org-inlinetask-in-task-p))
15621 (org-back-to-heading t))
15622 (t (org-with-limited-levels (org-back-to-heading t))))))
15623 (forward-line)
15624 (when (looking-at-p org-planning-line-re) (forward-line))
15625 (cond ((looking-at org-property-drawer-re)
15626 (forward-line)
15627 (cons (point) (progn (goto-char (match-end 0))
15628 (line-beginning-position))))
15629 (force
15630 (goto-char beg)
15631 (org-insert-property-drawer)
15632 (let ((pos (save-excursion (search-forward ":END:")
15633 (line-beginning-position))))
15634 (cons pos pos))))))))
15636 (defun org-at-property-p ()
15637 "Non-nil when point is inside a property drawer.
15638 See `org-property-re' for match data, if applicable."
15639 (save-excursion
15640 (beginning-of-line)
15641 (and (looking-at org-property-re)
15642 (let ((property-drawer (save-match-data (org-get-property-block))))
15643 (and property-drawer
15644 (>= (point) (car property-drawer))
15645 (< (point) (cdr property-drawer)))))))
15647 (defun org-property-action ()
15648 "Do an action on properties."
15649 (interactive)
15650 (unless (org-at-property-p) (user-error "Not at a property"))
15651 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15652 (let ((c (read-char-exclusive)))
15653 (cl-case c
15654 (?s (call-interactively #'org-set-property))
15655 (?d (call-interactively #'org-delete-property))
15656 (?D (call-interactively #'org-delete-property-globally))
15657 (?c (call-interactively #'org-compute-property-at-point))
15658 (otherwise (user-error "No such property action %c" c)))))
15660 (defun org-inc-effort ()
15661 "Increment the value of the effort property in the current entry."
15662 (interactive)
15663 (org-set-effort nil t))
15665 (defvar org-clock-effort) ; Defined in org-clock.el.
15666 (defvar org-clock-current-task) ; Defined in org-clock.el.
15667 (defun org-set-effort (&optional value increment)
15668 "Set the effort property of the current entry.
15669 With numerical prefix arg, use the nth allowed value, 0 stands for the
15670 10th allowed value.
15672 When INCREMENT is non-nil, set the property to the next allowed value."
15673 (interactive "P")
15674 (when (equal value 0) (setq value 10))
15675 (let* ((completion-ignore-case t)
15676 (prop org-effort-property)
15677 (cur (org-entry-get nil prop))
15678 (allowed (org-property-get-allowed-values nil prop 'table))
15679 (existing (mapcar 'list (org-property-values prop)))
15680 (heading (nth 4 (org-heading-components)))
15682 (val (cond
15683 ((stringp value) value)
15684 ((and allowed (integerp value))
15685 (or (car (nth (1- value) allowed))
15686 (car (org-last allowed))))
15687 ((and allowed increment)
15688 (or (cl-caadr (member (list cur) allowed))
15689 (user-error "Allowed effort values are not set")))
15690 (allowed
15691 (message "Select 1-9,0, [RET%s]: %s"
15692 (if cur (concat "=" cur) "")
15693 (mapconcat 'car allowed " "))
15694 (setq rpl (read-char-exclusive))
15695 (if (equal rpl ?\r)
15697 (setq rpl (- rpl ?0))
15698 (when (equal rpl 0) (setq rpl 10))
15699 (if (and (> rpl 0) (<= rpl (length allowed)))
15700 (car (nth (1- rpl) allowed))
15701 (org-completing-read "Effort: " allowed nil))))
15703 (org-completing-read
15704 (concat "Effort" (and cur (string-match "\\S-" cur)
15705 (concat " [" cur "]"))
15706 ": ")
15707 existing nil nil "" nil cur)))))
15708 (unless (equal (org-entry-get nil prop) val)
15709 (org-entry-put nil prop val))
15710 (org-refresh-property
15711 '((effort . identity)
15712 (effort-minutes . org-duration-string-to-minutes))
15713 val)
15714 (when (equal heading (bound-and-true-p org-clock-current-task))
15715 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15716 (org-clock-update-mode-line))
15717 (message "%s is now %s" prop val)))
15719 (defun org-entry-properties (&optional pom which)
15720 "Get all properties of the current entry.
15722 When POM is a buffer position, get all properties from the entry
15723 there instead.
15725 This includes the TODO keyword, the tags, time strings for
15726 deadline, scheduled, and clocking, and any additional properties
15727 defined in the entry.
15729 If WHICH is nil or `all', get all properties. If WHICH is
15730 `special' or `standard', only get that subclass. If WHICH is
15731 a string, only get that property.
15733 Return value is an alist. Keys are properties, as upcased
15734 strings."
15735 (org-with-point-at pom
15736 (when (and (derived-mode-p 'org-mode)
15737 (ignore-errors (org-back-to-heading t)))
15738 (catch 'exit
15739 (let* ((beg (point))
15740 (specific (and (stringp which) (upcase which)))
15741 (which (cond ((not specific) which)
15742 ((member specific org-special-properties) 'special)
15743 (t 'standard)))
15744 props)
15745 ;; Get the special properties, like TODO and TAGS.
15746 (when (memq which '(nil all special))
15747 (when (or (not specific) (string= specific "CLOCKSUM"))
15748 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15749 (when clocksum
15750 (push (cons "CLOCKSUM"
15751 (org-minutes-to-clocksum-string clocksum))
15752 props)))
15753 (when specific (throw 'exit props)))
15754 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15755 (let ((clocksumt (get-text-property (point)
15756 :org-clock-minutes-today)))
15757 (when clocksumt
15758 (push (cons "CLOCKSUM_T"
15759 (org-minutes-to-clocksum-string clocksumt))
15760 props)))
15761 (when specific (throw 'exit props)))
15762 (when (or (not specific) (string= specific "ITEM"))
15763 (let ((case-fold-search nil))
15764 (when (looking-at org-complex-heading-regexp)
15765 (push (cons "ITEM"
15766 (let ((title (match-string-no-properties 4)))
15767 (if (org-string-nw-p title)
15768 (org-remove-tabs title)
15769 "")))
15770 props)))
15771 (when specific (throw 'exit props)))
15772 (when (or (not specific) (string= specific "TODO"))
15773 (let ((case-fold-search nil))
15774 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15775 (push (cons "TODO" (match-string-no-properties 2)) props)))
15776 (when specific (throw 'exit props)))
15777 (when (or (not specific) (string= specific "PRIORITY"))
15778 (push (cons "PRIORITY"
15779 (if (looking-at org-priority-regexp)
15780 (match-string-no-properties 2)
15781 (char-to-string org-default-priority)))
15782 props)
15783 (when specific (throw 'exit props)))
15784 (when (or (not specific) (string= specific "FILE"))
15785 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15786 props)
15787 (when specific (throw 'exit props)))
15788 (when (or (not specific) (string= specific "TAGS"))
15789 (let ((value (org-string-nw-p (org-get-tags-string))))
15790 (when value (push (cons "TAGS" value) props)))
15791 (when specific (throw 'exit props)))
15792 (when (or (not specific) (string= specific "ALLTAGS"))
15793 (let ((value (org-get-tags-at)))
15794 (when value
15795 (push (cons "ALLTAGS"
15796 (format ":%s:" (mapconcat #'identity value ":")))
15797 props)))
15798 (when specific (throw 'exit props)))
15799 (when (or (not specific) (string= specific "BLOCKED"))
15800 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15801 (when specific (throw 'exit props)))
15802 (when (or (not specific)
15803 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15804 (forward-line)
15805 (when (looking-at-p org-planning-line-re)
15806 (end-of-line)
15807 (let ((bol (line-beginning-position))
15808 ;; Backward compatibility: time keywords used to
15809 ;; be configurable (before 8.3). Make sure we
15810 ;; get the correct keyword.
15811 (key-assoc `(("CLOSED" . ,org-closed-string)
15812 ("DEADLINE" . ,org-deadline-string)
15813 ("SCHEDULED" . ,org-scheduled-string))))
15814 (dolist (pair (if specific (list (assoc specific key-assoc))
15815 key-assoc))
15816 (save-excursion
15817 (when (search-backward (cdr pair) bol t)
15818 (goto-char (match-end 0))
15819 (skip-chars-forward " \t")
15820 (and (looking-at org-ts-regexp-both)
15821 (push (cons (car pair)
15822 (match-string-no-properties 0))
15823 props)))))))
15824 (when specific (throw 'exit props)))
15825 (when (or (not specific)
15826 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15827 (let ((find-ts
15828 (lambda (end ts)
15829 ;; Fix next time-stamp before END. TS is the
15830 ;; list of time-stamps found so far.
15831 (let ((ts ts)
15832 (regexp (cond
15833 ((string= specific "TIMESTAMP")
15834 org-ts-regexp)
15835 ((string= specific "TIMESTAMP_IA")
15836 org-ts-regexp-inactive)
15837 ((assoc "TIMESTAMP_IA" ts)
15838 org-ts-regexp)
15839 ((assoc "TIMESTAMP" ts)
15840 org-ts-regexp-inactive)
15841 (t org-ts-regexp-both))))
15842 (catch 'next
15843 (while (re-search-forward regexp end t)
15844 (backward-char)
15845 (let ((object (org-element-context)))
15846 ;; Accept to match timestamps in node
15847 ;; properties, too.
15848 (when (memq (org-element-type object)
15849 '(node-property timestamp))
15850 (let ((type
15851 (org-element-property :type object)))
15852 (cond
15853 ((and (memq type '(active active-range))
15854 (not (equal specific "TIMESTAMP_IA")))
15855 (unless (assoc "TIMESTAMP" ts)
15856 (push (cons "TIMESTAMP"
15857 (org-element-property
15858 :raw-value object))
15860 (when specific (throw 'exit ts))))
15861 ((and (memq type '(inactive inactive-range))
15862 (not (string= specific "TIMESTAMP")))
15863 (unless (assoc "TIMESTAMP_IA" ts)
15864 (push (cons "TIMESTAMP_IA"
15865 (org-element-property
15866 :raw-value object))
15868 (when specific (throw 'exit ts))))))
15869 ;; Both timestamp types are found,
15870 ;; move to next part.
15871 (when (= (length ts) 2) (throw 'next ts)))))
15872 ts)))))
15873 (goto-char beg)
15874 ;; First look for timestamps within headline.
15875 (let ((ts (funcall find-ts (line-end-position) nil)))
15876 (if (= (length ts) 2) (setq props (nconc ts props))
15877 (forward-line)
15878 ;; Then find timestamps in the section, skipping
15879 ;; planning line.
15880 (when (looking-at-p org-planning-line-re)
15881 (forward-line))
15882 (let ((end (save-excursion (outline-next-heading))))
15883 (setq props (nconc (funcall find-ts end ts) props))))))))
15884 ;; Get the standard properties, like :PROP:.
15885 (when (memq which '(nil all standard))
15886 ;; If we are looking after a specific property, delegate
15887 ;; to `org-entry-get', which is faster. However, make an
15888 ;; exception for "CATEGORY", since it can be also set
15889 ;; through keywords (i.e. #+CATEGORY).
15890 (if (and specific (not (equal specific "CATEGORY")))
15891 (let ((value (org-entry-get beg specific nil t)))
15892 (throw 'exit (and value (list (cons specific value)))))
15893 (let ((range (org-get-property-block beg)))
15894 (when range
15895 (let ((end (cdr range)) seen-base)
15896 (goto-char (car range))
15897 ;; Unlike to `org--update-property-plist', we
15898 ;; handle the case where base values is found
15899 ;; after its extension. We also forbid standard
15900 ;; properties to be named as special properties.
15901 (while (re-search-forward org-property-re end t)
15902 (let* ((key (upcase (match-string-no-properties 2)))
15903 (extendp (string-match-p "\\+\\'" key))
15904 (key-base (if extendp (substring key 0 -1) key))
15905 (value (match-string-no-properties 3)))
15906 (cond
15907 ((member-ignore-case key-base org-special-properties))
15908 (extendp
15909 (setq props
15910 (org--update-property-plist key value props)))
15911 ((member key seen-base))
15912 (t (push key seen-base)
15913 (let ((p (assoc-string key props t)))
15914 (if p (setcdr p (concat value " " (cdr p)))
15915 (push (cons key value) props))))))))))))
15916 (unless (assoc "CATEGORY" props)
15917 (push (cons "CATEGORY" (org-get-category beg)) props)
15918 (when (string= specific "CATEGORY") (throw 'exit props)))
15919 ;; Return value.
15920 props)))))
15922 (defun org-property--local-values (property literal-nil)
15923 "Return value for PROPERTY in current entry.
15924 Value is a list whose car is the base value for PROPERTY and cdr
15925 a list of accumulated values. Return nil if neither is found in
15926 the entry. Also return nil when PROPERTY is set to \"nil\",
15927 unless LITERAL-NIL is non-nil."
15928 (let ((range (org-get-property-block)))
15929 (when range
15930 (goto-char (car range))
15931 (let* ((case-fold-search t)
15932 (end (cdr range))
15933 (value
15934 ;; Base value.
15935 (save-excursion
15936 (let ((v (and (re-search-forward
15937 (org-re-property property nil t) end t)
15938 (match-string-no-properties 3))))
15939 (list (if literal-nil v (org-not-nil v)))))))
15940 ;; Find additional values.
15941 (let* ((property+ (org-re-property (concat property "+") nil t)))
15942 (while (re-search-forward property+ end t)
15943 (push (match-string-no-properties 3) value)))
15944 ;; Return final values.
15945 (and (not (equal value '(nil))) (nreverse value))))))
15947 (defun org-entry-get (pom property &optional inherit literal-nil)
15948 "Get value of PROPERTY for entry or content at point-or-marker POM.
15950 If INHERIT is non-nil and the entry does not have the property,
15951 then also check higher levels of the hierarchy. If INHERIT is
15952 the symbol `selective', use inheritance only if the setting in
15953 `org-use-property-inheritance' selects PROPERTY for inheritance.
15955 If the property is present but empty, the return value is the
15956 empty string. If the property is not present at all, nil is
15957 returned. In any other case, return the value as a string.
15958 Search is case-insensitive.
15960 If LITERAL-NIL is set, return the string value \"nil\" as
15961 a string, do not interpret it as the list atom nil. This is used
15962 for inheritance when a \"nil\" value can supersede a non-nil
15963 value higher up the hierarchy."
15964 (org-with-point-at pom
15965 (cond
15966 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15967 ;; We need a special property. Use `org-entry-properties' to
15968 ;; retrieve it, but specify the wanted property.
15969 (cdr (assoc-string property (org-entry-properties nil property))))
15970 ((and inherit
15971 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15972 (org-entry-get-with-inheritance property literal-nil))
15974 (let* ((local (org-property--local-values property literal-nil))
15975 (value (and local (mapconcat #'identity (delq nil local) " "))))
15976 (if literal-nil value (org-not-nil value)))))))
15978 (defun org-property-or-variable-value (var &optional inherit)
15979 "Check if there is a property fixing the value of VAR.
15980 If yes, return this value. If not, return the current value of the variable."
15981 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15982 (if (and prop (stringp prop) (string-match "\\S-" prop))
15983 (read prop)
15984 (symbol-value var))))
15986 (defun org-entry-delete (pom property)
15987 "Delete PROPERTY from entry at point-or-marker POM.
15988 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15989 non-nil when a property was removed."
15990 (unless (member property org-special-properties)
15991 (org-with-point-at pom
15992 (let ((range (org-get-property-block)))
15993 (when range
15994 (let* ((begin (car range))
15995 (origin (cdr range))
15996 (end (copy-marker origin))
15997 (re (org-re-property
15998 (concat (regexp-quote property) "\\+?") t t)))
15999 (goto-char begin)
16000 (while (re-search-forward re end t)
16001 (delete-region (match-beginning 0) (line-beginning-position 2)))
16002 ;; If drawer is empty, remove it altogether.
16003 (when (= begin end)
16004 (delete-region (line-beginning-position 0)
16005 (line-beginning-position 2)))
16006 ;; Return non-nil if some property was removed.
16007 (prog1 (/= end origin) (set-marker end nil))))))))
16009 ;; Multi-values properties are properties that contain multiple values
16010 ;; These values are assumed to be single words, separated by whitespace.
16011 (defun org-entry-add-to-multivalued-property (pom property value)
16012 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16013 (let* ((old (org-entry-get pom property))
16014 (values (and old (org-split-string old "[ \t]"))))
16015 (setq value (org-entry-protect-space value))
16016 (unless (member value values)
16017 (setq values (append values (list value)))
16018 (org-entry-put pom property
16019 (mapconcat 'identity values " ")))))
16021 (defun org-entry-remove-from-multivalued-property (pom property value)
16022 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16023 (let* ((old (org-entry-get pom property))
16024 (values (and old (org-split-string old "[ \t]"))))
16025 (setq value (org-entry-protect-space value))
16026 (when (member value values)
16027 (setq values (delete value values))
16028 (org-entry-put pom property
16029 (mapconcat 'identity values " ")))))
16031 (defun org-entry-member-in-multivalued-property (pom property value)
16032 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16033 (let* ((old (org-entry-get pom property))
16034 (values (and old (org-split-string old "[ \t]"))))
16035 (setq value (org-entry-protect-space value))
16036 (member value values)))
16038 (defun org-entry-get-multivalued-property (pom property)
16039 "Return a list of values in a multivalued property."
16040 (let* ((value (org-entry-get pom property))
16041 (values (and value (org-split-string value "[ \t]"))))
16042 (mapcar 'org-entry-restore-space values)))
16044 (defun org-entry-put-multivalued-property (pom property &rest values)
16045 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16046 VALUES should be a list of strings. Spaces will be protected."
16047 (org-entry-put pom property
16048 (mapconcat 'org-entry-protect-space values " "))
16049 (let* ((value (org-entry-get pom property))
16050 (values (and value (org-split-string value "[ \t]"))))
16051 (mapcar 'org-entry-restore-space values)))
16053 (defun org-entry-protect-space (s)
16054 "Protect spaces and newline in string S."
16055 (while (string-match " " s)
16056 (setq s (replace-match "%20" t t s)))
16057 (while (string-match "\n" s)
16058 (setq s (replace-match "%0A" t t s)))
16061 (defun org-entry-restore-space (s)
16062 "Restore spaces and newline in string S."
16063 (while (string-match "%20" s)
16064 (setq s (replace-match " " t t s)))
16065 (while (string-match "%0A" s)
16066 (setq s (replace-match "\n" t t s)))
16069 (defvar org-entry-property-inherited-from (make-marker)
16070 "Marker pointing to the entry from where a property was inherited.
16071 Each call to `org-entry-get-with-inheritance' will set this marker to the
16072 location of the entry where the inheritance search matched. If there was
16073 no match, the marker will point nowhere.
16074 Note that also `org-entry-get' calls this function, if the INHERIT flag
16075 is set.")
16077 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16078 "Get PROPERTY of entry or content at point, search higher levels if needed.
16079 The search will stop at the first ancestor which has the property defined.
16080 If the value found is \"nil\", return nil to show that the property
16081 should be considered as undefined (this is the meaning of nil here).
16082 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16083 (move-marker org-entry-property-inherited-from nil)
16084 (org-with-wide-buffer
16085 (let (value)
16086 (catch 'exit
16087 (while t
16088 (let ((v (org-property--local-values property literal-nil)))
16089 (when v
16090 (setq value
16091 (concat (mapconcat #'identity (delq nil v) " ")
16092 (and value " ")
16093 value)))
16094 (cond
16095 ((car v)
16096 (org-back-to-heading t)
16097 (move-marker org-entry-property-inherited-from (point))
16098 (throw 'exit nil))
16099 ((org-up-heading-safe))
16101 (let ((global
16102 (cdr (or (assoc-string property org-file-properties t)
16103 (assoc-string property org-global-properties t)
16104 (assoc-string property org-global-properties-fixed t)))))
16105 (cond ((not global))
16106 (value (setq value (concat global " " value)))
16107 (t (setq value global))))
16108 (throw 'exit nil))))))
16109 (if literal-nil value (org-not-nil value)))))
16111 (defvar org-property-changed-functions nil
16112 "Hook called when the value of a property has changed.
16113 Each hook function should accept two arguments, the name of the property
16114 and the new value.")
16116 (defun org-entry-put (pom property value)
16117 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16119 If the value is nil, it is converted to the empty string. If it
16120 is not a string, an error is raised. Also raise an error on
16121 invalid property names.
16123 PROPERTY can be any regular property (see
16124 `org-special-properties'). It can also be \"TODO\",
16125 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16127 For the last two properties, VALUE may have any of the special
16128 values \"earlier\" and \"later\". The function then increases or
16129 decreases scheduled or deadline date by one day."
16130 (cond ((null value) (setq value ""))
16131 ((not (stringp value)) (error "Properties values should be strings"))
16132 ((not (org--valid-property-p property))
16133 (user-error "Invalid property name: \"%s\"" property)))
16134 (org-with-point-at pom
16135 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16136 (org-back-to-heading t)
16137 (org-with-limited-levels (org-back-to-heading t)))
16138 (let ((beg (point)))
16139 (cond
16140 ((equal property "TODO")
16141 (cond ((not (org-string-nw-p value)) (setq value 'none))
16142 ((not (member value org-todo-keywords-1))
16143 (user-error "\"%s\" is not a valid TODO state" value)))
16144 (org-todo value)
16145 (org-set-tags nil 'align))
16146 ((equal property "PRIORITY")
16147 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16148 (org-set-tags nil 'align))
16149 ((equal property "SCHEDULED")
16150 (forward-line)
16151 (if (and (looking-at-p org-planning-line-re)
16152 (re-search-forward
16153 org-scheduled-time-regexp (line-end-position) t))
16154 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16155 ((string= value "later") (org-timestamp-change 1 'day))
16156 ((string= value "") (org-schedule '(4)))
16157 (t (org-schedule nil value)))
16158 (if (member value '("earlier" "later" ""))
16159 (call-interactively #'org-schedule)
16160 (org-schedule nil value))))
16161 ((equal property "DEADLINE")
16162 (forward-line)
16163 (if (and (looking-at-p org-planning-line-re)
16164 (re-search-forward
16165 org-deadline-time-regexp (line-end-position) t))
16166 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16167 ((string= value "later") (org-timestamp-change 1 'day))
16168 ((string= value "") (org-deadline '(4)))
16169 (t (org-deadline nil value)))
16170 (if (member value '("earlier" "later" ""))
16171 (call-interactively #'org-deadline)
16172 (org-deadline nil value))))
16173 ((member property org-special-properties)
16174 (error "The %s property cannot be set with `org-entry-put'" property))
16176 (let* ((range (org-get-property-block beg 'force))
16177 (end (cdr range))
16178 (case-fold-search t))
16179 (goto-char (car range))
16180 (if (re-search-forward (org-re-property property nil t) end t)
16181 (progn (delete-region (match-beginning 0) (match-end 0))
16182 (goto-char (match-beginning 0)))
16183 (goto-char end)
16184 (insert "\n")
16185 (backward-char))
16186 (insert ":" property ":")
16187 (when value (insert " " value))
16188 (org-indent-line)))))
16189 (run-hook-with-args 'org-property-changed-functions property value)))
16191 (defun org-buffer-property-keys
16192 (&optional specials defaults columns ignore-malformed)
16193 "Get all property keys in the current buffer.
16195 When SPECIALS is non-nil, also list the special properties that
16196 reflect things like tags and TODO state.
16198 When DEFAULTS is non-nil, also include properties that has
16199 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16200 DESCRIPTION, LOCATION, and LOGGING and others.
16202 When COLUMNS in non-nil, also include property names given in
16203 COLUMN formats in the current buffer.
16205 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16206 automatically performed, such drawers will be silently ignored."
16207 (let ((case-fold-search t)
16208 (props (append
16209 (and specials org-special-properties)
16210 (and defaults (cons org-effort-property org-default-properties))
16211 nil)))
16212 (org-with-wide-buffer
16213 (goto-char (point-min))
16214 (while (re-search-forward org-property-start-re nil t)
16215 (let ((range (org-get-property-block)))
16216 (catch 'skip
16217 (unless range
16218 (when (and (not ignore-malformed)
16219 (not (org-before-first-heading-p))
16220 (y-or-n-p (format "Malformed drawer at %d, repair?"
16221 (line-beginning-position))))
16222 (org-get-property-block nil t))
16223 (throw 'skip nil))
16224 (goto-char (car range))
16225 (let ((begin (car range))
16226 (end (cdr range)))
16227 ;; Make sure that found property block is not located
16228 ;; before current point, as it would generate an infloop.
16229 ;; It can happen, for example, in the following
16230 ;; situation:
16232 ;; * Headline
16233 ;; :PROPERTIES:
16234 ;; ...
16235 ;; :END:
16236 ;; *************** Inlinetask
16237 ;; #+BEGIN_EXAMPLE
16238 ;; :PROPERTIES:
16239 ;; #+END_EXAMPLE
16241 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16242 (while (< (point) end)
16243 (let ((p (progn (looking-at org-property-re)
16244 (match-string-no-properties 2))))
16245 ;; Only add true property name, not extension symbol.
16246 (push (if (not (string-match-p "\\+\\'" p)) p
16247 (substring p 0 -1))
16248 props))
16249 (forward-line))))
16250 (outline-next-heading)))
16251 (when columns
16252 (goto-char (point-min))
16253 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16254 (let ((element (org-element-at-point)))
16255 (when (memq (org-element-type element) '(keyword node-property))
16256 (let ((value (org-element-property :value element))
16257 (start 0))
16258 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16259 (setq start (match-end 0))
16260 (let ((p (match-string-no-properties 1 value)))
16261 (unless (member-ignore-case p org-special-properties)
16262 (push p props))))))))))
16263 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16265 (defun org-property-values (key)
16266 "List all non-nil values of property KEY in current buffer."
16267 (org-with-wide-buffer
16268 (goto-char (point-min))
16269 (let ((case-fold-search t)
16270 (re (org-re-property key))
16271 values)
16272 (while (re-search-forward re nil t)
16273 (push (org-entry-get (point) key) values))
16274 (delete-dups values))))
16276 (defun org-insert-property-drawer ()
16277 "Insert a property drawer into the current entry."
16278 (org-with-wide-buffer
16279 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16280 (org-back-to-heading t)
16281 (org-with-limited-levels (org-back-to-heading t)))
16282 (forward-line)
16283 (when (looking-at-p org-planning-line-re) (forward-line))
16284 (unless (looking-at-p org-property-drawer-re)
16285 ;; Make sure we start editing a line from current entry, not from
16286 ;; next one. It prevents extending text properties or overlays
16287 ;; belonging to the latter.
16288 (when (bolp) (backward-char))
16289 (let ((begin (1+ (point)))
16290 (inhibit-read-only t))
16291 (insert "\n:PROPERTIES:\n:END:")
16292 (when (eobp) (insert "\n"))
16293 (org-indent-region begin (point))))))
16295 (defun org-insert-drawer (&optional arg drawer)
16296 "Insert a drawer at point.
16298 When optional argument ARG is non-nil, insert a property drawer.
16300 Optional argument DRAWER, when non-nil, is a string representing
16301 drawer's name. Otherwise, the user is prompted for a name.
16303 If a region is active, insert the drawer around that region
16304 instead.
16306 Point is left between drawer's boundaries."
16307 (interactive "P")
16308 (let* ((drawer (if arg "PROPERTIES"
16309 (or drawer (read-from-minibuffer "Drawer: ")))))
16310 (cond
16311 ;; With C-u, fall back on `org-insert-property-drawer'
16312 (arg (org-insert-property-drawer))
16313 ;; Check validity of suggested drawer's name.
16314 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16315 (user-error "Invalid drawer name"))
16316 ;; With an active region, insert a drawer at point.
16317 ((not (org-region-active-p))
16318 (progn
16319 (unless (bolp) (insert "\n"))
16320 (insert (format ":%s:\n\n:END:\n" drawer))
16321 (forward-line -2)))
16322 ;; Otherwise, insert the drawer at point
16324 (let ((rbeg (region-beginning))
16325 (rend (copy-marker (region-end))))
16326 (unwind-protect
16327 (progn
16328 (goto-char rbeg)
16329 (beginning-of-line)
16330 (when (save-excursion
16331 (re-search-forward org-outline-regexp-bol rend t))
16332 (user-error "Drawers cannot contain headlines"))
16333 ;; Position point at the beginning of the first
16334 ;; non-blank line in region. Insert drawer's opening
16335 ;; there, then indent it.
16336 (org-skip-whitespace)
16337 (beginning-of-line)
16338 (insert ":" drawer ":\n")
16339 (forward-line -1)
16340 (indent-for-tab-command)
16341 ;; Move point to the beginning of the first blank line
16342 ;; after the last non-blank line in region. Insert
16343 ;; drawer's closing, then indent it.
16344 (goto-char rend)
16345 (skip-chars-backward " \r\t\n")
16346 (insert "\n:END:")
16347 (deactivate-mark t)
16348 (indent-for-tab-command)
16349 (unless (eolp) (insert "\n")))
16350 ;; Clear marker, whatever the outcome of insertion is.
16351 (set-marker rend nil)))))))
16353 (defvar org-property-set-functions-alist nil
16354 "Property set function alist.
16355 Each entry should have the following format:
16357 (PROPERTY . READ-FUNCTION)
16359 The read function will be called with the same argument as
16360 `org-completing-read'.")
16362 (defun org-set-property-function (property)
16363 "Get the function that should be used to set PROPERTY.
16364 This is computed according to `org-property-set-functions-alist'."
16365 (or (cdr (assoc property org-property-set-functions-alist))
16366 'org-completing-read))
16368 (defun org-read-property-value (property)
16369 "Read PROPERTY value from user."
16370 (let* ((completion-ignore-case t)
16371 (allowed (org-property-get-allowed-values nil property 'table))
16372 (cur (org-entry-get nil property))
16373 (prompt (concat property " value"
16374 (if (and cur (string-match "\\S-" cur))
16375 (concat " [" cur "]") "") ": "))
16376 (set-function (org-set-property-function property))
16377 (val (if allowed
16378 (funcall set-function prompt allowed nil
16379 (not (get-text-property 0 'org-unrestricted
16380 (caar allowed))))
16381 (funcall set-function prompt
16382 (mapcar 'list (org-property-values property))
16383 nil nil "" nil cur))))
16384 (org-trim val)))
16386 (defvar org-last-set-property nil)
16387 (defvar org-last-set-property-value nil)
16388 (defun org-read-property-name ()
16389 "Read a property name."
16390 (let ((completion-ignore-case t)
16391 (default-prop (or (and (org-at-property-p)
16392 (match-string-no-properties 2))
16393 org-last-set-property)))
16394 (org-completing-read
16395 (concat "Property"
16396 (if default-prop (concat " [" default-prop "]") "")
16397 ": ")
16398 (mapcar #'list (org-buffer-property-keys nil t t))
16399 nil nil nil nil default-prop)))
16401 (defun org-set-property-and-value (use-last)
16402 "Allow to set [PROPERTY]: [value] direction from prompt.
16403 When use-default, don't even ask, just use the last
16404 \"[PROPERTY]: [value]\" string from the history."
16405 (interactive "P")
16406 (let* ((completion-ignore-case t)
16407 (pv (or (and use-last org-last-set-property-value)
16408 (org-completing-read
16409 "Enter a \"[Property]: [value]\" pair: "
16410 nil nil nil nil nil
16411 org-last-set-property-value)))
16412 prop val)
16413 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16414 (setq prop (match-string 1 pv)
16415 val (match-string 2 pv))
16416 (org-set-property prop val))))
16418 (defun org-set-property (property value)
16419 "In the current entry, set PROPERTY to VALUE.
16421 When called interactively, this will prompt for a property name, offering
16422 completion on existing and default properties. And then it will prompt
16423 for a value, offering completion either on allowed values (via an inherited
16424 xxx_ALL property) or on existing values in other instances of this property
16425 in the current file.
16427 Throw an error when trying to set a property with an invalid name."
16428 (interactive (list nil nil))
16429 (let ((property (or property (org-read-property-name))))
16430 ;; `org-entry-put' also makes the following check, but this one
16431 ;; avoids polluting `org-last-set-property' and
16432 ;; `org-last-set-property-value' needlessly.
16433 (unless (org--valid-property-p property)
16434 (user-error "Invalid property name: \"%s\"" property))
16435 (let ((value (or value (org-read-property-value property)))
16436 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16437 (setq org-last-set-property property)
16438 (setq org-last-set-property-value (concat property ": " value))
16439 ;; Possibly postprocess the inserted value:
16440 (when fn (setq value (funcall fn value)))
16441 (unless (equal (org-entry-get nil property) value)
16442 (org-entry-put nil property value)))))
16444 (defun org-find-property (property &optional value)
16445 "Find first entry in buffer that sets PROPERTY.
16447 When optional argument VALUE is non-nil, only consider an entry
16448 if it contains PROPERTY set to this value. If PROPERTY should be
16449 explicitly set to nil, use string \"nil\" for VALUE.
16451 Return position where the entry begins, or nil if there is no
16452 such entry. If narrowing is in effect, only search the visible
16453 part of the buffer."
16454 (save-excursion
16455 (goto-char (point-min))
16456 (let ((case-fold-search t)
16457 (re (org-re-property property nil (not value) value)))
16458 (catch 'exit
16459 (while (re-search-forward re nil t)
16460 (when (if value (org-at-property-p)
16461 (org-entry-get (point) property nil t))
16462 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16464 (defun org-delete-property (property)
16465 "In the current entry, delete PROPERTY."
16466 (interactive
16467 (let* ((completion-ignore-case t)
16468 (cat (org-entry-get (point) "CATEGORY"))
16469 (props0 (org-entry-properties nil 'standard))
16470 (props (if cat props0
16471 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16472 (prop (if (< 1 (length props))
16473 (completing-read "Property: " props nil t)
16474 (caar props))))
16475 (list prop)))
16476 (if (not property)
16477 (message "No property to delete in this entry")
16478 (org-entry-delete nil property)
16479 (message "Property \"%s\" deleted" property)))
16481 (defun org-delete-property-globally (property)
16482 "Remove PROPERTY globally, from all entries.
16483 This function ignores narrowing, if any."
16484 (interactive
16485 (let* ((completion-ignore-case t)
16486 (prop (completing-read
16487 "Globally remove property: "
16488 (mapcar #'list (org-buffer-property-keys)))))
16489 (list prop)))
16490 (org-with-wide-buffer
16491 (goto-char (point-min))
16492 (let ((count 0)
16493 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16494 (while (re-search-forward re nil t)
16495 (when (org-entry-delete (point) property) (cl-incf count)))
16496 (message "Property \"%s\" removed from %d entries" property count))))
16498 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16500 (defun org-compute-property-at-point ()
16501 "Compute the property at point.
16502 This looks for an enclosing column format, extracts the operator and
16503 then applies it to the property in the column format's scope."
16504 (interactive)
16505 (unless (org-at-property-p)
16506 (user-error "Not at a property"))
16507 (let ((prop (match-string-no-properties 2)))
16508 (org-columns-get-format-and-top-level)
16509 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16510 (user-error "No operator defined for property %s" prop))
16511 (org-columns-compute prop)))
16513 (defvar org-property-allowed-value-functions nil
16514 "Hook for functions supplying allowed values for a specific property.
16515 The functions must take a single argument, the name of the property, and
16516 return a flat list of allowed values. If \":ETC\" is one of
16517 the values, this means that these values are intended as defaults for
16518 completion, but that other values should be allowed too.
16519 The functions must return nil if they are not responsible for this
16520 property.")
16522 (defun org-property-get-allowed-values (pom property &optional table)
16523 "Get allowed values for the property PROPERTY.
16524 When TABLE is non-nil, return an alist that can directly be used for
16525 completion."
16526 (let (vals)
16527 (cond
16528 ((equal property "TODO")
16529 (setq vals (org-with-point-at pom
16530 (append org-todo-keywords-1 '("")))))
16531 ((equal property "PRIORITY")
16532 (let ((n org-lowest-priority))
16533 (while (>= n org-highest-priority)
16534 (push (char-to-string n) vals)
16535 (setq n (1- n)))))
16536 ((equal property "CATEGORY"))
16537 ((member property org-special-properties))
16538 ((setq vals (run-hook-with-args-until-success
16539 'org-property-allowed-value-functions property)))
16541 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16542 (when (and vals (string-match "\\S-" vals))
16543 (setq vals (car (read-from-string (concat "(" vals ")"))))
16544 (setq vals (mapcar (lambda (x)
16545 (cond ((stringp x) x)
16546 ((numberp x) (number-to-string x))
16547 ((symbolp x) (symbol-name x))
16548 (t "???")))
16549 vals)))))
16550 (when (member ":ETC" vals)
16551 (setq vals (remove ":ETC" vals))
16552 (org-add-props (car vals) '(org-unrestricted t)))
16553 (if table (mapcar 'list vals) vals)))
16555 (defun org-property-previous-allowed-value (&optional _previous)
16556 "Switch to the next allowed value for this property."
16557 (interactive)
16558 (org-property-next-allowed-value t))
16560 (defun org-property-next-allowed-value (&optional previous)
16561 "Switch to the next allowed value for this property."
16562 (interactive)
16563 (unless (org-at-property-p)
16564 (user-error "Not at a property"))
16565 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16566 (key (match-string 2))
16567 (value (match-string 3))
16568 (allowed (or (org-property-get-allowed-values (point) key)
16569 (and (member value '("[ ]" "[-]" "[X]"))
16570 '("[ ]" "[X]"))))
16571 (heading (save-match-data (nth 4 (org-heading-components))))
16572 nval)
16573 (unless allowed
16574 (user-error "Allowed values for this property have not been defined"))
16575 (when previous (setq allowed (reverse allowed)))
16576 (when (member value allowed)
16577 (setq nval (car (cdr (member value allowed)))))
16578 (setq nval (or nval (car allowed)))
16579 (when (equal nval value)
16580 (user-error "Only one allowed value for this property"))
16581 (org-at-property-p)
16582 (replace-match (concat " :" key ": " nval) t t)
16583 (org-indent-line)
16584 (beginning-of-line 1)
16585 (skip-chars-forward " \t")
16586 (when (equal prop org-effort-property)
16587 (org-refresh-property
16588 '((effort . identity)
16589 (effort-minutes . org-duration-string-to-minutes))
16590 nval)
16591 (when (string= org-clock-current-task heading)
16592 (setq org-clock-effort nval)
16593 (org-clock-update-mode-line)))
16594 (run-hook-with-args 'org-property-changed-functions key nval)))
16596 (defun org-find-olp (path &optional this-buffer)
16597 "Return a marker pointing to the entry at outline path OLP.
16598 If anything goes wrong, throw an error.
16599 You can wrap this call to catch the error like this:
16601 (condition-case msg
16602 (org-mobile-locate-entry (match-string 4))
16603 (error (nth 1 msg)))
16605 The return value will then be either a string with the error message,
16606 or a marker if everything is OK.
16608 If THIS-BUFFER is set, the outline path does not contain a file,
16609 only headings."
16610 (let* ((file (if this-buffer buffer-file-name (pop path)))
16611 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16612 (level 1)
16613 (lmin 1)
16614 (lmax 1)
16615 end found flevel)
16616 (unless buffer (error "File not found :%s" file))
16617 (with-current-buffer buffer
16618 (org-with-wide-buffer
16619 (goto-char (point-min))
16620 (dolist (heading path)
16621 (let ((re (format org-complex-heading-regexp-format
16622 (regexp-quote heading)))
16623 (cnt 0))
16624 (while (re-search-forward re end t)
16625 (setq level (- (match-end 1) (match-beginning 1)))
16626 (when (and (>= level lmin) (<= level lmax))
16627 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16628 (when (= cnt 0)
16629 (error "Heading not found on level %d: %s" lmax heading))
16630 (when (> cnt 1)
16631 (error "Heading not unique on level %d: %s" lmax heading))
16632 (goto-char found)
16633 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16634 (setq end (save-excursion (org-end-of-subtree t t)))))
16635 (when (org-at-heading-p)
16636 (point-marker))))))
16638 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16639 "Find node HEADING in BUFFER.
16640 Return a marker to the heading if it was found, or nil if not.
16641 If POS-ONLY is set, return just the position instead of a marker.
16643 The heading text must match exact, but it may have a TODO keyword,
16644 a priority cookie and tags in the standard locations."
16645 (with-current-buffer (or buffer (current-buffer))
16646 (org-with-wide-buffer
16647 (goto-char (point-min))
16648 (let (case-fold-search)
16649 (when (re-search-forward
16650 (format org-complex-heading-regexp-format
16651 (regexp-quote heading)) nil t)
16652 (if pos-only
16653 (match-beginning 0)
16654 (move-marker (make-marker) (match-beginning 0))))))))
16656 (defun org-find-exact-heading-in-directory (heading &optional dir)
16657 "Find Org node headline HEADING in all .org files in directory DIR.
16658 When the target headline is found, return a marker to this location."
16659 (let ((files (directory-files (or dir default-directory)
16660 t "\\`[^.#].*\\.org\\'"))
16661 visiting m buffer)
16662 (catch 'found
16663 (dolist (file files)
16664 (message "trying %s" file)
16665 (setq visiting (org-find-base-buffer-visiting file))
16666 (setq buffer (or visiting (find-file-noselect file)))
16667 (setq m (org-find-exact-headline-in-buffer
16668 heading buffer))
16669 (when (and (not m) (not visiting)) (kill-buffer buffer))
16670 (and m (throw 'found m))))))
16672 (defun org-find-entry-with-id (ident)
16673 "Locate the entry that contains the ID property with exact value IDENT.
16674 IDENT can be a string, a symbol or a number, this function will search for
16675 the string representation of it.
16676 Return the position where this entry starts, or nil if there is no such entry."
16677 (interactive "sID: ")
16678 (let ((id (cond
16679 ((stringp ident) ident)
16680 ((symbolp ident) (symbol-name ident))
16681 ((numberp ident) (number-to-string ident))
16682 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16683 (org-with-wide-buffer (org-find-property "ID" id))))
16685 ;;;; Timestamps
16687 (defvar org-last-changed-timestamp nil)
16688 (defvar org-last-inserted-timestamp nil
16689 "The last time stamp inserted with `org-insert-time-stamp'.")
16690 (defvar org-ts-what) ; dynamically scoped parameter
16692 (defun org-time-stamp (arg &optional inactive)
16693 "Prompt for a date/time and insert a time stamp.
16695 If the user specifies a time like HH:MM or if this command is
16696 called with at least one prefix argument, the time stamp contains
16697 the date and the time. Otherwise, only the date is included.
16699 All parts of a date not specified by the user are filled in from
16700 the timestamp at point, if any, or the current date/time
16701 otherwise.
16703 If there is already a timestamp at the cursor, it is replaced.
16705 With two universal prefix arguments, insert an active timestamp
16706 with the current time without prompting the user.
16708 When called from lisp, the timestamp is inactive if INACTIVE is
16709 non-nil."
16710 (interactive "P")
16711 (let* ((ts (cond
16712 ((org-at-date-range-p t)
16713 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16714 ((org-at-timestamp-p t) (match-string 0))))
16715 ;; Default time is either the timestamp at point or today.
16716 ;; When entering a range, only the range start is considered.
16717 (default-time (if (not ts) (current-time)
16718 (apply #'encode-time (org-parse-time-string ts))))
16719 (default-input (and ts (org-get-compact-tod ts)))
16720 (repeater (and ts
16721 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16722 (match-string 0 ts)))
16723 org-time-was-given
16724 org-end-time-was-given
16725 (time
16726 (and (if (equal arg '(16)) (current-time)
16727 ;; Preserve `this-command' and `last-command'.
16728 (let ((this-command this-command)
16729 (last-command last-command))
16730 (org-read-date
16731 arg 'totime nil nil default-time default-input
16732 inactive))))))
16733 (cond
16734 ((and ts
16735 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16736 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16737 (insert "--")
16738 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16740 ;; Make sure we're on a timestamp. When in the middle of a date
16741 ;; range, move arbitrarily to range end.
16742 (unless (org-at-timestamp-p t)
16743 (skip-chars-forward "-")
16744 (org-at-timestamp-p t))
16745 (replace-match "")
16746 (setq org-last-changed-timestamp
16747 (org-insert-time-stamp
16748 time (or org-time-was-given arg)
16749 inactive nil nil (list org-end-time-was-given)))
16750 (when repeater
16751 (backward-char)
16752 (insert " " repeater)
16753 (setq org-last-changed-timestamp
16754 (concat (substring org-last-inserted-timestamp 0 -1)
16755 " " repeater ">")))
16756 (message "Timestamp updated"))
16757 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16758 (t (org-insert-time-stamp
16759 time (or org-time-was-given arg) inactive nil nil
16760 (list org-end-time-was-given))))))
16762 ;; FIXME: can we use this for something else, like computing time differences?
16763 (defun org-get-compact-tod (s)
16764 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16765 (let* ((t1 (match-string 1 s))
16766 (h1 (string-to-number (match-string 2 s)))
16767 (m1 (string-to-number (match-string 3 s)))
16768 (t2 (and (match-end 4) (match-string 5 s)))
16769 (h2 (and t2 (string-to-number (match-string 6 s))))
16770 (m2 (and t2 (string-to-number (match-string 7 s))))
16771 dh dm)
16772 (if (not t2)
16774 (setq dh (- h2 h1) dm (- m2 m1))
16775 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16776 (concat t1 "+" (number-to-string dh)
16777 (and (/= 0 dm) (format ":%02d" dm)))))))
16779 (defun org-time-stamp-inactive (&optional arg)
16780 "Insert an inactive time stamp.
16781 An inactive time stamp is enclosed in square brackets instead of angle
16782 brackets. It is inactive in the sense that it does not trigger agenda entries,
16783 does not link to the calendar and cannot be changed with the S-cursor keys.
16784 So these are more for recording a certain time/date."
16785 (interactive "P")
16786 (org-time-stamp arg 'inactive))
16788 (defvar org-date-ovl (make-overlay 1 1))
16789 (overlay-put org-date-ovl 'face 'org-date-selected)
16790 (delete-overlay org-date-ovl)
16792 (defvar org-ans1) ; dynamically scoped parameter
16793 (defvar org-ans2) ; dynamically scoped parameter
16795 (defvar org-plain-time-of-day-regexp) ; defined below
16797 (defvar org-overriding-default-time nil) ; dynamically scoped
16798 (defvar org-read-date-overlay nil)
16799 (defvar org-dcst nil) ; dynamically scoped
16800 (defvar org-read-date-history nil)
16801 (defvar org-read-date-final-answer nil)
16802 (defvar org-read-date-analyze-futurep nil)
16803 (defvar org-read-date-analyze-forced-year nil)
16804 (defvar org-read-date-inactive)
16806 (defvar org-read-date-minibuffer-local-map
16807 (let* ((map (make-sparse-keymap)))
16808 (set-keymap-parent map minibuffer-local-map)
16809 (org-defkey map (kbd ".")
16810 (lambda () (interactive)
16811 ;; Are we at the beginning of the prompt?
16812 (if (looking-back "^[^:]+: "
16813 (let ((inhibit-field-text-motion t))
16814 (line-beginning-position)))
16815 (org-eval-in-calendar '(calendar-goto-today))
16816 (insert "."))))
16817 (org-defkey map (kbd "C-.")
16818 (lambda () (interactive)
16819 (org-eval-in-calendar '(calendar-goto-today))))
16820 (org-defkey map [(meta shift left)]
16821 (lambda () (interactive)
16822 (org-eval-in-calendar '(calendar-backward-month 1))))
16823 (org-defkey map [(meta shift right)]
16824 (lambda () (interactive)
16825 (org-eval-in-calendar '(calendar-forward-month 1))))
16826 (org-defkey map [(meta shift up)]
16827 (lambda () (interactive)
16828 (org-eval-in-calendar '(calendar-backward-year 1))))
16829 (org-defkey map [(meta shift down)]
16830 (lambda () (interactive)
16831 (org-eval-in-calendar '(calendar-forward-year 1))))
16832 (org-defkey map [?\e (shift left)]
16833 (lambda () (interactive)
16834 (org-eval-in-calendar '(calendar-backward-month 1))))
16835 (org-defkey map [?\e (shift right)]
16836 (lambda () (interactive)
16837 (org-eval-in-calendar '(calendar-forward-month 1))))
16838 (org-defkey map [?\e (shift up)]
16839 (lambda () (interactive)
16840 (org-eval-in-calendar '(calendar-backward-year 1))))
16841 (org-defkey map [?\e (shift down)]
16842 (lambda () (interactive)
16843 (org-eval-in-calendar '(calendar-forward-year 1))))
16844 (org-defkey map [(shift up)]
16845 (lambda () (interactive)
16846 (org-eval-in-calendar '(calendar-backward-week 1))))
16847 (org-defkey map [(shift down)]
16848 (lambda () (interactive)
16849 (org-eval-in-calendar '(calendar-forward-week 1))))
16850 (org-defkey map [(shift left)]
16851 (lambda () (interactive)
16852 (org-eval-in-calendar '(calendar-backward-day 1))))
16853 (org-defkey map [(shift right)]
16854 (lambda () (interactive)
16855 (org-eval-in-calendar '(calendar-forward-day 1))))
16856 (org-defkey map "!"
16857 (lambda () (interactive)
16858 (org-eval-in-calendar '(diary-view-entries))
16859 (message "")))
16860 (org-defkey map ">"
16861 (lambda () (interactive)
16862 (org-eval-in-calendar '(calendar-scroll-left 1))))
16863 (org-defkey map "<"
16864 (lambda () (interactive)
16865 (org-eval-in-calendar '(calendar-scroll-right 1))))
16866 (org-defkey map "\C-v"
16867 (lambda () (interactive)
16868 (org-eval-in-calendar
16869 '(calendar-scroll-left-three-months 1))))
16870 (org-defkey map "\M-v"
16871 (lambda () (interactive)
16872 (org-eval-in-calendar
16873 '(calendar-scroll-right-three-months 1))))
16874 map)
16875 "Keymap for minibuffer commands when using `org-read-date'.")
16877 (defvar org-def)
16878 (defvar org-defdecode)
16879 (defvar org-with-time)
16881 (defvar calendar-setup) ; Dynamically scoped.
16882 (defun org-read-date (&optional with-time to-time from-string prompt
16883 default-time default-input inactive)
16884 "Read a date, possibly a time, and make things smooth for the user.
16885 The prompt will suggest to enter an ISO date, but you can also enter anything
16886 which will at least partially be understood by `parse-time-string'.
16887 Unrecognized parts of the date will default to the current day, month, year,
16888 hour and minute. If this command is called to replace a timestamp at point,
16889 or to enter the second timestamp of a range, the default time is taken
16890 from the existing stamp. Furthermore, the command prefers the future,
16891 so if you are giving a date where the year is not given, and the day-month
16892 combination is already past in the current year, it will assume you
16893 mean next year. For details, see the manual. A few examples:
16895 3-2-5 --> 2003-02-05
16896 feb 15 --> currentyear-02-15
16897 2/15 --> currentyear-02-15
16898 sep 12 9 --> 2009-09-12
16899 12:45 --> today 12:45
16900 22 sept 0:34 --> currentyear-09-22 0:34
16901 12 --> currentyear-currentmonth-12
16902 Fri --> nearest Friday after today
16903 -Tue --> last Tuesday
16904 etc.
16906 Furthermore you can specify a relative date by giving, as the *first* thing
16907 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16908 change in days weeks, months, years.
16909 With a single plus or minus, the date is relative to today. With a double
16910 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16911 +4d --> four days from today
16912 +4 --> same as above
16913 +2w --> two weeks from today
16914 ++5 --> five days from default date
16916 The function understands only English month and weekday abbreviations.
16918 While prompting, a calendar is popped up - you can also select the
16919 date with the mouse (button 1). The calendar shows a period of three
16920 months. To scroll it to other months, use the keys `>' and `<'.
16921 If you don't like the calendar, turn it off with
16922 (setq org-read-date-popup-calendar nil)
16924 With optional argument TO-TIME, the date will immediately be converted
16925 to an internal time.
16926 With an optional argument WITH-TIME, the prompt will suggest to
16927 also insert a time. Note that when WITH-TIME is not set, you can
16928 still enter a time, and this function will inform the calling routine
16929 about this change. The calling routine may then choose to change the
16930 format used to insert the time stamp into the buffer to include the time.
16931 With optional argument FROM-STRING, read from this string instead from
16932 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16933 the time/date that is used for everything that is not specified by the
16934 user."
16935 (require 'parse-time)
16936 (let* ((org-with-time with-time)
16937 (org-time-stamp-rounding-minutes
16938 (if (equal org-with-time '(16))
16939 '(0 0)
16940 org-time-stamp-rounding-minutes))
16941 (org-dcst org-display-custom-times)
16942 (ct (org-current-time))
16943 (org-def (or org-overriding-default-time default-time ct))
16944 (org-defdecode (decode-time org-def))
16945 (cur-frame (selected-frame))
16946 (mouse-autoselect-window nil) ; Don't let the mouse jump
16947 (calendar-setup
16948 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16949 (calendar-move-hook nil)
16950 (calendar-view-diary-initially-flag nil)
16951 (calendar-view-holidays-initially-flag nil)
16952 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16953 ;; Rationalize `org-def' and `org-defdecode', if required.
16954 (when (< (nth 2 org-defdecode) org-extend-today-until)
16955 (setf (nth 2 org-defdecode) -1)
16956 (setf (nth 1 org-defdecode) 59)
16957 (setq org-def (apply #'encode-time org-defdecode))
16958 (setq org-defdecode (decode-time org-def)))
16959 (let* ((timestr (format-time-string
16960 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16961 org-def))
16962 (prompt (concat (if prompt (concat prompt " ") "")
16963 (format "Date+time [%s]: " timestr))))
16964 (cond
16965 (from-string (setq ans from-string))
16966 (org-read-date-popup-calendar
16967 (save-excursion
16968 (save-window-excursion
16969 (calendar)
16970 (when (eq calendar-setup 'calendar-only)
16971 (setq cal-frame
16972 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16973 (select-frame cal-frame))
16974 (org-eval-in-calendar '(setq cursor-type nil) t)
16975 (unwind-protect
16976 (progn
16977 (calendar-forward-day (- (time-to-days org-def)
16978 (calendar-absolute-from-gregorian
16979 (calendar-current-date))))
16980 (org-eval-in-calendar nil t)
16981 (let* ((old-map (current-local-map))
16982 (map (copy-keymap calendar-mode-map))
16983 (minibuffer-local-map
16984 (copy-keymap org-read-date-minibuffer-local-map)))
16985 (org-defkey map (kbd "RET") 'org-calendar-select)
16986 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16987 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16988 (unwind-protect
16989 (progn
16990 (use-local-map map)
16991 (setq org-read-date-inactive inactive)
16992 (add-hook 'post-command-hook 'org-read-date-display)
16993 (setq org-ans0
16994 (read-string prompt
16995 default-input
16996 'org-read-date-history
16997 nil))
16998 ;; org-ans0: from prompt
16999 ;; org-ans1: from mouse click
17000 ;; org-ans2: from calendar motion
17001 (setq ans
17002 (concat org-ans0 " " (or org-ans1 org-ans2))))
17003 (remove-hook 'post-command-hook 'org-read-date-display)
17004 (use-local-map old-map)
17005 (when org-read-date-overlay
17006 (delete-overlay org-read-date-overlay)
17007 (setq org-read-date-overlay nil)))))
17008 (bury-buffer "*Calendar*")
17009 (when cal-frame
17010 (delete-frame cal-frame)
17011 (select-frame-set-input-focus cur-frame))))))
17013 (t ; Naked prompt only
17014 (unwind-protect
17015 (setq ans (read-string prompt default-input
17016 'org-read-date-history timestr))
17017 (when org-read-date-overlay
17018 (delete-overlay org-read-date-overlay)
17019 (setq org-read-date-overlay nil))))))
17021 (setq final (org-read-date-analyze ans org-def org-defdecode))
17023 (when org-read-date-analyze-forced-year
17024 (message "Year was forced into %s"
17025 (if org-read-date-force-compatible-dates
17026 "compatible range (1970-2037)"
17027 "range representable on this machine"))
17028 (ding))
17030 ;; One round trip to get rid of 34th of August and stuff like that....
17031 (setq final (decode-time (apply 'encode-time final)))
17033 (setq org-read-date-final-answer ans)
17035 (if to-time
17036 (apply 'encode-time final)
17037 (if (and (boundp 'org-time-was-given) org-time-was-given)
17038 (format "%04d-%02d-%02d %02d:%02d"
17039 (nth 5 final) (nth 4 final) (nth 3 final)
17040 (nth 2 final) (nth 1 final))
17041 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17043 (defun org-read-date-display ()
17044 "Display the current date prompt interpretation in the minibuffer."
17045 (when org-read-date-display-live
17046 (when org-read-date-overlay
17047 (delete-overlay org-read-date-overlay))
17048 (when (minibufferp (current-buffer))
17049 (save-excursion
17050 (end-of-line 1)
17051 (while (not (equal (buffer-substring
17052 (max (point-min) (- (point) 4)) (point))
17053 " "))
17054 (insert " ")))
17055 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17056 " " (or org-ans1 org-ans2)))
17057 (org-end-time-was-given nil)
17058 (f (org-read-date-analyze ans org-def org-defdecode))
17059 (fmts (if org-dcst
17060 org-time-stamp-custom-formats
17061 org-time-stamp-formats))
17062 (fmt (if (or org-with-time
17063 (and (boundp 'org-time-was-given) org-time-was-given))
17064 (cdr fmts)
17065 (car fmts)))
17066 (txt (format-time-string fmt (apply 'encode-time f)))
17067 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17068 (txt (concat "=> " txt)))
17069 (when (and org-end-time-was-given
17070 (string-match org-plain-time-of-day-regexp txt))
17071 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17072 org-end-time-was-given
17073 (substring txt (match-end 0)))))
17074 (when org-read-date-analyze-futurep
17075 (setq txt (concat txt " (=>F)")))
17076 (setq org-read-date-overlay
17077 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17078 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17080 (defun org-read-date-analyze (ans def defdecode)
17081 "Analyze the combined answer of the date prompt."
17082 ;; FIXME: cleanup and comment
17083 ;; Pass `current-time' result to `decode-time' (instead of calling
17084 ;; without arguments) so that only `current-time' has to be
17085 ;; overriden in tests.
17086 (let ((org-def def)
17087 (org-defdecode defdecode)
17088 (nowdecode (decode-time (current-time)))
17089 delta deltan deltaw deltadef year month day
17090 hour minute second wday pm h2 m2 tl wday1
17091 iso-year iso-weekday iso-week iso-date futurep kill-year)
17092 (setq org-read-date-analyze-futurep nil
17093 org-read-date-analyze-forced-year nil)
17094 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17095 (setq ans "+0"))
17097 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17098 (setq ans (replace-match "" t t ans)
17099 deltan (car delta)
17100 deltaw (nth 1 delta)
17101 deltadef (nth 2 delta)))
17103 ;; Check if there is an iso week date in there. If yes, store the
17104 ;; info and postpone interpreting it until the rest of the parsing
17105 ;; is done.
17106 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17107 (setq iso-year (when (match-end 1)
17108 (org-small-year-to-year
17109 (string-to-number (match-string 1 ans))))
17110 iso-weekday (when (match-end 3)
17111 (string-to-number (match-string 3 ans)))
17112 iso-week (string-to-number (match-string 2 ans)))
17113 (setq ans (replace-match "" t t ans)))
17115 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17116 (when (string-match
17117 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17118 (setq year (if (match-end 2)
17119 (string-to-number (match-string 2 ans))
17120 (progn (setq kill-year t)
17121 (string-to-number (format-time-string "%Y"))))
17122 month (string-to-number (match-string 3 ans))
17123 day (string-to-number (match-string 4 ans)))
17124 (setq year (org-small-year-to-year year))
17125 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17126 t nil ans)))
17128 ;; Help matching dotted european dates
17129 (when (string-match
17130 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17131 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17132 (setq kill-year t)
17133 (string-to-number (format-time-string "%Y")))
17134 day (string-to-number (match-string 1 ans))
17135 month (string-to-number (match-string 2 ans))
17136 ans (replace-match (format "%04d-%02d-%02d" year month day)
17137 t nil ans)))
17139 ;; Help matching american dates, like 5/30 or 5/30/7
17140 (when (string-match
17141 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17142 (setq year (if (match-end 4)
17143 (string-to-number (match-string 4 ans))
17144 (progn (setq kill-year t)
17145 (string-to-number (format-time-string "%Y"))))
17146 month (string-to-number (match-string 1 ans))
17147 day (string-to-number (match-string 2 ans)))
17148 (setq year (org-small-year-to-year year))
17149 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17150 t nil ans)))
17151 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17152 ;; If there is a time with am/pm, and *no* time without it, we convert
17153 ;; so that matching will be successful.
17154 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17155 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17156 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17157 (setq hour (string-to-number (match-string 1 ans))
17158 minute (if (match-end 3)
17159 (string-to-number (match-string 3 ans))
17161 pm (equal ?p
17162 (string-to-char (downcase (match-string 4 ans)))))
17163 (if (and (= hour 12) (not pm))
17164 (setq hour 0)
17165 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17166 (setq ans (replace-match (format "%02d:%02d" hour minute)
17167 t t ans))))
17169 ;; Check if a time range is given as a duration
17170 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17171 (setq hour (string-to-number (match-string 1 ans))
17172 h2 (+ hour (string-to-number (match-string 3 ans)))
17173 minute (string-to-number (match-string 2 ans))
17174 m2 (+ minute (if (match-end 5) (string-to-number
17175 (match-string 5 ans))0)))
17176 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17177 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17178 t t ans)))
17180 ;; Check if there is a time range
17181 (when (boundp 'org-end-time-was-given)
17182 (setq org-time-was-given nil)
17183 (when (and (string-match org-plain-time-of-day-regexp ans)
17184 (match-end 8))
17185 (setq org-end-time-was-given (match-string 8 ans))
17186 (setq ans (concat (substring ans 0 (match-beginning 7))
17187 (substring ans (match-end 7))))))
17189 (setq tl (parse-time-string ans)
17190 day (or (nth 3 tl) (nth 3 org-defdecode))
17191 month
17192 (cond ((nth 4 tl))
17193 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17194 ;; Day was specified. Make sure DAY+MONTH
17195 ;; combination happens in the future.
17196 ((nth 3 tl)
17197 (setq futurep t)
17198 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17199 (nth 4 nowdecode)))
17200 (t (nth 4 org-defdecode)))
17201 year
17202 (cond ((and (not kill-year) (nth 5 tl)))
17203 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17204 ;; Month was guessed in the future and is at least
17205 ;; equal to NOWDECODE's. Fix year accordingly.
17206 (futurep
17207 (if (or (> month (nth 4 nowdecode))
17208 (>= day (nth 3 nowdecode)))
17209 (nth 5 nowdecode)
17210 (1+ (nth 5 nowdecode))))
17211 ;; Month was specified. Make sure MONTH+YEAR
17212 ;; combination happens in the future.
17213 ((nth 4 tl)
17214 (setq futurep t)
17215 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17216 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17217 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17218 (t (nth 5 nowdecode))))
17219 (t (nth 5 org-defdecode)))
17220 hour (or (nth 2 tl) (nth 2 org-defdecode))
17221 minute (or (nth 1 tl) (nth 1 org-defdecode))
17222 second (or (nth 0 tl) 0)
17223 wday (nth 6 tl))
17225 (when (and (eq org-read-date-prefer-future 'time)
17226 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17227 (equal day (nth 3 nowdecode))
17228 (equal month (nth 4 nowdecode))
17229 (equal year (nth 5 nowdecode))
17230 (nth 2 tl)
17231 (or (< (nth 2 tl) (nth 2 nowdecode))
17232 (and (= (nth 2 tl) (nth 2 nowdecode))
17233 (nth 1 tl)
17234 (< (nth 1 tl) (nth 1 nowdecode)))))
17235 (setq day (1+ day)
17236 futurep t))
17238 ;; Special date definitions below
17239 (cond
17240 (iso-week
17241 ;; There was an iso week
17242 (require 'cal-iso)
17243 (setq futurep nil)
17244 (setq year (or iso-year year)
17245 day (or iso-weekday wday 1)
17246 wday nil ; to make sure that the trigger below does not match
17247 iso-date (calendar-gregorian-from-absolute
17248 (calendar-iso-to-absolute
17249 (list iso-week day year))))
17250 ; FIXME: Should we also push ISO weeks into the future?
17251 ; (when (and org-read-date-prefer-future
17252 ; (not iso-year)
17253 ; (< (calendar-absolute-from-gregorian iso-date)
17254 ; (time-to-days (current-time))))
17255 ; (setq year (1+ year)
17256 ; iso-date (calendar-gregorian-from-absolute
17257 ; (calendar-iso-to-absolute
17258 ; (list iso-week day year)))))
17259 (setq month (car iso-date)
17260 year (nth 2 iso-date)
17261 day (nth 1 iso-date)))
17262 (deltan
17263 (setq futurep nil)
17264 (unless deltadef
17265 ;; Pass `current-time' result to `decode-time' (instead of
17266 ;; calling without arguments) so that only `current-time' has
17267 ;; to be overriden in tests.
17268 (let ((now (decode-time (current-time))))
17269 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17270 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17271 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17272 ((equal deltaw "m") (setq month (+ month deltan)))
17273 ((equal deltaw "y") (setq year (+ year deltan)))))
17274 ((and wday (not (nth 3 tl)))
17275 ;; Weekday was given, but no day, so pick that day in the week
17276 ;; on or after the derived date.
17277 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17278 (unless (equal wday wday1)
17279 (setq day (+ day (% (- wday wday1 -7) 7))))))
17280 (when (and (boundp 'org-time-was-given)
17281 (nth 2 tl))
17282 (setq org-time-was-given t))
17283 (when (< year 100) (setq year (+ 2000 year)))
17284 ;; Check of the date is representable
17285 (if org-read-date-force-compatible-dates
17286 (progn
17287 (when (< year 1970)
17288 (setq year 1970 org-read-date-analyze-forced-year t))
17289 (when (> year 2037)
17290 (setq year 2037 org-read-date-analyze-forced-year t)))
17291 (condition-case nil
17292 (ignore (encode-time second minute hour day month year))
17293 (error
17294 (setq year (nth 5 org-defdecode))
17295 (setq org-read-date-analyze-forced-year t))))
17296 (setq org-read-date-analyze-futurep futurep)
17297 (list second minute hour day month year)))
17299 (defvar parse-time-weekdays)
17300 (defun org-read-date-get-relative (s today default)
17301 "Check string S for special relative date string.
17302 TODAY and DEFAULT are internal times, for today and for a default.
17303 Return shift list (N what def-flag)
17304 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17305 N is the number of WHATs to shift.
17306 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17307 the DEFAULT date rather than TODAY."
17308 (require 'parse-time)
17309 (when (and
17310 (string-match
17311 (concat
17312 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17313 "\\([0-9]+\\)?"
17314 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17315 "\\([ \t]\\|$\\)") s)
17316 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17317 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17318 (string-to-char (substring (match-string 1 s) -1))
17319 ?+))
17320 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17321 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17322 (what (if (match-end 3) (match-string 3 s) "d"))
17323 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17324 (date (if rel default today))
17325 (wday (nth 6 (decode-time date)))
17326 delta)
17327 (if wday1
17328 (progn
17329 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17330 (when (= delta 0) (setq delta 7))
17331 (when (= dir ?-)
17332 (setq delta (- delta 7))
17333 (when (= delta 0) (setq delta -7)))
17334 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17335 (list delta "d" rel))
17336 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17338 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17339 "Turn a user-specified date into the internal representation.
17340 The internal representation needed by the calendar is (month day year).
17341 This is a wrapper to handle the brain-dead convention in calendar that
17342 user function argument order change dependent on argument order."
17343 (pcase calendar-date-style
17344 (`american (list arg1 arg2 arg3))
17345 (`european (list arg2 arg1 arg3))
17346 (`iso (list arg2 arg3 arg1))))
17348 (defun org-eval-in-calendar (form &optional keepdate)
17349 "Eval FORM in the calendar window and return to current window.
17350 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17351 (let ((sf (selected-frame))
17352 (sw (selected-window)))
17353 (select-window (get-buffer-window "*Calendar*" t))
17354 (eval form)
17355 (when (and (not keepdate) (calendar-cursor-to-date))
17356 (let* ((date (calendar-cursor-to-date))
17357 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17358 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17359 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17360 (select-window sw)
17361 (select-frame-set-input-focus sf)))
17363 (defun org-calendar-select ()
17364 "Return to `org-read-date' with the date currently selected.
17365 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17366 (interactive)
17367 (when (calendar-cursor-to-date)
17368 (let* ((date (calendar-cursor-to-date))
17369 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17370 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17371 (when (active-minibuffer-window) (exit-minibuffer))))
17373 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17374 "Insert a date stamp for the date given by the internal TIME.
17375 See `format-time-string' for the format of TIME.
17376 WITH-HM means use the stamp format that includes the time of the day.
17377 INACTIVE means use square brackets instead of angular ones, so that the
17378 stamp will not contribute to the agenda.
17379 PRE and POST are optional strings to be inserted before and after the
17380 stamp.
17381 The command returns the inserted time stamp."
17382 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17383 stamp)
17384 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17385 (insert-before-markers (or pre ""))
17386 (when (listp extra)
17387 (setq extra (car extra))
17388 (if (and (stringp extra)
17389 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17390 (setq extra (format "-%02d:%02d"
17391 (string-to-number (match-string 1 extra))
17392 (string-to-number (match-string 2 extra))))
17393 (setq extra nil)))
17394 (when extra
17395 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17396 (insert-before-markers (setq stamp (format-time-string fmt time)))
17397 (insert-before-markers (or post ""))
17398 (setq org-last-inserted-timestamp stamp)))
17400 (defun org-toggle-time-stamp-overlays ()
17401 "Toggle the use of custom time stamp formats."
17402 (interactive)
17403 (setq org-display-custom-times (not org-display-custom-times))
17404 (unless org-display-custom-times
17405 (let ((p (point-min)) (bmp (buffer-modified-p)))
17406 (while (setq p (next-single-property-change p 'display))
17407 (when (and (get-text-property p 'display)
17408 (eq (get-text-property p 'face) 'org-date))
17409 (remove-text-properties
17410 p (setq p (next-single-property-change p 'display))
17411 '(display t))))
17412 (set-buffer-modified-p bmp)))
17413 (org-restart-font-lock)
17414 (setq org-table-may-need-update t)
17415 (if org-display-custom-times
17416 (message "Time stamps are overlaid with custom format")
17417 (message "Time stamp overlays removed")))
17419 (defun org-display-custom-time (beg end)
17420 "Overlay modified time stamp format over timestamp between BEG and END."
17421 (let* ((ts (buffer-substring beg end))
17422 t1 w1 with-hm tf time str w2 (off 0))
17423 (save-match-data
17424 (setq t1 (org-parse-time-string ts t))
17425 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17426 (setq off (- (match-end 0) (match-beginning 0)))))
17427 (setq end (- end off))
17428 (setq w1 (- end beg)
17429 with-hm (and (nth 1 t1) (nth 2 t1))
17430 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17431 time (org-fix-decoded-time t1)
17432 str (org-add-props
17433 (format-time-string
17434 (substring tf 1 -1) (apply 'encode-time time))
17435 nil 'mouse-face 'highlight)
17436 w2 (length str))
17437 (unless (= w2 w1)
17438 (add-text-properties (1+ beg) (+ 2 beg)
17439 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17440 (put-text-property beg end 'display str)))
17442 (defun org-fix-decoded-time (time)
17443 "Set 0 instead of nil for the first 6 elements of time.
17444 Don't touch the rest."
17445 (let ((n 0))
17446 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17448 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17449 "Difference between TIMESTAMP-STRING and now in days.
17450 If SECONDS is non-nil, return the difference in seconds."
17451 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17452 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17453 (funcall fdiff (current-time)))))
17455 (defun org-deadline-close-p (timestamp-string &optional ndays)
17456 "Is the time in TIMESTAMP-STRING close to the current date?"
17457 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17458 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17459 (not (org-entry-is-done-p))))
17461 (defun org-get-wdays (ts &optional delay zero-delay)
17462 "Get the deadline lead time appropriate for timestring TS.
17463 When DELAY is non-nil, get the delay time for scheduled items
17464 instead of the deadline lead time. When ZERO-DELAY is non-nil
17465 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17466 don't try to find the delay cookie in the scheduled timestamp."
17467 (let ((tv (if delay org-scheduled-delay-days
17468 org-deadline-warning-days)))
17469 (cond
17470 ((or (and delay (< tv 0))
17471 (and delay zero-delay (<= tv 0))
17472 (and (not delay) (<= tv 0)))
17473 ;; Enforce this value no matter what
17474 (- tv))
17475 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17476 ;; lead time is specified.
17477 (floor (* (string-to-number (match-string 1 ts))
17478 (cdr (assoc (match-string 2 ts)
17479 '(("d" . 1) ("w" . 7)
17480 ("m" . 30.4) ("y" . 365.25)
17481 ("h" . 0.041667)))))))
17482 ;; go for the default.
17483 (t tv))))
17485 (defun org-calendar-select-mouse (ev)
17486 "Return to `org-read-date' with the date currently selected.
17487 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17488 (interactive "e")
17489 (mouse-set-point ev)
17490 (when (calendar-cursor-to-date)
17491 (let* ((date (calendar-cursor-to-date))
17492 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17493 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17494 (when (active-minibuffer-window) (exit-minibuffer))))
17496 (defun org-check-deadlines (ndays)
17497 "Check if there are any deadlines due or past due.
17498 A deadline is considered due if it happens within `org-deadline-warning-days'
17499 days from today's date. If the deadline appears in an entry marked DONE,
17500 it is not shown. A numeric prefix argument NDAYS can be used to test that
17501 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17502 are shown."
17503 (interactive "P")
17504 (let* ((org-warn-days
17505 (cond
17506 ((equal ndays '(4)) 100000)
17507 (ndays (prefix-numeric-value ndays))
17508 (t (abs org-deadline-warning-days))))
17509 (case-fold-search nil)
17510 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17511 (callback
17512 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17513 (message "%d deadlines past-due or due within %d days"
17514 (org-occur regexp nil callback)
17515 org-warn-days)))
17517 (defsubst org-re-timestamp (type)
17518 "Return a regexp for timestamp TYPE.
17519 Allowed values for TYPE are:
17521 all: all timestamps
17522 active: only active timestamps (<...>)
17523 inactive: only inactive timestamps ([...])
17524 scheduled: only scheduled timestamps
17525 deadline: only deadline timestamps
17526 closed: only closed time-stamps
17528 When TYPE is nil, fall back on returning a regexp that matches
17529 both scheduled and deadline timestamps."
17530 (cl-case type
17531 (all org-ts-regexp-both)
17532 (active org-ts-regexp)
17533 (inactive org-ts-regexp-inactive)
17534 (scheduled org-scheduled-time-regexp)
17535 (deadline org-deadline-time-regexp)
17536 (closed org-closed-time-regexp)
17537 (otherwise
17538 (concat "\\<"
17539 (regexp-opt (list org-deadline-string org-scheduled-string))
17540 " *<\\([^>]+\\)>"))))
17542 (defun org-check-before-date (d)
17543 "Check if there are deadlines or scheduled entries before date D."
17544 (interactive (list (org-read-date)))
17545 (let* ((case-fold-search nil)
17546 (regexp (org-re-timestamp org-ts-type))
17547 (ts-type org-ts-type)
17548 (callback
17549 (lambda ()
17550 (let ((match (match-string 1)))
17551 (and (if (memq ts-type '(active inactive all))
17552 (eq (org-element-type (save-excursion
17553 (backward-char)
17554 (org-element-context)))
17555 'timestamp)
17556 (org-at-planning-p))
17557 (time-less-p
17558 (org-time-string-to-time match)
17559 (org-time-string-to-time d)))))))
17560 (message "%d entries before %s"
17561 (org-occur regexp nil callback)
17562 d)))
17564 (defun org-check-after-date (d)
17565 "Check if there are deadlines or scheduled entries after date D."
17566 (interactive (list (org-read-date)))
17567 (let* ((case-fold-search nil)
17568 (regexp (org-re-timestamp org-ts-type))
17569 (ts-type org-ts-type)
17570 (callback
17571 (lambda ()
17572 (let ((match (match-string 1)))
17573 (and (if (memq ts-type '(active inactive all))
17574 (eq (org-element-type (save-excursion
17575 (backward-char)
17576 (org-element-context)))
17577 'timestamp)
17578 (org-at-planning-p))
17579 (not (time-less-p
17580 (org-time-string-to-time match)
17581 (org-time-string-to-time d))))))))
17582 (message "%d entries after %s"
17583 (org-occur regexp nil callback)
17584 d)))
17586 (defun org-check-dates-range (start-date end-date)
17587 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17588 (interactive (list (org-read-date nil nil nil "Range starts")
17589 (org-read-date nil nil nil "Range end")))
17590 (let ((case-fold-search nil)
17591 (regexp (org-re-timestamp org-ts-type))
17592 (callback
17593 (let ((type org-ts-type))
17594 (lambda ()
17595 (let ((match (match-string 1)))
17596 (and
17597 (if (memq type '(active inactive all))
17598 (eq (org-element-type (save-excursion
17599 (backward-char)
17600 (org-element-context)))
17601 'timestamp)
17602 (org-at-planning-p))
17603 (not (time-less-p
17604 (org-time-string-to-time match)
17605 (org-time-string-to-time start-date)))
17606 (time-less-p
17607 (org-time-string-to-time match)
17608 (org-time-string-to-time end-date))))))))
17609 (message "%d entries between %s and %s"
17610 (org-occur regexp nil callback) start-date end-date)))
17612 (defun org-evaluate-time-range (&optional to-buffer)
17613 "Evaluate a time range by computing the difference between start and end.
17614 Normally the result is just printed in the echo area, but with prefix arg
17615 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17616 If the time range is actually in a table, the result is inserted into the
17617 next column.
17618 For time difference computation, a year is assumed to be exactly 365
17619 days in order to avoid rounding problems."
17620 (interactive "P")
17622 (org-clock-update-time-maybe)
17623 (save-excursion
17624 (unless (org-at-date-range-p t)
17625 (goto-char (point-at-bol))
17626 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17627 (unless (org-at-date-range-p t)
17628 (user-error "Not at a time-stamp range, and none found in current line")))
17629 (let* ((ts1 (match-string 1))
17630 (ts2 (match-string 2))
17631 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17632 (match-end (match-end 0))
17633 (time1 (org-time-string-to-time ts1))
17634 (time2 (org-time-string-to-time ts2))
17635 (t1 (float-time time1))
17636 (t2 (float-time time2))
17637 (diff (abs (- t2 t1)))
17638 (negative (< (- t2 t1) 0))
17639 ;; (ys (floor (* 365 24 60 60)))
17640 (ds (* 24 60 60))
17641 (hs (* 60 60))
17642 (fy "%dy %dd %02d:%02d")
17643 (fy1 "%dy %dd")
17644 (fd "%dd %02d:%02d")
17645 (fd1 "%dd")
17646 (fh "%02d:%02d")
17647 y d h m align)
17648 (if havetime
17649 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17651 d (floor (/ diff ds)) diff (mod diff ds)
17652 h (floor (/ diff hs)) diff (mod diff hs)
17653 m (floor (/ diff 60)))
17654 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17656 d (floor (+ (/ diff ds) 0.5))
17657 h 0 m 0))
17658 (if (not to-buffer)
17659 (message "%s" (org-make-tdiff-string y d h m))
17660 (if (org-at-table-p)
17661 (progn
17662 (goto-char match-end)
17663 (setq align t)
17664 (and (looking-at " *|") (goto-char (match-end 0))))
17665 (goto-char match-end))
17666 (when (looking-at
17667 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17668 (replace-match ""))
17669 (when negative (insert " -"))
17670 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17671 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17672 (insert " " (format fh h m))))
17673 (when align (org-table-align))
17674 (message "Time difference inserted")))))
17676 (defun org-make-tdiff-string (y d h m)
17677 (let ((fmt "")
17678 (l nil))
17679 (when (> y 0)
17680 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17681 (push y l))
17682 (when (> d 0)
17683 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17684 (push d l))
17685 (when (> h 0)
17686 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17687 (push h l))
17688 (when (> m 0)
17689 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17690 (push m l))
17691 (apply 'format fmt (nreverse l))))
17693 (defun org-time-string-to-time (s &optional buffer pos)
17694 "Convert a timestamp string into internal time."
17695 (condition-case errdata
17696 (apply 'encode-time (org-parse-time-string s))
17697 (error (error "Bad timestamp `%s'%s\nError was: %s"
17698 s (if (not (and buffer pos))
17700 (format-message " at %d in buffer `%s'" pos buffer))
17701 (cdr errdata)))))
17703 (defun org-time-string-to-seconds (s)
17704 "Convert a timestamp string to a number of seconds."
17705 (float-time (org-time-string-to-time s)))
17707 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17709 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17710 "Convert time stamp S to an absolute day number.
17712 If DAYNR in non-nil, and there is a specifier for a cyclic time
17713 stamp, get the closest date to DAYNR. If PREFER is
17714 `past' (respectively `future') return a date past (respectively
17715 after) or equal to DAYNR.
17717 POS is the location of time stamp S, as a buffer position in
17718 BUFFER.
17720 Diary sexp timestamps are matched against DAYNR, when non-nil.
17721 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17722 signalled."
17723 (cond
17724 ((string-match "\\`%%\\((.*)\\)" s)
17725 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17726 ;; only able to match individual dates. If it fails, raise an
17727 ;; error.
17728 (if (and daynr
17729 (org-diary-sexp-entry
17730 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17731 daynr
17732 (signal 'org-diary-sexp-no-match (list s))))
17733 (daynr (org-closest-date s daynr prefer))
17734 (t (time-to-days
17735 (condition-case errdata
17736 (apply #'encode-time (org-parse-time-string s))
17737 (error (error "Bad timestamp `%s'%s\nError was: %s"
17739 (if (not (and buffer pos)) ""
17740 (format-message " at %d in buffer `%s'" pos buffer))
17741 (cdr errdata))))))))
17743 (defun org-days-to-iso-week (days)
17744 "Return the iso week number."
17745 (require 'cal-iso)
17746 (car (calendar-iso-from-absolute days)))
17748 (defun org-small-year-to-year (year)
17749 "Convert 2-digit years into 4-digit years.
17750 YEAR is expanded into one of the 30 next years, if possible, or
17751 into a past one. Any year larger than 99 is returned unchanged."
17752 (if (>= year 100) year
17753 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17754 (century (/ current 100))
17755 (offset (- year (% current 100))))
17756 (cond ((> offset 30) (+ (* (1- century) 100) year))
17757 ((> offset -70) (+ (* century 100) year))
17758 (t (+ (* (1+ century) 100) year))))))
17760 (defun org-time-from-absolute (d)
17761 "Return the time corresponding to date D.
17762 D may be an absolute day number, or a calendar-type list (month day year)."
17763 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17764 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17766 (defvar org-agenda-current-date)
17767 (defun org-calendar-holiday ()
17768 "List of holidays, for Diary display in Org mode."
17769 (require 'holidays)
17770 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17771 (and hl (mapconcat #'identity hl "; "))))
17773 (defun org-diary-sexp-entry (sexp entry d)
17774 "Process a SEXP diary ENTRY for date D."
17775 (require 'diary-lib)
17776 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17777 ;; dynamically.
17778 (let* ((sexp `(let ((entry ,entry)
17779 (date ',d))
17780 ,(car (read-from-string sexp))))
17781 (result (if calendar-debug-sexp (eval sexp)
17782 (condition-case nil
17783 (eval sexp)
17784 (error
17785 (beep)
17786 (message "Bad sexp at line %d in %s: %s"
17787 (org-current-line)
17788 (buffer-file-name) sexp)
17789 (sleep-for 2))))))
17790 (cond ((stringp result) (split-string result "; "))
17791 ((and (consp result)
17792 (not (consp (cdr result)))
17793 (stringp (cdr result))) (cdr result))
17794 ((and (consp result)
17795 (stringp (car result))) result)
17796 (result entry))))
17798 (defun org-diary-to-ical-string (frombuf)
17799 "Get iCalendar entries from diary entries in buffer FROMBUF.
17800 This uses the icalendar.el library."
17801 (let* ((tmpdir temporary-file-directory)
17802 (tmpfile (make-temp-name
17803 (expand-file-name "orgics" tmpdir)))
17804 buf rtn b e)
17805 (with-current-buffer frombuf
17806 (icalendar-export-region (point-min) (point-max) tmpfile)
17807 (setq buf (find-buffer-visiting tmpfile))
17808 (set-buffer buf)
17809 (goto-char (point-min))
17810 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17811 (setq b (match-beginning 0)))
17812 (goto-char (point-max))
17813 (when (re-search-backward "^END:VEVENT" nil t)
17814 (setq e (match-end 0)))
17815 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17816 (kill-buffer buf)
17817 (delete-file tmpfile)
17818 rtn))
17820 (defun org-closest-date (start current prefer)
17821 "Return closest date to CURRENT starting from START.
17823 CURRENT and START are both time stamps.
17825 When PREFER is `past', return a date that is either CURRENT or
17826 past. When PREFER is `future', return a date that is either
17827 CURRENT or future.
17829 Only time stamps with a repeater are modified. Any other time
17830 stamp stay unchanged. In any case, return value is an absolute
17831 day number."
17832 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17833 ;; No repeater. Do not shift time stamp.
17834 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17835 (let ((value (string-to-number (match-string 1 start)))
17836 (type (match-string 2 start)))
17837 (if (= 0 value)
17838 ;; Repeater with a 0-value is considered as void.
17839 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17840 (let* ((base (org-date-to-gregorian start))
17841 (target (org-date-to-gregorian current))
17842 (sday (calendar-absolute-from-gregorian base))
17843 (cday (calendar-absolute-from-gregorian target))
17844 n1 n2)
17845 ;; If START is already past CURRENT, just return START.
17846 (if (<= cday sday) sday
17847 ;; Compute closest date before (N1) and closest date past
17848 ;; (N2) CURRENT.
17849 (pcase type
17850 ("h"
17851 (let ((missing-hours
17852 (mod (+ (- (* 24 (- cday sday))
17853 (nth 2 (org-parse-time-string start)))
17854 org-extend-today-until)
17855 value)))
17856 (setf n1 (if (= missing-hours 0) cday
17857 (- cday (1+ (/ missing-hours 24)))))
17858 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17859 ((or "d" "w")
17860 (let ((value (if (equal type "w") (* 7 value) value)))
17861 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17862 (setf n2 (+ n1 value))))
17863 ("m"
17864 (let* ((add-months
17865 (lambda (d n)
17866 ;; Add N months to gregorian date D, i.e.,
17867 ;; a list (MONTH DAY YEAR). Return a valid
17868 ;; gregorian date.
17869 (let ((m (+ (nth 0 d) n)))
17870 (list (mod m 12)
17871 (nth 1 d)
17872 (+ (/ m 12) (nth 2 d))))))
17873 (months ; Complete months to TARGET.
17874 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17875 (- (nth 0 target) (nth 0 base))
17876 ;; If START's day is greater than
17877 ;; TARGET's, remove incomplete month.
17878 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17879 value)
17880 value))
17881 (before (funcall add-months base months)))
17882 (setf n1 (calendar-absolute-from-gregorian before))
17883 (setf n2
17884 (calendar-absolute-from-gregorian
17885 (funcall add-months before value)))))
17887 (let* ((d (nth 1 base))
17888 (m (nth 0 base))
17889 (y (nth 2 base))
17890 (years ; Complete years to TARGET.
17891 (* (/ (- (nth 2 target)
17893 ;; If START's month and day are
17894 ;; greater than TARGET's, remove
17895 ;; incomplete year.
17896 (if (or (> (nth 0 target) m)
17897 (and (= (nth 0 target) m)
17898 (> (nth 1 target) d)))
17901 value)
17902 value))
17903 (before (list m d (+ y years))))
17904 (setf n1 (calendar-absolute-from-gregorian before))
17905 (setf n2 (calendar-absolute-from-gregorian
17906 (list m d (+ (nth 2 before) value)))))))
17907 ;; Handle PREFER parameter, if any.
17908 (cond
17909 ((eq prefer 'past) (if (= cday n2) n2 n1))
17910 ((eq prefer 'future) (if (= cday n1) n1 n2))
17911 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17913 (defun org-date-to-gregorian (d)
17914 "Turn any specification of date D into a Gregorian date for the calendar."
17915 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17916 ((and (listp d) (= (length d) 3)) d)
17917 ((stringp d)
17918 (let ((d (org-parse-time-string d)))
17919 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17920 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17922 (defun org-parse-time-string (s &optional nodefault)
17923 "Parse the standard Org time string.
17924 This should be a lot faster than the normal `parse-time-string'.
17925 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17926 hour and minute fields will be nil if not given."
17927 (cond ((string-match org-ts-regexp0 s)
17928 (list 0
17929 (when (or (match-beginning 8) (not nodefault))
17930 (string-to-number (or (match-string 8 s) "0")))
17931 (when (or (match-beginning 7) (not nodefault))
17932 (string-to-number (or (match-string 7 s) "0")))
17933 (string-to-number (match-string 4 s))
17934 (string-to-number (match-string 3 s))
17935 (string-to-number (match-string 2 s))
17936 nil nil nil))
17937 ((string-match "^<[^>]+>$" s)
17938 (decode-time (seconds-to-time (org-matcher-time s))))
17939 (t (error "Not a standard Org time string: %s" s))))
17941 (defun org-timestamp-up (&optional arg)
17942 "Increase the date item at the cursor by one.
17943 If the cursor is on the year, change the year. If it is on the month,
17944 the day or the time, change that.
17945 With prefix ARG, change by that many units."
17946 (interactive "p")
17947 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17949 (defun org-timestamp-down (&optional arg)
17950 "Decrease the date item at the cursor by one.
17951 If the cursor is on the year, change the year. If it is on the month,
17952 the day or the time, change that.
17953 With prefix ARG, change by that many units."
17954 (interactive "p")
17955 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17957 (defun org-timestamp-up-day (&optional arg)
17958 "Increase the date in the time stamp by one day.
17959 With prefix ARG, change that many days."
17960 (interactive "p")
17961 (if (and (not (org-at-timestamp-p t))
17962 (org-at-heading-p))
17963 (org-todo 'up)
17964 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17966 (defun org-timestamp-down-day (&optional arg)
17967 "Decrease the date in the time stamp by one day.
17968 With prefix ARG, change that many days."
17969 (interactive "p")
17970 (if (and (not (org-at-timestamp-p t))
17971 (org-at-heading-p))
17972 (org-todo 'down)
17973 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17975 (defun org-at-timestamp-p (&optional inactive-ok)
17976 "Non-nil if point is inside a timestamp.
17978 When optional argument INACTIVE-OK is non-nil, also consider
17979 inactive timestamps.
17981 When this function returns a non-nil value, match data is set
17982 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17983 INACTIVE-OK."
17984 (interactive)
17985 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17986 (pos (point))
17987 (ans (or (looking-at tsr)
17988 (save-excursion
17989 (skip-chars-backward "^[<\n\r\t")
17990 (when (> (point) (point-min)) (backward-char 1))
17991 (and (looking-at tsr)
17992 (> (- (match-end 0) pos) -1))))))
17993 (and ans
17994 (boundp 'org-ts-what)
17995 (setq org-ts-what
17996 (cond
17997 ((= pos (match-beginning 0)) 'bracket)
17998 ;; Point is considered to be "on the bracket" whether
17999 ;; it's really on it or right after it.
18000 ((= pos (1- (match-end 0))) 'bracket)
18001 ((= pos (match-end 0)) 'after)
18002 ((org-pos-in-match-range pos 2) 'year)
18003 ((org-pos-in-match-range pos 3) 'month)
18004 ((org-pos-in-match-range pos 7) 'hour)
18005 ((org-pos-in-match-range pos 8) 'minute)
18006 ((or (org-pos-in-match-range pos 4)
18007 (org-pos-in-match-range pos 5)) 'day)
18008 ((and (> pos (or (match-end 8) (match-end 5)))
18009 (< pos (match-end 0)))
18010 (- pos (or (match-end 8) (match-end 5))))
18011 (t 'day))))
18012 ans))
18014 (defun org-toggle-timestamp-type ()
18015 "Toggle the type (<active> or [inactive]) of a time stamp."
18016 (interactive)
18017 (when (org-at-timestamp-p t)
18018 (let ((beg (match-beginning 0)) (end (match-end 0))
18019 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18020 (save-excursion
18021 (goto-char beg)
18022 (while (re-search-forward "[][<>]" end t)
18023 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18024 t t)))
18025 (message "Timestamp is now %sactive"
18026 (if (equal (char-after beg) ?<) "" "in")))))
18028 (defun org-at-clock-log-p nil
18029 "Is the cursor on the clock log line?"
18030 (save-excursion
18031 (beginning-of-line)
18032 (looking-at org-clock-line-re)))
18034 (defvar org-clock-history) ; defined in org-clock.el
18035 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18036 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18037 "Change the date in the time stamp at point.
18038 The date will be changed by N times WHAT. WHAT can be `day', `month',
18039 `year', `minute', `second'. If WHAT is not given, the cursor position
18040 in the timestamp determines what will be changed.
18041 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18042 (let ((origin (point)) origin-cat
18043 with-hm inactive
18044 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18045 org-ts-what
18046 extra rem
18047 ts time time0 fixnext clrgx)
18048 (unless (org-at-timestamp-p t)
18049 (user-error "Not at a timestamp"))
18050 (if (and (not what) (eq org-ts-what 'bracket))
18051 (org-toggle-timestamp-type)
18052 ;; Point isn't on brackets. Remember the part of the time-stamp
18053 ;; the point was in. Indeed, size of time-stamps may change,
18054 ;; but point must be kept in the same category nonetheless.
18055 (setq origin-cat org-ts-what)
18056 (when (and (not what) (not (eq org-ts-what 'day))
18057 org-display-custom-times
18058 (get-text-property (point) 'display)
18059 (not (get-text-property (1- (point)) 'display)))
18060 (setq org-ts-what 'day))
18061 (setq org-ts-what (or what org-ts-what)
18062 inactive (= (char-after (match-beginning 0)) ?\[)
18063 ts (match-string 0))
18064 (replace-match "")
18065 (when (string-match
18066 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18068 (setq extra (match-string 1 ts))
18069 (when suppress-tmp-delay
18070 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18071 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18072 (setq with-hm t))
18073 (setq time0 (org-parse-time-string ts))
18074 (when (and updown
18075 (eq org-ts-what 'minute)
18076 (not current-prefix-arg))
18077 ;; This looks like s-up and s-down. Change by one rounding step.
18078 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18079 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18080 (setcar (cdr time0) (+ (nth 1 time0)
18081 (if (> n 0) (- rem) (- dm rem))))))
18082 (setq time
18083 (apply #'encode-time
18084 (or (car time0) 0)
18085 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18086 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18087 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18088 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18089 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18090 (nthcdr 6 time0)))
18091 (when (and (member org-ts-what '(hour minute))
18092 extra
18093 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18094 (setq extra (org-modify-ts-extra
18095 extra
18096 (if (eq org-ts-what 'hour) 2 5)
18097 n dm)))
18098 (when (integerp org-ts-what)
18099 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18100 (when (eq what 'calendar)
18101 (let ((cal-date (org-get-date-from-calendar)))
18102 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18103 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18104 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18105 (setcar time0 (or (car time0) 0))
18106 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18107 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18108 (setq time (apply 'encode-time time0))))
18109 ;; Insert the new time-stamp, and ensure point stays in the same
18110 ;; category as before (i.e. not after the last position in that
18111 ;; category).
18112 (let ((pos (point)))
18113 ;; Stay before inserted string. `save-excursion' is of no use.
18114 (setq org-last-changed-timestamp
18115 (org-insert-time-stamp time with-hm inactive nil nil extra))
18116 (goto-char pos))
18117 (save-match-data
18118 (looking-at org-ts-regexp3)
18119 (goto-char
18120 (pcase origin-cat
18121 ;; `day' category ends before `hour' if any, or at the end
18122 ;; of the day name.
18123 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18124 (`hour (min (match-end 7) origin))
18125 (`minute (min (1- (match-end 8)) origin))
18126 ((pred integerp) (min (1- (match-end 0)) origin))
18127 ;; Point was right after the time-stamp. However, the
18128 ;; time-stamp length might have changed, so refer to
18129 ;; (match-end 0) instead.
18130 (`after (match-end 0))
18131 ;; `year' and `month' have both fixed size: point couldn't
18132 ;; have moved into another part.
18133 (_ origin))))
18134 ;; Update clock if on a CLOCK line.
18135 (org-clock-update-time-maybe)
18136 ;; Maybe adjust the closest clock in `org-clock-history'
18137 (when org-clock-adjust-closest
18138 (if (not (and (org-at-clock-log-p)
18139 (< 1 (length (delq nil (mapcar 'marker-position
18140 org-clock-history))))))
18141 (message "No clock to adjust")
18142 (cond ((save-excursion ; fix previous clock?
18143 (re-search-backward org-ts-regexp0 nil t)
18144 (looking-back (concat org-clock-string " \\[")
18145 (line-beginning-position)))
18146 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18147 ((save-excursion ; fix next clock?
18148 (re-search-backward org-ts-regexp0 nil t)
18149 (looking-at (concat org-ts-regexp0 "\\] =>")))
18150 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18151 (save-window-excursion
18152 ;; Find closest clock to point, adjust the previous/next one in history
18153 (let* ((p (save-excursion (org-back-to-heading t)))
18154 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18155 (clfixnth
18156 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18157 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18158 (if (not clfixpos)
18159 (message "No clock to adjust")
18160 (save-excursion
18161 (org-goto-marker-or-bmk clfixpos)
18162 (org-show-subtree)
18163 (when (re-search-forward clrgx nil t)
18164 (goto-char (match-beginning 1))
18165 (let (org-clock-adjust-closest)
18166 (org-timestamp-change n org-ts-what updown))
18167 (message "Clock adjusted in %s for heading: %s"
18168 (file-name-nondirectory (buffer-file-name))
18169 (org-get-heading t t)))))))))
18170 ;; Try to recenter the calendar window, if any.
18171 (when (and org-calendar-follow-timestamp-change
18172 (get-buffer-window "*Calendar*" t)
18173 (memq org-ts-what '(day month year)))
18174 (org-recenter-calendar (time-to-days time))))))
18176 (defun org-modify-ts-extra (s pos n dm)
18177 "Change the different parts of the lead-time and repeat fields in timestamp."
18178 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18179 ng h m new rem)
18180 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18181 (cond
18182 ((or (org-pos-in-match-range pos 2)
18183 (org-pos-in-match-range pos 3))
18184 (setq m (string-to-number (match-string 3 s))
18185 h (string-to-number (match-string 2 s)))
18186 (if (org-pos-in-match-range pos 2)
18187 (setq h (+ h n))
18188 (setq n (* dm (with-no-warnings (signum n))))
18189 (unless (= 0 (setq rem (% m dm)))
18190 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18191 (setq m (+ m n)))
18192 (when (< m 0) (setq m (+ m 60) h (1- h)))
18193 (when (> m 59) (setq m (- m 60) h (1+ h)))
18194 (setq h (mod h 24))
18195 (setq ng 1 new (format "-%02d:%02d" h m)))
18196 ((org-pos-in-match-range pos 6)
18197 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18198 ((org-pos-in-match-range pos 5)
18199 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18201 ((org-pos-in-match-range pos 9)
18202 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18203 ((org-pos-in-match-range pos 8)
18204 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18206 (when ng
18207 (setq s (concat
18208 (substring s 0 (match-beginning ng))
18210 (substring s (match-end ng))))))
18213 (defun org-recenter-calendar (d)
18214 "If the calendar is visible, recenter it to date D."
18215 (let ((cwin (get-buffer-window "*Calendar*" t)))
18216 (when cwin
18217 (let ((calendar-move-hook nil))
18218 (with-selected-window cwin
18219 (calendar-goto-date
18220 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18222 (defun org-goto-calendar (&optional arg)
18223 "Go to the Emacs calendar at the current date.
18224 If there is a time stamp in the current line, go to that date.
18225 A prefix ARG can be used to force the current date."
18226 (interactive "P")
18227 (let ((tsr org-ts-regexp) diff
18228 (calendar-move-hook nil)
18229 (calendar-view-holidays-initially-flag nil)
18230 (calendar-view-diary-initially-flag nil))
18231 (when (or (org-at-timestamp-p)
18232 (save-excursion
18233 (beginning-of-line 1)
18234 (looking-at (concat ".*" tsr))))
18235 (let ((d1 (time-to-days (current-time)))
18236 (d2 (time-to-days
18237 (org-time-string-to-time (match-string 1)))))
18238 (setq diff (- d2 d1))))
18239 (calendar)
18240 (calendar-goto-today)
18241 (when (and diff (not arg)) (calendar-forward-day diff))))
18243 (defun org-get-date-from-calendar ()
18244 "Return a list (month day year) of date at point in calendar."
18245 (with-current-buffer "*Calendar*"
18246 (save-match-data
18247 (calendar-cursor-to-date))))
18249 (defun org-date-from-calendar ()
18250 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18251 If there is already a time stamp at the cursor position, update it."
18252 (interactive)
18253 (if (org-at-timestamp-p t)
18254 (org-timestamp-change 0 'calendar)
18255 (let ((cal-date (org-get-date-from-calendar)))
18256 (org-insert-time-stamp
18257 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18259 (defcustom org-effort-durations
18260 `(("min" . 1)
18261 ("h" . 60)
18262 ("d" . ,(* 60 8))
18263 ("w" . ,(* 60 8 5))
18264 ("m" . ,(* 60 8 5 4))
18265 ("y" . ,(* 60 8 5 40)))
18266 "Conversion factor to minutes for an effort modifier.
18268 Each entry has the form (MODIFIER . MINUTES).
18270 In an effort string, a number followed by MODIFIER is multiplied
18271 by the specified number of MINUTES to obtain an effort in
18272 minutes.
18274 For example, if the value of this variable is ((\"hours\" . 60)), then an
18275 effort string \"2hours\" is equivalent to 120 minutes."
18276 :group 'org-agenda
18277 :version "25.2"
18278 :package-version '(Org . "8.3")
18279 :type '(alist :key-type (string :tag "Modifier")
18280 :value-type (number :tag "Minutes")))
18282 (defun org-minutes-to-clocksum-string (m)
18283 "Format number of minutes as a clocksum string.
18284 The format is determined by `org-time-clocksum-format',
18285 `org-time-clocksum-use-fractional' and
18286 `org-time-clocksum-fractional-format' and
18287 `org-time-clocksum-use-effort-durations'."
18288 (let ((clocksum "")
18289 (m (round m)) ; Don't allow fractions of minutes
18290 h d w mo y fmt n)
18291 (setq h (if org-time-clocksum-use-effort-durations
18292 (cdr (assoc "h" org-effort-durations)) 60)
18293 d (if org-time-clocksum-use-effort-durations
18294 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18295 w (if org-time-clocksum-use-effort-durations
18296 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18297 mo (if org-time-clocksum-use-effort-durations
18298 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18299 y (if org-time-clocksum-use-effort-durations
18300 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18301 ;; fractional format
18302 (if org-time-clocksum-use-fractional
18303 (cond
18304 ;; single format string
18305 ((stringp org-time-clocksum-fractional-format)
18306 (format org-time-clocksum-fractional-format (/ m (float h))))
18307 ;; choice of fractional formats for different time units
18308 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18309 (> (/ (truncate m) (* y d h)) 0))
18310 (format fmt (/ m (* y d (float h)))))
18311 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18312 (> (/ (truncate m) (* mo d h)) 0))
18313 (format fmt (/ m (* mo d (float h)))))
18314 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18315 (> (/ (truncate m) (* w d h)) 0))
18316 (format fmt (/ m (* w d (float h)))))
18317 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18318 (> (/ (truncate m) (* d h)) 0))
18319 (format fmt (/ m (* d (float h)))))
18320 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18321 (> (/ (truncate m) h) 0))
18322 (format fmt (/ m (float h))))
18323 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18324 (format fmt m))
18325 ;; fall back to smallest time unit with a format
18326 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18327 (format fmt (/ m (float h))))
18328 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18329 (format fmt (/ m (* d (float h)))))
18330 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18331 (format fmt (/ m (* w d (float h)))))
18332 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18333 (format fmt (/ m (* mo d (float h)))))
18334 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18335 (format fmt (/ m (* y d (float h))))))
18336 ;; standard (non-fractional) format, with single format string
18337 (if (stringp org-time-clocksum-format)
18338 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18339 ;; separate formats components
18340 (and (setq fmt (plist-get org-time-clocksum-format :years))
18341 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18342 (plist-get org-time-clocksum-format :require-years))
18343 (setq clocksum (concat clocksum (format fmt n))
18344 m (- m (* n y d h))))
18345 (and (setq fmt (plist-get org-time-clocksum-format :months))
18346 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18347 (plist-get org-time-clocksum-format :require-months))
18348 (setq clocksum (concat clocksum (format fmt n))
18349 m (- m (* n mo d h))))
18350 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18351 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18352 (plist-get org-time-clocksum-format :require-weeks))
18353 (setq clocksum (concat clocksum (format fmt n))
18354 m (- m (* n w d h))))
18355 (and (setq fmt (plist-get org-time-clocksum-format :days))
18356 (or (> (setq n (/ (truncate m) (* d h))) 0)
18357 (plist-get org-time-clocksum-format :require-days))
18358 (setq clocksum (concat clocksum (format fmt n))
18359 m (- m (* n d h))))
18360 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18361 (or (> (setq n (/ (truncate m) h)) 0)
18362 (plist-get org-time-clocksum-format :require-hours))
18363 (setq clocksum (concat clocksum (format fmt n))
18364 m (- m (* n h))))
18365 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18366 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18367 (setq clocksum (concat clocksum (format fmt m))))
18368 ;; return formatted time duration
18369 clocksum))))
18371 (defun org-hours-to-clocksum-string (n)
18372 (org-minutes-to-clocksum-string (* n 60)))
18374 (defun org-hh:mm-string-to-minutes (s)
18375 "Convert a string H:MM to a number of minutes.
18376 If the string is just a number, interpret it as minutes.
18377 In fact, the first hh:mm or number in the string will be taken,
18378 there can be extra stuff in the string.
18379 If no number is found, the return value is 0."
18380 (cond
18381 ((integerp s) s)
18382 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18383 (+ (* (string-to-number (match-string 1 s)) 60)
18384 (string-to-number (match-string 2 s))))
18385 ((string-match "\\([0-9]+\\)" s)
18386 (string-to-number (match-string 1 s)))
18387 (t 0)))
18389 (defcustom org-image-actual-width t
18390 "Should we use the actual width of images when inlining them?
18392 When set to t, always use the image width.
18394 When set to a number, use imagemagick (when available) to set
18395 the image's width to this value.
18397 When set to a number in a list, try to get the width from any
18398 #+ATTR.* keyword if it matches a width specification like
18400 #+ATTR_HTML: :width 300px
18402 and fall back on that number if none is found.
18404 When set to nil, try to get the width from an #+ATTR.* keyword
18405 and fall back on the original width if none is found.
18407 This requires Emacs >= 24.1, build with imagemagick support."
18408 :group 'org-appearance
18409 :version "24.4"
18410 :package-version '(Org . "8.0")
18411 :type '(choice
18412 (const :tag "Use the image width" t)
18413 (integer :tag "Use a number of pixels")
18414 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18415 (const :tag "Use #+ATTR* or don't resize" nil)))
18417 (defcustom org-agenda-inhibit-startup nil
18418 "Inhibit startup when preparing agenda buffers.
18419 When this variable is t, the initialization of the Org agenda
18420 buffers is inhibited: e.g. the visibility state is not set, the
18421 tables are not re-aligned, etc."
18422 :type 'boolean
18423 :version "24.3"
18424 :group 'org-agenda)
18426 (defcustom org-agenda-ignore-properties nil
18427 "Avoid updating text properties when building the agenda.
18428 Properties are used to prepare buffers for effort estimates,
18429 appointments, statistics and subtree-local categories.
18430 If you don't use these in the agenda, you can add them to this
18431 list and agenda building will be a bit faster.
18432 The value is a list, with zero or more of the symbols `effort', `appt',
18433 `stats' or `category'."
18434 :type '(set :greedy t
18435 (const effort)
18436 (const appt)
18437 (const stats)
18438 (const category))
18439 :version "25.2"
18440 :package-version '(Org . "8.3")
18441 :group 'org-agenda)
18443 (defun org-duration-string-to-minutes (s &optional output-to-string)
18444 "Convert a duration string S to minutes.
18446 A bare number is interpreted as minutes, modifiers can be set by
18447 customizing `org-effort-durations' (which see).
18449 Entries containing a colon are interpreted as H:MM by
18450 `org-hh:mm-string-to-minutes'."
18451 (let ((result 0)
18452 (re (concat "\\([0-9.]+\\) *\\("
18453 (regexp-opt (mapcar 'car org-effort-durations))
18454 "\\)")))
18455 (while (string-match re s)
18456 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18457 (string-to-number (match-string 1 s))))
18458 (setq s (replace-match "" nil t s)))
18459 (setq result (floor result))
18460 (cl-incf result (org-hh:mm-string-to-minutes s))
18461 (if output-to-string (number-to-string result) result)))
18463 ;;;; Files
18465 (defun org-save-all-org-buffers ()
18466 "Save all Org buffers without user confirmation."
18467 (interactive)
18468 (message "Saving all Org buffers...")
18469 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18470 (when (featurep 'org-id) (org-id-locations-save))
18471 (message "Saving all Org buffers... done"))
18473 (defun org-revert-all-org-buffers ()
18474 "Revert all Org buffers.
18475 Prompt for confirmation when there are unsaved changes.
18476 Be sure you know what you are doing before letting this function
18477 overwrite your changes.
18479 This function is useful in a setup where one tracks org files
18480 with a version control system, to revert on one machine after pulling
18481 changes from another. I believe the procedure must be like this:
18483 1. M-x org-save-all-org-buffers
18484 2. Pull changes from the other machine, resolve conflicts
18485 3. M-x org-revert-all-org-buffers"
18486 (interactive)
18487 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18488 (user-error "Abort"))
18489 (save-excursion
18490 (save-window-excursion
18491 (dolist (b (buffer-list))
18492 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18493 (with-current-buffer b buffer-file-name))
18494 (pop-to-buffer-same-window b)
18495 (revert-buffer t 'no-confirm)))
18496 (when (and (featurep 'org-id) org-id-track-globally)
18497 (org-id-locations-load)))))
18499 ;;;; Agenda files
18501 ;;;###autoload
18502 (defun org-switchb (&optional arg)
18503 "Switch between Org buffers.
18505 With `\\[universal-argument]' prefix, restrict available buffers to files.
18507 With `\\[universal-argument] \\[universal-argument]' \
18508 prefix, restrict available buffers to agenda files."
18509 (interactive "P")
18510 (let ((blist (org-buffer-list
18511 (cond ((equal arg '(4)) 'files)
18512 ((equal arg '(16)) 'agenda)))))
18513 (pop-to-buffer-same-window
18514 (completing-read "Org buffer: "
18515 (mapcar #'list (mapcar #'buffer-name blist))
18516 nil t))))
18518 (defun org-buffer-list (&optional predicate exclude-tmp)
18519 "Return a list of Org buffers.
18520 PREDICATE can be `export', `files' or `agenda'.
18522 export restrict the list to Export buffers.
18523 files restrict the list to buffers visiting Org files.
18524 agenda restrict the list to buffers visiting agenda files.
18526 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18527 (let* ((bfn nil)
18528 (agenda-files (and (eq predicate 'agenda)
18529 (mapcar 'file-truename (org-agenda-files t))))
18530 (filter
18531 (cond
18532 ((eq predicate 'files)
18533 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18534 ((eq predicate 'export)
18535 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18536 ((eq predicate 'agenda)
18537 (lambda (b)
18538 (with-current-buffer b
18539 (and (derived-mode-p 'org-mode)
18540 (setq bfn (buffer-file-name b))
18541 (member (file-truename bfn) agenda-files)))))
18542 (t (lambda (b) (with-current-buffer b
18543 (or (derived-mode-p 'org-mode)
18544 (string-match "\\*Org .*Export"
18545 (buffer-name b)))))))))
18546 (delq nil
18547 (mapcar
18548 (lambda(b)
18549 (if (and (funcall filter b)
18550 (or (not exclude-tmp)
18551 (not (string-match "tmp" (buffer-name b)))))
18553 nil))
18554 (buffer-list)))))
18556 (defun org-agenda-files (&optional unrestricted archives)
18557 "Get the list of agenda files.
18558 Optional UNRESTRICTED means return the full list even if a restriction
18559 is currently in place.
18560 When ARCHIVES is t, include all archive files that are really being
18561 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18562 `org-agenda-archives-mode' is t."
18563 (let ((files
18564 (cond
18565 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18566 ((stringp org-agenda-files) (org-read-agenda-file-list))
18567 ((listp org-agenda-files) org-agenda-files)
18568 (t (error "Invalid value of `org-agenda-files'")))))
18569 (setq files (apply 'append
18570 (mapcar (lambda (f)
18571 (if (file-directory-p f)
18572 (directory-files
18573 f t org-agenda-file-regexp)
18574 (list f)))
18575 files)))
18576 (when org-agenda-skip-unavailable-files
18577 (setq files (delq nil
18578 (mapcar (function
18579 (lambda (file)
18580 (and (file-readable-p file) file)))
18581 files))))
18582 (when (or (eq archives t)
18583 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18584 (setq files (org-add-archive-files files)))
18585 files))
18587 (defun org-agenda-file-p (&optional file)
18588 "Return non-nil, if FILE is an agenda file.
18589 If FILE is omitted, use the file associated with the current
18590 buffer."
18591 (let ((fname (or file (buffer-file-name))))
18592 (and fname
18593 (member (file-truename fname)
18594 (mapcar #'file-truename (org-agenda-files t))))))
18596 (defun org-edit-agenda-file-list ()
18597 "Edit the list of agenda files.
18598 Depending on setup, this either uses customize to edit the variable
18599 `org-agenda-files', or it visits the file that is holding the list. In the
18600 latter case, the buffer is set up in a way that saving it automatically kills
18601 the buffer and restores the previous window configuration."
18602 (interactive)
18603 (if (stringp org-agenda-files)
18604 (let ((cw (current-window-configuration)))
18605 (find-file org-agenda-files)
18606 (setq-local org-window-configuration cw)
18607 (add-hook 'after-save-hook
18608 (lambda ()
18609 (set-window-configuration
18610 (prog1 org-window-configuration
18611 (kill-buffer (current-buffer))))
18612 (org-install-agenda-files-menu)
18613 (message "New agenda file list installed"))
18614 nil 'local)
18615 (message "%s" (substitute-command-keys
18616 "Edit list and finish with \\[save-buffer]")))
18617 (customize-variable 'org-agenda-files)))
18619 (defun org-store-new-agenda-file-list (list)
18620 "Set new value for the agenda file list and save it correctly."
18621 (if (stringp org-agenda-files)
18622 (let ((fe (org-read-agenda-file-list t)) b u)
18623 (while (setq b (find-buffer-visiting org-agenda-files))
18624 (kill-buffer b))
18625 (with-temp-file org-agenda-files
18626 (insert
18627 (mapconcat
18628 (lambda (f) ;; Keep un-expanded entries.
18629 (if (setq u (assoc f fe))
18630 (cdr u)
18632 list "\n")
18633 "\n")))
18634 (let ((org-mode-hook nil) (org-inhibit-startup t)
18635 (org-insert-mode-line-in-empty-file nil))
18636 (setq org-agenda-files list)
18637 (customize-save-variable 'org-agenda-files org-agenda-files))))
18639 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18640 "Read the list of agenda files from a file.
18641 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18642 filenames, used by `org-store-new-agenda-file-list' to write back
18643 un-expanded file names."
18644 (when (file-directory-p org-agenda-files)
18645 (error "`org-agenda-files' cannot be a single directory"))
18646 (when (stringp org-agenda-files)
18647 (with-temp-buffer
18648 (insert-file-contents org-agenda-files)
18649 (mapcar
18650 (lambda (f)
18651 (let ((e (expand-file-name (substitute-in-file-name f)
18652 org-directory)))
18653 (if pair-with-expansion
18654 (cons e f)
18655 e)))
18656 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18658 ;;;###autoload
18659 (defun org-cycle-agenda-files ()
18660 "Cycle through the files in `org-agenda-files'.
18661 If the current buffer visits an agenda file, find the next one in the list.
18662 If the current buffer does not, find the first agenda file."
18663 (interactive)
18664 (let* ((fs (or (org-agenda-files t)
18665 (user-error "No agenda files")))
18666 (files (copy-sequence fs))
18667 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18668 file)
18669 (when tcf
18670 (while (and (setq file (pop files))
18671 (not (equal (file-truename file) tcf)))))
18672 (find-file (car (or files fs)))
18673 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18675 (defun org-agenda-file-to-front (&optional to-end)
18676 "Move/add the current file to the top of the agenda file list.
18677 If the file is not present in the list, it is added to the front. If it is
18678 present, it is moved there. With optional argument TO-END, add/move to the
18679 end of the list."
18680 (interactive "P")
18681 (let ((org-agenda-skip-unavailable-files nil)
18682 (file-alist (mapcar (lambda (x)
18683 (cons (file-truename x) x))
18684 (org-agenda-files t)))
18685 (ctf (file-truename
18686 (or buffer-file-name
18687 (user-error "Please save the current buffer to a file"))))
18688 x had)
18689 (setq x (assoc ctf file-alist) had x)
18691 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18692 (if to-end
18693 (setq file-alist (append (delq x file-alist) (list x)))
18694 (setq file-alist (cons x (delq x file-alist))))
18695 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18696 (org-install-agenda-files-menu)
18697 (message "File %s to %s of agenda file list"
18698 (if had "moved" "added") (if to-end "end" "front"))))
18700 (defun org-remove-file (&optional file)
18701 "Remove current file from the list of files in variable `org-agenda-files'.
18702 These are the files which are being checked for agenda entries.
18703 Optional argument FILE means use this file instead of the current."
18704 (interactive)
18705 (let* ((org-agenda-skip-unavailable-files nil)
18706 (file (or file buffer-file-name
18707 (user-error "Current buffer does not visit a file")))
18708 (true-file (file-truename file))
18709 (afile (abbreviate-file-name file))
18710 (files (delq nil (mapcar
18711 (lambda (x)
18712 (unless (equal true-file
18713 (file-truename x))
18715 (org-agenda-files t)))))
18716 (if (not (= (length files) (length (org-agenda-files t))))
18717 (progn
18718 (org-store-new-agenda-file-list files)
18719 (org-install-agenda-files-menu)
18720 (message "Removed from Org Agenda list: %s" afile))
18721 (message "File was not in list: %s (not removed)" afile))))
18723 (defun org-file-menu-entry (file)
18724 (vector file (list 'find-file file) t))
18726 (defun org-check-agenda-file (file)
18727 "Make sure FILE exists. If not, ask user what to do."
18728 (unless (file-exists-p file)
18729 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18730 (abbreviate-file-name file))
18731 (let ((r (downcase (read-char-exclusive))))
18732 (cond
18733 ((equal r ?r)
18734 (org-remove-file file)
18735 (throw 'nextfile t))
18736 (t (user-error "Abort"))))))
18738 (defun org-get-agenda-file-buffer (file)
18739 "Get an agenda buffer visiting FILE.
18740 If the buffer needs to be created, add it to the list of buffers
18741 which might be released later."
18742 (let ((buf (org-find-base-buffer-visiting file)))
18743 (if buf
18744 buf ; just return it
18745 ;; Make a new buffer and remember it
18746 (setq buf (find-file-noselect file))
18747 (when buf (push buf org-agenda-new-buffers))
18748 buf)))
18750 (defun org-release-buffers (blist)
18751 "Release all buffers in list, asking the user for confirmation when needed.
18752 When a buffer is unmodified, it is just killed. When modified, it is saved
18753 \(if the user agrees) and then killed."
18754 (let (file)
18755 (dolist (buf blist)
18756 (setq file (buffer-file-name buf))
18757 (when (and (buffer-modified-p buf)
18758 file
18759 (y-or-n-p (format "Save file %s? " file)))
18760 (with-current-buffer buf (save-buffer)))
18761 (kill-buffer buf))))
18763 (defun org-agenda-prepare-buffers (files)
18764 "Create buffers for all agenda files, protect archived trees and comments."
18765 (interactive)
18766 (let ((pa '(:org-archived t))
18767 (pc '(:org-comment t))
18768 (pall '(:org-archived t :org-comment t))
18769 (inhibit-read-only t)
18770 (org-inhibit-startup org-agenda-inhibit-startup)
18771 (rea (concat ":" org-archive-tag ":"))
18772 re pos)
18773 (setq org-tag-alist-for-agenda nil
18774 org-tag-groups-alist-for-agenda nil)
18775 (save-excursion
18776 (save-restriction
18777 (dolist (file files)
18778 (catch 'nextfile
18779 (if (bufferp file)
18780 (set-buffer file)
18781 (org-check-agenda-file file)
18782 (set-buffer (org-get-agenda-file-buffer file)))
18783 (widen)
18784 (org-set-regexps-and-options 'tags-only)
18785 (setq pos (point))
18786 (or (memq 'category org-agenda-ignore-properties)
18787 (org-refresh-category-properties))
18788 (or (memq 'stats org-agenda-ignore-properties)
18789 (org-refresh-stats-properties))
18790 (or (memq 'effort org-agenda-ignore-properties)
18791 (org-refresh-effort-properties))
18792 (or (memq 'appt org-agenda-ignore-properties)
18793 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18794 (setq org-todo-keywords-for-agenda
18795 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18796 (setq org-done-keywords-for-agenda
18797 (append org-done-keywords-for-agenda org-done-keywords))
18798 (setq org-todo-keyword-alist-for-agenda
18799 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18800 (setq org-tag-alist-for-agenda
18801 (org-uniquify
18802 (append org-tag-alist-for-agenda
18803 org-current-tag-alist)))
18804 ;; Merge current file's tag groups into global
18805 ;; `org-tag-groups-alist-for-agenda'.
18806 (when org-group-tags
18807 (dolist (alist org-tag-groups-alist)
18808 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18809 (if old
18810 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18811 (push alist org-tag-groups-alist-for-agenda)))))
18812 (org-with-silent-modifications
18813 (save-excursion
18814 (remove-text-properties (point-min) (point-max) pall)
18815 (when org-agenda-skip-archived-trees
18816 (goto-char (point-min))
18817 (while (re-search-forward rea nil t)
18818 (when (org-at-heading-p t)
18819 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18820 (goto-char (point-min))
18821 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18822 (while (re-search-forward re nil t)
18823 (when (save-match-data (org-in-commented-heading-p t))
18824 (add-text-properties
18825 (match-beginning 0) (org-end-of-subtree t) pc)))))
18826 (goto-char pos)))))
18827 (setq org-todo-keywords-for-agenda
18828 (org-uniquify org-todo-keywords-for-agenda))
18829 (setq org-todo-keyword-alist-for-agenda
18830 (org-uniquify org-todo-keyword-alist-for-agenda))))
18833 ;;;; CDLaTeX minor mode
18835 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18836 "Keymap for the minor `org-cdlatex-mode'.")
18838 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18839 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18840 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18841 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18842 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18844 (defvar org-cdlatex-texmathp-advice-is-done nil
18845 "Flag remembering if we have applied the advice to texmathp already.")
18847 (define-minor-mode org-cdlatex-mode
18848 "Toggle the minor `org-cdlatex-mode'.
18849 This mode supports entering LaTeX environment and math in LaTeX fragments
18850 in Org mode.
18851 \\{org-cdlatex-mode-map}"
18852 nil " OCDL" nil
18853 (when org-cdlatex-mode
18854 (require 'cdlatex)
18855 (run-hooks 'cdlatex-mode-hook)
18856 (cdlatex-compute-tables))
18857 (unless org-cdlatex-texmathp-advice-is-done
18858 (setq org-cdlatex-texmathp-advice-is-done t)
18859 (defadvice texmathp (around org-math-always-on activate)
18860 "Always return t in Org buffers.
18861 This is because we want to insert math symbols without dollars even outside
18862 the LaTeX math segments. If Org mode thinks that point is actually inside
18863 an embedded LaTeX fragment, let `texmathp' do its job.
18864 `\\[org-cdlatex-mode-map]'"
18865 (interactive)
18866 (let (p)
18867 (cond
18868 ((not (derived-mode-p 'org-mode)) ad-do-it)
18869 ((eq this-command 'cdlatex-math-symbol)
18870 (setq ad-return-value t
18871 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18873 (let ((p (org-inside-LaTeX-fragment-p)))
18874 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18875 (setq ad-return-value t
18876 texmathp-why '("Org mode embedded math" . 0))
18877 (when p ad-do-it)))))))))
18879 (defun turn-on-org-cdlatex ()
18880 "Unconditionally turn on `org-cdlatex-mode'."
18881 (org-cdlatex-mode 1))
18883 (defun org-try-cdlatex-tab ()
18884 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18885 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18886 - inside a LaTeX fragment, or
18887 - after the first word in a line, where an abbreviation expansion could
18888 insert a LaTeX environment."
18889 (when org-cdlatex-mode
18890 (cond
18891 ;; Before any word on the line: No expansion possible.
18892 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18893 ;; Just after first word on the line: Expand it. Make sure it
18894 ;; cannot happen on headlines, though.
18895 ((save-excursion
18896 (skip-chars-backward "a-zA-Z0-9*")
18897 (skip-chars-backward " \t")
18898 (and (bolp) (not (org-at-heading-p))))
18899 (cdlatex-tab) t)
18900 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18902 (defun org-cdlatex-underscore-caret (&optional _arg)
18903 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18904 Revert to the normal definition outside of these fragments."
18905 (interactive "P")
18906 (if (org-inside-LaTeX-fragment-p)
18907 (call-interactively 'cdlatex-sub-superscript)
18908 (let (org-cdlatex-mode)
18909 (call-interactively (key-binding (vector last-input-event))))))
18911 (defun org-cdlatex-math-modify (&optional _arg)
18912 "Execute `cdlatex-math-modify' in LaTeX fragments.
18913 Revert to the normal definition outside of these fragments."
18914 (interactive "P")
18915 (if (org-inside-LaTeX-fragment-p)
18916 (call-interactively 'cdlatex-math-modify)
18917 (let (org-cdlatex-mode)
18918 (call-interactively (key-binding (vector last-input-event))))))
18920 (defun org-cdlatex-environment-indent (&optional environment item)
18921 "Execute `cdlatex-environment' and indent the inserted environment.
18923 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18925 The inserted environment is indented to current indentation
18926 unless point is at the beginning of the line, in which the
18927 environment remains unintended."
18928 (interactive)
18929 ;; cdlatex-environment always return nil. Therefore, capture output
18930 ;; first and determine if an environment was selected.
18931 (let* ((beg (point-marker))
18932 (end (copy-marker (point) t))
18933 (inserted (progn
18934 (ignore-errors (cdlatex-environment environment item))
18935 (< beg end)))
18936 ;; Figure out how many lines to move forward after the
18937 ;; environment has been inserted.
18938 (lines (when inserted
18939 (save-excursion
18940 (- (cl-loop while (< beg (point))
18941 with x = 0
18942 do (forward-line -1)
18943 (cl-incf x)
18944 finally return x)
18945 (if (progn (goto-char beg)
18946 (and (progn (skip-chars-forward " \t") (eolp))
18947 (progn (skip-chars-backward " \t") (bolp))))
18948 1 0)))))
18949 (env (org-trim (delete-and-extract-region beg end))))
18950 (when inserted
18951 ;; Get indentation of next line unless at column 0.
18952 (let ((ind (if (bolp) 0
18953 (save-excursion
18954 (org-return-indent)
18955 (prog1 (org-get-indentation)
18956 (when (progn (skip-chars-forward " \t") (eolp))
18957 (delete-region beg (point)))))))
18958 (bol (progn (skip-chars-backward " \t") (bolp))))
18959 ;; Insert a newline before environment unless at column zero
18960 ;; to "escape" the current line. Insert a newline if
18961 ;; something is one the same line as \end{ENVIRONMENT}.
18962 (insert
18963 (concat (unless bol "\n") env
18964 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18965 (unless (zerop ind)
18966 (save-excursion
18967 (goto-char beg)
18968 (while (< (point) end)
18969 (unless (eolp) (indent-line-to ind))
18970 (forward-line))))
18971 (goto-char beg)
18972 (forward-line lines)
18973 (indent-line-to ind)))
18974 (set-marker beg nil)
18975 (set-marker end nil)))
18978 ;;;; LaTeX fragments
18980 (defun org-inside-LaTeX-fragment-p ()
18981 "Test if point is inside a LaTeX fragment.
18982 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18983 sequence appearing also before point.
18984 Even though the matchers for math are configurable, this function assumes
18985 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18986 delimiters are skipped when they have been removed by customization.
18987 The return value is nil, or a cons cell with the delimiter and the
18988 position of this delimiter.
18990 This function does a reasonably good job, but can locally be fooled by
18991 for example currency specifications. For example it will assume being in
18992 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18993 fragments that are properly closed, but during editing, we have to live
18994 with the uncertainty caused by missing closing delimiters. This function
18995 looks only before point, not after."
18996 (catch 'exit
18997 (let ((pos (point))
18998 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18999 (lim (progn
19000 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19001 (point)))
19002 dd-on str (start 0) m re)
19003 (goto-char pos)
19004 (when dodollar
19005 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19006 re (nth 1 (assoc "$" org-latex-regexps)))
19007 (while (string-match re str start)
19008 (cond
19009 ((= (match-end 0) (length str))
19010 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19011 ((= (match-end 0) (- (length str) 5))
19012 (throw 'exit nil))
19013 (t (setq start (match-end 0))))))
19014 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19015 (goto-char pos)
19016 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19017 (and (match-beginning 2) (throw 'exit nil))
19018 ;; count $$
19019 (while (re-search-backward "\\$\\$" lim t)
19020 (setq dd-on (not dd-on)))
19021 (goto-char pos)
19022 (when dd-on (cons "$$" m))))))
19024 (defun org-inside-latex-macro-p ()
19025 "Is point inside a LaTeX macro or its arguments?"
19026 (save-match-data
19027 (org-in-regexp
19028 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19030 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19031 "Build an overlay between BEG and END using IMAGE file.
19032 Argument IMAGETYPE is the extension of the displayed image,
19033 as a string. It defaults to \"png\"."
19034 (let ((ov (make-overlay beg end))
19035 (imagetype (or (intern imagetype) 'png)))
19036 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19037 (overlay-put ov 'evaporate t)
19038 (overlay-put ov
19039 'modification-hooks
19040 (list (lambda (o _flag _beg _end &optional _l)
19041 (delete-overlay o))))
19042 (overlay-put ov
19043 'display
19044 (list 'image :type imagetype :file image :ascent 'center))))
19046 (defun org--list-latex-overlays (&optional beg end)
19047 "List all Org LaTeX overlays in current buffer.
19048 Limit to overlays between BEG and END when those are provided."
19049 (cl-remove-if-not
19050 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19051 (overlays-in (or beg (point-min)) (or end (point-max)))))
19053 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19054 "Remove all overlays with LaTeX fragment images in current buffer.
19055 When optional arguments BEG and END are non-nil, remove all
19056 overlays between them instead. Return a non-nil value when some
19057 overlays were removed, nil otherwise."
19058 (let ((overlays (org--list-latex-overlays beg end)))
19059 (mapc #'delete-overlay overlays)
19060 overlays))
19062 (defun org-toggle-latex-fragment (&optional arg)
19063 "Preview the LaTeX fragment at point, or all locally or globally.
19065 If the cursor is on a LaTeX fragment, create the image and overlay
19066 it over the source code, if there is none. Remove it otherwise.
19067 If there is no fragment at point, display all fragments in the
19068 current section.
19070 With prefix ARG, preview or clear image for all fragments in the
19071 current subtree or in the whole buffer when used before the first
19072 headline. With a prefix ARG `\\[universal-argument] \
19073 \\[universal-argument]' preview or clear images
19074 for all fragments in the buffer."
19075 (interactive "P")
19076 (when (display-graphic-p)
19077 (catch 'exit
19078 (save-excursion
19079 (let (beg end msg)
19080 (cond
19081 ((or (equal arg '(16))
19082 (and (equal arg '(4))
19083 (org-with-limited-levels (org-before-first-heading-p))))
19084 (if (org-remove-latex-fragment-image-overlays)
19085 (progn (message "LaTeX fragments images removed from buffer")
19086 (throw 'exit nil))
19087 (setq msg "Creating images for buffer...")))
19088 ((equal arg '(4))
19089 (org-with-limited-levels (org-back-to-heading t))
19090 (setq beg (point))
19091 (setq end (progn (org-end-of-subtree t) (point)))
19092 (if (org-remove-latex-fragment-image-overlays beg end)
19093 (progn
19094 (message "LaTeX fragment images removed from subtree")
19095 (throw 'exit nil))
19096 (setq msg "Creating images for subtree...")))
19097 ((let ((datum (org-element-context)))
19098 (when (memq (org-element-type datum)
19099 '(latex-environment latex-fragment))
19100 (setq beg (org-element-property :begin datum))
19101 (setq end (org-element-property :end datum))
19102 (if (org-remove-latex-fragment-image-overlays beg end)
19103 (progn (message "LaTeX fragment image removed")
19104 (throw 'exit nil))
19105 (setq msg "Creating image...")))))
19107 (org-with-limited-levels
19108 (setq beg (if (org-at-heading-p) (line-beginning-position)
19109 (outline-previous-heading)
19110 (point)))
19111 (setq end (progn (outline-next-heading) (point)))
19112 (if (org-remove-latex-fragment-image-overlays beg end)
19113 (progn
19114 (message "LaTeX fragment images removed from section")
19115 (throw 'exit nil))
19116 (setq msg "Creating images for section...")))))
19117 (let ((file (buffer-file-name (buffer-base-buffer))))
19118 (org-format-latex
19119 (concat org-preview-latex-image-directory "org-ltximg")
19120 beg end
19121 ;; Emacs cannot overlay images from remote hosts. Create
19122 ;; it in `temporary-file-directory' instead.
19123 (if (or (not file) (file-remote-p file))
19124 temporary-file-directory
19125 default-directory)
19126 'overlays msg 'forbuffer org-preview-latex-default-process))
19127 (message (concat msg "done")))))))
19129 (defun org-format-latex
19130 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19131 "Replace LaTeX fragments with links to an image.
19133 The function takes care of creating the replacement image.
19135 Only consider fragments between BEG and END when those are
19136 provided.
19138 When optional argument OVERLAYS is non-nil, display the image on
19139 top of the fragment instead of replacing it.
19141 PROCESSING-TYPE is the conversion method to use, as a symbol.
19143 Some of the options can be changed using the variable
19144 `org-format-latex-options', which see."
19145 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19146 (unless (eq processing-type 'verbatim)
19147 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19148 (cnt 0)
19149 checkdir-flag)
19150 (goto-char (or beg (point-min)))
19151 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19152 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19153 (overlay-recenter (or end (point-max))))
19154 (while (re-search-forward math-regexp end t)
19155 (unless (and overlays
19156 (eq (get-char-property (point) 'org-overlay-type)
19157 'org-latex-overlay))
19158 (let* ((context (org-element-context))
19159 (type (org-element-type context)))
19160 (when (memq type '(latex-environment latex-fragment))
19161 (let ((block-type (eq type 'latex-environment))
19162 (value (org-element-property :value context))
19163 (beg (org-element-property :begin context))
19164 (end (save-excursion
19165 (goto-char (org-element-property :end context))
19166 (skip-chars-backward " \r\t\n")
19167 (point))))
19168 (cond
19169 ((eq processing-type 'mathjax)
19170 ;; Prepare for MathJax processing.
19171 (if (not (string-match "\\`\\$\\$?" value))
19172 (goto-char end)
19173 (delete-region beg end)
19174 (if (string= (match-string 0 value) "$$")
19175 (insert "\\[" (substring value 2 -2) "\\]")
19176 (insert "\\(" (substring value 1 -1) "\\)"))))
19177 ((assq processing-type org-preview-latex-process-alist)
19178 ;; Process to an image.
19179 (cl-incf cnt)
19180 (goto-char beg)
19181 (let* ((processing-info
19182 (cdr (assq processing-type org-preview-latex-process-alist)))
19183 (face (face-at-point))
19184 ;; Get the colors from the face at point.
19186 (let ((color (plist-get org-format-latex-options
19187 :foreground)))
19188 (if (and forbuffer (eq color 'auto))
19189 (face-attribute face :foreground nil 'default)
19190 color)))
19192 (let ((color (plist-get org-format-latex-options
19193 :background)))
19194 (if (and forbuffer (eq color 'auto))
19195 (face-attribute face :background nil 'default)
19196 color)))
19197 (hash (sha1 (prin1-to-string
19198 (list org-format-latex-header
19199 org-latex-default-packages-alist
19200 org-latex-packages-alist
19201 org-format-latex-options
19202 forbuffer value fg bg))))
19203 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19204 (absprefix (expand-file-name prefix dir))
19205 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19206 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19207 (sep (and block-type "\n\n"))
19208 (link (concat sep "[[file:" linkfile "]]" sep))
19209 (options
19210 (org-combine-plists
19211 org-format-latex-options
19212 `(:foreground ,fg :background ,bg))))
19213 (when msg (message msg cnt))
19214 (unless checkdir-flag ; Ensure the directory exists.
19215 (setq checkdir-flag t)
19216 (let ((todir (file-name-directory absprefix)))
19217 (unless (file-directory-p todir)
19218 (make-directory todir t))))
19219 (unless (file-exists-p movefile)
19220 (org-create-formula-image
19221 value movefile options forbuffer processing-type))
19222 (if overlays
19223 (progn
19224 (dolist (o (overlays-in beg end))
19225 (when (eq (overlay-get o 'org-overlay-type)
19226 'org-latex-overlay)
19227 (delete-overlay o)))
19228 (org--format-latex-make-overlay beg end movefile imagetype)
19229 (goto-char end))
19230 (delete-region beg end)
19231 (insert
19232 (org-add-props link
19233 (list 'org-latex-src
19234 (replace-regexp-in-string "\"" "" value)
19235 'org-latex-src-embed-type
19236 (if block-type 'paragraph 'character)))))))
19237 ((eq processing-type 'mathml)
19238 ;; Process to MathML.
19239 (unless (org-format-latex-mathml-available-p)
19240 (user-error "LaTeX to MathML converter not configured"))
19241 (cl-incf cnt)
19242 (when msg (message msg cnt))
19243 (goto-char beg)
19244 (delete-region beg end)
19245 (insert (org-format-latex-as-mathml
19246 value block-type prefix dir)))
19248 (error "Unknown conversion process %s for LaTeX fragments"
19249 processing-type)))))))))))
19251 (defun org-create-math-formula (latex-frag &optional mathml-file)
19252 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19253 Use `org-latex-to-mathml-convert-command'. If the conversion is
19254 sucessful, return the portion between \"<math...> </math>\"
19255 elements otherwise return nil. When MATHML-FILE is specified,
19256 write the results in to that file. When invoked as an
19257 interactive command, prompt for LATEX-FRAG, with initial value
19258 set to the current active region and echo the results for user
19259 inspection."
19260 (interactive (list (let ((frag (when (org-region-active-p)
19261 (buffer-substring-no-properties
19262 (region-beginning) (region-end)))))
19263 (read-string "LaTeX Fragment: " frag nil frag))))
19264 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19265 (let* ((tmp-in-file
19266 (let ((file (file-relative-name
19267 (make-temp-name (expand-file-name "ltxmathml-in")))))
19268 (write-region latex-frag nil file)
19269 file))
19270 (tmp-out-file (file-relative-name
19271 (make-temp-name (expand-file-name "ltxmathml-out"))))
19272 (cmd (format-spec
19273 org-latex-to-mathml-convert-command
19274 `((?j . ,(and org-latex-to-mathml-jar-file
19275 (shell-quote-argument
19276 (expand-file-name
19277 org-latex-to-mathml-jar-file))))
19278 (?I . ,(shell-quote-argument tmp-in-file))
19279 (?i . ,latex-frag)
19280 (?o . ,(shell-quote-argument tmp-out-file)))))
19281 mathml shell-command-output)
19282 (when (called-interactively-p 'any)
19283 (unless (org-format-latex-mathml-available-p)
19284 (user-error "LaTeX to MathML converter not configured")))
19285 (message "Running %s" cmd)
19286 (setq shell-command-output (shell-command-to-string cmd))
19287 (setq mathml
19288 (when (file-readable-p tmp-out-file)
19289 (with-current-buffer (find-file-noselect tmp-out-file t)
19290 (goto-char (point-min))
19291 (when (re-search-forward
19292 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19293 (regexp-quote
19294 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19295 nil t)
19296 (prog1 (match-string 0) (kill-buffer))))))
19297 (cond
19298 (mathml
19299 (setq mathml
19300 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19301 (when mathml-file
19302 (write-region mathml nil mathml-file))
19303 (when (called-interactively-p 'any)
19304 (message mathml)))
19305 ((message "LaTeX to MathML conversion failed")
19306 (message shell-command-output)))
19307 (delete-file tmp-in-file)
19308 (when (file-exists-p tmp-out-file)
19309 (delete-file tmp-out-file))
19310 mathml))
19312 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19313 prefix &optional dir)
19314 "Use `org-create-math-formula' but check local cache first."
19315 (let* ((absprefix (expand-file-name prefix dir))
19316 (print-length nil) (print-level nil)
19317 (formula-id (concat
19318 "formula-"
19319 (sha1
19320 (prin1-to-string
19321 (list latex-frag
19322 org-latex-to-mathml-convert-command)))))
19323 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19324 (formula-cache-dir (file-name-directory formula-cache)))
19326 (unless (file-directory-p formula-cache-dir)
19327 (make-directory formula-cache-dir t))
19329 (unless (file-exists-p formula-cache)
19330 (org-create-math-formula latex-frag formula-cache))
19332 (if (file-exists-p formula-cache)
19333 ;; Successful conversion. Return the link to MathML file.
19334 (org-add-props
19335 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19336 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19337 'org-latex-src-embed-type (if latex-frag-type
19338 'paragraph 'character)))
19339 ;; Failed conversion. Return the LaTeX fragment verbatim
19340 latex-frag)))
19342 (declare-function org-export-get-backend "ox" (name))
19343 (declare-function org-export--get-global-options "ox" (&optional backend))
19344 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19345 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19346 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19347 (defun org-create-formula--latex-header ()
19348 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19349 (let ((info (org-combine-plists (org-export--get-global-options
19350 (org-export-get-backend 'latex))
19351 (org-export--get-inbuffer-options
19352 (org-export-get-backend 'latex)))))
19353 (org-latex-guess-babel-language
19354 (org-latex-guess-inputenc
19355 (org-splice-latex-header
19356 org-format-latex-header
19357 org-latex-default-packages-alist
19358 org-latex-packages-alist t
19359 (plist-get info :latex-header)))
19360 info)))
19362 (defun org--get-display-dpi ()
19363 "Get the DPI of the display.
19364 The function assumes that the display has the same pixel width in
19365 the horizontal and vertical directions."
19366 (if (display-graphic-p)
19367 (round (/ (display-pixel-height)
19368 (/ (display-mm-height) 25.4)))
19369 (error "Attempt to calculate the dpi of a non-graphic display")))
19371 (defun org-create-formula-image
19372 (string tofile options buffer &optional processing-type)
19373 "Create an image from LaTeX source using external processes.
19375 The LaTeX STRING is saved to a temporary LaTeX file, then
19376 converted to an image file by process PROCESSING-TYPE defined in
19377 `org-preview-latex-process-alist'. A nil value defaults to
19378 `org-preview-latex-default-process'.
19380 The generated image file is eventually moved to TOFILE.
19382 The OPTIONS argument controls the size, foreground color and
19383 background color of the generated image.
19385 When BUFFER non-nil, this function is used for LaTeX previewing.
19386 Otherwise, it is used to deal with LaTeX snippets showed in
19387 a HTML file."
19388 (let* ((processing-type (or processing-type
19389 org-preview-latex-default-process))
19390 (processing-info
19391 (cdr (assq processing-type org-preview-latex-process-alist)))
19392 (programs (plist-get processing-info :programs))
19393 (error-message (or (plist-get processing-info :message) ""))
19394 (use-xcolor (plist-get processing-info :use-xcolor))
19395 (image-input-type (plist-get processing-info :image-input-type))
19396 (image-output-type (plist-get processing-info :image-output-type))
19397 (post-clean (or (plist-get processing-info :post-clean)
19398 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19399 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19400 (latex-header (or (plist-get processing-info :latex-header)
19401 (org-create-formula--latex-header)))
19402 (latex-compiler (plist-get processing-info :latex-compiler))
19403 (image-converter (plist-get processing-info :image-converter))
19404 (tmpdir temporary-file-directory)
19405 (texfilebase (make-temp-name
19406 (expand-file-name "orgtex" tmpdir)))
19407 (texfile (concat texfilebase ".tex"))
19408 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19409 '(1.0 . 1.0)))
19410 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19411 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19412 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19413 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19414 "Black"))
19415 (bg (or (plist-get options (if buffer :background :html-background))
19416 "Transparent"))
19417 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19418 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19419 (dolist (program programs)
19420 (org-check-external-command program error-message))
19421 (if use-xcolor
19422 (progn (if (eq fg 'default)
19423 (setq fg (org-latex-color :foreground))
19424 (setq fg (org-latex-color-format fg)))
19425 (if (eq bg 'default)
19426 (setq bg (org-latex-color :background))
19427 (setq bg (org-latex-color-format
19428 (if (string= bg "Transparent") "white" bg))))
19429 (with-temp-file texfile
19430 (insert latex-header)
19431 (insert "\n\\begin{document}\n"
19432 "\\definecolor{fg}{rgb}{" fg "}\n"
19433 "\\definecolor{bg}{rgb}{" bg "}\n"
19434 "\n\\pagecolor{bg}\n"
19435 "\n{\\color{fg}\n"
19436 string
19437 "\n}\n"
19438 "\n\\end{document}\n")))
19439 (if (eq fg 'default)
19440 (setq fg (org-dvipng-color :foreground))
19441 (unless (string= fg "Transparent")
19442 (setq fg (org-dvipng-color-format fg))))
19443 (if (eq bg 'default)
19444 (setq bg (org-dvipng-color :background))
19445 (unless (string= bg "Transparent")
19446 (setq bg (org-dvipng-color-format bg))))
19447 (with-temp-file texfile
19448 (insert latex-header)
19449 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19451 (let* ((err-msg (format "Please adjust '%s' part of \
19452 `org-preview-latex-process-alist'."
19453 processing-type))
19454 (image-input-file
19455 (org-compile-file
19456 texfile latex-compiler image-input-type err-msg log-buf))
19457 (image-output-file
19458 (org-compile-file
19459 image-input-file image-converter image-output-type err-msg log-buf
19460 `((?F . ,(shell-quote-argument fg))
19461 (?B . ,(shell-quote-argument bg))
19462 (?D . ,(shell-quote-argument (format "%s" dpi)))
19463 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19464 (copy-file image-output-file tofile 'replace)
19465 (dolist (e post-clean)
19466 (when (file-exists-p (concat texfilebase e))
19467 (delete-file (concat texfilebase e))))
19468 image-output-file)))
19470 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19471 "Fill a LaTeX header template TPL.
19472 In the template, the following place holders will be recognized:
19474 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19475 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19476 [PACKAGES] \\usepackage statements for PKG
19477 [NO-PACKAGES] do not include PKG
19478 [EXTRA] the string EXTRA
19479 [NO-EXTRA] do not include EXTRA
19481 For backward compatibility, if both the positive and the negative place
19482 holder is missing, the positive one (without the \"NO-\") will be
19483 assumed to be present at the end of the template.
19484 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19485 EXTRA is a string.
19486 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19487 (let (rpl (end ""))
19488 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19489 (setq rpl (if (or (match-end 1) (not def-pkg))
19490 "" (org-latex-packages-to-string def-pkg snippets-p t))
19491 tpl (replace-match rpl t t tpl))
19492 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19494 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19495 (setq rpl (if (or (match-end 1) (not pkg))
19496 "" (org-latex-packages-to-string pkg snippets-p t))
19497 tpl (replace-match rpl t t tpl))
19498 (when pkg (setq end
19499 (concat end "\n"
19500 (org-latex-packages-to-string pkg snippets-p)))))
19502 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19503 (setq rpl (if (or (match-end 1) (not extra))
19504 "" (concat extra "\n"))
19505 tpl (replace-match rpl t t tpl))
19506 (when (and extra (string-match "\\S-" extra))
19507 (setq end (concat end "\n" extra))))
19509 (if (string-match "\\S-" end)
19510 (concat tpl "\n" end)
19511 tpl)))
19513 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19514 "Turn an alist of packages into a string with the \\usepackage macros."
19515 (setq pkg (mapconcat (lambda(p)
19516 (cond
19517 ((stringp p) p)
19518 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19519 (format "%% Package %s omitted" (cadr p)))
19520 ((equal "" (car p))
19521 (format "\\usepackage{%s}" (cadr p)))
19523 (format "\\usepackage[%s]{%s}"
19524 (car p) (cadr p)))))
19526 "\n"))
19527 (if newline (concat pkg "\n") pkg))
19529 (defun org-dvipng-color (attr)
19530 "Return a RGB color specification for dvipng."
19531 (org-dvipng-color-format (face-attribute 'default attr nil)))
19533 (defun org-dvipng-color-format (color-name)
19534 "Convert COLOR-NAME to a RGB color value for dvipng."
19535 (apply #'format "rgb %s %s %s"
19536 (mapcar 'org-normalize-color
19537 (color-values color-name))))
19539 (defun org-latex-color (attr)
19540 "Return a RGB color for the LaTeX color package."
19541 (org-latex-color-format (face-attribute 'default attr nil)))
19543 (defun org-latex-color-format (color-name)
19544 "Convert COLOR-NAME to a RGB color value."
19545 (apply #'format "%s,%s,%s"
19546 (mapcar 'org-normalize-color
19547 (color-values color-name))))
19549 (defun org-normalize-color (value)
19550 "Return string to be used as color value for an RGB component."
19551 (format "%g" (/ value 65535.0)))
19555 ;; Image display
19557 (defvar-local org-inline-image-overlays nil)
19559 (defun org-toggle-inline-images (&optional include-linked)
19560 "Toggle the display of inline images.
19561 INCLUDE-LINKED is passed to `org-display-inline-images'."
19562 (interactive "P")
19563 (if org-inline-image-overlays
19564 (progn
19565 (org-remove-inline-images)
19566 (when (called-interactively-p 'interactive)
19567 (message "Inline image display turned off")))
19568 (org-display-inline-images include-linked)
19569 (when (called-interactively-p 'interactive)
19570 (message (if org-inline-image-overlays
19571 (format "%d images displayed inline"
19572 (length org-inline-image-overlays))
19573 "No images to display inline")))))
19575 (defun org-redisplay-inline-images ()
19576 "Refresh the display of inline images."
19577 (interactive)
19578 (if (not org-inline-image-overlays)
19579 (org-toggle-inline-images)
19580 (org-toggle-inline-images)
19581 (org-toggle-inline-images)))
19583 (defun org-display-inline-images (&optional include-linked refresh beg end)
19584 "Display inline images.
19586 An inline image is a link which follows either of these
19587 conventions:
19589 1. Its path is a file with an extension matching return value
19590 from `image-file-name-regexp' and it has no contents.
19592 2. Its description consists in a single link of the previous
19593 type.
19595 When optional argument INCLUDE-LINKED is non-nil, also links with
19596 a text description part will be inlined. This can be nice for
19597 a quick look at those images, but it does not reflect what
19598 exported files will look like.
19600 When optional argument REFRESH is non-nil, refresh existing
19601 images between BEG and END. This will create new image displays
19602 only if necessary. BEG and END default to the buffer
19603 boundaries."
19604 (interactive "P")
19605 (when (display-graphic-p)
19606 (unless refresh
19607 (org-remove-inline-images)
19608 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19609 (org-with-wide-buffer
19610 (goto-char (or beg (point-min)))
19611 (let ((case-fold-search t)
19612 (file-extension-re (image-file-name-regexp)))
19613 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19614 (let ((link (save-match-data (org-element-context))))
19615 ;; Check if we're at an inline image.
19616 (when (and (equal (org-element-property :type link) "file")
19617 (or include-linked
19618 (not (org-element-property :contents-begin link)))
19619 (let ((parent (org-element-property :parent link)))
19620 (or (not (eq (org-element-type parent) 'link))
19621 (not (cdr (org-element-contents parent)))))
19622 (string-match-p file-extension-re
19623 (org-element-property :path link)))
19624 (let ((file (expand-file-name
19625 (org-link-unescape
19626 (org-element-property :path link)))))
19627 (when (file-exists-p file)
19628 (let ((width
19629 ;; Apply `org-image-actual-width' specifications.
19630 (cond
19631 ((not (image-type-available-p 'imagemagick)) nil)
19632 ((eq org-image-actual-width t) nil)
19633 ((listp org-image-actual-width)
19635 ;; First try to find a width among
19636 ;; attributes associated to the paragraph
19637 ;; containing link.
19638 (let ((paragraph
19639 (let ((e link))
19640 (while (and (setq e (org-element-property
19641 :parent e))
19642 (not (eq (org-element-type e)
19643 'paragraph))))
19644 e)))
19645 (when paragraph
19646 (save-excursion
19647 (goto-char (org-element-property :begin paragraph))
19648 (when
19649 (re-search-forward
19650 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19651 (org-element-property
19652 :post-affiliated paragraph)
19654 (string-to-number (match-string 1))))))
19655 ;; Otherwise, fall-back to provided number.
19656 (car org-image-actual-width)))
19657 ((numberp org-image-actual-width)
19658 org-image-actual-width)))
19659 (old (get-char-property-and-overlay
19660 (org-element-property :begin link)
19661 'org-image-overlay)))
19662 (if (and (car-safe old) refresh)
19663 (image-refresh (overlay-get (cdr old) 'display))
19664 (let ((image (create-image file
19665 (and width 'imagemagick)
19667 :width width)))
19668 (when image
19669 (let* ((link
19670 ;; If inline image is the description
19671 ;; of another link, be sure to
19672 ;; consider the latter as the one to
19673 ;; apply the overlay on.
19674 (let ((parent
19675 (org-element-property :parent link)))
19676 (if (eq (org-element-type parent) 'link)
19677 parent
19678 link)))
19679 (ov (make-overlay
19680 (org-element-property :begin link)
19681 (progn
19682 (goto-char
19683 (org-element-property :end link))
19684 (skip-chars-backward " \t")
19685 (point)))))
19686 (overlay-put ov 'display image)
19687 (overlay-put ov 'face 'default)
19688 (overlay-put ov 'org-image-overlay t)
19689 (overlay-put
19690 ov 'modification-hooks
19691 (list 'org-display-inline-remove-overlay))
19692 (push ov org-inline-image-overlays)))))))))))))))
19694 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19695 "Remove inline-display overlay if a corresponding region is modified."
19696 (let ((inhibit-modification-hooks t))
19697 (when (and ov after)
19698 (delete ov org-inline-image-overlays)
19699 (delete-overlay ov))))
19701 (defun org-remove-inline-images ()
19702 "Remove inline display of images."
19703 (interactive)
19704 (mapc #'delete-overlay org-inline-image-overlays)
19705 (setq org-inline-image-overlays nil))
19707 ;;;; Key bindings
19709 ;; Outline functions from `outline-mode-prefix-map'
19710 ;; that can be remapped in Org:
19711 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19712 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19713 (define-key org-mode-map [remap outline-forward-same-level]
19714 'org-forward-heading-same-level)
19715 (define-key org-mode-map [remap outline-backward-same-level]
19716 'org-backward-heading-same-level)
19717 (define-key org-mode-map [remap outline-show-branches]
19718 'org-kill-note-or-show-branches)
19719 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19720 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19721 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19722 (define-key org-mode-map [remap outline-next-visible-heading]
19723 'org-next-visible-heading)
19724 (define-key org-mode-map [remap outline-previous-visible-heading]
19725 'org-previous-visible-heading)
19726 (define-key org-mode-map [remap show-children] 'org-show-children)
19728 ;; Outline functions from `outline-mode-prefix-map' that can not
19729 ;; be remapped in Org:
19731 ;; - the column "key binding" shows whether the Outline function is still
19732 ;; available in Org mode on the same key that it has been bound to in
19733 ;; Outline mode:
19734 ;; - "overridden": key used for a different functionality in Org mode
19735 ;; - else: key still bound to the same Outline function in Org mode
19737 ;; | Outline function | key binding | Org replacement |
19738 ;; |------------------------------------+-------------+--------------------------|
19739 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19740 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19741 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19742 ;; | `show-entry' | overridden | no replacement |
19743 ;; | `show-branches' | `C-c C-k' | still same function |
19744 ;; | `show-subtree' | overridden | visibility cycling |
19745 ;; | `show-all' | overridden | no replacement |
19746 ;; | `hide-subtree' | overridden | visibility cycling |
19747 ;; | `hide-body' | overridden | no replacement |
19748 ;; | `hide-entry' | overridden | visibility cycling |
19749 ;; | `hide-leaves' | overridden | no replacement |
19750 ;; | `hide-sublevels' | overridden | no replacement |
19751 ;; | `hide-other' | overridden | no replacement |
19753 ;; Make `C-c C-x' a prefix key
19754 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19756 ;; TAB key with modifiers
19757 (org-defkey org-mode-map "\C-i" 'org-cycle)
19758 (org-defkey org-mode-map [(tab)] 'org-cycle)
19759 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19760 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19761 ;; The following line is necessary under Suse GNU/Linux
19762 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19763 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19764 (define-key org-mode-map [backtab] 'org-shifttab)
19766 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19767 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19768 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19770 ;; Cursor keys with modifiers
19771 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19772 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19773 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19774 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19776 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19777 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19778 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19779 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19780 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19781 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19783 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19784 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19785 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19786 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19788 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19789 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19790 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19791 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19793 ;; Babel keys
19794 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19795 (dolist (pair org-babel-key-bindings)
19796 (define-key org-babel-map (car pair) (cdr pair)))
19798 ;;; Extra keys for tty access.
19799 ;; We only set them when really needed because otherwise the
19800 ;; menus don't show the simple keys
19802 (when (or org-use-extra-keys (not window-system))
19803 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19804 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19805 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19806 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19807 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19808 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19809 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19810 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19811 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19812 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19813 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19814 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19815 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19816 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19817 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19818 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19819 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19820 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19821 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19822 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19823 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19824 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19825 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19826 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19827 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19828 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19829 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19830 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19832 ;; All the other keys
19834 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19835 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19836 (if (boundp 'narrow-map)
19837 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19838 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19839 (if (boundp 'narrow-map)
19840 (org-defkey narrow-map "b" 'org-narrow-to-block)
19841 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19842 (if (boundp 'narrow-map)
19843 (org-defkey narrow-map "e" 'org-narrow-to-element)
19844 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19845 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19846 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19847 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19848 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19849 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19850 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19851 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19852 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19853 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19854 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19855 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19856 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19857 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19858 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19859 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19860 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19861 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19862 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19863 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19864 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19865 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19866 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19867 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19868 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19869 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19870 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19871 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19872 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19873 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19874 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19875 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19876 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19877 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19878 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19879 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19880 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19881 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19882 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19883 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19884 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19885 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19886 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19887 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19888 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19889 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19890 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19891 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19892 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19893 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19894 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19895 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19896 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19897 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19898 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19899 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19900 (org-defkey org-mode-map "\C-c^" 'org-sort)
19901 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19902 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19903 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19904 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19905 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19906 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19907 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19908 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19909 (org-defkey org-mode-map "\C-m" 'org-return)
19910 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19911 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19912 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19913 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19914 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19915 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19916 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19917 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19918 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19919 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19920 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19921 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19922 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19923 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19924 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19925 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19926 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19927 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19928 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19929 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19930 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19931 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19932 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19933 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19934 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19936 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19937 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19938 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19940 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19941 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19942 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19943 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19944 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19945 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19946 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19947 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19948 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19949 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19950 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19951 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19952 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19953 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19954 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19955 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19956 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19957 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19958 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19959 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19960 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19961 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19963 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19964 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19965 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19966 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19967 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19969 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19971 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19973 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19974 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19976 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19979 (defconst org-speed-commands-default
19981 ("Outline Navigation")
19982 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19983 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19984 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19985 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19986 ("F" . org-next-block)
19987 ("B" . org-previous-block)
19988 ("u" . (org-speed-move-safe 'outline-up-heading))
19989 ("j" . org-goto)
19990 ("g" . (org-refile t))
19991 ("Outline Visibility")
19992 ("c" . org-cycle)
19993 ("C" . org-shifttab)
19994 (" " . org-display-outline-path)
19995 ("s" . org-narrow-to-subtree)
19996 ("=" . org-columns)
19997 ("Outline Structure Editing")
19998 ("U" . org-metaup)
19999 ("D" . org-metadown)
20000 ("r" . org-metaright)
20001 ("l" . org-metaleft)
20002 ("R" . org-shiftmetaright)
20003 ("L" . org-shiftmetaleft)
20004 ("i" . (progn (forward-char 1) (call-interactively
20005 'org-insert-heading-respect-content)))
20006 ("^" . org-sort)
20007 ("w" . org-refile)
20008 ("a" . org-archive-subtree-default-with-confirmation)
20009 ("@" . org-mark-subtree)
20010 ("#" . org-toggle-comment)
20011 ("Clock Commands")
20012 ("I" . org-clock-in)
20013 ("O" . org-clock-out)
20014 ("Meta Data Editing")
20015 ("t" . org-todo)
20016 ("," . (org-priority))
20017 ("0" . (org-priority ?\ ))
20018 ("1" . (org-priority ?A))
20019 ("2" . (org-priority ?B))
20020 ("3" . (org-priority ?C))
20021 (":" . org-set-tags-command)
20022 ("e" . org-set-effort)
20023 ("E" . org-inc-effort)
20024 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20025 (org-entry-put (point) "APPT_WARNTIME" m)))
20026 ("Agenda Views etc")
20027 ("v" . org-agenda)
20028 ("/" . org-sparse-tree)
20029 ("Misc")
20030 ("o" . org-open-at-point)
20031 ("?" . org-speed-command-help)
20032 ("<" . (org-agenda-set-restriction-lock 'subtree))
20033 (">" . (org-agenda-remove-restriction-lock))
20035 "The default speed commands.")
20037 (defun org-print-speed-command (e)
20038 (if (> (length (car e)) 1)
20039 (progn
20040 (princ "\n")
20041 (princ (car e))
20042 (princ "\n")
20043 (princ (make-string (length (car e)) ?-))
20044 (princ "\n"))
20045 (princ (car e))
20046 (princ " ")
20047 (if (symbolp (cdr e))
20048 (princ (symbol-name (cdr e)))
20049 (prin1 (cdr e)))
20050 (princ "\n")))
20052 (defun org-speed-command-help ()
20053 "Show the available speed commands."
20054 (interactive)
20055 (if (not org-use-speed-commands)
20056 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20057 (with-output-to-temp-buffer "*Help*"
20058 (princ "User-defined Speed commands\n===========================\n")
20059 (mapc #'org-print-speed-command org-speed-commands-user)
20060 (princ "\n")
20061 (princ "Built-in Speed commands\n=======================\n")
20062 (mapc #'org-print-speed-command org-speed-commands-default))
20063 (with-current-buffer "*Help*"
20064 (setq truncate-lines t))))
20066 (defun org-speed-move-safe (cmd)
20067 "Execute CMD, but make sure that the cursor always ends up in a headline.
20068 If not, return to the original position and throw an error."
20069 (interactive)
20070 (let ((pos (point)))
20071 (call-interactively cmd)
20072 (unless (and (bolp) (org-at-heading-p))
20073 (goto-char pos)
20074 (error "Boundary reached while executing %s" cmd))))
20076 (defvar org-self-insert-command-undo-counter 0)
20078 (defvar org-table-auto-blank-field) ; defined in org-table.el
20079 (defvar org-speed-command nil)
20081 (defun org-speed-command-activate (keys)
20082 "Hook for activating single-letter speed commands.
20083 `org-speed-commands-default' specifies a minimal command set.
20084 Use `org-speed-commands-user' for further customization."
20085 (when (or (and (bolp) (looking-at org-outline-regexp))
20086 (and (functionp org-use-speed-commands)
20087 (funcall org-use-speed-commands)))
20088 (cdr (assoc keys (append org-speed-commands-user
20089 org-speed-commands-default)))))
20091 (defun org-babel-speed-command-activate (keys)
20092 "Hook for activating single-letter code block commands."
20093 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20094 (cdr (assoc keys org-babel-key-bindings))))
20096 (defcustom org-speed-command-hook
20097 '(org-speed-command-activate org-babel-speed-command-activate)
20098 "Hook for activating speed commands at strategic locations.
20099 Hook functions are called in sequence until a valid handler is
20100 found.
20102 Each hook takes a single argument, a user-pressed command key
20103 which is also a `self-insert-command' from the global map.
20105 Within the hook, examine the cursor position and the command key
20106 and return nil or a valid handler as appropriate. Handler could
20107 be one of an interactive command, a function, or a form.
20109 Set `org-use-speed-commands' to non-nil value to enable this
20110 hook. The default setting is `org-speed-command-activate'."
20111 :group 'org-structure
20112 :version "24.1"
20113 :type 'hook)
20115 (defun org-self-insert-command (N)
20116 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20117 If the cursor is in a table looking at whitespace, the whitespace is
20118 overwritten, and the table is not marked as requiring realignment."
20119 (interactive "p")
20120 (org-check-before-invisible-edit 'insert)
20121 (cond
20122 ((and org-use-speed-commands
20123 (let ((kv (this-command-keys-vector)))
20124 (setq org-speed-command
20125 (run-hook-with-args-until-success
20126 'org-speed-command-hook
20127 (make-string 1 (aref kv (1- (length kv))))))))
20128 (cond
20129 ((commandp org-speed-command)
20130 (setq this-command org-speed-command)
20131 (call-interactively org-speed-command))
20132 ((functionp org-speed-command)
20133 (funcall org-speed-command))
20134 ((and org-speed-command (listp org-speed-command))
20135 (eval org-speed-command))
20136 (t (let (org-use-speed-commands)
20137 (call-interactively 'org-self-insert-command)))))
20138 ((and
20139 (org-at-table-p)
20140 (progn
20141 ;; Check if we blank the field, and if that triggers align.
20142 (and (featurep 'org-table) org-table-auto-blank-field
20143 (memq last-command
20144 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20145 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20146 ;; Got extra space, this field does not determine
20147 ;; column width.
20148 (let (org-table-may-need-update) (org-table-blank-field))
20149 ;; No extra space, this field may determine column
20150 ;; width.
20151 (org-table-blank-field)))
20153 (eq N 1)
20154 (looking-at "[^|\n]* \\( \\)|"))
20155 ;; There is room for insertion without re-aligning the table.
20156 (delete-region (match-beginning 1) (match-end 1))
20157 (self-insert-command N))
20159 (setq org-table-may-need-update t)
20160 (self-insert-command N)
20161 (org-fix-tags-on-the-fly)
20162 (when org-self-insert-cluster-for-undo
20163 (if (not (eq last-command 'org-self-insert-command))
20164 (setq org-self-insert-command-undo-counter 1)
20165 (if (>= org-self-insert-command-undo-counter 20)
20166 (setq org-self-insert-command-undo-counter 1)
20167 (and (> org-self-insert-command-undo-counter 0)
20168 buffer-undo-list (listp buffer-undo-list)
20169 (not (cadr buffer-undo-list)) ; remove nil entry
20170 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20171 (setq org-self-insert-command-undo-counter
20172 (1+ org-self-insert-command-undo-counter))))))))
20174 (defun org-check-before-invisible-edit (kind)
20175 "Check is editing if kind KIND would be dangerous with invisible text around.
20176 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20177 ;; First, try to get out of here as quickly as possible, to reduce overhead
20178 (when (and org-catch-invisible-edits
20179 (or (not (boundp 'visible-mode)) (not visible-mode))
20180 (or (get-char-property (point) 'invisible)
20181 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20182 ;; OK, we need to take a closer look
20183 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20184 (invisible-before-point (unless (bobp) (get-char-property
20185 (1- (point)) 'invisible)))
20186 (border-and-ok-direction
20188 ;; Check if we are acting predictably before invisible text
20189 (and invisible-at-point (not invisible-before-point)
20190 (memq kind '(insert delete-backward)))
20191 ;; Check if we are acting predictably after invisible text
20192 ;; This works not well, and I have turned it off. It seems
20193 ;; better to always show and stop after invisible text.
20194 ;; (and (not invisible-at-point) invisible-before-point
20195 ;; (memq kind '(insert delete)))
20197 (when (or (memq invisible-at-point '(outline org-hide-block t))
20198 (memq invisible-before-point '(outline org-hide-block t)))
20199 (when (eq org-catch-invisible-edits 'error)
20200 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20201 (if (and org-custom-properties-overlays
20202 (y-or-n-p "Display invisible properties in this buffer? "))
20203 (org-toggle-custom-properties-visibility)
20204 ;; Make the area visible
20205 (save-excursion
20206 (when invisible-before-point
20207 (goto-char (previous-single-char-property-change
20208 (point) 'invisible)))
20209 (outline-show-subtree))
20210 (cond
20211 ((eq org-catch-invisible-edits 'show)
20212 ;; That's it, we do the edit after showing
20213 (message
20214 "Unfolding invisible region around point before editing")
20215 (sit-for 1))
20216 ((and (eq org-catch-invisible-edits 'smart)
20217 border-and-ok-direction)
20218 (message "Unfolding invisible region around point before editing"))
20220 ;; Don't do the edit, make the user repeat it in full visibility
20221 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20223 (defun org-fix-tags-on-the-fly ()
20224 "Align tags in headline at point.
20225 Unlike to `org-set-tags', it ignores region and sorting."
20226 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20227 (org-at-heading-p))
20228 (let ((org-ignore-region t)
20229 (org-tags-sort-function nil))
20230 (org-set-tags nil t))))
20232 (defun org-delete-backward-char (N)
20233 "Like `delete-backward-char', insert whitespace at field end in tables.
20234 When deleting backwards, in tables this function will insert whitespace in
20235 front of the next \"|\" separator, to keep the table aligned. The table will
20236 still be marked for re-alignment if the field did fill the entire column,
20237 because, in this case the deletion might narrow the column."
20238 (interactive "p")
20239 (save-match-data
20240 (org-check-before-invisible-edit 'delete-backward)
20241 (if (and (org-at-table-p)
20242 (eq N 1)
20243 (string-match "|" (buffer-substring (point-at-bol) (point)))
20244 (looking-at ".*?|"))
20245 (let ((pos (point))
20246 (noalign (looking-at "[^|\n\r]* |"))
20247 (c org-table-may-need-update))
20248 (backward-delete-char N)
20249 (unless overwrite-mode
20250 (skip-chars-forward "^|")
20251 (insert " ")
20252 (goto-char (1- pos)))
20253 ;; noalign: if there were two spaces at the end, this field
20254 ;; does not determine the width of the column.
20255 (when noalign (setq org-table-may-need-update c)))
20256 (backward-delete-char N)
20257 (org-fix-tags-on-the-fly))))
20259 (defun org-delete-char (N)
20260 "Like `delete-char', but insert whitespace at field end in tables.
20261 When deleting characters, in tables this function will insert whitespace in
20262 front of the next \"|\" separator, to keep the table aligned. The table will
20263 still be marked for re-alignment if the field did fill the entire column,
20264 because, in this case the deletion might narrow the column."
20265 (interactive "p")
20266 (save-match-data
20267 (org-check-before-invisible-edit 'delete)
20268 (if (and (org-at-table-p)
20269 (not (bolp))
20270 (not (= (char-after) ?|))
20271 (eq N 1))
20272 (if (looking-at ".*?|")
20273 (let ((pos (point))
20274 (noalign (looking-at "[^|\n\r]* |"))
20275 (c org-table-may-need-update))
20276 (replace-match
20277 (concat (substring (match-string 0) 1 -1) " |") nil t)
20278 (goto-char pos)
20279 ;; noalign: if there were two spaces at the end, this field
20280 ;; does not determine the width of the column.
20281 (when noalign (setq org-table-may-need-update c)))
20282 (delete-char N))
20283 (delete-char N)
20284 (org-fix-tags-on-the-fly))))
20286 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20287 (put 'org-self-insert-command 'delete-selection
20288 (lambda ()
20289 (not (run-hook-with-args-until-success
20290 'self-insert-uses-region-functions))))
20291 (put 'orgtbl-self-insert-command 'delete-selection
20292 (lambda ()
20293 (not (run-hook-with-args-until-success
20294 'self-insert-uses-region-functions))))
20295 (put 'org-delete-char 'delete-selection 'supersede)
20296 (put 'org-delete-backward-char 'delete-selection 'supersede)
20297 (put 'org-yank 'delete-selection 'yank)
20299 ;; Make `flyspell-mode' delay after some commands
20300 (put 'org-self-insert-command 'flyspell-delayed t)
20301 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20302 (put 'org-delete-char 'flyspell-delayed t)
20303 (put 'org-delete-backward-char 'flyspell-delayed t)
20305 ;; Make pabbrev-mode expand after Org mode commands
20306 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20307 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20309 (defun org-remap (map &rest commands)
20310 "In MAP, remap the functions given in COMMANDS.
20311 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20312 (let (new old)
20313 (while commands
20314 (setq old (pop commands) new (pop commands))
20315 (org-defkey map (vector 'remap old) new))))
20317 (defun org-transpose-words ()
20318 "Transpose words for Org.
20319 This uses the `org-mode-transpose-word-syntax-table' syntax
20320 table, which interprets characters in `org-emphasis-alist' as
20321 word constituents."
20322 (interactive)
20323 (with-syntax-table org-mode-transpose-word-syntax-table
20324 (call-interactively 'transpose-words)))
20325 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20327 (when (eq org-enable-table-editor 'optimized)
20328 ;; If the user wants maximum table support, we need to hijack
20329 ;; some standard editing functions
20330 (org-remap org-mode-map
20331 'self-insert-command 'org-self-insert-command
20332 'delete-char 'org-delete-char
20333 'delete-backward-char 'org-delete-backward-char)
20334 (org-defkey org-mode-map "|" 'org-force-self-insert))
20336 (defvar org-ctrl-c-ctrl-c-hook nil
20337 "Hook for functions attaching themselves to `C-c C-c'.
20339 This can be used to add additional functionality to the C-c C-c
20340 key which executes context-dependent commands. This hook is run
20341 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20342 run after the last test.
20344 Each function will be called with no arguments. The function
20345 must check if the context is appropriate for it to act. If yes,
20346 it should do its thing and then return a non-nil value. If the
20347 context is wrong, just do nothing and return nil.")
20349 (defvar org-ctrl-c-ctrl-c-final-hook nil
20350 "Hook for functions attaching themselves to `C-c C-c'.
20352 This can be used to add additional functionality to the C-c C-c
20353 key which executes context-dependent commands. This hook is run
20354 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20355 before the first test.
20357 Each function will be called with no arguments. The function
20358 must check if the context is appropriate for it to act. If yes,
20359 it should do its thing and then return a non-nil value. If the
20360 context is wrong, just do nothing and return nil.")
20362 (defvar org-tab-first-hook nil
20363 "Hook for functions to attach themselves to TAB.
20364 See `org-ctrl-c-ctrl-c-hook' for more information.
20365 This hook runs as the first action when TAB is pressed, even before
20366 `org-cycle' messes around with the `outline-regexp' to cater for
20367 inline tasks and plain list item folding.
20368 If any function in this hook returns t, any other actions that
20369 would have been caused by TAB (such as table field motion or visibility
20370 cycling) will not occur.")
20372 (defvar org-tab-after-check-for-table-hook nil
20373 "Hook for functions to attach themselves to TAB.
20374 See `org-ctrl-c-ctrl-c-hook' for more information.
20375 This hook runs after it has been established that the cursor is not in a
20376 table, but before checking if the cursor is in a headline or if global cycling
20377 should be done.
20378 If any function in this hook returns t, not other actions like visibility
20379 cycling will be done.")
20381 (defvar org-tab-after-check-for-cycling-hook nil
20382 "Hook for functions to attach themselves to TAB.
20383 See `org-ctrl-c-ctrl-c-hook' for more information.
20384 This hook runs after it has been established that not table field motion and
20385 not visibility should be done because of current context. This is probably
20386 the place where a package like yasnippets can hook in.")
20388 (defvar org-tab-before-tab-emulation-hook nil
20389 "Hook for functions to attach themselves to TAB.
20390 See `org-ctrl-c-ctrl-c-hook' for more information.
20391 This hook runs after every other options for TAB have been exhausted, but
20392 before indentation and \t insertion takes place.")
20394 (defvar org-metaleft-hook nil
20395 "Hook for functions attaching themselves to `M-left'.
20396 See `org-ctrl-c-ctrl-c-hook' for more information.")
20397 (defvar org-metaright-hook nil
20398 "Hook for functions attaching themselves to `M-right'.
20399 See `org-ctrl-c-ctrl-c-hook' for more information.")
20400 (defvar org-metaup-hook nil
20401 "Hook for functions attaching themselves to `M-up'.
20402 See `org-ctrl-c-ctrl-c-hook' for more information.")
20403 (defvar org-metadown-hook nil
20404 "Hook for functions attaching themselves to `M-down'.
20405 See `org-ctrl-c-ctrl-c-hook' for more information.")
20406 (defvar org-shiftmetaleft-hook nil
20407 "Hook for functions attaching themselves to `M-S-left'.
20408 See `org-ctrl-c-ctrl-c-hook' for more information.")
20409 (defvar org-shiftmetaright-hook nil
20410 "Hook for functions attaching themselves to `M-S-right'.
20411 See `org-ctrl-c-ctrl-c-hook' for more information.")
20412 (defvar org-shiftmetaup-hook nil
20413 "Hook for functions attaching themselves to `M-S-up'.
20414 See `org-ctrl-c-ctrl-c-hook' for more information.")
20415 (defvar org-shiftmetadown-hook nil
20416 "Hook for functions attaching themselves to `M-S-down'.
20417 See `org-ctrl-c-ctrl-c-hook' for more information.")
20418 (defvar org-metareturn-hook nil
20419 "Hook for functions attaching themselves to `M-RET'.
20420 See `org-ctrl-c-ctrl-c-hook' for more information.")
20421 (defvar org-shiftup-hook nil
20422 "Hook for functions attaching themselves to `S-up'.
20423 See `org-ctrl-c-ctrl-c-hook' for more information.")
20424 (defvar org-shiftup-final-hook nil
20425 "Hook for functions attaching themselves to `S-up'.
20426 This one runs after all other options except shift-select have been excluded.
20427 See `org-ctrl-c-ctrl-c-hook' for more information.")
20428 (defvar org-shiftdown-hook nil
20429 "Hook for functions attaching themselves to `S-down'.
20430 See `org-ctrl-c-ctrl-c-hook' for more information.")
20431 (defvar org-shiftdown-final-hook nil
20432 "Hook for functions attaching themselves to `S-down'.
20433 This one runs after all other options except shift-select have been excluded.
20434 See `org-ctrl-c-ctrl-c-hook' for more information.")
20435 (defvar org-shiftleft-hook nil
20436 "Hook for functions attaching themselves to `S-left'.
20437 See `org-ctrl-c-ctrl-c-hook' for more information.")
20438 (defvar org-shiftleft-final-hook nil
20439 "Hook for functions attaching themselves to `S-left'.
20440 This one runs after all other options except shift-select have been excluded.
20441 See `org-ctrl-c-ctrl-c-hook' for more information.")
20442 (defvar org-shiftright-hook nil
20443 "Hook for functions attaching themselves to `S-right'.
20444 See `org-ctrl-c-ctrl-c-hook' for more information.")
20445 (defvar org-shiftright-final-hook nil
20446 "Hook for functions attaching themselves to `S-right'.
20447 This one runs after all other options except shift-select have been excluded.
20448 See `org-ctrl-c-ctrl-c-hook' for more information.")
20450 (defun org-modifier-cursor-error ()
20451 "Throw an error, a modified cursor command was applied in wrong context."
20452 (user-error "This command is active in special context like tables, headlines or items"))
20454 (defun org-shiftselect-error ()
20455 "Throw an error because Shift-Cursor command was applied in wrong context."
20456 (if (and (boundp 'shift-select-mode) shift-select-mode)
20457 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20458 (user-error "This command works only in special context like headlines or timestamps")))
20460 (defun org-call-for-shift-select (cmd)
20461 (let ((this-command-keys-shift-translated t))
20462 (call-interactively cmd)))
20464 (defun org-shifttab (&optional arg)
20465 "Global visibility cycling or move to previous table field.
20466 Call `org-table-previous-field' within a table.
20467 When ARG is nil, cycle globally through visibility states.
20468 When ARG is a numeric prefix, show contents of this level."
20469 (interactive "P")
20470 (cond
20471 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20472 ((integerp arg)
20473 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20474 (message "Content view to level: %d" arg)
20475 (org-content (prefix-numeric-value arg2))
20476 (org-cycle-show-empty-lines t)
20477 (setq org-cycle-global-status 'overview)))
20478 (t (call-interactively 'org-global-cycle))))
20480 (defun org-shiftmetaleft ()
20481 "Promote subtree or delete table column.
20482 Calls `org-promote-subtree', `org-outdent-item-tree', or
20483 `org-table-delete-column', depending on context. See the
20484 individual commands for more information."
20485 (interactive)
20486 (cond
20487 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20488 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20489 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20490 ((if (not (org-region-active-p)) (org-at-item-p)
20491 (save-excursion (goto-char (region-beginning))
20492 (org-at-item-p)))
20493 (call-interactively 'org-outdent-item-tree))
20494 (t (org-modifier-cursor-error))))
20496 (defun org-shiftmetaright ()
20497 "Demote subtree or insert table column.
20498 Calls `org-demote-subtree', `org-indent-item-tree', or
20499 `org-table-insert-column', depending on context. See the
20500 individual commands for more information."
20501 (interactive)
20502 (cond
20503 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20504 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20505 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20506 ((if (not (org-region-active-p)) (org-at-item-p)
20507 (save-excursion (goto-char (region-beginning))
20508 (org-at-item-p)))
20509 (call-interactively 'org-indent-item-tree))
20510 (t (org-modifier-cursor-error))))
20512 (defun org-shiftmetaup (&optional _arg)
20513 "Drag the line at point up.
20514 In a table, kill the current row.
20515 On a clock timestamp, update the value of the timestamp like `S-<up>'
20516 but also adjust the previous clocked item in the clock history.
20517 Everywhere else, drag the line at point up."
20518 (interactive "P")
20519 (cond
20520 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20521 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20522 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20523 (call-interactively 'org-timestamp-up)))
20524 (t (call-interactively 'org-drag-line-backward))))
20526 (defun org-shiftmetadown (&optional _arg)
20527 "Drag the line at point down.
20528 In a table, insert an empty row at the current line.
20529 On a clock timestamp, update the value of the timestamp like `S-<down>'
20530 but also adjust the previous clocked item in the clock history.
20531 Everywhere else, drag the line at point down."
20532 (interactive "P")
20533 (cond
20534 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20535 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20536 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20537 (call-interactively 'org-timestamp-down)))
20538 (t (call-interactively 'org-drag-line-forward))))
20540 (defsubst org-hidden-tree-error ()
20541 (user-error
20542 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20544 (defun org-metaleft (&optional _arg)
20545 "Promote heading, list item at point or move table column left.
20547 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20548 depending on context. With no specific context, calls the Emacs
20549 default `backward-word'. See the individual commands for more
20550 information.
20552 This function runs the hook `org-metaleft-hook' as a first step,
20553 and returns at first non-nil value."
20554 (interactive "P")
20555 (cond
20556 ((run-hook-with-args-until-success 'org-metaleft-hook))
20557 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20558 ((org-with-limited-levels
20559 (or (org-at-heading-p)
20560 (and (org-region-active-p)
20561 (save-excursion
20562 (goto-char (region-beginning))
20563 (org-at-heading-p)))))
20564 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20565 (call-interactively 'org-do-promote))
20566 ;; At an inline task.
20567 ((org-at-heading-p)
20568 (call-interactively 'org-inlinetask-promote))
20569 ((or (org-at-item-p)
20570 (and (org-region-active-p)
20571 (save-excursion
20572 (goto-char (region-beginning))
20573 (org-at-item-p))))
20574 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20575 (call-interactively 'org-outdent-item))
20576 (t (call-interactively 'backward-word))))
20578 (defun org-metaright (&optional _arg)
20579 "Demote heading, list item at point or move table column right.
20581 In front of a drawer or a block keyword, indent it correctly.
20583 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20584 `org-indent-drawer' or `org-indent-block' depending on context.
20585 With no specific context, calls the Emacs default `forward-word'.
20586 See the individual commands for more information.
20588 This function runs the hook `org-metaright-hook' as a first step,
20589 and returns at first non-nil value."
20590 (interactive "P")
20591 (cond
20592 ((run-hook-with-args-until-success 'org-metaright-hook))
20593 ((org-at-table-p) (call-interactively 'org-table-move-column))
20594 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20595 ((org-at-block-p) (call-interactively 'org-indent-block))
20596 ((org-with-limited-levels
20597 (or (org-at-heading-p)
20598 (and (org-region-active-p)
20599 (save-excursion
20600 (goto-char (region-beginning))
20601 (org-at-heading-p)))))
20602 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20603 (call-interactively 'org-do-demote))
20604 ;; At an inline task.
20605 ((org-at-heading-p)
20606 (call-interactively 'org-inlinetask-demote))
20607 ((or (org-at-item-p)
20608 (and (org-region-active-p)
20609 (save-excursion
20610 (goto-char (region-beginning))
20611 (org-at-item-p))))
20612 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20613 (call-interactively 'org-indent-item))
20614 (t (call-interactively 'forward-word))))
20616 (defun org-check-for-hidden (what)
20617 "Check if there are hidden headlines/items in the current visual line.
20618 WHAT can be either `headlines' or `items'. If the current line is
20619 an outline or item heading and it has a folded subtree below it,
20620 this function returns t, nil otherwise."
20621 (let ((re (cond
20622 ((eq what 'headlines) org-outline-regexp-bol)
20623 ((eq what 'items) (org-item-beginning-re))
20624 (t (error "This should not happen"))))
20625 beg end)
20626 (save-excursion
20627 (catch 'exit
20628 (unless (org-region-active-p)
20629 (setq beg (point-at-bol))
20630 (beginning-of-line 2)
20631 (while (and (not (eobp)) ;; this is like `next-line'
20632 (get-char-property (1- (point)) 'invisible))
20633 (beginning-of-line 2))
20634 (setq end (point))
20635 (goto-char beg)
20636 (goto-char (point-at-eol))
20637 (setq end (max end (point)))
20638 (while (re-search-forward re end t)
20639 (when (get-char-property (match-beginning 0) 'invisible)
20640 (throw 'exit t))))
20641 nil))))
20643 (defun org-metaup (&optional _arg)
20644 "Move subtree up or move table row up.
20645 Calls `org-move-subtree-up' or `org-table-move-row' or
20646 `org-move-item-up', depending on context. See the individual commands
20647 for more information."
20648 (interactive "P")
20649 (cond
20650 ((run-hook-with-args-until-success 'org-metaup-hook))
20651 ((org-region-active-p)
20652 (let* ((a (min (region-beginning) (region-end)))
20653 (b (1- (max (region-beginning) (region-end))))
20654 (c (save-excursion (goto-char a)
20655 (move-beginning-of-line 0)))
20656 (d (save-excursion (goto-char a)
20657 (move-end-of-line 0) (point))))
20658 (transpose-regions a b c d)
20659 (goto-char c)))
20660 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20661 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20662 ((org-at-item-p) (call-interactively 'org-move-item-up))
20663 (t (org-drag-element-backward))))
20665 (defun org-metadown (&optional _arg)
20666 "Move subtree down or move table row down.
20667 Calls `org-move-subtree-down' or `org-table-move-row' or
20668 `org-move-item-down', depending on context. See the individual
20669 commands for more information."
20670 (interactive "P")
20671 (cond
20672 ((run-hook-with-args-until-success 'org-metadown-hook))
20673 ((org-region-active-p)
20674 (let* ((a (min (region-beginning) (region-end)))
20675 (b (max (region-beginning) (region-end)))
20676 (c (save-excursion (goto-char b)
20677 (move-beginning-of-line 1)))
20678 (d (save-excursion (goto-char b)
20679 (move-end-of-line 1) (1+ (point)))))
20680 (transpose-regions a b c d)
20681 (goto-char d)))
20682 ((org-at-table-p) (call-interactively 'org-table-move-row))
20683 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20684 ((org-at-item-p) (call-interactively 'org-move-item-down))
20685 (t (org-drag-element-forward))))
20687 (defun org-shiftup (&optional arg)
20688 "Increase item in timestamp or increase priority of current headline.
20689 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20690 depending on context. See the individual commands for more information."
20691 (interactive "P")
20692 (cond
20693 ((run-hook-with-args-until-success 'org-shiftup-hook))
20694 ((and org-support-shift-select (org-region-active-p))
20695 (org-call-for-shift-select 'previous-line))
20696 ((org-at-timestamp-p t)
20697 (call-interactively (if org-edit-timestamp-down-means-later
20698 'org-timestamp-down 'org-timestamp-up)))
20699 ((and (not (eq org-support-shift-select 'always))
20700 org-enable-priority-commands
20701 (org-at-heading-p))
20702 (call-interactively 'org-priority-up))
20703 ((and (not org-support-shift-select) (org-at-item-p))
20704 (call-interactively 'org-previous-item))
20705 ((org-clocktable-try-shift 'up arg))
20706 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20707 (org-support-shift-select
20708 (org-call-for-shift-select 'previous-line))
20709 (t (org-shiftselect-error))))
20711 (defun org-shiftdown (&optional arg)
20712 "Decrease item in timestamp or decrease priority of current headline.
20713 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20714 depending on context. See the individual commands for more information."
20715 (interactive "P")
20716 (cond
20717 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20718 ((and org-support-shift-select (org-region-active-p))
20719 (org-call-for-shift-select 'next-line))
20720 ((org-at-timestamp-p t)
20721 (call-interactively (if org-edit-timestamp-down-means-later
20722 'org-timestamp-up 'org-timestamp-down)))
20723 ((and (not (eq org-support-shift-select 'always))
20724 org-enable-priority-commands
20725 (org-at-heading-p))
20726 (call-interactively 'org-priority-down))
20727 ((and (not org-support-shift-select) (org-at-item-p))
20728 (call-interactively 'org-next-item))
20729 ((org-clocktable-try-shift 'down arg))
20730 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20731 (org-support-shift-select
20732 (org-call-for-shift-select 'next-line))
20733 (t (org-shiftselect-error))))
20735 (defun org-shiftright (&optional arg)
20736 "Cycle the thing at point or in the current line, depending on context.
20737 Depending on context, this does one of the following:
20739 - switch a timestamp at point one day into the future
20740 - on a headline, switch to the next TODO keyword.
20741 - on an item, switch entire list to the next bullet type
20742 - on a property line, switch to the next allowed value
20743 - on a clocktable definition line, move time block into the future"
20744 (interactive "P")
20745 (cond
20746 ((run-hook-with-args-until-success 'org-shiftright-hook))
20747 ((and org-support-shift-select (org-region-active-p))
20748 (org-call-for-shift-select 'forward-char))
20749 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20750 ((and (not (eq org-support-shift-select 'always))
20751 (org-at-heading-p))
20752 (let ((org-inhibit-logging
20753 (not org-treat-S-cursor-todo-selection-as-state-change))
20754 (org-inhibit-blocking
20755 (not org-treat-S-cursor-todo-selection-as-state-change)))
20756 (org-call-with-arg 'org-todo 'right)))
20757 ((or (and org-support-shift-select
20758 (not (eq org-support-shift-select 'always))
20759 (org-at-item-bullet-p))
20760 (and (not org-support-shift-select) (org-at-item-p)))
20761 (org-call-with-arg 'org-cycle-list-bullet nil))
20762 ((and (not (eq org-support-shift-select 'always))
20763 (org-at-property-p))
20764 (call-interactively 'org-property-next-allowed-value))
20765 ((org-clocktable-try-shift 'right arg))
20766 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20767 (org-support-shift-select
20768 (org-call-for-shift-select 'forward-char))
20769 (t (org-shiftselect-error))))
20771 (defun org-shiftleft (&optional arg)
20772 "Cycle the thing at point or in the current line, depending on context.
20773 Depending on context, this does one of the following:
20775 - switch a timestamp at point one day into the past
20776 - on a headline, switch to the previous TODO keyword.
20777 - on an item, switch entire list to the previous bullet type
20778 - on a property line, switch to the previous allowed value
20779 - on a clocktable definition line, move time block into the past"
20780 (interactive "P")
20781 (cond
20782 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20783 ((and org-support-shift-select (org-region-active-p))
20784 (org-call-for-shift-select 'backward-char))
20785 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20786 ((and (not (eq org-support-shift-select 'always))
20787 (org-at-heading-p))
20788 (let ((org-inhibit-logging
20789 (not org-treat-S-cursor-todo-selection-as-state-change))
20790 (org-inhibit-blocking
20791 (not org-treat-S-cursor-todo-selection-as-state-change)))
20792 (org-call-with-arg 'org-todo 'left)))
20793 ((or (and org-support-shift-select
20794 (not (eq org-support-shift-select 'always))
20795 (org-at-item-bullet-p))
20796 (and (not org-support-shift-select) (org-at-item-p)))
20797 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20798 ((and (not (eq org-support-shift-select 'always))
20799 (org-at-property-p))
20800 (call-interactively 'org-property-previous-allowed-value))
20801 ((org-clocktable-try-shift 'left arg))
20802 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20803 (org-support-shift-select
20804 (org-call-for-shift-select 'backward-char))
20805 (t (org-shiftselect-error))))
20807 (defun org-shiftcontrolright ()
20808 "Switch to next TODO set."
20809 (interactive)
20810 (cond
20811 ((and org-support-shift-select (org-region-active-p))
20812 (org-call-for-shift-select 'forward-word))
20813 ((and (not (eq org-support-shift-select 'always))
20814 (org-at-heading-p))
20815 (org-call-with-arg 'org-todo 'nextset))
20816 (org-support-shift-select
20817 (org-call-for-shift-select 'forward-word))
20818 (t (org-shiftselect-error))))
20820 (defun org-shiftcontrolleft ()
20821 "Switch to previous TODO set."
20822 (interactive)
20823 (cond
20824 ((and org-support-shift-select (org-region-active-p))
20825 (org-call-for-shift-select 'backward-word))
20826 ((and (not (eq org-support-shift-select 'always))
20827 (org-at-heading-p))
20828 (org-call-with-arg 'org-todo 'previousset))
20829 (org-support-shift-select
20830 (org-call-for-shift-select 'backward-word))
20831 (t (org-shiftselect-error))))
20833 (defun org-shiftcontrolup (&optional n)
20834 "Change timestamps synchronously up in CLOCK log lines.
20835 Optional argument N tells to change by that many units."
20836 (interactive "P")
20837 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20838 (let (org-support-shift-select)
20839 (org-clock-timestamps-up n))
20840 (user-error "Not at a clock log")))
20842 (defun org-shiftcontroldown (&optional n)
20843 "Change timestamps synchronously down in CLOCK log lines.
20844 Optional argument N tells to change by that many units."
20845 (interactive "P")
20846 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20847 (let (org-support-shift-select)
20848 (org-clock-timestamps-down n))
20849 (user-error "Not at a clock log")))
20851 (defun org-increase-number-at-point (&optional inc)
20852 "Increment the number at point.
20853 With an optional prefix numeric argument INC, increment using
20854 this numeric value."
20855 (interactive "p")
20856 (if (not (number-at-point))
20857 (user-error "Not on a number")
20858 (unless inc (setq inc 1))
20859 (let ((pos (point))
20860 (beg (skip-chars-backward "-+^/*0-9eE."))
20861 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20862 (setq nap (buffer-substring-no-properties
20863 (+ pos beg) (+ pos beg end)))
20864 (delete-region (+ pos beg) (+ pos beg end))
20865 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20866 (when (org-at-table-p)
20867 (org-table-align)
20868 (org-table-end-of-field 1))))
20870 (defun org-decrease-number-at-point (&optional inc)
20871 "Decrement the number at point.
20872 With an optional prefix numeric argument INC, decrement using
20873 this numeric value."
20874 (interactive "p")
20875 (org-increase-number-at-point (- (or inc 1))))
20877 (defun org-ctrl-c-ret ()
20878 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20879 (interactive)
20880 (cond
20881 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20882 (t (call-interactively 'org-insert-heading))))
20884 (defun org-find-visible ()
20885 (let ((s (point)))
20886 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20887 (get-char-property s 'invisible)))
20889 (defun org-find-invisible ()
20890 (let ((s (point)))
20891 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20892 (not (get-char-property s 'invisible))))
20895 (defun org-copy-visible (beg end)
20896 "Copy the visible parts of the region."
20897 (interactive "r")
20898 (let (snippets s)
20899 (save-excursion
20900 (save-restriction
20901 (narrow-to-region beg end)
20902 (setq s (goto-char (point-min)))
20903 (while (not (= (point) (point-max)))
20904 (goto-char (org-find-invisible))
20905 (push (buffer-substring s (point)) snippets)
20906 (setq s (goto-char (org-find-visible))))))
20907 (kill-new (apply 'concat (nreverse snippets)))))
20909 (defun org-copy-special ()
20910 "Copy region in table or copy current subtree.
20911 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20912 context. See the individual commands for more information."
20913 (interactive)
20914 (call-interactively
20915 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20917 (defun org-cut-special ()
20918 "Cut region in table or cut current subtree.
20919 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20920 context. See the individual commands for more information."
20921 (interactive)
20922 (call-interactively
20923 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20925 (defun org-paste-special (arg)
20926 "Paste rectangular region into table, or past subtree relative to level.
20927 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20928 See the individual commands for more information."
20929 (interactive "P")
20930 (if (org-at-table-p)
20931 (org-table-paste-rectangle)
20932 (org-paste-subtree arg)))
20934 (defun org-edit-special (&optional arg)
20935 "Call a special editor for the element at point.
20936 When at a table, call the formula editor with `org-table-edit-formulas'.
20937 When in a source code block, call `org-edit-src-code'.
20938 When in a fixed-width region, call `org-edit-fixed-width-region'.
20939 When in an export block, call `org-edit-export-block'.
20940 When at an #+INCLUDE keyword, visit the included file.
20941 When at a footnote reference, call `org-edit-footnote-reference'
20942 On a link, call `ffap' to visit the link at point.
20943 Otherwise, return a user error."
20944 (interactive "P")
20945 (let ((element (org-element-at-point)))
20946 (barf-if-buffer-read-only)
20947 (pcase (org-element-type element)
20948 (`src-block
20949 (if (not arg) (org-edit-src-code)
20950 (let* ((info (org-babel-get-src-block-info))
20951 (lang (nth 0 info))
20952 (params (nth 2 info))
20953 (session (cdr (assq :session params))))
20954 (if (not session) (org-edit-src-code)
20955 ;; At a src-block with a session and function called with
20956 ;; an ARG: switch to the buffer related to the inferior
20957 ;; process.
20958 (switch-to-buffer
20959 (funcall (intern (concat "org-babel-prep-session:" lang))
20960 session params))))))
20961 (`keyword
20962 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20963 (org-open-link-from-string
20964 (format "[[%s]]"
20965 (expand-file-name
20966 (let ((value (org-element-property :value element)))
20967 (cond ((not (org-string-nw-p value))
20968 (user-error "No file to edit"))
20969 ((string-match "\\`\"\\(.*?\\)\"" value)
20970 (match-string 1 value))
20971 ((string-match "\\`[^ \t\"]\\S-*" value)
20972 (match-string 0 value))
20973 (t (user-error "No valid file specified")))))))
20974 (user-error "No special environment to edit here")))
20975 (`table
20976 (if (eq (org-element-property :type element) 'table.el)
20977 (org-edit-table.el)
20978 (call-interactively 'org-table-edit-formulas)))
20979 ;; Only Org tables contain `table-row' type elements.
20980 (`table-row (call-interactively 'org-table-edit-formulas))
20981 (`example-block (org-edit-src-code))
20982 (`export-block (org-edit-export-block))
20983 (`fixed-width (org-edit-fixed-width-region))
20985 ;; No notable element at point. Though, we may be at a link or
20986 ;; a footnote reference, which are objects. Thus, scan deeper.
20987 (let ((context (org-element-context element)))
20988 (pcase (org-element-type context)
20989 (`footnote-reference (org-edit-footnote-reference))
20990 (`inline-src-block (org-edit-inline-src-code))
20991 (`link (call-interactively #'ffap))
20992 (_ (user-error "No special environment to edit here"))))))))
20994 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20995 (defun org-ctrl-c-ctrl-c (&optional arg)
20996 "Set tags in headline, or update according to changed information at point.
20998 This command does many different things, depending on context:
21000 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21001 this is what we do.
21003 - If the cursor is on a statistics cookie, update it.
21005 - If the cursor is in a headline, prompt for tags and insert them
21006 into the current line, aligned to `org-tags-column'. When called
21007 with prefix arg, realign all tags in the current buffer.
21009 - If the cursor is in one of the special #+KEYWORD lines, this
21010 triggers scanning the buffer for these lines and updating the
21011 information.
21013 - If the cursor is inside a table, realign the table. This command
21014 works even if the automatic table editor has been turned off.
21016 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21017 the entire table.
21019 - If the cursor is at a footnote reference or definition, jump to
21020 the corresponding definition or references, respectively.
21022 - If the cursor is a the beginning of a dynamic block, update it.
21024 - If the current buffer is a capture buffer, close note and file it.
21026 - If the cursor is on a <<<target>>>, update radio targets and
21027 corresponding links in this buffer.
21029 - If the cursor is on a numbered item in a plain list, renumber the
21030 ordered list.
21032 - If the cursor is on a checkbox, toggle it.
21034 - If the cursor is on a code block, evaluate it. The variable
21035 `org-confirm-babel-evaluate' can be used to control prompting
21036 before code block evaluation, by default every code block
21037 evaluation requires confirmation. Code block evaluation can be
21038 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21039 (interactive "P")
21040 (cond
21041 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
21042 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21043 (org-remove-occur-highlights)
21044 (message "Temporary highlights/overlays removed from current buffer"))
21045 ((and (local-variable-p 'org-finish-function)
21046 (fboundp org-finish-function))
21047 (funcall org-finish-function))
21048 ((org-babel-hash-at-point))
21049 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21050 ((save-excursion (beginning-of-line) (looking-at-p "[ \t]*$"))
21051 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21052 (user-error
21053 (substitute-command-keys
21054 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
21056 (let* ((context
21057 (org-element-lineage
21058 (org-element-context)
21059 ;; Limit to supported contexts.
21060 '(babel-call clock dynamic-block footnote-definition
21061 footnote-reference inline-babel-call inline-src-block
21062 inlinetask item keyword node-property paragraph
21063 plain-list property-drawer radio-target src-block
21064 statistics-cookie table table-cell table-row
21065 timestamp)
21067 (type (org-element-type context)))
21068 ;; For convenience: at the first line of a paragraph on the same
21069 ;; line as an item, apply function on that item instead.
21070 (when (eq type 'paragraph)
21071 (let ((parent (org-element-property :parent context)))
21072 (when (and (eq (org-element-type parent) 'item)
21073 (= (line-beginning-position)
21074 (org-element-property :begin parent)))
21075 (setq context parent)
21076 (setq type 'item))))
21077 ;; Act according to type of element or object at point.
21078 (pcase type
21079 ((or `babel-call `inline-babel-call)
21080 (let ((info (org-babel-lob-get-info context)))
21081 (when info (org-babel-execute-src-block nil info))))
21082 (`clock (org-clock-update-time-maybe))
21083 (`dynamic-block
21084 (save-excursion
21085 (goto-char (org-element-property :post-affiliated context))
21086 (org-update-dblock)))
21087 (`footnote-definition
21088 (goto-char (org-element-property :post-affiliated context))
21089 (call-interactively 'org-footnote-action))
21090 (`footnote-reference (call-interactively #'org-footnote-action))
21091 ((or `headline `inlinetask)
21092 (save-excursion (goto-char (org-element-property :begin context))
21093 (call-interactively #'org-set-tags)))
21094 ((or `inline-src-block `src-block)
21095 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
21096 (org-babel-eval-wipe-error-buffer)
21097 (org-babel-execute-src-block
21098 current-prefix-arg (org-babel-get-src-block-info nil context))))
21099 (`item
21100 ;; At an item: `C-u C-u' sets checkbox to "[-]"
21101 ;; unconditionally, whereas `C-u' will toggle its presence.
21102 ;; Without a universal argument, if the item has a checkbox,
21103 ;; toggle it. Otherwise repair the list.
21104 (let* ((box (org-element-property :checkbox context))
21105 (struct (org-element-property :structure context))
21106 (old-struct (copy-tree struct))
21107 (parents (org-list-parents-alist struct))
21108 (prevs (org-list-prevs-alist struct))
21109 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21110 (org-list-set-checkbox
21111 (org-element-property :begin context) struct
21112 (cond ((equal arg '(16)) "[-]")
21113 ((and (not box) (equal arg '(4))) "[ ]")
21114 ((or (not box) (equal arg '(4))) nil)
21115 ((eq box 'on) "[ ]")
21116 (t "[X]")))
21117 ;; Mimic `org-list-write-struct' but with grabbing a return
21118 ;; value from `org-list-struct-fix-box'.
21119 (org-list-struct-fix-ind struct parents 2)
21120 (org-list-struct-fix-item-end struct)
21121 (org-list-struct-fix-bul struct prevs)
21122 (org-list-struct-fix-ind struct parents)
21123 (let ((block-item
21124 (org-list-struct-fix-box struct parents prevs orderedp)))
21125 (if (and box (equal struct old-struct))
21126 (if (equal arg '(16))
21127 (message "Checkboxes already reset")
21128 (user-error "Cannot toggle this checkbox: %s"
21129 (if (eq box 'on)
21130 "all subitems checked"
21131 "unchecked subitems")))
21132 (org-list-struct-apply-struct struct old-struct)
21133 (org-update-checkbox-count-maybe))
21134 (when block-item
21135 (message "Checkboxes were removed due to empty box at line %d"
21136 (org-current-line block-item))))))
21137 (`keyword
21138 (let ((org-inhibit-startup-visibility-stuff t)
21139 (org-startup-align-all-tables nil))
21140 (when (boundp 'org-table-coordinate-overlays)
21141 (mapc #'delete-overlay org-table-coordinate-overlays)
21142 (setq org-table-coordinate-overlays nil))
21143 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21144 (message "Local setup has been refreshed"))
21145 (`plain-list
21146 ;; At a plain list, with a double C-u argument, set
21147 ;; checkboxes of each item to "[-]", whereas a single one
21148 ;; will toggle their presence according to the state of the
21149 ;; first item in the list. Without an argument, repair the
21150 ;; list.
21151 (let* ((begin (org-element-property :contents-begin context))
21152 (beginm (move-marker (make-marker) begin))
21153 (struct (org-element-property :structure context))
21154 (old-struct (copy-tree struct))
21155 (first-box (save-excursion
21156 (goto-char begin)
21157 (looking-at org-list-full-item-re)
21158 (match-string-no-properties 3)))
21159 (new-box (cond ((equal arg '(16)) "[-]")
21160 ((equal arg '(4)) (unless first-box "[ ]"))
21161 ((equal first-box "[X]") "[ ]")
21162 (t "[X]"))))
21163 (cond
21164 (arg
21165 (dolist (pos
21166 (org-list-get-all-items
21167 begin struct (org-list-prevs-alist struct)))
21168 (org-list-set-checkbox pos struct new-box)))
21169 ((and first-box (eq (point) begin))
21170 ;; For convenience, when point is at bol on the first
21171 ;; item of the list and no argument is provided, simply
21172 ;; toggle checkbox of that item, if any.
21173 (org-list-set-checkbox begin struct new-box)))
21174 (org-list-write-struct
21175 struct (org-list-parents-alist struct) old-struct)
21176 (org-update-checkbox-count-maybe)
21177 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21178 ((or `property-drawer `node-property)
21179 (call-interactively #'org-property-action))
21180 (`radio-target
21181 (call-interactively #'org-update-radio-target-regexp))
21182 (`statistics-cookie
21183 (call-interactively #'org-update-statistics-cookies))
21184 ((or `table `table-cell `table-row)
21185 ;; At a table, recalculate every field and align it. Also
21186 ;; send the table if necessary. If the table has
21187 ;; a `table.el' type, just give up. At a table row or cell,
21188 ;; maybe recalculate line but always align table.
21189 (if (eq (org-element-property :type context) 'table.el)
21190 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21191 Use `\\[org-edit-special]' to edit table.el tables"))
21192 (let ((org-enable-table-editor t))
21193 (if (or (eq type 'table)
21194 ;; Check if point is at a TBLFM line.
21195 (and (eq type 'table-row)
21196 (= (point) (org-element-property :end context))))
21197 (save-excursion
21198 (if (org-at-TBLFM-p)
21199 (progn (require 'org-table)
21200 (org-table-calc-current-TBLFM))
21201 (goto-char (org-element-property :contents-begin context))
21202 (org-call-with-arg 'org-table-recalculate (or arg t))
21203 (orgtbl-send-table 'maybe)))
21204 (org-table-maybe-eval-formula)
21205 (cond (arg (call-interactively #'org-table-recalculate))
21206 ((org-table-maybe-recalculate-line))
21207 (t (org-table-align)))))))
21208 (`timestamp (org-timestamp-change 0 'day))
21209 ((and `nil (guard (org-at-heading-p)))
21210 ;; When point is on an unsupported object type, we can miss
21211 ;; the fact that it also is at a heading. Handle it here.
21212 (call-interactively #'org-set-tags))
21213 ((guard
21214 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21216 (user-error
21217 (substitute-command-keys
21218 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21220 (defun org-mode-restart ()
21221 (interactive)
21222 (let ((indent-status (bound-and-true-p org-indent-mode)))
21223 (funcall major-mode)
21224 (hack-local-variables)
21225 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21226 (org-indent-mode -1)))
21227 (message "%s restarted" major-mode))
21229 (defun org-kill-note-or-show-branches ()
21230 "Abort storing current note, or call `outline-show-branches'."
21231 (interactive)
21232 (if (not org-finish-function)
21233 (progn
21234 (outline-hide-subtree)
21235 (call-interactively 'outline-show-branches))
21236 (let ((org-note-abort t))
21237 (funcall org-finish-function))))
21239 (defun org-delete-indentation (&optional arg)
21240 "Join current line to previous and fix whitespace at join.
21242 If previous line is a headline add to headline title. Otherwise
21243 the function calls `delete-indentation'.
21245 With a non-nil optional argument, join it to the following one."
21246 (interactive "*P")
21247 (if (save-excursion
21248 (beginning-of-line (if arg 1 0))
21249 (let ((case-fold-search nil))
21250 (looking-at org-complex-heading-regexp)))
21251 ;; At headline.
21252 (let ((tags-column (when (match-beginning 5)
21253 (save-excursion (goto-char (match-beginning 5))
21254 (current-column))))
21255 (string (concat " " (progn (when arg (forward-line 1))
21256 (org-trim (delete-and-extract-region
21257 (line-beginning-position)
21258 (line-end-position)))))))
21259 (unless (bobp) (delete-region (point) (1- (point))))
21260 (goto-char (or (match-end 4)
21261 (match-beginning 5)
21262 (match-end 0)))
21263 (skip-chars-backward " \t")
21264 (save-excursion (insert string))
21265 ;; Adjust alignment of tags.
21266 (cond
21267 ((not tags-column)) ;no tags
21268 (org-auto-align-tags (org-set-tags nil t))
21269 (t (org--align-tags-here tags-column)))) ;preserve tags column
21270 (delete-indentation arg)))
21272 (defun org-open-line (n)
21273 "Insert a new row in tables, call `open-line' elsewhere.
21274 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21275 As a special case, when a document starts with a table, allow to
21276 call `open-line' on the very first character."
21277 (interactive "*p")
21278 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21279 (org-table-insert-row)
21280 (open-line n)))
21282 (defun org-return (&optional indent)
21283 "Goto next table row or insert a newline.
21285 Calls `org-table-next-row' or `newline', depending on context.
21287 When optional INDENT argument is non-nil, call
21288 `newline-and-indent' instead of `newline'.
21290 When `org-return-follows-link' is non-nil and point is on
21291 a timestamp or a link, call `org-open-at-point'. However, it
21292 will not happen if point is in a table or on a \"dead\"
21293 object (e.g., within a comment). In these case, you need to use
21294 `org-open-at-point' directly."
21295 (interactive)
21296 (let ((context (if org-return-follows-link (org-element-context)
21297 (org-element-at-point))))
21298 (cond
21299 ;; In a table, call `org-table-next-row'.
21300 ((or (and (eq (org-element-type context) 'table)
21301 (>= (point) (org-element-property :contents-begin context))
21302 (< (point) (org-element-property :contents-end context)))
21303 (org-element-lineage context '(table-row table-cell) t))
21304 (org-table-justify-field-maybe)
21305 (call-interactively #'org-table-next-row))
21306 ;; On a link or a timestamp, call `org-open-at-point' if
21307 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21308 ;; locations, e.g., in a comment, as `org-open-at-point'.
21309 ((and org-return-follows-link
21310 (or (org-in-regexp org-ts-regexp-both nil t)
21311 (org-in-regexp org-tsr-regexp-both nil t)
21312 (org-in-regexp org-any-link-re nil t)))
21313 (call-interactively #'org-open-at-point))
21314 ;; Insert newline in heading, but preserve tags.
21315 ((and (not (bolp))
21316 (save-excursion (beginning-of-line)
21317 (let ((case-fold-search nil))
21318 (looking-at org-complex-heading-regexp))))
21319 ;; At headline. Split line. However, if point is on keyword,
21320 ;; priority cookie or tags, do not break any of them: add
21321 ;; a newline after the headline instead.
21322 (let ((tags-column (and (match-beginning 5)
21323 (save-excursion (goto-char (match-beginning 5))
21324 (current-column))))
21325 (string
21326 (when (and (match-end 4) (org-point-in-group (point) 4))
21327 (delete-and-extract-region (point) (match-end 4)))))
21328 ;; Adjust tag alignment.
21329 (cond
21330 ((not (and tags-column string)))
21331 (org-auto-align-tags (org-set-tags nil t))
21332 (t (org--align-tags-here tags-column))) ;preserve tags column
21333 (end-of-line)
21334 (org-show-entry)
21335 (if indent (newline-and-indent) (newline))
21336 (when string (save-excursion (insert (org-trim string))))))
21337 ;; In a list, make sure indenting keeps trailing text within.
21338 ((and indent
21339 (not (eolp))
21340 (org-element-lineage context '(item)))
21341 (let ((trailing-data
21342 (delete-and-extract-region (point) (line-end-position))))
21343 (newline-and-indent)
21344 (save-excursion (insert trailing-data))))
21345 (t (if indent (newline-and-indent) (newline))))))
21347 (defun org-return-indent ()
21348 "Goto next table row or insert a newline and indent.
21349 Calls `org-table-next-row' or `newline-and-indent', depending on
21350 context. See the individual commands for more information."
21351 (interactive)
21352 (org-return t))
21354 (defun org-ctrl-c-star ()
21355 "Compute table, or change heading status of lines.
21356 Calls `org-table-recalculate' or `org-toggle-heading',
21357 depending on context."
21358 (interactive)
21359 (cond
21360 ((org-at-table-p)
21361 (call-interactively 'org-table-recalculate))
21363 ;; Convert all lines in region to list items
21364 (call-interactively 'org-toggle-heading))))
21366 (defun org-ctrl-c-minus ()
21367 "Insert separator line in table or modify bullet status of line.
21368 Also turns a plain line or a region of lines into list items.
21369 Calls `org-table-insert-hline', `org-toggle-item', or
21370 `org-cycle-list-bullet', depending on context."
21371 (interactive)
21372 (cond
21373 ((org-at-table-p)
21374 (call-interactively 'org-table-insert-hline))
21375 ((org-region-active-p)
21376 (call-interactively 'org-toggle-item))
21377 ((org-in-item-p)
21378 (call-interactively 'org-cycle-list-bullet))
21380 (call-interactively 'org-toggle-item))))
21382 (defun org-toggle-heading (&optional nstars)
21383 "Convert headings to normal text, or items or text to headings.
21384 If there is no active region, only convert the current line.
21386 With a `\\[universal-argument]' prefix, convert the whole list at
21387 point into heading.
21389 In a region:
21391 - If the first non blank line is a headline, remove the stars
21392 from all headlines in the region.
21394 - If it is a normal line, turn each and every normal line (i.e.,
21395 not an heading or an item) in the region into headings. If you
21396 want to convert only the first line of this region, use one
21397 universal prefix argument.
21399 - If it is a plain list item, turn all plain list items into headings.
21401 When converting a line into a heading, the number of stars is chosen
21402 such that the lines become children of the current entry. However,
21403 when a numeric prefix argument is given, its value determines the
21404 number of stars to add."
21405 (interactive "P")
21406 (let ((skip-blanks
21407 (function
21408 ;; Return beginning of first non-blank line, starting from
21409 ;; line at POS.
21410 (lambda (pos)
21411 (save-excursion
21412 (goto-char pos)
21413 (while (org-at-comment-p) (forward-line))
21414 (skip-chars-forward " \r\t\n")
21415 (point-at-bol)))))
21416 beg end toggled)
21417 ;; Determine boundaries of changes. If a universal prefix has
21418 ;; been given, put the list in a region. If region ends at a bol,
21419 ;; do not consider the last line to be in the region.
21421 (when (and current-prefix-arg (org-at-item-p))
21422 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21423 (org-mark-element))
21425 (if (org-region-active-p)
21426 (setq beg (funcall skip-blanks (region-beginning))
21427 end (copy-marker (save-excursion
21428 (goto-char (region-end))
21429 (if (bolp) (point) (point-at-eol)))))
21430 (setq beg (funcall skip-blanks (point-at-bol))
21431 end (copy-marker (point-at-eol))))
21432 ;; Ensure inline tasks don't count as headings.
21433 (org-with-limited-levels
21434 (save-excursion
21435 (goto-char beg)
21436 (cond
21437 ;; Case 1. Started at an heading: de-star headings.
21438 ((org-at-heading-p)
21439 (while (< (point) end)
21440 (when (org-at-heading-p t)
21441 (looking-at org-outline-regexp) (replace-match "")
21442 (setq toggled t))
21443 (forward-line)))
21444 ;; Case 2. Started at an item: change items into headlines.
21445 ;; One star will be added by `org-list-to-subtree'.
21446 ((org-at-item-p)
21447 (while (< (point) end)
21448 (when (org-at-item-p)
21449 ;; Pay attention to cases when region ends before list.
21450 (let* ((struct (org-list-struct))
21451 (list-end
21452 (min (org-list-get-bottom-point struct) (1+ end))))
21453 (save-restriction
21454 (narrow-to-region (point) list-end)
21455 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21456 (setq toggled t))
21457 (forward-line)))
21458 ;; Case 3. Started at normal text: make every line an heading,
21459 ;; skipping headlines and items.
21460 (t (let* ((stars
21461 (make-string
21462 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21463 (add-stars
21464 (cond (nstars "") ; stars from prefix only
21465 ((equal stars "") "*") ; before first heading
21466 (org-odd-levels-only "**") ; inside heading, odd
21467 (t "*"))) ; inside heading, oddeven
21468 (rpl (concat stars add-stars " "))
21469 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21470 (while (< (point) (if (equal nstars '(4)) lend end))
21471 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21472 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21473 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21474 (forward-line)))))))
21475 (unless toggled (message "Cannot toggle heading from here"))))
21477 (defun org-meta-return (&optional arg)
21478 "Insert a new heading or wrap a region in a table.
21479 Calls `org-insert-heading', `org-insert-item' or
21480 `org-table-wrap-region', depending on context. When called with
21481 an argument, unconditionally call `org-insert-heading'."
21482 (interactive "P")
21483 (org-check-before-invisible-edit 'insert)
21484 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21485 (call-interactively (cond (arg #'org-insert-heading)
21486 ((org-at-table-p) #'org-table-wrap-region)
21487 ((org-in-item-p) #'org-insert-item)
21488 (t #'org-insert-heading)))))
21490 ;;; Menu entries
21492 (defsubst org-in-subtree-not-table-p ()
21493 "Are we in a subtree and not in a table?"
21494 (and (not (org-before-first-heading-p))
21495 (not (org-at-table-p))))
21497 ;; Define the Org mode menus
21498 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21499 '("Tbl"
21500 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21501 ["Next Field" org-cycle (org-at-table-p)]
21502 ["Previous Field" org-shifttab (org-at-table-p)]
21503 ["Next Row" org-return (org-at-table-p)]
21504 "--"
21505 ["Blank Field" org-table-blank-field (org-at-table-p)]
21506 ["Edit Field" org-table-edit-field (org-at-table-p)]
21507 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21508 "--"
21509 ("Column"
21510 ["Move Column Left" org-metaleft (org-at-table-p)]
21511 ["Move Column Right" org-metaright (org-at-table-p)]
21512 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21513 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21514 ("Row"
21515 ["Move Row Up" org-metaup (org-at-table-p)]
21516 ["Move Row Down" org-metadown (org-at-table-p)]
21517 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21518 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21519 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21520 "--"
21521 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21522 ("Rectangle"
21523 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21524 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21525 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21526 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21527 "--"
21528 ("Calculate"
21529 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21530 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21531 ["Edit Formulas" org-edit-special (org-at-table-p)]
21532 "--"
21533 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21534 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21535 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21536 "--"
21537 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21538 "--"
21539 ["Sum Column/Rectangle" org-table-sum
21540 (or (org-at-table-p) (org-region-active-p))]
21541 ["Which Column?" org-table-current-column (org-at-table-p)])
21542 ["Debug Formulas"
21543 org-table-toggle-formula-debugger
21544 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21545 ["Show Col/Row Numbers"
21546 org-table-toggle-coordinate-overlays
21547 :style toggle
21548 :selected (bound-and-true-p org-table-overlay-coordinates)]
21549 "--"
21550 ["Create" org-table-create (and (not (org-at-table-p))
21551 org-enable-table-editor)]
21552 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21553 ["Import from File" org-table-import (not (org-at-table-p))]
21554 ["Export to File" org-table-export (org-at-table-p)]
21555 "--"
21556 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21557 "--"
21558 ("Plot"
21559 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21560 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21562 (easy-menu-define org-org-menu org-mode-map "Org menu"
21563 '("Org"
21564 ("Show/Hide"
21565 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21566 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21567 ["Sparse Tree..." org-sparse-tree t]
21568 ["Reveal Context" org-reveal t]
21569 ["Show All" outline-show-all t]
21570 "--"
21571 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21572 "--"
21573 ["New Heading" org-insert-heading t]
21574 ("Navigate Headings"
21575 ["Up" outline-up-heading t]
21576 ["Next" outline-next-visible-heading t]
21577 ["Previous" outline-previous-visible-heading t]
21578 ["Next Same Level" outline-forward-same-level t]
21579 ["Previous Same Level" outline-backward-same-level t]
21580 "--"
21581 ["Jump" org-goto t])
21582 ("Edit Structure"
21583 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21584 "--"
21585 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21586 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21587 "--"
21588 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21589 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21590 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21591 "--"
21592 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21593 "--"
21594 ["Copy visible text" org-copy-visible t]
21595 "--"
21596 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21597 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21598 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21599 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21600 "--"
21601 ["Sort Region/Children" org-sort t]
21602 "--"
21603 ["Convert to odd levels" org-convert-to-odd-levels t]
21604 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21605 ("Editing"
21606 ["Emphasis..." org-emphasize t]
21607 ["Edit Source Example" org-edit-special t]
21608 "--"
21609 ["Footnote new/jump" org-footnote-action t]
21610 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21611 ("Archive"
21612 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21613 "--"
21614 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21615 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21616 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21618 "--"
21619 ("Hyperlinks"
21620 ["Store Link (Global)" org-store-link t]
21621 ["Find existing link to here" org-occur-link-in-agenda-files t]
21622 ["Insert Link" org-insert-link t]
21623 ["Follow Link" org-open-at-point t]
21624 "--"
21625 ["Next link" org-next-link t]
21626 ["Previous link" org-previous-link t]
21627 "--"
21628 ["Descriptive Links"
21629 org-toggle-link-display
21630 :style radio
21631 :selected org-descriptive-links
21633 ["Literal Links"
21634 org-toggle-link-display
21635 :style radio
21636 :selected (not org-descriptive-links)])
21637 "--"
21638 ("TODO Lists"
21639 ["TODO/DONE/-" org-todo t]
21640 ("Select keyword"
21641 ["Next keyword" org-shiftright (org-at-heading-p)]
21642 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21643 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21644 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21645 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21646 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21647 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21648 "--"
21649 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21650 :selected org-enforce-todo-dependencies :style toggle :active t]
21651 "Settings for tree at point"
21652 ["Do Children sequentially" org-toggle-ordered-property :style radio
21653 :selected (org-entry-get nil "ORDERED")
21654 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21655 ["Do Children parallel" org-toggle-ordered-property :style radio
21656 :selected (not (org-entry-get nil "ORDERED"))
21657 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21658 "--"
21659 ["Set Priority" org-priority t]
21660 ["Priority Up" org-shiftup t]
21661 ["Priority Down" org-shiftdown t]
21662 "--"
21663 ["Get news from all feeds" org-feed-update-all t]
21664 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21665 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21666 ("TAGS and Properties"
21667 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21668 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21669 "--"
21670 ["Set property" org-set-property (not (org-before-first-heading-p))]
21671 ["Column view of properties" org-columns t]
21672 ["Insert Column View DBlock" org-columns-insert-dblock t])
21673 ("Dates and Scheduling"
21674 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21675 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21676 ("Change Date"
21677 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21678 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21679 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21680 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21681 ["Compute Time Range" org-evaluate-time-range t]
21682 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21683 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21684 "--"
21685 ["Custom time format" org-toggle-time-stamp-overlays
21686 :style radio :selected org-display-custom-times]
21687 "--"
21688 ["Goto Calendar" org-goto-calendar t]
21689 ["Date from Calendar" org-date-from-calendar t]
21690 "--"
21691 ["Start/Restart Timer" org-timer-start t]
21692 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21693 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21694 ["Insert Timer String" org-timer t]
21695 ["Insert Timer Item" org-timer-item t])
21696 ("Logging work"
21697 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21698 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21699 ["Clock out" org-clock-out t]
21700 ["Clock cancel" org-clock-cancel t]
21701 "--"
21702 ["Mark as default task" org-clock-mark-default-task t]
21703 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21704 ["Goto running clock" org-clock-goto t]
21705 "--"
21706 ["Display times" org-clock-display t]
21707 ["Create clock table" org-clock-report t]
21708 "--"
21709 ["Record DONE time"
21710 (progn (setq org-log-done (not org-log-done))
21711 (message "Switching to %s will %s record a timestamp"
21712 (car org-done-keywords)
21713 (if org-log-done "automatically" "not")))
21714 :style toggle :selected org-log-done])
21715 "--"
21716 ["Agenda Command..." org-agenda t]
21717 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21718 ("File List for Agenda")
21719 ("Special views current file"
21720 ["TODO Tree" org-show-todo-tree t]
21721 ["Check Deadlines" org-check-deadlines t]
21722 ["Tags/Property tree" org-match-sparse-tree t])
21723 "--"
21724 ["Export/Publish..." org-export-dispatch t]
21725 ("LaTeX"
21726 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21727 :selected org-cdlatex-mode]
21728 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21729 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21730 ["Modify math symbol" org-cdlatex-math-modify
21731 (org-inside-LaTeX-fragment-p)]
21732 ["Insert citation" org-reftex-citation t])
21733 "--"
21734 ("MobileOrg"
21735 ["Push Files and Views" org-mobile-push t]
21736 ["Get Captured and Flagged" org-mobile-pull t]
21737 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21738 "--"
21739 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21740 "--"
21741 ("Documentation"
21742 ["Show Version" org-version t]
21743 ["Info Documentation" org-info t])
21744 ("Customize"
21745 ["Browse Org Group" org-customize t]
21746 "--"
21747 ["Expand This Menu" org-create-customize-menu
21748 (fboundp 'customize-menu-create)])
21749 ["Send bug report" org-submit-bug-report t]
21750 "--"
21751 ("Refresh/Reload"
21752 ["Refresh setup current buffer" org-mode-restart t]
21753 ["Reload Org (after update)" org-reload t]
21754 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21757 (defun org-info (&optional node)
21758 "Read documentation for Org in the info system.
21759 With optional NODE, go directly to that node."
21760 (interactive)
21761 (info (format "(org)%s" (or node ""))))
21763 ;;;###autoload
21764 (defun org-submit-bug-report ()
21765 "Submit a bug report on Org via mail.
21767 Don't hesitate to report any problems or inaccurate documentation.
21769 If you don't have setup sending mail from (X)Emacs, please copy the
21770 output buffer into your mail program, as it gives us important
21771 information about your Org version and configuration."
21772 (interactive)
21773 (require 'reporter)
21774 (defvar reporter-prompt-for-summary-p)
21775 (org-load-modules-maybe)
21776 (org-require-autoloaded-modules)
21777 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21778 (reporter-submit-bug-report
21779 "emacs-orgmode@gnu.org"
21780 (org-version nil 'full)
21781 (let (list)
21782 (save-window-excursion
21783 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21784 (delete-other-windows)
21785 (erase-buffer)
21786 (insert "You are about to submit a bug report to the Org mailing list.
21788 We would like to add your full Org and Outline configuration to the
21789 bug report. This greatly simplifies the work of the maintainer and
21790 other experts on the mailing list.
21792 HOWEVER, some variables you have customized may contain private
21793 information. The names of customers, colleagues, or friends, might
21794 appear in the form of file names, tags, todo states, or search strings.
21795 If you answer yes to the prompt, you might want to check and remove
21796 such private information before sending the email.")
21797 (add-text-properties (point-min) (point-max) '(face org-warning))
21798 (when (yes-or-no-p "Include your Org configuration ")
21799 (mapatoms
21800 (lambda (v)
21801 (and (boundp v)
21802 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21803 (or (and (symbol-value v)
21804 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21805 (and
21806 (get v 'custom-type) (get v 'standard-value)
21807 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21808 (push v list)))))
21809 (kill-buffer (get-buffer "*Warn about privacy*"))
21810 list))
21811 nil nil
21812 "Remember to cover the basics, that is, what you expected to happen and
21813 what in fact did happen. You don't know how to make a good report? See
21815 http://orgmode.org/manual/Feedback.html#Feedback
21817 Your bug report will be posted to the Org mailing list.
21818 ------------------------------------------------------------------------")
21819 (save-excursion
21820 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21821 (replace-match "\\1Bug: \\3 [\\2]")))))
21824 (defun org-install-agenda-files-menu ()
21825 (let ((bl (buffer-list)))
21826 (save-excursion
21827 (while bl
21828 (set-buffer (pop bl))
21829 (when (derived-mode-p 'org-mode) (setq bl nil)))
21830 (when (derived-mode-p 'org-mode)
21831 (easy-menu-change
21832 '("Org") "File List for Agenda"
21833 (append
21834 (list
21835 ["Edit File List" (org-edit-agenda-file-list) t]
21836 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21837 ["Remove Current File from List" org-remove-file t]
21838 ["Cycle through agenda files" org-cycle-agenda-files t]
21839 ["Occur in all agenda files" org-occur-in-agenda-files t]
21840 "--")
21841 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21843 ;;;; Documentation
21845 (defun org-require-autoloaded-modules ()
21846 (interactive)
21847 (mapc #'require
21848 '(org-agenda org-archive org-attach org-clock org-colview org-id
21849 org-table org-timer)))
21851 ;;;###autoload
21852 (defun org-reload (&optional uncompiled)
21853 "Reload all org lisp files.
21854 With prefix arg UNCOMPILED, load the uncompiled versions."
21855 (interactive "P")
21856 (require 'loadhist)
21857 (let* ((org-dir (org-find-library-dir "org"))
21858 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21859 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21860 (remove-re (format "\\`%s\\'"
21861 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21862 (feats (delete-dups
21863 (mapcar 'file-name-sans-extension
21864 (mapcar 'file-name-nondirectory
21865 (delq nil
21866 (mapcar 'feature-file
21867 features))))))
21868 (lfeat (append
21869 (sort
21870 (setq feats
21871 (delq nil (mapcar
21872 (lambda (f)
21873 (if (and (string-match feature-re f)
21874 (not (string-match remove-re f)))
21875 f nil))
21876 feats)))
21877 'string-lessp)
21878 (list "org-version" "org")))
21879 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21880 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21881 load-uncore load-misses)
21882 (setq load-misses
21883 (delq 't
21884 (mapcar (lambda (f)
21885 (or (org-load-noerror-mustsuffix (concat org-dir f))
21886 (and (string= org-dir contrib-dir)
21887 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21888 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21889 (add-to-list 'load-uncore f 'append)
21892 lfeat)))
21893 (when load-uncore
21894 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21895 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21896 (if load-misses
21897 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21898 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21899 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21901 ;;;###autoload
21902 (defun org-customize ()
21903 "Call the customize function with org as argument."
21904 (interactive)
21905 (org-load-modules-maybe)
21906 (org-require-autoloaded-modules)
21907 (customize-browse 'org))
21909 (defun org-create-customize-menu ()
21910 "Create a full customization menu for Org mode, insert it into the menu."
21911 (interactive)
21912 (org-load-modules-maybe)
21913 (org-require-autoloaded-modules)
21914 (if (fboundp 'customize-menu-create)
21915 (progn
21916 (easy-menu-change
21917 '("Org") "Customize"
21918 `(["Browse Org group" org-customize t]
21919 "--"
21920 ,(customize-menu-create 'org)
21921 ["Set" Custom-set t]
21922 ["Save" Custom-save t]
21923 ["Reset to Current" Custom-reset-current t]
21924 ["Reset to Saved" Custom-reset-saved t]
21925 ["Reset to Standard Settings" Custom-reset-standard t]))
21926 (message "\"Org\"-menu now contains full customization menu"))
21927 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21929 ;;;; Miscellaneous stuff
21931 ;;; Generally useful functions
21933 (defun org-get-at-eol (property n)
21934 "Get text property PROPERTY at the end of line less N characters."
21935 (get-text-property (- (point-at-eol) n) property))
21937 (defun org-find-text-property-in-string (prop s)
21938 "Return the first non-nil value of property PROP in string S."
21939 (or (get-text-property 0 prop s)
21940 (get-text-property (or (next-single-property-change 0 prop s) 0)
21941 prop s)))
21943 (defun org-display-warning (message)
21944 "Display the given MESSAGE as a warning."
21945 (display-warning 'org message :warning))
21947 (defun org-eval (form)
21948 "Eval FORM and return result."
21949 (condition-case error
21950 (eval form)
21951 (error (format "%%![Error: %s]" error))))
21953 (defun org-in-clocktable-p ()
21954 "Check if the cursor is in a clocktable."
21955 (let ((pos (point)) start)
21956 (save-excursion
21957 (end-of-line 1)
21958 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21959 (setq start (match-beginning 0))
21960 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21961 (>= (match-end 0) pos)
21962 start))))
21964 (defun org-in-verbatim-emphasis ()
21965 (save-match-data
21966 (and (org-in-regexp org-verbatim-re 2)
21967 (>= (point) (match-beginning 3))
21968 (<= (point) (match-end 4)))))
21970 (defun org-overlay-display (ovl text &optional face evap)
21971 "Make overlay OVL display TEXT with face FACE."
21972 (overlay-put ovl 'display text)
21973 (if face (overlay-put ovl 'face face))
21974 (if evap (overlay-put ovl 'evaporate t)))
21976 (defun org-overlay-before-string (ovl text &optional face evap)
21977 "Make overlay OVL display TEXT with face FACE."
21978 (if face (org-add-props text nil 'face face))
21979 (overlay-put ovl 'before-string text)
21980 (if evap (overlay-put ovl 'evaporate t)))
21982 (defun org-find-overlays (prop &optional pos delete)
21983 "Find all overlays specifying PROP at POS or point.
21984 If DELETE is non-nil, delete all those overlays."
21985 (let (found)
21986 (dolist (ov (overlays-at (or pos (point))) found)
21987 (cond ((not (overlay-get ov prop)))
21988 (delete (delete-overlay ov))
21989 (t (push ov found))))))
21991 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21992 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21993 (if (and marker (marker-buffer marker)
21994 (buffer-live-p (marker-buffer marker)))
21995 (progn
21996 (pop-to-buffer-same-window (marker-buffer marker))
21997 (when (or (> marker (point-max)) (< marker (point-min)))
21998 (widen))
21999 (goto-char marker)
22000 (org-show-context 'org-goto))
22001 (if bookmark
22002 (bookmark-jump bookmark)
22003 (error "Cannot find location"))))
22005 (defun org-quote-csv-field (s)
22006 "Quote field for inclusion in CSV material."
22007 (if (string-match "[\",]" s)
22008 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22011 (defun org-force-self-insert (N)
22012 "Needed to enforce self-insert under remapping."
22013 (interactive "p")
22014 (self-insert-command N))
22016 (defun org-string-width (s)
22017 "Compute width of string, ignoring invisible characters.
22018 This ignores character with invisibility property `org-link', and also
22019 characters with property `org-cwidth', because these will become invisible
22020 upon the next fontification round."
22021 (let (b l)
22022 (when (or (eq t buffer-invisibility-spec)
22023 (assq 'org-link buffer-invisibility-spec))
22024 (while (setq b (text-property-any 0 (length s)
22025 'invisible 'org-link s))
22026 (setq s (concat (substring s 0 b)
22027 (substring s (or (next-single-property-change
22028 b 'invisible s)
22029 (length s)))))))
22030 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22031 (setq s (concat (substring s 0 b)
22032 (substring s (or (next-single-property-change
22033 b 'org-cwidth s)
22034 (length s))))))
22035 (setq l (string-width s) b -1)
22036 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22037 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22040 (defun org-shorten-string (s maxlength)
22041 "Shorten string S so that it is no longer than MAXLENGTH characters.
22042 If the string is shorter or has length MAXLENGTH, just return the
22043 original string. If it is longer, the functions finds a space in the
22044 string, breaks this string off at that locations and adds three dots
22045 as ellipsis. Including the ellipsis, the string will not be longer
22046 than MAXLENGTH. If finding a good breaking point in the string does
22047 not work, the string is just chopped off in the middle of a word
22048 if necessary."
22049 (if (<= (length s) maxlength)
22051 (let* ((n (max (- maxlength 4) 1))
22052 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22053 (if (string-match re s)
22054 (concat (match-string 1 s) "...")
22055 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22057 (defun org-get-indentation (&optional line)
22058 "Get the indentation of the current line, interpreting tabs.
22059 When LINE is given, assume it represents a line and compute its indentation."
22060 (if line
22061 (when (string-match "^ *" (org-remove-tabs line))
22062 (match-end 0))
22063 (save-excursion
22064 (beginning-of-line 1)
22065 (skip-chars-forward " \t")
22066 (current-column))))
22068 (defun org-get-string-indentation (s)
22069 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22070 (let ((n -1) (i 0) (w tab-width) c)
22071 (catch 'exit
22072 (while (< (setq n (1+ n)) (length s))
22073 (setq c (aref s n))
22074 (cond ((= c ?\ ) (setq i (1+ i)))
22075 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22076 (t (throw 'exit t)))))
22079 (defun org-remove-tabs (s &optional width)
22080 "Replace tabulators in S with spaces.
22081 Assumes that s is a single line, starting in column 0."
22082 (setq width (or width tab-width))
22083 (while (string-match "\t" s)
22084 (setq s (replace-match
22085 (make-string
22086 (- (* width (/ (+ (match-beginning 0) width) width))
22087 (match-beginning 0)) ?\ )
22088 t t s)))
22091 (defun org-fix-indentation (line ind)
22092 "Fix indentation in LINE.
22093 IND is a cons cell with target and minimum indentation.
22094 If the current indentation in LINE is smaller than the minimum,
22095 leave it alone. If it is larger than ind, set it to the target."
22096 (let* ((l (org-remove-tabs line))
22097 (i (org-get-indentation l))
22098 (i1 (car ind)) (i2 (cdr ind)))
22099 (when (>= i i2) (setq l (substring line i2)))
22100 (if (> i1 0)
22101 (concat (make-string i1 ?\ ) l)
22102 l)))
22104 (defun org-remove-indentation (code &optional n)
22105 "Remove maximum common indentation in string CODE and return it.
22106 N may optionally be the number of columns to remove. Return CODE
22107 as-is if removal failed."
22108 (with-temp-buffer
22109 (insert code)
22110 (if (org-do-remove-indentation n) (buffer-string) code)))
22112 (defun org-do-remove-indentation (&optional n)
22113 "Remove the maximum common indentation from the buffer.
22114 When optional argument N is a positive integer, remove exactly
22115 that much characters from indentation, if possible. Return nil
22116 if it fails."
22117 (catch :exit
22118 (goto-char (point-min))
22119 ;; Find maximum common indentation, if not specified.
22120 (let ((n (or n
22121 (let ((min-ind (point-max)))
22122 (save-excursion
22123 (while (re-search-forward "^[ \t]*\\S-" nil t)
22124 (let ((ind (1- (current-column))))
22125 (if (zerop ind) (throw :exit nil)
22126 (setq min-ind (min min-ind ind))))))
22127 min-ind))))
22128 (if (zerop n) (throw :exit nil)
22129 ;; Remove exactly N indentation, but give up if not possible.
22130 (while (not (eobp))
22131 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22132 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22133 ((< ind n) (throw :exit nil))
22134 (t (indent-line-to (- ind n))))
22135 (forward-line)))
22136 ;; Signal success.
22137 t))))
22139 (defun org-fill-template (template alist)
22140 "Find each %key of ALIST in TEMPLATE and replace it."
22141 (let ((case-fold-search nil))
22142 (dolist (entry (sort (copy-sequence alist)
22143 (lambda (a b) (< (length (car a)) (length (car b))))))
22144 (setq template
22145 (replace-regexp-in-string
22146 (concat "%" (regexp-quote (car entry)))
22147 (or (cdr entry) "") template t t)))
22148 template))
22150 (defun org-base-buffer (buffer)
22151 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22152 (if (not buffer)
22153 buffer
22154 (or (buffer-base-buffer buffer)
22155 buffer)))
22157 (defun org-wrap (string &optional width lines)
22158 "Wrap string to either a number of lines, or a width in characters.
22159 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22160 that costs. If there is a word longer than WIDTH, the text is actually
22161 wrapped to the length of that word.
22162 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22163 many lines, whatever width that takes.
22164 The return value is a list of lines, without newlines at the end."
22165 (let* ((words (org-split-string string "[ \t\n]+"))
22166 (maxword (apply 'max (mapcar 'org-string-width words)))
22167 w ll)
22168 (cond (width
22169 (org-do-wrap words (max maxword width)))
22170 (lines
22171 (setq w maxword)
22172 (setq ll (org-do-wrap words maxword))
22173 (if (<= (length ll) lines)
22175 (setq ll words)
22176 (while (> (length ll) lines)
22177 (setq w (1+ w))
22178 (setq ll (org-do-wrap words w)))
22179 ll))
22180 (t (error "Cannot wrap this")))))
22182 (defun org-do-wrap (words width)
22183 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22184 (let (lines line)
22185 (while words
22186 (setq line (pop words))
22187 (while (and words (< (+ (length line) (length (car words))) width))
22188 (setq line (concat line " " (pop words))))
22189 (setq lines (push line lines)))
22190 (nreverse lines)))
22192 (defun org-split-string (string &optional separators)
22193 "Splits STRING into substrings at SEPARATORS.
22194 SEPARATORS is a regular expression.
22195 No empty strings are returned if there are matches at the beginning
22196 and end of string."
22197 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22198 (let ((start 0) notfirst list)
22199 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22200 (if (and notfirst
22201 (= start (match-beginning 0))
22202 (< start (length string)))
22203 (1+ start) start))
22204 (< (match-beginning 0) (length string)))
22205 (setq notfirst t)
22206 (or (eq (match-beginning 0) 0)
22207 (and (eq (match-beginning 0) (match-end 0))
22208 (eq (match-beginning 0) start))
22209 (push (substring string start (match-beginning 0)) list))
22210 (setq start (match-end 0)))
22211 (or (eq start (length string))
22212 (push (substring string start) list))
22213 (nreverse list)))
22215 (defun org-quote-vert (s)
22216 "Replace \"|\" with \"\\vert\"."
22217 (while (string-match "|" s)
22218 (setq s (replace-match "\\vert" t t s)))
22221 (defun org-uuidgen-p (s)
22222 "Is S an ID created by UUIDGEN?"
22223 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22225 (defun org-in-src-block-p (&optional inside)
22226 "Whether point is in a code source block.
22227 When INSIDE is non-nil, don't consider we are within a src block
22228 when point is at #+BEGIN_SRC or #+END_SRC."
22229 (let ((case-fold-search t))
22230 (or (and (eq (get-char-property (point) 'src-block) t))
22231 (and (not inside)
22232 (save-match-data
22233 (save-excursion
22234 (beginning-of-line)
22235 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22237 (defun org-context ()
22238 "Return a list of contexts of the current cursor position.
22239 If several contexts apply, all are returned.
22240 Each context entry is a list with a symbol naming the context, and
22241 two positions indicating start and end of the context. Possible
22242 contexts are:
22244 :headline anywhere in a headline
22245 :headline-stars on the leading stars in a headline
22246 :todo-keyword on a TODO keyword (including DONE) in a headline
22247 :tags on the TAGS in a headline
22248 :priority on the priority cookie in a headline
22249 :item on the first line of a plain list item
22250 :item-bullet on the bullet/number of a plain list item
22251 :checkbox on the checkbox in a plain list item
22252 :table in an Org table
22253 :table-special on a special filed in a table
22254 :table-table in a table.el table
22255 :clocktable in a clocktable
22256 :src-block in a source block
22257 :link on a hyperlink
22258 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22259 :target on a <<target>>
22260 :radio-target on a <<<radio-target>>>
22261 :latex-fragment on a LaTeX fragment
22262 :latex-preview on a LaTeX fragment with overlaid preview image
22264 This function expects the position to be visible because it uses font-lock
22265 faces as a help to recognize the following contexts: :table-special, :link,
22266 and :keyword."
22267 (let* ((f (get-text-property (point) 'face))
22268 (faces (if (listp f) f (list f)))
22269 (case-fold-search t)
22270 (p (point)) clist o)
22271 ;; First the large context
22272 (cond
22273 ((org-at-heading-p t)
22274 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22275 (when (progn
22276 (beginning-of-line 1)
22277 (looking-at org-todo-line-tags-regexp))
22278 (push (org-point-in-group p 1 :headline-stars) clist)
22279 (push (org-point-in-group p 2 :todo-keyword) clist)
22280 (push (org-point-in-group p 4 :tags) clist))
22281 (goto-char p)
22282 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22283 (when (looking-at "\\[#[A-Z0-9]\\]")
22284 (push (org-point-in-group p 0 :priority) clist)))
22286 ((org-at-item-p)
22287 (push (org-point-in-group p 2 :item-bullet) clist)
22288 (push (list :item (point-at-bol)
22289 (save-excursion (org-end-of-item) (point)))
22290 clist)
22291 (and (org-at-item-checkbox-p)
22292 (push (org-point-in-group p 0 :checkbox) clist)))
22294 ((org-at-table-p)
22295 (push (list :table (org-table-begin) (org-table-end)) clist)
22296 (when (memq 'org-formula faces)
22297 (push (list :table-special
22298 (previous-single-property-change p 'face)
22299 (next-single-property-change p 'face)) clist)))
22300 ((org-at-table-p 'any)
22301 (push (list :table-table) clist)))
22302 (goto-char p)
22304 (let ((case-fold-search t))
22305 ;; New the "medium" contexts: clocktables, source blocks
22306 (cond ((org-in-clocktable-p)
22307 (push (list :clocktable
22308 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22309 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22310 (match-beginning 1))
22311 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22312 (match-end 0))) clist))
22313 ((org-in-src-block-p)
22314 (push (list :src-block
22315 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22316 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22317 (match-beginning 1))
22318 (and (search-forward "#+END_SRC" nil t)
22319 (match-beginning 0))) clist))))
22320 (goto-char p)
22322 ;; Now the small context
22323 (cond
22324 ((org-at-timestamp-p)
22325 (push (org-point-in-group p 0 :timestamp) clist))
22326 ((memq 'org-link faces)
22327 (push (list :link
22328 (previous-single-property-change p 'face)
22329 (next-single-property-change p 'face)) clist))
22330 ((memq 'org-special-keyword faces)
22331 (push (list :keyword
22332 (previous-single-property-change p 'face)
22333 (next-single-property-change p 'face)) clist))
22334 ((org-at-target-p)
22335 (push (org-point-in-group p 0 :target) clist)
22336 (goto-char (1- (match-beginning 0)))
22337 (when (looking-at org-radio-target-regexp)
22338 (push (org-point-in-group p 0 :radio-target) clist))
22339 (goto-char p))
22340 ((setq o (cl-some
22341 (lambda (o)
22342 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22344 (overlays-at (point))))
22345 (push (list :latex-fragment
22346 (overlay-start o) (overlay-end o)) clist)
22347 (push (list :latex-preview
22348 (overlay-start o) (overlay-end o)) clist))
22349 ((org-inside-LaTeX-fragment-p)
22350 ;; FIXME: positions wrong.
22351 (push (list :latex-fragment (point) (point)) clist)))
22353 (setq clist (nreverse (delq nil clist)))
22354 clist))
22356 (defun org-in-regexp (regexp &optional nlines visually)
22357 "Check if point is inside a match of REGEXP.
22359 Normally only the current line is checked, but you can include
22360 NLINES extra lines around point into the search. If VISUALLY is
22361 set, require that the cursor is not after the match but really
22362 on, so that the block visually is on the match.
22364 Return nil or a cons cell (BEG . END) where BEG and END are,
22365 respectively, the positions at the beginning and the end of the
22366 match."
22367 (catch :exit
22368 (let ((pos (point))
22369 (eol (line-end-position (if nlines (1+ nlines) 1))))
22370 (save-excursion
22371 (beginning-of-line (- 1 (or nlines 0)))
22372 (while (and (re-search-forward regexp eol t)
22373 (<= (match-beginning 0) pos))
22374 (let ((end (match-end 0)))
22375 (when (or (> end pos) (and (= end pos) (not visually)))
22376 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22378 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22379 "Non-nil when point is between matches of START-RE and END-RE.
22381 Also return a non-nil value when point is on one of the matches.
22383 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22384 buffer positions. Default values are the positions of headlines
22385 surrounding the point.
22387 The functions returns a cons cell whose car (resp. cdr) is the
22388 position before START-RE (resp. after END-RE)."
22389 (save-match-data
22390 (let ((pos (point))
22391 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22392 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22393 beg end)
22394 (save-excursion
22395 ;; Point is on a block when on START-RE or if START-RE can be
22396 ;; found before it...
22397 (and (or (org-in-regexp start-re)
22398 (re-search-backward start-re limit-up t))
22399 (setq beg (match-beginning 0))
22400 ;; ... and END-RE after it...
22401 (goto-char (match-end 0))
22402 (re-search-forward end-re limit-down t)
22403 (> (setq end (match-end 0)) pos)
22404 ;; ... without another START-RE in-between.
22405 (goto-char (match-beginning 0))
22406 (not (re-search-backward start-re (1+ beg) t))
22407 ;; Return value.
22408 (cons beg end))))))
22410 (defun org-in-block-p (names)
22411 "Non-nil when point belongs to a block whose name belongs to NAMES.
22413 NAMES is a list of strings containing names of blocks.
22415 Return first block name matched, or nil. Beware that in case of
22416 nested blocks, the returned name may not belong to the closest
22417 block from point."
22418 (save-match-data
22419 (catch 'exit
22420 (let ((case-fold-search t)
22421 (lim-up (save-excursion (outline-previous-heading)))
22422 (lim-down (save-excursion (outline-next-heading))))
22423 (dolist (name names)
22424 (let ((n (regexp-quote name)))
22425 (when (org-between-regexps-p
22426 (concat "^[ \t]*#\\+begin_" n)
22427 (concat "^[ \t]*#\\+end_" n)
22428 lim-up lim-down)
22429 (throw 'exit n)))))
22430 nil)))
22432 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22433 "Call `multi-occur' with buffers for all agenda files."
22434 (interactive "sOrg-files matching: ")
22435 (let* ((files (org-agenda-files))
22436 (tnames (mapcar #'file-truename files))
22437 (extra org-agenda-text-search-extra-files))
22438 (when (eq (car extra) 'agenda-archives)
22439 (setq extra (cdr extra))
22440 (setq files (org-add-archive-files files)))
22441 (dolist (f extra)
22442 (unless (member (file-truename f) tnames)
22443 (unless (member f files) (setq files (append files (list f))))
22444 (setq tnames (append tnames (list (file-truename f))))))
22445 (multi-occur
22446 (mapcar (lambda (x)
22447 (with-current-buffer
22448 ;; FIXME: Why not just (find-file-noselect x)?
22449 ;; Is it to avoid the "revert buffer" prompt?
22450 (or (get-file-buffer x) (find-file-noselect x))
22451 (widen)
22452 (current-buffer)))
22453 files)
22454 regexp)))
22456 (add-hook 'occur-mode-find-occurrence-hook
22457 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22459 (defun org-occur-link-in-agenda-files ()
22460 "Create a link and search for it in the agendas.
22461 The link is not stored in `org-stored-links', it is just created
22462 for the search purpose."
22463 (interactive)
22464 (let ((link (condition-case nil
22465 (org-store-link nil)
22466 (error "Unable to create a link to here"))))
22467 (org-occur-in-agenda-files (regexp-quote link))))
22469 (defun org-reverse-string (string)
22470 "Return the reverse of STRING."
22471 (apply 'string (reverse (string-to-list string))))
22473 ;; defsubst org-uniquify must be defined before first use
22475 (defun org-uniquify-alist (alist)
22476 "Merge elements of ALIST with the same key.
22478 For example, in this alist:
22480 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22481 => \\='((a 1 3) (b 2))
22483 merge (a 1) and (a 3) into (a 1 3).
22485 The function returns the new ALIST."
22486 (let (rtn)
22487 (dolist (e alist rtn)
22488 (let (n)
22489 (if (not (assoc (car e) rtn))
22490 (push e rtn)
22491 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22492 (setq rtn (assq-delete-all (car e) rtn))
22493 (push n rtn))))))
22495 (defun org-delete-all (elts list)
22496 "Remove all elements in ELTS from LIST.
22497 Comparison is done with `equal'. It is a destructive operation
22498 that may remove elements by altering the list structure."
22499 (while elts
22500 (setq list (delete (pop elts) list)))
22501 list)
22503 (defun org-back-over-empty-lines ()
22504 "Move backwards over whitespace, to the beginning of the first empty line.
22505 Returns the number of empty lines passed."
22506 (let ((pos (point)))
22507 (if (cdr (assq 'heading org-blank-before-new-entry))
22508 (skip-chars-backward " \t\n\r")
22509 (unless (eobp)
22510 (forward-line -1)))
22511 (beginning-of-line 2)
22512 (goto-char (min (point) pos))
22513 (count-lines (point) pos)))
22515 (defun org-skip-whitespace ()
22516 (skip-chars-forward " \t\n\r"))
22518 (defun org-point-in-group (point group &optional context)
22519 "Check if POINT is in match-group GROUP.
22520 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22521 match. If the match group does not exist or point is not inside it,
22522 return nil."
22523 (and (match-beginning group)
22524 (>= point (match-beginning group))
22525 (<= point (match-end group))
22526 (if context
22527 (list context (match-beginning group) (match-end group))
22528 t)))
22530 (defun org-switch-to-buffer-other-window (&rest args)
22531 "Switch to buffer in a second window on the current frame.
22532 In particular, do not allow pop-up frames.
22533 Returns the newly created buffer."
22534 (org-no-popups
22535 (apply 'switch-to-buffer-other-window args)))
22537 (defun org-combine-plists (&rest plists)
22538 "Create a single property list from all plists in PLISTS.
22539 The process starts by copying the first list, and then setting properties
22540 from the other lists. Settings in the last list are the most significant
22541 ones and overrule settings in the other lists."
22542 (let ((rtn (copy-sequence (pop plists)))
22543 p v ls)
22544 (while plists
22545 (setq ls (pop plists))
22546 (while ls
22547 (setq p (pop ls) v (pop ls))
22548 (setq rtn (plist-put rtn p v))))
22549 rtn))
22551 (defun org-replace-escapes (string table)
22552 "Replace %-escapes in STRING with values in TABLE.
22553 TABLE is an association list with keys like \"%a\" and string values.
22554 The sequences in STRING may contain normal field width and padding information,
22555 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22556 so values can contain further %-escapes if they are define later in TABLE."
22557 (let ((tbl (copy-alist table))
22558 (case-fold-search nil)
22559 (pchg 0)
22560 re rpl)
22561 (dolist (e tbl)
22562 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22563 (when (and (cdr e) (string-match re (cdr e)))
22564 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22565 (safe "SREF"))
22566 (add-text-properties 0 3 (list 'sref sref) safe)
22567 (setcdr e (replace-match safe t t (cdr e)))))
22568 (while (string-match re string)
22569 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22570 (cdr e)))
22571 (setq string (replace-match rpl t t string))))
22572 (while (setq pchg (next-property-change pchg string))
22573 (let ((sref (get-text-property pchg 'sref string)))
22574 (when (and sref (string-match "SREF" string pchg))
22575 (setq string (replace-match sref t t string)))))
22576 string))
22578 (defun org-find-base-buffer-visiting (file)
22579 "Like `find-buffer-visiting' but always return the base buffer and
22580 not an indirect buffer."
22581 (let ((buf (or (get-file-buffer file)
22582 (find-buffer-visiting file))))
22583 (if buf
22584 (or (buffer-base-buffer buf) buf)
22585 nil)))
22587 ;;; TODO: Only called once, from ox-odt which should probably use
22588 ;;; org-export-inline-image-p or something.
22589 (defun org-file-image-p (file)
22590 "Return non-nil if FILE is an image."
22591 (save-match-data
22592 (string-match (image-file-name-regexp) file)))
22594 (defun org-get-cursor-date (&optional with-time)
22595 "Return the date at cursor in as a time.
22596 This works in the calendar and in the agenda, anywhere else it just
22597 returns the current time.
22598 If WITH-TIME is non-nil, returns the time of the event at point (in
22599 the agenda) or the current time of the day."
22600 (let (date day defd tp hod mod)
22601 (when with-time
22602 (setq tp (get-text-property (point) 'time))
22603 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22604 (setq hod (string-to-number (match-string 1 tp))
22605 mod (string-to-number (match-string 2 tp))))
22606 (or tp (let ((now (decode-time)))
22607 (setq hod (nth 2 now)
22608 mod (nth 1 now)))))
22609 (cond
22610 ((eq major-mode 'calendar-mode)
22611 (setq date (calendar-cursor-to-date)
22612 defd (encode-time 0 (or mod 0) (or hod 0)
22613 (nth 1 date) (nth 0 date) (nth 2 date))))
22614 ((eq major-mode 'org-agenda-mode)
22615 (setq day (get-text-property (point) 'day))
22616 (when day
22617 (setq date (calendar-gregorian-from-absolute day)
22618 defd (encode-time 0 (or mod 0) (or hod 0)
22619 (nth 1 date) (nth 0 date) (nth 2 date))))))
22620 (or defd (current-time))))
22622 (defun org-mark-subtree (&optional up)
22623 "Mark the current subtree.
22624 This puts point at the start of the current subtree, and mark at
22625 the end. If a numeric prefix UP is given, move up into the
22626 hierarchy of headlines by UP levels before marking the subtree."
22627 (interactive "P")
22628 (org-with-limited-levels
22629 (cond ((org-at-heading-p) (beginning-of-line))
22630 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22631 (t (outline-previous-visible-heading 1))))
22632 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22633 (if (called-interactively-p 'any)
22634 (call-interactively 'org-mark-element)
22635 (org-mark-element)))
22637 (defun org-file-newer-than-p (file time)
22638 "Non-nil if FILE is newer than TIME.
22639 FILE is a filename, as a string, TIME is a list of integers, as
22640 returned by, e.g., `current-time'."
22641 (and (file-exists-p file)
22642 ;; Only compare times up to whole seconds as some file-systems
22643 ;; (e.g. HFS+) do not retain any finer granularity. As
22644 ;; a consequence, make sure we return non-nil when the two
22645 ;; times are equal.
22646 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22647 (cl-subseq time 0 2)))))
22649 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22650 "Compile a SOURCE file using PROCESS.
22652 PROCESS is either a function or a list of shell commands, as
22653 strings. EXT is a file extension, without the leading dot, as
22654 a string. It is used to check if the process actually succeeded.
22656 PROCESS must create a file with the same base name and directory
22657 as SOURCE, but ending with EXT. The function then returns its
22658 filename. Otherwise, it raises an error. The error message can
22659 then be refined by providing string ERR-MSG, which is appended to
22660 the standard message.
22662 If PROCESS is a function, it is called with a single argument:
22663 the SOURCE file.
22665 If it is a list of commands, each of them is called using
22666 `shell-command'. By default, in each command, %b, %f, %F, %o and
22667 %O are replaced with, respectively, SOURCE base name, name, full
22668 name, directory and absolute output file name. It is possible,
22669 however, to use more place-holders by specifying them in optional
22670 argument SPEC, as an alist following the pattern
22672 (CHARACTER . REPLACEMENT-STRING).
22674 When PROCESS is a list of commands, optional argument LOG-BUF can
22675 be set to a buffer or a buffer name. `shell-command' then uses
22676 it for output."
22677 (let* ((base-name (file-name-base source))
22678 (full-name (file-truename source))
22679 (out-dir (or (file-name-directory source) "./"))
22680 (output (expand-file-name (concat base-name "." ext) out-dir))
22681 (time (current-time))
22682 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22683 (save-window-excursion
22684 (pcase process
22685 ((pred functionp) (funcall process (shell-quote-argument source)))
22686 ((pred consp)
22687 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22688 (spec (append spec
22689 `((?b . ,(shell-quote-argument base-name))
22690 (?f . ,(shell-quote-argument source))
22691 (?F . ,(shell-quote-argument full-name))
22692 (?o . ,(shell-quote-argument out-dir))
22693 (?O . ,(shell-quote-argument output))))))
22694 (dolist (command process)
22695 (shell-command (format-spec command spec) log-buf))))
22696 (_ (error "No valid command to process %S%s" source err-msg))))
22697 ;; Check for process failure. Output file is expected to be
22698 ;; located in the same directory as SOURCE.
22699 (unless (org-file-newer-than-p output time)
22700 (error (format "File %S wasn't produced%s" output err-msg)))
22701 output))
22703 ;;; Indentation
22705 (defun org--get-expected-indentation (element contentsp)
22706 "Expected indentation column for current line, according to ELEMENT.
22707 ELEMENT is an element containing point. CONTENTSP is non-nil
22708 when indentation is to be computed according to contents of
22709 ELEMENT."
22710 (let ((type (org-element-type element))
22711 (start (org-element-property :begin element))
22712 (post-affiliated (org-element-property :post-affiliated element)))
22713 (org-with-wide-buffer
22714 (cond
22715 (contentsp
22716 (cl-case type
22717 ((diary-sexp footnote-definition) 0)
22718 ((headline inlinetask nil)
22719 (if (not org-adapt-indentation) 0
22720 (let ((level (org-current-level)))
22721 (if level (1+ level) 0))))
22722 ((item plain-list) (org-list-item-body-column post-affiliated))
22724 (goto-char start)
22725 (org-get-indentation))))
22726 ((memq type '(headline inlinetask nil))
22727 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22728 (org--get-expected-indentation element t)
22730 ((memq type '(diary-sexp footnote-definition)) 0)
22731 ;; First paragraph of a footnote definition or an item.
22732 ;; Indent like parent.
22733 ((< (line-beginning-position) start)
22734 (org--get-expected-indentation
22735 (org-element-property :parent element) t))
22736 ;; At first line: indent according to previous sibling, if any,
22737 ;; ignoring footnote definitions and inline tasks, or parent's
22738 ;; contents.
22739 ((= (line-beginning-position) start)
22740 (catch 'exit
22741 (while t
22742 (if (= (point-min) start) (throw 'exit 0)
22743 (goto-char (1- start))
22744 (let* ((previous (org-element-at-point))
22745 (parent previous))
22746 (while (and parent (<= (org-element-property :end parent) start))
22747 (setq previous parent
22748 parent (org-element-property :parent parent)))
22749 (cond
22750 ((not previous) (throw 'exit 0))
22751 ((> (org-element-property :end previous) start)
22752 (throw 'exit (org--get-expected-indentation previous t)))
22753 ((memq (org-element-type previous)
22754 '(footnote-definition inlinetask))
22755 (setq start (org-element-property :begin previous)))
22756 (t (goto-char (org-element-property :begin previous))
22757 (throw 'exit
22758 (if (bolp) (org-get-indentation)
22759 ;; At first paragraph in an item or
22760 ;; a footnote definition.
22761 (org--get-expected-indentation
22762 (org-element-property :parent previous) t))))))))))
22763 ;; Otherwise, move to the first non-blank line above.
22765 (beginning-of-line)
22766 (let ((pos (point)))
22767 (skip-chars-backward " \r\t\n")
22768 (cond
22769 ;; Two blank lines end a footnote definition or a plain
22770 ;; list. When we indent an empty line after them, the
22771 ;; containing list or footnote definition is over, so it
22772 ;; qualifies as a previous sibling. Therefore, we indent
22773 ;; like its first line.
22774 ((and (memq type '(footnote-definition plain-list))
22775 (> (count-lines (point) pos) 2))
22776 (goto-char start)
22777 (org-get-indentation))
22778 ;; Line above is the first one of a paragraph at the
22779 ;; beginning of an item or a footnote definition. Indent
22780 ;; like parent.
22781 ((< (line-beginning-position) start)
22782 (org--get-expected-indentation
22783 (org-element-property :parent element) t))
22784 ;; Line above is the beginning of an element, i.e., point
22785 ;; was originally on the blank lines between element's start
22786 ;; and contents.
22787 ((= (line-beginning-position) post-affiliated)
22788 (org--get-expected-indentation element t))
22789 ;; POS is after contents in a greater element. Indent like
22790 ;; the beginning of the element.
22792 ;; As a special case, if point is at the end of a footnote
22793 ;; definition or an item, indent like the very last element
22794 ;; within. If that last element is an item, indent like its
22795 ;; contents.
22796 ((and (not (eq type 'paragraph))
22797 (let ((cend (org-element-property :contents-end element)))
22798 (and cend (<= cend pos))))
22799 (if (memq type '(footnote-definition item plain-list))
22800 (let ((last (org-element-at-point)))
22801 (org--get-expected-indentation
22802 last (eq (org-element-type last) 'item)))
22803 (goto-char start)
22804 (org-get-indentation)))
22805 ;; In any other case, indent like the current line.
22806 (t (org-get-indentation)))))))))
22808 (defun org--align-node-property ()
22809 "Align node property at point.
22810 Alignment is done according to `org-property-format', which see."
22811 (when (save-excursion
22812 (beginning-of-line)
22813 (looking-at org-property-re))
22814 (replace-match
22815 (concat (match-string 4)
22816 (org-trim
22817 (format org-property-format (match-string 1) (match-string 3))))
22818 t t)))
22820 (defun org-indent-line ()
22821 "Indent line depending on context.
22823 Indentation is done according to the following rules:
22825 - Footnote definitions, diary sexps, headlines and inline tasks
22826 have to start at column 0.
22828 - On the very first line of an element, consider, in order, the
22829 next rules until one matches:
22831 1. If there's a sibling element before, ignoring footnote
22832 definitions and inline tasks, indent like its first line.
22834 2. If element has a parent, indent like its contents. More
22835 precisely, if parent is an item, indent after the
22836 description part, if any, or the bullet (see
22837 `org-list-description-max-indent'). Else, indent like
22838 parent's first line.
22840 3. Otherwise, indent relatively to current level, if
22841 `org-adapt-indentation' is non-nil, or to left margin.
22843 - On a blank line at the end of an element, indent according to
22844 the type of the element. More precisely
22846 1. If element is a plain list, an item, or a footnote
22847 definition, indent like the very last element within.
22849 2. If element is a paragraph, indent like its last non blank
22850 line.
22852 3. Otherwise, indent like its very first line.
22854 - In the code part of a source block, use language major mode
22855 to indent current line if `org-src-tab-acts-natively' is
22856 non-nil. If it is nil, do nothing.
22858 - Otherwise, indent like the first non-blank line above.
22860 The function doesn't indent an item as it could break the whole
22861 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22862 `\\[org-shiftmetaright]'.
22864 Also align node properties according to `org-property-format'."
22865 (interactive)
22866 (cond
22867 (orgstruct-is-++
22868 (let ((indent-line-function
22869 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22870 (indent-according-to-mode)))
22871 ((org-at-heading-p) 'noindent)
22873 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22874 (type (org-element-type element)))
22875 (cond ((and (memq type '(plain-list item))
22876 (= (line-beginning-position)
22877 (org-element-property :post-affiliated element)))
22878 'noindent)
22879 ((and (eq type 'src-block)
22880 org-src-tab-acts-natively
22881 (> (line-beginning-position)
22882 (org-element-property :post-affiliated element))
22883 (< (line-beginning-position)
22884 (org-with-wide-buffer
22885 (goto-char (org-element-property :end element))
22886 (skip-chars-backward " \r\t\n")
22887 (line-beginning-position))))
22888 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22890 (let ((column (org--get-expected-indentation element nil)))
22891 ;; Preserve current column.
22892 (if (<= (current-column) (current-indentation))
22893 (indent-line-to column)
22894 (save-excursion (indent-line-to column))))
22895 ;; Align node property. Also preserve current column.
22896 (when (eq type 'node-property)
22897 (let ((column (current-column)))
22898 (org--align-node-property)
22899 (org-move-to-column column)))))))))
22901 (defun org-indent-region (start end)
22902 "Indent each non-blank line in the region.
22903 Called from a program, START and END specify the region to
22904 indent. The function will not indent contents of example blocks,
22905 verse blocks and export blocks as leading white spaces are
22906 assumed to be significant there."
22907 (interactive "r")
22908 (save-excursion
22909 (goto-char start)
22910 (skip-chars-forward " \r\t\n")
22911 (unless (eobp) (beginning-of-line))
22912 (let ((indent-to
22913 (lambda (ind pos)
22914 ;; Set IND as indentation for all lines between point and
22915 ;; POS. Blank lines are ignored. Leave point after POS
22916 ;; once done.
22917 (let ((limit (copy-marker pos)))
22918 (while (< (point) limit)
22919 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22920 (forward-line))
22921 (set-marker limit nil))))
22922 (end (copy-marker end)))
22923 (while (< (point) end)
22924 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22925 (let* ((element (org-element-at-point))
22926 (type (org-element-type element))
22927 (element-end (copy-marker (org-element-property :end element)))
22928 (ind (org--get-expected-indentation element nil)))
22929 (cond
22930 ((or (memq type '(paragraph table table-row))
22931 (not (or (org-element-property :contents-begin element)
22932 (memq type
22933 '(example-block export-block src-block)))))
22934 ;; Elements here are indented as a single block. Also
22935 ;; align node properties.
22936 (when (eq type 'node-property)
22937 (org--align-node-property)
22938 (beginning-of-line))
22939 (funcall indent-to ind (min element-end end)))
22941 ;; Elements in this category consist of three parts:
22942 ;; before the contents, the contents, and after the
22943 ;; contents. The contents are treated specially,
22944 ;; according to the element type, or not indented at
22945 ;; all. Other parts are indented as a single block.
22946 (let* ((post (copy-marker
22947 (org-element-property :post-affiliated element)))
22948 (cbeg
22949 (copy-marker
22950 (cond
22951 ((not (org-element-property :contents-begin element))
22952 ;; Fake contents for source blocks.
22953 (org-with-wide-buffer
22954 (goto-char post)
22955 (forward-line)
22956 (point)))
22957 ((memq type '(footnote-definition item plain-list))
22958 ;; Contents in these elements could start on
22959 ;; the same line as the beginning of the
22960 ;; element. Make sure we start indenting
22961 ;; from the second line.
22962 (org-with-wide-buffer
22963 (goto-char post)
22964 (end-of-line)
22965 (skip-chars-forward " \r\t\n")
22966 (if (eobp) (point) (line-beginning-position))))
22967 (t (org-element-property :contents-begin element)))))
22968 (cend (copy-marker
22969 (or (org-element-property :contents-end element)
22970 ;; Fake contents for source blocks.
22971 (org-with-wide-buffer
22972 (goto-char element-end)
22973 (skip-chars-backward " \r\t\n")
22974 (line-beginning-position)))
22975 t)))
22976 ;; Do not change items indentation individually as it
22977 ;; might break the list as a whole. On the other
22978 ;; hand, when at a plain list, indent it as a whole.
22979 (cond ((eq type 'plain-list)
22980 (let ((offset (- ind (org-get-indentation))))
22981 (unless (zerop offset)
22982 (indent-rigidly (org-element-property :begin element)
22983 (org-element-property :end element)
22984 offset))
22985 (goto-char cbeg)))
22986 ((eq type 'item) (goto-char cbeg))
22987 (t (funcall indent-to ind (min cbeg end))))
22988 (when (< (point) end)
22989 (cl-case type
22990 ((example-block export-block verse-block))
22991 (src-block
22992 ;; In a source block, indent source code
22993 ;; according to language major mode, but only if
22994 ;; `org-src-tab-acts-natively' is non-nil.
22995 (when (and (< (point) end) org-src-tab-acts-natively)
22996 (ignore-errors
22997 (org-babel-do-in-edit-buffer
22998 (indent-region (point-min) (point-max))))))
22999 (t (org-indent-region (point) (min cend end))))
23000 (goto-char (min cend end))
23001 (when (< (point) end)
23002 (funcall indent-to ind (min element-end end))))
23003 (set-marker post nil)
23004 (set-marker cbeg nil)
23005 (set-marker cend nil))))
23006 (set-marker element-end nil))))
23007 (set-marker end nil))))
23009 (defun org-indent-drawer ()
23010 "Indent the drawer at point."
23011 (interactive)
23012 (unless (save-excursion
23013 (beginning-of-line)
23014 (looking-at-p org-drawer-regexp))
23015 (user-error "Not at a drawer"))
23016 (let ((element (org-element-at-point)))
23017 (unless (memq (org-element-type element) '(drawer property-drawer))
23018 (user-error "Not at a drawer"))
23019 (org-with-wide-buffer
23020 (org-indent-region (org-element-property :begin element)
23021 (org-element-property :end element))))
23022 (message "Drawer at point indented"))
23024 (defun org-indent-block ()
23025 "Indent the block at point."
23026 (interactive)
23027 (unless (save-excursion
23028 (beginning-of-line)
23029 (let ((case-fold-search t))
23030 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23031 (user-error "Not at a block"))
23032 (let ((element (org-element-at-point)))
23033 (unless (memq (org-element-type element)
23034 '(comment-block center-block dynamic-block example-block
23035 export-block quote-block special-block
23036 src-block verse-block))
23037 (user-error "Not at a block"))
23038 (org-with-wide-buffer
23039 (org-indent-region (org-element-property :begin element)
23040 (org-element-property :end element))))
23041 (message "Block at point indented"))
23044 ;;; Filling
23046 ;; We use our own fill-paragraph and auto-fill functions.
23048 ;; `org-fill-paragraph' relies on adaptive filling and context
23049 ;; checking. Appropriate `fill-prefix' is computed with
23050 ;; `org-adaptive-fill-function'.
23052 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23053 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23054 ;; `org-adaptive-fill-function' value. Internally,
23055 ;; `org-comment-line-break-function' breaks the line.
23057 ;; `org-setup-filling' installs filling and auto-filling related
23058 ;; variables during `org-mode' initialization.
23060 (defvar org-element-paragraph-separate) ; org-element.el
23061 (defun org-setup-filling ()
23062 (require 'org-element)
23063 ;; Prevent auto-fill from inserting unwanted new items.
23064 (when (boundp 'fill-nobreak-predicate)
23065 (setq-local
23066 fill-nobreak-predicate
23067 (org-uniquify
23068 (append fill-nobreak-predicate
23069 '(org-fill-line-break-nobreak-p
23070 org-fill-paragraph-with-timestamp-nobreak-p)))))
23071 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23072 (setq-local paragraph-start paragraph-ending)
23073 (setq-local paragraph-separate paragraph-ending))
23074 (setq-local fill-paragraph-function 'org-fill-paragraph)
23075 (setq-local auto-fill-inhibit-regexp nil)
23076 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23077 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23078 (setq-local comment-line-break-function 'org-comment-line-break-function))
23080 (defun org-fill-line-break-nobreak-p ()
23081 "Non-nil when a new line at point would create an Org line break."
23082 (save-excursion
23083 (skip-chars-backward "[ \t]")
23084 (skip-chars-backward "\\\\")
23085 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23087 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23088 "Non-nil when a new line at point would split a timestamp."
23089 (and (org-at-timestamp-p t)
23090 (not (looking-at org-ts-regexp-both))))
23092 (declare-function message-in-body-p "message" ())
23093 (defvar orgtbl-line-start-regexp) ; From org-table.el
23094 (defun org-adaptive-fill-function ()
23095 "Compute a fill prefix for the current line.
23096 Return fill prefix, as a string, or nil if current line isn't
23097 meant to be filled. For convenience, if `adaptive-fill-regexp'
23098 matches in paragraphs or comments, use it."
23099 (catch 'exit
23100 (when (derived-mode-p 'message-mode)
23101 (save-excursion
23102 (beginning-of-line)
23103 (cond ((not (message-in-body-p)) (throw 'exit nil))
23104 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23105 ((looking-at message-cite-prefix-regexp)
23106 (throw 'exit (match-string-no-properties 0)))
23107 ((looking-at org-outline-regexp)
23108 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23109 (org-with-wide-buffer
23110 (unless (org-at-heading-p)
23111 (let* ((p (line-beginning-position))
23112 (element (save-excursion
23113 (beginning-of-line)
23114 (org-element-at-point)))
23115 (type (org-element-type element))
23116 (post-affiliated (org-element-property :post-affiliated element)))
23117 (unless (< p post-affiliated)
23118 (cl-case type
23119 (comment
23120 (save-excursion
23121 (beginning-of-line)
23122 (looking-at "[ \t]*")
23123 (concat (match-string 0) "# ")))
23124 (footnote-definition "")
23125 ((item plain-list)
23126 (make-string (org-list-item-body-column post-affiliated) ?\s))
23127 (paragraph
23128 ;; Fill prefix is usually the same as the current line,
23129 ;; unless the paragraph is at the beginning of an item.
23130 (let ((parent (org-element-property :parent element)))
23131 (save-excursion
23132 (beginning-of-line)
23133 (cond ((eq (org-element-type parent) 'item)
23134 (make-string (org-list-item-body-column
23135 (org-element-property :begin parent))
23136 ?\s))
23137 ((and adaptive-fill-regexp
23138 ;; Locally disable
23139 ;; `adaptive-fill-function' to let
23140 ;; `fill-context-prefix' handle
23141 ;; `adaptive-fill-regexp' variable.
23142 (let (adaptive-fill-function)
23143 (fill-context-prefix
23144 post-affiliated
23145 (org-element-property :end element)))))
23146 ((looking-at "[ \t]+") (match-string 0))
23147 (t "")))))
23148 (comment-block
23149 ;; Only fill contents if P is within block boundaries.
23150 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23151 (forward-line)
23152 (point)))
23153 (cend (save-excursion
23154 (goto-char (org-element-property :end element))
23155 (skip-chars-backward " \r\t\n")
23156 (line-beginning-position))))
23157 (when (and (>= p cbeg) (< p cend))
23158 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23159 (match-string 0)
23160 "")))))))))))
23162 (declare-function message-goto-body "message" ())
23163 (defvar message-cite-prefix-regexp) ; From message.el
23164 (defun org-fill-paragraph (&optional justify)
23165 "Fill element at point, when applicable.
23167 This function only applies to comment blocks, comments, example
23168 blocks and paragraphs. Also, as a special case, re-align table
23169 when point is at one.
23171 If JUSTIFY is non-nil (interactively, with prefix argument),
23172 justify as well. If `sentence-end-double-space' is non-nil, then
23173 period followed by one space does not end a sentence, so don't
23174 break a line there. The variable `fill-column' controls the
23175 width for filling.
23177 For convenience, when point is at a plain list, an item or
23178 a footnote definition, try to fill the first paragraph within."
23179 (interactive)
23180 (if (and (derived-mode-p 'message-mode)
23181 (or (not (message-in-body-p))
23182 (save-excursion (move-beginning-of-line 1)
23183 (looking-at message-cite-prefix-regexp))))
23184 ;; First ensure filling is correct in message-mode.
23185 (let ((fill-paragraph-function
23186 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23187 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23188 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23189 (paragraph-separate
23190 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23191 (fill-paragraph nil))
23192 (with-syntax-table org-mode-transpose-word-syntax-table
23193 ;; Move to end of line in order to get the first paragraph
23194 ;; within a plain list or a footnote definition.
23195 (let ((element (save-excursion
23196 (end-of-line)
23197 (or (ignore-errors (org-element-at-point))
23198 (user-error "An element cannot be parsed line %d"
23199 (line-number-at-pos (point)))))))
23200 ;; First check if point is in a blank line at the beginning of
23201 ;; the buffer. In that case, ignore filling.
23202 (cl-case (org-element-type element)
23203 ;; Use major mode filling function is src blocks.
23204 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23205 ;; Align Org tables, leave table.el tables as-is.
23206 (table-row (org-table-align) t)
23207 (table
23208 (when (eq (org-element-property :type element) 'org)
23209 (save-excursion
23210 (goto-char (org-element-property :post-affiliated element))
23211 (org-table-align)))
23213 (paragraph
23214 ;; Paragraphs may contain `line-break' type objects.
23215 (let ((beg (max (point-min)
23216 (org-element-property :contents-begin element)))
23217 (end (min (point-max)
23218 (org-element-property :contents-end element))))
23219 ;; Do nothing if point is at an affiliated keyword.
23220 (if (< (line-end-position) beg) t
23221 (when (derived-mode-p 'message-mode)
23222 ;; In `message-mode', do not fill following citation
23223 ;; in current paragraph nor text before message body.
23224 (let ((body-start (save-excursion (message-goto-body))))
23225 (when body-start (setq beg (max body-start beg))))
23226 (when (save-excursion
23227 (re-search-forward
23228 (concat "^" message-cite-prefix-regexp) end t))
23229 (setq end (match-beginning 0))))
23230 ;; Fill paragraph, taking line breaks into account.
23231 (save-excursion
23232 (goto-char beg)
23233 (let ((cuts (list beg)))
23234 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23235 (when (eq 'line-break
23236 (org-element-type
23237 (save-excursion (backward-char)
23238 (org-element-context))))
23239 (push (point) cuts)))
23240 (dolist (c (delq end cuts))
23241 (fill-region-as-paragraph c end justify)
23242 (setq end c))))
23243 t)))
23244 ;; Contents of `comment-block' type elements should be
23245 ;; filled as plain text, but only if point is within block
23246 ;; markers.
23247 (comment-block
23248 (let* ((case-fold-search t)
23249 (beg (save-excursion
23250 (goto-char (org-element-property :begin element))
23251 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23252 (forward-line)
23253 (point)))
23254 (end (save-excursion
23255 (goto-char (org-element-property :end element))
23256 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23257 (line-beginning-position))))
23258 (if (or (< (point) beg) (> (point) end)) t
23259 (fill-region-as-paragraph
23260 (save-excursion (end-of-line)
23261 (re-search-backward "^[ \t]*$" beg 'move)
23262 (line-beginning-position))
23263 (save-excursion (beginning-of-line)
23264 (re-search-forward "^[ \t]*$" end 'move)
23265 (line-beginning-position))
23266 justify))))
23267 ;; Fill comments.
23268 (comment
23269 (let ((begin (org-element-property :post-affiliated element))
23270 (end (org-element-property :end element)))
23271 (when (and (>= (point) begin) (<= (point) end))
23272 (let ((begin (save-excursion
23273 (end-of-line)
23274 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23275 (progn (forward-line) (point))
23276 begin)))
23277 (end (save-excursion
23278 (end-of-line)
23279 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23280 (1- (line-beginning-position))
23281 (skip-chars-backward " \r\t\n")
23282 (line-end-position)))))
23283 ;; Do not fill comments when at a blank line.
23284 (when (> end begin)
23285 (let ((fill-prefix
23286 (save-excursion
23287 (beginning-of-line)
23288 (looking-at "[ \t]*#")
23289 (let ((comment-prefix (match-string 0)))
23290 (goto-char (match-end 0))
23291 (if (looking-at adaptive-fill-regexp)
23292 (concat comment-prefix (match-string 0))
23293 (concat comment-prefix " "))))))
23294 (save-excursion
23295 (fill-region-as-paragraph begin end justify))))))
23297 ;; Ignore every other element.
23298 (otherwise t))))))
23300 (defun org-auto-fill-function ()
23301 "Auto-fill function."
23302 ;; Check if auto-filling is meaningful.
23303 (let ((fc (current-fill-column)))
23304 (when (and fc (> (current-column) fc))
23305 (let* ((fill-prefix (org-adaptive-fill-function))
23306 ;; Enforce empty fill prefix, if required. Otherwise, it
23307 ;; will be computed again.
23308 (adaptive-fill-mode (not (equal fill-prefix ""))))
23309 (when fill-prefix (do-auto-fill))))))
23311 (defun org-comment-line-break-function (&optional soft)
23312 "Break line at point and indent, continuing comment if within one.
23313 The inserted newline is marked hard if variable
23314 `use-hard-newlines' is true, unless optional argument SOFT is
23315 non-nil."
23316 (if soft (insert-and-inherit ?\n) (newline 1))
23317 (save-excursion (forward-char -1) (delete-horizontal-space))
23318 (delete-horizontal-space)
23319 (indent-to-left-margin)
23320 (insert-before-markers-and-inherit fill-prefix))
23323 ;;; Fixed Width Areas
23325 (defun org-toggle-fixed-width ()
23326 "Toggle fixed-width markup.
23328 Add or remove fixed-width markup on current line, whenever it
23329 makes sense. Return an error otherwise.
23331 If a region is active and if it contains only fixed-width areas
23332 or blank lines, remove all fixed-width markup in it. If the
23333 region contains anything else, convert all non-fixed-width lines
23334 to fixed-width ones.
23336 Blank lines at the end of the region are ignored unless the
23337 region only contains such lines."
23338 (interactive)
23339 (if (not (org-region-active-p))
23340 ;; No region:
23342 ;; Remove fixed width marker only in a fixed-with element.
23344 ;; Add fixed width maker in paragraphs, in blank lines after
23345 ;; elements or at the beginning of a headline or an inlinetask,
23346 ;; and before any one-line elements (e.g., a clock).
23347 (progn
23348 (beginning-of-line)
23349 (let* ((element (org-element-at-point))
23350 (type (org-element-type element)))
23351 (cond
23352 ((and (eq type 'fixed-width)
23353 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23354 (replace-match
23355 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23356 ((and (memq type '(babel-call clock comment diary-sexp headline
23357 horizontal-rule keyword paragraph
23358 planning))
23359 (<= (org-element-property :post-affiliated element) (point)))
23360 (skip-chars-forward " \t")
23361 (insert ": "))
23362 ((and (looking-at-p "[ \t]*$")
23363 (or (eq type 'inlinetask)
23364 (save-excursion
23365 (skip-chars-forward " \r\t\n")
23366 (<= (org-element-property :end element) (point)))))
23367 (delete-region (point) (line-end-position))
23368 (org-indent-line)
23369 (insert ": "))
23370 (t (user-error "Cannot insert a fixed-width line here")))))
23371 ;; Region active.
23372 (let* ((begin (save-excursion
23373 (goto-char (region-beginning))
23374 (line-beginning-position)))
23375 (end (copy-marker
23376 (save-excursion
23377 (goto-char (region-end))
23378 (unless (eolp) (beginning-of-line))
23379 (if (save-excursion (re-search-backward "\\S-" begin t))
23380 (progn (skip-chars-backward " \r\t\n") (point))
23381 (point)))))
23382 (all-fixed-width-p
23383 (catch 'not-all-p
23384 (save-excursion
23385 (goto-char begin)
23386 (skip-chars-forward " \r\t\n")
23387 (when (eobp) (throw 'not-all-p nil))
23388 (while (< (point) end)
23389 (let ((element (org-element-at-point)))
23390 (if (eq (org-element-type element) 'fixed-width)
23391 (goto-char (org-element-property :end element))
23392 (throw 'not-all-p nil))))
23393 t))))
23394 (if all-fixed-width-p
23395 (save-excursion
23396 (goto-char begin)
23397 (while (< (point) end)
23398 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23399 (replace-match
23400 "" nil nil nil
23401 (if (= (line-end-position) (match-end 0)) 0 1)))
23402 (forward-line)))
23403 (let ((min-ind (point-max)))
23404 ;; Find minimum indentation across all lines.
23405 (save-excursion
23406 (goto-char begin)
23407 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23408 (setq min-ind 0)
23409 (catch 'zerop
23410 (while (< (point) end)
23411 (unless (looking-at-p "[ \t]*$")
23412 (let ((ind (org-get-indentation)))
23413 (setq min-ind (min min-ind ind))
23414 (when (zerop ind) (throw 'zerop t))))
23415 (forward-line)))))
23416 ;; Loop over all lines and add fixed-width markup everywhere
23417 ;; but in fixed-width lines.
23418 (save-excursion
23419 (goto-char begin)
23420 (while (< (point) end)
23421 (cond
23422 ((org-at-heading-p)
23423 (insert ": ")
23424 (forward-line)
23425 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23426 (insert ":")
23427 (forward-line)))
23428 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23429 (let* ((element (org-element-at-point))
23430 (element-end (org-element-property :end element)))
23431 (if (eq (org-element-type element) 'fixed-width)
23432 (progn (goto-char element-end)
23433 (skip-chars-backward " \r\t\n")
23434 (forward-line))
23435 (let ((limit (min end element-end)))
23436 (while (< (point) limit)
23437 (org-move-to-column min-ind t)
23438 (insert ": ")
23439 (forward-line))))))
23441 (org-move-to-column min-ind t)
23442 (insert ": ")
23443 (forward-line)))))))
23444 (set-marker end nil))))
23447 ;;; Comments
23449 ;; Org comments syntax is quite complex. It requires the entire line
23450 ;; to be just a comment. Also, even with the right syntax at the
23451 ;; beginning of line, some some elements (i.e. verse-block or
23452 ;; example-block) don't accept comments. Usual Emacs comment commands
23453 ;; cannot cope with those requirements. Therefore, Org replaces them.
23455 ;; Org still relies on `comment-dwim', but cannot trust
23456 ;; `comment-only-p'. So, `comment-region-function' and
23457 ;; `uncomment-region-function' both point
23458 ;; to`org-comment-or-uncomment-region'. Eventually,
23459 ;; `org-insert-comment' takes care of insertion of comments at the
23460 ;; beginning of line.
23462 ;; `org-setup-comments-handling' install comments related variables
23463 ;; during `org-mode' initialization.
23465 (defun org-setup-comments-handling ()
23466 (interactive)
23467 (setq-local comment-use-syntax nil)
23468 (setq-local comment-start "# ")
23469 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23470 (setq-local comment-insert-comment-function 'org-insert-comment)
23471 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23472 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23474 (defun org-insert-comment ()
23475 "Insert an empty comment above current line.
23476 If the line is empty, insert comment at its beginning. When
23477 point is within a source block, comment according to the related
23478 major mode."
23479 (if (let ((element (org-element-at-point)))
23480 (and (eq (org-element-type element) 'src-block)
23481 (< (save-excursion
23482 (goto-char (org-element-property :post-affiliated element))
23483 (line-end-position))
23484 (point))
23485 (> (save-excursion
23486 (goto-char (org-element-property :end element))
23487 (skip-chars-backward " \r\t\n")
23488 (line-beginning-position))
23489 (point))))
23490 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23491 (beginning-of-line)
23492 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23493 (open-line 1))
23494 (org-indent-line)
23495 (insert "# ")))
23497 (defvar comment-empty-lines) ; From newcomment.el.
23498 (defun org-comment-or-uncomment-region (beg end &rest _)
23499 "Comment or uncomment each non-blank line in the region.
23500 Uncomment each non-blank line between BEG and END if it only
23501 contains commented lines. Otherwise, comment them. If region is
23502 strictly within a source block, use appropriate comment syntax."
23503 (if (let ((element (org-element-at-point)))
23504 (and (eq (org-element-type element) 'src-block)
23505 (< (save-excursion
23506 (goto-char (org-element-property :post-affiliated element))
23507 (line-end-position))
23508 beg)
23509 (>= (save-excursion
23510 (goto-char (org-element-property :end element))
23511 (skip-chars-backward " \r\t\n")
23512 (line-beginning-position))
23513 end)))
23514 ;; Translate region boundaries for the Org buffer to the source
23515 ;; buffer.
23516 (let ((offset (- end beg)))
23517 (save-excursion
23518 (goto-char beg)
23519 (org-babel-do-in-edit-buffer
23520 (comment-or-uncomment-region (point) (+ offset (point))))))
23521 (save-restriction
23522 ;; Restrict region
23523 (narrow-to-region (save-excursion (goto-char beg)
23524 (skip-chars-forward " \r\t\n" end)
23525 (line-beginning-position))
23526 (save-excursion (goto-char end)
23527 (skip-chars-backward " \r\t\n" beg)
23528 (line-end-position)))
23529 (let ((uncommentp
23530 ;; UNCOMMENTP is non-nil when every non blank line between
23531 ;; BEG and END is a comment.
23532 (save-excursion
23533 (goto-char (point-min))
23534 (while (and (not (eobp))
23535 (let ((element (org-element-at-point)))
23536 (and (eq (org-element-type element) 'comment)
23537 (goto-char (min (point-max)
23538 (org-element-property
23539 :end element)))))))
23540 (eobp))))
23541 (if uncommentp
23542 ;; Only blank lines and comments in region: uncomment it.
23543 (save-excursion
23544 (goto-char (point-min))
23545 (while (not (eobp))
23546 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23547 (replace-match "" nil nil nil 1))
23548 (forward-line)))
23549 ;; Comment each line in region.
23550 (let ((min-indent (point-max)))
23551 ;; First find the minimum indentation across all lines.
23552 (save-excursion
23553 (goto-char (point-min))
23554 (while (and (not (eobp)) (not (zerop min-indent)))
23555 (unless (looking-at "[ \t]*$")
23556 (setq min-indent (min min-indent (current-indentation))))
23557 (forward-line)))
23558 ;; Then loop over all lines.
23559 (save-excursion
23560 (goto-char (point-min))
23561 (while (not (eobp))
23562 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23563 ;; Don't get fooled by invisible text (e.g. link path)
23564 ;; when moving to column MIN-INDENT.
23565 (let ((buffer-invisibility-spec nil))
23566 (org-move-to-column min-indent t))
23567 (insert comment-start))
23568 (forward-line)))))))))
23570 (defun org-comment-dwim (_arg)
23571 "Call `comment-dwim' within a source edit buffer if needed."
23572 (interactive "*P")
23573 (if (org-in-src-block-p)
23574 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23575 (call-interactively 'comment-dwim)))
23578 ;;; Timestamps API
23580 ;; This section contains tools to operate on timestamp objects, as
23581 ;; returned by, e.g. `org-element-context'.
23583 (defun org-timestamp--to-internal-time (timestamp &optional end)
23584 "Encode TIMESTAMP object into Emacs internal time.
23585 Use end of date range or time range when END is non-nil."
23586 (apply #'encode-time
23587 (cons 0
23588 (mapcar
23589 (lambda (prop) (or (org-element-property prop timestamp) 0))
23590 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23591 '(:minute-start :hour-start :day-start :month-start
23592 :year-start))))))
23594 (defun org-timestamp-has-time-p (timestamp)
23595 "Non-nil when TIMESTAMP has a time specified."
23596 (org-element-property :hour-start timestamp))
23598 (defun org-timestamp-format (timestamp format &optional end utc)
23599 "Format a TIMESTAMP object into a string.
23601 FORMAT is a format specifier to be passed to
23602 `format-time-string'.
23604 When optional argument END is non-nil, use end of date-range or
23605 time-range, if possible.
23607 When optional argument UTC is non-nil, time will be expressed as
23608 Universal Time."
23609 (format-time-string
23610 format (org-timestamp--to-internal-time timestamp end)
23611 (and utc t)))
23613 (defun org-timestamp-split-range (timestamp &optional end)
23614 "Extract a TIMESTAMP object from a date or time range.
23616 END, when non-nil, means extract the end of the range.
23617 Otherwise, extract its start.
23619 Return a new timestamp object."
23620 (let ((type (org-element-property :type timestamp)))
23621 (if (memq type '(active inactive diary)) timestamp
23622 (let ((split-ts (org-element-copy timestamp)))
23623 ;; Set new type.
23624 (org-element-put-property
23625 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23626 ;; Copy start properties over end properties if END is
23627 ;; non-nil. Otherwise, copy end properties over `start' ones.
23628 (let ((p-alist '((:minute-start . :minute-end)
23629 (:hour-start . :hour-end)
23630 (:day-start . :day-end)
23631 (:month-start . :month-end)
23632 (:year-start . :year-end))))
23633 (dolist (p-cell p-alist)
23634 (org-element-put-property
23635 split-ts
23636 (funcall (if end #'car #'cdr) p-cell)
23637 (org-element-property
23638 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23639 ;; Eventually refresh `:raw-value'.
23640 (org-element-put-property split-ts :raw-value nil)
23641 (org-element-put-property
23642 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23644 (defun org-timestamp-translate (timestamp &optional boundary)
23645 "Translate TIMESTAMP object to custom format.
23647 Format string is defined in `org-time-stamp-custom-formats',
23648 which see.
23650 When optional argument BOUNDARY is non-nil, it is either the
23651 symbol `start' or `end'. In this case, only translate the
23652 starting or ending part of TIMESTAMP if it is a date or time
23653 range. Otherwise, translate both parts.
23655 Return timestamp as-is if `org-display-custom-times' is nil or if
23656 it has a `diary' type."
23657 (let ((type (org-element-property :type timestamp)))
23658 (if (or (not org-display-custom-times) (eq type 'diary))
23659 (org-element-interpret-data timestamp)
23660 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23661 org-time-stamp-custom-formats)))
23662 (if (and (not boundary) (memq type '(active-range inactive-range)))
23663 (concat (org-timestamp-format timestamp fmt)
23664 "--"
23665 (org-timestamp-format timestamp fmt t))
23666 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23670 ;;; Other stuff.
23672 (defvar reftex-docstruct-symbol)
23673 (defvar org--rds)
23675 (defun org-reftex-citation ()
23676 "Use reftex-citation to insert a citation into the buffer.
23677 This looks for a line like
23679 #+BIBLIOGRAPHY: foo plain option:-d
23681 and derives from it that foo.bib is the bibliography file relevant
23682 for this document. It then installs the necessary environment for RefTeX
23683 to work in this buffer and calls `reftex-citation' to insert a citation
23684 into the buffer.
23686 Export of such citations to both LaTeX and HTML is handled by the contributed
23687 package ox-bibtex by Taru Karttunen."
23688 (interactive)
23689 (let ((reftex-docstruct-symbol 'org--rds)
23690 org--rds bib)
23691 (org-with-wide-buffer
23692 (let ((case-fold-search t)
23693 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23694 (if (not (save-excursion
23695 (or (re-search-forward re nil t)
23696 (re-search-backward re nil t))))
23697 (user-error "No bibliography defined in file")
23698 (setq bib (concat (match-string 1) ".bib")
23699 org--rds (list (list 'bib bib))))))
23700 (call-interactively 'reftex-citation)))
23702 ;;;; Functions extending outline functionality
23704 (defun org-beginning-of-line (&optional n)
23705 "Go to the beginning of the current visible line.
23707 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23708 tags on the first attempt, and only move to after the tags when
23709 the cursor is already beyond the end of the headline.
23711 With argument N not nil or 1, move forward N - 1 lines first."
23712 (interactive "^p")
23713 (let ((origin (point))
23714 (special (pcase org-special-ctrl-a/e
23715 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23716 deactivate-mark)
23717 ;; First move to a visible line.
23718 (if (bound-and-true-p visual-line-mode)
23719 (beginning-of-visual-line n)
23720 (move-beginning-of-line n)
23721 ;; `move-beginning-of-line' may leave point after invisible
23722 ;; characters if line starts with such of these (e.g., with
23723 ;; a link at column 0). Really move to the beginning of the
23724 ;; current visible line.
23725 (beginning-of-line))
23726 (cond
23727 ;; No special behavior. Point is already at the beginning of
23728 ;; a line, logical or visual.
23729 ((not special))
23730 ;; `beginning-of-visual-line' left point before logical beginning
23731 ;; of line: point is at the beginning of a visual line. Bail
23732 ;; out.
23733 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23734 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23735 ;; At a headline, special position is before the title, but
23736 ;; after any TODO keyword or priority cookie.
23737 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23738 (line-end-position)))
23739 (bol (point)))
23740 (if (eq special 'reversed)
23741 (when (and (= origin bol) (eq last-command this-command))
23742 (goto-char refpos))
23743 (when (or (> origin refpos) (= origin bol))
23744 (goto-char refpos)))))
23745 ((and (looking-at org-list-full-item-re)
23746 (memq (org-element-type (save-match-data (org-element-at-point)))
23747 '(item plain-list)))
23748 ;; Set special position at first white space character after
23749 ;; bullet, and check-box, if any.
23750 (let ((after-bullet
23751 (let ((box (match-end 3)))
23752 (cond ((not box) (match-end 1))
23753 ((eq (char-after box) ?\s) (1+ box))
23754 (t box)))))
23755 (if (eq special 'reversed)
23756 (when (and (= (point) origin) (eq last-command this-command))
23757 (goto-char after-bullet))
23758 (when (or (> origin after-bullet) (= (point) origin))
23759 (goto-char after-bullet)))))
23760 ;; No special context. Point is already at beginning of line.
23761 (t nil))))
23763 (defun org-end-of-line (&optional n)
23764 "Go to the end of the line, but before ellipsis, if any.
23766 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23767 tags on the first attempt, and only move to after the tags when
23768 the cursor is already beyond the end of the headline.
23770 With argument N not nil or 1, move forward N - 1 lines first."
23771 (interactive "^p")
23772 (let ((origin (point))
23773 (special (pcase org-special-ctrl-a/e
23774 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23775 deactivate-mark)
23776 ;; First move to a visible line.
23777 (if (bound-and-true-p visual-line-mode)
23778 (beginning-of-visual-line n)
23779 (move-beginning-of-line n))
23780 (cond
23781 ;; At a headline, with tags.
23782 ((and special
23783 (save-excursion
23784 (beginning-of-line)
23785 (let ((case-fold-search nil))
23786 (looking-at org-complex-heading-regexp)))
23787 (match-end 5))
23788 (let ((tags (save-excursion
23789 (goto-char (match-beginning 5))
23790 (skip-chars-backward " \t")
23791 (point)))
23792 (visual-end (and (bound-and-true-p visual-line-mode)
23793 (save-excursion
23794 (end-of-visual-line)
23795 (point)))))
23796 ;; If `end-of-visual-line' brings us before end of line or
23797 ;; even tags, i.e., the headline spans over multiple visual
23798 ;; lines, move there.
23799 (cond ((and visual-end
23800 (< visual-end tags)
23801 (<= origin visual-end))
23802 (goto-char visual-end))
23803 ((eq special 'reversed)
23804 (if (and (= origin (line-end-position))
23805 (eq this-command last-command))
23806 (goto-char tags)
23807 (end-of-line)))
23809 (if (or (< origin tags) (= origin (line-end-position)))
23810 (goto-char tags)
23811 (end-of-line))))))
23812 ((bound-and-true-p visual-line-mode)
23813 (let ((bol (line-beginning-position)))
23814 (end-of-visual-line)
23815 ;; If `end-of-visual-line' gets us past the ellipsis at the
23816 ;; end of a line, backtrack and use `end-of-line' instead.
23817 (when (/= bol (line-beginning-position))
23818 (goto-char bol)
23819 (end-of-line))))
23820 (t (end-of-line)))))
23822 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23823 (define-key org-mode-map "\C-e" 'org-end-of-line)
23825 (defun org-backward-sentence (&optional _arg)
23826 "Go to beginning of sentence, or beginning of table field.
23827 This will call `backward-sentence' or `org-table-beginning-of-field',
23828 depending on context."
23829 (interactive)
23830 (let* ((element (org-element-at-point))
23831 (contents-begin (org-element-property :contents-begin element))
23832 (table (org-element-lineage element '(table) t)))
23833 (if (and table
23834 (> (point) contents-begin)
23835 (<= (point) (org-element-property :contents-end table)))
23836 (call-interactively #'org-table-beginning-of-field)
23837 (save-restriction
23838 (when (and contents-begin
23839 (< (point-min) contents-begin)
23840 (> (point) contents-begin))
23841 (narrow-to-region contents-begin
23842 (org-element-property :contents-end element)))
23843 (call-interactively #'backward-sentence)))))
23845 (defun org-forward-sentence (&optional _arg)
23846 "Go to end of sentence, or end of table field.
23847 This will call `forward-sentence' or `org-table-end-of-field',
23848 depending on context."
23849 (interactive)
23850 (let* ((element (org-element-at-point))
23851 (contents-end (org-element-property :contents-end element))
23852 (table (org-element-lineage element '(table) t)))
23853 (if (and table
23854 (>= (point) (org-element-property :contents-begin table))
23855 (< (point) contents-end))
23856 (call-interactively #'org-table-end-of-field)
23857 (save-restriction
23858 (when (and contents-end
23859 (> (point-max) contents-end)
23860 ;; Skip blank lines between elements.
23861 (< (org-element-property :end element)
23862 (save-excursion (goto-char contents-end)
23863 (skip-chars-forward " \r\t\n"))))
23864 (narrow-to-region (org-element-property :contents-begin element)
23865 contents-end))
23866 (call-interactively #'forward-sentence)))))
23868 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23869 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23871 (defun org-kill-line (&optional _arg)
23872 "Kill line, to tags or end of line."
23873 (interactive)
23874 (cond
23875 ((or (not org-special-ctrl-k)
23876 (bolp)
23877 (not (org-at-heading-p)))
23878 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23879 org-ctrl-k-protect-subtree
23880 (or (eq org-ctrl-k-protect-subtree 'error)
23881 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23882 (user-error "C-k aborted as it would kill a hidden subtree"))
23883 (call-interactively
23884 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23885 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23886 (kill-region (point) (match-beginning 1))
23887 (org-set-tags nil t))
23888 (t (kill-region (point) (point-at-eol)))))
23890 (define-key org-mode-map "\C-k" 'org-kill-line)
23892 (defun org-yank (&optional arg)
23893 "Yank. If the kill is a subtree, treat it specially.
23894 This command will look at the current kill and check if is a single
23895 subtree, or a series of subtrees[1]. If it passes the test, and if the
23896 cursor is at the beginning of a line or after the stars of a currently
23897 empty headline, then the yank is handled specially. How exactly depends
23898 on the value of the following variables.
23900 `org-yank-folded-subtrees'
23901 By default, this variable is non-nil, which results in
23902 subtree(s) being folded after insertion, except if doing so
23903 would swallow text after the yanked text.
23905 `org-yank-adjusted-subtrees'
23906 When non-nil (the default value is nil), the subtree will be
23907 promoted or demoted in order to fit into the local outline tree
23908 structure, which means that the level will be adjusted so that it
23909 becomes the smaller one of the two *visible* surrounding headings.
23911 Any prefix to this command will cause `yank' to be called directly with
23912 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23913 will just
23914 plainly yank the text as it is.
23916 \[1] The test checks if the first non-white line is a heading
23917 and if there are no other headings with fewer stars."
23918 (interactive "P")
23919 (org-yank-generic 'yank arg))
23921 (defun org-yank-generic (command arg)
23922 "Perform some yank-like command.
23924 This function implements the behavior described in the `org-yank'
23925 documentation. However, it has been generalized to work for any
23926 interactive command with similar behavior."
23928 ;; pretend to be command COMMAND
23929 (setq this-command command)
23931 (if arg
23932 (call-interactively command)
23934 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23935 (and (org-kill-is-subtree-p)
23936 (or (bolp)
23937 (and (looking-at "[ \t]*$")
23938 (string-match
23939 "\\`\\*+\\'"
23940 (buffer-substring (point-at-bol) (point)))))))
23941 swallowp)
23942 (cond
23943 ((and subtreep org-yank-folded-subtrees)
23944 (let ((beg (point))
23945 end)
23946 (if (and subtreep org-yank-adjusted-subtrees)
23947 (org-paste-subtree nil nil 'for-yank)
23948 (call-interactively command))
23950 (setq end (point))
23951 (goto-char beg)
23952 (when (and (bolp) subtreep
23953 (not (setq swallowp
23954 (org-yank-folding-would-swallow-text beg end))))
23955 (org-with-limited-levels
23956 (or (looking-at org-outline-regexp)
23957 (re-search-forward org-outline-regexp-bol end t))
23958 (while (and (< (point) end) (looking-at org-outline-regexp))
23959 (outline-hide-subtree)
23960 (org-cycle-show-empty-lines 'folded)
23961 (condition-case nil
23962 (outline-forward-same-level 1)
23963 (error (goto-char end))))))
23964 (when swallowp
23965 (message
23966 "Inserted text not folded because that would swallow text"))
23968 (goto-char end)
23969 (skip-chars-forward " \t\n\r")
23970 (beginning-of-line 1)
23971 (push-mark beg 'nomsg)))
23972 ((and subtreep org-yank-adjusted-subtrees)
23973 (let ((beg (point-at-bol)))
23974 (org-paste-subtree nil nil 'for-yank)
23975 (push-mark beg 'nomsg)))
23977 (call-interactively command))))))
23979 (defun org-yank-folding-would-swallow-text (beg end)
23980 "Would hide-subtree at BEG swallow any text after END?"
23981 (let (level)
23982 (org-with-limited-levels
23983 (save-excursion
23984 (goto-char beg)
23985 (when (or (looking-at org-outline-regexp)
23986 (re-search-forward org-outline-regexp-bol end t))
23987 (setq level (org-outline-level)))
23988 (goto-char end)
23989 (skip-chars-forward " \t\r\n\v\f")
23990 (not (or (eobp)
23991 (and (bolp) (looking-at-p org-outline-regexp)
23992 (<= (org-outline-level) level))))))))
23994 (define-key org-mode-map "\C-y" 'org-yank)
23996 (defun org-truely-invisible-p ()
23997 "Check if point is at a character currently not visible.
23998 This version does not only check the character property, but also
23999 `visible-mode'."
24000 ;; Early versions of noutline don't have `outline-invisible-p'.
24001 (unless (bound-and-true-p visible-mode)
24002 (outline-invisible-p)))
24004 (defun org-invisible-p2 ()
24005 "Check if point is at a character currently not visible."
24006 (save-excursion
24007 (when (and (eolp) (not (bobp))) (backward-char 1))
24008 ;; Early versions of noutline don't have `outline-invisible-p'.
24009 (outline-invisible-p)))
24011 (defun org-back-to-heading (&optional invisible-ok)
24012 "Call `outline-back-to-heading', but provide a better error message."
24013 (condition-case nil
24014 (outline-back-to-heading invisible-ok)
24015 (error (error "Before first headline at position %d in buffer %s"
24016 (point) (current-buffer)))))
24018 (defun org-before-first-heading-p ()
24019 "Before first heading?"
24020 (save-excursion
24021 (end-of-line)
24022 (null (re-search-backward org-outline-regexp-bol nil t))))
24024 (defun org-at-heading-p (&optional ignored)
24025 (outline-on-heading-p t))
24027 (defun org-in-commented-heading-p (&optional no-inheritance)
24028 "Non-nil if point is under a commented heading.
24029 This function also checks ancestors of the current headline,
24030 unless optional argument NO-INHERITANCE is non-nil."
24031 (cond
24032 ((org-before-first-heading-p) nil)
24033 ((let ((headline (nth 4 (org-heading-components))))
24034 (and headline
24035 (let ((case-fold-search nil))
24036 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24037 headline)))))
24038 (no-inheritance nil)
24040 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24042 (defun org-at-comment-p nil
24043 "Is cursor in a commented line?"
24044 (save-excursion
24045 (save-match-data
24046 (beginning-of-line)
24047 (looking-at "^[ \t]*# "))))
24049 (defun org-at-drawer-p nil
24050 "Is cursor at a drawer keyword?"
24051 (save-excursion
24052 (move-beginning-of-line 1)
24053 (looking-at org-drawer-regexp)))
24055 (defun org-at-block-p nil
24056 "Is cursor at a block keyword?"
24057 (save-excursion
24058 (move-beginning-of-line 1)
24059 (looking-at org-block-regexp)))
24061 (defun org-point-at-end-of-empty-headline ()
24062 "If point is at the end of an empty headline, return t, else nil.
24063 If the heading only contains a TODO keyword, it is still still considered
24064 empty."
24065 (let ((case-fold-search nil))
24066 (and (looking-at "[ \t]*$")
24067 org-todo-line-regexp
24068 (save-excursion
24069 (beginning-of-line)
24070 (looking-at org-todo-line-regexp)
24071 (string= (match-string 3) "")))))
24073 (defun org-at-heading-or-item-p ()
24074 (or (org-at-heading-p) (org-at-item-p)))
24076 (defun org-at-target-p ()
24077 (or (org-in-regexp org-radio-target-regexp)
24078 (org-in-regexp org-target-regexp)))
24079 ;; Compatibility alias with Org versions < 7.8.03
24080 (defalias 'org-on-target-p 'org-at-target-p)
24082 (defun org-up-heading-all (arg)
24083 "Move to the heading line of which the present line is a subheading.
24084 This function considers both visible and invisible heading lines.
24085 With argument, move up ARG levels."
24086 (outline-up-heading arg t))
24088 (defun org-up-heading-safe ()
24089 "Move to the heading line of which the present line is a subheading.
24090 This version will not throw an error. It will return the level of the
24091 headline found, or nil if no higher level is found.
24093 Also, this function will be a lot faster than `outline-up-heading',
24094 because it relies on stars being the outline starters. This can really
24095 make a significant difference in outlines with very many siblings."
24096 (when (ignore-errors (org-back-to-heading t))
24097 (let ((level-up (1- (funcall outline-level))))
24098 (and (> level-up 0)
24099 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24100 (funcall outline-level)))))
24102 (defun org-first-sibling-p ()
24103 "Is this heading the first child of its parents?"
24104 (interactive)
24105 (let ((re org-outline-regexp-bol)
24106 level l)
24107 (unless (org-at-heading-p t)
24108 (user-error "Not at a heading"))
24109 (setq level (funcall outline-level))
24110 (save-excursion
24111 (if (not (re-search-backward re nil t))
24113 (setq l (funcall outline-level))
24114 (< l level)))))
24116 (defun org-goto-sibling (&optional previous)
24117 "Goto the next sibling, even if it is invisible.
24118 When PREVIOUS is set, go to the previous sibling instead. Returns t
24119 when a sibling was found. When none is found, return nil and don't
24120 move point."
24121 (let ((fun (if previous 're-search-backward 're-search-forward))
24122 (pos (point))
24123 (re org-outline-regexp-bol)
24124 level l)
24125 (when (ignore-errors (org-back-to-heading t))
24126 (setq level (funcall outline-level))
24127 (catch 'exit
24128 (or previous (forward-char 1))
24129 (while (funcall fun re nil t)
24130 (setq l (funcall outline-level))
24131 (when (< l level) (goto-char pos) (throw 'exit nil))
24132 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24133 (goto-char pos)
24134 nil))))
24136 (defun org-show-siblings ()
24137 "Show all siblings of the current headline."
24138 (save-excursion
24139 (while (org-goto-sibling) (org-flag-heading nil)))
24140 (save-excursion
24141 (while (org-goto-sibling 'previous)
24142 (org-flag-heading nil))))
24144 (defun org-goto-first-child ()
24145 "Goto the first child, even if it is invisible.
24146 Return t when a child was found. Otherwise don't move point and
24147 return nil."
24148 (let (level (pos (point)) (re org-outline-regexp-bol))
24149 (when (ignore-errors (org-back-to-heading t))
24150 (setq level (outline-level))
24151 (forward-char 1)
24152 (if (and (re-search-forward re nil t) (> (outline-level) level))
24153 (progn (goto-char (match-beginning 0)) t)
24154 (goto-char pos) nil))))
24156 (defun org-show-hidden-entry ()
24157 "Show an entry where even the heading is hidden."
24158 (save-excursion
24159 (org-show-entry)))
24161 (defun org-flag-heading (flag &optional entry)
24162 "Flag the current heading. FLAG non-nil means make invisible.
24163 When ENTRY is non-nil, show the entire entry."
24164 (save-excursion
24165 (org-back-to-heading t)
24166 ;; Check if we should show the entire entry
24167 (if entry
24168 (progn
24169 (org-show-entry)
24170 (save-excursion
24171 (and (outline-next-heading)
24172 (org-flag-heading nil))))
24173 (outline-flag-region (max (point-min) (1- (point)))
24174 (save-excursion (outline-end-of-heading) (point))
24175 flag))))
24177 (defun org-get-next-sibling ()
24178 "Move to next heading of the same level, and return point.
24179 If there is no such heading, return nil.
24180 This is like outline-next-sibling, but invisible headings are ok."
24181 (let ((level (funcall outline-level)))
24182 (outline-next-heading)
24183 (while (and (not (eobp)) (> (funcall outline-level) level))
24184 (outline-next-heading))
24185 (unless (or (eobp) (< (funcall outline-level) level))
24186 (point))))
24188 (defun org-get-last-sibling ()
24189 "Move to previous heading of the same level, and return point.
24190 If there is no such heading, return nil."
24191 (let ((opoint (point))
24192 (level (funcall outline-level)))
24193 (outline-previous-heading)
24194 (when (and (/= (point) opoint) (outline-on-heading-p t))
24195 (while (and (> (funcall outline-level) level)
24196 (not (bobp)))
24197 (outline-previous-heading))
24198 (unless (< (funcall outline-level) level)
24199 (point)))))
24201 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24202 "Goto to the end of a subtree."
24203 ;; This contains an exact copy of the original function, but it uses
24204 ;; `org-back-to-heading', to make it work also in invisible
24205 ;; trees. And is uses an invisible-ok argument.
24206 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24207 ;; Furthermore, when used inside Org, finding the end of a large subtree
24208 ;; with many children and grandchildren etc, this can be much faster
24209 ;; than the outline version.
24210 (org-back-to-heading invisible-ok)
24211 (let ((first t)
24212 (level (funcall outline-level)))
24213 (if (and (derived-mode-p 'org-mode) (< level 1000))
24214 ;; A true heading (not a plain list item), in Org
24215 ;; This means we can easily find the end by looking
24216 ;; only for the right number of stars. Using a regexp to do
24217 ;; this is so much faster than using a Lisp loop.
24218 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24219 (forward-char 1)
24220 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24221 ;; something else, do it the slow way
24222 (while (and (not (eobp))
24223 (or first (> (funcall outline-level) level)))
24224 (setq first nil)
24225 (outline-next-heading)))
24226 (unless to-heading
24227 (when (memq (preceding-char) '(?\n ?\^M))
24228 ;; Go to end of line before heading
24229 (forward-char -1)
24230 (when (memq (preceding-char) '(?\n ?\^M))
24231 ;; leave blank line before heading
24232 (forward-char -1)))))
24233 (point))
24235 (defun org-end-of-meta-data (&optional full)
24236 "Skip planning line and properties drawer in current entry.
24237 When optional argument FULL is non-nil, also skip empty lines,
24238 clocking lines and regular drawers at the beginning of the
24239 entry."
24240 (org-back-to-heading t)
24241 (forward-line)
24242 (when (looking-at-p org-planning-line-re) (forward-line))
24243 (when (looking-at org-property-drawer-re)
24244 (goto-char (match-end 0))
24245 (forward-line))
24246 (when (and full (not (org-at-heading-p)))
24247 (catch 'exit
24248 (let ((end (save-excursion (outline-next-heading) (point)))
24249 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24250 (while (not (eobp))
24251 (cond ((looking-at-p org-drawer-regexp)
24252 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24253 (forward-line)
24254 (throw 'exit t)))
24255 ((looking-at-p re) (forward-line))
24256 (t (throw 'exit t))))))))
24258 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24259 "Move forward to the ARG'th subheading at same level as this one.
24260 Stop at the first and last subheadings of a superior heading.
24261 Normally this only looks at visible headings, but when INVISIBLE-OK is
24262 non-nil it will also look at invisible ones."
24263 (interactive "p")
24264 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24265 (if (and arg (< arg 0))
24266 (goto-char (point-min))
24267 (outline-next-heading))
24268 (org-at-heading-p)
24269 (let ((level (- (match-end 0) (match-beginning 0) 1))
24270 (f (if (and arg (< arg 0))
24271 're-search-backward
24272 're-search-forward))
24273 (count (if arg (abs arg) 1))
24274 (result (point)))
24275 (while (and (prog1 (> count 0)
24276 (forward-char (if (and arg (< arg 0)) -1 1)))
24277 (funcall f org-outline-regexp-bol nil 'move))
24278 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24279 (cond ((< l level) (setq count 0))
24280 ((and (= l level)
24281 (or invisible-ok
24282 (progn
24283 (goto-char (line-beginning-position))
24284 (not (outline-invisible-p)))))
24285 (setq count (1- count))
24286 (when (eq l level)
24287 (setq result (point)))))))
24288 (goto-char result))
24289 (beginning-of-line 1)))
24291 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24292 "Move backward to the ARG'th subheading at same level as this one.
24293 Stop at the first and last subheadings of a superior heading."
24294 (interactive "p")
24295 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24297 (defun org-next-visible-heading (arg)
24298 "Move to the next visible heading.
24300 This function wraps `outline-next-visible-heading' with
24301 `org-with-limited-levels' in order to skip over inline tasks and
24302 respect customization of `org-odd-levels-only'."
24303 (interactive "p")
24304 (org-with-limited-levels
24305 (outline-next-visible-heading arg)))
24307 (defun org-previous-visible-heading (arg)
24308 "Move to the previous visible heading.
24310 This function wraps `outline-previous-visible-heading' with
24311 `org-with-limited-levels' in order to skip over inline tasks and
24312 respect customization of `org-odd-levels-only'."
24313 (interactive "p")
24314 (org-with-limited-levels
24315 (outline-previous-visible-heading arg)))
24317 (defun org-next-block (arg &optional backward block-regexp)
24318 "Jump to the next block.
24320 With a prefix argument ARG, jump forward ARG many blocks.
24322 When BACKWARD is non-nil, jump to the previous block.
24324 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24325 Match data is set according to this regexp when the function
24326 returns.
24328 Return point at beginning of the opening line of found block.
24329 Throw an error if no block is found."
24330 (interactive "p")
24331 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24332 (case-fold-search t)
24333 (search-fn (if backward #'re-search-backward #'re-search-forward))
24334 (count (or arg 1))
24335 (origin (point))
24336 last-element)
24337 (if backward (beginning-of-line) (end-of-line))
24338 (while (and (> count 0) (funcall search-fn re nil t))
24339 (let ((element (save-excursion
24340 (goto-char (match-beginning 0))
24341 (save-match-data (org-element-at-point)))))
24342 (when (and (memq (org-element-type element)
24343 '(center-block comment-block dynamic-block
24344 example-block export-block quote-block
24345 special-block src-block verse-block))
24346 (<= (match-beginning 0)
24347 (org-element-property :post-affiliated element)))
24348 (setq last-element element)
24349 (cl-decf count))))
24350 (if (= count 0)
24351 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24352 (save-match-data (org-show-context)))
24353 (goto-char origin)
24354 (user-error "No %s code blocks" (if backward "previous" "further")))))
24356 (defun org-previous-block (arg &optional block-regexp)
24357 "Jump to the previous block.
24358 With a prefix argument ARG, jump backward ARG many source blocks.
24359 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24360 (interactive "p")
24361 (org-next-block arg t block-regexp))
24363 (defun org-forward-paragraph ()
24364 "Move forward to beginning of next paragraph or equivalent.
24366 The function moves point to the beginning of the next visible
24367 structural element, which can be a paragraph, a table, a list
24368 item, etc. It also provides some special moves for convenience:
24370 - On an affiliated keyword, jump to the beginning of the
24371 relative element.
24372 - On an item or a footnote definition, move to the second
24373 element inside, if any.
24374 - On a table or a property drawer, jump after it.
24375 - On a verse or source block, stop after blank lines."
24376 (interactive)
24377 (when (eobp) (user-error "Cannot move further down"))
24378 (let* ((deactivate-mark nil)
24379 (element (org-element-at-point))
24380 (type (org-element-type element))
24381 (post-affiliated (org-element-property :post-affiliated element))
24382 (contents-begin (org-element-property :contents-begin element))
24383 (contents-end (org-element-property :contents-end element))
24384 (end (let ((end (org-element-property :end element)) (parent element))
24385 (while (and (setq parent (org-element-property :parent parent))
24386 (= (org-element-property :contents-end parent) end))
24387 (setq end (org-element-property :end parent)))
24388 end)))
24389 (cond ((not element)
24390 (skip-chars-forward " \r\t\n")
24391 (or (eobp) (beginning-of-line)))
24392 ;; On affiliated keywords, move to element's beginning.
24393 ((< (point) post-affiliated)
24394 (goto-char post-affiliated))
24395 ;; At a table row, move to the end of the table. Similarly,
24396 ;; at a node property, move to the end of the property
24397 ;; drawer.
24398 ((memq type '(node-property table-row))
24399 (goto-char (org-element-property
24400 :end (org-element-property :parent element))))
24401 ((memq type '(property-drawer table)) (goto-char end))
24402 ;; Consider blank lines as separators in verse and source
24403 ;; blocks to ease editing.
24404 ((memq type '(src-block verse-block))
24405 (when (eq type 'src-block)
24406 (setq contents-end
24407 (save-excursion (goto-char end)
24408 (skip-chars-backward " \r\t\n")
24409 (line-beginning-position))))
24410 (beginning-of-line)
24411 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24412 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24413 (goto-char end)
24414 (skip-chars-forward " \r\t\n")
24415 (if (= (point) contents-end) (goto-char end)
24416 (beginning-of-line))))
24417 ;; With no contents, just skip element.
24418 ((not contents-begin) (goto-char end))
24419 ;; If contents are invisible, skip the element altogether.
24420 ((outline-invisible-p (line-end-position))
24421 (cl-case type
24422 (headline
24423 (org-with-limited-levels (outline-next-visible-heading 1)))
24424 ;; At a plain list, make sure we move to the next item
24425 ;; instead of skipping the whole list.
24426 (plain-list (forward-char)
24427 (org-forward-paragraph))
24428 (otherwise (goto-char end))))
24429 ((>= (point) contents-end) (goto-char end))
24430 ((>= (point) contents-begin)
24431 ;; This can only happen on paragraphs and plain lists.
24432 (cl-case type
24433 (paragraph (goto-char end))
24434 ;; At a plain list, try to move to second element in
24435 ;; first item, if possible.
24436 (plain-list (end-of-line)
24437 (org-forward-paragraph))))
24438 ;; When contents start on the middle of a line (e.g. in
24439 ;; items and footnote definitions), try to reach first
24440 ;; element starting after current line.
24441 ((> (line-end-position) contents-begin)
24442 (end-of-line)
24443 (org-forward-paragraph))
24444 (t (goto-char contents-begin)))))
24446 (defun org-backward-paragraph ()
24447 "Move backward to start of previous paragraph or equivalent.
24449 The function moves point to the beginning of the current
24450 structural element, which can be a paragraph, a table, a list
24451 item, etc., or to the beginning of the previous visible one if
24452 point is already there. It also provides some special moves for
24453 convenience:
24455 - On an affiliated keyword, jump to the first one.
24456 - On a table or a property drawer, move to its beginning.
24457 - On a verse or source block, stop before blank lines."
24458 (interactive)
24459 (when (bobp) (user-error "Cannot move further up"))
24460 (let* ((deactivate-mark nil)
24461 (element (org-element-at-point))
24462 (type (org-element-type element))
24463 (contents-begin (org-element-property :contents-begin element))
24464 (contents-end (org-element-property :contents-end element))
24465 (post-affiliated (org-element-property :post-affiliated element))
24466 (begin (org-element-property :begin element)))
24467 (cond
24468 ((not element) (goto-char (point-min)))
24469 ((= (point) begin)
24470 (backward-char)
24471 (org-backward-paragraph))
24472 ((<= (point) post-affiliated) (goto-char begin))
24473 ((memq type '(node-property table-row))
24474 (goto-char (org-element-property
24475 :post-affiliated (org-element-property :parent element))))
24476 ((memq type '(property-drawer table)) (goto-char begin))
24477 ((memq type '(src-block verse-block))
24478 (when (eq type 'src-block)
24479 (setq contents-begin
24480 (save-excursion (goto-char begin) (forward-line) (point))))
24481 (if (= (point) contents-begin) (goto-char post-affiliated)
24482 ;; Inside a verse block, see blank lines as paragraph
24483 ;; separators.
24484 (let ((origin (point)))
24485 (skip-chars-backward " \r\t\n" contents-begin)
24486 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24487 (skip-chars-forward " \r\t\n" origin)
24488 (if (= (point) origin) (goto-char contents-begin)
24489 (beginning-of-line))))))
24490 ((not contents-begin) (goto-char (or post-affiliated begin)))
24491 ((eq type 'paragraph)
24492 (goto-char contents-begin)
24493 ;; When at first paragraph in an item or a footnote definition,
24494 ;; move directly to beginning of line.
24495 (let ((parent-contents
24496 (org-element-property
24497 :contents-begin (org-element-property :parent element))))
24498 (when (and parent-contents (= parent-contents contents-begin))
24499 (beginning-of-line))))
24500 ;; At the end of a greater element, move to the beginning of the
24501 ;; last element within.
24502 ((>= (point) contents-end)
24503 (goto-char (1- contents-end))
24504 (org-backward-paragraph))
24505 (t (goto-char (or post-affiliated begin))))
24506 ;; Ensure we never leave point invisible.
24507 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24509 (defun org-forward-element ()
24510 "Move forward by one element.
24511 Move to the next element at the same level, when possible."
24512 (interactive)
24513 (cond ((eobp) (user-error "Cannot move further down"))
24514 ((org-with-limited-levels (org-at-heading-p))
24515 (let ((origin (point)))
24516 (goto-char (org-end-of-subtree nil t))
24517 (unless (org-with-limited-levels (org-at-heading-p))
24518 (goto-char origin)
24519 (user-error "Cannot move further down"))))
24521 (let* ((elem (org-element-at-point))
24522 (end (org-element-property :end elem))
24523 (parent (org-element-property :parent elem)))
24524 (cond ((and parent (= (org-element-property :contents-end parent) end))
24525 (goto-char (org-element-property :end parent)))
24526 ((integer-or-marker-p end) (goto-char end))
24527 (t (message "No element at point")))))))
24529 (defun org-backward-element ()
24530 "Move backward by one element.
24531 Move to the previous element at the same level, when possible."
24532 (interactive)
24533 (cond ((bobp) (user-error "Cannot move further up"))
24534 ((org-with-limited-levels (org-at-heading-p))
24535 ;; At a headline, move to the previous one, if any, or stay
24536 ;; here.
24537 (let ((origin (point)))
24538 (org-with-limited-levels (org-backward-heading-same-level 1))
24539 ;; When current headline has no sibling above, move to its
24540 ;; parent.
24541 (when (= (point) origin)
24542 (or (org-with-limited-levels (org-up-heading-safe))
24543 (progn (goto-char origin)
24544 (user-error "Cannot move further up"))))))
24546 (let* ((elem (org-element-at-point))
24547 (beg (org-element-property :begin elem)))
24548 (cond
24549 ;; Move to beginning of current element if point isn't
24550 ;; there already.
24551 ((null beg) (message "No element at point"))
24552 ((/= (point) beg) (goto-char beg))
24553 (t (goto-char beg)
24554 (skip-chars-backward " \r\t\n")
24555 (unless (bobp)
24556 (let ((prev (org-element-at-point)))
24557 (goto-char (org-element-property :begin prev))
24558 (while (and (setq prev (org-element-property :parent prev))
24559 (<= (org-element-property :end prev) beg))
24560 (goto-char (org-element-property :begin prev)))))))))))
24562 (defun org-up-element ()
24563 "Move to upper element."
24564 (interactive)
24565 (if (org-with-limited-levels (org-at-heading-p))
24566 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24567 (let* ((elem (org-element-at-point))
24568 (parent (org-element-property :parent elem)))
24569 (if parent (goto-char (org-element-property :begin parent))
24570 (if (org-with-limited-levels (org-before-first-heading-p))
24571 (user-error "No surrounding element")
24572 (org-with-limited-levels (org-back-to-heading)))))))
24574 (defvar org-element-greater-elements)
24575 (defun org-down-element ()
24576 "Move to inner element."
24577 (interactive)
24578 (let ((element (org-element-at-point)))
24579 (cond
24580 ((memq (org-element-type element) '(plain-list table))
24581 (goto-char (org-element-property :contents-begin element))
24582 (forward-char))
24583 ((memq (org-element-type element) org-element-greater-elements)
24584 ;; If contents are hidden, first disclose them.
24585 (when (outline-invisible-p (line-end-position)) (org-cycle))
24586 (goto-char (or (org-element-property :contents-begin element)
24587 (user-error "No content for this element"))))
24588 (t (user-error "No inner element")))))
24590 (defun org-drag-element-backward ()
24591 "Move backward element at point."
24592 (interactive)
24593 (let ((elem (or (org-element-at-point)
24594 (user-error "No element at point"))))
24595 (if (eq (org-element-type elem) 'headline)
24596 ;; Preserve point when moving a whole tree, even if point was
24597 ;; on blank lines below the headline.
24598 (let ((offset (skip-chars-backward " \t\n")))
24599 (unwind-protect (org-move-subtree-up)
24600 (forward-char (- offset))))
24601 (let ((prev-elem
24602 (save-excursion
24603 (goto-char (org-element-property :begin elem))
24604 (skip-chars-backward " \r\t\n")
24605 (unless (bobp)
24606 (let* ((beg (org-element-property :begin elem))
24607 (prev (org-element-at-point))
24608 (up prev))
24609 (while (and (setq up (org-element-property :parent up))
24610 (<= (org-element-property :end up) beg))
24611 (setq prev up))
24612 prev)))))
24613 ;; Error out if no previous element or previous element is
24614 ;; a parent of the current one.
24615 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24616 (user-error "Cannot drag element backward")
24617 (let ((pos (point)))
24618 (org-element-swap-A-B prev-elem elem)
24619 (goto-char (+ (org-element-property :begin prev-elem)
24620 (- pos (org-element-property :begin elem))))))))))
24622 (defun org-drag-element-forward ()
24623 "Move forward element at point."
24624 (interactive)
24625 (let* ((pos (point))
24626 (elem (or (org-element-at-point)
24627 (user-error "No element at point"))))
24628 (when (= (point-max) (org-element-property :end elem))
24629 (user-error "Cannot drag element forward"))
24630 (goto-char (org-element-property :end elem))
24631 (let ((next-elem (org-element-at-point)))
24632 (when (or (org-element-nested-p elem next-elem)
24633 (and (eq (org-element-type next-elem) 'headline)
24634 (not (eq (org-element-type elem) 'headline))))
24635 (goto-char pos)
24636 (user-error "Cannot drag element forward"))
24637 ;; Compute new position of point: it's shifted by NEXT-ELEM
24638 ;; body's length (without final blanks) and by the length of
24639 ;; blanks between ELEM and NEXT-ELEM.
24640 (let ((size-next (- (save-excursion
24641 (goto-char (org-element-property :end next-elem))
24642 (skip-chars-backward " \r\t\n")
24643 (forward-line)
24644 ;; Small correction if buffer doesn't end
24645 ;; with a newline character.
24646 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24647 (org-element-property :begin next-elem)))
24648 (size-blank (- (org-element-property :end elem)
24649 (save-excursion
24650 (goto-char (org-element-property :end elem))
24651 (skip-chars-backward " \r\t\n")
24652 (forward-line)
24653 (point)))))
24654 (org-element-swap-A-B elem next-elem)
24655 (goto-char (+ pos size-next size-blank))))))
24657 (defun org-drag-line-forward (arg)
24658 "Drag the line at point ARG lines forward."
24659 (interactive "p")
24660 (dotimes (_ (abs arg))
24661 (let ((c (current-column)))
24662 (if (< 0 arg)
24663 (progn
24664 (beginning-of-line 2)
24665 (transpose-lines 1)
24666 (beginning-of-line 0))
24667 (transpose-lines 1)
24668 (beginning-of-line -1))
24669 (org-move-to-column c))))
24671 (defun org-drag-line-backward (arg)
24672 "Drag the line at point ARG lines backward."
24673 (interactive "p")
24674 (org-drag-line-forward (- arg)))
24676 (defun org-mark-element ()
24677 "Put point at beginning of this element, mark at end.
24679 Interactively, if this command is repeated or (in Transient Mark
24680 mode) if the mark is active, it marks the next element after the
24681 ones already marked."
24682 (interactive)
24683 (let (deactivate-mark)
24684 (if (and (called-interactively-p 'any)
24685 (or (and (eq last-command this-command) (mark t))
24686 (and transient-mark-mode mark-active)))
24687 (set-mark
24688 (save-excursion
24689 (goto-char (mark))
24690 (goto-char (org-element-property :end (org-element-at-point)))))
24691 (let ((element (org-element-at-point)))
24692 (end-of-line)
24693 (push-mark (org-element-property :end element) t t)
24694 (goto-char (org-element-property :begin element))))))
24696 (defun org-narrow-to-element ()
24697 "Narrow buffer to current element."
24698 (interactive)
24699 (let ((elem (org-element-at-point)))
24700 (cond
24701 ((eq (car elem) 'headline)
24702 (narrow-to-region
24703 (org-element-property :begin elem)
24704 (org-element-property :end elem)))
24705 ((memq (car elem) org-element-greater-elements)
24706 (narrow-to-region
24707 (org-element-property :contents-begin elem)
24708 (org-element-property :contents-end elem)))
24710 (narrow-to-region
24711 (org-element-property :begin elem)
24712 (org-element-property :end elem))))))
24714 (defun org-transpose-element ()
24715 "Transpose current and previous elements, keeping blank lines between.
24716 Point is moved after both elements."
24717 (interactive)
24718 (org-skip-whitespace)
24719 (let ((end (org-element-property :end (org-element-at-point))))
24720 (org-drag-element-backward)
24721 (goto-char end)))
24723 (defun org-unindent-buffer ()
24724 "Un-indent the visible part of the buffer.
24725 Relative indentation (between items, inside blocks, etc.) isn't
24726 modified."
24727 (interactive)
24728 (unless (eq major-mode 'org-mode)
24729 (user-error "Cannot un-indent a buffer not in Org mode"))
24730 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24731 (unindent-tree
24732 (lambda (contents)
24733 (dolist (element (reverse contents))
24734 (if (memq (org-element-type element) '(headline section))
24735 (funcall unindent-tree (org-element-contents element))
24736 (save-excursion
24737 (save-restriction
24738 (narrow-to-region
24739 (org-element-property :begin element)
24740 (org-element-property :end element))
24741 (org-do-remove-indentation))))))))
24742 (funcall unindent-tree (org-element-contents parse-tree))))
24744 (defun org-show-children (&optional level)
24745 "Show all direct subheadings of this heading.
24746 Prefix arg LEVEL is how many levels below the current level
24747 should be shown. Default is enough to cause the following
24748 heading to appear."
24749 (interactive "p")
24750 ;; If `orgstruct-mode' is active, use the slower version.
24751 (if orgstruct-mode (call-interactively #'outline-show-children)
24752 (save-excursion
24753 (org-back-to-heading t)
24754 (let* ((current-level (funcall outline-level))
24755 (max-level (org-get-valid-level
24756 current-level
24757 (if level (prefix-numeric-value level) 1)))
24758 (end (save-excursion (org-end-of-subtree t t)))
24759 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24760 (past-first-child nil)
24761 ;; Make sure to skip inlinetasks.
24762 (re (format regexp-fmt
24763 current-level
24764 (cond
24765 ((not (featurep 'org-inlinetask)) "")
24766 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24768 (t (1- org-inlinetask-min-level))))))
24769 ;; Display parent heading.
24770 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24771 (forward-line)
24772 ;; Display children. First child may be deeper than expected
24773 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24774 ;; MAX-LEVEL accordingly.
24775 (while (re-search-forward re end t)
24776 (unless past-first-child
24777 (setq re (format regexp-fmt
24778 current-level
24779 (max (funcall outline-level) max-level)))
24780 (setq past-first-child t))
24781 (outline-flag-region
24782 (line-end-position 0) (line-end-position) nil))))))
24784 (defun org-show-subtree ()
24785 "Show everything after this heading at deeper levels."
24786 (interactive)
24787 (outline-flag-region
24788 (point)
24789 (save-excursion
24790 (org-end-of-subtree t t))
24791 nil))
24793 (defun org-show-entry ()
24794 "Show the body directly following this heading.
24795 Show the heading too, if it is currently invisible."
24796 (interactive)
24797 (save-excursion
24798 (ignore-errors
24799 (org-back-to-heading t)
24800 (outline-flag-region
24801 (max (point-min) (1- (point)))
24802 (save-excursion
24803 (if (re-search-forward
24804 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24805 (match-beginning 1)
24806 (point-max)))
24807 nil)
24808 (org-cycle-hide-drawers 'children))))
24810 (defun org-make-options-regexp (kwds &optional extra)
24811 "Make a regular expression for keyword lines.
24812 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24813 when non-nil, is a regexp matching keywords names."
24814 (concat "^[ \t]*#\\+\\("
24815 (regexp-opt kwds)
24816 (and extra (concat (and kwds "\\|") extra))
24817 "\\):[ \t]*\\(.*\\)"))
24819 ;;;; Integration with and fixes for other packages
24821 ;;; Imenu support
24823 (defvar-local org-imenu-markers nil
24824 "All markers currently used by Imenu.")
24826 (defun org-imenu-new-marker (&optional pos)
24827 "Return a new marker for use by Imenu, and remember the marker."
24828 (let ((m (make-marker)))
24829 (move-marker m (or pos (point)))
24830 (push m org-imenu-markers)
24833 (defun org-imenu-get-tree ()
24834 "Produce the index for Imenu."
24835 (dolist (x org-imenu-markers) (move-marker x nil))
24836 (setq org-imenu-markers nil)
24837 (let* ((case-fold-search nil)
24838 (n org-imenu-depth)
24839 (re (concat "^" (org-get-limited-outline-regexp)))
24840 (subs (make-vector (1+ n) nil))
24841 (last-level 0)
24842 m level head0 head)
24843 (org-with-wide-buffer
24844 (goto-char (point-max))
24845 (while (re-search-backward re nil t)
24846 (setq level (org-reduced-level (funcall outline-level)))
24847 (when (and (<= level n)
24848 (looking-at org-complex-heading-regexp)
24849 (setq head0 (match-string-no-properties 4)))
24850 (setq head (org-link-display-format head0)
24851 m (org-imenu-new-marker))
24852 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24853 (if (>= level last-level)
24854 (push (cons head m) (aref subs level))
24855 (push (cons head (aref subs (1+ level))) (aref subs level))
24856 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24857 (setq last-level level))))
24858 (aref subs 1)))
24860 (eval-after-load "imenu"
24861 '(progn
24862 (add-hook 'imenu-after-jump-hook
24863 (lambda ()
24864 (when (derived-mode-p 'org-mode)
24865 (org-show-context 'org-goto))))))
24867 (defun org-link-display-format (s)
24868 "Replace links in string S with their description.
24869 If there is no description, use the link target."
24870 (save-match-data
24871 (replace-regexp-in-string
24872 org-bracket-link-analytic-regexp
24873 (lambda (m)
24874 (if (match-end 5) (match-string 5 m)
24875 (concat (match-string 1 m) (match-string 3 m))))
24876 s nil t)))
24878 (defun org-toggle-link-display ()
24879 "Toggle the literal or descriptive display of links."
24880 (interactive)
24881 (if org-descriptive-links
24882 (progn (org-remove-from-invisibility-spec '(org-link))
24883 (org-restart-font-lock)
24884 (setq org-descriptive-links nil))
24885 (progn (add-to-invisibility-spec '(org-link))
24886 (org-restart-font-lock)
24887 (setq org-descriptive-links t))))
24889 ;; Speedbar support
24891 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24892 "Overlay marking the agenda restriction line in speedbar.")
24893 (overlay-put org-speedbar-restriction-lock-overlay
24894 'face 'org-agenda-restriction-lock)
24895 (overlay-put org-speedbar-restriction-lock-overlay
24896 'help-echo "Agendas are currently limited to this item.")
24897 (delete-overlay org-speedbar-restriction-lock-overlay)
24899 (defun org-speedbar-set-agenda-restriction ()
24900 "Restrict future agenda commands to the location at point in speedbar.
24901 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24902 (interactive)
24903 (require 'org-agenda)
24904 (let (p m tp np dir txt)
24905 (cond
24906 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24907 'org-imenu t))
24908 (setq m (get-text-property p 'org-imenu-marker))
24909 (with-current-buffer (marker-buffer m)
24910 (goto-char m)
24911 (org-agenda-set-restriction-lock 'subtree)))
24912 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24913 'speedbar-function 'speedbar-find-file))
24914 (setq tp (previous-single-property-change
24915 (1+ p) 'speedbar-function)
24916 np (next-single-property-change
24917 tp 'speedbar-function)
24918 dir (speedbar-line-directory)
24919 txt (buffer-substring-no-properties (or tp (point-min))
24920 (or np (point-max))))
24921 (with-current-buffer (find-file-noselect
24922 (let ((default-directory dir))
24923 (expand-file-name txt)))
24924 (unless (derived-mode-p 'org-mode)
24925 (user-error "Cannot restrict to non-Org mode file"))
24926 (org-agenda-set-restriction-lock 'file)))
24927 (t (user-error "Don't know how to restrict Org mode agenda")))
24928 (move-overlay org-speedbar-restriction-lock-overlay
24929 (point-at-bol) (point-at-eol))
24930 (setq current-prefix-arg nil)
24931 (org-agenda-maybe-redo)))
24933 (defvar speedbar-file-key-map)
24934 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24935 (eval-after-load "speedbar"
24936 '(progn
24937 (speedbar-add-supported-extension ".org")
24938 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24939 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24940 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24941 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24942 (add-hook 'speedbar-visiting-tag-hook
24943 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24945 ;;; Fixes and Hacks for problems with other packages
24947 (defun org--flyspell-object-check-p (element)
24948 "Non-nil when Flyspell can check object at point.
24949 ELEMENT is the element at point."
24950 (let ((object (save-excursion
24951 (when (looking-at-p "\\>") (backward-char))
24952 (org-element-context element))))
24953 (cl-case (org-element-type object)
24954 ;; Prevent checks in links due to keybinding conflict with
24955 ;; Flyspell.
24956 ((code entity export-snippet inline-babel-call
24957 inline-src-block line-break latex-fragment link macro
24958 statistics-cookie target timestamp verbatim)
24959 nil)
24960 (footnote-reference
24961 ;; Only in inline footnotes, within the definition.
24962 (and (eq (org-element-property :type object) 'inline)
24963 (< (save-excursion
24964 (goto-char (org-element-property :begin object))
24965 (search-forward ":" nil t 2))
24966 (point))))
24967 (otherwise t))))
24969 (defun org-mode-flyspell-verify ()
24970 "Function used for `flyspell-generic-check-word-predicate'."
24971 (if (org-at-heading-p)
24972 ;; At a headline or an inlinetask, check title only. This is
24973 ;; faster than relying on `org-element-at-point'.
24974 (and (save-excursion (beginning-of-line)
24975 (and (let ((case-fold-search t))
24976 (not (looking-at-p "\\*+ END[ \t]*$")))
24977 (let ((case-fold-search nil))
24978 (looking-at org-complex-heading-regexp))))
24979 (match-beginning 4)
24980 (>= (point) (match-beginning 4))
24981 (or (not (match-beginning 5))
24982 (< (point) (match-beginning 5))))
24983 (let* ((element (org-element-at-point))
24984 (post-affiliated (org-element-property :post-affiliated element)))
24985 (cond
24986 ;; Ignore checks in all affiliated keywords but captions.
24987 ((< (point) post-affiliated)
24988 (and (save-excursion
24989 (beginning-of-line)
24990 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24991 (> (point) (match-end 0))
24992 (org--flyspell-object-check-p element)))
24993 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24994 ((let ((log (org-log-into-drawer)))
24995 (and log
24996 (let ((drawer (org-element-lineage element '(drawer))))
24997 (and drawer
24998 (eq (compare-strings
24999 log nil nil
25000 (org-element-property :drawer-name drawer) nil nil t)
25001 t)))))
25002 nil)
25004 (cl-case (org-element-type element)
25005 ((comment quote-section) t)
25006 (comment-block
25007 ;; Allow checks between block markers, not on them.
25008 (and (> (line-beginning-position) post-affiliated)
25009 (save-excursion
25010 (end-of-line)
25011 (skip-chars-forward " \r\t\n")
25012 (< (point) (org-element-property :end element)))))
25013 ;; Arbitrary list of keywords where checks are meaningful.
25014 ;; Make sure point is on the value part of the element.
25015 (keyword
25016 (and (member (org-element-property :key element)
25017 '("DESCRIPTION" "TITLE"))
25018 (save-excursion
25019 (search-backward ":" (line-beginning-position) t))))
25020 ;; Check is globally allowed in paragraphs verse blocks and
25021 ;; table rows (after affiliated keywords) but some objects
25022 ;; must not be affected.
25023 ((paragraph table-row verse-block)
25024 (let ((cbeg (org-element-property :contents-begin element))
25025 (cend (org-element-property :contents-end element)))
25026 (and cbeg (>= (point) cbeg) (< (point) cend)
25027 (org--flyspell-object-check-p element))))))))))
25028 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25030 (defun org-remove-flyspell-overlays-in (beg end)
25031 "Remove flyspell overlays in region."
25032 (and (bound-and-true-p flyspell-mode)
25033 (fboundp 'flyspell-delete-region-overlays)
25034 (flyspell-delete-region-overlays beg end)))
25036 (defvar flyspell-delayed-commands)
25037 (eval-after-load "flyspell"
25038 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25040 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25041 (eval-after-load "bookmark"
25042 '(if (boundp 'bookmark-after-jump-hook)
25043 ;; We can use the hook
25044 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25045 ;; Hook not available, use advice
25046 (defadvice bookmark-jump (after org-make-visible activate)
25047 "Make the position visible."
25048 (org-bookmark-jump-unhide))))
25050 ;; Make sure saveplace shows the location if it was hidden
25051 (eval-after-load "saveplace"
25052 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25053 "Make the position visible."
25054 (org-bookmark-jump-unhide)))
25056 ;; Make sure ecb shows the location if it was hidden
25057 (eval-after-load "ecb"
25058 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25059 "Make hierarchy visible when jumping into location from ECB tree buffer."
25060 (when (derived-mode-p 'org-mode)
25061 (org-show-context))))
25063 (defun org-bookmark-jump-unhide ()
25064 "Unhide the current position, to show the bookmark location."
25065 (and (derived-mode-p 'org-mode)
25066 (or (outline-invisible-p)
25067 (save-excursion (goto-char (max (point-min) (1- (point))))
25068 (outline-invisible-p)))
25069 (org-show-context 'bookmark-jump)))
25071 (defun org-mark-jump-unhide ()
25072 "Make the point visible with `org-show-context' after jumping to the mark."
25073 (when (and (derived-mode-p 'org-mode)
25074 (outline-invisible-p))
25075 (org-show-context 'mark-goto)))
25077 (eval-after-load "simple"
25078 '(defadvice pop-to-mark-command (after org-make-visible activate)
25079 "Make the point visible with `org-show-context'."
25080 (org-mark-jump-unhide)))
25082 (eval-after-load "simple"
25083 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25084 "Make the point visible with `org-show-context'."
25085 (org-mark-jump-unhide)))
25087 (eval-after-load "simple"
25088 '(defadvice pop-global-mark (after org-make-visible activate)
25089 "Make the point visible with `org-show-context'."
25090 (org-mark-jump-unhide)))
25092 ;; Make session.el ignore our circular variable
25093 (defvar session-globals-exclude)
25094 (eval-after-load "session"
25095 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25097 ;;;; Finish up
25099 (provide 'org)
25101 (run-hooks 'org-load-hook)
25103 ;;; org.el ends here