Turn org-mode into Org or Org mode
[org-mode.git] / lisp / org.el
blob8a5780b683eac8b635db2a077ccb83eb361af03d
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2016 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (equal 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-edit-field "org-table" (arg))
160 (declare-function org-table-end "org-table" (&optional table-type))
161 (declare-function org-table-end-of-field "org-table" (&optional n))
162 (declare-function org-table-insert-row "org-table" (&optional arg))
163 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
164 (declare-function org-table-maybe-eval-formula "org-table" ())
165 (declare-function org-table-maybe-recalculate-line "org-table" ())
166 (declare-function org-table-next-row "org-table" ())
167 (declare-function org-table-paste-rectangle "org-table" ())
168 (declare-function org-table-wrap-region "org-table" (arg))
169 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
170 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
171 (declare-function orgtbl-mode "org-table" (&optional arg))
173 (defsubst org-uniquify (list)
174 "Non-destructively remove duplicate elements from LIST."
175 (let ((res (copy-sequence list))) (delete-dups res)))
177 (defsubst org-get-at-bol (property)
178 "Get text property PROPERTY at the beginning of line."
179 (get-text-property (point-at-bol) property))
181 (defsubst org-trim (s &optional keep-lead)
182 "Remove whitespace at the beginning and the end of string S.
183 When optional argument KEEP-LEAD is non-nil, removing blank lines
184 at the beginning of the string does not affect leading indentation."
185 (replace-regexp-in-string
186 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
187 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
189 ;; load languages based on value of `org-babel-load-languages'
190 (defvar org-babel-load-languages)
192 ;;;###autoload
193 (defun org-babel-do-load-languages (sym value)
194 "Load the languages defined in `org-babel-load-languages'."
195 (set-default sym value)
196 (dolist (pair org-babel-load-languages)
197 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
198 (if active
199 (require (intern (concat "ob-" lang)))
200 (funcall 'fmakunbound
201 (intern (concat "org-babel-execute:" lang)))
202 (funcall 'fmakunbound
203 (intern (concat "org-babel-expand-body:" lang)))))))
205 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
206 ;;;###autoload
207 (defun org-babel-load-file (file &optional compile)
208 "Load Emacs Lisp source code blocks in the Org FILE.
209 This function exports the source code using `org-babel-tangle'
210 and then loads the resulting file using `load-file'. With prefix
211 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
212 file to byte-code before it is loaded."
213 (interactive "fFile to load: \nP")
214 (let* ((age (lambda (file)
215 (float-time
216 (time-subtract (current-time)
217 (nth 5 (or (file-attributes (file-truename file))
218 (file-attributes file)))))))
219 (base-name (file-name-sans-extension file))
220 (exported-file (concat base-name ".el")))
221 ;; tangle if the Org file is newer than the elisp file
222 (unless (and (file-exists-p exported-file)
223 (> (funcall age file) (funcall age exported-file)))
224 ;; Tangle-file traversal returns reversed list of tangled files
225 ;; and we want to evaluate the first target.
226 (setq exported-file
227 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
228 (message "%s %s"
229 (if compile
230 (progn (byte-compile-file exported-file 'load)
231 "Compiled and loaded")
232 (progn (load-file exported-file) "Loaded"))
233 exported-file)))
235 (defcustom org-babel-load-languages '((emacs-lisp . t))
236 "Languages which can be evaluated in Org buffers.
237 This list can be used to load support for any of the languages
238 below, note that each language will depend on a different set of
239 system executables and/or Emacs modes. When a language is
240 \"loaded\", then code blocks in that language can be evaluated
241 with `org-babel-execute-src-block' bound by default to C-c
242 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
243 be set to remove code block evaluation from the C-c C-c
244 keybinding. By default only Emacs Lisp (which has no
245 requirements) is loaded."
246 :group 'org-babel
247 :set 'org-babel-do-load-languages
248 :version "24.1"
249 :type '(alist :tag "Babel Languages"
250 :key-type
251 (choice
252 (const :tag "Awk" awk)
253 (const :tag "C" C)
254 (const :tag "R" R)
255 (const :tag "Asymptote" asymptote)
256 (const :tag "Calc" calc)
257 (const :tag "Clojure" clojure)
258 (const :tag "CSS" css)
259 (const :tag "Ditaa" ditaa)
260 (const :tag "Dot" dot)
261 (const :tag "Emacs Lisp" emacs-lisp)
262 (const :tag "Forth" forth)
263 (const :tag "Fortran" fortran)
264 (const :tag "Gnuplot" gnuplot)
265 (const :tag "Haskell" haskell)
266 (const :tag "IO" io)
267 (const :tag "J" J)
268 (const :tag "Java" java)
269 (const :tag "Javascript" js)
270 (const :tag "LaTeX" latex)
271 (const :tag "Ledger" ledger)
272 (const :tag "Lilypond" lilypond)
273 (const :tag "Lisp" lisp)
274 (const :tag "Makefile" makefile)
275 (const :tag "Maxima" maxima)
276 (const :tag "Matlab" matlab)
277 (const :tag "Mscgen" mscgen)
278 (const :tag "Ocaml" ocaml)
279 (const :tag "Octave" octave)
280 (const :tag "Org" org)
281 (const :tag "Perl" perl)
282 (const :tag "Pico Lisp" picolisp)
283 (const :tag "PlantUML" plantuml)
284 (const :tag "Python" python)
285 (const :tag "Ruby" ruby)
286 (const :tag "Sass" sass)
287 (const :tag "Scala" scala)
288 (const :tag "Scheme" scheme)
289 (const :tag "Screen" screen)
290 (const :tag "Shell Script" shell)
291 (const :tag "Shen" shen)
292 (const :tag "Sql" sql)
293 (const :tag "Sqlite" sqlite)
294 (const :tag "Stan" stan)
295 (const :tag "ebnf2ps" ebnf2ps))
296 :value-type (boolean :tag "Activate" :value t)))
298 ;;;; Customization variables
299 (defcustom org-clone-delete-id nil
300 "Remove ID property of clones of a subtree.
301 When non-nil, clones of a subtree don't inherit the ID property.
302 Otherwise they inherit the ID property with a new unique
303 identifier."
304 :type 'boolean
305 :version "24.1"
306 :group 'org-id)
308 ;;; Version
309 (org-check-version)
311 ;;;###autoload
312 (defun org-version (&optional here full message)
313 "Show the Org version.
314 Interactively, or when MESSAGE is non-nil, show it in echo area.
315 With prefix argument, or when HERE is non-nil, insert it at point.
316 In non-interactive uses, a reduced version string is output unless
317 FULL is given."
318 (interactive (list current-prefix-arg t (not current-prefix-arg)))
319 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
320 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
321 (load-suffixes (list ".el"))
322 (org-install-dir
323 (ignore-errors (org-find-library-dir "org-loaddefs"))))
324 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
325 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
326 (let* ((load-suffixes save-load-suffixes)
327 (release (org-release))
328 (git-version (org-git-version))
329 (version (format "Org-mode version %s (%s @ %s)"
330 release
331 git-version
332 (if org-install-dir
333 (if (string= org-dir org-install-dir)
334 org-install-dir
335 (concat "mixed installation! "
336 org-install-dir
337 " and "
338 org-dir))
339 "org-loaddefs.el can not be found!")))
340 (version1 (if full version release)))
341 (when here (insert version1))
342 (when message (message "%s" version1))
343 version1)))
345 (defconst org-version (org-version))
348 ;;; Syntax Constants
350 ;;;; Block
352 (defconst org-block-regexp
353 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
354 "Regular expression for hiding blocks.")
356 (defconst org-dblock-start-re
357 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
358 "Matches the start line of a dynamic block, with parameters.")
360 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
361 "Matches the end of a dynamic block.")
363 ;;;; Clock and Planning
365 (defconst org-clock-string "CLOCK:"
366 "String used as prefix for timestamps clocking work hours on an item.")
368 (defvar org-closed-string "CLOSED:"
369 "String used as the prefix for timestamps logging closing a TODO entry.")
371 (defvar org-deadline-string "DEADLINE:"
372 "String to mark deadline entries.
373 A deadline is this string, followed by a time stamp. Should be a word,
374 terminated by a colon. You can insert a schedule keyword and
375 a timestamp with \\[org-deadline].")
377 (defvar org-scheduled-string "SCHEDULED:"
378 "String to mark scheduled TODO entries.
379 A schedule is this string, followed by a time stamp. Should be a word,
380 terminated by a colon. You can insert a schedule keyword and
381 a timestamp with \\[org-schedule].")
383 (defconst org-ds-keyword-length
384 (+ 2
385 (apply #'max
386 (mapcar #'length
387 (list org-deadline-string org-scheduled-string
388 org-clock-string org-closed-string))))
389 "Maximum length of the DEADLINE and SCHEDULED keywords.")
391 (defconst org-planning-line-re
392 (concat "^[ \t]*"
393 (regexp-opt
394 (list org-closed-string org-deadline-string org-scheduled-string)
396 "Matches a line with planning info.
397 Matched keyword is in group 1.")
399 (defconst org-clock-line-re
400 (concat "^[ \t]*" org-clock-string)
401 "Matches a line with clock info.")
403 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
404 "Matches the DEADLINE keyword.")
406 (defconst org-deadline-time-regexp
407 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
408 "Matches the DEADLINE keyword together with a time stamp.")
410 (defconst org-deadline-time-hour-regexp
411 (concat "\\<" org-deadline-string
412 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
413 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
415 (defconst org-deadline-line-regexp
416 (concat "\\<\\(" org-deadline-string "\\).*")
417 "Matches the DEADLINE keyword and the rest of the line.")
419 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
420 "Matches the SCHEDULED keyword.")
422 (defconst org-scheduled-time-regexp
423 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
424 "Matches the SCHEDULED keyword together with a time stamp.")
426 (defconst org-scheduled-time-hour-regexp
427 (concat "\\<" org-scheduled-string
428 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
429 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
431 (defconst org-closed-time-regexp
432 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
433 "Matches the CLOSED keyword together with a time stamp.")
435 (defconst org-keyword-time-regexp
436 (concat "\\<"
437 (regexp-opt
438 (list org-scheduled-string org-deadline-string org-closed-string
439 org-clock-string)
441 " *[[<]\\([^]>]+\\)[]>]")
442 "Matches any of the 4 keywords, together with the time stamp.")
444 (defconst org-keyword-time-not-clock-regexp
445 (concat
446 "\\<"
447 (regexp-opt
448 (list org-scheduled-string org-deadline-string org-closed-string) t)
449 " *[[<]\\([^]>]+\\)[]>]")
450 "Matches any of the 3 keywords, together with the time stamp.")
452 (defconst org-maybe-keyword-time-regexp
453 (concat "\\(\\<"
454 (regexp-opt
455 (list org-scheduled-string org-deadline-string org-closed-string
456 org-clock-string)
458 "\\)?"
459 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
460 "\\|"
461 "<%%([^\r\n>]*>\\)")
462 "Matches a timestamp, possibly preceded by a keyword.")
464 (defconst org-all-time-keywords
465 (mapcar (lambda (w) (substring w 0 -1))
466 (list org-scheduled-string org-deadline-string
467 org-clock-string org-closed-string))
468 "List of time keywords.")
470 ;;;; Drawer
472 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
473 "Matches first or last line of a hidden block.
474 Group 1 contains drawer's name or \"END\".")
476 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
477 "Regular expression matching the first line of a property drawer.")
479 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
480 "Regular expression matching the last line of a property drawer.")
482 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
483 "Regular expression matching the first line of a clock drawer.")
485 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
486 "Regular expression matching the last line of a clock drawer.")
488 (defconst org-property-drawer-re
489 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
490 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
491 "[ \t]*:END:[ \t]*$")
492 "Matches an entire property drawer.")
494 (defconst org-clock-drawer-re
495 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
496 org-clock-drawer-end-re "\\)\n?")
497 "Matches an entire clock drawer.")
499 ;;;; Headline
501 (defconst org-heading-keyword-regexp-format
502 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
503 "Printf format for a regexp matching a headline with some keyword.
504 This regexp will match the headline of any node which has the
505 exact keyword that is put into the format. The keyword isn't in
506 any group by default, but the stars and the body are.")
508 (defconst org-heading-keyword-maybe-regexp-format
509 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
510 "Printf format for a regexp matching a headline, possibly with some keyword.
511 This regexp can match any headline with the specified keyword, or
512 without a keyword. The keyword isn't in any group by default,
513 but the stars and the body are.")
515 (defconst org-archive-tag "ARCHIVE"
516 "The tag that marks a subtree as archived.
517 An archived subtree does not open during visibility cycling, and does
518 not contribute to the agenda listings.")
520 (defconst org-comment-string "COMMENT"
521 "Entries starting with this keyword will never be exported.
522 An entry can be toggled between COMMENT and normal with
523 \\[org-toggle-comment].")
526 ;;;; LaTeX Environments and Fragments
528 (defconst org-latex-regexps
529 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
530 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
531 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
532 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
533 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
534 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
535 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
536 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
537 "Regular expressions for matching embedded LaTeX.")
539 ;;;; Node Property
541 (defconst org-effort-property "Effort"
542 "The property that is being used to keep track of effort estimates.
543 Effort estimates given in this property need to have the format H:MM.")
545 ;;;; Table
547 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
548 "Detect an org-type or table-type table.")
550 (defconst org-table-line-regexp "^[ \t]*|"
551 "Detect an org-type table line.")
553 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
554 "Detect an org-type table line.")
556 (defconst org-table-hline-regexp "^[ \t]*|-"
557 "Detect an org-type table hline.")
559 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
560 "Detect a table-type table hline.")
562 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
563 "Detect the first line outside a table when searching from within it.
564 This works for both table types.")
566 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
567 "Detect a #+TBLFM line.")
569 ;;;; Timestamp
571 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
572 "Regular expression for fast time stamp matching.")
574 (defconst org-ts-regexp-inactive
575 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
576 "Regular expression for fast inactive time stamp matching.")
578 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
579 "Regular expression for fast time stamp matching.")
581 (defconst org-ts-regexp0
582 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
583 "Regular expression matching time strings for analysis.
584 This one does not require the space after the date, so it can be used
585 on a string that terminates immediately after the date.")
587 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
588 "Regular expression matching time strings for analysis.")
590 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
591 "Regular expression matching time stamps, with groups.")
593 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
594 "Regular expression matching time stamps (also [..]), with groups.")
596 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
597 "Regular expression matching a time stamp range.")
599 (defconst org-tr-regexp-both
600 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
601 "Regular expression matching a time stamp range.")
603 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
604 org-ts-regexp "\\)?")
605 "Regular expression matching a time stamp or time stamp range.")
607 (defconst org-tsr-regexp-both
608 (concat org-ts-regexp-both "\\(--?-?"
609 org-ts-regexp-both "\\)?")
610 "Regular expression matching a time stamp or time stamp range.
611 The time stamps may be either active or inactive.")
613 (defconst org-repeat-re
614 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
615 "Regular expression for specifying repeated events.
616 After a match, group 1 contains the repeat expression.")
618 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
619 "Formats for `format-time-string' which are used for time stamps.")
622 ;;; The custom variables
624 (defgroup org nil
625 "Outline-based notes management and organizer."
626 :tag "Org"
627 :group 'outlines
628 :group 'calendar)
630 (defcustom org-mode-hook nil
631 "Mode hook for Org-mode, run after the mode was turned on."
632 :group 'org
633 :type 'hook)
635 (defcustom org-load-hook nil
636 "Hook that is run after org.el has been loaded."
637 :group 'org
638 :type 'hook)
640 (defcustom org-log-buffer-setup-hook nil
641 "Hook that is run after an Org log buffer is created."
642 :group 'org
643 :version "24.1"
644 :type 'hook)
646 (defvar org-modules) ; defined below
647 (defvar org-modules-loaded nil
648 "Have the modules been loaded already?")
650 (defun org-load-modules-maybe (&optional force)
651 "Load all extensions listed in `org-modules'."
652 (when (or force (not org-modules-loaded))
653 (dolist (ext org-modules)
654 (condition-case nil (require ext)
655 (error (message "Problems while trying to load feature `%s'" ext))))
656 (setq org-modules-loaded t)))
658 (defun org-set-modules (var value)
659 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
660 (set var value)
661 (when (featurep 'org)
662 (org-load-modules-maybe 'force)
663 (org-element-cache-reset 'all)))
665 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
666 "Modules that should always be loaded together with org.el.
668 If a description starts with <C>, the file is not part of Emacs
669 and loading it will require that you have downloaded and properly
670 installed the Org mode distribution.
672 You can also use this system to load external packages (i.e. neither Org
673 core modules, nor modules from the CONTRIB directory). Just add symbols
674 to the end of the list. If the package is called org-xyz.el, then you need
675 to add the symbol `xyz', and the package must have a call to:
677 (provide \\='org-xyz)
679 For export specific modules, see also `org-export-backends'."
680 :group 'org
681 :set 'org-set-modules
682 :version "24.4"
683 :package-version '(Org . "8.0")
684 :type
685 '(set :greedy t
686 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
687 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
688 (const :tag " crypt: Encryption of subtrees" org-crypt)
689 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
690 (const :tag " docview: Links to doc-view buffers" org-docview)
691 (const :tag " eww: Store link to url of eww" org-eww)
692 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
693 (const :tag " habit: Track your consistency with habits" org-habit)
694 (const :tag " id: Global IDs for identifying entries" org-id)
695 (const :tag " info: Links to Info nodes" org-info)
696 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
697 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
698 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
699 (const :tag " mouse: Additional mouse support" org-mouse)
700 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
701 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
702 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
704 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
705 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
706 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
707 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
708 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
709 (const :tag "C collector: Collect properties into tables" org-collector)
710 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
711 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
712 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
713 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
714 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
715 (const :tag "C eval: Include command output as text" org-eval)
716 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
717 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
718 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
719 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
720 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
721 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
722 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
723 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
724 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
725 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
726 (const :tag "C mew: Links to Mew folders/messages" org-mew)
727 (const :tag "C mtags: Support for muse-like tags" org-mtags)
728 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
729 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
730 (const :tag "C registry: A registry for Org links" org-registry)
731 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
732 (const :tag "C secretary: Team management with org-mode" org-secretary)
733 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
734 (const :tag "C toc: Table of contents for Org buffer" org-toc)
735 (const :tag "C track: Keep up with Org mode development" org-track)
736 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
737 (const :tag "C vm: Links to VM folders/messages" org-vm)
738 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
739 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
740 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
742 (defvar org-export-registered-backends) ; From ox.el.
743 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
744 (declare-function org-export-backend-name "ox" (backend) t)
745 (defcustom org-export-backends '(ascii html icalendar latex odt)
746 "List of export back-ends that should be always available.
748 If a description starts with <C>, the file is not part of Emacs
749 and loading it will require that you have downloaded and properly
750 installed the Org mode distribution.
752 Unlike to `org-modules', libraries in this list will not be
753 loaded along with Org, but only once the export framework is
754 needed.
756 This variable needs to be set before org.el is loaded. If you
757 need to make a change while Emacs is running, use the customize
758 interface or run the following code, where VAL stands for the new
759 value of the variable, after updating it:
761 (progn
762 (setq org-export-registered-backends
763 (cl-remove-if-not
764 (lambda (backend)
765 (let ((name (org-export-backend-name backend)))
766 (or (memq name val)
767 (catch \\='parentp
768 (dolist (b val)
769 (and (org-export-derived-backend-p b name)
770 (throw \\='parentp t)))))))
771 org-export-registered-backends))
772 (let ((new-list (mapcar #\\='org-export-backend-name
773 org-export-registered-backends)))
774 (dolist (backend val)
775 (cond
776 ((not (load (format \"ox-%s\" backend) t t))
777 (message \"Problems while trying to load export back-end \\=`%s\\='\"
778 backend))
779 ((not (memq backend new-list)) (push backend new-list))))
780 (set-default \\='org-export-backends new-list)))
782 Adding a back-end to this list will also pull the back-end it
783 depends on, if any."
784 :group 'org
785 :group 'org-export
786 :version "25.1"
787 :package-version '(Org . "9.0")
788 :initialize 'custom-initialize-set
789 :set (lambda (var val)
790 (if (not (featurep 'ox)) (set-default var val)
791 ;; Any back-end not required anymore (not present in VAL and not
792 ;; a parent of any back-end in the new value) is removed from the
793 ;; list of registered back-ends.
794 (setq org-export-registered-backends
795 (cl-remove-if-not
796 (lambda (backend)
797 (let ((name (org-export-backend-name backend)))
798 (or (memq name val)
799 (catch 'parentp
800 (dolist (b val)
801 (and (org-export-derived-backend-p b name)
802 (throw 'parentp t)))))))
803 org-export-registered-backends))
804 ;; Now build NEW-LIST of both new back-ends and required
805 ;; parents.
806 (let ((new-list (mapcar #'org-export-backend-name
807 org-export-registered-backends)))
808 (dolist (backend val)
809 (cond
810 ((not (load (format "ox-%s" backend) t t))
811 (message "Problems while trying to load export back-end `%s'"
812 backend))
813 ((not (memq backend new-list)) (push backend new-list))))
814 ;; Set VAR to that list with fixed dependencies.
815 (set-default var new-list))))
816 :type '(set :greedy t
817 (const :tag " ascii Export buffer to ASCII format" ascii)
818 (const :tag " beamer Export buffer to Beamer presentation" beamer)
819 (const :tag " html Export buffer to HTML format" html)
820 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
821 (const :tag " latex Export buffer to LaTeX format" latex)
822 (const :tag " man Export buffer to MAN format" man)
823 (const :tag " md Export buffer to Markdown format" md)
824 (const :tag " odt Export buffer to ODT format" odt)
825 (const :tag " org Export buffer to Org format" org)
826 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
827 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
828 (const :tag "C deck Export buffer to deck.js presentations" deck)
829 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
830 (const :tag "C groff Export buffer to Groff format" groff)
831 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
832 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
833 (const :tag "C s5 Export buffer to s5 presentations" s5)
834 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
836 (eval-after-load 'ox
837 '(dolist (backend org-export-backends)
838 (condition-case nil (require (intern (format "ox-%s" backend)))
839 (error (message "Problems while trying to load export back-end `%s'"
840 backend)))))
842 (defcustom org-support-shift-select nil
843 "Non-nil means make shift-cursor commands select text when possible.
844 \\<org-mode-map>\
846 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
847 start selecting a region, or enlarge regions started in this way.
848 In Org-mode, in special contexts, these same keys are used for
849 other purposes, important enough to compete with shift selection.
850 Org tries to balance these needs by supporting `shift-select-mode'
851 outside these special contexts, under control of this variable.
853 The default of this variable is nil, to avoid confusing behavior. Shifted
854 cursor keys will then execute Org commands in the following contexts:
855 - on a headline, changing TODO state (left/right) and priority (up/down)
856 - on a time stamp, changing the time
857 - in a plain list item, changing the bullet type
858 - in a property definition line, switching between allowed values
859 - in the BEGIN line of a clock table (changing the time block).
860 Outside these contexts, the commands will throw an error.
862 When this variable is t and the cursor is not in a special
863 context, Org mode will support shift-selection for making and
864 enlarging regions. To make this more effective, the bullet
865 cycling will no longer happen anywhere in an item line, but only
866 if the cursor is exactly on the bullet.
868 If you set this variable to the symbol `always', then the keys
869 will not be special in headlines, property lines, and item lines,
870 to make shift selection work there as well. If this is what you
871 want, you can use the following alternative commands:
872 `\\[org-todo]' and `\\[org-priority]' \
873 to change TODO state and priority,
874 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
875 can be used to switch TODO sets,
876 `\\[org-ctrl-c-minus]' to cycle item bullet types,
877 and properties can be edited by hand or in column view.
879 However, when the cursor is on a timestamp, shift-cursor commands
880 will still edit the time stamp - this is just too good to give up."
881 :group 'org
882 :type '(choice
883 (const :tag "Never" nil)
884 (const :tag "When outside special context" t)
885 (const :tag "Everywhere except timestamps" always)))
887 (defcustom org-loop-over-headlines-in-active-region nil
888 "Shall some commands act upon headlines in the active region?
890 When set to t, some commands will be performed in all headlines
891 within the active region.
893 When set to `start-level', some commands will be performed in all
894 headlines within the active region, provided that these headlines
895 are of the same level than the first one.
897 When set to a string, those commands will be performed on the
898 matching headlines within the active region. Such string must be
899 a tags/property/todo match as it is used in the agenda tags view.
901 The list of commands is: `org-schedule', `org-deadline',
902 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
903 `org-archive-to-archive-sibling'. The archiving commands skip
904 already archived entries."
905 :type '(choice (const :tag "Don't loop" nil)
906 (const :tag "All headlines in active region" t)
907 (const :tag "In active region, headlines at the same level than the first one" start-level)
908 (string :tag "Tags/Property/Todo matcher"))
909 :version "24.1"
910 :group 'org-todo
911 :group 'org-archive)
913 (defgroup org-startup nil
914 "Options concerning startup of Org-mode."
915 :tag "Org Startup"
916 :group 'org)
918 (defcustom org-startup-folded t
919 "Non-nil means entering Org mode will switch to OVERVIEW.
920 This can also be configured on a per-file basis by adding one of
921 the following lines anywhere in the buffer:
923 #+STARTUP: fold (or `overview', this is equivalent)
924 #+STARTUP: nofold (or `showall', this is equivalent)
925 #+STARTUP: content
926 #+STARTUP: showeverything
928 By default, this option is ignored when Org opens agenda files
929 for the first time. If you want the agenda to honor the startup
930 option, set `org-agenda-inhibit-startup' to nil."
931 :group 'org-startup
932 :type '(choice
933 (const :tag "nofold: show all" nil)
934 (const :tag "fold: overview" t)
935 (const :tag "content: all headlines" content)
936 (const :tag "show everything, even drawers" showeverything)))
938 (defcustom org-startup-truncated t
939 "Non-nil means entering Org mode will set `truncate-lines'.
940 This is useful since some lines containing links can be very long and
941 uninteresting. Also tables look terrible when wrapped.
943 The variable `org-startup-truncated' allows to configure
944 truncation for Org mode different to the other modes that use the
945 variable `truncate-lines' and as a shortcut instead of putting
946 the variable `truncate-lines' into the `org-mode-hook'. If one
947 wants to configure truncation for Org mode not statically but
948 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
949 the variable `truncate-lines' has to be used because in such a
950 case it is too late to set the variable `org-startup-truncated'."
951 :group 'org-startup
952 :type 'boolean)
954 (defcustom org-startup-indented nil
955 "Non-nil means turn on `org-indent-mode' on startup.
956 This can also be configured on a per-file basis by adding one of
957 the following lines anywhere in the buffer:
959 #+STARTUP: indent
960 #+STARTUP: noindent"
961 :group 'org-structure
962 :type '(choice
963 (const :tag "Not" nil)
964 (const :tag "Globally (slow on startup in large files)" t)))
966 (defcustom org-use-sub-superscripts t
967 "Non-nil means interpret \"_\" and \"^\" for display.
969 If you want to control how Org exports those characters, see
970 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
971 used to be an alias for `org-export-with-sub-superscripts' in
972 Org <8.0, it is not anymore.
974 When this option is turned on, you can use TeX-like syntax for
975 sub- and superscripts within the buffer. Several characters after
976 \"_\" or \"^\" will be considered as a single item - so grouping
977 with {} is normally not needed. For example, the following things
978 will be parsed as single sub- or superscripts:
980 10^24 or 10^tau several digits will be considered 1 item.
981 10^-12 or 10^-tau a leading sign with digits or a word
982 x^2-y^3 will be read as x^2 - y^3, because items are
983 terminated by almost any nonword/nondigit char.
984 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
986 Still, ambiguity is possible. So when in doubt, use {} to enclose
987 the sub/superscript. If you set this variable to the symbol `{}',
988 the braces are *required* in order to trigger interpretations as
989 sub/superscript. This can be helpful in documents that need \"_\"
990 frequently in plain text."
991 :group 'org-startup
992 :version "24.4"
993 :package-version '(Org . "8.0")
994 :type '(choice
995 (const :tag "Always interpret" t)
996 (const :tag "Only with braces" {})
997 (const :tag "Never interpret" nil)))
999 (defcustom org-startup-with-beamer-mode nil
1000 "Non-nil means turn on `org-beamer-mode' on startup.
1001 This can also be configured on a per-file basis by adding one of
1002 the following lines anywhere in the buffer:
1004 #+STARTUP: beamer"
1005 :group 'org-startup
1006 :version "24.1"
1007 :type 'boolean)
1009 (defcustom org-startup-align-all-tables nil
1010 "Non-nil means align all tables when visiting a file.
1011 This is useful when the column width in tables is forced with <N> cookies
1012 in table fields. Such tables will look correct only after the first re-align.
1013 This can also be configured on a per-file basis by adding one of
1014 the following lines anywhere in the buffer:
1015 #+STARTUP: align
1016 #+STARTUP: noalign"
1017 :group 'org-startup
1018 :type 'boolean)
1020 (defcustom org-startup-with-inline-images nil
1021 "Non-nil means show inline images when loading a new Org file.
1022 This can also be configured on a per-file basis by adding one of
1023 the following lines anywhere in the buffer:
1024 #+STARTUP: inlineimages
1025 #+STARTUP: noinlineimages"
1026 :group 'org-startup
1027 :version "24.1"
1028 :type 'boolean)
1030 (defcustom org-startup-with-latex-preview nil
1031 "Non-nil means preview LaTeX fragments when loading a new Org file.
1033 This can also be configured on a per-file basis by adding one of
1034 the following lines anywhere in the buffer:
1035 #+STARTUP: latexpreview
1036 #+STARTUP: nolatexpreview"
1037 :group 'org-startup
1038 :version "24.4"
1039 :package-version '(Org . "8.0")
1040 :type 'boolean)
1042 (defcustom org-insert-mode-line-in-empty-file nil
1043 "Non-nil means insert the first line setting Org mode in empty files.
1044 When the function `org-mode' is called interactively in an empty file, this
1045 normally means that the file name does not automatically trigger Org mode.
1046 To ensure that the file will always be in Org mode in the future, a
1047 line enforcing Org mode will be inserted into the buffer, if this option
1048 has been set."
1049 :group 'org-startup
1050 :type 'boolean)
1052 (defcustom org-replace-disputed-keys nil
1053 "Non-nil means use alternative key bindings for some keys.
1054 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1055 These keys are also used by other packages like shift-selection-mode'
1056 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1057 If you want to use Org mode together with one of these other modes,
1058 or more generally if you would like to move some Org mode commands to
1059 other keys, set this variable and configure the keys with the variable
1060 `org-disputed-keys'.
1062 This option is only relevant at load-time of Org-mode, and must be set
1063 *before* org.el is loaded. Changing it requires a restart of Emacs to
1064 become effective."
1065 :group 'org-startup
1066 :type 'boolean)
1068 (defcustom org-use-extra-keys nil
1069 "Non-nil means use extra key sequence definitions for certain commands.
1070 This happens automatically if `window-system' is nil. This
1071 variable lets you do the same manually. You must set it before
1072 loading Org."
1073 :group 'org-startup
1074 :type 'boolean)
1076 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1078 (defcustom org-disputed-keys
1079 '(([(shift up)] . [(meta p)])
1080 ([(shift down)] . [(meta n)])
1081 ([(shift left)] . [(meta -)])
1082 ([(shift right)] . [(meta +)])
1083 ([(control shift right)] . [(meta shift +)])
1084 ([(control shift left)] . [(meta shift -)]))
1085 "Keys for which Org mode and other modes compete.
1086 This is an alist, cars are the default keys, second element specifies
1087 the alternative to use when `org-replace-disputed-keys' is t.
1089 Keys can be specified in any syntax supported by `define-key'.
1090 The value of this option takes effect only at Org-mode's startup,
1091 therefore you'll have to restart Emacs to apply it after changing."
1092 :group 'org-startup
1093 :type 'alist)
1095 (defun org-key (key)
1096 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1097 Or return the original if not disputed."
1098 (when org-replace-disputed-keys
1099 (let* ((nkey (key-description key))
1100 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1101 org-disputed-keys)))
1102 (setq key (if x (cdr x) key))))
1103 key)
1105 (defun org-defkey (keymap key def)
1106 "Define a key, possibly translated, as returned by `org-key'."
1107 (define-key keymap (org-key key) def))
1109 (defcustom org-ellipsis nil
1110 "The ellipsis to use in the Org mode outline.
1111 When nil, just use the standard three dots.
1112 When a string, use that string instead.
1113 When a face, use the standard 3 dots, but with the specified face.
1114 The change affects only Org mode (which will then use its own display table).
1115 Changing this requires executing \\[org-mode] in a buffer to become
1116 effective."
1117 :group 'org-startup
1118 :type '(choice (const :tag "Default" nil)
1119 (face :tag "Face" :value org-warning)
1120 (string :tag "String" :value "...#")))
1122 (defvar org-display-table nil
1123 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1125 (defgroup org-keywords nil
1126 "Keywords in Org-mode."
1127 :tag "Org Keywords"
1128 :group 'org)
1130 (defcustom org-closed-keep-when-no-todo nil
1131 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1132 :group 'org-todo
1133 :group 'org-keywords
1134 :version "24.4"
1135 :package-version '(Org . "8.0")
1136 :type 'boolean)
1138 (defgroup org-structure nil
1139 "Options concerning the general structure of Org files."
1140 :tag "Org Structure"
1141 :group 'org)
1143 (defgroup org-reveal-location nil
1144 "Options about how to make context of a location visible."
1145 :tag "Org Reveal Location"
1146 :group 'org-structure)
1148 (defcustom org-show-context-detail '((agenda . local)
1149 (bookmark-jump . lineage)
1150 (isearch . lineage)
1151 (default . ancestors))
1152 "Alist between context and visibility span when revealing a location.
1154 \\<org-mode-map>Some actions may move point into invisible
1155 locations. As a consequence, Org always expose a neighborhood
1156 around point. How much is shown depends on the initial action,
1157 or context. Valid contexts are
1159 agenda when exposing an entry from the agenda
1160 org-goto when using the command `org-goto' (\\[org-goto])
1161 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1162 tags-tree when constructing a sparse tree based on tags matches
1163 link-search when exposing search matches associated with a link
1164 mark-goto when exposing the jump goal of a mark
1165 bookmark-jump when exposing a bookmark location
1166 isearch when exiting from an incremental search
1167 default default for all contexts not set explicitly
1169 Allowed visibility spans are
1171 minimal show current headline; if point is not on headline,
1172 also show entry
1174 local show current headline, entry and next headline
1176 ancestors show current headline and its direct ancestors; if
1177 point is not on headline, also show entry
1179 lineage show current headline, its direct ancestors and all
1180 their children; if point is not on headline, also show
1181 entry and first child
1183 tree show current headline, its direct ancestors and all
1184 their children; if point is not on headline, also show
1185 entry and all children
1187 canonical show current headline, its direct ancestors along with
1188 their entries and children; if point is not located on
1189 the headline, also show current entry and all children
1191 As special cases, a nil or t value means show all contexts in
1192 `minimal' or `canonical' view, respectively.
1194 Some views can make displayed information very compact, but also
1195 make it harder to edit the location of the match. In such
1196 a case, use the command `org-reveal' (\\[org-reveal]) to show
1197 more context."
1198 :group 'org-reveal-location
1199 :version "25.2"
1200 :package-version '(Org . "9.0")
1201 :type '(choice
1202 (const :tag "Canonical" t)
1203 (const :tag "Minimal" nil)
1204 (repeat :greedy t :tag "Individual contexts"
1205 (cons
1206 (choice :tag "Context"
1207 (const agenda)
1208 (const org-goto)
1209 (const occur-tree)
1210 (const tags-tree)
1211 (const link-search)
1212 (const mark-goto)
1213 (const bookmark-jump)
1214 (const isearch)
1215 (const default))
1216 (choice :tag "Detail level"
1217 (const minimal)
1218 (const local)
1219 (const ancestors)
1220 (const lineage)
1221 (const tree)
1222 (const canonical))))))
1224 (defcustom org-indirect-buffer-display 'other-window
1225 "How should indirect tree buffers be displayed?
1226 This applies to indirect buffers created with the commands
1227 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1228 Valid values are:
1229 current-window Display in the current window
1230 other-window Just display in another window.
1231 dedicated-frame Create one new frame, and re-use it each time.
1232 new-frame Make a new frame each time. Note that in this case
1233 previously-made indirect buffers are kept, and you need to
1234 kill these buffers yourself."
1235 :group 'org-structure
1236 :group 'org-agenda-windows
1237 :type '(choice
1238 (const :tag "In current window" current-window)
1239 (const :tag "In current frame, other window" other-window)
1240 (const :tag "Each time a new frame" new-frame)
1241 (const :tag "One dedicated frame" dedicated-frame)))
1243 (defcustom org-use-speed-commands nil
1244 "Non-nil means activate single letter commands at beginning of a headline.
1245 This may also be a function to test for appropriate locations where speed
1246 commands should be active.
1248 For example, to activate speed commands when the point is on any
1249 star at the beginning of the headline, you can do this:
1251 (setq org-use-speed-commands
1252 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1253 :group 'org-structure
1254 :type '(choice
1255 (const :tag "Never" nil)
1256 (const :tag "At beginning of headline stars" t)
1257 (function)))
1259 (defcustom org-speed-commands-user nil
1260 "Alist of additional speed commands.
1261 This list will be checked before `org-speed-commands-default'
1262 when the variable `org-use-speed-commands' is non-nil
1263 and when the cursor is at the beginning of a headline.
1264 The car if each entry is a string with a single letter, which must
1265 be assigned to `self-insert-command' in the global map.
1266 The cdr is either a command to be called interactively, a function
1267 to be called, or a form to be evaluated.
1268 An entry that is just a list with a single string will be interpreted
1269 as a descriptive headline that will be added when listing the speed
1270 commands in the Help buffer using the `?' speed command."
1271 :group 'org-structure
1272 :type '(repeat :value ("k" . ignore)
1273 (choice :value ("k" . ignore)
1274 (list :tag "Descriptive Headline" (string :tag "Headline"))
1275 (cons :tag "Letter and Command"
1276 (string :tag "Command letter")
1277 (choice
1278 (function)
1279 (sexp))))))
1281 (defcustom org-bookmark-names-plist
1282 '(:last-capture "org-capture-last-stored"
1283 :last-refile "org-refile-last-stored"
1284 :last-capture-marker "org-capture-last-stored-marker")
1285 "Names for bookmarks automatically set by some Org commands.
1286 This can provide strings as names for a number of bookmarks Org sets
1287 automatically. The following keys are currently implemented:
1288 :last-capture
1289 :last-capture-marker
1290 :last-refile
1291 When a key does not show up in the property list, the corresponding bookmark
1292 is not set."
1293 :group 'org-structure
1294 :type 'plist)
1296 (defgroup org-cycle nil
1297 "Options concerning visibility cycling in Org-mode."
1298 :tag "Org Cycle"
1299 :group 'org-structure)
1301 (defcustom org-cycle-skip-children-state-if-no-children t
1302 "Non-nil means skip CHILDREN state in entries that don't have any."
1303 :group 'org-cycle
1304 :type 'boolean)
1306 (defcustom org-cycle-max-level nil
1307 "Maximum level which should still be subject to visibility cycling.
1308 Levels higher than this will, for cycling, be treated as text, not a headline.
1309 When `org-odd-levels-only' is set, a value of N in this variable actually
1310 means 2N-1 stars as the limiting headline.
1311 When nil, cycle all levels.
1312 Note that the limiting level of cycling is also influenced by
1313 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1314 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1315 than its value."
1316 :group 'org-cycle
1317 :type '(choice
1318 (const :tag "No limit" nil)
1319 (integer :tag "Maximum level")))
1321 (defcustom org-hide-block-startup nil
1322 "Non-nil means entering Org mode will fold all blocks.
1323 This can also be set in on a per-file basis with
1325 #+STARTUP: hideblocks
1326 #+STARTUP: showblocks"
1327 :group 'org-startup
1328 :group 'org-cycle
1329 :type 'boolean)
1331 (defcustom org-cycle-global-at-bob nil
1332 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1333 This makes it possible to do global cycling without having to use S-TAB or
1334 \\[universal-argument] TAB. For this special case to work, the first line
1335 of the buffer must not be a headline -- it may be empty or some other text.
1336 When used in this way, `org-cycle-hook' is disabled temporarily to make
1337 sure the cursor stays at the beginning of the buffer. When this option is
1338 nil, don't do anything special at the beginning of the buffer."
1339 :group 'org-cycle
1340 :type 'boolean)
1342 (defcustom org-cycle-level-after-item/entry-creation t
1343 "Non-nil means cycle entry level or item indentation in new empty entries.
1345 When the cursor is at the end of an empty headline, i.e., with only stars
1346 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1347 and then all possible ancestor states, before returning to the original state.
1348 This makes data entry extremely fast: M-RET to create a new headline,
1349 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1351 When the cursor is at the end of an empty plain list item, one TAB will
1352 make it a subitem, two or more tabs will back up to make this an item
1353 higher up in the item hierarchy."
1354 :group 'org-cycle
1355 :type 'boolean)
1357 (defcustom org-cycle-emulate-tab t
1358 "Where should `org-cycle' emulate TAB.
1359 nil Never
1360 white Only in completely white lines
1361 whitestart Only at the beginning of lines, before the first non-white char
1362 t Everywhere except in headlines
1363 exc-hl-bol Everywhere except at the start of a headline
1364 If TAB is used in a place where it does not emulate TAB, the current subtree
1365 visibility is cycled."
1366 :group 'org-cycle
1367 :type '(choice (const :tag "Never" nil)
1368 (const :tag "Only in completely white lines" white)
1369 (const :tag "Before first char in a line" whitestart)
1370 (const :tag "Everywhere except in headlines" t)
1371 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1373 (defcustom org-cycle-separator-lines 2
1374 "Number of empty lines needed to keep an empty line between collapsed trees.
1375 If you leave an empty line between the end of a subtree and the following
1376 headline, this empty line is hidden when the subtree is folded.
1377 Org mode will leave (exactly) one empty line visible if the number of
1378 empty lines is equal or larger to the number given in this variable.
1379 So the default 2 means at least 2 empty lines after the end of a subtree
1380 are needed to produce free space between a collapsed subtree and the
1381 following headline.
1383 If the number is negative, and the number of empty lines is at least -N,
1384 all empty lines are shown.
1386 Special case: when 0, never leave empty lines in collapsed view."
1387 :group 'org-cycle
1388 :type 'integer)
1389 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1391 (defcustom org-pre-cycle-hook nil
1392 "Hook that is run before visibility cycling is happening.
1393 The function(s) in this hook must accept a single argument which indicates
1394 the new state that will be set right after running this hook. The
1395 argument is a symbol. Before a global state change, it can have the values
1396 `overview', `content', or `all'. Before a local state change, it can have
1397 the values `folded', `children', or `subtree'."
1398 :group 'org-cycle
1399 :type 'hook)
1401 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1402 org-cycle-hide-drawers
1403 org-cycle-show-empty-lines
1404 org-optimize-window-after-visibility-change)
1405 "Hook that is run after `org-cycle' has changed the buffer visibility.
1406 The function(s) in this hook must accept a single argument which indicates
1407 the new state that was set by the most recent `org-cycle' command. The
1408 argument is a symbol. After a global state change, it can have the values
1409 `overview', `contents', or `all'. After a local state change, it can have
1410 the values `folded', `children', or `subtree'."
1411 :group 'org-cycle
1412 :type 'hook
1413 :version "25.1"
1414 :package-version '(Org . "8.3"))
1416 (defgroup org-edit-structure nil
1417 "Options concerning structure editing in Org-mode."
1418 :tag "Org Edit Structure"
1419 :group 'org-structure)
1421 (defcustom org-odd-levels-only nil
1422 "Non-nil means skip even levels and only use odd levels for the outline.
1423 This has the effect that two stars are being added/taken away in
1424 promotion/demotion commands. It also influences how levels are
1425 handled by the exporters.
1426 Changing it requires restart of `font-lock-mode' to become effective
1427 for fontification also in regions already fontified.
1428 You may also set this on a per-file basis by adding one of the following
1429 lines to the buffer:
1431 #+STARTUP: odd
1432 #+STARTUP: oddeven"
1433 :group 'org-edit-structure
1434 :group 'org-appearance
1435 :type 'boolean)
1437 (defcustom org-adapt-indentation t
1438 "Non-nil means adapt indentation to outline node level.
1440 When this variable is set, Org assumes that you write outlines by
1441 indenting text in each node to align with the headline (after the
1442 stars). The following issues are influenced by this variable:
1444 - The indentation is increased by one space in a demotion
1445 command, and decreased by one in a promotion command. However,
1446 in the latter case, if shifting some line in the entry body
1447 would alter document structure (e.g., insert a new headline),
1448 indentation is not changed at all.
1450 - Property drawers and planning information is inserted indented
1451 when this variable is set. When nil, they will not be indented.
1453 - TAB indents a line relative to current level. The lines below
1454 a headline will be indented when this variable is set.
1456 Note that this is all about true indentation, by adding and
1457 removing space characters. See also `org-indent.el' which does
1458 level-dependent indentation in a virtual way, i.e. at display
1459 time in Emacs."
1460 :group 'org-edit-structure
1461 :type 'boolean)
1463 (defcustom org-special-ctrl-a/e nil
1464 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1466 When t, `C-a' will bring back the cursor to the beginning of the
1467 headline text, i.e. after the stars and after a possible TODO
1468 keyword. In an item, this will be the position after bullet and
1469 check-box, if any. When the cursor is already at that position,
1470 another `C-a' will bring it to the beginning of the line.
1472 `C-e' will jump to the end of the headline, ignoring the presence
1473 of tags in the headline. A second `C-e' will then jump to the
1474 true end of the line, after any tags. This also means that, when
1475 this variable is non-nil, `C-e' also will never jump beyond the
1476 end of the heading of a folded section, i.e. not after the
1477 ellipses.
1479 When set to the symbol `reversed', the first `C-a' or `C-e' works
1480 normally, going to the true line boundary first. Only a directly
1481 following, identical keypress will bring the cursor to the
1482 special positions.
1484 This may also be a cons cell where the behavior for `C-a' and
1485 `C-e' is set separately."
1486 :group 'org-edit-structure
1487 :type '(choice
1488 (const :tag "off" nil)
1489 (const :tag "on: after stars/bullet and before tags first" t)
1490 (const :tag "reversed: true line boundary first" reversed)
1491 (cons :tag "Set C-a and C-e separately"
1492 (choice :tag "Special C-a"
1493 (const :tag "off" nil)
1494 (const :tag "on: after stars/bullet first" t)
1495 (const :tag "reversed: before stars/bullet first" reversed))
1496 (choice :tag "Special C-e"
1497 (const :tag "off" nil)
1498 (const :tag "on: before tags first" t)
1499 (const :tag "reversed: after tags first" reversed)))))
1500 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1502 (defcustom org-special-ctrl-k nil
1503 "Non-nil means `C-k' will behave specially in headlines.
1504 When nil, `C-k' will call the default `kill-line' command.
1505 When t, the following will happen while the cursor is in the headline:
1507 - When the cursor is at the beginning of a headline, kill the entire
1508 line and possible the folded subtree below the line.
1509 - When in the middle of the headline text, kill the headline up to the tags.
1510 - When after the headline text, kill the tags."
1511 :group 'org-edit-structure
1512 :type 'boolean)
1514 (defcustom org-ctrl-k-protect-subtree nil
1515 "Non-nil means, do not delete a hidden subtree with C-k.
1516 When set to the symbol `error', simply throw an error when C-k is
1517 used to kill (part-of) a headline that has hidden text behind it.
1518 Any other non-nil value will result in a query to the user, if it is
1519 OK to kill that hidden subtree. When nil, kill without remorse."
1520 :group 'org-edit-structure
1521 :version "24.1"
1522 :type '(choice
1523 (const :tag "Do not protect hidden subtrees" nil)
1524 (const :tag "Protect hidden subtrees with a security query" t)
1525 (const :tag "Never kill a hidden subtree with C-k" error)))
1527 (defcustom org-special-ctrl-o t
1528 "Non-nil means, make `C-o' insert a row in tables."
1529 :group 'org-edit-structure
1530 :type 'boolean)
1532 (defcustom org-catch-invisible-edits nil
1533 "Check if in invisible region before inserting or deleting a character.
1534 Valid values are:
1536 nil Do not check, so just do invisible edits.
1537 error Throw an error and do nothing.
1538 show Make point visible, and do the requested edit.
1539 show-and-error Make point visible, then throw an error and abort the edit.
1540 smart Make point visible, and do insertion/deletion if it is
1541 adjacent to visible text and the change feels predictable.
1542 Never delete a previously invisible character or add in the
1543 middle or right after an invisible region. Basically, this
1544 allows insertion and backward-delete right before ellipses.
1545 FIXME: maybe in this case we should not even show?"
1546 :group 'org-edit-structure
1547 :version "24.1"
1548 :type '(choice
1549 (const :tag "Do not check" nil)
1550 (const :tag "Throw error when trying to edit" error)
1551 (const :tag "Unhide, but do not do the edit" show-and-error)
1552 (const :tag "Show invisible part and do the edit" show)
1553 (const :tag "Be smart and do the right thing" smart)))
1555 (defcustom org-yank-folded-subtrees t
1556 "Non-nil means when yanking subtrees, fold them.
1557 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1558 it starts with a heading and all other headings in it are either children
1559 or siblings, then fold all the subtrees. However, do this only if no
1560 text after the yank would be swallowed into a folded tree by this action."
1561 :group 'org-edit-structure
1562 :type 'boolean)
1564 (defcustom org-yank-adjusted-subtrees nil
1565 "Non-nil means when yanking subtrees, adjust the level.
1566 With this setting, `org-paste-subtree' is used to insert the subtree, see
1567 this function for details."
1568 :group 'org-edit-structure
1569 :type 'boolean)
1571 (defcustom org-M-RET-may-split-line '((default . t))
1572 "Non-nil means M-RET will split the line at the cursor position.
1573 When nil, it will go to the end of the line before making a
1574 new line.
1575 You may also set this option in a different way for different
1576 contexts. Valid contexts are:
1578 headline when creating a new headline
1579 item when creating a new item
1580 table in a table field
1581 default the value to be used for all contexts not explicitly
1582 customized"
1583 :group 'org-structure
1584 :group 'org-table
1585 :type '(choice
1586 (const :tag "Always" t)
1587 (const :tag "Never" nil)
1588 (repeat :greedy t :tag "Individual contexts"
1589 (cons
1590 (choice :tag "Context"
1591 (const headline)
1592 (const item)
1593 (const table)
1594 (const default))
1595 (boolean)))))
1598 (defcustom org-insert-heading-respect-content nil
1599 "Non-nil means insert new headings after the current subtree.
1600 When nil, the new heading is created directly after the current line.
1601 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1602 this variable on for the duration of the command."
1603 :group 'org-structure
1604 :type 'boolean)
1606 (defcustom org-blank-before-new-entry '((heading . auto)
1607 (plain-list-item . auto))
1608 "Should `org-insert-heading' leave a blank line before new heading/item?
1609 The value is an alist, with `heading' and `plain-list-item' as CAR,
1610 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1611 which case Org will look at the surrounding headings/items and try to
1612 make an intelligent decision whether to insert a blank line or not."
1613 :group 'org-edit-structure
1614 :type '(list
1615 (cons (const heading)
1616 (choice (const :tag "Never" nil)
1617 (const :tag "Always" t)
1618 (const :tag "Auto" auto)))
1619 (cons (const plain-list-item)
1620 (choice (const :tag "Never" nil)
1621 (const :tag "Always" t)
1622 (const :tag "Auto" auto)))))
1624 (defcustom org-insert-heading-hook nil
1625 "Hook being run after inserting a new heading."
1626 :group 'org-edit-structure
1627 :type 'hook)
1629 (defcustom org-enable-fixed-width-editor t
1630 "Non-nil means lines starting with \":\" are treated as fixed-width.
1631 This currently only means they are never auto-wrapped.
1632 When nil, such lines will be treated like ordinary lines."
1633 :group 'org-edit-structure
1634 :type 'boolean)
1636 (defcustom org-goto-auto-isearch t
1637 "Non-nil means typing characters in `org-goto' starts incremental search.
1638 When nil, you can use these keybindings to navigate the buffer:
1640 q Quit the org-goto interface
1641 n Go to the next visible heading
1642 p Go to the previous visible heading
1643 f Go one heading forward on same level
1644 b Go one heading backward on same level
1645 u Go one heading up"
1646 :group 'org-edit-structure
1647 :type 'boolean)
1649 (defgroup org-sparse-trees nil
1650 "Options concerning sparse trees in Org-mode."
1651 :tag "Org Sparse Trees"
1652 :group 'org-structure)
1654 (defcustom org-highlight-sparse-tree-matches t
1655 "Non-nil means highlight all matches that define a sparse tree.
1656 The highlights will automatically disappear the next time the buffer is
1657 changed by an edit command."
1658 :group 'org-sparse-trees
1659 :type 'boolean)
1661 (defcustom org-remove-highlights-with-change t
1662 "Non-nil means any change to the buffer will remove temporary highlights.
1663 \\<org-mode-map>\
1664 Such highlights are created by `org-occur' and `org-clock-display'.
1665 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1666 to get rid of the highlights.
1667 The highlights created by `org-toggle-latex-fragment' always need
1668 `\\[org-toggle-latex-fragment]' to be removed."
1669 :group 'org-sparse-trees
1670 :group 'org-time
1671 :type 'boolean)
1673 (defcustom org-occur-case-fold-search t
1674 "Non-nil means `org-occur' should be case-insensitive.
1675 If set to `smart' the search will be case-insensitive only if it
1676 doesn't specify any upper case character."
1677 :group 'org-sparse-trees
1678 :version "25.1"
1679 :type '(choice
1680 (const :tag "Case-sensitive" nil)
1681 (const :tag "Case-insensitive" t)
1682 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1684 (defcustom org-occur-hook '(org-first-headline-recenter)
1685 "Hook that is run after `org-occur' has constructed a sparse tree.
1686 This can be used to recenter the window to show as much of the structure
1687 as possible."
1688 :group 'org-sparse-trees
1689 :type 'hook)
1691 (defgroup org-imenu-and-speedbar nil
1692 "Options concerning imenu and speedbar in Org-mode."
1693 :tag "Org Imenu and Speedbar"
1694 :group 'org-structure)
1696 (defcustom org-imenu-depth 2
1697 "The maximum level for Imenu access to Org headlines.
1698 This also applied for speedbar access."
1699 :group 'org-imenu-and-speedbar
1700 :type 'integer)
1702 (defgroup org-table nil
1703 "Options concerning tables in Org-mode."
1704 :tag "Org Table"
1705 :group 'org)
1707 (defcustom org-enable-table-editor 'optimized
1708 "Non-nil means lines starting with \"|\" are handled by the table editor.
1709 When nil, such lines will be treated like ordinary lines.
1711 When equal to the symbol `optimized', the table editor will be optimized to
1712 do the following:
1713 - Automatic overwrite mode in front of whitespace in table fields.
1714 This makes the structure of the table stay in tact as long as the edited
1715 field does not exceed the column width.
1716 - Minimize the number of realigns. Normally, the table is aligned each time
1717 TAB or RET are pressed to move to another field. With optimization this
1718 happens only if changes to a field might have changed the column width.
1719 Optimization requires replacing the functions `self-insert-command',
1720 `delete-char', and `backward-delete-char' in Org buffers, with a
1721 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1722 good at guessing when a re-align will be necessary, but you can always
1723 force one with \\[org-ctrl-c-ctrl-c].
1725 If you would like to use the optimized version in Org-mode, but the
1726 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1728 This variable can be used to turn on and off the table editor during a session,
1729 but in order to toggle optimization, a restart is required.
1731 See also the variable `org-table-auto-blank-field'."
1732 :group 'org-table
1733 :type '(choice
1734 (const :tag "off" nil)
1735 (const :tag "on" t)
1736 (const :tag "on, optimized" optimized)))
1738 (defcustom org-self-insert-cluster-for-undo nil
1739 "Non-nil means cluster self-insert commands for undo when possible.
1740 If this is set, then, like in the Emacs command loop, 20 consecutive
1741 characters will be undone together.
1742 This is configurable, because there is some impact on typing performance."
1743 :group 'org-table
1744 :type 'boolean)
1746 (defcustom org-table-tab-recognizes-table.el t
1747 "Non-nil means TAB will automatically notice a table.el table.
1748 When it sees such a table, it moves point into it and - if necessary -
1749 calls `table-recognize-table'."
1750 :group 'org-table-editing
1751 :type 'boolean)
1753 (defgroup org-link nil
1754 "Options concerning links in Org-mode."
1755 :tag "Org Link"
1756 :group 'org)
1758 (defvar-local org-link-abbrev-alist-local nil
1759 "Buffer-local version of `org-link-abbrev-alist', which see.
1760 The value of this is taken from the #+LINK lines.")
1762 (defcustom org-link-parameters
1763 '(("doi" :follow org--open-doi-link)
1764 ("elisp" :follow org--open-elisp-link)
1765 ("file" :complete org-file-complete-link)
1766 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1767 ("help" :follow org--open-help-link)
1768 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1769 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1770 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1771 ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
1772 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1773 ("shell" :follow org--open-shell-link))
1774 "An alist of properties that defines all the links in Org mode.
1775 The key in each association is a string of the link type.
1776 Subsequent optional elements make up a p-list of link properties.
1778 :follow - A function that takes the link path as an argument.
1780 :export - A function that takes the link path, description and
1781 export-backend as arguments.
1783 :store - A function responsible for storing the link. See the
1784 function `org-store-link-functions'.
1786 :complete - A function that inserts a link with completion. The
1787 function takes one optional prefix arg.
1789 :face - A face for the link, or a function that returns a face.
1790 The function takes one argument which is the link path. The
1791 default face is `org-link'.
1793 :mouse-face - The mouse-face. The default is `highlight'.
1795 :display - `full' will not fold the link in descriptive
1796 display. Default is `org-link'.
1798 :help-echo - A string or function that takes (window object position)
1799 as arguments and returns a string.
1801 :keymap - A keymap that is active on the link. The default is
1802 `org-mouse-map'.
1804 :htmlize-link - A function for the htmlize-link. Defaults
1805 to (list :uri \"type:path\")
1807 :activate-func - A function to run at the end of font-lock
1808 activation. The function must accept (link-start link-end path bracketp)
1809 as arguments."
1810 :group 'org-link
1811 :type '(alist :tag "Link display parameters"
1812 :value-type plist))
1814 (defun org-link-get-parameter (type key)
1815 "Get TYPE link property for KEY.
1816 TYPE is a string and KEY is a plist keyword."
1817 (plist-get
1818 (cdr (assoc type org-link-parameters))
1819 key))
1821 (defun org-link-set-parameters (type &rest parameters)
1822 "Set link TYPE properties to PARAMETERS.
1823 PARAMETERS should be :key val pairs."
1824 (let ((data (assoc type org-link-parameters)))
1825 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1826 (push (cons type parameters) org-link-parameters)
1827 (org-make-link-regexps)
1828 (org-element-update-syntax))))
1830 (defun org-link-types ()
1831 "Return a list of known link types."
1832 (mapcar #'car org-link-parameters))
1834 (defcustom org-link-abbrev-alist nil
1835 "Alist of link abbreviations.
1836 The car of each element is a string, to be replaced at the start of a link.
1837 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1838 links in Org buffers can have an optional tag after a double colon, e.g.,
1840 [[linkkey:tag][description]]
1842 The `linkkey' must be a word word, starting with a letter, followed
1843 by letters, numbers, `-' or `_'.
1845 If REPLACE is a string, the tag will simply be appended to create the link.
1846 If the string contains \"%s\", the tag will be inserted there. If the string
1847 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1848 at that point (see the function `url-hexify-string'). If the string contains
1849 the specifier \"%(my-function)\", then the custom function `my-function' will
1850 be invoked: this function takes the tag as its only argument and must return
1851 a string.
1853 REPLACE may also be a function that will be called with the tag as the
1854 only argument to create the link, which should be returned as a string.
1856 See the manual for examples."
1857 :group 'org-link
1858 :type '(repeat
1859 (cons
1860 (string :tag "Protocol")
1861 (choice
1862 (string :tag "Format")
1863 (function)))))
1865 (defcustom org-descriptive-links t
1866 "Non-nil means Org will display descriptive links.
1867 E.g. [[http://orgmode.org][Org website]] will be displayed as
1868 \"Org Website\", hiding the link itself and just displaying its
1869 description. When set to nil, Org will display the full links
1870 literally.
1872 You can interactively set the value of this variable by calling
1873 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1874 :group 'org-link
1875 :type 'boolean)
1877 (defcustom org-link-file-path-type 'adaptive
1878 "How the path name in file links should be stored.
1879 Valid values are:
1881 relative Relative to the current directory, i.e. the directory of the file
1882 into which the link is being inserted.
1883 absolute Absolute path, if possible with ~ for home directory.
1884 noabbrev Absolute path, no abbreviation of home directory.
1885 adaptive Use relative path for files in the current directory and sub-
1886 directories of it. For other files, use an absolute path."
1887 :group 'org-link
1888 :type '(choice
1889 (const relative)
1890 (const absolute)
1891 (const noabbrev)
1892 (const adaptive)))
1894 (defvaralias 'org-activate-links 'org-highlight-links)
1895 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1896 "Types of links that should be highlighted in Org files.
1898 This is a list of symbols, each one of them leading to the
1899 highlighting of a certain link type.
1901 You can still open links that are not highlighted.
1903 In principle, it does not hurt to turn on highlighting for all
1904 link types. There may be a small gain when turning off unused
1905 link types. The types are:
1907 bracket The recommended [[link][description]] or [[link]] links with hiding.
1908 angle Links in angular brackets that may contain whitespace like
1909 <bbdb:Carsten Dominik>.
1910 plain Plain links in normal text, no whitespace, like http://google.com.
1911 radio Text that is matched by a radio target, see manual for details.
1912 tag Tag settings in a headline (link to tag search).
1913 date Time stamps (link to calendar).
1914 footnote Footnote labels.
1916 If you set this variable during an Emacs session, use `org-mode-restart'
1917 in the Org buffer so that the change takes effect."
1918 :group 'org-link
1919 :group 'org-appearance
1920 :type '(set :greedy t
1921 (const :tag "Double bracket links" bracket)
1922 (const :tag "Angular bracket links" angle)
1923 (const :tag "Plain text links" plain)
1924 (const :tag "Radio target matches" radio)
1925 (const :tag "Tags" tag)
1926 (const :tag "Timestamps" date)
1927 (const :tag "Footnotes" footnote)))
1929 (defcustom org-make-link-description-function nil
1930 "Function to use for generating link descriptions from links.
1931 When nil, the link location will be used. This function must take
1932 two parameters: the first one is the link, the second one is the
1933 description generated by `org-insert-link'. The function should
1934 return the description to use."
1935 :group 'org-link
1936 :type '(choice (const nil) (function)))
1938 (defgroup org-link-store nil
1939 "Options concerning storing links in Org-mode."
1940 :tag "Org Store Link"
1941 :group 'org-link)
1943 (defcustom org-url-hexify-p t
1944 "When non-nil, hexify URL when creating a link."
1945 :type 'boolean
1946 :version "24.3"
1947 :group 'org-link-store)
1949 (defcustom org-email-link-description-format "Email %c: %.30s"
1950 "Format of the description part of a link to an email or usenet message.
1951 The following %-escapes will be replaced by corresponding information:
1953 %F full \"From\" field
1954 %f name, taken from \"From\" field, address if no name
1955 %T full \"To\" field
1956 %t first name in \"To\" field, address if no name
1957 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1958 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1959 %s subject
1960 %d date
1961 %m message-id.
1963 You may use normal field width specification between the % and the letter.
1964 This is for example useful to limit the length of the subject.
1966 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1967 :group 'org-link-store
1968 :type 'string)
1970 (defcustom org-from-is-user-regexp
1971 (let (r1 r2)
1972 (when (and user-mail-address (not (string= user-mail-address "")))
1973 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1974 (when (and user-full-name (not (string= user-full-name "")))
1975 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1976 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1977 "Regexp matched against the \"From:\" header of an email or usenet message.
1978 It should match if the message is from the user him/herself."
1979 :group 'org-link-store
1980 :type 'regexp)
1982 (defcustom org-context-in-file-links t
1983 "Non-nil means file links from `org-store-link' contain context.
1984 A search string will be added to the file name with :: as separator and
1985 used to find the context when the link is activated by the command
1986 `org-open-at-point'. When this option is t, the entire active region
1987 will be placed in the search string of the file link. If set to a
1988 positive integer, only the first n lines of context will be stored.
1990 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1991 negates this setting for the duration of the command."
1992 :group 'org-link-store
1993 :type '(choice boolean integer))
1995 (defcustom org-keep-stored-link-after-insertion nil
1996 "Non-nil means keep link in list for entire session.
1998 The command `org-store-link' adds a link pointing to the current
1999 location to an internal list. These links accumulate during a session.
2000 The command `org-insert-link' can be used to insert links into any
2001 Org file (offering completion for all stored links). When this option
2002 is nil, every link which has been inserted once using \\[org-insert-link]
2003 will be removed from the list, to make completing the unused links
2004 more efficient."
2005 :group 'org-link-store
2006 :type 'boolean)
2008 (defgroup org-link-follow nil
2009 "Options concerning following links in Org-mode."
2010 :tag "Org Follow Link"
2011 :group 'org-link)
2013 (defcustom org-link-translation-function nil
2014 "Function to translate links with different syntax to Org syntax.
2015 This can be used to translate links created for example by the Planner
2016 or emacs-wiki packages to Org syntax.
2017 The function must accept two parameters, a TYPE containing the link
2018 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2019 which is everything after the link protocol. It should return a cons
2020 with possibly modified values of type and path.
2021 Org contains a function for this, so if you set this variable to
2022 `org-translate-link-from-planner', you should be able follow many
2023 links created by planner."
2024 :group 'org-link-follow
2025 :type '(choice (const nil) (function)))
2027 (defcustom org-follow-link-hook nil
2028 "Hook that is run after a link has been followed."
2029 :group 'org-link-follow
2030 :type 'hook)
2032 (defcustom org-tab-follows-link nil
2033 "Non-nil means on links TAB will follow the link.
2034 Needs to be set before org.el is loaded.
2035 This really should not be used, it does not make sense, and the
2036 implementation is bad."
2037 :group 'org-link-follow
2038 :type 'boolean)
2040 (defcustom org-return-follows-link nil
2041 "Non-nil means on links RET will follow the link.
2042 In tables, the special behavior of RET has precedence."
2043 :group 'org-link-follow
2044 :type 'boolean)
2046 (defcustom org-mouse-1-follows-link
2047 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2048 "Non-nil means mouse-1 on a link will follow the link.
2049 A longer mouse click will still set point. Needs to be set
2050 before org.el is loaded."
2051 :group 'org-link-follow
2052 :version "24.4"
2053 :package-version '(Org . "8.3")
2054 :type '(choice
2055 (const :tag "A double click follows the link" double)
2056 (const :tag "Unconditionally follow the link with mouse-1" t)
2057 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2059 (defcustom org-mark-ring-length 4
2060 "Number of different positions to be recorded in the ring.
2061 Changing this requires a restart of Emacs to work correctly."
2062 :group 'org-link-follow
2063 :type 'integer)
2065 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2066 "Non-nil means internal links in Org files must exactly match a headline.
2067 When nil, the link search tries to match a phrase with all words
2068 in the search text."
2069 :group 'org-link-follow
2070 :version "24.1"
2071 :type '(choice
2072 (const :tag "Use fuzzy text search" nil)
2073 (const :tag "Match only exact headline" t)
2074 (const :tag "Match exact headline or query to create it"
2075 query-to-create)))
2077 (defcustom org-link-frame-setup
2078 '((vm . vm-visit-folder-other-frame)
2079 (vm-imap . vm-visit-imap-folder-other-frame)
2080 (gnus . org-gnus-no-new-news)
2081 (file . find-file-other-window)
2082 (wl . wl-other-frame))
2083 "Setup the frame configuration for following links.
2084 When following a link with Emacs, it may often be useful to display
2085 this link in another window or frame. This variable can be used to
2086 set this up for the different types of links.
2087 For VM, use any of
2088 `vm-visit-folder'
2089 `vm-visit-folder-other-window'
2090 `vm-visit-folder-other-frame'
2091 For Gnus, use any of
2092 `gnus'
2093 `gnus-other-frame'
2094 `org-gnus-no-new-news'
2095 For FILE, use any of
2096 `find-file'
2097 `find-file-other-window'
2098 `find-file-other-frame'
2099 For Wanderlust use any of
2100 `wl'
2101 `wl-other-frame'
2102 For the calendar, use the variable `calendar-setup'.
2103 For BBDB, it is currently only possible to display the matches in
2104 another window."
2105 :group 'org-link-follow
2106 :type '(list
2107 (cons (const vm)
2108 (choice
2109 (const vm-visit-folder)
2110 (const vm-visit-folder-other-window)
2111 (const vm-visit-folder-other-frame)))
2112 (cons (const vm-imap)
2113 (choice
2114 (const vm-visit-imap-folder)
2115 (const vm-visit-imap-folder-other-window)
2116 (const vm-visit-imap-folder-other-frame)))
2117 (cons (const gnus)
2118 (choice
2119 (const gnus)
2120 (const gnus-other-frame)
2121 (const org-gnus-no-new-news)))
2122 (cons (const file)
2123 (choice
2124 (const find-file)
2125 (const find-file-other-window)
2126 (const find-file-other-frame)))
2127 (cons (const wl)
2128 (choice
2129 (const wl)
2130 (const wl-other-frame)))))
2132 (defcustom org-display-internal-link-with-indirect-buffer nil
2133 "Non-nil means use indirect buffer to display infile links.
2134 Activating internal links (from one location in a file to another location
2135 in the same file) normally just jumps to the location. When the link is
2136 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2137 is displayed in
2138 another window. When this option is set, the other window actually displays
2139 an indirect buffer clone of the current buffer, to avoid any visibility
2140 changes to the current buffer."
2141 :group 'org-link-follow
2142 :type 'boolean)
2144 (defcustom org-open-non-existing-files nil
2145 "Non-nil means `org-open-file' will open non-existing files.
2146 When nil, an error will be generated.
2147 This variable applies only to external applications because they
2148 might choke on non-existing files. If the link is to a file that
2149 will be opened in Emacs, the variable is ignored."
2150 :group 'org-link-follow
2151 :type 'boolean)
2153 (defcustom org-open-directory-means-index-dot-org nil
2154 "Non-nil means a link to a directory really means to index.org.
2155 When nil, following a directory link will run dired or open a finder/explorer
2156 window on that directory."
2157 :group 'org-link-follow
2158 :type 'boolean)
2160 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2161 "Non-nil means ask for confirmation before executing shell links.
2162 Shell links can be dangerous: just think about a link
2164 [[shell:rm -rf ~/*][Google Search]]
2166 This link would show up in your Org document as \"Google Search\",
2167 but really it would remove your entire home directory.
2168 Therefore we advise against setting this variable to nil.
2169 Just change it to `y-or-n-p' if you want to confirm with a
2170 single keystroke rather than having to type \"yes\"."
2171 :group 'org-link-follow
2172 :type '(choice
2173 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2174 (const :tag "with y-or-n (faster)" y-or-n-p)
2175 (const :tag "no confirmation (dangerous)" nil)))
2176 (put 'org-confirm-shell-link-function
2177 'safe-local-variable
2178 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2180 (defcustom org-confirm-shell-link-not-regexp ""
2181 "A regexp to skip confirmation for shell links."
2182 :group 'org-link-follow
2183 :version "24.1"
2184 :type 'regexp)
2186 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2187 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2188 Elisp links can be dangerous: just think about a link
2190 [[elisp:(shell-command \"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-elisp-link-not-regexp ""
2207 "A regexp to skip confirmation for Elisp links."
2208 :group 'org-link-follow
2209 :version "24.1"
2210 :type 'regexp)
2212 (defconst org-file-apps-defaults-gnu
2213 '((remote . emacs)
2214 (system . mailcap)
2215 (t . mailcap))
2216 "Default file applications on a UNIX or GNU/Linux system.
2217 See `org-file-apps'.")
2219 (defconst org-file-apps-defaults-macosx
2220 '((remote . emacs)
2221 (system . "open %s")
2222 ("ps.gz" . "gv %s")
2223 ("eps.gz" . "gv %s")
2224 ("dvi" . "xdvi %s")
2225 ("fig" . "xfig %s")
2226 (t . "open %s"))
2227 "Default file applications on a MacOS X system.
2228 The system \"open\" is known as a default, but we use X11 applications
2229 for some files for which the OS does not have a good default.
2230 See `org-file-apps'.")
2232 (defconst org-file-apps-defaults-windowsnt
2233 (list '(remote . emacs)
2234 (cons 'system (lambda (file _path)
2235 (with-no-warnings (w32-shell-execute "open" file))))
2236 (cons t (lambda (file _path)
2237 (with-no-warnings (w32-shell-execute "open" file)))))
2238 "Default file applications on a Windows NT system.
2239 The system \"open\" is used for most files.
2240 See `org-file-apps'.")
2242 (defcustom org-file-apps
2243 '((auto-mode . emacs)
2244 ("\\.mm\\'" . default)
2245 ("\\.x?html?\\'" . default)
2246 ("\\.pdf\\'" . default))
2247 "External applications for opening `file:path' items in a document.
2248 \\<org-mode-map>\
2250 Org mode uses system defaults for different file types, but
2251 you can use this variable to set the application for a given file
2252 extension. The entries in this list are cons cells where the car identifies
2253 files and the cdr the corresponding command.
2255 Possible values for the file identifier are:
2257 \"string\" A string as a file identifier can be interpreted in different
2258 ways, depending on its contents:
2260 - Alphanumeric characters only:
2261 Match links with this file extension.
2262 Example: (\"pdf\" . \"evince %s\")
2263 to open PDFs with evince.
2265 - Regular expression: Match links where the
2266 filename matches the regexp. If you want to
2267 use groups here, use shy groups.
2269 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2270 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2271 to open *.html and *.xhtml with firefox.
2273 - Regular expression which contains (non-shy) groups:
2274 Match links where the whole link, including \"::\", and
2275 anything after that, matches the regexp.
2276 In a custom command string, %1, %2, etc. are replaced with
2277 the parts of the link that were matched by the groups.
2278 For backwards compatibility, if a command string is given
2279 that does not use any of the group matches, this case is
2280 handled identically to the second one (i.e. match against
2281 file name only).
2282 In a custom function, you can access the group matches with
2283 \(match-string n link).
2285 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2286 \"evince -p %1 %s\")
2287 to open [[file:document.pdf::5]] with evince at page 5.
2289 `directory' Matches a directory
2290 `remote' Matches a remote file, accessible through tramp or efs.
2291 Remote files most likely should be visited through Emacs
2292 because external applications cannot handle such paths.
2293 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2294 so all files Emacs knows how to handle. Using this with
2295 command `emacs' will open most files in Emacs. Beware that this
2296 will also open html files inside Emacs, unless you add
2297 \(\"html\" . default) to the list as well.
2298 `system' The system command to open files, like `open' on Windows
2299 and Mac OS X, and mailcap under GNU/Linux. This is the command
2300 that will be selected if you call \\[org-open-at-point] with a double
2301 \\[universal-argument] \\[universal-argument] prefix.
2302 t Default for files not matched by any of the other options.
2304 Possible values for the command are:
2306 `emacs' The file will be visited by the current Emacs process.
2307 `default' Use the default application for this file type, which is the
2308 association for t in the list, most likely in the system-specific
2309 part. This can be used to overrule an unwanted setting in the
2310 system-specific variable.
2311 `system' Use the system command for opening files, like \"open\".
2312 This command is specified by the entry whose car is `system'.
2313 Most likely, the system-specific version of this variable
2314 does define this command, but you can overrule/replace it
2315 here.
2316 `mailcap' Use command specified in the mailcaps.
2317 string A command to be executed by a shell; %s will be replaced
2318 by the path to the file.
2319 function A Lisp function, which will be called with two arguments:
2320 the file path and the original link string, without the
2321 \"file:\" prefix.
2323 For more examples, see the system specific constants
2324 `org-file-apps-defaults-macosx'
2325 `org-file-apps-defaults-windowsnt'
2326 `org-file-apps-defaults-gnu'."
2327 :group 'org-link-follow
2328 :type '(repeat
2329 (cons (choice :value ""
2330 (string :tag "Extension")
2331 (const :tag "System command to open files" system)
2332 (const :tag "Default for unrecognized files" t)
2333 (const :tag "Remote file" remote)
2334 (const :tag "Links to a directory" directory)
2335 (const :tag "Any files that have Emacs modes"
2336 auto-mode))
2337 (choice :value ""
2338 (const :tag "Visit with Emacs" emacs)
2339 (const :tag "Use default" default)
2340 (const :tag "Use the system command" system)
2341 (string :tag "Command")
2342 (function :tag "Function")))))
2344 (defcustom org-doi-server-url "http://dx.doi.org/"
2345 "The URL of the DOI server."
2346 :type 'string
2347 :version "24.3"
2348 :group 'org-link-follow)
2350 (defgroup org-refile nil
2351 "Options concerning refiling entries in Org-mode."
2352 :tag "Org Refile"
2353 :group 'org)
2355 (defcustom org-directory "~/org"
2356 "Directory with Org files.
2357 This is just a default location to look for Org files. There is no need
2358 at all to put your files into this directory. It is used in the
2359 following situations:
2361 1. When a capture template specifies a target file that is not an
2362 absolute path. The path will then be interpreted relative to
2363 `org-directory'
2364 2. When the value of variable `org-agenda-files' is a single file, any
2365 relative paths in this file will be taken as relative to
2366 `org-directory'."
2367 :group 'org-refile
2368 :group 'org-capture
2369 :type 'directory)
2371 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2372 "Default target for storing notes.
2373 Used as a fall back file for org-capture.el, for templates that
2374 do not specify a target file."
2375 :group 'org-refile
2376 :group 'org-capture
2377 :type 'file)
2379 (defcustom org-goto-interface 'outline
2380 "The default interface to be used for `org-goto'.
2381 Allowed values are:
2382 outline The interface shows an outline of the relevant file
2383 and the correct heading is found by moving through
2384 the outline or by searching with incremental search.
2385 outline-path-completion Headlines in the current buffer are offered via
2386 completion. This is the interface also used by
2387 the refile command."
2388 :group 'org-refile
2389 :type '(choice
2390 (const :tag "Outline" outline)
2391 (const :tag "Outline-path-completion" outline-path-completion)))
2393 (defcustom org-goto-max-level 5
2394 "Maximum target level when running `org-goto' with refile interface."
2395 :group 'org-refile
2396 :type 'integer)
2398 (defcustom org-reverse-note-order nil
2399 "Non-nil means store new notes at the beginning of a file or entry.
2400 When nil, new notes will be filed to the end of a file or entry.
2401 This can also be a list with cons cells of regular expressions that
2402 are matched against file names, and values."
2403 :group 'org-capture
2404 :group 'org-refile
2405 :type '(choice
2406 (const :tag "Reverse always" t)
2407 (const :tag "Reverse never" nil)
2408 (repeat :tag "By file name regexp"
2409 (cons regexp boolean))))
2411 (defcustom org-log-refile nil
2412 "Information to record when a task is refiled.
2414 Possible values are:
2416 nil Don't add anything
2417 time Add a time stamp to the task
2418 note Prompt for a note and add it with template `org-log-note-headings'
2420 This option can also be set with on a per-file-basis with
2422 #+STARTUP: nologrefile
2423 #+STARTUP: logrefile
2424 #+STARTUP: lognoterefile
2426 You can have local logging settings for a subtree by setting the LOGGING
2427 property to one or more of these keywords.
2429 When bulk-refiling from the agenda, the value `note' is forbidden and
2430 will temporarily be changed to `time'."
2431 :group 'org-refile
2432 :group 'org-progress
2433 :version "24.1"
2434 :type '(choice
2435 (const :tag "No logging" nil)
2436 (const :tag "Record timestamp" time)
2437 (const :tag "Record timestamp with note." note)))
2439 (defcustom org-refile-targets nil
2440 "Targets for refiling entries with \\[org-refile].
2441 This is a list of cons cells. Each cell contains:
2442 - a specification of the files to be considered, either a list of files,
2443 or a symbol whose function or variable value will be used to retrieve
2444 a file name or a list of file names. If you use `org-agenda-files' for
2445 that, all agenda files will be scanned for targets. Nil means consider
2446 headings in the current buffer.
2447 - A specification of how to find candidate refile targets. This may be
2448 any of:
2449 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2450 This tag has to be present in all target headlines, inheritance will
2451 not be considered.
2452 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2453 todo keyword.
2454 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2455 headlines that are refiling targets.
2456 - a cons cell (:level . N). Any headline of level N is considered a target.
2457 Note that, when `org-odd-levels-only' is set, level corresponds to
2458 order in hierarchy, not to the number of stars.
2459 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2460 Note that, when `org-odd-levels-only' is set, level corresponds to
2461 order in hierarchy, not to the number of stars.
2463 Each element of this list generates a set of possible targets.
2464 The union of these sets is presented (with completion) to
2465 the user by `org-refile'.
2467 You can set the variable `org-refile-target-verify-function' to a function
2468 to verify each headline found by the simple criteria above.
2470 When this variable is nil, all top-level headlines in the current buffer
2471 are used, equivalent to the value `((nil . (:level . 1))'."
2472 :group 'org-refile
2473 :type '(repeat
2474 (cons
2475 (choice :value org-agenda-files
2476 (const :tag "All agenda files" org-agenda-files)
2477 (const :tag "Current buffer" nil)
2478 (function) (variable) (file))
2479 (choice :tag "Identify target headline by"
2480 (cons :tag "Specific tag" (const :value :tag) (string))
2481 (cons :tag "TODO keyword" (const :value :todo) (string))
2482 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2483 (cons :tag "Level number" (const :value :level) (integer))
2484 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2486 (defcustom org-refile-target-verify-function nil
2487 "Function to verify if the headline at point should be a refile target.
2488 The function will be called without arguments, with point at the
2489 beginning of the headline. It should return t and leave point
2490 where it is if the headline is a valid target for refiling.
2492 If the target should not be selected, the function must return nil.
2493 In addition to this, it may move point to a place from where the search
2494 should be continued. For example, the function may decide that the entire
2495 subtree of the current entry should be excluded and move point to the end
2496 of the subtree."
2497 :group 'org-refile
2498 :type '(choice
2499 (const nil)
2500 (function)))
2502 (defcustom org-refile-use-cache nil
2503 "Non-nil means cache refile targets to speed up the process.
2504 \\<org-mode-map>\
2505 The cache for a particular file will be updated automatically when
2506 the buffer has been killed, or when any of the marker used for flagging
2507 refile targets no longer points at a live buffer.
2508 If you have added new entries to a buffer that might themselves be targets,
2509 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2510 if you find that easier, \
2511 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2512 \\[org-refile]'."
2513 :group 'org-refile
2514 :version "24.1"
2515 :type 'boolean)
2517 (defcustom org-refile-use-outline-path nil
2518 "Non-nil means provide refile targets as paths.
2519 So a level 3 headline will be available as level1/level2/level3.
2521 When the value is `file', also include the file name (without directory)
2522 into the path. In this case, you can also stop the completion after
2523 the file name, to get entries inserted as top level in the file.
2525 When `full-file-path', include the full file path."
2526 :group 'org-refile
2527 :type '(choice
2528 (const :tag "Not" nil)
2529 (const :tag "Yes" t)
2530 (const :tag "Start with file name" file)
2531 (const :tag "Start with full file path" full-file-path)))
2533 (defcustom org-outline-path-complete-in-steps t
2534 "Non-nil means complete the outline path in hierarchical steps.
2535 When Org uses the refile interface to select an outline path (see
2536 `org-refile-use-outline-path'), the completion of the path can be
2537 done in a single go, or it can be done in steps down the headline
2538 hierarchy. Going in steps is probably the best if you do not use
2539 a special completion package like `ido' or `icicles'. However,
2540 when using these packages, going in one step can be very fast,
2541 while still showing the whole path to the entry."
2542 :group 'org-refile
2543 :type 'boolean)
2545 (defcustom org-refile-allow-creating-parent-nodes nil
2546 "Non-nil means allow the creation of new nodes as refile targets.
2547 New nodes are then created by adding \"/new node name\" to the completion
2548 of an existing node. When the value of this variable is `confirm',
2549 new node creation must be confirmed by the user (recommended).
2550 When nil, the completion must match an existing entry.
2552 Note that, if the new heading is not seen by the criteria
2553 listed in `org-refile-targets', multiple instances of the same
2554 heading would be created by trying again to file under the new
2555 heading."
2556 :group 'org-refile
2557 :type '(choice
2558 (const :tag "Never" nil)
2559 (const :tag "Always" t)
2560 (const :tag "Prompt for confirmation" confirm)))
2562 (defcustom org-refile-active-region-within-subtree nil
2563 "Non-nil means also refile active region within a subtree.
2565 By default `org-refile' doesn't allow refiling regions if they
2566 don't contain a set of subtrees, but it might be convenient to
2567 do so sometimes: in that case, the first line of the region is
2568 converted to a headline before refiling."
2569 :group 'org-refile
2570 :version "24.1"
2571 :type 'boolean)
2573 (defgroup org-todo nil
2574 "Options concerning TODO items in Org-mode."
2575 :tag "Org TODO"
2576 :group 'org)
2578 (defgroup org-progress nil
2579 "Options concerning Progress logging in Org-mode."
2580 :tag "Org Progress"
2581 :group 'org-time)
2583 (defvar org-todo-interpretation-widgets
2584 '((:tag "Sequence (cycling hits every state)" sequence)
2585 (:tag "Type (cycling directly to DONE)" type))
2586 "The available interpretation symbols for customizing `org-todo-keywords'.
2587 Interested libraries should add to this list.")
2589 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2590 "List of TODO entry keyword sequences and their interpretation.
2591 \\<org-mode-map>This is a list of sequences.
2593 Each sequence starts with a symbol, either `sequence' or `type',
2594 indicating if the keywords should be interpreted as a sequence of
2595 action steps, or as different types of TODO items. The first
2596 keywords are states requiring action - these states will select a headline
2597 for inclusion into the global TODO list Org produces. If one of the
2598 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2599 signify that no further action is necessary. If \"|\" is not found,
2600 the last keyword is treated as the only DONE state of the sequence.
2602 The command \\[org-todo] cycles an entry through these states, and one
2603 additional state where no keyword is present. For details about this
2604 cycling, see the manual.
2606 TODO keywords and interpretation can also be set on a per-file basis with
2607 the special #+SEQ_TODO and #+TYP_TODO lines.
2609 Each keyword can optionally specify a character for fast state selection
2610 \(in combination with the variable `org-use-fast-todo-selection')
2611 and specifiers for state change logging, using the same syntax that
2612 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2613 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2614 indicates to record a time stamp each time this state is selected.
2616 Each keyword may also specify if a timestamp or a note should be
2617 recorded when entering or leaving the state, by adding additional
2618 characters in the parenthesis after the keyword. This looks like this:
2619 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2620 record only the time of the state change. With X and Y being either
2621 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2622 Y when leaving the state if and only if the *target* state does not
2623 define X. You may omit any of the fast-selection key or X or /Y,
2624 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2626 For backward compatibility, this variable may also be just a list
2627 of keywords. In this case the interpretation (sequence or type) will be
2628 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2629 :group 'org-todo
2630 :group 'org-keywords
2631 :type '(choice
2632 (repeat :tag "Old syntax, just keywords"
2633 (string :tag "Keyword"))
2634 (repeat :tag "New syntax"
2635 (cons
2636 (choice
2637 :tag "Interpretation"
2638 ;;Quick and dirty way to see
2639 ;;`org-todo-interpretations'. This takes the
2640 ;;place of item arguments
2641 :convert-widget
2642 (lambda (widget)
2643 (widget-put widget
2644 :args (mapcar
2645 (lambda (x)
2646 (widget-convert
2647 (cons 'const x)))
2648 org-todo-interpretation-widgets))
2649 widget))
2650 (repeat
2651 (string :tag "Keyword"))))))
2653 (defvar-local org-todo-keywords-1 nil
2654 "All TODO and DONE keywords active in a buffer.")
2655 (defvar org-todo-keywords-for-agenda nil)
2656 (defvar org-done-keywords-for-agenda nil)
2657 (defvar org-todo-keyword-alist-for-agenda nil)
2658 (defvar org-tag-alist-for-agenda nil
2659 "Alist of all tags from all agenda files.")
2660 (defvar org-tag-groups-alist-for-agenda nil
2661 "Alist of all groups tags from all current agenda files.")
2662 (defvar-local org-tag-groups-alist nil)
2663 (defvar org-agenda-contributing-files nil)
2664 (defvar-local org-current-tag-alist nil
2665 "Alist of all tag groups in current buffer.
2666 This variable takes into consideration `org-tag-alist',
2667 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2668 (defvar-local org-not-done-keywords nil)
2669 (defvar-local org-done-keywords nil)
2670 (defvar-local org-todo-heads nil)
2671 (defvar-local org-todo-sets nil)
2672 (defvar-local org-todo-log-states nil)
2673 (defvar-local org-todo-kwd-alist nil)
2674 (defvar-local org-todo-key-alist nil)
2675 (defvar-local org-todo-key-trigger nil)
2677 (defcustom org-todo-interpretation 'sequence
2678 "Controls how TODO keywords are interpreted.
2679 This variable is in principle obsolete and is only used for
2680 backward compatibility, if the interpretation of todo keywords is
2681 not given already in `org-todo-keywords'. See that variable for
2682 more information."
2683 :group 'org-todo
2684 :group 'org-keywords
2685 :type '(choice (const sequence)
2686 (const type)))
2688 (defcustom org-use-fast-todo-selection t
2689 "\\<org-mode-map>\
2690 Non-nil means use the fast todo selection scheme with \\[org-todo].
2691 This variable describes if and under what circumstances the cycling
2692 mechanism for TODO keywords will be replaced by a single-key, direct
2693 selection scheme.
2695 When nil, fast selection is never used.
2697 When the symbol `prefix', it will be used when `org-todo' is called
2698 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2699 in an Org buffer, and
2700 `\\[universal-argument] t' in an agenda buffer.
2702 When t, fast selection is used by default. In this case, the prefix
2703 argument forces cycling instead.
2705 In all cases, the special interface is only used if access keys have
2706 actually been assigned by the user, i.e. if keywords in the configuration
2707 are followed by a letter in parenthesis, like TODO(t)."
2708 :group 'org-todo
2709 :type '(choice
2710 (const :tag "Never" nil)
2711 (const :tag "By default" t)
2712 (const :tag "Only with C-u C-c C-t" prefix)))
2714 (defcustom org-provide-todo-statistics t
2715 "Non-nil means update todo statistics after insert and toggle.
2716 ALL-HEADLINES means update todo statistics by including headlines
2717 with no TODO keyword as well, counting them as not done.
2718 A list of TODO keywords means the same, but skip keywords that are
2719 not in this list.
2720 When set to a list of two lists, the first list contains keywords
2721 to consider as TODO keywords, the second list contains keywords
2722 to consider as DONE keywords.
2724 When this is set, todo statistics is updated in the parent of the
2725 current entry each time a todo state is changed."
2726 :group 'org-todo
2727 :type '(choice
2728 (const :tag "Yes, only for TODO entries" t)
2729 (const :tag "Yes, including all entries" all-headlines)
2730 (repeat :tag "Yes, for TODOs in this list"
2731 (string :tag "TODO keyword"))
2732 (list :tag "Yes, for TODOs and DONEs in these lists"
2733 (repeat (string :tag "TODO keyword"))
2734 (repeat (string :tag "DONE keyword")))
2735 (other :tag "No TODO statistics" nil)))
2737 (defcustom org-hierarchical-todo-statistics t
2738 "Non-nil means TODO statistics covers just direct children.
2739 When nil, all entries in the subtree are considered.
2740 This has only an effect if `org-provide-todo-statistics' is set.
2741 To set this to nil for only a single subtree, use a COOKIE_DATA
2742 property and include the word \"recursive\" into the value."
2743 :group 'org-todo
2744 :type 'boolean)
2746 (defcustom org-after-todo-state-change-hook nil
2747 "Hook which is run after the state of a TODO item was changed.
2748 The new state (a string with a TODO keyword, or nil) is available in the
2749 Lisp variable `org-state'."
2750 :group 'org-todo
2751 :type 'hook)
2753 (defvar org-blocker-hook nil
2754 "Hook for functions that are allowed to block a state change.
2756 Functions in this hook should not modify the buffer.
2757 Each function gets as its single argument a property list,
2758 see `org-trigger-hook' for more information about this list.
2760 If any of the functions in this hook returns nil, the state change
2761 is blocked.")
2763 (defvar org-trigger-hook nil
2764 "Hook for functions that are triggered by a state change.
2766 Each function gets as its single argument a property list with at
2767 least the following elements:
2769 (:type type-of-change :position pos-at-entry-start
2770 :from old-state :to new-state)
2772 Depending on the type, more properties may be present.
2774 This mechanism is currently implemented for:
2776 TODO state changes
2777 ------------------
2778 :type todo-state-change
2779 :from previous state (keyword as a string), or nil, or a symbol
2780 `todo' or `done', to indicate the general type of state.
2781 :to new state, like in :from")
2783 (defcustom org-enforce-todo-dependencies nil
2784 "Non-nil means undone TODO entries will block switching the parent to DONE.
2785 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2786 be blocked if any prior sibling is not yet done.
2787 Finally, if the parent is blocked because of ordered siblings of its own,
2788 the child will also be blocked."
2789 :set (lambda (var val)
2790 (set var val)
2791 (if val
2792 (add-hook 'org-blocker-hook
2793 'org-block-todo-from-children-or-siblings-or-parent)
2794 (remove-hook 'org-blocker-hook
2795 'org-block-todo-from-children-or-siblings-or-parent)))
2796 :group 'org-todo
2797 :type 'boolean)
2799 (defcustom org-enforce-todo-checkbox-dependencies nil
2800 "Non-nil means unchecked boxes will block switching the parent to DONE.
2801 When this is nil, checkboxes have no influence on switching TODO states.
2802 When non-nil, you first need to check off all check boxes before the TODO
2803 entry can be switched to DONE.
2804 This variable needs to be set before org.el is loaded, and you need to
2805 restart Emacs after a change to make the change effective. The only way
2806 to change is while Emacs is running is through the customize interface."
2807 :set (lambda (var val)
2808 (set var val)
2809 (if val
2810 (add-hook 'org-blocker-hook
2811 'org-block-todo-from-checkboxes)
2812 (remove-hook 'org-blocker-hook
2813 'org-block-todo-from-checkboxes)))
2814 :group 'org-todo
2815 :type 'boolean)
2817 (defcustom org-treat-insert-todo-heading-as-state-change nil
2818 "Non-nil means inserting a TODO heading is treated as state change.
2819 So when the command \\[org-insert-todo-heading] is used, state change
2820 logging will apply if appropriate. When nil, the new TODO item will
2821 be inserted directly, and no logging will take place."
2822 :group 'org-todo
2823 :type 'boolean)
2825 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2826 "Non-nil means switching TODO states with S-cursor counts as state change.
2827 This is the default behavior. However, setting this to nil allows a
2828 convenient way to select a TODO state and bypass any logging associated
2829 with that."
2830 :group 'org-todo
2831 :type 'boolean)
2833 (defcustom org-todo-state-tags-triggers nil
2834 "Tag changes that should be triggered by TODO state changes.
2835 This is a list. Each entry is
2837 (state-change (tag . flag) .......)
2839 State-change can be a string with a state, and empty string to indicate the
2840 state that has no TODO keyword, or it can be one of the symbols `todo'
2841 or `done', meaning any not-done or done state, respectively."
2842 :group 'org-todo
2843 :group 'org-tags
2844 :type '(repeat
2845 (cons (choice :tag "When changing to"
2846 (const :tag "Not-done state" todo)
2847 (const :tag "Done state" done)
2848 (string :tag "State"))
2849 (repeat
2850 (cons :tag "Tag action"
2851 (string :tag "Tag")
2852 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2854 (defcustom org-log-done nil
2855 "Information to record when a task moves to the DONE state.
2857 Possible values are:
2859 nil Don't add anything, just change the keyword
2860 time Add a time stamp to the task
2861 note Prompt for a note and add it with template `org-log-note-headings'
2863 This option can also be set with on a per-file-basis with
2865 #+STARTUP: nologdone
2866 #+STARTUP: logdone
2867 #+STARTUP: lognotedone
2869 You can have local logging settings for a subtree by setting the LOGGING
2870 property to one or more of these keywords."
2871 :group 'org-todo
2872 :group 'org-progress
2873 :type '(choice
2874 (const :tag "No logging" nil)
2875 (const :tag "Record CLOSED timestamp" time)
2876 (const :tag "Record CLOSED timestamp with note." note)))
2878 ;; Normalize old uses of org-log-done.
2879 (cond
2880 ((eq org-log-done t) (setq org-log-done 'time))
2881 ((and (listp org-log-done) (memq 'done org-log-done))
2882 (setq org-log-done 'note)))
2884 (defcustom org-log-reschedule nil
2885 "Information to record when the scheduling date of a tasks is modified.
2887 Possible values are:
2889 nil Don't add anything, just change the date
2890 time Add a time stamp to the task
2891 note Prompt for a note and add it with template `org-log-note-headings'
2893 This option can also be set with on a per-file-basis with
2895 #+STARTUP: nologreschedule
2896 #+STARTUP: logreschedule
2897 #+STARTUP: lognotereschedule"
2898 :group 'org-todo
2899 :group 'org-progress
2900 :type '(choice
2901 (const :tag "No logging" nil)
2902 (const :tag "Record timestamp" time)
2903 (const :tag "Record timestamp with note." note)))
2905 (defcustom org-log-redeadline nil
2906 "Information to record when the deadline date of a tasks is modified.
2908 Possible values are:
2910 nil Don't add anything, just change the date
2911 time Add a time stamp to the task
2912 note Prompt for a note and add it with template `org-log-note-headings'
2914 This option can also be set with on a per-file-basis with
2916 #+STARTUP: nologredeadline
2917 #+STARTUP: logredeadline
2918 #+STARTUP: lognoteredeadline
2920 You can have local logging settings for a subtree by setting the LOGGING
2921 property to one or more of these keywords."
2922 :group 'org-todo
2923 :group 'org-progress
2924 :type '(choice
2925 (const :tag "No logging" nil)
2926 (const :tag "Record timestamp" time)
2927 (const :tag "Record timestamp with note." note)))
2929 (defcustom org-log-note-clock-out nil
2930 "Non-nil means record a note when clocking out of an item.
2931 This can also be configured on a per-file basis by adding one of
2932 the following lines anywhere in the buffer:
2934 #+STARTUP: lognoteclock-out
2935 #+STARTUP: nolognoteclock-out"
2936 :group 'org-todo
2937 :group 'org-progress
2938 :type 'boolean)
2940 (defcustom org-log-done-with-time t
2941 "Non-nil means the CLOSED time stamp will contain date and time.
2942 When nil, only the date will be recorded."
2943 :group 'org-progress
2944 :type 'boolean)
2946 (defcustom org-log-note-headings
2947 '((done . "CLOSING NOTE %t")
2948 (state . "State %-12s from %-12S %t")
2949 (note . "Note taken on %t")
2950 (reschedule . "Rescheduled from %S on %t")
2951 (delschedule . "Not scheduled, was %S on %t")
2952 (redeadline . "New deadline from %S on %t")
2953 (deldeadline . "Removed deadline, was %S on %t")
2954 (refile . "Refiled on %t")
2955 (clock-out . ""))
2956 "Headings for notes added to entries.
2958 The value is an alist, with the car being a symbol indicating the
2959 note context, and the cdr is the heading to be used. The heading
2960 may also be the empty string. The following placeholders can be
2961 used:
2963 %t a time stamp.
2964 %T an active time stamp instead the default inactive one
2965 %d a short-format time stamp.
2966 %D an active short-format time stamp.
2967 %s the new TODO state or time stamp (inactive), in double quotes.
2968 %S the old TODO state or time stamp (inactive), in double quotes.
2969 %u the user name.
2970 %U full user name.
2972 In fact, it is not a good idea to change the `state' entry,
2973 because Agenda Log mode depends on the format of these entries."
2974 :group 'org-todo
2975 :group 'org-progress
2976 :type '(list :greedy t
2977 (cons (const :tag "Heading when closing an item" done) string)
2978 (cons (const :tag
2979 "Heading when changing todo state (todo sequence only)"
2980 state) string)
2981 (cons (const :tag "Heading when just taking a note" note) string)
2982 (cons (const :tag "Heading when rescheduling" reschedule) string)
2983 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2984 (cons (const :tag "Heading when changing deadline" redeadline) string)
2985 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2986 (cons (const :tag "Heading when refiling" refile) string)
2987 (cons (const :tag "Heading when clocking out" clock-out) string)))
2989 (unless (assq 'note org-log-note-headings)
2990 (push '(note . "%t") org-log-note-headings))
2992 (defcustom org-log-into-drawer nil
2993 "Non-nil means insert state change notes and time stamps into a drawer.
2994 When nil, state changes notes will be inserted after the headline and
2995 any scheduling and clock lines, but not inside a drawer.
2997 The value of this variable should be the name of the drawer to use.
2998 LOGBOOK is proposed as the default drawer for this purpose, you can
2999 also set this to a string to define the drawer of your choice.
3001 A value of t is also allowed, representing \"LOGBOOK\".
3003 A value of t or nil can also be set with on a per-file-basis with
3005 #+STARTUP: logdrawer
3006 #+STARTUP: nologdrawer
3008 If this variable is set, `org-log-state-notes-insert-after-drawers'
3009 will be ignored.
3011 You can set the property LOG_INTO_DRAWER to overrule this setting for
3012 a subtree.
3014 Do not check directly this variable in a Lisp program. Call
3015 function `org-log-into-drawer' instead."
3016 :group 'org-todo
3017 :group 'org-progress
3018 :type '(choice
3019 (const :tag "Not into a drawer" nil)
3020 (const :tag "LOGBOOK" t)
3021 (string :tag "Other")))
3023 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3025 (defun org-log-into-drawer ()
3026 "Name of the log drawer, as a string, or nil.
3027 This is the value of `org-log-into-drawer'. However, if the
3028 current entry has or inherits a LOG_INTO_DRAWER property, it will
3029 be used instead of the default value."
3030 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3031 (cond ((equal p "nil") nil)
3032 ((equal p "t") "LOGBOOK")
3033 ((stringp p) p)
3034 (p "LOGBOOK")
3035 ((stringp org-log-into-drawer) org-log-into-drawer)
3036 (org-log-into-drawer "LOGBOOK"))))
3038 (defcustom org-log-state-notes-insert-after-drawers nil
3039 "Non-nil means insert state change notes after any drawers in entry.
3040 Only the drawers that *immediately* follow the headline and the
3041 deadline/scheduled line are skipped.
3042 When nil, insert notes right after the heading and perhaps the line
3043 with deadline/scheduling if present.
3045 This variable will have no effect if `org-log-into-drawer' is
3046 set."
3047 :group 'org-todo
3048 :group 'org-progress
3049 :type 'boolean)
3051 (defcustom org-log-states-order-reversed t
3052 "Non-nil means the latest state note will be directly after heading.
3053 When nil, the state change notes will be ordered according to time.
3055 This option can also be set with on a per-file-basis with
3057 #+STARTUP: logstatesreversed
3058 #+STARTUP: nologstatesreversed"
3059 :group 'org-todo
3060 :group 'org-progress
3061 :type 'boolean)
3063 (defcustom org-todo-repeat-to-state nil
3064 "The TODO state to which a repeater should return the repeating task.
3065 By default this is the first task in a TODO sequence, or the previous state
3066 in a TODO_TYP set. But you can specify another task here.
3067 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3068 :group 'org-todo
3069 :version "24.1"
3070 :type '(choice (const :tag "Head of sequence" nil)
3071 (string :tag "Specific state")))
3073 (defcustom org-log-repeat 'time
3074 "Non-nil means record moving through the DONE state when triggering repeat.
3075 An auto-repeating task is immediately switched back to TODO when
3076 marked DONE. If you are not logging state changes (by adding \"@\"
3077 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3078 record a closing note, there will be no record of the task moving
3079 through DONE. This variable forces taking a note anyway.
3081 nil Don't force a record
3082 time Record a time stamp
3083 note Prompt for a note and add it with template `org-log-note-headings'
3085 This option can also be set with on a per-file-basis with
3087 #+STARTUP: nologrepeat
3088 #+STARTUP: logrepeat
3089 #+STARTUP: lognoterepeat
3091 You can have local logging settings for a subtree by setting the LOGGING
3092 property to one or more of these keywords."
3093 :group 'org-todo
3094 :group 'org-progress
3095 :type '(choice
3096 (const :tag "Don't force a record" nil)
3097 (const :tag "Force recording the DONE state" time)
3098 (const :tag "Force recording a note with the DONE state" note)))
3101 (defgroup org-priorities nil
3102 "Priorities in Org-mode."
3103 :tag "Org Priorities"
3104 :group 'org-todo)
3106 (defcustom org-enable-priority-commands t
3107 "Non-nil means priority commands are active.
3108 When nil, these commands will be disabled, so that you never accidentally
3109 set a priority."
3110 :group 'org-priorities
3111 :type 'boolean)
3113 (defcustom org-highest-priority ?A
3114 "The highest priority of TODO items. A character like ?A, ?B etc.
3115 Must have a smaller ASCII number than `org-lowest-priority'."
3116 :group 'org-priorities
3117 :type 'character)
3119 (defcustom org-lowest-priority ?C
3120 "The lowest priority of TODO items. A character like ?A, ?B etc.
3121 Must have a larger ASCII number than `org-highest-priority'."
3122 :group 'org-priorities
3123 :type 'character)
3125 (defcustom org-default-priority ?B
3126 "The default priority of TODO items.
3127 This is the priority an item gets if no explicit priority is given.
3128 When starting to cycle on an empty priority the first step in the cycle
3129 depends on `org-priority-start-cycle-with-default'. The resulting first
3130 step priority must not exceed the range from `org-highest-priority' to
3131 `org-lowest-priority' which means that `org-default-priority' has to be
3132 in this range exclusive or inclusive the range boundaries. Else the
3133 first step refuses to set the default and the second will fall back
3134 to (depending on the command used) the highest or lowest priority."
3135 :group 'org-priorities
3136 :type 'character)
3138 (defcustom org-priority-start-cycle-with-default t
3139 "Non-nil means start with default priority when starting to cycle.
3140 When this is nil, the first step in the cycle will be (depending on the
3141 command used) one higher or lower than the default priority.
3142 See also `org-default-priority'."
3143 :group 'org-priorities
3144 :type 'boolean)
3146 (defcustom org-get-priority-function nil
3147 "Function to extract the priority from a string.
3148 The string is normally the headline. If this is nil Org computes the
3149 priority from the priority cookie like [#A] in the headline. It returns
3150 an integer, increasing by 1000 for each priority level.
3151 The user can set a different function here, which should take a string
3152 as an argument and return the numeric priority."
3153 :group 'org-priorities
3154 :version "24.1"
3155 :type '(choice
3156 (const nil)
3157 (function)))
3159 (defgroup org-time nil
3160 "Options concerning time stamps and deadlines in Org-mode."
3161 :tag "Org Time"
3162 :group 'org)
3164 (defcustom org-time-stamp-rounding-minutes '(0 5)
3165 "Number of minutes to round time stamps to.
3166 \\<org-mode-map>\
3167 These are two values, the first applies when first creating a time stamp.
3168 The second applies when changing it with the commands `S-up' and `S-down'.
3169 When changing the time stamp, this means that it will change in steps
3170 of N minutes, as given by the second value.
3172 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3173 numbers should be factors of 60, so for example 5, 10, 15.
3175 When this is larger than 1, you can still force an exact time stamp by using
3176 a double prefix argument to a time stamp command like \
3177 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3178 and by using a prefix arg to `S-up/down' to specify the exact number
3179 of minutes to shift."
3180 :group 'org-time
3181 :get (lambda (var) ; Make sure both elements are there
3182 (if (integerp (default-value var))
3183 (list (default-value var) 5)
3184 (default-value var)))
3185 :type '(list
3186 (integer :tag "when inserting times")
3187 (integer :tag "when modifying times")))
3189 ;; Normalize old customizations of this variable.
3190 (when (integerp org-time-stamp-rounding-minutes)
3191 (setq org-time-stamp-rounding-minutes
3192 (list org-time-stamp-rounding-minutes
3193 org-time-stamp-rounding-minutes)))
3195 (defcustom org-display-custom-times nil
3196 "Non-nil means overlay custom formats over all time stamps.
3197 The formats are defined through the variable `org-time-stamp-custom-formats'.
3198 To turn this on on a per-file basis, insert anywhere in the file:
3199 #+STARTUP: customtime"
3200 :group 'org-time
3201 :set 'set-default
3202 :type 'sexp)
3203 (make-variable-buffer-local 'org-display-custom-times)
3205 (defcustom org-time-stamp-custom-formats
3206 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3207 "Custom formats for time stamps. See `format-time-string' for the syntax.
3208 These are overlaid over the default ISO format if the variable
3209 `org-display-custom-times' is set. Time like %H:%M should be at the
3210 end of the second format. The custom formats are also honored by export
3211 commands, if custom time display is turned on at the time of export."
3212 :group 'org-time
3213 :type 'sexp)
3215 (defun org-time-stamp-format (&optional long inactive)
3216 "Get the right format for a time string."
3217 (let ((f (if long (cdr org-time-stamp-formats)
3218 (car org-time-stamp-formats))))
3219 (if inactive
3220 (concat "[" (substring f 1 -1) "]")
3221 f)))
3223 (defcustom org-time-clocksum-format
3224 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3225 "The format string used when creating CLOCKSUM lines.
3226 This is also used when Org mode generates a time duration.
3228 The value can be a single format string containing two
3229 %-sequences, which will be filled with the number of hours and
3230 minutes in that order.
3232 Alternatively, the value can be a plist associating any of the
3233 keys :years, :months, :weeks, :days, :hours or :minutes with
3234 format strings. The time duration is formatted using only the
3235 time components that are needed and concatenating the results.
3236 If a time unit in absent, it falls back to the next smallest
3237 unit.
3239 The keys :require-years, :require-months, :require-days,
3240 :require-weeks, :require-hours, :require-minutes are also
3241 meaningful. A non-nil value for these keys indicates that the
3242 corresponding time component should always be included, even if
3243 its value is 0.
3246 For example,
3248 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3249 :require-minutes t)
3251 means durations longer than a day will be expressed in days,
3252 hours and minutes, and durations less than a day will always be
3253 expressed in hours and minutes (even for durations less than an
3254 hour).
3256 The value
3258 (:days \"%dd\" :minutes \"%dm\")
3260 means durations longer than a day will be expressed in days and
3261 minutes, and durations less than a day will be expressed entirely
3262 in minutes (even for durations longer than an hour)."
3263 :group 'org-time
3264 :group 'org-clock
3265 :version "24.4"
3266 :package-version '(Org . "8.0")
3267 :type '(choice (string :tag "Format string")
3268 (set :tag "Plist"
3269 (group :inline t (const :tag "Years" :years)
3270 (string :tag "Format string"))
3271 (group :inline t
3272 (const :tag "Always show years" :require-years)
3273 (const t))
3274 (group :inline t (const :tag "Months" :months)
3275 (string :tag "Format string"))
3276 (group :inline t
3277 (const :tag "Always show months" :require-months)
3278 (const t))
3279 (group :inline t (const :tag "Weeks" :weeks)
3280 (string :tag "Format string"))
3281 (group :inline t
3282 (const :tag "Always show weeks" :require-weeks)
3283 (const t))
3284 (group :inline t (const :tag "Days" :days)
3285 (string :tag "Format string"))
3286 (group :inline t
3287 (const :tag "Always show days" :require-days)
3288 (const t))
3289 (group :inline t (const :tag "Hours" :hours)
3290 (string :tag "Format string"))
3291 (group :inline t
3292 (const :tag "Always show hours" :require-hours)
3293 (const t))
3294 (group :inline t (const :tag "Minutes" :minutes)
3295 (string :tag "Format string"))
3296 (group :inline t
3297 (const :tag "Always show minutes" :require-minutes)
3298 (const t)))))
3300 (defcustom org-time-clocksum-use-fractional nil
3301 "When non-nil, \\[org-clock-display] uses fractional times.
3302 See `org-time-clocksum-format' for more on time clock formats."
3303 :group 'org-time
3304 :group 'org-clock
3305 :version "24.3"
3306 :type 'boolean)
3308 (defcustom org-time-clocksum-use-effort-durations nil
3309 "When non-nil, \\[org-clock-display] uses effort durations.
3310 E.g. by default, one day is considered to be a 8 hours effort,
3311 so a task that has been clocked for 16 hours will be displayed
3312 as during 2 days in the clock display or in the clocktable.
3314 See `org-effort-durations' on how to set effort durations
3315 and `org-time-clocksum-format' for more on time clock formats."
3316 :group 'org-time
3317 :group 'org-clock
3318 :version "24.4"
3319 :package-version '(Org . "8.0")
3320 :type 'boolean)
3322 (defcustom org-time-clocksum-fractional-format "%.2f"
3323 "The format string used when creating CLOCKSUM lines,
3324 or when Org mode generates a time duration, if
3325 `org-time-clocksum-use-fractional' is enabled.
3327 The value can be a single format string containing one
3328 %-sequence, which will be filled with the number of hours as
3329 a float.
3331 Alternatively, the value can be a plist associating any of the
3332 keys :years, :months, :weeks, :days, :hours or :minutes with
3333 a format string. The time duration is formatted using the
3334 largest time unit which gives a non-zero integer part. If all
3335 specified formats have zero integer part, the smallest time unit
3336 is used."
3337 :group 'org-time
3338 :type '(choice (string :tag "Format string")
3339 (set (group :inline t (const :tag "Years" :years)
3340 (string :tag "Format string"))
3341 (group :inline t (const :tag "Months" :months)
3342 (string :tag "Format string"))
3343 (group :inline t (const :tag "Weeks" :weeks)
3344 (string :tag "Format string"))
3345 (group :inline t (const :tag "Days" :days)
3346 (string :tag "Format string"))
3347 (group :inline t (const :tag "Hours" :hours)
3348 (string :tag "Format string"))
3349 (group :inline t (const :tag "Minutes" :minutes)
3350 (string :tag "Format string")))))
3352 (defcustom org-deadline-warning-days 14
3353 "Number of days before expiration during which a deadline becomes active.
3354 This variable governs the display in sparse trees and in the agenda.
3355 When 0 or negative, it means use this number (the absolute value of it)
3356 even if a deadline has a different individual lead time specified.
3358 Custom commands can set this variable in the options section."
3359 :group 'org-time
3360 :group 'org-agenda-daily/weekly
3361 :type 'integer)
3363 (defcustom org-scheduled-delay-days 0
3364 "Number of days before a scheduled item becomes active.
3365 This variable governs the display in sparse trees and in the agenda.
3366 The default value (i.e. 0) means: don't delay scheduled item.
3367 When negative, it means use this number (the absolute value of it)
3368 even if a scheduled item has a different individual delay time
3369 specified.
3371 Custom commands can set this variable in the options section."
3372 :group 'org-time
3373 :group 'org-agenda-daily/weekly
3374 :version "24.4"
3375 :package-version '(Org . "8.0")
3376 :type 'integer)
3378 (defcustom org-read-date-prefer-future t
3379 "Non-nil means assume future for incomplete date input from user.
3380 This affects the following situations:
3381 1. The user gives a month but not a year.
3382 For example, if it is April and you enter \"feb 2\", this will be read
3383 as Feb 2, *next* year. \"May 5\", however, will be this year.
3384 2. The user gives a day, but no month.
3385 For example, if today is the 15th, and you enter \"3\", Org will read
3386 this as the third of *next* month. However, if you enter \"17\",
3387 it will be considered as *this* month.
3389 If you set this variable to the symbol `time', then also the following
3390 will work:
3392 3. If the user gives a time.
3393 If the time is before now, it will be interpreted as tomorrow.
3395 Currently none of this works for ISO week specifications.
3397 When this option is nil, the current day, month and year will always be
3398 used as defaults.
3400 See also `org-agenda-jump-prefer-future'."
3401 :group 'org-time
3402 :type '(choice
3403 (const :tag "Never" nil)
3404 (const :tag "Check month and day" t)
3405 (const :tag "Check month, day, and time" time)))
3407 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3408 "Should the agenda jump command prefer the future for incomplete dates?
3409 The default is to do the same as configured in `org-read-date-prefer-future'.
3410 But you can also set a deviating value here.
3411 This may t or nil, or the symbol `org-read-date-prefer-future'."
3412 :group 'org-agenda
3413 :group 'org-time
3414 :version "24.1"
3415 :type '(choice
3416 (const :tag "Use org-read-date-prefer-future"
3417 org-read-date-prefer-future)
3418 (const :tag "Never" nil)
3419 (const :tag "Always" t)))
3421 (defcustom org-read-date-force-compatible-dates t
3422 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3424 Depending on the system Emacs is running on, certain dates cannot
3425 be represented with the type used internally to represent time.
3426 Dates between 1970-1-1 and 2038-1-1 can always be represented
3427 correctly. Some systems allow for earlier dates, some for later,
3428 some for both. One way to find out it to insert any date into an
3429 Org buffer, putting the cursor on the year and hitting S-up and
3430 S-down to test the range.
3432 When this variable is set to t, the date/time prompt will not let
3433 you specify dates outside the 1970-2037 range, so it is certain that
3434 these dates will work in whatever version of Emacs you are
3435 running, and also that you can move a file from one Emacs implementation
3436 to another. WHenever Org is forcing the year for you, it will display
3437 a message and beep.
3439 When this variable is nil, Org will check if the date is
3440 representable in the specific Emacs implementation you are using.
3441 If not, it will force a year, usually the current year, and beep
3442 to remind you. Currently this setting is not recommended because
3443 the likelihood that you will open your Org files in an Emacs that
3444 has limited date range is not negligible.
3446 A workaround for this problem is to use diary sexp dates for time
3447 stamps outside of this range."
3448 :group 'org-time
3449 :version "24.1"
3450 :type 'boolean)
3452 (defcustom org-read-date-display-live t
3453 "Non-nil means display current interpretation of date prompt live.
3454 This display will be in an overlay, in the minibuffer."
3455 :group 'org-time
3456 :type 'boolean)
3458 (defcustom org-read-date-popup-calendar t
3459 "Non-nil means pop up a calendar when prompting for a date.
3460 In the calendar, the date can be selected with mouse-1. However, the
3461 minibuffer will also be active, and you can simply enter the date as well.
3462 When nil, only the minibuffer will be available."
3463 :group 'org-time
3464 :type 'boolean)
3465 (defvaralias 'org-popup-calendar-for-date-prompt
3466 'org-read-date-popup-calendar)
3468 (defcustom org-extend-today-until 0
3469 "The hour when your day really ends. Must be an integer.
3470 This has influence for the following applications:
3471 - When switching the agenda to \"today\". It it is still earlier than
3472 the time given here, the day recognized as TODAY is actually yesterday.
3473 - When a date is read from the user and it is still before the time given
3474 here, the current date and time will be assumed to be yesterday, 23:59.
3475 Also, timestamps inserted in capture templates follow this rule.
3477 IMPORTANT: This is a feature whose implementation is and likely will
3478 remain incomplete. Really, it is only here because past midnight seems to
3479 be the favorite working time of John Wiegley :-)"
3480 :group 'org-time
3481 :type 'integer)
3483 (defcustom org-use-effective-time nil
3484 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3485 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3486 \"effective time\" of any timestamps between midnight and 8am will be
3487 23:59 of the previous day."
3488 :group 'org-time
3489 :version "24.1"
3490 :type 'boolean)
3492 (defcustom org-use-last-clock-out-time-as-effective-time nil
3493 "When non-nil, use the last clock out time for `org-todo'.
3494 Note that this option has precedence over the combined use of
3495 `org-use-effective-time' and `org-extend-today-until'."
3496 :group 'org-time
3497 :version "24.4"
3498 :package-version '(Org . "8.0")
3499 :type 'boolean)
3501 (defcustom org-edit-timestamp-down-means-later nil
3502 "Non-nil means S-down will increase the time in a time stamp.
3503 When nil, S-up will increase."
3504 :group 'org-time
3505 :type 'boolean)
3507 (defcustom org-calendar-follow-timestamp-change t
3508 "Non-nil means make the calendar window follow timestamp changes.
3509 When a timestamp is modified and the calendar window is visible, it will be
3510 moved to the new date."
3511 :group 'org-time
3512 :type 'boolean)
3514 (defgroup org-tags nil
3515 "Options concerning tags in Org-mode."
3516 :tag "Org Tags"
3517 :group 'org)
3519 (defcustom org-tag-alist nil
3520 "Default tags available in Org files.
3522 The value of this variable is an alist. Associations either:
3524 (TAG)
3525 (TAG . SELECT)
3526 (SPECIAL)
3528 where TAG is a tag as a string, SELECT is a character, used to
3529 select that tag through the fast tag selection interface, and
3530 SPECIAL is one of the following keywords: `:startgroup',
3531 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3532 `:newline'. These keywords are used to define a hierarchy of
3533 tags. See manual for details.
3535 When this variable is nil, Org mode bases tag input on what is
3536 already in the buffer. The value can be overridden locally by
3537 using a TAGS keyword, e.g.,
3539 #+TAGS: tag1 tag2
3541 See also `org-tag-persistent-alist' to sidestep this behavior."
3542 :group 'org-tags
3543 :type '(repeat
3544 (choice
3545 (cons (string :tag "Tag name")
3546 (character :tag "Access char"))
3547 (const :tag "Start radio group" (:startgroup))
3548 (const :tag "Start tag group, non distinct" (:startgrouptag))
3549 (const :tag "Group tags delimiter" (:grouptags))
3550 (const :tag "End radio group" (:endgroup))
3551 (const :tag "End tag group, non distinct" (:endgrouptag))
3552 (const :tag "New line" (:newline)))))
3554 (defcustom org-tag-persistent-alist nil
3555 "Tags always available in Org files.
3557 The value of this variable is an alist. Associations either:
3559 (TAG)
3560 (TAG . SELECT)
3561 (SPECIAL)
3563 where TAG is a tag as a string, SELECT is a character, used to
3564 select that tag through the fast tag selection interface, and
3565 SPECIAL is one of the following keywords: `:startgroup',
3566 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3567 `:newline'. These keywords are used to define a hierarchy of
3568 tags. See manual for details.
3570 Unlike to `org-tag-alist', tags defined in this variable do not
3571 depend on a local TAGS keyword. Instead, to disable these tags
3572 on a per-file basis, insert anywhere in the file:
3574 #+STARTUP: noptag"
3575 :group 'org-tags
3576 :type '(repeat
3577 (choice
3578 (cons (string :tag "Tag name")
3579 (character :tag "Access char"))
3580 (const :tag "Start radio group" (:startgroup))
3581 (const :tag "Start tag group, non distinct" (:startgrouptag))
3582 (const :tag "Group tags delimiter" (:grouptags))
3583 (const :tag "End radio group" (:endgroup))
3584 (const :tag "End tag group, non distinct" (:endgrouptag))
3585 (const :tag "New line" (:newline)))))
3587 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3588 "If non-nil, always offer completion for all tags of all agenda files.
3589 Instead of customizing this variable directly, you might want to
3590 set it locally for capture buffers, because there no list of
3591 tags in that file can be created dynamically (there are none).
3593 (add-hook \\='org-capture-mode-hook
3594 (lambda ()
3595 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3596 :group 'org-tags
3597 :version "24.1"
3598 :type 'boolean)
3600 (defvar org-file-tags nil
3601 "List of tags that can be inherited by all entries in the file.
3602 The tags will be inherited if the variable `org-use-tag-inheritance'
3603 says they should be.
3604 This variable is populated from #+FILETAGS lines.")
3606 (defcustom org-use-fast-tag-selection 'auto
3607 "Non-nil means use fast tag selection scheme.
3608 This is a special interface to select and deselect tags with single keys.
3609 When nil, fast selection is never used.
3610 When the symbol `auto', fast selection is used if and only if selection
3611 characters for tags have been configured, either through the variable
3612 `org-tag-alist' or through a #+TAGS line in the buffer.
3613 When t, fast selection is always used and selection keys are assigned
3614 automatically if necessary."
3615 :group 'org-tags
3616 :type '(choice
3617 (const :tag "Always" t)
3618 (const :tag "Never" nil)
3619 (const :tag "When selection characters are configured" auto)))
3621 (defcustom org-fast-tag-selection-single-key nil
3622 "Non-nil means fast tag selection exits after first change.
3623 When nil, you have to press RET to exit it.
3624 During fast tag selection, you can toggle this flag with `C-c'.
3625 This variable can also have the value `expert'. In this case, the window
3626 displaying the tags menu is not even shown, until you press C-c again."
3627 :group 'org-tags
3628 :type '(choice
3629 (const :tag "No" nil)
3630 (const :tag "Yes" t)
3631 (const :tag "Expert" expert)))
3633 (defvar org-fast-tag-selection-include-todo nil
3634 "Non-nil means fast tags selection interface will also offer TODO states.
3635 This is an undocumented feature, you should not rely on it.")
3637 (defcustom org-tags-column -77
3638 "The column to which tags should be indented in a headline.
3639 If this number is positive, it specifies the column. If it is negative,
3640 it means that the tags should be flushright to that column. For example,
3641 -80 works well for a normal 80 character screen.
3642 When 0, place tags directly after headline text, with only one space in
3643 between."
3644 :group 'org-tags
3645 :type 'integer)
3647 (defcustom org-auto-align-tags t
3648 "Non-nil keeps tags aligned when modifying headlines.
3649 Some operations (i.e. demoting) change the length of a headline and
3650 therefore shift the tags around. With this option turned on, after
3651 each such operation the tags are again aligned to `org-tags-column'."
3652 :group 'org-tags
3653 :type 'boolean)
3655 (defcustom org-use-tag-inheritance t
3656 "Non-nil means tags in levels apply also for sublevels.
3657 When nil, only the tags directly given in a specific line apply there.
3658 This may also be a list of tags that should be inherited, or a regexp that
3659 matches tags that should be inherited. Additional control is possible
3660 with the variable `org-tags-exclude-from-inheritance' which gives an
3661 explicit list of tags to be excluded from inheritance, even if the value of
3662 `org-use-tag-inheritance' would select it for inheritance.
3664 If this option is t, a match early-on in a tree can lead to a large
3665 number of matches in the subtree when constructing the agenda or creating
3666 a sparse tree. If you only want to see the first match in a tree during
3667 a search, check out the variable `org-tags-match-list-sublevels'."
3668 :group 'org-tags
3669 :type '(choice
3670 (const :tag "Not" nil)
3671 (const :tag "Always" t)
3672 (repeat :tag "Specific tags" (string :tag "Tag"))
3673 (regexp :tag "Tags matched by regexp")))
3675 (defcustom org-tags-exclude-from-inheritance nil
3676 "List of tags that should never be inherited.
3677 This is a way to exclude a few tags from inheritance. For way to do
3678 the opposite, to actively allow inheritance for selected tags,
3679 see the variable `org-use-tag-inheritance'."
3680 :group 'org-tags
3681 :type '(repeat (string :tag "Tag")))
3683 (defun org-tag-inherit-p (tag)
3684 "Check if TAG is one that should be inherited."
3685 (cond
3686 ((member tag org-tags-exclude-from-inheritance) nil)
3687 ((eq org-use-tag-inheritance t) t)
3688 ((not org-use-tag-inheritance) nil)
3689 ((stringp org-use-tag-inheritance)
3690 (string-match org-use-tag-inheritance tag))
3691 ((listp org-use-tag-inheritance)
3692 (member tag org-use-tag-inheritance))
3693 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3695 (defcustom org-tags-match-list-sublevels t
3696 "Non-nil means list also sublevels of headlines matching a search.
3697 This variable applies to tags/property searches, and also to stuck
3698 projects because this search is based on a tags match as well.
3700 When set to the symbol `indented', sublevels are indented with
3701 leading dots.
3703 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3704 the sublevels of a headline matching a tag search often also match
3705 the same search. Listing all of them can create very long lists.
3706 Setting this variable to nil causes subtrees of a match to be skipped.
3708 This variable is semi-obsolete and probably should always be true. It
3709 is better to limit inheritance to certain tags using the variables
3710 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3711 :group 'org-tags
3712 :type '(choice
3713 (const :tag "No, don't list them" nil)
3714 (const :tag "Yes, do list them" t)
3715 (const :tag "List them, indented with leading dots" indented)))
3717 (defcustom org-tags-sort-function nil
3718 "When set, tags are sorted using this function as a comparator."
3719 :group 'org-tags
3720 :type '(choice
3721 (const :tag "No sorting" nil)
3722 (const :tag "Alphabetical" string<)
3723 (const :tag "Reverse alphabetical" string>)
3724 (function :tag "Custom function" nil)))
3726 (defvar org-tags-history nil
3727 "History of minibuffer reads for tags.")
3728 (defvar org-last-tags-completion-table nil
3729 "The last used completion table for tags.")
3730 (defvar org-after-tags-change-hook nil
3731 "Hook that is run after the tags in a line have changed.")
3733 (defgroup org-properties nil
3734 "Options concerning properties in Org-mode."
3735 :tag "Org Properties"
3736 :group 'org)
3738 (defcustom org-property-format "%-10s %s"
3739 "How property key/value pairs should be formatted by `indent-line'.
3740 When `indent-line' hits a property definition, it will format the line
3741 according to this format, mainly to make sure that the values are
3742 lined-up with respect to each other."
3743 :group 'org-properties
3744 :type 'string)
3746 (defcustom org-properties-postprocess-alist nil
3747 "Alist of properties and functions to adjust inserted values.
3748 Elements of this alist must be of the form
3750 ([string] [function])
3752 where [string] must be a property name and [function] must be a
3753 lambda expression: this lambda expression must take one argument,
3754 the value to adjust, and return the new value as a string.
3756 For example, this element will allow the property \"Remaining\"
3757 to be updated wrt the relation between the \"Effort\" property
3758 and the clock summary:
3760 ((\"Remaining\" (lambda(value)
3761 (let ((clocksum (org-clock-sum-current-item))
3762 (effort (org-duration-string-to-minutes
3763 (org-entry-get (point) \"Effort\"))))
3764 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3765 :group 'org-properties
3766 :version "24.1"
3767 :type '(alist :key-type (string :tag "Property")
3768 :value-type (function :tag "Function")))
3770 (defcustom org-use-property-inheritance nil
3771 "Non-nil means properties apply also for sublevels.
3773 This setting is chiefly used during property searches. Turning it on can
3774 cause significant overhead when doing a search, which is why it is not
3775 on by default.
3777 When nil, only the properties directly given in the current entry count.
3778 When t, every property is inherited. The value may also be a list of
3779 properties that should have inheritance, or a regular expression matching
3780 properties that should be inherited.
3782 However, note that some special properties use inheritance under special
3783 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3784 and the properties ending in \"_ALL\" when they are used as descriptor
3785 for valid values of a property.
3787 Note for programmers:
3788 When querying an entry with `org-entry-get', you can control if inheritance
3789 should be used. By default, `org-entry-get' looks only at the local
3790 properties. You can request inheritance by setting the inherit argument
3791 to t (to force inheritance) or to `selective' (to respect the setting
3792 in this variable)."
3793 :group 'org-properties
3794 :type '(choice
3795 (const :tag "Not" nil)
3796 (const :tag "Always" t)
3797 (repeat :tag "Specific properties" (string :tag "Property"))
3798 (regexp :tag "Properties matched by regexp")))
3800 (defun org-property-inherit-p (property)
3801 "Check if PROPERTY is one that should be inherited."
3802 (cond
3803 ((eq org-use-property-inheritance t) t)
3804 ((not org-use-property-inheritance) nil)
3805 ((stringp org-use-property-inheritance)
3806 (string-match org-use-property-inheritance property))
3807 ((listp org-use-property-inheritance)
3808 (member property org-use-property-inheritance))
3809 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3811 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3812 "The default column format, if no other format has been defined.
3813 This variable can be set on the per-file basis by inserting a line
3815 #+COLUMNS: %25ITEM ....."
3816 :group 'org-properties
3817 :type 'string)
3819 (defcustom org-columns-ellipses ".."
3820 "The ellipses to be used when a field in column view is truncated.
3821 When this is the empty string, as many characters as possible are shown,
3822 but then there will be no visual indication that the field has been truncated.
3823 When this is a string of length N, the last N characters of a truncated
3824 field are replaced by this string. If the column is narrower than the
3825 ellipses string, only part of the ellipses string will be shown."
3826 :group 'org-properties
3827 :type 'string)
3829 (defconst org-global-properties-fixed
3830 '(("VISIBILITY_ALL" . "folded children content all")
3831 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3832 "List of property/value pairs that can be inherited by any entry.
3834 These are fixed values, for the preset properties. The user variable
3835 that can be used to add to this list is `org-global-properties'.
3837 The entries in this list are cons cells where the car is a property
3838 name and cdr is a string with the value. If the value represents
3839 multiple items like an \"_ALL\" property, separate the items by
3840 spaces.")
3842 (defcustom org-global-properties nil
3843 "List of property/value pairs that can be inherited by any entry.
3845 This list will be combined with the constant `org-global-properties-fixed'.
3847 The entries in this list are cons cells where the car is a property
3848 name and cdr is a string with the value.
3850 You can set buffer-local values for the same purpose in the variable
3851 `org-file-properties' this by adding lines like
3853 #+PROPERTY: NAME VALUE"
3854 :group 'org-properties
3855 :type '(repeat
3856 (cons (string :tag "Property")
3857 (string :tag "Value"))))
3859 (defvar-local org-file-properties nil
3860 "List of property/value pairs that can be inherited by any entry.
3861 Valid for the current buffer.
3862 This variable is populated from #+PROPERTY lines.")
3864 (defgroup org-agenda nil
3865 "Options concerning agenda views in Org-mode."
3866 :tag "Org Agenda"
3867 :group 'org)
3869 (defvar-local org-category nil
3870 "Variable used by org files to set a category for agenda display.
3871 Such files should use a file variable to set it, for example
3873 # -*- mode: org; org-category: \"ELisp\"
3875 or contain a special line
3877 #+CATEGORY: ELisp
3879 If the file does not specify a category, then file's base name
3880 is used instead.")
3881 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3883 (defcustom org-agenda-files nil
3884 "The files to be used for agenda display.
3885 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3886 \\[org-remove-file]. You can also use customize to edit the list.
3888 If an entry is a directory, all files in that directory that are matched by
3889 `org-agenda-file-regexp' will be part of the file list.
3891 If the value of the variable is not a list but a single file name, then
3892 the list of agenda files is actually stored and maintained in that file, one
3893 agenda file per line. In this file paths can be given relative to
3894 `org-directory'. Tilde expansion and environment variable substitution
3895 are also made."
3896 :group 'org-agenda
3897 :type '(choice
3898 (repeat :tag "List of files and directories" file)
3899 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3901 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3902 "Regular expression to match files for `org-agenda-files'.
3903 If any element in the list in that variable contains a directory instead
3904 of a normal file, all files in that directory that are matched by this
3905 regular expression will be included."
3906 :group 'org-agenda
3907 :type 'regexp)
3909 (defcustom org-agenda-text-search-extra-files nil
3910 "List of extra files to be searched by text search commands.
3911 These files will be searched in addition to the agenda files by the
3912 commands `org-search-view' (`\\[org-agenda] s') \
3913 and `org-occur-in-agenda-files'.
3914 Note that these files will only be searched for text search commands,
3915 not for the other agenda views like todo lists, tag searches or the weekly
3916 agenda. This variable is intended to list notes and possibly archive files
3917 that should also be searched by these two commands.
3918 In fact, if the first element in the list is the symbol `agenda-archives',
3919 then all archive files of all agenda files will be added to the search
3920 scope."
3921 :group 'org-agenda
3922 :type '(set :greedy t
3923 (const :tag "Agenda Archives" agenda-archives)
3924 (repeat :inline t (file))))
3926 (defvaralias 'org-agenda-multi-occur-extra-files
3927 'org-agenda-text-search-extra-files)
3929 (defcustom org-agenda-skip-unavailable-files nil
3930 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3931 A nil value means to remove them, after a query, from the list."
3932 :group 'org-agenda
3933 :type 'boolean)
3935 (defcustom org-calendar-to-agenda-key [?c]
3936 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3937 The command `org-calendar-goto-agenda' will be bound to this key. The
3938 default is the character `c' because then `c' can be used to switch back and
3939 forth between agenda and calendar."
3940 :group 'org-agenda
3941 :type 'sexp)
3943 (defcustom org-calendar-insert-diary-entry-key [?i]
3944 "The key to be installed in `calendar-mode-map' for adding diary entries.
3945 This option is irrelevant until `org-agenda-diary-file' has been configured
3946 to point to an Org file. When that is the case, the command
3947 `org-agenda-diary-entry' will be bound to the key given here, by default
3948 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3949 if you want to continue doing this, you need to change this to a different
3950 key."
3951 :group 'org-agenda
3952 :type 'sexp)
3954 (defcustom org-agenda-diary-file 'diary-file
3955 "File to which to add new entries with the `i' key in agenda and calendar.
3956 When this is the symbol `diary-file', the functionality in the Emacs
3957 calendar will be used to add entries to the `diary-file'. But when this
3958 points to a file, `org-agenda-diary-entry' will be used instead."
3959 :group 'org-agenda
3960 :type '(choice
3961 (const :tag "The standard Emacs diary file" diary-file)
3962 (file :tag "Special Org file diary entries")))
3964 (eval-after-load "calendar"
3965 '(progn
3966 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3967 'org-calendar-goto-agenda)
3968 (add-hook 'calendar-mode-hook
3969 (lambda ()
3970 (unless (eq org-agenda-diary-file 'diary-file)
3971 (define-key calendar-mode-map
3972 org-calendar-insert-diary-entry-key
3973 'org-agenda-diary-entry))))))
3975 (defgroup org-latex nil
3976 "Options for embedding LaTeX code into Org-mode."
3977 :tag "Org LaTeX"
3978 :group 'org)
3980 (defcustom org-format-latex-options
3981 '(:foreground default :background default :scale 1.0
3982 :html-foreground "Black" :html-background "Transparent"
3983 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3984 "Options for creating images from LaTeX fragments.
3985 This is a property list with the following properties:
3986 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3987 `default' means use the foreground of the default face.
3988 `auto' means use the foreground from the text face.
3989 :background the background color, or \"Transparent\".
3990 `default' means use the background of the default face.
3991 `auto' means use the background from the text face.
3992 :scale a scaling factor for the size of the images, to get more pixels
3993 :html-foreground, :html-background, :html-scale
3994 the same numbers for HTML export.
3995 :matchers a list indicating which matchers should be used to
3996 find LaTeX fragments. Valid members of this list are:
3997 \"begin\" find environments
3998 \"$1\" find single characters surrounded by $.$
3999 \"$\" find math expressions surrounded by $...$
4000 \"$$\" find math expressions surrounded by $$....$$
4001 \"\\(\" find math expressions surrounded by \\(...\\)
4002 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4003 :group 'org-latex
4004 :type 'plist)
4006 (defcustom org-format-latex-signal-error t
4007 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4008 When nil, just push out a message."
4009 :group 'org-latex
4010 :version "24.1"
4011 :type 'boolean)
4013 (defcustom org-latex-to-mathml-jar-file nil
4014 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4015 Use this to specify additional executable file say a jar file.
4017 When using MathToWeb as the converter, specify the full-path to
4018 your mathtoweb.jar file."
4019 :group 'org-latex
4020 :version "24.1"
4021 :type '(choice
4022 (const :tag "None" nil)
4023 (file :tag "JAR file" :must-match t)))
4025 (defcustom org-latex-to-mathml-convert-command nil
4026 "Command to convert LaTeX fragments to MathML.
4027 Replace format-specifiers in the command as noted below and use
4028 `shell-command' to convert LaTeX to MathML.
4029 %j: Executable file in fully expanded form as specified by
4030 `org-latex-to-mathml-jar-file'.
4031 %I: Input LaTeX file in fully expanded form.
4032 %i: The latex fragment to be converted.
4033 %o: Output MathML file.
4035 This command is used by `org-create-math-formula'.
4037 When using MathToWeb as the converter, set this option to
4038 \"java -jar %j -unicode -force -df %o %I\".
4040 When using LaTeXML set this option to
4041 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4042 :group 'org-latex
4043 :version "24.1"
4044 :type '(choice
4045 (const :tag "None" nil)
4046 (string :tag "\nShell command")))
4048 (defcustom org-preview-latex-default-process 'dvipng
4049 "The default process to convert LaTeX fragments to image files.
4050 All available processes and theirs documents can be found in
4051 `org-preview-latex-process-alist', which see."
4052 :group 'org-latex
4053 :version "25.2"
4054 :package-version '(Org . "9.0")
4055 :type 'symbol)
4057 (defcustom org-preview-latex-process-alist
4058 '((dvipng
4059 :programs ("latex" "dvipng" "gs")
4060 :description "dvi > png"
4061 :message "you need to install the programs: latex, dvipng and ghostscript."
4062 :image-input-type "dvi"
4063 :image-output-type "png"
4064 :image-size-adjust (1.0 . 1.0)
4065 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4066 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
4067 (dvisvgm
4068 :programs ("latex" "dvisvgm" "gs")
4069 :description "dvi > svg"
4070 :message "you need to install the programs: latex, dvisvgm and ghostscript."
4071 :use-xcolor t
4072 :image-input-type "dvi"
4073 :image-output-type "svg"
4074 :image-size-adjust (1.7 . 1.5)
4075 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4076 :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
4077 (imagemagick
4078 :programs ("latex" "convert" "gs")
4079 :description "pdf > png"
4080 :message
4081 "you need to install the programs: latex, imagemagick and ghostscript."
4082 :use-xcolor t
4083 :image-input-type "pdf"
4084 :image-output-type "png"
4085 :image-size-adjust (1.0 . 1.0)
4086 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4087 :image-converter
4088 ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
4089 "Definitions of external processes for LaTeX previewing.
4090 Org mode can use some external commands to generate TeX snippet's images for
4091 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4092 `org-create-formula-image' how to call them.
4094 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4095 PROPERTIES accepts the following attributes:
4097 :programs list of strings, required programs.
4098 :description string, describe the process.
4099 :message string, message it when required programs cannot be found.
4100 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4101 :image-output-type string, output file type of image converter (e.g., \"png\").
4102 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4103 deal with background and foreground color of image.
4104 Otherwise, dvipng style background and foregroud color
4105 format are generated. You may then refer to them in
4106 command options with \"%F\" and \"%B\".
4107 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4108 image size showed in buffer and the cdr element is for
4109 HTML file. This option is only useful for process
4110 developers, users should use variable
4111 `org-format-latex-options' instead.
4112 :post-clean list of strings, files matched are to be cleaned up once
4113 the image is generated. When nil, the files with \".dvi\",
4114 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4115 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4116 be cleaned up.
4117 :latex-header list of strings, the LaTeX header of the snippet file.
4118 When nil, the fallback value is used instead, which is
4119 controlled by `org-format-latex-header',
4120 `org-latex-default-packages-alist' and
4121 `org-latex-packages-alist', which see.
4122 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4123 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4124 replaced with values defined below.
4125 :image-converter list of image converter commands strings. Each of them is
4126 given to the shell and supports any of the following
4127 place-holders defined below.
4129 Place-holders used by `:image-converter' and `:latex-compiler':
4131 %f input file name.
4132 %b base name of input file.
4133 %o base directory of input file.
4135 Place-holders only used by `:image-converter':
4137 %F foreground of image
4138 %B background of image
4139 %D dpi, which is used to adjust image size by some processing commands.
4140 %S the image size scale ratio, which is used to adjust image size by some
4141 processing commands."
4142 :group 'org-latex
4143 :version "25.2"
4144 :package-version '(Org . "9.0")
4145 :type '(alist :tag "LaTeX to image backends"
4146 :value-type (plist)))
4148 (defcustom org-preview-latex-image-directory "ltximg/"
4149 "Path to store latex preview images.
4150 A relative path here creates many directories relative to the
4151 processed org files paths. An absolute path puts all preview
4152 images at the same place."
4153 :group 'org-latex
4154 :version "25.1"
4155 :package-version '(Org . "9.0")
4156 :type 'string)
4158 (defun org-format-latex-mathml-available-p ()
4159 "Return t if `org-latex-to-mathml-convert-command' is usable."
4160 (save-match-data
4161 (when (and (boundp 'org-latex-to-mathml-convert-command)
4162 org-latex-to-mathml-convert-command)
4163 (let ((executable (car (split-string
4164 org-latex-to-mathml-convert-command))))
4165 (when (executable-find executable)
4166 (if (string-match
4167 "%j" org-latex-to-mathml-convert-command)
4168 (file-readable-p org-latex-to-mathml-jar-file)
4169 t))))))
4171 (defcustom org-format-latex-header "\\documentclass{article}
4172 \\usepackage[usenames]{color}
4173 \[PACKAGES]
4174 \[DEFAULT-PACKAGES]
4175 \\pagestyle{empty} % do not remove
4176 % The settings below are copied from fullpage.sty
4177 \\setlength{\\textwidth}{\\paperwidth}
4178 \\addtolength{\\textwidth}{-3cm}
4179 \\setlength{\\oddsidemargin}{1.5cm}
4180 \\addtolength{\\oddsidemargin}{-2.54cm}
4181 \\setlength{\\evensidemargin}{\\oddsidemargin}
4182 \\setlength{\\textheight}{\\paperheight}
4183 \\addtolength{\\textheight}{-\\headheight}
4184 \\addtolength{\\textheight}{-\\headsep}
4185 \\addtolength{\\textheight}{-\\footskip}
4186 \\addtolength{\\textheight}{-3cm}
4187 \\setlength{\\topmargin}{1.5cm}
4188 \\addtolength{\\topmargin}{-2.54cm}"
4189 "The document header used for processing LaTeX fragments.
4190 It is imperative that this header make sure that no page number
4191 appears on the page. The package defined in the variables
4192 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4193 will either replace the placeholder \"[PACKAGES]\" in this
4194 header, or they will be appended."
4195 :group 'org-latex
4196 :type 'string)
4198 (defun org-set-packages-alist (var val)
4199 "Set the packages alist and make sure it has 3 elements per entry."
4200 (set var (mapcar (lambda (x)
4201 (if (and (consp x) (= (length x) 2))
4202 (list (car x) (nth 1 x) t)
4204 val)))
4206 (defun org-get-packages-alist (var)
4207 "Get the packages alist and make sure it has 3 elements per entry."
4208 (mapcar (lambda (x)
4209 (if (and (consp x) (= (length x) 2))
4210 (list (car x) (nth 1 x) t)
4212 (default-value var)))
4214 (defcustom org-latex-default-packages-alist
4215 '(("AUTO" "inputenc" t ("pdflatex"))
4216 ("T1" "fontenc" t ("pdflatex"))
4217 ("" "graphicx" t)
4218 ("" "grffile" t)
4219 ("" "longtable" nil)
4220 ("" "wrapfig" nil)
4221 ("" "rotating" nil)
4222 ("normalem" "ulem" t)
4223 ("" "amsmath" t)
4224 ("" "textcomp" t)
4225 ("" "amssymb" t)
4226 ("" "capt-of" nil)
4227 ("" "hyperref" nil))
4228 "Alist of default packages to be inserted in the header.
4230 Change this only if one of the packages here causes an
4231 incompatibility with another package you are using.
4233 The packages in this list are needed by one part or another of
4234 Org mode to function properly:
4236 - inputenc, fontenc: for basic font and character selection
4237 - graphicx: for including images
4238 - grffile: allow periods and spaces in graphics file names
4239 - longtable: For multipage tables
4240 - wrapfig: for figure placement
4241 - rotating: for sideways figures and tables
4242 - ulem: for underline and strike-through
4243 - amsmath: for subscript and superscript and math environments
4244 - textcomp, amssymb: for various symbols used
4245 for interpreting the entities in `org-entities'. You can skip
4246 some of these packages if you don't use any of their symbols.
4247 - capt-of: for captions outside of floats
4248 - hyperref: for cross references
4250 Therefore you should not modify this variable unless you know
4251 what you are doing. The one reason to change it anyway is that
4252 you might be loading some other package that conflicts with one
4253 of the default packages. Each element is either a cell or
4254 a string.
4256 A cell is of the format
4258 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4260 If SNIPPET-FLAG is non-nil, the package also needs to be included
4261 when compiling LaTeX snippets into images for inclusion into
4262 non-LaTeX output. COMPILERS is a list of compilers that should
4263 include the package, see `org-latex-compiler'. If the document
4264 compiler is not in the list, and the list is non-nil, the package
4265 will not be inserted in the final document.
4267 A string will be inserted as-is in the header of the document."
4268 :group 'org-latex
4269 :group 'org-export-latex
4270 :set 'org-set-packages-alist
4271 :get 'org-get-packages-alist
4272 :version "25.1"
4273 :package-version '(Org . "8.3")
4274 :type '(repeat
4275 (choice
4276 (list :tag "options/package pair"
4277 (string :tag "options")
4278 (string :tag "package")
4279 (boolean :tag "Snippet"))
4280 (string :tag "A line of LaTeX"))))
4282 (defcustom org-latex-packages-alist nil
4283 "Alist of packages to be inserted in every LaTeX header.
4285 These will be inserted after `org-latex-default-packages-alist'.
4286 Each element is either a cell or a string.
4288 A cell is of the format:
4290 (\"options\" \"package\" SNIPPET-FLAG)
4292 SNIPPET-FLAG, when non-nil, indicates that this package is also
4293 needed when turning LaTeX snippets into images for inclusion into
4294 non-LaTeX output.
4296 A string will be inserted as-is in the header of the document.
4298 Make sure that you only list packages here which:
4300 - you want in every file;
4301 - do not conflict with the setup in `org-format-latex-header';
4302 - do not conflict with the default packages in
4303 `org-latex-default-packages-alist'."
4304 :group 'org-latex
4305 :group 'org-export-latex
4306 :set 'org-set-packages-alist
4307 :get 'org-get-packages-alist
4308 :type '(repeat
4309 (choice
4310 (list :tag "options/package pair"
4311 (string :tag "options")
4312 (string :tag "package")
4313 (boolean :tag "Snippet"))
4314 (string :tag "A line of LaTeX"))))
4316 (defgroup org-appearance nil
4317 "Settings for Org mode appearance."
4318 :tag "Org Appearance"
4319 :group 'org)
4321 (defcustom org-level-color-stars-only nil
4322 "Non-nil means fontify only the stars in each headline.
4323 When nil, the entire headline is fontified.
4324 Changing it requires restart of `font-lock-mode' to become effective
4325 also in regions already fontified."
4326 :group 'org-appearance
4327 :type 'boolean)
4329 (defcustom org-hide-leading-stars nil
4330 "Non-nil means hide the first N-1 stars in a headline.
4331 This works by using the face `org-hide' for these stars. This
4332 face is white for a light background, and black for a dark
4333 background. You may have to customize the face `org-hide' to
4334 make this work.
4335 Changing it requires restart of `font-lock-mode' to become effective
4336 also in regions already fontified.
4337 You may also set this on a per-file basis by adding one of the following
4338 lines to the buffer:
4340 #+STARTUP: hidestars
4341 #+STARTUP: showstars"
4342 :group 'org-appearance
4343 :type 'boolean)
4345 (defcustom org-hidden-keywords nil
4346 "List of symbols corresponding to keywords to be hidden the org buffer.
4347 For example, a value \\='(title) for this list will make the document's title
4348 appear in the buffer without the initial #+TITLE: keyword."
4349 :group 'org-appearance
4350 :version "24.1"
4351 :type '(set (const :tag "#+AUTHOR" author)
4352 (const :tag "#+DATE" date)
4353 (const :tag "#+EMAIL" email)
4354 (const :tag "#+TITLE" title)))
4356 (defcustom org-custom-properties nil
4357 "List of properties (as strings) with a special meaning.
4358 The default use of these custom properties is to let the user
4359 hide them with `org-toggle-custom-properties-visibility'."
4360 :group 'org-properties
4361 :group 'org-appearance
4362 :version "24.3"
4363 :type '(repeat (string :tag "Property Name")))
4365 (defcustom org-fontify-done-headline nil
4366 "Non-nil means change the face of a headline if it is marked DONE.
4367 Normally, only the TODO/DONE keyword indicates the state of a headline.
4368 When this is non-nil, the headline after the keyword is set to the
4369 `org-headline-done' as an additional indication."
4370 :group 'org-appearance
4371 :type 'boolean)
4373 (defcustom org-fontify-emphasized-text t
4374 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4375 Changing this variable requires a restart of Emacs to take effect."
4376 :group 'org-appearance
4377 :type 'boolean)
4379 (defcustom org-fontify-whole-heading-line nil
4380 "Non-nil means fontify the whole line for headings.
4381 This is useful when setting a background color for the
4382 org-level-* faces."
4383 :group 'org-appearance
4384 :type 'boolean)
4386 (defcustom org-highlight-latex-and-related nil
4387 "Non-nil means highlight LaTeX related syntax in the buffer.
4388 When non nil, the value should be a list containing any of the
4389 following symbols:
4390 `latex' Highlight LaTeX snippets and environments.
4391 `script' Highlight subscript and superscript.
4392 `entities' Highlight entities."
4393 :group 'org-appearance
4394 :version "24.4"
4395 :package-version '(Org . "8.0")
4396 :type '(choice
4397 (const :tag "No highlighting" nil)
4398 (set :greedy t :tag "Highlight"
4399 (const :tag "LaTeX snippets and environments" latex)
4400 (const :tag "Subscript and superscript" script)
4401 (const :tag "Entities" entities))))
4403 (defcustom org-hide-emphasis-markers nil
4404 "Non-nil mean font-lock should hide the emphasis marker characters."
4405 :group 'org-appearance
4406 :type 'boolean)
4408 (defcustom org-hide-macro-markers nil
4409 "Non-nil mean font-lock should hide the brackets marking macro calls."
4410 :group 'org-appearance
4411 :type 'boolean)
4413 (defcustom org-pretty-entities nil
4414 "Non-nil means show entities as UTF8 characters.
4415 When nil, the \\name form remains in the buffer."
4416 :group 'org-appearance
4417 :version "24.1"
4418 :type 'boolean)
4420 (defcustom org-pretty-entities-include-sub-superscripts t
4421 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4422 :group 'org-appearance
4423 :version "24.1"
4424 :type 'boolean)
4426 (defvar org-emph-re nil
4427 "Regular expression for matching emphasis.
4428 After a match, the match groups contain these elements:
4429 0 The match of the full regular expression, including the characters
4430 before and after the proper match
4431 1 The character before the proper match, or empty at beginning of line
4432 2 The proper match, including the leading and trailing markers
4433 3 The leading marker like * or /, indicating the type of highlighting
4434 4 The text between the emphasis markers, not including the markers
4435 5 The character after the match, empty at the end of a line")
4436 (defvar org-verbatim-re nil
4437 "Regular expression for matching verbatim text.")
4438 (defvar org-emphasis-regexp-components) ; defined just below
4439 (defvar org-emphasis-alist) ; defined just below
4440 (defun org-set-emph-re (var val)
4441 "Set variable and compute the emphasis regular expression."
4442 (set var val)
4443 (when (and (boundp 'org-emphasis-alist)
4444 (boundp 'org-emphasis-regexp-components)
4445 org-emphasis-alist org-emphasis-regexp-components)
4446 (let* ((e org-emphasis-regexp-components)
4447 (pre (car e))
4448 (post (nth 1 e))
4449 (border (nth 2 e))
4450 (body (nth 3 e))
4451 (nl (nth 4 e))
4452 (body1 (concat body "*?"))
4453 (markers (mapconcat 'car org-emphasis-alist ""))
4454 (vmarkers (mapconcat
4455 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4456 org-emphasis-alist "")))
4457 ;; make sure special characters appear at the right position in the class
4458 (if (string-match "\\^" markers)
4459 (setq markers (concat (replace-match "" t t markers) "^")))
4460 (if (string-match "-" markers)
4461 (setq markers (concat (replace-match "" t t markers) "-")))
4462 (if (string-match "\\^" vmarkers)
4463 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4464 (if (string-match "-" vmarkers)
4465 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4466 (if (> nl 0)
4467 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4468 (int-to-string nl) "\\}")))
4469 ;; Make the regexp
4470 (setq org-emph-re
4471 (concat "\\([" pre "]\\|^\\)"
4472 "\\("
4473 "\\([" markers "]\\)"
4474 "\\("
4475 "[^" border "]\\|"
4476 "[^" border "]"
4477 body1
4478 "[^" border "]"
4479 "\\)"
4480 "\\3\\)"
4481 "\\([" post "]\\|$\\)"))
4482 (setq org-verbatim-re
4483 (concat "\\([" pre "]\\|^\\)"
4484 "\\("
4485 "\\([" vmarkers "]\\)"
4486 "\\("
4487 "[^" border "]\\|"
4488 "[^" border "]"
4489 body1
4490 "[^" border "]"
4491 "\\)"
4492 "\\3\\)"
4493 "\\([" post "]\\|$\\)")))))
4495 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4496 ;; set this option proved cumbersome. See this message/thread:
4497 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4498 (defvar org-emphasis-regexp-components
4499 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4500 "Components used to build the regular expression for emphasis.
4501 This is a list with five entries. Terminology: In an emphasis string
4502 like \" *strong word* \", we call the initial space PREMATCH, the final
4503 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4504 and \"trong wor\" is the body. The different components in this variable
4505 specify what is allowed/forbidden in each part:
4507 pre Chars allowed as prematch. Beginning of line will be allowed too.
4508 post Chars allowed as postmatch. End of line will be allowed too.
4509 border The chars *forbidden* as border characters.
4510 body-regexp A regexp like \".\" to match a body character. Don't use
4511 non-shy groups here, and don't allow newline here.
4512 newline The maximum number of newlines allowed in an emphasis exp.
4514 You need to reload Org or to restart Emacs after customizing this.")
4516 (defcustom org-emphasis-alist
4517 '(("*" bold)
4518 ("/" italic)
4519 ("_" underline)
4520 ("=" org-verbatim verbatim)
4521 ("~" org-code verbatim)
4522 ("+" (:strike-through t)))
4523 "Alist of characters and faces to emphasize text.
4524 Text starting and ending with a special character will be emphasized,
4525 for example *bold*, _underlined_ and /italic/. This variable sets the
4526 marker characters and the face to be used by font-lock for highlighting
4527 in Org buffers.
4529 You need to reload Org or to restart Emacs after customizing this."
4530 :group 'org-appearance
4531 :set 'org-set-emph-re
4532 :version "24.4"
4533 :package-version '(Org . "8.0")
4534 :type '(repeat
4535 (list
4536 (string :tag "Marker character")
4537 (choice
4538 (face :tag "Font-lock-face")
4539 (plist :tag "Face property list"))
4540 (option (const verbatim)))))
4542 (defvar org-protecting-blocks '("src" "example" "export")
4543 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4544 This is needed for font-lock setup.")
4546 ;;; Functions and variables from their packages
4547 ;; Declared here to avoid compiler warnings
4548 (defvar mark-active)
4550 ;; Various packages
4551 (declare-function calc-eval "calc" (str &optional separator &rest args))
4552 (declare-function calendar-forward-day "cal-move" (arg))
4553 (declare-function calendar-goto-date "cal-move" (date))
4554 (declare-function calendar-goto-today "cal-move" ())
4555 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4556 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4557 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4558 (declare-function cdlatex-tab "ext:cdlatex" ())
4559 (declare-function dired-get-filename
4560 "dired"
4561 (&optional localp no-error-if-not-filep))
4562 (declare-function iswitchb-read-buffer
4563 "iswitchb"
4564 (prompt &optional
4565 default require-match _predicate start matches-set))
4566 (declare-function org-agenda-change-all-lines
4567 "org-agenda"
4568 (newhead hdmarker &optional fixface just-this))
4569 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4570 "org-agenda"
4571 (&optional end))
4572 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4573 (declare-function org-agenda-format-item
4574 "org-agenda"
4575 (extra txt &optional level category tags dotime
4576 remove-re habitp))
4577 (declare-function org-agenda-maybe-redo "org-agenda" ())
4578 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4579 (declare-function org-agenda-save-markers-for-cut-and-paste
4580 "org-agenda"
4581 (beg end))
4582 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4583 (declare-function org-agenda-skip "org-agenda" ())
4584 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4585 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4586 (declare-function org-indent-mode "org-indent" (&optional arg))
4587 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4588 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4589 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4590 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4591 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4592 (declare-function parse-time-string "parse-time" (string))
4593 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4594 (declare-function table--at-cell-p
4595 "table"
4596 (position &optional object at-column))
4598 (defvar align-mode-rules-list)
4599 (defvar calc-embedded-close-formula)
4600 (defvar calc-embedded-open-formula)
4601 (defvar calc-embedded-open-mode)
4602 (defvar font-lock-unfontify-region-function)
4603 (defvar iswitchb-temp-buflist)
4604 (defvar org-agenda-tags-todo-honor-ignore-options)
4605 (defvar remember-data-file)
4606 (defvar texmathp-why)
4608 ;;;###autoload
4609 (defun turn-on-orgtbl ()
4610 "Unconditionally turn on `orgtbl-mode'."
4611 (require 'org-table)
4612 (orgtbl-mode 1))
4614 (defun org-at-table-p (&optional table-type)
4615 "Non-nil if the cursor is inside an Org table.
4616 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4617 If `org-enable-table-editor' is nil, return nil unconditionally."
4618 (and
4619 org-enable-table-editor
4620 (save-excursion
4621 (beginning-of-line)
4622 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4623 (or (not (derived-mode-p 'org-mode))
4624 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4625 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4627 (defun org-at-table.el-p ()
4628 "Non-nil when point is at a table.el table."
4629 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4630 (let ((element (org-element-at-point)))
4631 (and (eq (org-element-type element) 'table)
4632 (eq (org-element-property :type element) 'table.el)))))
4634 (defun org-table-recognize-table.el ()
4635 "If there is a table.el table nearby, recognize it and move into it."
4636 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4637 (beginning-of-line)
4638 (unless (or (looking-at org-table-dataline-regexp)
4639 (not (looking-at org-table1-hline-regexp)))
4640 (forward-line)
4641 (when (looking-at org-table-any-border-regexp)
4642 (forward-line -2)))
4643 (if (re-search-forward "|" (org-table-end t) t)
4644 (progn
4645 (require 'table)
4646 (if (table--at-cell-p (point)) t
4647 (message "recognizing table.el table...")
4648 (table-recognize-table)
4649 (message "recognizing table.el table...done")))
4650 (error "This should not happen"))))
4651 ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
4652 (make-obsolete 'org-table-recognize-table.el
4653 "please notify the org mailing list if you use this function."
4654 "Org 9.0")
4656 (defun org-at-table-hline-p ()
4657 "Non-nil when point is inside a hline in a table.
4658 Assume point is already in a table. If `org-enable-table-editor'
4659 is nil, return nil unconditionally."
4660 (and org-enable-table-editor
4661 (save-excursion
4662 (beginning-of-line)
4663 (looking-at org-table-hline-regexp))))
4665 (defun org-table-map-tables (function &optional quietly)
4666 "Apply FUNCTION to the start of all tables in the buffer."
4667 (save-excursion
4668 (save-restriction
4669 (widen)
4670 (goto-char (point-min))
4671 (while (re-search-forward org-table-any-line-regexp nil t)
4672 (unless quietly
4673 (message "Mapping tables: %d%%"
4674 (floor (* 100.0 (point)) (buffer-size))))
4675 (beginning-of-line 1)
4676 (when (and (looking-at org-table-line-regexp)
4677 ;; Exclude tables in src/example/verbatim/clocktable blocks
4678 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4679 (save-excursion (funcall function))
4680 (or (looking-at org-table-line-regexp)
4681 (forward-char 1)))
4682 (re-search-forward org-table-any-border-regexp nil 1))))
4683 (unless quietly (message "Mapping tables: done")))
4685 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4686 (declare-function org-clock-update-mode-line "org-clock" ())
4687 (declare-function org-resolve-clocks "org-clock"
4688 (&optional also-non-dangling-p prompt last-valid))
4690 (defun org-at-TBLFM-p (&optional pos)
4691 "Non-nil when point (or POS) is in #+TBLFM line."
4692 (save-excursion
4693 (goto-char (or pos (point)))
4694 (beginning-of-line)
4695 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4696 (eq (org-element-type (org-element-at-point)) 'table))))
4698 (defvar org-clock-start-time)
4699 (defvar org-clock-marker (make-marker)
4700 "Marker recording the last clock-in.")
4701 (defvar org-clock-hd-marker (make-marker)
4702 "Marker recording the last clock-in, but the headline position.")
4703 (defvar org-clock-heading ""
4704 "The heading of the current clock entry.")
4705 (defun org-clock-is-active ()
4706 "Return the buffer where the clock is currently running.
4707 Return nil if no clock is running."
4708 (marker-buffer org-clock-marker))
4710 (defun org-check-running-clock ()
4711 "Check if the current buffer contains the running clock.
4712 If yes, offer to stop it and to save the buffer with the changes."
4713 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4714 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4715 (buffer-name))))
4716 (org-clock-out)
4717 (when (y-or-n-p "Save changed buffer?")
4718 (save-buffer))))
4720 (defun org-clocktable-try-shift (dir n)
4721 "Check if this line starts a clock table, if yes, shift the time block."
4722 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4723 (org-clocktable-shift dir n)))
4725 ;;;###autoload
4726 (defun org-clock-persistence-insinuate ()
4727 "Set up hooks for clock persistence."
4728 (require 'org-clock)
4729 (add-hook 'org-mode-hook 'org-clock-load)
4730 (add-hook 'kill-emacs-hook 'org-clock-save))
4732 (defgroup org-archive nil
4733 "Options concerning archiving in Org-mode."
4734 :tag "Org Archive"
4735 :group 'org-structure)
4737 (defcustom org-archive-location "%s_archive::"
4738 "The location where subtrees should be archived.
4740 The value of this variable is a string, consisting of two parts,
4741 separated by a double-colon. The first part is a filename and
4742 the second part is a headline.
4744 When the filename is omitted, archiving happens in the same file.
4745 %s in the filename will be replaced by the current file
4746 name (without the directory part). Archiving to a different file
4747 is useful to keep archived entries from contributing to the
4748 Org Agenda.
4750 The archived entries will be filed as subtrees of the specified
4751 headline. When the headline is omitted, the subtrees are simply
4752 filed away at the end of the file, as top-level entries. Also in
4753 the heading you can use %s to represent the file name, this can be
4754 useful when using the same archive for a number of different files.
4756 Here are a few examples:
4757 \"%s_archive::\"
4758 If the current file is Projects.org, archive in file
4759 Projects.org_archive, as top-level trees. This is the default.
4761 \"::* Archived Tasks\"
4762 Archive in the current file, under the top-level headline
4763 \"* Archived Tasks\".
4765 \"~/org/archive.org::\"
4766 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4768 \"~/org/archive.org::* From %s\"
4769 Archive in file ~/org/archive.org (absolute path), under headlines
4770 \"From FILENAME\" where file name is the current file name.
4772 \"~/org/datetree.org::datetree/* Finished Tasks\"
4773 The \"datetree/\" string is special, signifying to archive
4774 items to the datetree. Items are placed in either the CLOSED
4775 date of the item, or the current date if there is no CLOSED date.
4776 The heading will be a subentry to the current date. There doesn't
4777 need to be a heading, but there always needs to be a slash after
4778 datetree. For example, to store archived items directly in the
4779 datetree, use \"~/org/datetree.org::datetree/\".
4781 \"basement::** Finished Tasks\"
4782 Archive in file ./basement (relative path), as level 3 trees
4783 below the level 2 heading \"** Finished Tasks\".
4785 You may set this option on a per-file basis by adding to the buffer a
4786 line like
4788 #+ARCHIVE: basement::** Finished Tasks
4790 You may also define it locally for a subtree by setting an ARCHIVE property
4791 in the entry. If such a property is found in an entry, or anywhere up
4792 the hierarchy, it will be used."
4793 :group 'org-archive
4794 :type 'string)
4796 (defcustom org-agenda-skip-archived-trees t
4797 "Non-nil means the agenda will skip any items located in archived trees.
4798 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4799 variable is no longer recommended, you should leave it at the value t.
4800 Instead, use the key `v' to cycle the archives-mode in the agenda."
4801 :group 'org-archive
4802 :group 'org-agenda-skip
4803 :type 'boolean)
4805 (defcustom org-columns-skip-archived-trees t
4806 "Non-nil means ignore archived trees when creating column view."
4807 :group 'org-archive
4808 :group 'org-properties
4809 :type 'boolean)
4811 (defcustom org-cycle-open-archived-trees nil
4812 "Non-nil means `org-cycle' will open archived trees.
4813 An archived tree is a tree marked with the tag ARCHIVE.
4814 When nil, archived trees will stay folded. You can still open them with
4815 normal outline commands like `show-all', but not with the cycling commands."
4816 :group 'org-archive
4817 :group 'org-cycle
4818 :type 'boolean)
4820 (defcustom org-sparse-tree-open-archived-trees nil
4821 "Non-nil means sparse tree construction shows matches in archived trees.
4822 When nil, matches in these trees are highlighted, but the trees are kept in
4823 collapsed state."
4824 :group 'org-archive
4825 :group 'org-sparse-trees
4826 :type 'boolean)
4828 (defcustom org-sparse-tree-default-date-type nil
4829 "The default date type when building a sparse tree.
4830 When this is nil, a date is a scheduled or a deadline timestamp.
4831 Otherwise, these types are allowed:
4833 all: all timestamps
4834 active: only active timestamps (<...>)
4835 inactive: only inactive timestamps ([...])
4836 scheduled: only scheduled timestamps
4837 deadline: only deadline timestamps"
4838 :type '(choice (const :tag "Scheduled or deadline" nil)
4839 (const :tag "All timestamps" all)
4840 (const :tag "Only active timestamps" active)
4841 (const :tag "Only inactive timestamps" inactive)
4842 (const :tag "Only scheduled timestamps" scheduled)
4843 (const :tag "Only deadline timestamps" deadline)
4844 (const :tag "Only closed timestamps" closed))
4845 :version "25.1"
4846 :package-version '(Org . "8.3")
4847 :group 'org-sparse-trees)
4849 (defun org-cycle-hide-archived-subtrees (state)
4850 "Re-hide all archived subtrees after a visibility state change."
4851 (when (and (not org-cycle-open-archived-trees)
4852 (not (memq state '(overview folded))))
4853 (save-excursion
4854 (let* ((globalp (memq state '(contents all)))
4855 (beg (if globalp (point-min) (point)))
4856 (end (if globalp (point-max) (org-end-of-subtree t))))
4857 (org-hide-archived-subtrees beg end)
4858 (goto-char beg)
4859 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4860 (message "%s" (substitute-command-keys
4861 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4863 (defun org-force-cycle-archived ()
4864 "Cycle subtree even if it is archived."
4865 (interactive)
4866 (setq this-command 'org-cycle)
4867 (let ((org-cycle-open-archived-trees t))
4868 (call-interactively 'org-cycle)))
4870 (defun org-hide-archived-subtrees (beg end)
4871 "Re-hide all archived subtrees after a visibility state change."
4872 (org-with-wide-buffer
4873 (let ((case-fold-search nil)
4874 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4875 (goto-char beg)
4876 ;; Include headline point is currently on.
4877 (beginning-of-line)
4878 (while (and (< (point) end) (re-search-forward re end t))
4879 (when (member org-archive-tag (org-get-tags))
4880 (org-flag-subtree t)
4881 (org-end-of-subtree t))))))
4883 (declare-function outline-end-of-heading "outline" ())
4884 (declare-function outline-flag-region "outline" (from to flag))
4885 (defun org-flag-subtree (flag)
4886 (save-excursion
4887 (org-back-to-heading t)
4888 (outline-end-of-heading)
4889 (outline-flag-region (point)
4890 (progn (org-end-of-subtree t) (point))
4891 flag)))
4893 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4895 ;; Declare Column View Code
4897 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4898 (declare-function org-columns-compute "org-colview" (property))
4900 ;; Declare ID code
4902 (declare-function org-id-store-link "org-id")
4903 (declare-function org-id-locations-load "org-id")
4904 (declare-function org-id-locations-save "org-id")
4905 (defvar org-id-track-globally)
4907 ;;; Variables for pre-computed regular expressions, all buffer local
4909 (defvar-local org-todo-regexp nil
4910 "Matches any of the TODO state keywords.")
4911 (defvar-local org-not-done-regexp nil
4912 "Matches any of the TODO state keywords except the last one.")
4913 (defvar-local org-not-done-heading-regexp nil
4914 "Matches a TODO headline that is not done.")
4915 (defvar-local org-todo-line-regexp nil
4916 "Matches a headline and puts TODO state into group 2 if present.")
4917 (defvar-local org-complex-heading-regexp nil
4918 "Matches a headline and puts everything into groups:
4919 group 1: the stars
4920 group 2: The todo keyword, maybe
4921 group 3: Priority cookie
4922 group 4: True headline
4923 group 5: Tags")
4924 (defvar-local org-complex-heading-regexp-format nil
4925 "Printf format to make regexp to match an exact headline.
4926 This regexp will match the headline of any node which has the
4927 exact headline text that is put into the format, but may have any
4928 TODO state, priority and tags.")
4929 (defvar-local org-todo-line-tags-regexp nil
4930 "Matches a headline and puts TODO state into group 2 if present.
4931 Also put tags into group 4 if tags are present.")
4933 (defconst org-plain-time-of-day-regexp
4934 (concat
4935 "\\(\\<[012]?[0-9]"
4936 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4937 "\\(--?"
4938 "\\(\\<[012]?[0-9]"
4939 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4940 "\\)?")
4941 "Regular expression to match a plain time or time range.
4942 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4943 groups carry important information:
4944 0 the full match
4945 1 the first time, range or not
4946 8 the second time, if it is a range.")
4948 (defconst org-plain-time-extension-regexp
4949 (concat
4950 "\\(\\<[012]?[0-9]"
4951 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4952 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4953 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4954 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4955 groups carry important information:
4956 0 the full match
4957 7 hours of duration
4958 9 minutes of duration")
4960 (defconst org-stamp-time-of-day-regexp
4961 (concat
4962 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4963 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4964 "\\(--?"
4965 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4966 "Regular expression to match a timestamp time or time range.
4967 After a match, the following groups carry important information:
4968 0 the full match
4969 1 date plus weekday, for back referencing to make sure both times are on the same day
4970 2 the first time, range or not
4971 4 the second time, if it is a range.")
4973 (defconst org-startup-options
4974 '(("fold" org-startup-folded t)
4975 ("overview" org-startup-folded t)
4976 ("nofold" org-startup-folded nil)
4977 ("showall" org-startup-folded nil)
4978 ("showeverything" org-startup-folded showeverything)
4979 ("content" org-startup-folded content)
4980 ("indent" org-startup-indented t)
4981 ("noindent" org-startup-indented nil)
4982 ("hidestars" org-hide-leading-stars t)
4983 ("showstars" org-hide-leading-stars nil)
4984 ("odd" org-odd-levels-only t)
4985 ("oddeven" org-odd-levels-only nil)
4986 ("align" org-startup-align-all-tables t)
4987 ("noalign" org-startup-align-all-tables nil)
4988 ("inlineimages" org-startup-with-inline-images t)
4989 ("noinlineimages" org-startup-with-inline-images nil)
4990 ("latexpreview" org-startup-with-latex-preview t)
4991 ("nolatexpreview" org-startup-with-latex-preview nil)
4992 ("customtime" org-display-custom-times t)
4993 ("logdone" org-log-done time)
4994 ("lognotedone" org-log-done note)
4995 ("nologdone" org-log-done nil)
4996 ("lognoteclock-out" org-log-note-clock-out t)
4997 ("nolognoteclock-out" org-log-note-clock-out nil)
4998 ("logrepeat" org-log-repeat state)
4999 ("lognoterepeat" org-log-repeat note)
5000 ("logdrawer" org-log-into-drawer t)
5001 ("nologdrawer" org-log-into-drawer nil)
5002 ("logstatesreversed" org-log-states-order-reversed t)
5003 ("nologstatesreversed" org-log-states-order-reversed nil)
5004 ("nologrepeat" org-log-repeat nil)
5005 ("logreschedule" org-log-reschedule time)
5006 ("lognotereschedule" org-log-reschedule note)
5007 ("nologreschedule" org-log-reschedule nil)
5008 ("logredeadline" org-log-redeadline time)
5009 ("lognoteredeadline" org-log-redeadline note)
5010 ("nologredeadline" org-log-redeadline nil)
5011 ("logrefile" org-log-refile time)
5012 ("lognoterefile" org-log-refile note)
5013 ("nologrefile" org-log-refile nil)
5014 ("fninline" org-footnote-define-inline t)
5015 ("nofninline" org-footnote-define-inline nil)
5016 ("fnlocal" org-footnote-section nil)
5017 ("fnauto" org-footnote-auto-label t)
5018 ("fnprompt" org-footnote-auto-label nil)
5019 ("fnconfirm" org-footnote-auto-label confirm)
5020 ("fnplain" org-footnote-auto-label plain)
5021 ("fnadjust" org-footnote-auto-adjust t)
5022 ("nofnadjust" org-footnote-auto-adjust nil)
5023 ("constcgs" constants-unit-system cgs)
5024 ("constSI" constants-unit-system SI)
5025 ("noptag" org-tag-persistent-alist nil)
5026 ("hideblocks" org-hide-block-startup t)
5027 ("nohideblocks" org-hide-block-startup nil)
5028 ("beamer" org-startup-with-beamer-mode t)
5029 ("entitiespretty" org-pretty-entities t)
5030 ("entitiesplain" org-pretty-entities nil))
5031 "Variable associated with STARTUP options for org-mode.
5032 Each element is a list of three items: the startup options (as written
5033 in the #+STARTUP line), the corresponding variable, and the value to set
5034 this variable to if the option is found. An optional forth element PUSH
5035 means to push this value onto the list in the variable.")
5037 (defcustom org-group-tags t
5038 "When non-nil (the default), use group tags.
5039 This can be turned on/off through `org-toggle-tags-groups'."
5040 :group 'org-tags
5041 :group 'org-startup
5042 :type 'boolean)
5044 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5046 (defun org-toggle-tags-groups ()
5047 "Toggle support for group tags.
5048 Support for group tags is controlled by the option
5049 `org-group-tags', which is non-nil by default."
5050 (interactive)
5051 (setq org-group-tags (not org-group-tags))
5052 (cond ((and (derived-mode-p 'org-agenda-mode)
5053 org-group-tags)
5054 (org-agenda-redo))
5055 ((derived-mode-p 'org-mode)
5056 (let ((org-inhibit-startup t)) (org-mode))))
5057 (message "Groups tags support has been turned %s"
5058 (if org-group-tags "on" "off")))
5060 (defun org-set-regexps-and-options (&optional tags-only)
5061 "Precompute regular expressions used in the current buffer.
5062 When optional argument TAGS-ONLY is non-nil, only compute tags
5063 related expressions."
5064 (when (derived-mode-p 'org-mode)
5065 (let ((alist (org--setup-collect-keywords
5066 (org-make-options-regexp
5067 (append '("FILETAGS" "TAGS" "SETUPFILE")
5068 (and (not tags-only)
5069 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5070 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5071 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5072 ;; Startup options. Get this early since it does change
5073 ;; behavior for other options (e.g., tags).
5074 (let ((startup (cdr (assq 'startup alist))))
5075 (dolist (option startup)
5076 (let ((entry (assoc-string option org-startup-options t)))
5077 (when entry
5078 (let ((var (nth 1 entry))
5079 (val (nth 2 entry)))
5080 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5081 (unless (listp (symbol-value var))
5082 (set (make-local-variable var) nil))
5083 (add-to-list var val)))))))
5084 (setq-local org-file-tags
5085 (mapcar #'org-add-prop-inherited
5086 (cdr (assq 'filetags alist))))
5087 (setq org-current-tag-alist
5088 (append org-tag-persistent-alist
5089 (let ((tags (cdr (assq 'tags alist))))
5090 (if tags (org-tag-string-to-alist tags)
5091 org-tag-alist))))
5092 (setq org-tag-groups-alist
5093 (org-tag-alist-to-groups org-current-tag-alist))
5094 (unless tags-only
5095 ;; File properties.
5096 (setq-local org-file-properties (cdr (assq 'property alist)))
5097 ;; Archive location.
5098 (let ((archive (cdr (assq 'archive alist))))
5099 (when archive (setq-local org-archive-location archive)))
5100 ;; Category.
5101 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5102 (when cat
5103 (setq-local org-category (intern cat))
5104 (setq-local org-file-properties
5105 (org--update-property-plist
5106 "CATEGORY" cat org-file-properties))))
5107 ;; Columns.
5108 (let ((column (cdr (assq 'columns alist))))
5109 (when column (setq-local org-columns-default-format column)))
5110 ;; Constants.
5111 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5112 ;; Link abbreviations.
5113 (let ((links (cdr (assq 'link alist))))
5114 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5115 ;; Priorities.
5116 (let ((priorities (cdr (assq 'priorities alist))))
5117 (when priorities
5118 (setq-local org-highest-priority (nth 0 priorities))
5119 (setq-local org-lowest-priority (nth 1 priorities))
5120 (setq-local org-default-priority (nth 2 priorities))))
5121 ;; Scripts.
5122 (let ((scripts (assq 'scripts alist)))
5123 (when scripts
5124 (setq-local org-use-sub-superscripts (cdr scripts))))
5125 ;; TODO keywords.
5126 (setq-local org-todo-kwd-alist nil)
5127 (setq-local org-todo-key-alist nil)
5128 (setq-local org-todo-key-trigger nil)
5129 (setq-local org-todo-keywords-1 nil)
5130 (setq-local org-done-keywords nil)
5131 (setq-local org-todo-heads nil)
5132 (setq-local org-todo-sets nil)
5133 (setq-local org-todo-log-states nil)
5134 (let ((todo-sequences
5135 (or (nreverse (cdr (assq 'todo alist)))
5136 (let ((d (default-value 'org-todo-keywords)))
5137 (if (not (stringp (car d))) d
5138 ;; XXX: Backward compatibility code.
5139 (list (cons org-todo-interpretation d)))))))
5140 (dolist (sequence todo-sequences)
5141 (let* ((sequence (or (run-hook-with-args-until-success
5142 'org-todo-setup-filter-hook sequence)
5143 sequence))
5144 (sequence-type (car sequence))
5145 (keywords (cdr sequence))
5146 (sep (member "|" keywords))
5147 names alist)
5148 (dolist (k (remove "|" keywords))
5149 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5151 (error "Invalid TODO keyword %s" k))
5152 (let ((name (match-string 1 k))
5153 (key (match-string 2 k))
5154 (log (org-extract-log-state-settings k)))
5155 (push name names)
5156 (push (cons name (and key (string-to-char key))) alist)
5157 (when log (push log org-todo-log-states))))
5158 (let* ((names (nreverse names))
5159 (done (if sep (org-remove-keyword-keys (cdr sep))
5160 (last names)))
5161 (head (car names))
5162 (tail (list sequence-type head (car done) (org-last done))))
5163 (add-to-list 'org-todo-heads head 'append)
5164 (push names org-todo-sets)
5165 (setq org-done-keywords (append org-done-keywords done nil))
5166 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5167 (setq org-todo-key-alist
5168 (append org-todo-key-alist
5169 (and alist
5170 (append '((:startgroup))
5171 (nreverse alist)
5172 '((:endgroup))))))
5173 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5174 (setq org-todo-sets (nreverse org-todo-sets)
5175 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5176 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5177 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5178 ;; Compute the regular expressions and other local variables.
5179 ;; Using `org-outline-regexp-bol' would complicate them much,
5180 ;; because of the fixed white space at the end of that string.
5181 (unless org-done-keywords
5182 (setq org-done-keywords
5183 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5184 (setq org-not-done-keywords
5185 (org-delete-all org-done-keywords
5186 (copy-sequence org-todo-keywords-1))
5187 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5188 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5189 org-not-done-heading-regexp
5190 (format org-heading-keyword-regexp-format org-not-done-regexp)
5191 org-todo-line-regexp
5192 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5193 org-complex-heading-regexp
5194 (concat "^\\(\\*+\\)"
5195 "\\(?: +" org-todo-regexp "\\)?"
5196 "\\(?: +\\(\\[#.\\]\\)\\)?"
5197 "\\(?: +\\(.*?\\)\\)??"
5198 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5199 "[ \t]*$")
5200 org-complex-heading-regexp-format
5201 (concat "^\\(\\*+\\)"
5202 "\\(?: +" org-todo-regexp "\\)?"
5203 "\\(?: +\\(\\[#.\\]\\)\\)?"
5204 "\\(?: +"
5205 ;; Stats cookies can be stuck to body.
5206 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5207 "\\(%s\\)"
5208 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5209 "\\)"
5210 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5211 "[ \t]*$")
5212 org-todo-line-tags-regexp
5213 (concat "^\\(\\*+\\)"
5214 "\\(?: +" org-todo-regexp "\\)?"
5215 "\\(?: +\\(.*?\\)\\)??"
5216 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5217 "[ \t]*$"))
5218 (org-compute-latex-and-related-regexp)))))
5220 (defun org--setup-collect-keywords (regexp &optional files alist)
5221 "Return setup keywords values as an alist.
5223 REGEXP matches a subset of setup keywords. FILES is a list of
5224 file names already visited. It is used to avoid circular setup
5225 files. ALIST, when non-nil, is the alist computed so far.
5227 Return value contains the following keys: `archive', `category',
5228 `columns', `constants', `filetags', `link', `priorities',
5229 `property', `scripts', `startup', `tags' and `todo'."
5230 (org-with-wide-buffer
5231 (goto-char (point-min))
5232 (let ((case-fold-search t))
5233 (while (re-search-forward regexp nil t)
5234 (let ((element (org-element-at-point)))
5235 (when (eq (org-element-type element) 'keyword)
5236 (let ((key (org-element-property :key element))
5237 (value (org-element-property :value element)))
5238 (cond
5239 ((equal key "ARCHIVE")
5240 (when (org-string-nw-p value)
5241 (push (cons 'archive value) alist)))
5242 ((equal key "CATEGORY") (push (cons 'category value) alist))
5243 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5244 ((equal key "CONSTANTS")
5245 (let* ((constants (assq 'constants alist))
5246 (store (cdr constants)))
5247 (dolist (pair (org-split-string value))
5248 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5249 pair)
5250 (let* ((name (match-string 1 pair))
5251 (value (match-string 2 pair))
5252 (old (assoc name store)))
5253 (if old (setcdr old value)
5254 (push (cons name value) store)))))
5255 (if constants (setcdr constants store)
5256 (push (cons 'constants store) alist))))
5257 ((equal key "FILETAGS")
5258 (when (org-string-nw-p value)
5259 (let ((old (assq 'filetags alist))
5260 (new (apply #'nconc
5261 (mapcar (lambda (x) (org-split-string x ":"))
5262 (org-split-string value)))))
5263 (if old (setcdr old (append new (cdr old)))
5264 (push (cons 'filetags new) alist)))))
5265 ((equal key "LINK")
5266 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5267 (let ((links (assq 'link alist))
5268 (pair (cons (match-string-no-properties 1 value)
5269 (match-string-no-properties 2 value))))
5270 (if links (push pair (cdr links))
5271 (push (list 'link pair) alist)))))
5272 ((equal key "OPTIONS")
5273 (when (and (org-string-nw-p value)
5274 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5275 (push (cons 'scripts (read (match-string 1 value))) alist)))
5276 ((equal key "PRIORITIES")
5277 (push (cons 'priorities
5278 (let ((prio (org-split-string value)))
5279 (if (< (length prio) 3) '(?A ?C ?B)
5280 (mapcar #'string-to-char prio))))
5281 alist))
5282 ((equal key "PROPERTY")
5283 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5284 (let* ((property (assq 'property alist))
5285 (value (org--update-property-plist
5286 (match-string-no-properties 1 value)
5287 (match-string-no-properties 2 value)
5288 (cdr property))))
5289 (if property (setcdr property value)
5290 (push (cons 'property value) alist)))))
5291 ((equal key "STARTUP")
5292 (let ((startup (assq 'startup alist)))
5293 (if startup
5294 (setcdr startup
5295 (append (cdr startup) (org-split-string value)))
5296 (push (cons 'startup (org-split-string value)) alist))))
5297 ((equal key "TAGS")
5298 (let ((tag-cell (assq 'tags alist)))
5299 (if tag-cell
5300 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5301 (push (cons 'tags value) alist))))
5302 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5303 (let ((todo (assq 'todo alist))
5304 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5305 (org-split-string value))))
5306 (if todo (push value (cdr todo))
5307 (push (list 'todo value) alist))))
5308 ((equal key "SETUPFILE")
5309 (unless buffer-read-only ; Do not check in Gnus messages.
5310 (let ((f (and (org-string-nw-p value)
5311 (expand-file-name
5312 (org-remove-double-quotes value)))))
5313 (when (and f (file-readable-p f) (not (member f files)))
5314 (with-temp-buffer
5315 (setq default-directory (file-name-directory f))
5316 (insert-file-contents f)
5317 (setq alist
5318 ;; Fake Org mode to benefit from cache
5319 ;; without recurring needlessly.
5320 (let ((major-mode 'org-mode))
5321 (org--setup-collect-keywords
5322 regexp (cons f files) alist)))))))))))))))
5323 alist)
5325 (defun org-tag-string-to-alist (s)
5326 "Return tag alist associated to string S.
5327 S is a value for TAGS keyword or produced with
5328 `org-tag-alist-to-string'. Return value is an alist suitable for
5329 `org-tag-alist' or `org-tag-persistent-alist'."
5330 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5331 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5332 "\\|{.+?}\\)" ; regular expression
5333 "\\(?:(\\(.\\))\\)?\\'"))
5334 alist group-flag)
5335 (dolist (tokens lines (cdr (nreverse alist)))
5336 (push '(:newline) alist)
5337 (while tokens
5338 (let ((token (pop tokens)))
5339 (pcase token
5340 ("{"
5341 (push '(:startgroup) alist)
5342 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5343 ("}"
5344 (push '(:endgroup) alist)
5345 (setq group-flag nil))
5346 ("["
5347 (push '(:startgrouptag) alist)
5348 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5349 ("]"
5350 (push '(:endgrouptag) alist)
5351 (setq group-flag nil))
5352 (":"
5353 (push '(:grouptags) alist))
5354 ((guard (string-match tag-re token))
5355 (let ((tag (match-string 1 token))
5356 (key (and (match-beginning 2)
5357 (string-to-char (match-string 2 token)))))
5358 ;; Push all tags in groups, no matter if they already
5359 ;; appear somewhere else in the list.
5360 (when (or group-flag (not (assoc tag alist)))
5361 (push (cons tag key) alist))))))))))
5363 (defun org-tag-alist-to-string (alist &optional skip-key)
5364 "Return tag string associated to ALIST.
5366 ALIST is an alist, as defined in `org-tag-alist' or
5367 `org-tag-persistent-alist', or produced with
5368 `org-tag-string-to-alist'.
5370 Return value is a string suitable as a value for \"TAGS\"
5371 keyword.
5373 When optional argument SKIP-KEY is non-nil, skip selection keys
5374 next to tags."
5375 (mapconcat (lambda (token)
5376 (pcase token
5377 (`(:startgroup) "{")
5378 (`(:endgroup) "}")
5379 (`(:startgrouptag) "[")
5380 (`(:endgrouptag) "]")
5381 (`(:grouptags) ":")
5382 (`(:newline) "\\n")
5383 ((and
5384 (guard (not skip-key))
5385 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5386 (format "%s(%c)" tag key))
5387 (`(,(and tag (pred stringp)) . ,_) tag)
5388 (_ (user-error "Invalid tag token: %S" token))))
5389 alist
5390 " "))
5392 (defun org-tag-alist-to-groups (alist)
5393 "Return group alist from tag ALIST.
5394 ALIST is an alist, as defined in `org-tag-alist' or
5395 `org-tag-persistent-alist', or produced with
5396 `org-tag-string-to-alist'. Return value is an alist following
5397 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5398 a string, summarizing TAGS, as a list of strings."
5399 (let (groups group-status current-group)
5400 (dolist (token alist (nreverse groups))
5401 (pcase token
5402 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5403 (`(,(or :endgroup :endgrouptag))
5404 (when (eq group-status 'append)
5405 (push (nreverse current-group) groups))
5406 (setq group-status nil))
5407 (`(:grouptags) (setq group-status 'append))
5408 ((and `(,tag . ,_) (guard group-status))
5409 (if (eq group-status 'append) (push tag current-group)
5410 (setq current-group (list tag))))
5411 (_ nil)))))
5413 (defun org-file-contents (file &optional noerror)
5414 "Return the contents of FILE, as a string."
5415 (if (and file (file-readable-p file))
5416 (with-temp-buffer
5417 (insert-file-contents file)
5418 (buffer-string))
5419 (funcall (if noerror 'message 'error)
5420 "Cannot read file \"%s\"%s"
5421 file
5422 (let ((from (buffer-file-name (buffer-base-buffer))))
5423 (if from (concat " (referenced in file \"" from "\")") "")))))
5425 (defun org-extract-log-state-settings (x)
5426 "Extract the log state setting from a TODO keyword string.
5427 This will extract info from a string like \"WAIT(w@/!)\"."
5428 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5429 (let ((kw (match-string 1 x))
5430 (log1 (and (match-end 3) (match-string 3 x)))
5431 (log2 (and (match-end 4) (match-string 4 x))))
5432 (and (or log1 log2)
5433 (list kw
5434 (and log1 (if (equal log1 "!") 'time 'note))
5435 (and log2 (if (equal log2 "!") 'time 'note)))))))
5437 (defun org-remove-keyword-keys (list)
5438 "Remove a pair of parenthesis at the end of each string in LIST."
5439 (mapcar (lambda (x)
5440 (if (string-match "(.*)$" x)
5441 (substring x 0 (match-beginning 0))
5443 list))
5445 (defun org-assign-fast-keys (alist)
5446 "Assign fast keys to a keyword-key alist.
5447 Respect keys that are already there."
5448 (let (new e (alt ?0))
5449 (while (setq e (pop alist))
5450 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5451 (cdr e)) ;; Key already assigned.
5452 (push e new)
5453 (let ((clist (string-to-list (downcase (car e))))
5454 (used (append new alist)))
5455 (when (= (car clist) ?@)
5456 (pop clist))
5457 (while (and clist (rassoc (car clist) used))
5458 (pop clist))
5459 (unless clist
5460 (while (rassoc alt used)
5461 (cl-incf alt)))
5462 (push (cons (car e) (or (car clist) alt)) new))))
5463 (nreverse new)))
5465 ;;; Some variables used in various places
5467 (defvar org-window-configuration nil
5468 "Used in various places to store a window configuration.")
5469 (defvar org-selected-window nil
5470 "Used in various places to store a window configuration.")
5471 (defvar org-finish-function nil
5472 "Function to be called when `C-c C-c' is used.
5473 This is for getting out of special buffers like capture.")
5474 (defvar org-last-state)
5476 ;; Defined somewhere in this file, but used before definition.
5477 (defvar org-entities) ;; defined in org-entities.el
5478 (defvar org-struct-menu)
5479 (defvar org-org-menu)
5480 (defvar org-tbl-menu)
5482 ;;;; Define the Org mode
5484 ;; We use a before-change function to check if a table might need
5485 ;; an update.
5486 (defvar org-table-may-need-update t
5487 "Indicates that a table might need an update.
5488 This variable is set by `org-before-change-function'.
5489 `org-table-align' sets it back to nil.")
5490 (defun org-before-change-function (_beg _end)
5491 "Every change indicates that a table might need an update."
5492 (setq org-table-may-need-update t))
5493 (defvar org-mode-map)
5494 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5495 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5496 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5497 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5498 (defvar org-table-buffer-is-an nil)
5500 (defvar bidi-paragraph-direction)
5501 (defvar buffer-face-mode-face)
5503 (require 'outline)
5505 ;; Other stuff we need.
5506 (require 'time-date)
5507 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5508 (require 'easymenu)
5509 (autoload 'easy-menu-add "easymenu")
5510 (require 'overlay)
5512 ;; (require 'org-macs) moved higher up in the file before it is first used
5513 (require 'org-entities)
5514 ;; (require 'org-compat) moved higher up in the file before it is first used
5515 (require 'org-faces)
5516 (require 'org-list)
5517 (require 'org-pcomplete)
5518 (require 'org-src)
5519 (require 'org-footnote)
5520 (require 'org-macro)
5522 ;; babel
5523 (require 'ob)
5525 ;;;###autoload
5526 (define-derived-mode org-mode outline-mode "Org"
5527 "Outline-based notes management and organizer, alias
5528 \"Carsten's outline-mode for keeping track of everything.\"
5530 Org mode develops organizational tasks around a NOTES file which
5531 contains information about projects as plain text. Org mode is
5532 implemented on top of Outline mode, which is ideal to keep the content
5533 of large files well structured. It supports ToDo items, deadlines and
5534 time stamps, which magically appear in the diary listing of the Emacs
5535 calendar. Tables are easily created with a built-in table editor.
5536 Plain text URL-like links connect to websites, emails (VM), Usenet
5537 messages (Gnus), BBDB entries, and any files related to the project.
5538 For printing and sharing of notes, an Org file (or a part of it)
5539 can be exported as a structured ASCII or HTML file.
5541 The following commands are available:
5543 \\{org-mode-map}"
5545 ;; Get rid of Outline menus, they are not needed
5546 ;; Need to do this here because define-derived-mode sets up
5547 ;; the keymap so late. Still, it is a waste to call this each time
5548 ;; we switch another buffer into Org mode.
5549 (define-key org-mode-map [menu-bar headings] 'undefined)
5550 (define-key org-mode-map [menu-bar hide] 'undefined)
5551 (define-key org-mode-map [menu-bar show] 'undefined)
5553 (org-load-modules-maybe)
5554 (org-install-agenda-files-menu)
5555 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5556 (add-to-invisibility-spec '(org-cwidth))
5557 (add-to-invisibility-spec '(org-hide-block . t))
5558 (setq-local outline-regexp org-outline-regexp)
5559 (setq-local outline-level 'org-outline-level)
5560 (setq bidi-paragraph-direction 'left-to-right)
5561 (when (and org-ellipsis
5562 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5563 (fboundp 'make-glyph-code))
5564 (unless org-display-table
5565 (setq org-display-table (make-display-table)))
5566 (set-display-table-slot
5567 org-display-table 4
5568 (vconcat (mapcar
5569 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5570 org-ellipsis)))
5571 (if (stringp org-ellipsis) org-ellipsis "..."))))
5572 (setq buffer-display-table org-display-table))
5573 (org-set-regexps-and-options)
5574 (org-set-font-lock-defaults)
5575 (when (and org-tag-faces (not org-tags-special-faces-re))
5576 ;; tag faces set outside customize.... force initialization.
5577 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5578 ;; Calc embedded
5579 (setq-local calc-embedded-open-mode "# ")
5580 ;; Modify a few syntax entries
5581 (modify-syntax-entry ?@ "w")
5582 (modify-syntax-entry ?\" "\"")
5583 (modify-syntax-entry ?\\ "_")
5584 (modify-syntax-entry ?~ "_")
5585 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5586 ;; Activate before-change-function
5587 (setq-local org-table-may-need-update t)
5588 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5589 ;; Check for running clock before killing a buffer
5590 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5591 ;; Initialize macros templates.
5592 (org-macro-initialize-templates)
5593 ;; Initialize radio targets.
5594 (org-update-radio-target-regexp)
5595 ;; Indentation.
5596 (setq-local indent-line-function 'org-indent-line)
5597 (setq-local indent-region-function 'org-indent-region)
5598 ;; Filling and auto-filling.
5599 (org-setup-filling)
5600 ;; Comments.
5601 (org-setup-comments-handling)
5602 ;; Initialize cache.
5603 (org-element-cache-reset)
5604 ;; Beginning/end of defun
5605 (setq-local beginning-of-defun-function 'org-backward-element)
5606 (setq-local end-of-defun-function
5607 (lambda ()
5608 (if (not (org-at-heading-p))
5609 (org-forward-element)
5610 (org-forward-element)
5611 (forward-char -1))))
5612 ;; Next error for sparse trees
5613 (setq-local next-error-function 'org-occur-next-match)
5614 ;; Make sure dependence stuff works reliably, even for users who set it
5615 ;; too late :-(
5616 (if org-enforce-todo-dependencies
5617 (add-hook 'org-blocker-hook
5618 'org-block-todo-from-children-or-siblings-or-parent)
5619 (remove-hook 'org-blocker-hook
5620 'org-block-todo-from-children-or-siblings-or-parent))
5621 (if org-enforce-todo-checkbox-dependencies
5622 (add-hook 'org-blocker-hook
5623 'org-block-todo-from-checkboxes)
5624 (remove-hook 'org-blocker-hook
5625 'org-block-todo-from-checkboxes))
5627 ;; Align options lines
5628 (setq-local
5629 align-mode-rules-list
5630 '((org-in-buffer-settings
5631 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5632 (modes . '(org-mode)))))
5634 ;; Imenu
5635 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5637 ;; Make isearch reveal context
5638 (setq-local outline-isearch-open-invisible-function
5639 (lambda (&rest _) (org-show-context 'isearch)))
5641 ;; Setup the pcomplete hooks
5642 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5643 (setq-local pcomplete-command-name-function 'org-command-at-point)
5644 (setq-local pcomplete-default-completion-function 'ignore)
5645 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5646 (setq-local pcomplete-termination-string "")
5647 (setq-local buffer-face-mode-face 'org-default)
5649 ;; If empty file that did not turn on Org mode automatically, make
5650 ;; it to.
5651 (when (and org-insert-mode-line-in-empty-file
5652 (called-interactively-p 'any)
5653 (= (point-min) (point-max)))
5654 (insert "# -*- mode: org -*-\n\n"))
5655 (unless org-inhibit-startup
5656 (org-unmodified
5657 (when org-startup-with-beamer-mode (org-beamer-mode))
5658 (when org-startup-align-all-tables
5659 (org-table-map-tables #'org-table-align t))
5660 (when org-startup-with-inline-images (org-display-inline-images))
5661 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5662 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5663 (when org-startup-truncated (setq truncate-lines t))
5664 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5665 (org-refresh-effort-properties)))
5666 ;; Try to set `org-hide' face correctly.
5667 (let ((foreground (org-find-invisible-foreground)))
5668 (when foreground
5669 (set-face-foreground 'org-hide foreground))))
5671 ;; Update `customize-package-emacs-version-alist'
5672 (add-to-list 'customize-package-emacs-version-alist
5673 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5674 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5675 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5677 (defvar org-mode-transpose-word-syntax-table
5678 (let ((st (make-syntax-table text-mode-syntax-table)))
5679 (dolist (c org-emphasis-alist st)
5680 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5682 (when (fboundp 'abbrev-table-put)
5683 (abbrev-table-put org-mode-abbrev-table
5684 :parents (list text-mode-abbrev-table)))
5686 (defun org-find-invisible-foreground ()
5687 (let ((candidates (remove
5688 "unspecified-bg"
5689 (nconc
5690 (list (face-background 'default)
5691 (face-background 'org-default))
5692 (mapcar
5693 (lambda (alist)
5694 (when (boundp alist)
5695 (cdr (assoc 'background-color (symbol-value alist)))))
5696 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5697 (list (face-foreground 'org-hide))))))
5698 (car (remove nil candidates))))
5700 (defun org-current-time (&optional rounding-minutes past)
5701 "Current time, possibly rounded to ROUNDING-MINUTES.
5702 When ROUNDING-MINUTES is not an integer, fall back on the car of
5703 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5704 the rounding returns a past time."
5705 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5706 (car org-time-stamp-rounding-minutes)))
5707 (time (decode-time)) res)
5708 (if (< r 1)
5709 (current-time)
5710 (setq res
5711 (apply 'encode-time
5712 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5713 (nthcdr 2 time))))
5714 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5715 (seconds-to-time (- (float-time res) (* r 60)))
5716 res))))
5718 (defun org-today ()
5719 "Return today date, considering `org-extend-today-until'."
5720 (time-to-days
5721 (time-subtract (current-time)
5722 (list 0 (* 3600 org-extend-today-until) 0))))
5724 ;;;; Font-Lock stuff, including the activators
5726 (defvar org-mouse-map (make-sparse-keymap))
5727 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5728 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5729 (when org-mouse-1-follows-link
5730 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5731 (when org-tab-follows-link
5732 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5733 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5735 (require 'font-lock)
5737 (defconst org-non-link-chars "]\t\n\r<>")
5738 (defvar org-link-types-re nil
5739 "Matches a link that has a url-like prefix like \"http:\"")
5740 (defvar org-link-re-with-space nil
5741 "Matches a link with spaces, optional angular brackets around it.")
5742 (defvar org-link-re-with-space2 nil
5743 "Matches a link with spaces, optional angular brackets around it.")
5744 (defvar org-link-re-with-space3 nil
5745 "Matches a link with spaces, only for internal part in bracket links.")
5746 (defvar org-angle-link-re nil
5747 "Matches link with angular brackets, spaces are allowed.")
5748 (defvar org-plain-link-re nil
5749 "Matches plain link, without spaces.")
5750 (defvar org-bracket-link-regexp nil
5751 "Matches a link in double brackets.")
5752 (defvar org-bracket-link-analytic-regexp nil
5753 "Regular expression used to analyze links.
5754 Here is what the match groups contain after a match:
5755 1: http:
5756 2: http
5757 3: path
5758 4: [desc]
5759 5: desc")
5760 (defvar org-bracket-link-analytic-regexp++ nil
5761 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5762 (defvar org-any-link-re nil
5763 "Regular expression matching any link.")
5765 (defconst org-match-sexp-depth 3
5766 "Number of stacked braces for sub/superscript matching.")
5768 (defun org-create-multibrace-regexp (left right n)
5769 "Create a regular expression which will match a balanced sexp.
5770 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5771 as single character strings.
5772 The regexp returned will match the entire expression including the
5773 delimiters. It will also define a single group which contains the
5774 match except for the outermost delimiters. The maximum depth of
5775 stacked delimiters is N. Escaping delimiters is not possible."
5776 (let* ((nothing (concat "[^" left right "]*?"))
5777 (or "\\|")
5778 (re nothing)
5779 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5780 (while (> n 1)
5781 (setq n (1- n)
5782 re (concat re or next)
5783 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5784 (concat left "\\(" re "\\)" right)))
5786 (defconst org-match-substring-regexp
5787 (concat
5788 "\\(\\S-\\)\\([_^]\\)\\("
5789 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5790 "\\|"
5791 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5792 "\\|"
5793 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5794 "The regular expression matching a sub- or superscript.")
5796 (defconst org-match-substring-with-braces-regexp
5797 (concat
5798 "\\(\\S-\\)\\([_^]\\)"
5799 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5800 "The regular expression matching a sub- or superscript, forcing braces.")
5802 (defun org-make-link-regexps ()
5803 "Update the link regular expressions.
5804 This should be called after the variable `org-link-parameters' has changed."
5805 (let ((types-re (regexp-opt (org-link-types) t)))
5806 (setq org-link-types-re
5807 (concat "\\`" types-re ":")
5808 org-link-re-with-space
5809 (concat "<?" types-re ":"
5810 "\\([^" org-non-link-chars " ]"
5811 "[^" org-non-link-chars "]*"
5812 "[^" org-non-link-chars " ]\\)>?")
5813 org-link-re-with-space2
5814 (concat "<?" types-re ":"
5815 "\\([^" org-non-link-chars " ]"
5816 "[^\t\n\r]*"
5817 "[^" org-non-link-chars " ]\\)>?")
5818 org-link-re-with-space3
5819 (concat "<?" types-re ":"
5820 "\\([^" org-non-link-chars " ]"
5821 "[^\t\n\r]*\\)")
5822 org-angle-link-re
5823 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5824 types-re)
5825 org-plain-link-re
5826 (concat
5827 "\\<" types-re ":"
5828 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5829 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5830 org-bracket-link-regexp
5831 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5832 org-bracket-link-analytic-regexp
5833 (concat
5834 "\\[\\["
5835 "\\(" types-re ":\\)?"
5836 "\\([^]]+\\)"
5837 "\\]"
5838 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5839 "\\]")
5840 org-bracket-link-analytic-regexp++
5841 (concat
5842 "\\[\\["
5843 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5844 "\\([^]]+\\)"
5845 "\\]"
5846 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5847 "\\]")
5848 org-any-link-re
5849 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5850 org-angle-link-re "\\)\\|\\("
5851 org-plain-link-re "\\)"))))
5853 (org-make-link-regexps)
5855 (defvar org-emph-face nil)
5857 (defun org-do-emphasis-faces (limit)
5858 "Run through the buffer and emphasize strings."
5859 (let (rtn a)
5860 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5861 (let* ((border (char-after (match-beginning 3)))
5862 (bre (regexp-quote (char-to-string border))))
5863 (when (and (not (= border (char-after (match-beginning 4))))
5864 (not (string-match-p (concat bre ".*" bre)
5865 (replace-regexp-in-string
5866 "\n" " "
5867 (substring (match-string 2) 1 -1)))))
5868 (setq rtn t)
5869 (setq a (assoc (match-string 3) org-emphasis-alist))
5870 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5871 'face
5872 (nth 1 a))
5873 (and (nth 2 a)
5874 (org-remove-flyspell-overlays-in
5875 (match-beginning 0) (match-end 0)))
5876 (add-text-properties (match-beginning 2) (match-end 2)
5877 '(font-lock-multiline t org-emphasis t))
5878 (when org-hide-emphasis-markers
5879 (add-text-properties (match-end 4) (match-beginning 5)
5880 '(invisible org-link))
5881 (add-text-properties (match-beginning 3) (match-end 3)
5882 '(invisible org-link)))))
5883 (goto-char (1+ (match-beginning 0))))
5884 rtn))
5886 (defun org-emphasize (&optional char)
5887 "Insert or change an emphasis, i.e. a font like bold or italic.
5888 If there is an active region, change that region to a new emphasis.
5889 If there is no region, just insert the marker characters and position
5890 the cursor between them.
5891 CHAR should be the marker character. If it is a space, it means to
5892 remove the emphasis of the selected region.
5893 If CHAR is not given (for example in an interactive call) it will be
5894 prompted for."
5895 (interactive)
5896 (let ((erc org-emphasis-regexp-components)
5897 (string "") beg end move s)
5898 (if (org-region-active-p)
5899 (setq beg (region-beginning)
5900 end (region-end)
5901 string (buffer-substring beg end))
5902 (setq move t))
5904 (unless char
5905 (message "Emphasis marker or tag: [%s]"
5906 (mapconcat #'car org-emphasis-alist ""))
5907 (setq char (read-char-exclusive)))
5908 (if (equal char ?\s)
5909 (setq s ""
5910 move nil)
5911 (unless (assoc (char-to-string char) org-emphasis-alist)
5912 (user-error "No such emphasis marker: \"%c\"" char))
5913 (setq s (char-to-string char)))
5914 (while (and (> (length string) 1)
5915 (equal (substring string 0 1) (substring string -1))
5916 (assoc (substring string 0 1) org-emphasis-alist))
5917 (setq string (substring string 1 -1)))
5918 (setq string (concat s string s))
5919 (when beg (delete-region beg end))
5920 (unless (or (bolp)
5921 (string-match (concat "[" (nth 0 erc) "\n]")
5922 (char-to-string (char-before (point)))))
5923 (insert " "))
5924 (unless (or (eobp)
5925 (string-match (concat "[" (nth 1 erc) "\n]")
5926 (char-to-string (char-after (point)))))
5927 (insert " ") (backward-char 1))
5928 (insert string)
5929 (and move (backward-char 1))))
5931 (defconst org-nonsticky-props
5932 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5934 (defsubst org-rear-nonsticky-at (pos)
5935 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5937 (defun org-activate-plain-links (limit)
5938 "Add link properties for plain links."
5939 (when (and (re-search-forward org-plain-link-re limit t)
5940 (not (org-in-src-block-p)))
5942 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5943 'face))
5944 (link (match-string-no-properties 0))
5945 (type (match-string-no-properties 1))
5946 (path (match-string-no-properties 2))
5947 (link-start (match-beginning 0))
5948 (link-end (match-end 0))
5949 (link-face (org-link-get-parameter type :face))
5950 (help-echo (org-link-get-parameter type :help-echo))
5951 (htmlize-link (org-link-get-parameter type :htmlize-link))
5952 (activate-func (org-link-get-parameter type :activate-func)))
5953 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5954 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5955 (add-text-properties (match-beginning 0) (match-end 0)
5956 (list
5957 'mouse-face (or (org-link-get-parameter type :mouse-face)
5958 'highlight)
5959 'face (cond
5960 ;; A function that returns a face
5961 ((functionp link-face)
5962 (funcall link-face path))
5963 ;; a face
5964 ((facep link-face)
5965 link-face)
5966 ;; An anonymous face
5967 ((consp link-face)
5968 link-face)
5969 ;; default
5971 'org-link))
5972 'help-echo (cond
5973 ((stringp help-echo)
5974 help-echo)
5975 ((functionp help-echo)
5976 help-echo)
5978 (concat "LINK: "
5979 (save-match-data
5980 (org-link-unescape link)))))
5981 'htmlize-link (cond
5982 ((functionp htmlize-link)
5983 (funcall htmlize-link path))
5985 `(:uri ,link)))
5986 'keymap (or (org-link-get-parameter type :keymap)
5987 org-mouse-map)
5988 'org-link-start (match-beginning 0)))
5989 (org-rear-nonsticky-at (match-end 0))
5990 (when activate-func
5991 (funcall activate-func link-start link-end path nil))
5992 t))))
5994 (defun org-activate-code (limit)
5995 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5996 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5997 (remove-text-properties (match-beginning 0) (match-end 0)
5998 '(display t invisible t intangible t))
6001 (defcustom org-src-fontify-natively t
6002 "When non-nil, fontify code in code blocks.
6003 See also the `org-block' face."
6004 :type 'boolean
6005 :version "24.4"
6006 :package-version '(Org . "8.3")
6007 :group 'org-appearance
6008 :group 'org-babel)
6010 (defcustom org-allow-promoting-top-level-subtree nil
6011 "When non-nil, allow promoting a top level subtree.
6012 The leading star of the top level headline will be replaced
6013 by a #."
6014 :type 'boolean
6015 :version "24.1"
6016 :group 'org-appearance)
6018 (defun org-fontify-meta-lines-and-blocks (limit)
6019 (condition-case nil
6020 (org-fontify-meta-lines-and-blocks-1 limit)
6021 (error (message "org-mode fontification error in %S at %d"
6022 (current-buffer)
6023 (line-number-at-pos)))))
6025 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6026 "Fontify #+ lines and blocks."
6027 (let ((case-fold-search t))
6028 (when (re-search-forward
6029 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6030 limit t)
6031 (let ((beg (match-beginning 0))
6032 (block-start (match-end 0))
6033 (block-end nil)
6034 (lang (match-string 7))
6035 (beg1 (line-beginning-position 2))
6036 (dc1 (downcase (match-string 2)))
6037 (dc3 (downcase (match-string 3)))
6038 end end1 quoting block-type)
6039 (cond
6040 ((and (match-end 4) (equal dc3 "+begin"))
6041 ;; Truly a block
6042 (setq block-type (downcase (match-string 5))
6043 quoting (member block-type org-protecting-blocks))
6044 (when (re-search-forward
6045 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6046 nil t) ;; on purpose, we look further than LIMIT
6047 (setq end (min (point-max) (match-end 0))
6048 end1 (min (point-max) (1- (match-beginning 0))))
6049 (setq block-end (match-beginning 0))
6050 (when quoting
6051 (org-remove-flyspell-overlays-in beg1 end1)
6052 (remove-text-properties beg end
6053 '(display t invisible t intangible t)))
6054 (add-text-properties
6055 beg end '(font-lock-fontified t font-lock-multiline t))
6056 (add-text-properties beg beg1 '(face org-meta-line))
6057 (org-remove-flyspell-overlays-in beg beg1)
6058 (add-text-properties ; For end_src
6059 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6060 (org-remove-flyspell-overlays-in end1 end)
6061 (cond
6062 ((and lang (not (string= lang "")) org-src-fontify-natively)
6063 (org-src-font-lock-fontify-block lang block-start block-end)
6064 (add-text-properties beg1 block-end '(src-block t)))
6065 (quoting
6066 (add-text-properties beg1 (min (point-max) (1+ end1))
6067 (list 'face
6068 (list :inherit
6069 (let ((face-name
6070 (intern (format "org-block-%s" lang))))
6071 (append (and (facep face-name) (list face-name))
6072 '(org-block))))))) ; end of source block
6073 ((not org-fontify-quote-and-verse-blocks))
6074 ((string= block-type "quote")
6075 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
6076 ((string= block-type "verse")
6077 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
6078 (add-text-properties beg beg1 '(face org-block-begin-line))
6079 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6080 '(face org-block-end-line))
6082 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6083 (org-remove-flyspell-overlays-in
6084 (match-beginning 0)
6085 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6086 (add-text-properties
6087 beg (match-end 3)
6088 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6089 '(font-lock-fontified t invisible t)
6090 '(font-lock-fontified t face org-document-info-keyword)))
6091 (add-text-properties
6092 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6093 (if (string-equal dc1 "+title:")
6094 '(font-lock-fontified t face org-document-title)
6095 '(font-lock-fontified t face org-document-info))))
6096 ((equal dc1 "+caption:")
6097 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6098 (remove-text-properties (match-beginning 0) (match-end 0)
6099 '(display t invisible t intangible t))
6100 (add-text-properties (match-beginning 1) (match-end 3)
6101 '(font-lock-fontified t face org-meta-line))
6102 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
6103 '(font-lock-fontified t face org-block))
6105 ((member dc3 '(" " ""))
6106 (org-remove-flyspell-overlays-in beg (match-end 0))
6107 (add-text-properties
6108 beg (match-end 0)
6109 '(font-lock-fontified t face font-lock-comment-face)))
6110 (t ;; just any other in-buffer setting, but not indented
6111 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6112 (remove-text-properties (match-beginning 0) (match-end 0)
6113 '(display t invisible t intangible t))
6114 (add-text-properties beg (match-end 0)
6115 '(font-lock-fontified t face org-meta-line))
6116 t))))))
6118 (defun org-fontify-drawers (limit)
6119 "Fontify drawers."
6120 (when (re-search-forward org-drawer-regexp limit t)
6121 (add-text-properties
6122 (match-beginning 0) (match-end 0)
6123 '(font-lock-fontified t face org-special-keyword))
6124 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6127 (defun org-fontify-macros (limit)
6128 "Fontify macros."
6129 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6130 (add-text-properties
6131 (match-beginning 0) (match-end 0)
6132 '(font-lock-fontified t face org-macro))
6133 (when org-hide-macro-markers
6134 (add-text-properties (match-end 2) (match-beginning 2)
6135 '(invisible t))
6136 (add-text-properties (match-beginning 1) (match-end 1)
6137 '(invisible t)))
6138 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6141 (defun org-activate-angle-links (limit)
6142 "Add text properties for angle links."
6143 (when (and (re-search-forward org-angle-link-re limit t)
6144 (not (org-in-src-block-p)))
6145 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6146 (add-text-properties (match-beginning 0) (match-end 0)
6147 (list 'mouse-face 'highlight
6148 'keymap org-mouse-map
6149 'font-lock-multiline t))
6150 (org-rear-nonsticky-at (match-end 0))
6153 (defun org-activate-footnote-links (limit)
6154 "Add text properties for footnotes."
6155 (let ((fn (org-footnote-next-reference-or-definition limit)))
6156 (when fn
6157 (let* ((beg (nth 1 fn))
6158 (end (nth 2 fn))
6159 (label (car fn))
6160 (referencep (/= (line-beginning-position) beg)))
6161 (when (and referencep (nth 3 fn))
6162 (save-excursion
6163 (goto-char beg)
6164 (search-forward (or label "fn:"))
6165 (org-remove-flyspell-overlays-in beg (match-end 0))))
6166 (add-text-properties beg end
6167 (list 'mouse-face 'highlight
6168 'keymap org-mouse-map
6169 'help-echo
6170 (if referencep "Footnote reference"
6171 "Footnote definition")
6172 'font-lock-fontified t
6173 'font-lock-multiline t
6174 'face 'org-footnote))))))
6176 (defun org-activate-bracket-links (limit)
6177 "Add text properties for bracketed links."
6178 (when (and (re-search-forward org-bracket-link-regexp limit t)
6179 (not (org-in-src-block-p)))
6180 (let* ((hl (save-match-data
6181 (org-link-expand-abbrev (match-string-no-properties 1))))
6182 (type (save-match-data
6183 (and (string-match org-plain-link-re hl)
6184 (match-string-no-properties 1 hl))))
6185 (path (save-match-data
6186 (and (string-match org-plain-link-re hl)
6187 (match-string-no-properties 2 hl))))
6188 (link-start (match-beginning 0))
6189 (link-end (match-end 0))
6190 (bracketp t)
6191 (help-echo (org-link-get-parameter type :help-echo))
6192 (help (cond
6193 ((stringp help-echo)
6194 help-echo)
6195 ((functionp help-echo)
6196 help-echo)
6198 (concat "LINK: "
6199 (save-match-data
6200 (org-link-unescape hl))))))
6201 (link-face (org-link-get-parameter type :face))
6202 (face (cond
6203 ;; A function that returns a face
6204 ((functionp link-face)
6205 (funcall link-face path))
6206 ;; a face
6207 ((facep link-face)
6208 link-face)
6209 ;; An anonymous face
6210 ((consp link-face)
6211 link-face)
6212 ;; default
6214 'org-link)))
6215 (keymap (or (org-link-get-parameter type :keymap)
6216 org-mouse-map))
6217 (mouse-face (or (org-link-get-parameter type :mouse-face)
6218 'highlight))
6219 (htmlize (org-link-get-parameter type :htmlize-link))
6220 (htmlize-link (cond
6221 ((functionp htmlize)
6222 (funcall htmlize))
6224 `(:uri ,(format "%s:%s" type path)))))
6225 (activate-func (org-link-get-parameter type :activate-func))
6226 ;; invisible part
6227 (ip (list 'invisible (or
6228 (org-link-get-parameter type :display)
6229 'org-link)
6230 'face face
6231 'keymap keymap
6232 'mouse-face mouse-face
6233 'font-lock-multiline t
6234 'help-echo help
6235 'htmlize-link htmlize-link))
6236 ;; visible part
6237 (vp (list 'keymap keymap
6238 'face face
6239 'mouse-face mouse-face
6240 'font-lock-multiline t
6241 'help-echo help
6242 'htmlize-link htmlize-link)))
6243 ;; We need to remove the invisible property here. Table narrowing
6244 ;; may have made some of this invisible.
6245 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6246 (remove-text-properties (match-beginning 0) (match-end 0)
6247 '(invisible nil))
6248 (if (match-end 3)
6249 (progn
6250 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6251 (org-rear-nonsticky-at (match-beginning 3))
6252 (add-text-properties (match-beginning 3) (match-end 3) vp)
6253 (org-rear-nonsticky-at (match-end 3))
6254 (add-text-properties (match-end 3) (match-end 0) ip)
6255 (org-rear-nonsticky-at (match-end 0)))
6256 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6257 (org-rear-nonsticky-at (match-beginning 1))
6258 (add-text-properties (match-beginning 1) (match-end 1) vp)
6259 (org-rear-nonsticky-at (match-end 1))
6260 (add-text-properties (match-end 1) (match-end 0) ip)
6261 (org-rear-nonsticky-at (match-end 0)))
6262 (when activate-func
6263 (funcall activate-func link-start link-end path bracketp))
6264 t)))
6266 (defun org-activate-dates (limit)
6267 "Add text properties for dates."
6268 (when (and (re-search-forward org-tsr-regexp-both limit t)
6269 (not (equal (char-before (match-beginning 0)) 91)))
6270 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6271 (add-text-properties (match-beginning 0) (match-end 0)
6272 (list 'mouse-face 'highlight
6273 'keymap org-mouse-map))
6274 (org-rear-nonsticky-at (match-end 0))
6275 (when org-display-custom-times
6276 (if (match-end 3)
6277 (org-display-custom-time (match-beginning 3) (match-end 3))
6278 (org-display-custom-time (match-beginning 1) (match-end 1))))
6281 (defvar-local org-target-link-regexp nil
6282 "Regular expression matching radio targets in plain text.")
6284 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6285 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6286 border border border))
6287 "Regular expression matching a link target.")
6289 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6290 "Regular expression matching a radio target.")
6292 (defconst org-any-target-regexp
6293 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6294 "Regular expression matching any target.")
6296 (defun org-activate-target-links (limit)
6297 "Add text properties for target matches."
6298 (when org-target-link-regexp
6299 (let ((case-fold-search t))
6300 (when (re-search-forward org-target-link-regexp limit t)
6301 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6302 (add-text-properties (match-beginning 1) (match-end 1)
6303 (list 'mouse-face 'highlight
6304 'keymap org-mouse-map
6305 'help-echo "Radio target link"
6306 'org-linked-text t))
6307 (org-rear-nonsticky-at (match-end 1))
6308 t))))
6310 (defun org-update-radio-target-regexp ()
6311 "Find all radio targets in this file and update the regular expression.
6312 Also refresh fontification if needed."
6313 (interactive)
6314 (let ((old-regexp org-target-link-regexp)
6315 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6316 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6317 (targets
6318 (org-with-wide-buffer
6319 (goto-char (point-min))
6320 (let (rtn)
6321 (while (re-search-forward org-radio-target-regexp nil t)
6322 ;; Make sure point is really within the object.
6323 (backward-char)
6324 (let ((obj (org-element-context)))
6325 (when (eq (org-element-type obj) 'radio-target)
6326 (cl-pushnew (org-element-property :value obj) rtn
6327 :test #'equal))))
6328 rtn))))
6329 (setq org-target-link-regexp
6330 (and targets
6331 (concat before-re
6332 (mapconcat
6333 (lambda (x)
6334 (replace-regexp-in-string
6335 " +" "\\s-+" (regexp-quote x) t t))
6336 targets
6337 "\\|")
6338 after-re)))
6339 (unless (equal old-regexp org-target-link-regexp)
6340 ;; Clean-up cache.
6341 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6342 ((not org-target-link-regexp) old-regexp)
6344 (concat before-re
6345 (mapconcat
6346 (lambda (re)
6347 (substring re (length before-re)
6348 (- (length after-re))))
6349 (list old-regexp org-target-link-regexp)
6350 "\\|")
6351 after-re)))))
6352 (org-with-wide-buffer
6353 (goto-char (point-min))
6354 (while (re-search-forward regexp nil t)
6355 (org-element-cache-refresh (match-beginning 1)))))
6356 ;; Re fontify buffer.
6357 (when (memq 'radio org-highlight-links)
6358 (org-restart-font-lock)))))
6360 (defun org-hide-wide-columns (limit)
6361 (let (s e)
6362 (setq s (text-property-any (point) (or limit (point-max))
6363 'org-cwidth t))
6364 (when s
6365 (setq e (next-single-property-change s 'org-cwidth))
6366 (add-text-properties s e '(invisible org-cwidth))
6367 (goto-char e)
6368 t)))
6370 (defvar org-latex-and-related-regexp nil
6371 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6373 (defun org-compute-latex-and-related-regexp ()
6374 "Compute regular expression for LaTeX, entities and sub/superscript.
6375 Result depends on variable `org-highlight-latex-and-related'."
6376 (setq-local
6377 org-latex-and-related-regexp
6378 (let* ((re-sub
6379 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6380 ((eq org-use-sub-superscripts '{})
6381 (list org-match-substring-with-braces-regexp))
6382 (org-use-sub-superscripts (list org-match-substring-regexp))))
6383 (re-latex
6384 (when (memq 'latex org-highlight-latex-and-related)
6385 (let ((matchers (plist-get org-format-latex-options :matchers)))
6386 (delq nil
6387 (mapcar (lambda (x)
6388 (and (member (car x) matchers) (nth 1 x)))
6389 org-latex-regexps)))))
6390 (re-entities
6391 (when (memq 'entities org-highlight-latex-and-related)
6392 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6393 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6395 (defun org-do-latex-and-related (limit)
6396 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6397 LIMIT bounds the search for syntax to highlight. Stop at first
6398 highlighted object, if any. Return t if some highlighting was
6399 done, nil otherwise."
6400 (when (org-string-nw-p org-latex-and-related-regexp)
6401 (catch 'found
6402 (while (re-search-forward org-latex-and-related-regexp limit t)
6403 (unless
6404 (cl-some
6405 (lambda (f)
6406 (memq f '(org-code org-verbatim underline org-special-keyword)))
6407 (save-excursion
6408 (goto-char (1+ (match-beginning 0)))
6409 (face-at-point nil t)))
6410 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6411 '(?_ ?^))
6413 0)))
6414 (font-lock-prepend-text-property
6415 (+ offset (match-beginning 0)) (match-end 0)
6416 'face 'org-latex-and-related)
6417 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6418 '(font-lock-multiline t)))
6419 (throw 'found t)))
6420 nil)))
6422 (defun org-restart-font-lock ()
6423 "Restart `font-lock-mode', to force refontification."
6424 (when (and (boundp 'font-lock-mode) font-lock-mode)
6425 (font-lock-mode -1)
6426 (font-lock-mode 1)))
6428 (defun org-activate-tags (limit)
6429 (when (re-search-forward
6430 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6431 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6432 (add-text-properties (match-beginning 1) (match-end 1)
6433 (list 'mouse-face 'highlight
6434 'keymap org-mouse-map))
6435 (org-rear-nonsticky-at (match-end 1))
6438 (defun org-outline-level ()
6439 "Compute the outline level of the heading at point.
6441 If this is called at a normal headline, the level is the number
6442 of stars. Use `org-reduced-level' to remove the effect of
6443 `org-odd-levels'. Unlike to `org-current-level', this function
6444 takes into consideration inlinetasks."
6445 (org-with-wide-buffer
6446 (end-of-line)
6447 (if (re-search-backward org-outline-regexp-bol nil t)
6448 (1- (- (match-end 0) (match-beginning 0)))
6449 0)))
6451 (defvar org-font-lock-keywords nil)
6453 (defsubst org-re-property (property &optional literal allow-null value)
6454 "Return a regexp matching a PROPERTY line.
6456 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6457 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6458 non-nil, match properties even without a value.
6460 Match group 3 is set to the value when it exists. If there is no
6461 value and ALLOW-NULL is non-nil, it is set to the empty string.
6463 With optional argument VALUE, match only property lines with
6464 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6465 unless LITERAL is non-nil."
6466 (concat
6467 "^\\(?4:[ \t]*\\)"
6468 (format "\\(?1::\\(?2:%s\\):\\)"
6469 (if literal property (regexp-quote property)))
6470 (cond (value
6471 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6472 (if literal value (regexp-quote value))))
6473 (allow-null
6474 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6476 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6478 (defconst org-property-re
6479 (org-re-property "\\S-+" 'literal t)
6480 "Regular expression matching a property line.
6481 There are four matching groups:
6482 1: :PROPKEY: including the leading and trailing colon,
6483 2: PROPKEY without the leading and trailing colon,
6484 3: PROPVAL without leading or trailing spaces,
6485 4: the indentation of the current line,
6486 5: trailing whitespace.")
6488 (defvar org-font-lock-hook nil
6489 "Functions to be called for special font lock stuff.")
6491 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6493 (defvar org-font-lock-set-keywords-hook nil
6494 "Functions that can manipulate `org-font-lock-extra-keywords'.
6495 This is called after `org-font-lock-extra-keywords' is defined, but before
6496 it is installed to be used by font lock. This can be useful if something
6497 needs to be inserted at a specific position in the font-lock sequence.")
6499 (defun org-font-lock-hook (limit)
6500 "Run `org-font-lock-hook' within LIMIT."
6501 (run-hook-with-args 'org-font-lock-hook limit))
6503 (defun org-set-font-lock-defaults ()
6504 "Set font lock defaults for the current buffer."
6505 (let* ((em org-fontify-emphasized-text)
6506 (lk org-highlight-links)
6507 (org-font-lock-extra-keywords
6508 (list
6509 ;; Call the hook
6510 '(org-font-lock-hook)
6511 ;; Headlines
6512 `(,(if org-fontify-whole-heading-line
6513 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6514 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6515 (1 (org-get-level-face 1))
6516 (2 (org-get-level-face 2))
6517 (3 (org-get-level-face 3)))
6518 ;; Table lines
6519 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6520 (1 'org-table t))
6521 ;; Table internals
6522 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6523 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6524 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6525 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6526 ;; Drawers
6527 '(org-fontify-drawers)
6528 ;; Properties
6529 (list org-property-re
6530 '(1 'org-special-keyword t)
6531 '(3 'org-property-value t))
6532 ;; Links
6533 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6534 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6535 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6536 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6537 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6538 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6539 (when (memq 'footnote lk) '(org-activate-footnote-links))
6540 ;; Targets.
6541 (list org-any-target-regexp '(0 'org-target t))
6542 ;; Diary sexps.
6543 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6544 ;; Macro
6545 '(org-fontify-macros)
6546 '(org-hide-wide-columns (0 nil append))
6547 ;; TODO keyword
6548 (list (format org-heading-keyword-regexp-format
6549 org-todo-regexp)
6550 '(2 (org-get-todo-face 2) t))
6551 ;; DONE
6552 (if org-fontify-done-headline
6553 (list (format org-heading-keyword-regexp-format
6554 (concat
6555 "\\(?:"
6556 (mapconcat 'regexp-quote org-done-keywords "\\|")
6557 "\\)"))
6558 '(2 'org-headline-done t))
6559 nil)
6560 ;; Priorities
6561 '(org-font-lock-add-priority-faces)
6562 ;; Tags
6563 '(org-font-lock-add-tag-faces)
6564 ;; Tags groups
6565 (when (and org-group-tags org-tag-groups-alist)
6566 (list (concat org-outline-regexp-bol ".+\\(:"
6567 (regexp-opt (mapcar 'car org-tag-groups-alist))
6568 ":\\).*$")
6569 '(1 'org-tag-group prepend)))
6570 ;; Special keywords
6571 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6572 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6573 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6574 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6575 ;; Emphasis
6576 (when em '(org-do-emphasis-faces))
6577 ;; Checkboxes
6578 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6579 1 'org-checkbox prepend)
6580 (when (cdr (assq 'checkbox org-list-automatic-rules))
6581 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6582 (0 (org-get-checkbox-statistics-face) t)))
6583 ;; Description list items
6584 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6585 1 'org-list-dt prepend)
6586 ;; ARCHIVEd headings
6587 (list (concat
6588 org-outline-regexp-bol
6589 "\\(.*:" org-archive-tag ":.*\\)")
6590 '(1 'org-archived prepend))
6591 ;; Specials
6592 '(org-do-latex-and-related)
6593 '(org-fontify-entities)
6594 '(org-raise-scripts)
6595 ;; Code
6596 '(org-activate-code (1 'org-code t))
6597 ;; COMMENT
6598 (list (format
6599 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6600 org-todo-regexp
6601 org-comment-string)
6602 '(9 'org-special-keyword t))
6603 ;; Blocks and meta lines
6604 '(org-fontify-meta-lines-and-blocks))))
6605 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6606 (run-hooks 'org-font-lock-set-keywords-hook)
6607 ;; Now set the full font-lock-keywords
6608 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6609 (setq-local font-lock-defaults
6610 '(org-font-lock-keywords t nil nil backward-paragraph))
6611 (kill-local-variable 'font-lock-keywords)
6612 nil))
6614 (defun org-toggle-pretty-entities ()
6615 "Toggle the composition display of entities as UTF8 characters."
6616 (interactive)
6617 (setq-local org-pretty-entities (not org-pretty-entities))
6618 (org-restart-font-lock)
6619 (if org-pretty-entities
6620 (message "Entities are now displayed as UTF8 characters")
6621 (save-restriction
6622 (widen)
6623 (decompose-region (point-min) (point-max))
6624 (message "Entities are now displayed as plain text"))))
6626 (defvar-local org-custom-properties-overlays nil
6627 "List of overlays used for custom properties.")
6629 (defun org-toggle-custom-properties-visibility ()
6630 "Display or hide properties in `org-custom-properties'."
6631 (interactive)
6632 (if org-custom-properties-overlays
6633 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6634 (setq org-custom-properties-overlays nil))
6635 (when org-custom-properties
6636 (org-with-wide-buffer
6637 (goto-char (point-min))
6638 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6639 (while (re-search-forward regexp nil t)
6640 (let ((end (cdr (save-match-data (org-get-property-block)))))
6641 (when (and end (< (point) end))
6642 ;; Hide first custom property in current drawer.
6643 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6644 (overlay-put o 'invisible t)
6645 (overlay-put o 'org-custom-property t)
6646 (push o org-custom-properties-overlays))
6647 ;; Hide additional custom properties in the same drawer.
6648 (while (re-search-forward regexp end t)
6649 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6650 (overlay-put o 'invisible t)
6651 (overlay-put o 'org-custom-property t)
6652 (push o org-custom-properties-overlays)))))
6653 ;; Each entry is limited to a single property drawer.
6654 (outline-next-heading)))))))
6656 (defun org-fontify-entities (limit)
6657 "Find an entity to fontify."
6658 (let (ee)
6659 (when org-pretty-entities
6660 (catch 'match
6661 ;; "\_ "-family is left out on purpose. Only the first one,
6662 ;; i.e., "\_ ", could be fontified anyway, and it would be
6663 ;; confusing when adding a second white space character.
6664 (while (re-search-forward
6665 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6666 limit t)
6667 (when (and (not (org-at-comment-p))
6668 (setq ee (org-entity-get (match-string 1)))
6669 (= (length (nth 6 ee)) 1))
6670 (let* ((end (if (equal (match-string 2) "{}")
6671 (match-end 2)
6672 (match-end 1))))
6673 (add-text-properties
6674 (match-beginning 0) end
6675 (list 'font-lock-fontified t))
6676 (compose-region (match-beginning 0) end
6677 (nth 6 ee) nil)
6678 (backward-char 1)
6679 (throw 'match t))))
6680 nil))))
6682 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6683 "Fontify string S like in Org-mode."
6684 (with-temp-buffer
6685 (insert s)
6686 (let ((org-odd-levels-only odd-levels))
6687 (org-mode)
6688 (org-font-lock-ensure)
6689 (buffer-string))))
6691 (defvar org-m nil)
6692 (defvar org-l nil)
6693 (defvar org-f nil)
6694 (defun org-get-level-face (n)
6695 "Get the right face for match N in font-lock matching of headlines."
6696 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6697 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6698 (if org-cycle-level-faces
6699 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6700 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6701 (cond
6702 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6703 ((eq n 2) org-f)
6704 (t (unless org-level-color-stars-only org-f))))
6706 (defun org-face-from-face-or-color (context inherit face-or-color)
6707 "Create a face list that inherits INHERIT, but sets the foreground color.
6708 When FACE-OR-COLOR is not a string, just return it."
6709 (if (stringp face-or-color)
6710 (list :inherit inherit
6711 (cdr (assoc context org-faces-easy-properties))
6712 face-or-color)
6713 face-or-color))
6715 (defun org-get-todo-face (kwd)
6716 "Get the right face for a TODO keyword KWD.
6717 If KWD is a number, get the corresponding match group."
6718 (when (numberp kwd) (setq kwd (match-string kwd)))
6719 (or (org-face-from-face-or-color
6720 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6721 (and (member kwd org-done-keywords) 'org-done)
6722 'org-todo))
6724 (defun org-get-priority-face (priority)
6725 "Get the right face for PRIORITY.
6726 PRIORITY is a character."
6727 (or (org-face-from-face-or-color
6728 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6729 'org-priority))
6731 (defun org-get-tag-face (tag)
6732 "Get the right face for TAG.
6733 If TAG is a number, get the corresponding match group."
6734 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6735 (or (org-face-from-face-or-color
6736 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6737 'org-tag)))
6739 (defun org-font-lock-add-priority-faces (limit)
6740 "Add the special priority faces."
6741 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6742 (add-text-properties
6743 (match-beginning 1) (match-end 1)
6744 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6745 'font-lock-fontified t))))
6747 (defun org-font-lock-add-tag-faces (limit)
6748 "Add the special tag faces."
6749 (when (and org-tag-faces org-tags-special-faces-re)
6750 (while (re-search-forward org-tags-special-faces-re limit t)
6751 (add-text-properties (match-beginning 1) (match-end 1)
6752 (list 'face (org-get-tag-face 1)
6753 'font-lock-fontified t))
6754 (backward-char 1))))
6756 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6757 "Remove fontification and activation overlays from links."
6758 (font-lock-default-unfontify-region beg end)
6759 (let* ((buffer-undo-list t)
6760 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6761 (inhibit-modification-hooks t)
6762 deactivate-mark buffer-file-name buffer-file-truename)
6763 (decompose-region beg end)
6764 (remove-text-properties beg end
6765 '(mouse-face t keymap t org-linked-text t
6766 invisible t intangible t
6767 org-emphasis t))
6768 (org-remove-font-lock-display-properties beg end)))
6770 (defconst org-script-display '(((raise -0.3) (height 0.7))
6771 ((raise 0.3) (height 0.7))
6772 ((raise -0.5))
6773 ((raise 0.5)))
6774 "Display properties for showing superscripts and subscripts.")
6776 (defun org-remove-font-lock-display-properties (beg end)
6777 "Remove specific display properties that have been added by font lock.
6778 The will remove the raise properties that are used to show superscripts
6779 and subscripts."
6780 (let (next prop)
6781 (while (< beg end)
6782 (setq next (next-single-property-change beg 'display nil end)
6783 prop (get-text-property beg 'display))
6784 (when (member prop org-script-display)
6785 (put-text-property beg next 'display nil))
6786 (setq beg next))))
6788 (defun org-raise-scripts (limit)
6789 "Add raise properties to sub/superscripts."
6790 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6791 (re-search-forward
6792 (if (eq org-use-sub-superscripts t)
6793 org-match-substring-regexp
6794 org-match-substring-with-braces-regexp)
6795 limit t))
6796 (let* ((pos (point)) table-p comment-p
6797 (mpos (match-beginning 3))
6798 (emph-p (get-text-property mpos 'org-emphasis))
6799 (link-p (get-text-property mpos 'mouse-face))
6800 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6801 (goto-char (point-at-bol))
6802 (setq table-p (looking-at-p org-table-dataline-regexp)
6803 comment-p (looking-at-p "^[ \t]*#[ +]"))
6804 (goto-char pos)
6805 ;; Handle a_b^c
6806 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6807 (unless (or comment-p emph-p link-p keyw-p)
6808 (put-text-property (match-beginning 3) (match-end 0)
6809 'display
6810 (if (equal (char-after (match-beginning 2)) ?^)
6811 (nth (if table-p 3 1) org-script-display)
6812 (nth (if table-p 2 0) org-script-display)))
6813 (add-text-properties (match-beginning 2) (match-end 2)
6814 (list 'invisible t
6815 'org-dwidth t 'org-dwidth-n 1))
6816 (if (and (eq (char-after (match-beginning 3)) ?{)
6817 (eq (char-before (match-end 3)) ?}))
6818 (progn
6819 (add-text-properties
6820 (match-beginning 3) (1+ (match-beginning 3))
6821 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6822 (add-text-properties
6823 (1- (match-end 3)) (match-end 3)
6824 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6825 t)))
6827 ;;;; Visibility cycling, including org-goto and indirect buffer
6829 ;;; Cycling
6831 (defvar-local org-cycle-global-status nil)
6832 (put 'org-cycle-global-status 'org-state t)
6833 (defvar-local org-cycle-subtree-status nil)
6834 (put 'org-cycle-subtree-status 'org-state t)
6836 (defvar org-inlinetask-min-level)
6838 (defun org-unlogged-message (&rest args)
6839 "Display a message, but avoid logging it in the *Messages* buffer."
6840 (let ((message-log-max nil))
6841 (apply 'message args)))
6843 ;;;###autoload
6844 (defun org-cycle (&optional arg)
6845 "TAB-action and visibility cycling for Org-mode.
6847 This is the command invoked in Org mode by the TAB key. Its main purpose
6848 is outline visibility cycling, but it also invokes other actions
6849 in special contexts.
6851 - When this function is called with a prefix argument, rotate the entire
6852 buffer through 3 states (global cycling)
6853 1. OVERVIEW: Show only top-level headlines.
6854 2. CONTENTS: Show all headlines of all levels, but no body text.
6855 3. SHOW ALL: Show everything.
6856 With a double \\[universal-argument] prefix argument, \
6857 switch to the startup visibility,
6858 determined by the variable `org-startup-folded', and by any VISIBILITY
6859 properties in the buffer.
6860 With a triple \\[universal-argument] prefix argument, \
6861 show the entire buffer, including any drawers.
6863 - When inside a table, re-align the table and move to the next field.
6865 - When point is at the beginning of a headline, rotate the subtree started
6866 by this line through 3 different states (local cycling)
6867 1. FOLDED: Only the main headline is shown.
6868 2. CHILDREN: The main headline and the direct children are shown.
6869 From this state, you can move to one of the children
6870 and zoom in further.
6871 3. SUBTREE: Show the entire subtree, including body text.
6872 If there is no subtree, switch directly from CHILDREN to FOLDED.
6874 - When point is at the beginning of an empty headline and the variable
6875 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6876 of the headline by demoting and promoting it to likely levels. This
6877 speeds up creation document structure by pressing TAB once or several
6878 times right after creating a new headline.
6880 - When there is a numeric prefix, go up to a heading with level ARG, do
6881 a `show-subtree' and return to the previous cursor position. If ARG
6882 is negative, go up that many levels.
6884 - When point is not at the beginning of a headline, execute the global
6885 binding for TAB, which is re-indenting the line. See the option
6886 `org-cycle-emulate-tab' for details.
6888 - Special case: if point is at the beginning of the buffer and there is
6889 no headline in line 1, this function will act as if called with prefix arg
6890 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6891 But only if also the variable `org-cycle-global-at-bob' is t."
6892 (interactive "P")
6893 (org-load-modules-maybe)
6894 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6895 (and org-cycle-level-after-item/entry-creation
6896 (or (org-cycle-level)
6897 (org-cycle-item-indentation))))
6898 (let* ((limit-level
6899 (or org-cycle-max-level
6900 (and (boundp 'org-inlinetask-min-level)
6901 org-inlinetask-min-level
6902 (1- org-inlinetask-min-level))))
6903 (nstars (and limit-level
6904 (if org-odd-levels-only
6905 (and limit-level (1- (* limit-level 2)))
6906 limit-level)))
6907 (org-outline-regexp
6908 (if (not (derived-mode-p 'org-mode))
6909 outline-regexp
6910 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6911 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6912 (not (looking-at org-outline-regexp))))
6913 (org-cycle-hook
6914 (if bob-special
6915 (delq 'org-optimize-window-after-visibility-change
6916 (copy-sequence org-cycle-hook))
6917 org-cycle-hook))
6918 (pos (point)))
6920 (when (or bob-special (equal arg '(4)))
6921 ;; special case: use global cycling
6922 (setq arg t))
6924 (cond
6926 ((equal arg '(16))
6927 (setq last-command 'dummy)
6928 (org-set-startup-visibility)
6929 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6931 ((equal arg '(64))
6932 (outline-show-all)
6933 (org-unlogged-message "Entire buffer visible, including drawers"))
6935 ;; Try cdlatex TAB completion
6936 ((org-try-cdlatex-tab))
6938 ;; Table: enter it or move to the next field.
6939 ((org-at-table-p 'any)
6940 (if (org-at-table.el-p)
6941 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6942 Use \\[org-edit-special] to edit table.el tables"))
6943 (if arg (org-table-edit-field t)
6944 (org-table-justify-field-maybe)
6945 (call-interactively 'org-table-next-field))))
6947 ((run-hook-with-args-until-success
6948 'org-tab-after-check-for-table-hook))
6950 ;; Global cycling: delegate to `org-cycle-internal-global'.
6951 ((eq arg t) (org-cycle-internal-global))
6953 ;; Drawers: delegate to `org-flag-drawer'.
6954 ((save-excursion
6955 (beginning-of-line 1)
6956 (looking-at org-drawer-regexp))
6957 (org-flag-drawer ; toggle block visibility
6958 (not (get-char-property (match-end 0) 'invisible))))
6960 ;; Show-subtree, ARG levels up from here.
6961 ((integerp arg)
6962 (save-excursion
6963 (org-back-to-heading)
6964 (outline-up-heading (if (< arg 0) (- arg)
6965 (- (funcall outline-level) arg)))
6966 (org-show-subtree)))
6968 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6969 ((and (featurep 'org-inlinetask)
6970 (org-inlinetask-at-task-p)
6971 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6972 (org-inlinetask-toggle-visibility))
6974 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6975 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6976 (save-excursion (move-beginning-of-line 1)
6977 (looking-at org-outline-regexp)))
6978 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6979 (org-cycle-internal-local))
6981 ;; From there: TAB emulation and template completion.
6982 (buffer-read-only (org-back-to-heading))
6984 ((run-hook-with-args-until-success
6985 'org-tab-after-check-for-cycling-hook))
6987 ((org-try-structure-completion))
6989 ((run-hook-with-args-until-success
6990 'org-tab-before-tab-emulation-hook))
6992 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6993 (or (not (bolp))
6994 (not (looking-at org-outline-regexp))))
6995 (call-interactively (global-key-binding "\t")))
6997 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6998 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6999 (or (and (eq org-cycle-emulate-tab 'white)
7000 (= (match-end 0) (point-at-eol)))
7001 (and (eq org-cycle-emulate-tab 'whitestart)
7002 (>= (match-end 0) pos))))
7004 (eq org-cycle-emulate-tab t))
7005 (call-interactively (global-key-binding "\t")))
7007 (t (save-excursion
7008 (org-back-to-heading)
7009 (org-cycle)))))))
7011 (defun org-cycle-internal-global ()
7012 "Do the global cycling action."
7013 ;; Hack to avoid display of messages for .org attachments in Gnus
7014 (let ((ga (string-match "\\*fontification" (buffer-name))))
7015 (cond
7016 ((and (eq last-command this-command)
7017 (eq org-cycle-global-status 'overview))
7018 ;; We just created the overview - now do table of contents
7019 ;; This can be slow in very large buffers, so indicate action
7020 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7021 (unless ga (org-unlogged-message "CONTENTS..."))
7022 (org-content)
7023 (unless ga (org-unlogged-message "CONTENTS...done"))
7024 (setq org-cycle-global-status 'contents)
7025 (run-hook-with-args 'org-cycle-hook 'contents))
7027 ((and (eq last-command this-command)
7028 (eq org-cycle-global-status 'contents))
7029 ;; We just showed the table of contents - now show everything
7030 (run-hook-with-args 'org-pre-cycle-hook 'all)
7031 (outline-show-all)
7032 (unless ga (org-unlogged-message "SHOW ALL"))
7033 (setq org-cycle-global-status 'all)
7034 (run-hook-with-args 'org-cycle-hook 'all))
7037 ;; Default action: go to overview
7038 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7039 (org-overview)
7040 (unless ga (org-unlogged-message "OVERVIEW"))
7041 (setq org-cycle-global-status 'overview)
7042 (run-hook-with-args 'org-cycle-hook 'overview)))))
7044 (defvar org-called-with-limited-levels nil
7045 "Non-nil when `org-with-limited-levels' is currently active.")
7047 (defun org-cycle-internal-local ()
7048 "Do the local cycling action."
7049 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7050 ;; First, determine end of headline (EOH), end of subtree or item
7051 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7052 (save-excursion
7053 (if (org-at-item-p)
7054 (progn
7055 (beginning-of-line)
7056 (setq struct (org-list-struct))
7057 (setq eoh (point-at-eol))
7058 (setq eos (org-list-get-item-end-before-blank (point) struct))
7059 (setq has-children (org-list-has-child-p (point) struct)))
7060 (org-back-to-heading)
7061 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7062 (setq eos (save-excursion (org-end-of-subtree t t)
7063 (when (bolp) (backward-char)) (point)))
7064 (setq has-children
7065 (or (save-excursion
7066 (let ((level (funcall outline-level)))
7067 (outline-next-heading)
7068 (and (org-at-heading-p t)
7069 (> (funcall outline-level) level))))
7070 (save-excursion
7071 (org-list-search-forward (org-item-beginning-re) eos t)))))
7072 ;; Determine end invisible part of buffer (EOL)
7073 (beginning-of-line 2)
7074 (while (and (not (eobp)) ;This is like `next-line'.
7075 (get-char-property (1- (point)) 'invisible))
7076 (goto-char (next-single-char-property-change (point) 'invisible))
7077 (and (eolp) (beginning-of-line 2)))
7078 (setq eol (point)))
7079 ;; Find out what to do next and set `this-command'
7080 (cond
7081 ((= eos eoh)
7082 ;; Nothing is hidden behind this heading
7083 (unless (org-before-first-heading-p)
7084 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7085 (org-unlogged-message "EMPTY ENTRY")
7086 (setq org-cycle-subtree-status nil)
7087 (save-excursion
7088 (goto-char eos)
7089 (outline-next-heading)
7090 (when (outline-invisible-p) (org-flag-heading nil))))
7091 ((and (or (>= eol eos)
7092 (not (string-match "\\S-" (buffer-substring eol eos))))
7093 (or has-children
7094 (not (setq children-skipped
7095 org-cycle-skip-children-state-if-no-children))))
7096 ;; Entire subtree is hidden in one line: children view
7097 (unless (org-before-first-heading-p)
7098 (run-hook-with-args 'org-pre-cycle-hook 'children))
7099 (if (org-at-item-p)
7100 (org-list-set-item-visibility (point-at-bol) struct 'children)
7101 (org-show-entry)
7102 (org-with-limited-levels (org-show-children))
7103 ;; FIXME: This slows down the func way too much.
7104 ;; How keep drawers hidden in subtree anyway?
7105 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7106 ;; (org-cycle-hide-drawers 'subtree))
7108 ;; Fold every list in subtree to top-level items.
7109 (when (eq org-cycle-include-plain-lists 'integrate)
7110 (save-excursion
7111 (org-back-to-heading)
7112 (while (org-list-search-forward (org-item-beginning-re) eos t)
7113 (beginning-of-line 1)
7114 (let* ((struct (org-list-struct))
7115 (prevs (org-list-prevs-alist struct))
7116 (end (org-list-get-bottom-point struct)))
7117 (dolist (e (org-list-get-all-items (point) struct prevs))
7118 (org-list-set-item-visibility e struct 'folded))
7119 (goto-char (if (< end eos) end eos)))))))
7120 (org-unlogged-message "CHILDREN")
7121 (save-excursion
7122 (goto-char eos)
7123 (outline-next-heading)
7124 (when (outline-invisible-p) (org-flag-heading nil)))
7125 (setq org-cycle-subtree-status 'children)
7126 (unless (org-before-first-heading-p)
7127 (run-hook-with-args 'org-cycle-hook 'children)))
7128 ((or children-skipped
7129 (and (eq last-command this-command)
7130 (eq org-cycle-subtree-status 'children)))
7131 ;; We just showed the children, or no children are there,
7132 ;; now show everything.
7133 (unless (org-before-first-heading-p)
7134 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7135 (outline-flag-region eoh eos nil)
7136 (org-unlogged-message
7137 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7138 (setq org-cycle-subtree-status 'subtree)
7139 (unless (org-before-first-heading-p)
7140 (run-hook-with-args 'org-cycle-hook 'subtree)))
7142 ;; Default action: hide the subtree.
7143 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7144 (outline-flag-region eoh eos t)
7145 (org-unlogged-message "FOLDED")
7146 (setq org-cycle-subtree-status 'folded)
7147 (unless (org-before-first-heading-p)
7148 (run-hook-with-args 'org-cycle-hook 'folded))))))
7150 ;;;###autoload
7151 (defun org-global-cycle (&optional arg)
7152 "Cycle the global visibility. For details see `org-cycle'.
7153 With \\[universal-argument] prefix arg, switch to startup visibility.
7154 With a numeric prefix, show all headlines up to that level."
7155 (interactive "P")
7156 (let ((org-cycle-include-plain-lists
7157 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7158 (cond
7159 ((integerp arg)
7160 (outline-show-all)
7161 (outline-hide-sublevels arg)
7162 (setq org-cycle-global-status 'contents))
7163 ((equal arg '(4))
7164 (org-set-startup-visibility)
7165 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7167 (org-cycle '(4))))))
7169 (defun org-set-startup-visibility ()
7170 "Set the visibility required by startup options and properties."
7171 (cond
7172 ((eq org-startup-folded t)
7173 (org-overview))
7174 ((eq org-startup-folded 'content)
7175 (org-content))
7176 ((or (eq org-startup-folded 'showeverything)
7177 (eq org-startup-folded nil))
7178 (outline-show-all)))
7179 (unless (eq org-startup-folded 'showeverything)
7180 (when org-hide-block-startup (org-hide-block-all))
7181 (org-set-visibility-according-to-property 'no-cleanup)
7182 (org-cycle-hide-archived-subtrees 'all)
7183 (org-cycle-hide-drawers 'all)
7184 (org-cycle-show-empty-lines t)))
7186 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7187 "Switch subtree visibilities according to :VISIBILITY: property."
7188 (interactive)
7189 (org-with-wide-buffer
7190 (goto-char (point-min))
7191 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7192 (if (not (org-at-property-p)) (outline-next-heading)
7193 (let ((state (match-string 3)))
7194 (save-excursion
7195 (org-back-to-heading t)
7196 (outline-hide-subtree)
7197 (org-reveal)
7198 (cond
7199 ((equal state "folded")
7200 (outline-hide-subtree))
7201 ((equal state "children")
7202 (org-show-hidden-entry)
7203 (org-show-children))
7204 ((equal state "content")
7205 (save-excursion
7206 (save-restriction
7207 (org-narrow-to-subtree)
7208 (org-content))))
7209 ((member state '("all" "showall"))
7210 (outline-show-subtree)))))))
7211 (unless no-cleanup
7212 (org-cycle-hide-archived-subtrees 'all)
7213 (org-cycle-hide-drawers 'all)
7214 (org-cycle-show-empty-lines 'all))))
7216 ;; This function uses outline-regexp instead of the more fundamental
7217 ;; org-outline-regexp so that org-cycle-global works outside of Org
7218 ;; buffers, where outline-regexp is needed.
7219 (defun org-overview ()
7220 "Switch to overview mode, showing only top-level headlines.
7221 This shows all headlines with a level equal or greater than the level
7222 of the first headline in the buffer. This is important, because if the
7223 first headline is not level one, then (hide-sublevels 1) gives confusing
7224 results."
7225 (interactive)
7226 (save-excursion
7227 (let ((level
7228 (save-excursion
7229 (goto-char (point-min))
7230 (when (re-search-forward (concat "^" outline-regexp) nil t)
7231 (goto-char (match-beginning 0))
7232 (funcall outline-level)))))
7233 (and level (outline-hide-sublevels level)))))
7235 (defun org-content (&optional arg)
7236 "Show all headlines in the buffer, like a table of contents.
7237 With numerical argument N, show content up to level N."
7238 (interactive "P")
7239 (org-overview)
7240 (save-excursion
7241 ;; Visit all headings and show their offspring
7242 (and (integerp arg) (org-overview))
7243 (goto-char (point-max))
7244 (catch 'exit
7245 (while (and (progn (condition-case nil
7246 (outline-previous-visible-heading 1)
7247 (error (goto-char (point-min))))
7249 (looking-at org-outline-regexp))
7250 (if (integerp arg)
7251 (org-show-children (1- arg))
7252 (outline-show-branches))
7253 (when (bobp) (throw 'exit nil))))))
7255 (defun org-optimize-window-after-visibility-change (state)
7256 "Adjust the window after a change in outline visibility.
7257 This function is the default value of the hook `org-cycle-hook'."
7258 (when (get-buffer-window (current-buffer))
7259 (cond
7260 ((eq state 'content) nil)
7261 ((eq state 'all) nil)
7262 ((eq state 'folded) nil)
7263 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7264 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7266 (defun org-remove-empty-overlays-at (pos)
7267 "Remove outline overlays that do not contain non-white stuff."
7268 (dolist (o (overlays-at pos))
7269 (and (eq 'outline (overlay-get o 'invisible))
7270 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7271 (overlay-end o))))
7272 (delete-overlay o))))
7274 (defun org-clean-visibility-after-subtree-move ()
7275 "Fix visibility issues after moving a subtree."
7276 ;; First, find a reasonable region to look at:
7277 ;; Start two siblings above, end three below
7278 (let* ((beg (save-excursion
7279 (and (org-get-last-sibling)
7280 (org-get-last-sibling))
7281 (point)))
7282 (end (save-excursion
7283 (and (org-get-next-sibling)
7284 (org-get-next-sibling)
7285 (org-get-next-sibling))
7286 (if (org-at-heading-p)
7287 (point-at-eol)
7288 (point))))
7289 (level (looking-at "\\*+"))
7290 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7291 (save-excursion
7292 (save-restriction
7293 (narrow-to-region beg end)
7294 (when re
7295 ;; Properly fold already folded siblings
7296 (goto-char (point-min))
7297 (while (re-search-forward re nil t)
7298 (when (and (not (outline-invisible-p))
7299 (save-excursion
7300 (goto-char (point-at-eol)) (outline-invisible-p)))
7301 (outline-hide-entry))))
7302 (org-cycle-show-empty-lines 'overview)
7303 (org-cycle-hide-drawers 'overview)))))
7305 (defun org-cycle-show-empty-lines (state)
7306 "Show empty lines above all visible headlines.
7307 The region to be covered depends on STATE when called through
7308 `org-cycle-hook'. Lisp program can use t for STATE to get the
7309 entire buffer covered. Note that an empty line is only shown if there
7310 are at least `org-cycle-separator-lines' empty lines before the headline."
7311 (when (/= org-cycle-separator-lines 0)
7312 (save-excursion
7313 (let* ((n (abs org-cycle-separator-lines))
7314 (re (cond
7315 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7316 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7317 (t (let ((ns (number-to-string (- n 2))))
7318 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7319 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7320 beg end)
7321 (cond
7322 ((memq state '(overview contents t))
7323 (setq beg (point-min) end (point-max)))
7324 ((memq state '(children folded))
7325 (setq beg (point)
7326 end (progn (org-end-of-subtree t t)
7327 (line-beginning-position 2)))))
7328 (when beg
7329 (goto-char beg)
7330 (while (re-search-forward re end t)
7331 (unless (get-char-property (match-end 1) 'invisible)
7332 (let ((e (match-end 1))
7333 (b (if (>= org-cycle-separator-lines 0)
7334 (match-beginning 1)
7335 (save-excursion
7336 (goto-char (match-beginning 0))
7337 (skip-chars-backward " \t\n")
7338 (line-end-position)))))
7339 (outline-flag-region b e nil))))))))
7340 ;; Never hide empty lines at the end of the file.
7341 (save-excursion
7342 (goto-char (point-max))
7343 (outline-previous-heading)
7344 (outline-end-of-heading)
7345 (when (and (looking-at "[ \t\n]+")
7346 (= (match-end 0) (point-max)))
7347 (outline-flag-region (point) (match-end 0) nil))))
7349 (defun org-show-empty-lines-in-parent ()
7350 "Move to the parent and re-show empty lines before visible headlines."
7351 (save-excursion
7352 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7353 (org-cycle-show-empty-lines context))))
7355 (defun org-files-list ()
7356 "Return `org-agenda-files' list, plus all open Org files.
7357 This is useful for operations that need to scan all of a user's
7358 open and agenda-wise Org files."
7359 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7360 (dolist (buf (buffer-list))
7361 (with-current-buffer buf
7362 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7363 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7364 files))
7366 (defsubst org-entry-beginning-position ()
7367 "Return the beginning position of the current entry."
7368 (save-excursion (org-back-to-heading t) (point)))
7370 (defsubst org-entry-end-position ()
7371 "Return the end position of the current entry."
7372 (save-excursion (outline-next-heading) (point)))
7374 (defun org-cycle-hide-drawers (state &optional exceptions)
7375 "Re-hide all drawers after a visibility state change.
7376 When non-nil, optional argument EXCEPTIONS is a list of strings
7377 specifying which drawers should not be hidden."
7378 (when (and (derived-mode-p 'org-mode)
7379 (not (memq state '(overview folded contents))))
7380 (save-excursion
7381 (let* ((globalp (memq state '(contents all)))
7382 (beg (if globalp (point-min) (point)))
7383 (end (if globalp (point-max)
7384 (if (eq state 'children)
7385 (save-excursion (outline-next-heading) (point))
7386 (org-end-of-subtree t)))))
7387 (goto-char beg)
7388 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7389 (unless (member-ignore-case (match-string 1) exceptions)
7390 (let ((drawer (org-element-at-point)))
7391 (when (memq (org-element-type drawer) '(drawer property-drawer))
7392 (org-flag-drawer t drawer)
7393 ;; Make sure to skip drawer entirely or we might flag
7394 ;; it another time when matching its ending line with
7395 ;; `org-drawer-regexp'.
7396 (goto-char (org-element-property :end drawer))))))))))
7398 (defun org-flag-drawer (flag &optional element)
7399 "When FLAG is non-nil, hide the drawer we are at.
7400 Otherwise make it visible. When optional argument ELEMENT is
7401 a parsed drawer, as returned by `org-element-at-point', hide or
7402 show that drawer instead."
7403 (let ((drawer (or element
7404 (and (save-excursion
7405 (beginning-of-line)
7406 (looking-at-p org-drawer-regexp))
7407 (org-element-at-point)))))
7408 (when (memq (org-element-type drawer) '(drawer property-drawer))
7409 (let ((post (org-element-property :post-affiliated drawer)))
7410 (save-excursion
7411 (outline-flag-region
7412 (progn (goto-char post) (line-end-position))
7413 (progn (goto-char (org-element-property :end drawer))
7414 (skip-chars-backward " \r\t\n")
7415 (line-end-position))
7416 flag))
7417 ;; When the drawer is hidden away, make sure point lies in
7418 ;; a visible part of the buffer.
7419 (when (and flag (> (line-beginning-position) post))
7420 (goto-char post))))))
7422 (defun org-subtree-end-visible-p ()
7423 "Is the end of the current subtree visible?"
7424 (pos-visible-in-window-p
7425 (save-excursion (org-end-of-subtree t) (point))))
7427 (defun org-first-headline-recenter ()
7428 "Move cursor to the first headline and recenter the headline."
7429 (let ((window (get-buffer-window)))
7430 (when window
7431 (goto-char (point-min))
7432 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7433 (set-window-start window (line-beginning-position))))))
7435 ;;; Saving and restoring visibility
7437 (defun org-outline-overlay-data (&optional use-markers)
7438 "Return a list of the locations of all outline overlays.
7439 These are overlays with the `invisible' property value `outline'.
7440 The return value is a list of cons cells, with start and stop
7441 positions for each overlay.
7442 If USE-MARKERS is set, return the positions as markers."
7443 (let (beg end)
7444 (save-excursion
7445 (save-restriction
7446 (widen)
7447 (delq nil
7448 (mapcar (lambda (o)
7449 (when (eq (overlay-get o 'invisible) 'outline)
7450 (setq beg (overlay-start o)
7451 end (overlay-end o))
7452 (and beg end (> end beg)
7453 (if use-markers
7454 (cons (copy-marker beg)
7455 (copy-marker end t))
7456 (cons beg end)))))
7457 (overlays-in (point-min) (point-max))))))))
7459 (defun org-set-outline-overlay-data (data)
7460 "Create visibility overlays for all positions in DATA.
7461 DATA should have been made by `org-outline-overlay-data'."
7462 (org-with-wide-buffer
7463 (outline-show-all)
7464 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7466 ;;; Folding of blocks
7468 (defvar-local org-hide-block-overlays nil
7469 "Overlays hiding blocks.")
7471 (defun org-block-map (function &optional start end)
7472 "Call FUNCTION at the head of all source blocks in the current buffer.
7473 Optional arguments START and END can be used to limit the range."
7474 (let ((start (or start (point-min)))
7475 (end (or end (point-max))))
7476 (save-excursion
7477 (goto-char start)
7478 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7479 (save-excursion
7480 (save-match-data
7481 (goto-char (match-beginning 0))
7482 (funcall function)))))))
7484 (defun org-hide-block-toggle-all ()
7485 "Toggle the visibility of all blocks in the current buffer."
7486 (org-block-map 'org-hide-block-toggle))
7488 (defun org-hide-block-all ()
7489 "Fold all blocks in the current buffer."
7490 (interactive)
7491 (org-show-block-all)
7492 (org-block-map 'org-hide-block-toggle-maybe))
7494 (defun org-show-block-all ()
7495 "Unfold all blocks in the current buffer."
7496 (interactive)
7497 (mapc #'delete-overlay org-hide-block-overlays)
7498 (setq org-hide-block-overlays nil))
7500 (defun org-hide-block-toggle-maybe ()
7501 "Toggle visibility of block at point.
7502 Unlike to `org-hide-block-toggle', this function does not throw
7503 an error. Return a non-nil value when toggling is successful."
7504 (interactive)
7505 (ignore-errors (org-hide-block-toggle)))
7507 (defun org-hide-block-toggle (&optional force)
7508 "Toggle the visibility of the current block.
7509 When optional argument FORCE is `off', make block visible. If it
7510 is non-nil, hide it unconditionally. Throw an error when not at
7511 a block. Return a non-nil value when toggling is successful."
7512 (interactive)
7513 (let ((element (org-element-at-point)))
7514 (unless (memq (org-element-type element)
7515 '(center-block comment-block dynamic-block example-block
7516 export-block quote-block special-block
7517 src-block verse-block))
7518 (user-error "Not at a block"))
7519 (let* ((start (save-excursion
7520 (goto-char (org-element-property :post-affiliated element))
7521 (line-end-position)))
7522 (end (save-excursion
7523 (goto-char (org-element-property :end element))
7524 (skip-chars-backward " \r\t\n")
7525 (line-end-position)))
7526 (overlays (overlays-at start)))
7527 (cond
7528 ;; Do nothing when not before or at the block opening line or
7529 ;; at the block closing line.
7530 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7531 ((and (not (eq force 'off))
7532 (not (memq t (mapcar
7533 (lambda (o)
7534 (eq (overlay-get o 'invisible) 'org-hide-block))
7535 overlays))))
7536 (let ((ov (make-overlay start end)))
7537 (overlay-put ov 'invisible 'org-hide-block)
7538 ;; Make the block accessible to `isearch'.
7539 (overlay-put
7540 ov 'isearch-open-invisible
7541 (lambda (ov)
7542 (when (memq ov org-hide-block-overlays)
7543 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7544 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7545 (delete-overlay ov))))
7546 (push ov org-hide-block-overlays)
7547 ;; When the block is hidden away, make sure point is left in
7548 ;; a visible part of the buffer.
7549 (when (> (line-beginning-position) start)
7550 (goto-char start)
7551 (beginning-of-line))
7552 ;; Signal successful toggling.
7554 ((or (not force) (eq force 'off))
7555 (dolist (ov overlays t)
7556 (when (memq ov org-hide-block-overlays)
7557 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7558 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7559 (delete-overlay ov))))))))
7561 ;; org-tab-after-check-for-cycling-hook
7562 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7563 ;; Remove overlays when changing major mode
7564 (add-hook 'org-mode-hook
7565 (lambda () (add-hook 'change-major-mode-hook
7566 'org-show-block-all 'append 'local)))
7568 ;;; Org-goto
7570 (defvar org-goto-window-configuration nil)
7571 (defvar org-goto-marker nil)
7572 (defvar org-goto-map)
7573 (defun org-goto-map ()
7574 "Set the keymap `org-goto'."
7575 (setq org-goto-map
7576 (let ((map (make-sparse-keymap)))
7577 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7578 mouse-drag-region universal-argument org-occur)))
7579 (dolist (cmd cmds)
7580 (substitute-key-definition cmd cmd map global-map)))
7581 (suppress-keymap map)
7582 (org-defkey map "\C-m" 'org-goto-ret)
7583 (org-defkey map [(return)] 'org-goto-ret)
7584 (org-defkey map [(left)] 'org-goto-left)
7585 (org-defkey map [(right)] 'org-goto-right)
7586 (org-defkey map [(control ?g)] 'org-goto-quit)
7587 (org-defkey map "\C-i" 'org-cycle)
7588 (org-defkey map [(tab)] 'org-cycle)
7589 (org-defkey map [(down)] 'outline-next-visible-heading)
7590 (org-defkey map [(up)] 'outline-previous-visible-heading)
7591 (if org-goto-auto-isearch
7592 (if (fboundp 'define-key-after)
7593 (define-key-after map [t] 'org-goto-local-auto-isearch)
7594 nil)
7595 (org-defkey map "q" 'org-goto-quit)
7596 (org-defkey map "n" 'outline-next-visible-heading)
7597 (org-defkey map "p" 'outline-previous-visible-heading)
7598 (org-defkey map "f" 'outline-forward-same-level)
7599 (org-defkey map "b" 'outline-backward-same-level)
7600 (org-defkey map "u" 'outline-up-heading))
7601 (org-defkey map "/" 'org-occur)
7602 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7603 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7604 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7605 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7606 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7607 map)))
7609 (defconst org-goto-help
7610 "Browse buffer copy, to find location or copy text.%s
7611 RET=jump to location C-g=quit and return to previous location
7612 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7614 (defvar org-goto-start-pos) ; dynamically scoped parameter
7616 (defun org-goto (&optional alternative-interface)
7617 "Look up a different location in the current file, keeping current visibility.
7619 When you want look-up or go to a different location in a
7620 document, the fastest way is often to fold the entire buffer and
7621 then dive into the tree. This method has the disadvantage, that
7622 the previous location will be folded, which may not be what you
7623 want.
7625 This command works around this by showing a copy of the current
7626 buffer in an indirect buffer, in overview mode. You can dive
7627 into the tree in that copy, use org-occur and incremental search
7628 to find a location. When pressing RET or `Q', the command
7629 returns to the original buffer in which the visibility is still
7630 unchanged. After RET it will also jump to the location selected
7631 in the indirect buffer and expose the headline hierarchy above.
7633 With a prefix argument, use the alternative interface: e.g., if
7634 `org-goto-interface' is `outline' use `outline-path-completion'."
7635 (interactive "P")
7636 (org-goto-map)
7637 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7638 (org-refile-use-outline-path t)
7639 (org-refile-target-verify-function nil)
7640 (interface
7641 (if (not alternative-interface)
7642 org-goto-interface
7643 (if (eq org-goto-interface 'outline)
7644 'outline-path-completion
7645 'outline)))
7646 (org-goto-start-pos (point))
7647 (selected-point
7648 (if (eq interface 'outline)
7649 (car (org-get-location (current-buffer) org-goto-help))
7650 (let ((pa (org-refile-get-location "Goto")))
7651 (org-refile-check-position pa)
7652 (nth 3 pa)))))
7653 (if selected-point
7654 (progn
7655 (org-mark-ring-push org-goto-start-pos)
7656 (goto-char selected-point)
7657 (when (or (outline-invisible-p) (org-invisible-p2))
7658 (org-show-context 'org-goto)))
7659 (message "Quit"))))
7661 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7662 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7663 (defvar org-goto-local-auto-isearch-map) ; defined below
7665 (defun org-get-location (_buf help)
7666 "Let the user select a location in current buffer.
7667 This function uses a recursive edit. It returns the selected position
7668 or nil."
7669 (org-no-popups
7670 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7671 (isearch-hide-immediately nil)
7672 (isearch-search-fun-function
7673 (lambda () 'org-goto-local-search-headings))
7674 (org-goto-selected-point org-goto-exit-command))
7675 (save-excursion
7676 (save-window-excursion
7677 (delete-other-windows)
7678 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7679 (pop-to-buffer-same-window
7680 (condition-case nil
7681 (make-indirect-buffer (current-buffer) "*org-goto*")
7682 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7683 (with-output-to-temp-buffer "*Org Help*"
7684 (princ (format help (if org-goto-auto-isearch
7685 " Just type for auto-isearch."
7686 " n/p/f/b/u to navigate, q to quit."))))
7687 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7688 (setq buffer-read-only nil)
7689 (let ((org-startup-truncated t)
7690 (org-startup-folded nil)
7691 (org-startup-align-all-tables nil))
7692 (org-mode)
7693 (org-overview))
7694 (setq buffer-read-only t)
7695 (if (and (boundp 'org-goto-start-pos)
7696 (integer-or-marker-p org-goto-start-pos))
7697 (progn (goto-char org-goto-start-pos)
7698 (when (outline-invisible-p)
7699 (org-show-set-visibility 'lineage)))
7700 (goto-char (point-min)))
7701 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7702 (message "Select location and press RET")
7703 (use-local-map org-goto-map)
7704 (recursive-edit)))
7705 (kill-buffer "*org-goto*")
7706 (cons org-goto-selected-point org-goto-exit-command))))
7708 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7709 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7710 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7711 (if (fboundp 'isearch-other-control-char)
7712 (progn
7713 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7714 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7715 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7716 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7717 (define-key org-goto-local-auto-isearch-map [return] nil))
7719 (defun org-goto-local-search-headings (string bound noerror)
7720 "Search and make sure that any matches are in headlines."
7721 (catch 'return
7722 (while (if isearch-forward
7723 (search-forward string bound noerror)
7724 (search-backward string bound noerror))
7725 (when (save-match-data
7726 (and (save-excursion
7727 (beginning-of-line)
7728 (looking-at org-complex-heading-regexp))
7729 (or (not (match-beginning 5))
7730 (< (point) (match-beginning 5)))))
7731 (throw 'return (point))))))
7733 (defun org-goto-local-auto-isearch ()
7734 "Start isearch."
7735 (interactive)
7736 (goto-char (point-min))
7737 (let ((keys (this-command-keys)))
7738 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7739 (isearch-mode t)
7740 (isearch-process-search-char (string-to-char keys)))))
7742 (defun org-goto-ret (&optional _arg)
7743 "Finish `org-goto' by going to the new location."
7744 (interactive "P")
7745 (setq org-goto-selected-point (point))
7746 (setq org-goto-exit-command 'return)
7747 (throw 'exit nil))
7749 (defun org-goto-left ()
7750 "Finish `org-goto' by going to the new location."
7751 (interactive)
7752 (if (org-at-heading-p)
7753 (progn
7754 (beginning-of-line 1)
7755 (setq org-goto-selected-point (point)
7756 org-goto-exit-command 'left)
7757 (throw 'exit nil))
7758 (user-error "Not on a heading")))
7760 (defun org-goto-right ()
7761 "Finish `org-goto' by going to the new location."
7762 (interactive)
7763 (if (org-at-heading-p)
7764 (progn
7765 (setq org-goto-selected-point (point)
7766 org-goto-exit-command 'right)
7767 (throw 'exit nil))
7768 (user-error "Not on a heading")))
7770 (defun org-goto-quit ()
7771 "Finish `org-goto' without cursor motion."
7772 (interactive)
7773 (setq org-goto-selected-point nil)
7774 (setq org-goto-exit-command 'quit)
7775 (throw 'exit nil))
7777 ;;; Indirect buffer display of subtrees
7779 (defvar org-indirect-dedicated-frame nil
7780 "This is the frame being used for indirect tree display.")
7781 (defvar org-last-indirect-buffer nil)
7783 (defun org-tree-to-indirect-buffer (&optional arg)
7784 "Create indirect buffer and narrow it to current subtree.
7785 With a numerical prefix ARG, go up to this level and then take that tree.
7786 If ARG is negative, go up that many levels.
7788 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7789 indirect buffer previously made with this command, to avoid proliferation of
7790 indirect buffers. However, when you call the command with a \
7791 \\[universal-argument] prefix, or
7792 when `org-indirect-buffer-display' is `new-frame', the last buffer
7793 is kept so that you can work with several indirect buffers at the same time.
7794 If `org-indirect-buffer-display' is `dedicated-frame', the \
7795 \\[universal-argument] prefix also
7796 requests that a new frame be made for the new buffer, so that the dedicated
7797 frame is not changed."
7798 (interactive "P")
7799 (let ((cbuf (current-buffer))
7800 (cwin (selected-window))
7801 (pos (point))
7802 beg end level heading ibuf)
7803 (save-excursion
7804 (org-back-to-heading t)
7805 (when (numberp arg)
7806 (setq level (org-outline-level))
7807 (when (< arg 0) (setq arg (+ level arg)))
7808 (while (> (setq level (org-outline-level)) arg)
7809 (org-up-heading-safe)))
7810 (setq beg (point)
7811 heading (org-get-heading 'no-tags))
7812 (org-end-of-subtree t t)
7813 (when (org-at-heading-p) (backward-char 1))
7814 (setq end (point)))
7815 (when (and (buffer-live-p org-last-indirect-buffer)
7816 (not (eq org-indirect-buffer-display 'new-frame))
7817 (not arg))
7818 (kill-buffer org-last-indirect-buffer))
7819 (setq ibuf (org-get-indirect-buffer cbuf heading)
7820 org-last-indirect-buffer ibuf)
7821 (cond
7822 ((or (eq org-indirect-buffer-display 'new-frame)
7823 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7824 (select-frame (make-frame))
7825 (delete-other-windows)
7826 (pop-to-buffer-same-window ibuf)
7827 (org-set-frame-title heading))
7828 ((eq org-indirect-buffer-display 'dedicated-frame)
7829 (raise-frame
7830 (select-frame (or (and org-indirect-dedicated-frame
7831 (frame-live-p org-indirect-dedicated-frame)
7832 org-indirect-dedicated-frame)
7833 (setq org-indirect-dedicated-frame (make-frame)))))
7834 (delete-other-windows)
7835 (pop-to-buffer-same-window ibuf)
7836 (org-set-frame-title (concat "Indirect: " heading)))
7837 ((eq org-indirect-buffer-display 'current-window)
7838 (pop-to-buffer-same-window ibuf))
7839 ((eq org-indirect-buffer-display 'other-window)
7840 (pop-to-buffer ibuf))
7841 (t (error "Invalid value")))
7842 (narrow-to-region beg end)
7843 (outline-show-all)
7844 (goto-char pos)
7845 (run-hook-with-args 'org-cycle-hook 'all)
7846 (and (window-live-p cwin) (select-window cwin))))
7848 (defun org-get-indirect-buffer (&optional buffer heading)
7849 (setq buffer (or buffer (current-buffer)))
7850 (let ((n 1) (base (buffer-name buffer)) bname)
7851 (while (buffer-live-p
7852 (get-buffer
7853 (setq bname
7854 (concat base "-"
7855 (if heading (concat heading "-" (number-to-string n))
7856 (number-to-string n))))))
7857 (setq n (1+ n)))
7858 (condition-case nil
7859 (make-indirect-buffer buffer bname 'clone)
7860 (error (make-indirect-buffer buffer bname)))))
7862 (defun org-set-frame-title (title)
7863 "Set the title of the current frame to the string TITLE."
7864 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7866 ;;;; Structure editing
7868 ;;; Inserting headlines
7870 (defun org--line-empty-p (n)
7871 "Is the Nth next line empty?
7873 Counts the current line as N = 1 and the previous line as N = 0;
7874 see `beginning-of-line'."
7875 (save-excursion
7876 (and (not (bobp))
7877 (or (beginning-of-line n) t)
7878 (save-match-data
7879 (looking-at "[ \t]*$")))))
7881 (defun org-previous-line-empty-p ()
7882 "Is the previous line a blank line?
7883 When NEXT is non-nil, check the next line instead."
7884 (org--line-empty-p 0))
7886 (defun org-next-line-empty-p ()
7887 "Is the previous line a blank line?
7888 When NEXT is non-nil, check the next line instead."
7889 (org--line-empty-p 2))
7891 (defun org-insert-heading (&optional arg invisible-ok top)
7892 "Insert a new heading or an item with the same depth at point.
7894 If point is at the beginning of a heading or a list item, insert
7895 a new heading or a new item above the current one. If point is
7896 at the beginning of a normal line, turn the line into a heading.
7898 If point is in the middle of a headline or a list item, split the
7899 headline or the item and create a new headline/item with the text
7900 in the current line after point \(see `org-M-RET-may-split-line'
7901 on how to modify this behavior).
7903 With one universal prefix argument, set the user option
7904 `org-insert-heading-respect-content' to t for the duration of
7905 the command. This modifies the behavior described above in this
7906 ways: on list items and at the beginning of normal lines, force
7907 the insertion of a heading after the current subtree.
7909 With two universal prefix arguments, insert the heading at the
7910 end of the grandparent subtree. For example, if point is within
7911 a 2nd-level heading, then it will insert a 2nd-level heading at
7912 the end of the 1st-level parent heading.
7914 If point is at the beginning of a headline, insert a sibling
7915 before the current headline. If point is not at the beginning,
7916 split the line and create a new headline with the text in the
7917 current line after point \(see `org-M-RET-may-split-line' on how
7918 to modify this behavior).
7920 If point is at the beginning of a normal line, turn this line
7921 into a heading.
7923 When INVISIBLE-OK is set, stop at invisible headlines when going
7924 back. This is important for non-interactive uses of the
7925 command.
7927 When optional argument TOP is non-nil, insert a level 1 heading,
7928 unconditionally."
7929 (interactive "P")
7930 (let ((itemp (and (not top) (org-in-item-p)))
7931 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7932 (respect-content (or org-insert-heading-respect-content
7933 (equal arg '(4))))
7934 (initial-content ""))
7936 (cond
7938 ((or (= (buffer-size) 0)
7939 (and (not (save-excursion
7940 (and (ignore-errors (org-back-to-heading invisible-ok))
7941 (org-at-heading-p))))
7942 (or arg (not itemp))))
7943 ;; At beginning of buffer or so high up that only a heading
7944 ;; makes sense.
7945 (cond ((and (bolp) (not respect-content)) (insert "* "))
7946 ((not respect-content)
7947 (unless may-split (end-of-line))
7948 (insert "\n* "))
7949 ((re-search-forward org-outline-regexp-bol nil t)
7950 (beginning-of-line)
7951 (insert "* \n")
7952 (backward-char))
7953 (t (goto-char (point-max))
7954 (insert "\n* ")))
7955 (run-hooks 'org-insert-heading-hook))
7957 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7960 ;; Maybe move at the end of the subtree
7961 (when (equal arg '(16))
7962 (org-up-heading-safe)
7963 (org-end-of-subtree t))
7964 ;; Insert a heading
7965 (save-restriction
7966 (widen)
7967 (let* ((level nil)
7968 (on-heading (org-at-heading-p))
7969 (empty-line-p (if on-heading
7970 (org-previous-line-empty-p)
7971 ;; We will decide later
7972 nil))
7973 ;; Get a level string to fall back on.
7974 (fix-level
7975 (if (org-before-first-heading-p) "*"
7976 (save-excursion
7977 (org-back-to-heading t)
7978 (when (org-previous-line-empty-p) (setq empty-line-p t))
7979 (looking-at org-outline-regexp)
7980 (make-string (1- (length (match-string 0))) ?*))))
7981 (stars
7982 (save-excursion
7983 (condition-case nil
7984 (if top "* "
7985 (org-back-to-heading invisible-ok)
7986 (when (and (not on-heading)
7987 (featurep 'org-inlinetask)
7988 (integerp org-inlinetask-min-level)
7989 (>= (length (match-string 0))
7990 org-inlinetask-min-level))
7991 ;; Find a heading level before the inline
7992 ;; task.
7993 (while (and (setq level (org-up-heading-safe))
7994 (>= level org-inlinetask-min-level)))
7995 (if (org-at-heading-p)
7996 (org-back-to-heading invisible-ok)
7997 (error "This should not happen")))
7998 (unless (and (save-excursion
7999 (save-match-data
8000 (org-backward-heading-same-level
8001 1 invisible-ok))
8002 (= (point) (match-beginning 0)))
8003 (not (org-next-line-empty-p)))
8004 (setq empty-line-p (or empty-line-p
8005 (org-previous-line-empty-p))))
8006 (match-string 0))
8007 (error (or fix-level "* ")))))
8008 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
8009 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
8011 ;; If we insert after content, move there and clean up
8012 ;; whitespace.
8013 (when (and respect-content
8014 (not (looking-at-p org-outline-regexp-bol)))
8015 (if (not (org-before-first-heading-p))
8016 (org-end-of-subtree nil t)
8017 (re-search-forward org-outline-regexp-bol)
8018 (beginning-of-line 0))
8019 (skip-chars-backward " \r\t\n")
8020 (and (not (looking-back "^\\*+" (line-beginning-position)))
8021 (looking-at "[ \t]+") (replace-match ""))
8022 (unless (eobp) (forward-char 1))
8023 (when (looking-at "^\\*")
8024 (unless (bobp) (backward-char 1))
8025 (insert "\n")))
8027 ;; If we are splitting, grab the text that should be moved
8028 ;; to the new headline.
8029 (when may-split
8030 (if (org-at-heading-p)
8031 ;; This is a heading: split intelligently (keeping
8032 ;; tags).
8033 (let ((pos (point)))
8034 (beginning-of-line)
8035 (unless (looking-at org-complex-heading-regexp)
8036 (error "This should not happen"))
8037 (when (and (match-beginning 4)
8038 (> pos (match-beginning 4))
8039 (< pos (match-end 4)))
8040 (setq initial-content (buffer-substring pos (match-end 4)))
8041 (goto-char pos)
8042 (delete-region (point) (match-end 4))
8043 (if (looking-at "[ \t]*$")
8044 (replace-match "")
8045 (insert (make-string (length initial-content) ?\s)))
8046 (setq initial-content (org-trim initial-content)))
8047 (goto-char pos))
8048 ;; A normal line.
8049 (setq initial-content
8050 (org-trim
8051 (delete-and-extract-region (point) (line-end-position))))))
8053 ;; If we are at the beginning of the line, insert before it.
8054 ;; Otherwise, after it.
8055 (cond
8056 ((and (bolp) (looking-at "[ \t]*$")))
8057 ((bolp) (save-excursion (insert "\n")))
8058 (t (end-of-line)
8059 (insert "\n")))
8061 ;; Insert the new heading
8062 (insert stars)
8063 (just-one-space)
8064 (insert initial-content)
8065 (unless (and blank (org-previous-line-empty-p))
8066 (org-N-empty-lines-before-current (if blank 1 0)))
8067 ;; Adjust visibility, which may be messed up if we removed
8068 ;; blank lines while previous entry was hidden.
8069 (let ((bol (line-beginning-position)))
8070 (dolist (o (overlays-at (1- bol)))
8071 (when (and (eq (overlay-get o 'invisible) 'outline)
8072 (eq (overlay-end o) bol))
8073 (move-overlay o (overlay-start o) (1- bol)))))
8074 (run-hooks 'org-insert-heading-hook)))))))
8076 (defun org-N-empty-lines-before-current (N)
8077 "Make the number of empty lines before current exactly N.
8078 So this will delete or add empty lines."
8079 (save-excursion
8080 (beginning-of-line)
8081 (let ((p (point)))
8082 (skip-chars-backward " \r\t\n")
8083 (unless (bolp) (forward-line))
8084 (delete-region (point) p))
8085 (when (> N 0) (insert (make-string N ?\n)))))
8087 (defun org-get-heading (&optional no-tags no-todo)
8088 "Return the heading of the current entry, without the stars.
8089 When NO-TAGS is non-nil, don't include tags.
8090 When NO-TODO is non-nil, don't include TODO keywords."
8091 (save-excursion
8092 (org-back-to-heading t)
8093 (let ((case-fold-search nil))
8094 (cond
8095 ((and no-tags no-todo)
8096 (looking-at org-complex-heading-regexp)
8097 ;; Return value has to be a string, but match group 4 is
8098 ;; optional.
8099 (or (match-string 4) ""))
8100 (no-tags
8101 (looking-at (concat org-outline-regexp
8102 "\\(.*?\\)"
8103 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8104 (match-string 1))
8105 (no-todo
8106 (looking-at org-todo-line-regexp)
8107 (match-string 3))
8108 (t (looking-at org-heading-regexp)
8109 (match-string 2))))))
8111 (defvar orgstruct-mode) ; defined below
8113 (defun org-heading-components ()
8114 "Return the components of the current heading.
8115 This is a list with the following elements:
8116 - the level as an integer
8117 - the reduced level, different if `org-odd-levels-only' is set.
8118 - the TODO keyword, or nil
8119 - the priority character, like ?A, or nil if no priority is given
8120 - the headline text itself, or the tags string if no headline text
8121 - the tags string, or nil."
8122 (save-excursion
8123 (org-back-to-heading t)
8124 (when (let (case-fold-search)
8125 (looking-at
8126 (if orgstruct-mode
8127 org-heading-regexp
8128 org-complex-heading-regexp)))
8129 (if orgstruct-mode
8130 (list (length (match-string 1))
8131 (org-reduced-level (length (match-string 1)))
8134 (match-string 2)
8135 nil)
8136 (list (length (match-string 1))
8137 (org-reduced-level (length (match-string 1)))
8138 (match-string-no-properties 2)
8139 (and (match-end 3) (aref (match-string 3) 2))
8140 (match-string-no-properties 4)
8141 (match-string-no-properties 5))))))
8143 (defun org-get-entry ()
8144 "Get the entry text, after heading, entire subtree."
8145 (save-excursion
8146 (org-back-to-heading t)
8147 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8149 (defun org-edit-headline (&optional heading)
8150 "Edit the current headline.
8151 Set it to HEADING when provided."
8152 (interactive)
8153 (org-with-wide-buffer
8154 (org-back-to-heading t)
8155 (when (looking-at org-complex-heading-regexp)
8156 (let* ((old (match-string-no-properties 4))
8157 (new (save-match-data
8158 (org-trim (or heading (read-string "Edit: " old))))))
8159 (unless (equal old new)
8160 (if old (replace-match new t t nil 4)
8161 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8162 (insert " " new))
8163 (org-set-tags nil t)
8164 (when (looking-at "[ \t]*$") (replace-match "")))))))
8166 (defun org-insert-heading-after-current ()
8167 "Insert a new heading with same level as current, after current subtree."
8168 (interactive)
8169 (org-back-to-heading)
8170 (org-insert-heading)
8171 (org-move-subtree-down)
8172 (end-of-line 1))
8174 (defun org-insert-heading-respect-content (&optional invisible-ok)
8175 "Insert heading with `org-insert-heading-respect-content' set to t."
8176 (interactive)
8177 (org-insert-heading '(4) invisible-ok))
8179 (defun org-insert-todo-heading-respect-content (&optional force-state)
8180 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8181 (interactive)
8182 (org-insert-todo-heading force-state '(4)))
8184 (defun org-insert-todo-heading (arg &optional force-heading)
8185 "Insert a new heading with the same level and TODO state as current heading.
8186 If the heading has no TODO state, or if the state is DONE, use the first
8187 state (TODO by default). Also with one prefix arg, force first state. With
8188 two prefix args, force inserting at the end of the parent subtree."
8189 (interactive "P")
8190 (when (or force-heading (not (org-insert-item 'checkbox)))
8191 (org-insert-heading (or (and (equal arg '(16)) '(16))
8192 force-heading))
8193 (save-excursion
8194 (org-back-to-heading)
8195 (outline-previous-heading)
8196 (looking-at org-todo-line-regexp))
8197 (let*
8198 ((new-mark-x
8199 (if (or (equal arg '(4))
8200 (not (match-beginning 2))
8201 (member (match-string 2) org-done-keywords))
8202 (car org-todo-keywords-1)
8203 (match-string 2)))
8204 (new-mark
8206 (run-hook-with-args-until-success
8207 'org-todo-get-default-hook new-mark-x nil)
8208 new-mark-x)))
8209 (beginning-of-line 1)
8210 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8211 (if org-treat-insert-todo-heading-as-state-change
8212 (org-todo new-mark)
8213 (insert new-mark " "))))
8214 (when org-provide-todo-statistics
8215 (org-update-parent-todo-statistics))))
8217 (defun org-insert-subheading (arg)
8218 "Insert a new subheading and demote it.
8219 Works for outline headings and for plain lists alike."
8220 (interactive "P")
8221 (org-insert-heading arg)
8222 (cond
8223 ((org-at-heading-p) (org-do-demote))
8224 ((org-at-item-p) (org-indent-item))))
8226 (defun org-insert-todo-subheading (arg)
8227 "Insert a new subheading with TODO keyword or checkbox and demote it.
8228 Works for outline headings and for plain lists alike."
8229 (interactive "P")
8230 (org-insert-todo-heading arg)
8231 (cond
8232 ((org-at-heading-p) (org-do-demote))
8233 ((org-at-item-p) (org-indent-item))))
8235 ;;; Promotion and Demotion
8237 (defvar org-after-demote-entry-hook nil
8238 "Hook run after an entry has been demoted.
8239 The cursor will be at the beginning of the entry.
8240 When a subtree is being demoted, the hook will be called for each node.")
8242 (defvar org-after-promote-entry-hook nil
8243 "Hook run after an entry has been promoted.
8244 The cursor will be at the beginning of the entry.
8245 When a subtree is being promoted, the hook will be called for each node.")
8247 (defun org-promote-subtree ()
8248 "Promote the entire subtree.
8249 See also `org-promote'."
8250 (interactive)
8251 (save-excursion
8252 (org-with-limited-levels (org-map-tree 'org-promote)))
8253 (org-fix-position-after-promote))
8255 (defun org-demote-subtree ()
8256 "Demote the entire subtree.
8257 See `org-demote' and `org-promote'."
8258 (interactive)
8259 (save-excursion
8260 (org-with-limited-levels (org-map-tree 'org-demote)))
8261 (org-fix-position-after-promote))
8263 (defun org-do-promote ()
8264 "Promote the current heading higher up the tree.
8265 If the region is active in `transient-mark-mode', promote all
8266 headings in the region."
8267 (interactive)
8268 (save-excursion
8269 (if (org-region-active-p)
8270 (org-map-region 'org-promote (region-beginning) (region-end))
8271 (org-promote)))
8272 (org-fix-position-after-promote))
8274 (defun org-do-demote ()
8275 "Demote the current heading lower down the tree.
8276 If the region is active in `transient-mark-mode', demote all
8277 headings in the region."
8278 (interactive)
8279 (save-excursion
8280 (if (org-region-active-p)
8281 (org-map-region 'org-demote (region-beginning) (region-end))
8282 (org-demote)))
8283 (org-fix-position-after-promote))
8285 (defun org-fix-position-after-promote ()
8286 "Fix cursor position and indentation after demoting/promoting."
8287 (let ((pos (point)))
8288 (when (save-excursion
8289 (beginning-of-line 1)
8290 (looking-at org-todo-line-regexp)
8291 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8292 (cond ((eobp) (insert " "))
8293 ((eolp) (insert " "))
8294 ((equal (char-after) ?\ ) (forward-char 1))))))
8296 (defun org-current-level ()
8297 "Return the level of the current entry, or nil if before the first headline.
8298 The level is the number of stars at the beginning of the
8299 headline. Use `org-reduced-level' to remove the effect of
8300 `org-odd-levels'. Unlike to `org-outline-level', this function
8301 ignores inlinetasks."
8302 (let ((level (org-with-limited-levels (org-outline-level))))
8303 (and (> level 0) level)))
8305 (defun org-get-previous-line-level ()
8306 "Return the outline depth of the last headline before the current line.
8307 Returns 0 for the first headline in the buffer, and nil if before the
8308 first headline."
8309 (and (org-current-level)
8310 (or (and (/= (line-beginning-position) (point-min))
8311 (save-excursion (beginning-of-line 0) (org-current-level)))
8312 0)))
8314 (defun org-reduced-level (l)
8315 "Compute the effective level of a heading.
8316 This takes into account the setting of `org-odd-levels-only'."
8317 (cond
8318 ((zerop l) 0)
8319 (org-odd-levels-only (1+ (floor (/ l 2))))
8320 (t l)))
8322 (defun org-level-increment ()
8323 "Return the number of stars that will be added or removed at a
8324 time to headlines when structure editing, based on the value of
8325 `org-odd-levels-only'."
8326 (if org-odd-levels-only 2 1))
8328 (defun org-get-valid-level (level &optional change)
8329 "Rectify a level change under the influence of `org-odd-levels-only'
8330 LEVEL is a current level, CHANGE is by how much the level should be
8331 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8332 even level numbers will become the next higher odd number."
8333 (if org-odd-levels-only
8334 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8335 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8336 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8337 (max 1 (+ level (or change 0)))))
8339 (defun org-promote ()
8340 "Promote the current heading higher up the tree."
8341 (org-with-wide-buffer
8342 (org-back-to-heading t)
8343 (let* ((after-change-functions (remq 'flyspell-after-change-function
8344 after-change-functions))
8345 (level (save-match-data (funcall outline-level)))
8346 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8347 (diff (abs (- level (length up-head) -1))))
8348 (cond
8349 ((and (= level 1) org-allow-promoting-top-level-subtree)
8350 (replace-match "# " nil t))
8351 ((= level 1)
8352 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8353 (t (replace-match up-head nil t)))
8354 (unless (= level 1)
8355 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8356 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8357 (run-hooks 'org-after-promote-entry-hook))))
8359 (defun org-demote ()
8360 "Demote the current heading lower down the tree."
8361 (org-with-wide-buffer
8362 (org-back-to-heading t)
8363 (let* ((after-change-functions (remq 'flyspell-after-change-function
8364 after-change-functions))
8365 (level (save-match-data (funcall outline-level)))
8366 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8367 (diff (abs (- level (length down-head) -1))))
8368 (replace-match down-head nil t)
8369 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8370 (when org-adapt-indentation (org-fixup-indentation diff))
8371 (run-hooks 'org-after-demote-entry-hook))))
8373 (defun org-cycle-level ()
8374 "Cycle the level of an empty headline through possible states.
8375 This goes first to child, then to parent, level, then up the hierarchy.
8376 After top level, it switches back to sibling level."
8377 (interactive)
8378 (let ((org-adapt-indentation nil))
8379 (when (org-point-at-end-of-empty-headline)
8380 (setq this-command 'org-cycle-level) ; Only needed for caching
8381 (let ((cur-level (org-current-level))
8382 (prev-level (org-get-previous-line-level)))
8383 (cond
8384 ;; If first headline in file, promote to top-level.
8385 ((= prev-level 0)
8386 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8387 do (org-do-promote)))
8388 ;; If same level as prev, demote one.
8389 ((= prev-level cur-level)
8390 (org-do-demote))
8391 ;; If parent is top-level, promote to top level if not already.
8392 ((= prev-level 1)
8393 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8394 do (org-do-promote)))
8395 ;; If top-level, return to prev-level.
8396 ((= cur-level 1)
8397 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8398 do (org-do-demote)))
8399 ;; If less than prev-level, promote one.
8400 ((< cur-level prev-level)
8401 (org-do-promote))
8402 ;; If deeper than prev-level, promote until higher than
8403 ;; prev-level.
8404 ((> cur-level prev-level)
8405 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8406 do (org-do-promote))))
8407 t))))
8409 (defun org-map-tree (fun)
8410 "Call FUN for every heading underneath the current one."
8411 (org-back-to-heading t)
8412 (let ((level (funcall outline-level)))
8413 (save-excursion
8414 (funcall fun)
8415 (while (and (progn
8416 (outline-next-heading)
8417 (> (funcall outline-level) level))
8418 (not (eobp)))
8419 (funcall fun)))))
8421 (defun org-map-region (fun beg end)
8422 "Call FUN for every heading between BEG and END."
8423 (let ((org-ignore-region t))
8424 (save-excursion
8425 (setq end (copy-marker end))
8426 (goto-char beg)
8427 (when (and (re-search-forward org-outline-regexp-bol nil t)
8428 (< (point) end))
8429 (funcall fun))
8430 (while (and (progn
8431 (outline-next-heading)
8432 (< (point) end))
8433 (not (eobp)))
8434 (funcall fun)))))
8436 (defun org-fixup-indentation (diff)
8437 "Change the indentation in the current entry by DIFF.
8439 DIFF is an integer. Indentation is done according to the
8440 following rules:
8442 - Planning information and property drawers are always indented
8443 according to the new level of the headline;
8445 - Footnote definitions and their contents are ignored;
8447 - Inlinetasks' boundaries are not shifted;
8449 - Empty lines are ignored;
8451 - Other lines' indentation are shifted by DIFF columns, unless
8452 it would introduce a structural change in the document, in
8453 which case no shifting is done at all.
8455 Assume point is at a heading or an inlinetask beginning."
8456 (org-with-wide-buffer
8457 (narrow-to-region (line-beginning-position)
8458 (save-excursion
8459 (if (org-with-limited-levels (org-at-heading-p))
8460 (org-with-limited-levels (outline-next-heading))
8461 (org-inlinetask-goto-end))
8462 (point)))
8463 (forward-line)
8464 ;; Indent properly planning info and property drawer.
8465 (when (looking-at-p org-planning-line-re)
8466 (org-indent-line)
8467 (forward-line))
8468 (when (looking-at org-property-drawer-re)
8469 (goto-char (match-end 0))
8470 (forward-line)
8471 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8472 (catch 'no-shift
8473 (when (zerop diff) (throw 'no-shift nil))
8474 ;; If DIFF is negative, first check if a shift is possible at all
8475 ;; (e.g., it doesn't break structure). This can only happen if
8476 ;; some contents are not properly indented.
8477 (let ((case-fold-search t))
8478 (when (< diff 0)
8479 (let ((diff (- diff))
8480 (forbidden-re (concat org-outline-regexp
8481 "\\|"
8482 (substring org-footnote-definition-re 1))))
8483 (save-excursion
8484 (while (not (eobp))
8485 (cond
8486 ((looking-at-p "[ \t]*$") (forward-line))
8487 ((and (looking-at-p org-footnote-definition-re)
8488 (let ((e (org-element-at-point)))
8489 (and (eq (org-element-type e) 'footnote-definition)
8490 (goto-char (org-element-property :end e))))))
8491 ((looking-at-p org-outline-regexp) (forward-line))
8492 ;; Give up if shifting would move before column 0 or
8493 ;; if it would introduce a headline or a footnote
8494 ;; definition.
8496 (skip-chars-forward " \t")
8497 (let ((ind (current-column)))
8498 (when (or (< ind diff)
8499 (and (= ind diff) (looking-at-p forbidden-re)))
8500 (throw 'no-shift nil)))
8501 ;; Ignore contents of example blocks and source
8502 ;; blocks if their indentation is meant to be
8503 ;; preserved. Jump to block's closing line.
8504 (beginning-of-line)
8505 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8506 (let ((e (org-element-at-point)))
8507 (and (memq (org-element-type e)
8508 '(example-block src-block))
8509 (or org-src-preserve-indentation
8510 (org-element-property :preserve-indent e))
8511 (goto-char (org-element-property :end e))
8512 (progn (skip-chars-backward " \r\t\n")
8513 (beginning-of-line)
8514 t))))
8515 (forward-line))))))))
8516 ;; Shift lines but footnote definitions, inlinetasks boundaries
8517 ;; by DIFF. Also skip contents of source or example blocks
8518 ;; when indentation is meant to be preserved.
8519 (while (not (eobp))
8520 (cond
8521 ((and (looking-at-p org-footnote-definition-re)
8522 (let ((e (org-element-at-point)))
8523 (and (eq (org-element-type e) 'footnote-definition)
8524 (goto-char (org-element-property :end e))))))
8525 ((looking-at-p org-outline-regexp) (forward-line))
8526 ((looking-at-p "[ \t]*$") (forward-line))
8528 (indent-line-to (+ (org-get-indentation) diff))
8529 (beginning-of-line)
8530 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8531 (let ((e (org-element-at-point)))
8532 (and (memq (org-element-type e)
8533 '(example-block src-block))
8534 (or org-src-preserve-indentation
8535 (org-element-property :preserve-indent e))
8536 (goto-char (org-element-property :end e))
8537 (progn (skip-chars-backward " \r\t\n")
8538 (beginning-of-line)
8539 t))))
8540 (forward-line)))))))))
8542 (defun org-convert-to-odd-levels ()
8543 "Convert an Org file with all levels allowed to one with odd levels.
8544 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8545 level 5 etc."
8546 (interactive)
8547 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8548 (let ((outline-level 'org-outline-level)
8549 (org-odd-levels-only nil) n)
8550 (save-excursion
8551 (goto-char (point-min))
8552 (while (re-search-forward "^\\*\\*+ " nil t)
8553 (setq n (- (length (match-string 0)) 2))
8554 (while (>= (setq n (1- n)) 0)
8555 (org-demote))
8556 (end-of-line 1))))))
8558 (defun org-convert-to-oddeven-levels ()
8559 "Convert an Org file with only odd levels to one with odd/even levels.
8560 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8561 file contains a section with an even level, conversion would
8562 destroy the structure of the file. An error is signaled in this
8563 case."
8564 (interactive)
8565 (goto-char (point-min))
8566 ;; First check if there are no even levels
8567 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8568 (org-show-set-visibility 'canonical)
8569 (error "Not all levels are odd in this file. Conversion not possible"))
8570 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8571 (let ((outline-regexp org-outline-regexp)
8572 (outline-level 'org-outline-level)
8573 (org-odd-levels-only nil) n)
8574 (save-excursion
8575 (goto-char (point-min))
8576 (while (re-search-forward "^\\*\\*+ " nil t)
8577 (setq n (/ (1- (length (match-string 0))) 2))
8578 (while (>= (setq n (1- n)) 0)
8579 (org-promote))
8580 (end-of-line 1))))))
8582 (defun org-tr-level (n)
8583 "Make N odd if required."
8584 (if org-odd-levels-only (1+ (/ n 2)) n))
8586 ;;; Vertical tree motion, cutting and pasting of subtrees
8588 (defun org-move-subtree-up (&optional arg)
8589 "Move the current subtree up past ARG headlines of the same level."
8590 (interactive "p")
8591 (org-move-subtree-down (- (prefix-numeric-value arg))))
8593 (defun org-move-subtree-down (&optional arg)
8594 "Move the current subtree down past ARG headlines of the same level."
8595 (interactive "p")
8596 (setq arg (prefix-numeric-value arg))
8597 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8598 'org-get-last-sibling))
8599 (ins-point (make-marker))
8600 (cnt (abs arg))
8601 (col (current-column))
8602 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8603 ;; Select the tree
8604 (org-back-to-heading)
8605 (setq beg0 (point))
8606 (save-excursion
8607 (setq ne-beg (org-back-over-empty-lines))
8608 (setq beg (point)))
8609 (save-match-data
8610 (save-excursion (outline-end-of-heading)
8611 (setq folded (outline-invisible-p)))
8612 (progn (org-end-of-subtree nil t)
8613 (unless (eobp) (backward-char))))
8614 (outline-next-heading)
8615 (setq ne-end (org-back-over-empty-lines))
8616 (setq end (point))
8617 (goto-char beg0)
8618 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8619 ;; include less whitespace
8620 (save-excursion
8621 (goto-char beg)
8622 (forward-line (- ne-beg ne-end))
8623 (setq beg (point))))
8624 ;; Find insertion point, with error handling
8625 (while (> cnt 0)
8626 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8627 (progn (goto-char beg0)
8628 (user-error "Cannot move past superior level or buffer limit")))
8629 (setq cnt (1- cnt)))
8630 (when (> arg 0)
8631 ;; Moving forward - still need to move over subtree
8632 (org-end-of-subtree t t)
8633 (save-excursion
8634 (org-back-over-empty-lines)
8635 (or (bolp) (newline))))
8636 (setq ne-ins (org-back-over-empty-lines))
8637 (move-marker ins-point (point))
8638 (setq txt (buffer-substring beg end))
8639 (org-save-markers-in-region beg end)
8640 (delete-region beg end)
8641 (org-remove-empty-overlays-at beg)
8642 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8643 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8644 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8645 (let ((bbb (point)))
8646 (insert-before-markers txt)
8647 (org-reinstall-markers-in-region bbb)
8648 (move-marker ins-point bbb))
8649 (or (bolp) (insert "\n"))
8650 (setq ins-end (point))
8651 (goto-char ins-point)
8652 (org-skip-whitespace)
8653 (when (and (< arg 0)
8654 (org-first-sibling-p)
8655 (> ne-ins ne-beg))
8656 ;; Move whitespace back to beginning
8657 (save-excursion
8658 (goto-char ins-end)
8659 (let ((kill-whole-line t))
8660 (kill-line (- ne-ins ne-beg)) (point)))
8661 (insert (make-string (- ne-ins ne-beg) ?\n)))
8662 (move-marker ins-point nil)
8663 (if folded
8664 (outline-hide-subtree)
8665 (org-show-entry)
8666 (org-show-children)
8667 (org-cycle-hide-drawers 'children))
8668 (org-clean-visibility-after-subtree-move)
8669 ;; move back to the initial column we were at
8670 (move-to-column col)))
8672 (defvar org-subtree-clip ""
8673 "Clipboard for cut and paste of subtrees.
8674 This is actually only a copy of the kill, because we use the normal kill
8675 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8677 (defvar org-subtree-clip-folded nil
8678 "Was the last copied subtree folded?
8679 This is used to fold the tree back after pasting.")
8681 (defun org-cut-subtree (&optional n)
8682 "Cut the current subtree into the clipboard.
8683 With prefix arg N, cut this many sequential subtrees.
8684 This is a short-hand for marking the subtree and then cutting it."
8685 (interactive "p")
8686 (org-copy-subtree n 'cut))
8688 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8689 "Copy the current subtree it in the clipboard.
8690 With prefix arg N, copy this many sequential subtrees.
8691 This is a short-hand for marking the subtree and then copying it.
8692 If CUT is non-nil, actually cut the subtree.
8693 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8694 of some markers in the region, even if CUT is non-nil. This is
8695 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8696 (interactive "p")
8697 (let (beg end folded (beg0 (point)))
8698 (if (called-interactively-p 'any)
8699 (org-back-to-heading nil) ; take what looks like a subtree
8700 (org-back-to-heading t)) ; take what is really there
8701 (setq beg (point))
8702 (skip-chars-forward " \t\r\n")
8703 (save-match-data
8704 (if nosubtrees
8705 (outline-next-heading)
8706 (save-excursion (outline-end-of-heading)
8707 (setq folded (outline-invisible-p)))
8708 (ignore-errors (org-forward-heading-same-level (1- n) t))
8709 (org-end-of-subtree t t)))
8710 ;; Include the end of an inlinetask
8711 (when (and (featurep 'org-inlinetask)
8712 (looking-at-p (concat (org-inlinetask-outline-regexp)
8713 "END[ \t]*$")))
8714 (end-of-line))
8715 (setq end (point))
8716 (goto-char beg0)
8717 (when (> end beg)
8718 (setq org-subtree-clip-folded folded)
8719 (when (or cut force-store-markers)
8720 (org-save-markers-in-region beg end))
8721 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8722 (setq org-subtree-clip (current-kill 0))
8723 (message "%s: Subtree(s) with %d characters"
8724 (if cut "Cut" "Copied")
8725 (length org-subtree-clip)))))
8727 (defun org-paste-subtree (&optional level tree for-yank remove)
8728 "Paste the clipboard as a subtree, with modification of headline level.
8729 The entire subtree is promoted or demoted in order to match a new headline
8730 level.
8732 If the cursor is at the beginning of a headline, the same level as
8733 that headline is used to paste the tree.
8735 If not, the new level is derived from the *visible* headings
8736 before and after the insertion point, and taken to be the inferior headline
8737 level of the two. So if the previous visible heading is level 3 and the
8738 next is level 4 (or vice versa), level 4 will be used for insertion.
8739 This makes sure that the subtree remains an independent subtree and does
8740 not swallow low level entries.
8742 You can also force a different level, either by using a numeric prefix
8743 argument, or by inserting the heading marker by hand. For example, if the
8744 cursor is after \"*****\", then the tree will be shifted to level 5.
8746 If optional TREE is given, use this text instead of the kill ring.
8748 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8749 move back over whitespace before inserting, and move point to the end of
8750 the inserted text when done.
8752 When REMOVE is non-nil, remove the subtree from the clipboard."
8753 (interactive "P")
8754 (setq tree (or tree (and kill-ring (current-kill 0))))
8755 (unless (org-kill-is-subtree-p tree)
8756 (user-error "%s"
8757 (substitute-command-keys
8758 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8759 (org-with-limited-levels
8760 (let* ((visp (not (outline-invisible-p)))
8761 (txt tree)
8762 (^re_ "\\(\\*+\\)[ \t]*")
8763 (old-level (if (string-match org-outline-regexp-bol txt)
8764 (- (match-end 0) (match-beginning 0) 1)
8765 -1))
8766 (force-level (cond (level (prefix-numeric-value level))
8767 ((and (looking-at "[ \t]*$")
8768 (string-match
8769 "^\\*+$" (buffer-substring
8770 (point-at-bol) (point))))
8771 (- (match-end 0) (match-beginning 0)))
8772 ((and (bolp)
8773 (looking-at org-outline-regexp))
8774 (- (match-end 0) (point) 1))))
8775 (previous-level (save-excursion
8776 (condition-case nil
8777 (progn
8778 (outline-previous-visible-heading 1)
8779 (if (looking-at ^re_)
8780 (- (match-end 0) (match-beginning 0) 1)
8782 (error 1))))
8783 (next-level (save-excursion
8784 (condition-case nil
8785 (progn
8786 (or (looking-at org-outline-regexp)
8787 (outline-next-visible-heading 1))
8788 (if (looking-at ^re_)
8789 (- (match-end 0) (match-beginning 0) 1)
8791 (error 1))))
8792 (new-level (or force-level (max previous-level next-level)))
8793 (shift (if (or (= old-level -1)
8794 (= new-level -1)
8795 (= old-level new-level))
8797 (- new-level old-level)))
8798 (delta (if (> shift 0) -1 1))
8799 (func (if (> shift 0) 'org-demote 'org-promote))
8800 (org-odd-levels-only nil)
8801 beg end newend)
8802 ;; Remove the forced level indicator
8803 (when force-level
8804 (delete-region (point-at-bol) (point)))
8805 ;; Paste
8806 (beginning-of-line (if (bolp) 1 2))
8807 (setq beg (point))
8808 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8809 (insert-before-markers txt)
8810 (unless (string-match "\n\\'" txt) (insert "\n"))
8811 (setq newend (point))
8812 (org-reinstall-markers-in-region beg)
8813 (setq end (point))
8814 (goto-char beg)
8815 (skip-chars-forward " \t\n\r")
8816 (setq beg (point))
8817 (when (and (outline-invisible-p) visp)
8818 (save-excursion (outline-show-heading)))
8819 ;; Shift if necessary
8820 (unless (= shift 0)
8821 (save-restriction
8822 (narrow-to-region beg end)
8823 (while (not (= shift 0))
8824 (org-map-region func (point-min) (point-max))
8825 (setq shift (+ delta shift)))
8826 (goto-char (point-min))
8827 (setq newend (point-max))))
8828 (when (or (called-interactively-p 'interactive) for-yank)
8829 (message "Clipboard pasted as level %d subtree" new-level))
8830 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8831 kill-ring
8832 (eq org-subtree-clip (current-kill 0))
8833 org-subtree-clip-folded)
8834 ;; The tree was folded before it was killed/copied
8835 (outline-hide-subtree))
8836 (and for-yank (goto-char newend))
8837 (and remove (setq kill-ring (cdr kill-ring))))))
8839 (defun org-kill-is-subtree-p (&optional txt)
8840 "Check if the current kill is an outline subtree, or a set of trees.
8841 Returns nil if kill does not start with a headline, or if the first
8842 headline level is not the largest headline level in the tree.
8843 So this will actually accept several entries of equal levels as well,
8844 which is OK for `org-paste-subtree'.
8845 If optional TXT is given, check this string instead of the current kill."
8846 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8847 (re (org-get-limited-outline-regexp))
8848 (^re (concat "^" re))
8849 (start-level (and kill
8850 (string-match
8851 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8852 kill)
8853 (- (match-end 2) (match-beginning 2) 1)))
8854 (start (1+ (or (match-beginning 2) -1))))
8855 (if (not start-level)
8856 (progn
8857 nil) ;; does not even start with a heading
8858 (catch 'exit
8859 (while (setq start (string-match ^re kill (1+ start)))
8860 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8861 (throw 'exit nil)))
8862 t))))
8864 (defvar org-markers-to-move nil
8865 "Markers that should be moved with a cut-and-paste operation.
8866 Those markers are stored together with their positions relative to
8867 the start of the region.")
8869 (defun org-save-markers-in-region (beg end)
8870 "Check markers in region.
8871 If these markers are between BEG and END, record their position relative
8872 to BEG, so that after moving the block of text, we can put the markers back
8873 into place.
8874 This function gets called just before an entry or tree gets cut from the
8875 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8876 called immediately, to move the markers with the entries."
8877 (setq org-markers-to-move nil)
8878 (when (featurep 'org-clock)
8879 (org-clock-save-markers-for-cut-and-paste beg end))
8880 (when (featurep 'org-agenda)
8881 (org-agenda-save-markers-for-cut-and-paste beg end)))
8883 (defun org-check-and-save-marker (marker beg end)
8884 "Check if MARKER is between BEG and END.
8885 If yes, remember the marker and the distance to BEG."
8886 (when (and (marker-buffer marker)
8887 (equal (marker-buffer marker) (current-buffer))
8888 (>= marker beg) (< marker end))
8889 (push (cons marker (- marker beg)) org-markers-to-move)))
8891 (defun org-reinstall-markers-in-region (beg)
8892 "Move all remembered markers to their position relative to BEG."
8893 (dolist (x org-markers-to-move)
8894 (move-marker (car x) (+ beg (cdr x))))
8895 (setq org-markers-to-move nil))
8897 (defun org-narrow-to-subtree ()
8898 "Narrow buffer to the current subtree."
8899 (interactive)
8900 (save-excursion
8901 (save-match-data
8902 (org-with-limited-levels
8903 (narrow-to-region
8904 (progn (org-back-to-heading t) (point))
8905 (progn (org-end-of-subtree t t)
8906 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8907 (point)))))))
8909 (defun org-narrow-to-block ()
8910 "Narrow buffer to the current block."
8911 (interactive)
8912 (let* ((case-fold-search t)
8913 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8914 "^[ \t]*#\\+end_.*")))
8915 (if blockp
8916 (narrow-to-region (car blockp) (cdr blockp))
8917 (user-error "Not in a block"))))
8919 (defun org-clone-subtree-with-time-shift (n &optional shift)
8920 "Clone the task (subtree) at point N times.
8921 The clones will be inserted as siblings.
8923 In interactive use, the user will be prompted for the number of
8924 clones to be produced. If the entry has a timestamp, the user
8925 will also be prompted for a time shift, which may be a repeater
8926 as used in time stamps, for example `+3d'. To disable this,
8927 you can call the function with a universal prefix argument.
8929 When a valid repeater is given and the entry contains any time
8930 stamps, the clones will become a sequence in time, with time
8931 stamps in the subtree shifted for each clone produced. If SHIFT
8932 is nil or the empty string, time stamps will be left alone. The
8933 ID property of the original subtree is removed.
8935 If the original subtree did contain time stamps with a repeater,
8936 the following will happen:
8937 - the repeater will be removed in each clone
8938 - an additional clone will be produced, with the current, unshifted
8939 date(s) in the entry.
8940 - the original entry will be placed *after* all the clones, with
8941 repeater intact.
8942 - the start days in the repeater in the original entry will be shifted
8943 to past the last clone.
8944 In this way you can spell out a number of instances of a repeating task,
8945 and still retain the repeater to cover future instances of the task.
8947 As described above, N+1 clones are produced when the original
8948 subtree has a repeater. Setting N to 0, then, can be used to
8949 remove the repeater from a subtree and create a shifted clone
8950 with the original repeater."
8951 (interactive "nNumber of clones to produce: ")
8952 (let ((shift
8953 (or shift
8954 (if (and (not (equal current-prefix-arg '(4)))
8955 (save-excursion
8956 (re-search-forward org-ts-regexp-both
8957 (save-excursion
8958 (org-end-of-subtree t)
8959 (point)) t)))
8960 (read-from-minibuffer
8961 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8962 ""))) ;; No time shift
8963 (n-no-remove -1)
8964 (drawer-re org-drawer-regexp)
8965 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8966 beg end template task idprop
8967 shift-n shift-what doshift nmin nmax)
8968 (unless (wholenump n)
8969 (user-error "Invalid number of replications %s" n))
8970 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8971 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8972 shift)))
8973 (user-error "Invalid shift specification %s" shift))
8974 (when doshift
8975 (setq shift-n (string-to-number (match-string 1 shift))
8976 shift-what (cdr (assoc (match-string 2 shift)
8977 '(("d" . day) ("w" . week)
8978 ("m" . month) ("y" . year))))))
8979 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8980 (setq nmin 1 nmax n)
8981 (org-back-to-heading t)
8982 (setq beg (point))
8983 (setq idprop (org-entry-get nil "ID"))
8984 (org-end-of-subtree t t)
8985 (or (bolp) (insert "\n"))
8986 (setq end (point))
8987 (setq template (buffer-substring beg end))
8988 (when (and doshift
8989 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8990 (delete-region beg end)
8991 (setq end beg)
8992 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8993 (goto-char end)
8994 (cl-loop for n from nmin to nmax do
8995 ;; prepare clone
8996 (with-temp-buffer
8997 (insert template)
8998 (org-mode)
8999 (goto-char (point-min))
9000 (org-show-subtree)
9001 (and idprop (if org-clone-delete-id
9002 (org-entry-delete nil "ID")
9003 (org-id-get-create t)))
9004 (unless (= n 0)
9005 (while (re-search-forward org-clock-re nil t)
9006 (kill-whole-line))
9007 (goto-char (point-min))
9008 (while (re-search-forward drawer-re nil t)
9009 (org-remove-empty-drawer-at (point))))
9010 (goto-char (point-min))
9011 (when doshift
9012 (while (re-search-forward org-ts-regexp-both nil t)
9013 (org-timestamp-change (* n shift-n) shift-what))
9014 (unless (= n n-no-remove)
9015 (goto-char (point-min))
9016 (while (re-search-forward org-ts-regexp nil t)
9017 (save-excursion
9018 (goto-char (match-beginning 0))
9019 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
9020 (delete-region (match-beginning 1) (match-end 1)))))))
9021 (setq task (buffer-string)))
9022 (insert task))
9023 (goto-char beg)))
9025 ;;; Outline Sorting
9027 (defun org-sort (with-case)
9028 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
9029 Optional argument WITH-CASE means sort case-sensitively."
9030 (interactive "P")
9031 (cond
9032 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
9033 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
9035 (org-call-with-arg 'org-sort-entries with-case))))
9037 (defun org-sort-remove-invisible (s)
9038 "Remove invisible links from string S."
9039 (remove-text-properties 0 (length s) org-rm-props s)
9040 (while (string-match org-bracket-link-regexp s)
9041 (setq s (replace-match (if (match-end 2)
9042 (match-string 3 s)
9043 (match-string 1 s))
9044 t t s)))
9045 (let ((st (format " %s " s)))
9046 (while (string-match org-emph-re st)
9047 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
9048 (setq s (substring st 1 -1)))
9051 (defvar org-priority-regexp) ; defined later in the file
9053 (defvar org-after-sorting-entries-or-items-hook nil
9054 "Hook that is run after a bunch of entries or items have been sorted.
9055 When children are sorted, the cursor is in the parent line when this
9056 hook gets called. When a region or a plain list is sorted, the cursor
9057 will be in the first entry of the sorted region/list.")
9059 (defun org-sort-entries
9060 (&optional with-case sorting-type getkey-func compare-func property)
9061 "Sort entries on a certain level of an outline tree.
9062 If there is an active region, the entries in the region are sorted.
9063 Else, if the cursor is before the first entry, sort the top-level items.
9064 Else, the children of the entry at point are sorted.
9066 Sorting can be alphabetically, numerically, by date/time as given by
9067 a time stamp, by a property, by priority order, or by a custom function.
9069 The command prompts for the sorting type unless it has been given to the
9070 function through the SORTING-TYPE argument, which needs to be a character,
9071 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9072 the precise meaning of each character:
9074 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9075 c By creation time, which is assumed to be the first inactive time stamp
9076 at the beginning of a line.
9077 d By deadline date/time.
9078 k By clocking time.
9079 n Numerically, by converting the beginning of the entry/item to a number.
9080 o By order of TODO keywords.
9081 p By priority according to the cookie.
9082 r By the value of a property.
9083 s By scheduled date/time.
9084 t By date/time, either the first active time stamp in the entry, or, if
9085 none exist, by the first inactive one.
9087 Capital letters will reverse the sort order.
9089 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9090 called with point at the beginning of the record. It must return either
9091 a string or a number that should serve as the sorting key for that record.
9093 Comparing entries ignores case by default. However, with an optional argument
9094 WITH-CASE, the sorting considers case as well.
9096 Sorting is done against the visible part of the headlines, it ignores hidden
9097 links.
9099 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
9100 (interactive "P")
9101 (let ((case-func (if with-case 'identity 'downcase))
9102 (cmstr
9103 ;; The clock marker is lost when using `sort-subr', let's
9104 ;; store the clocking string.
9105 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9106 (save-excursion
9107 (goto-char org-clock-marker)
9108 (buffer-substring-no-properties (line-beginning-position)
9109 (point)))))
9110 start beg end stars re re2
9111 txt what tmp)
9112 ;; Find beginning and end of region to sort
9113 (cond
9114 ((org-region-active-p)
9115 ;; we will sort the region
9116 (setq end (region-end)
9117 what "region")
9118 (goto-char (region-beginning))
9119 (unless (org-at-heading-p) (outline-next-heading))
9120 (setq start (point)))
9121 ((or (org-at-heading-p)
9122 (ignore-errors (progn (org-back-to-heading) t)))
9123 ;; we will sort the children of the current headline
9124 (org-back-to-heading)
9125 (setq start (point)
9126 end (progn (org-end-of-subtree t t)
9127 (or (bolp) (insert "\n"))
9128 (when (>= (org-back-over-empty-lines) 1)
9129 (forward-line 1))
9130 (point))
9131 what "children")
9132 (goto-char start)
9133 (outline-show-subtree)
9134 (outline-next-heading))
9136 ;; we will sort the top-level entries in this file
9137 (goto-char (point-min))
9138 (or (org-at-heading-p) (outline-next-heading))
9139 (setq start (point))
9140 (goto-char (point-max))
9141 (beginning-of-line 1)
9142 (when (looking-at ".*?\\S-")
9143 ;; File ends in a non-white line
9144 (end-of-line 1)
9145 (insert "\n"))
9146 (setq end (point-max))
9147 (setq what "top-level")
9148 (goto-char start)
9149 (outline-show-all)))
9151 (setq beg (point))
9152 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9154 (looking-at "\\(\\*+\\)")
9155 (setq stars (match-string 1)
9156 re (concat "^" (regexp-quote stars) " +")
9157 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9158 txt (buffer-substring beg end))
9159 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9160 (when (and (not (equal stars "*")) (string-match re2 txt))
9161 (user-error "Region to sort contains a level above the first entry"))
9163 (unless sorting-type
9164 (message
9165 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9166 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9167 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9168 what)
9169 (setq sorting-type (read-char-exclusive))
9171 (unless getkey-func
9172 (and (= (downcase sorting-type) ?f)
9173 (setq getkey-func
9174 (completing-read "Sort using function: "
9175 obarray 'fboundp t nil nil))
9176 (setq getkey-func (intern getkey-func))))
9178 (and (= (downcase sorting-type) ?r)
9179 (not property)
9180 (setq property
9181 (completing-read "Property: "
9182 (mapcar #'list (org-buffer-property-keys t))
9183 nil t))))
9185 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9186 (message "Sorting entries...")
9188 (save-restriction
9189 (narrow-to-region start end)
9190 (let ((dcst (downcase sorting-type))
9191 (case-fold-search nil)
9192 (now (current-time)))
9193 (sort-subr
9194 (/= dcst sorting-type)
9195 ;; This function moves to the beginning character of the "record" to
9196 ;; be sorted.
9197 (lambda nil
9198 (if (re-search-forward re nil t)
9199 (goto-char (match-beginning 0))
9200 (goto-char (point-max))))
9201 ;; This function moves to the last character of the "record" being
9202 ;; sorted.
9203 (lambda nil
9204 (save-match-data
9205 (condition-case nil
9206 (outline-forward-same-level 1)
9207 (error
9208 (goto-char (point-max))))))
9209 ;; This function returns the value that gets sorted against.
9210 (lambda nil
9211 (cond
9212 ((= dcst ?n)
9213 (if (looking-at org-complex-heading-regexp)
9214 (string-to-number (org-sort-remove-invisible (match-string 4)))
9215 nil))
9216 ((= dcst ?a)
9217 (if (looking-at org-complex-heading-regexp)
9218 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9219 nil))
9220 ((= dcst ?k)
9221 (or (get-text-property (point) :org-clock-minutes) 0))
9222 ((= dcst ?t)
9223 (let ((end (save-excursion (outline-next-heading) (point))))
9224 (if (or (re-search-forward org-ts-regexp end t)
9225 (re-search-forward org-ts-regexp-both end t))
9226 (org-time-string-to-seconds (match-string 0))
9227 (float-time now))))
9228 ((= dcst ?c)
9229 (let ((end (save-excursion (outline-next-heading) (point))))
9230 (if (re-search-forward
9231 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9232 end t)
9233 (org-time-string-to-seconds (match-string 0))
9234 (float-time now))))
9235 ((= dcst ?s)
9236 (let ((end (save-excursion (outline-next-heading) (point))))
9237 (if (re-search-forward org-scheduled-time-regexp end t)
9238 (org-time-string-to-seconds (match-string 1))
9239 (float-time now))))
9240 ((= dcst ?d)
9241 (let ((end (save-excursion (outline-next-heading) (point))))
9242 (if (re-search-forward org-deadline-time-regexp end t)
9243 (org-time-string-to-seconds (match-string 1))
9244 (float-time now))))
9245 ((= dcst ?p)
9246 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9247 (string-to-char (match-string 2))
9248 org-default-priority))
9249 ((= dcst ?r)
9250 (or (org-entry-get nil property) ""))
9251 ((= dcst ?o)
9252 (when (looking-at org-complex-heading-regexp)
9253 (let* ((m (match-string 2))
9254 (s (if (member m org-done-keywords) '- '+)))
9255 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9256 ((= dcst ?f)
9257 (if getkey-func
9258 (progn
9259 (setq tmp (funcall getkey-func))
9260 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9261 tmp)
9262 (error "Invalid key function `%s'" getkey-func)))
9263 (t (error "Invalid sorting type `%c'" sorting-type))))
9265 (cond
9266 ((= dcst ?a) 'string<)
9267 ((= dcst ?f) compare-func)
9268 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9269 (run-hooks 'org-after-sorting-entries-or-items-hook)
9270 ;; Reset the clock marker if needed
9271 (when cmstr
9272 (save-excursion
9273 (goto-char start)
9274 (search-forward cmstr nil t)
9275 (move-marker org-clock-marker (point))))
9276 (message "Sorting entries...done")))
9278 ;;; The orgstruct minor mode
9280 ;; Define a minor mode which can be used in other modes in order to
9281 ;; integrate the Org mode structure editing commands.
9283 ;; This is really a hack, because the Org mode structure commands use
9284 ;; keys which normally belong to the major mode. Here is how it
9285 ;; works: The minor mode defines all the keys necessary to operate the
9286 ;; structure commands, but wraps the commands into a function which
9287 ;; tests if the cursor is currently at a headline or a plain list
9288 ;; item. If that is the case, the structure command is used,
9289 ;; temporarily setting many Org mode variables like regular
9290 ;; expressions for filling etc. However, when any of those keys is
9291 ;; used at a different location, function uses `key-binding' to look
9292 ;; up if the key has an associated command in another currently active
9293 ;; keymap (minor modes, major mode, global), and executes that
9294 ;; command. There might be problems if any of the keys is otherwise
9295 ;; used as a prefix key.
9297 (defcustom orgstruct-heading-prefix-regexp ""
9298 "Regexp that matches the custom prefix of Org headlines in
9299 orgstruct(++)-mode."
9300 :group 'org
9301 :version "24.4"
9302 :package-version '(Org . "8.3")
9303 :type 'regexp)
9304 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9306 (defcustom orgstruct-setup-hook nil
9307 "Hook run after orgstruct-mode-map is filled."
9308 :group 'org
9309 :version "24.4"
9310 :package-version '(Org . "8.0")
9311 :type 'hook)
9313 (defvar orgstruct-initialized nil)
9315 (defvar org-local-vars nil
9316 "List of local variables, for use by `orgstruct-mode'.")
9318 ;;;###autoload
9319 (define-minor-mode orgstruct-mode
9320 "Toggle the minor mode `orgstruct-mode'.
9321 This mode is for using Org mode structure commands in other
9322 modes. The following keys behave as if Org mode were active, if
9323 the cursor is on a headline, or on a plain list item (both as
9324 defined by Org-mode)."
9325 nil " OrgStruct" (make-sparse-keymap)
9326 (funcall (if orgstruct-mode
9327 'add-to-invisibility-spec
9328 'remove-from-invisibility-spec)
9329 '(outline . t))
9330 (when orgstruct-mode
9331 (org-load-modules-maybe)
9332 (unless orgstruct-initialized
9333 (orgstruct-setup)
9334 (setq orgstruct-initialized t))))
9336 ;;;###autoload
9337 (defun turn-on-orgstruct ()
9338 "Unconditionally turn on `orgstruct-mode'."
9339 (orgstruct-mode 1))
9341 (defvar-local orgstruct-is-++ nil
9342 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9343 (defvar-local org-fb-vars nil)
9344 (defun orgstruct++-mode (&optional arg)
9345 "Toggle `orgstruct-mode', the enhanced version of it.
9346 In addition to setting orgstruct-mode, this also exports all
9347 indentation and autofilling variables from Org mode into the
9348 buffer. It will also recognize item context in multiline items."
9349 (interactive "P")
9350 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9351 (if (< arg 1)
9352 (progn (orgstruct-mode -1)
9353 (dolist (v org-fb-vars)
9354 (set (make-local-variable (car v))
9355 (if (eq (car-safe (cadr v)) 'quote)
9356 (cl-cadadr v)
9357 (nth 1 v)))))
9358 (orgstruct-mode 1)
9359 (setq org-fb-vars nil)
9360 (unless org-local-vars
9361 (setq org-local-vars (org-get-local-variables)))
9362 (let (var val)
9363 (dolist (x org-local-vars)
9364 (when (string-match
9365 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9366 \\|fill-prefix\\|indent-\\)"
9367 (symbol-name (car x)))
9368 (setq var (car x) val (nth 1 x))
9369 (push (list var `(quote ,(eval var))) org-fb-vars)
9370 (set (make-local-variable var)
9371 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9372 (setq-local orgstruct-is-++ t))))
9374 ;;;###autoload
9375 (defun turn-on-orgstruct++ ()
9376 "Unconditionally turn on `orgstruct++-mode'."
9377 (orgstruct++-mode 1))
9379 (defun orgstruct-error ()
9380 "Error when there is no default binding for a structure key."
9381 (interactive)
9382 (funcall (if (fboundp 'user-error)
9383 'user-error
9384 'error)
9385 "This key has no function outside structure elements"))
9387 (defun orgstruct-setup ()
9388 "Setup orgstruct keymap."
9389 (dolist (cell '((org-demote . t)
9390 (org-metaleft . t)
9391 (org-metaright . t)
9392 (org-promote . t)
9393 (org-shiftmetaleft . t)
9394 (org-shiftmetaright . t)
9395 org-backward-element
9396 org-backward-heading-same-level
9397 org-ctrl-c-ret
9398 org-ctrl-c-minus
9399 org-ctrl-c-star
9400 org-cycle
9401 org-force-cycle-archived
9402 org-forward-heading-same-level
9403 org-insert-heading
9404 org-insert-heading-respect-content
9405 org-kill-note-or-show-branches
9406 org-mark-subtree
9407 org-meta-return
9408 org-metadown
9409 org-metaup
9410 org-narrow-to-subtree
9411 org-promote-subtree
9412 org-reveal
9413 org-shiftdown
9414 org-shiftleft
9415 org-shiftmetadown
9416 org-shiftmetaup
9417 org-shiftright
9418 org-shifttab
9419 org-shifttab
9420 org-shiftup
9421 org-show-children
9422 org-show-subtree
9423 org-sort
9424 org-up-element
9425 outline-demote
9426 outline-next-visible-heading
9427 outline-previous-visible-heading
9428 outline-promote
9429 outline-up-heading))
9430 (let ((f (or (car-safe cell) cell))
9431 (disable-when-heading-prefix (cdr-safe cell)))
9432 (when (fboundp f)
9433 (let ((new-bindings))
9434 (dolist (binding (nconc (where-is-internal f org-mode-map)
9435 (where-is-internal f outline-mode-map)))
9436 (push binding new-bindings)
9437 ;; TODO use local-function-key-map
9438 (dolist (rep '(("<tab>" . "TAB")
9439 ("<return>" . "RET")
9440 ("<escape>" . "ESC")
9441 ("<delete>" . "DEL")))
9442 (setq binding (read-kbd-macro
9443 (let ((case-fold-search))
9444 (replace-regexp-in-string
9445 (regexp-quote (cdr rep))
9446 (car rep)
9447 (key-description binding)))))
9448 (cl-pushnew binding new-bindings :test 'equal)))
9449 (dolist (binding new-bindings)
9450 (let ((key (lookup-key orgstruct-mode-map binding)))
9451 (when (or (not key) (numberp key))
9452 (ignore-errors
9453 (org-defkey orgstruct-mode-map
9454 binding
9455 (orgstruct-make-binding
9456 f binding disable-when-heading-prefix))))))))))
9457 (run-hooks 'orgstruct-setup-hook))
9459 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9460 "Create a function for binding in the structure minor mode.
9461 FUN is the command to call inside a table. KEY is the key that
9462 should be checked in for a command to execute outside of tables.
9463 Non-nil `disable-when-heading-prefix' means to disable the command
9464 if `orgstruct-heading-prefix-regexp' is not empty."
9465 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9466 (let ((nname name)
9467 (i 0))
9468 (while (fboundp (intern nname))
9469 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9470 (setq name (intern nname)))
9471 (eval
9472 (let ((bindings '((org-heading-regexp
9473 (concat "^"
9474 orgstruct-heading-prefix-regexp
9475 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9476 (org-outline-regexp
9477 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9478 (org-outline-regexp-bol
9479 (concat "^" org-outline-regexp))
9480 (outline-regexp org-outline-regexp)
9481 (outline-heading-end-regexp "\n")
9482 (outline-level 'org-outline-level)
9483 (outline-heading-alist))))
9484 `(defun ,name (arg)
9485 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9486 "Outside of structure, run the binding of `"
9487 (key-description key) "'."
9488 (when disable-when-heading-prefix
9489 (concat
9490 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9491 "back to the default binding due to limitations of Org's implementation of\n"
9492 "`" (symbol-name fun) "'.")))
9493 (interactive "p")
9494 (let* ((disable
9495 ,(and disable-when-heading-prefix
9496 '(not (string= orgstruct-heading-prefix-regexp ""))))
9497 (fallback
9498 (or disable
9499 (not
9500 (let* ,bindings
9501 (org-context-p 'headline 'item
9502 ,(when (memq fun
9503 '(org-insert-heading
9504 org-insert-heading-respect-content
9505 org-meta-return))
9506 '(when orgstruct-is-++
9507 'item-body))))))))
9508 (if fallback
9509 (let* ((orgstruct-mode)
9510 (binding
9511 (let ((key ,key))
9512 (catch 'exit
9513 (dolist
9514 (rep
9515 '(nil
9516 ("<\\([^>]*\\)tab>" . "\\1TAB")
9517 ("<\\([^>]*\\)return>" . "\\1RET")
9518 ("<\\([^>]*\\)escape>" . "\\1ESC")
9519 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9520 nil)
9521 (when rep
9522 (setq key (read-kbd-macro
9523 (let ((case-fold-search))
9524 (replace-regexp-in-string
9525 (car rep)
9526 (cdr rep)
9527 (key-description key))))))
9528 (when (key-binding key)
9529 (throw 'exit (key-binding key))))))))
9530 (if (keymapp binding)
9531 (org-set-transient-map binding)
9532 (let ((func (or binding
9533 (unless disable
9534 'orgstruct-error))))
9535 (when func
9536 (call-interactively func)))))
9537 (org-run-like-in-org-mode
9538 (lambda ()
9539 (interactive)
9540 (let* ,bindings
9541 (call-interactively ',fun)))))))))
9542 name))
9544 (defun org-contextualize-keys (alist contexts)
9545 "Return valid elements in ALIST depending on CONTEXTS.
9547 `org-agenda-custom-commands' or `org-capture-templates' are the
9548 values used for ALIST, and `org-agenda-custom-commands-contexts'
9549 or `org-capture-templates-contexts' are the associated contexts
9550 definitions."
9551 (let ((contexts
9552 ;; normalize contexts
9553 (mapcar
9554 (lambda(c) (cond ((listp (cadr c))
9555 (list (car c) (car c) (nth 1 c)))
9556 ((string= "" (cadr c))
9557 (list (car c) (car c) (nth 2 c)))
9558 (t c)))
9559 contexts))
9560 (a alist) r s)
9561 ;; loop over all commands or templates
9562 (dolist (c a)
9563 (let (vrules repl)
9564 (cond
9565 ((not (assoc (car c) contexts))
9566 (push c r))
9567 ((and (assoc (car c) contexts)
9568 (setq vrules (org-contextualize-validate-key
9569 (car c) contexts)))
9570 (mapc (lambda (vr)
9571 (unless (equal (car vr) (cadr vr))
9572 (setq repl vr)))
9573 vrules)
9574 (if (not repl) (push c r)
9575 (push (cadr repl) s)
9576 (push
9577 (cons (car c)
9578 (cdr (or (assoc (cadr repl) alist)
9579 (error "Undefined key `%s' as contextual replacement for `%s'"
9580 (cadr repl) (car c)))))
9581 r))))))
9582 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9583 (delq
9585 (delete-dups
9586 (mapcar (lambda (x)
9587 (let ((tpl (car x)))
9588 (unless (delq
9590 (mapcar (lambda (y)
9591 (equal y tpl))
9593 x)))
9594 (reverse r))))))
9596 (defun org-contextualize-validate-key (key contexts)
9597 "Check CONTEXTS for agenda or capture KEY."
9598 (let (res)
9599 (dolist (r contexts)
9600 (dolist (rr (car (last r)))
9601 (when
9602 (and (equal key (car r))
9603 (if (functionp rr) (funcall rr)
9604 (or (and (eq (car rr) 'in-file)
9605 (buffer-file-name)
9606 (string-match (cdr rr) (buffer-file-name)))
9607 (and (eq (car rr) 'in-mode)
9608 (string-match (cdr rr) (symbol-name major-mode)))
9609 (and (eq (car rr) 'in-buffer)
9610 (string-match (cdr rr) (buffer-name)))
9611 (when (and (eq (car rr) 'not-in-file)
9612 (buffer-file-name))
9613 (not (string-match (cdr rr) (buffer-file-name))))
9614 (when (eq (car rr) 'not-in-mode)
9615 (not (string-match (cdr rr) (symbol-name major-mode))))
9616 (when (eq (car rr) 'not-in-buffer)
9617 (not (string-match (cdr rr) (buffer-name)))))))
9618 (push r res))))
9619 (delete-dups (delq nil res))))
9621 (defun org-context-p (&rest contexts)
9622 "Check if local context is any of CONTEXTS.
9623 Possible values in the list of contexts are `table', `headline', and `item'."
9624 (let ((pos (point)))
9625 (goto-char (point-at-bol))
9626 (prog1 (or (and (memq 'table contexts)
9627 (looking-at "[ \t]*|"))
9628 (and (memq 'headline contexts)
9629 (looking-at org-outline-regexp))
9630 (and (memq 'item contexts)
9631 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9632 (and (memq 'item-body contexts)
9633 (org-in-item-p)))
9634 (goto-char pos))))
9636 (defconst org-unique-local-variables
9637 '(org-element--cache
9638 org-element--cache-objects
9639 org-element--cache-sync-keys
9640 org-element--cache-sync-requests
9641 org-element--cache-sync-timer)
9642 "List of local variables that cannot be transferred to another buffer.")
9644 (defun org-get-local-variables ()
9645 "Return a list of all local variables in an Org mode buffer."
9646 (delq nil
9647 (mapcar
9648 (lambda (x)
9649 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9650 (name (car binding)))
9651 (and (not (get name 'org-state))
9652 (not (memq name org-unique-local-variables))
9653 (string-match-p
9654 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9655 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9656 (symbol-name name))
9657 binding)))
9658 (with-temp-buffer
9659 (org-mode)
9660 (buffer-local-variables)))))
9662 (defun org-clone-local-variables (from-buffer &optional regexp)
9663 "Clone local variables from FROM-BUFFER.
9664 Optional argument REGEXP selects variables to clone."
9665 (dolist (pair (buffer-local-variables from-buffer))
9666 (let ((name (car pair)))
9667 (when (and (symbolp name)
9668 (not (memq name org-unique-local-variables))
9669 (or (null regexp) (string-match regexp (symbol-name name))))
9670 (set (make-local-variable name) (cdr pair))))))
9672 ;;;###autoload
9673 (defun org-run-like-in-org-mode (cmd)
9674 "Run a command, pretending that the current buffer is in Org-mode.
9675 This will temporarily bind local variables that are typically bound in
9676 Org mode to the values they have in Org-mode, and then interactively
9677 call CMD."
9678 (org-load-modules-maybe)
9679 (unless org-local-vars
9680 (setq org-local-vars (org-get-local-variables)))
9681 (let (binds)
9682 (dolist (var org-local-vars)
9683 (when (or (not (boundp (car var)))
9684 (eq (symbol-value (car var))
9685 (default-value (car var))))
9686 (push (list (car var) `(quote ,(cadr var))) binds)))
9687 (eval `(let ,binds
9688 (call-interactively (quote ,cmd))))))
9690 (defun org-get-category (&optional pos force-refresh)
9691 "Get the category applying to position POS."
9692 (save-match-data
9693 (when force-refresh (org-refresh-category-properties))
9694 (let ((pos (or pos (point))))
9695 (or (get-text-property pos 'org-category)
9696 (progn (org-refresh-category-properties)
9697 (get-text-property pos 'org-category))))))
9699 ;;; Refresh properties
9701 (defun org-refresh-properties (dprop tprop)
9702 "Refresh buffer text properties.
9703 DPROP is the drawer property and TPROP is either the
9704 corresponding text property to set, or an alist with each element
9705 being a text property (as a symbol) and a function to apply to
9706 the value of the drawer property."
9707 (let ((case-fold-search t)
9708 (inhibit-read-only t))
9709 (org-with-silent-modifications
9710 (save-excursion
9711 (save-restriction
9712 (widen)
9713 (goto-char (point-min))
9714 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9715 (org-refresh-property tprop (match-string-no-properties 1))))))))
9717 (defun org-refresh-property (tprop p)
9718 "Refresh the buffer text property TPROP from the drawer property P.
9719 The refresh happens only for the current tree (not subtree)."
9720 (unless (org-before-first-heading-p)
9721 (save-excursion
9722 (org-back-to-heading t)
9723 (if (symbolp tprop)
9724 ;; TPROP is a text property symbol
9725 (put-text-property
9726 (point) (or (outline-next-heading) (point-max)) tprop p)
9727 ;; TPROP is an alist with (properties . function) elements
9728 (dolist (al tprop)
9729 (save-excursion
9730 (put-text-property
9731 (line-beginning-position) (or (outline-next-heading) (point-max))
9732 (car al)
9733 (funcall (cdr al) p))))))))
9735 (defun org-refresh-category-properties ()
9736 "Refresh category text properties in the buffer."
9737 (let ((case-fold-search t)
9738 (inhibit-read-only t)
9739 (default-category
9740 (cond ((null org-category)
9741 (if buffer-file-name
9742 (file-name-sans-extension
9743 (file-name-nondirectory buffer-file-name))
9744 "???"))
9745 ((symbolp org-category) (symbol-name org-category))
9746 (t org-category))))
9747 (org-with-silent-modifications
9748 (org-with-wide-buffer
9749 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9750 ;; This is the default category for the buffer. If none is
9751 ;; found, fall-back to `org-category' or buffer file name.
9752 (put-text-property
9753 (point-min) (point-max)
9754 'org-category
9755 (catch 'buffer-category
9756 (goto-char (point-max))
9757 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9758 (let ((element (org-element-at-point)))
9759 (when (eq (org-element-type element) 'keyword)
9760 (throw 'buffer-category
9761 (org-element-property :value element)))))
9762 default-category))
9763 ;; Set sub-tree specific categories.
9764 (goto-char (point-min))
9765 (let ((regexp (org-re-property "CATEGORY")))
9766 (while (re-search-forward regexp nil t)
9767 (let ((value (match-string-no-properties 3)))
9768 (when (org-at-property-p)
9769 (put-text-property
9770 (save-excursion (org-back-to-heading t) (point))
9771 (save-excursion (org-end-of-subtree t t) (point))
9772 'org-category
9773 value)))))))))
9775 (defun org-refresh-stats-properties ()
9776 "Refresh stats text properties in the buffer."
9777 (let (stats)
9778 (org-with-silent-modifications
9779 (save-excursion
9780 (save-restriction
9781 (widen)
9782 (goto-char (point-min))
9783 (while (re-search-forward
9784 (concat org-outline-regexp-bol ".*"
9785 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9786 nil t)
9787 (setq stats (cond ((equal (match-string 3) "0") 0)
9788 ((match-string 2)
9789 (/ (* (string-to-number (match-string 2)) 100)
9790 (string-to-number (match-string 3))))
9791 (t (string-to-number (match-string 1)))))
9792 (org-back-to-heading t)
9793 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9794 'org-stats stats)))))))
9796 (defun org-refresh-effort-properties ()
9797 "Refresh effort properties"
9798 (org-refresh-properties
9799 org-effort-property
9800 '((effort . identity)
9801 (effort-minutes . org-duration-string-to-minutes))))
9803 ;;;; Link Stuff
9805 ;;; Link abbreviations
9807 (defun org-link-expand-abbrev (link)
9808 "Apply replacements as defined in `org-link-abbrev-alist'."
9809 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9810 (let* ((key (match-string 1 link))
9811 (as (or (assoc key org-link-abbrev-alist-local)
9812 (assoc key org-link-abbrev-alist)))
9813 (tag (and (match-end 2) (match-string 3 link)))
9814 rpl)
9815 (if (not as)
9816 link
9817 (setq rpl (cdr as))
9818 (cond
9819 ((symbolp rpl) (funcall rpl tag))
9820 ((string-match "%(\\([^)]+\\))" rpl)
9821 (replace-match
9822 (save-match-data
9823 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9824 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9825 ((string-match "%h" rpl)
9826 (replace-match (url-hexify-string (or tag "")) t t rpl))
9827 (t (concat rpl tag)))))
9828 link))
9830 ;;; Storing and inserting links
9832 (defvar org-insert-link-history nil
9833 "Minibuffer history for links inserted with `org-insert-link'.")
9835 (defvar org-stored-links nil
9836 "Contains the links stored with `org-store-link'.")
9838 (defvar org-store-link-plist nil
9839 "Plist with info about the most recently link created with `org-store-link'.")
9841 (defun org-store-link-functions ()
9842 "Return a list of functions that are called to create and store a link.
9843 The functions defined in the :store property of
9844 `org-link-parameters'.
9846 Each function will be called in turn until one returns a non-nil
9847 value. Each function should check if it is responsible for
9848 creating this link (for example by looking at the major mode).
9849 If not, it must exit and return nil. If yes, it should return
9850 a non-nil value after calling `org-store-link-props' with a list
9851 of properties and values. Special properties are:
9853 :type The link prefix, like \"http\". This must be given.
9854 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9855 This is obligatory as well.
9856 :description Optional default description for the second pair
9857 of brackets in an Org mode link. The user can still change
9858 this when inserting this link into an Org mode buffer.
9860 In addition to these, any additional properties can be specified
9861 and then used in capture templates."
9862 (cl-loop for link in org-link-parameters
9863 with store-func
9864 do (setq store-func (org-link-get-parameter (car link) :store))
9865 if store-func
9866 collect store-func))
9868 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9869 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9871 ;;;###autoload
9872 (defun org-store-link (arg)
9873 "\\<org-mode-map>Store an org-link to the current location.
9874 This link is added to `org-stored-links' and can later be inserted
9875 into an Org buffer with \\[org-insert-link].
9877 For some link types, a prefix ARG is interpreted.
9878 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9879 For file links, ARG negates `org-context-in-file-links'.
9881 A double prefix ARG force skipping storing functions that are not
9882 part of Org's core.
9884 A triple prefix ARG force storing a link for each line in the
9885 active region."
9886 (interactive "P")
9887 (org-load-modules-maybe)
9888 (if (and (equal arg '(64)) (org-region-active-p))
9889 (save-excursion
9890 (let ((end (region-end)))
9891 (goto-char (region-beginning))
9892 (set-mark (point))
9893 (while (< (point-at-eol) end)
9894 (move-end-of-line 1) (activate-mark)
9895 (let (current-prefix-arg)
9896 (call-interactively 'org-store-link))
9897 (move-beginning-of-line 2)
9898 (set-mark (point)))))
9899 (setq org-store-link-plist nil)
9900 (let (link cpltxt desc description search
9901 txt custom-id agenda-link sfuns sfunsn)
9902 (cond
9904 ;; Store a link using an external link type
9905 ((and (not (equal arg '(16)))
9906 (setq sfuns
9907 (delq
9908 nil (mapcar (lambda (f)
9909 (let (fs) (if (funcall f) (push f fs))))
9910 (org-store-link-functions)))
9911 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9912 (or (and (cdr sfuns)
9913 (funcall (intern
9914 (completing-read
9915 "Which function for creating the link? "
9916 sfunsn nil t (car sfunsn)))))
9917 (funcall (caar sfuns)))
9918 (setq link (plist-get org-store-link-plist :link)
9919 desc (or (plist-get org-store-link-plist
9920 :description)
9921 link))))
9923 ;; Store a link from a source code buffer.
9924 ((org-src-edit-buffer-p)
9925 (let ((coderef-format (org-src-coderef-format)))
9926 (cond ((save-excursion
9927 (beginning-of-line)
9928 (looking-at (org-src-coderef-regexp coderef-format)))
9929 (setq link (format "(%s)" (match-string-no-properties 3))))
9930 ((called-interactively-p 'any)
9931 (let ((label (read-string "Code line label: ")))
9932 (end-of-line)
9933 (setq link (format coderef-format label))
9934 (let ((gc (- 79 (length link))))
9935 (if (< (current-column) gc)
9936 (org-move-to-column gc t)
9937 (insert " ")))
9938 (insert link)
9939 (setq link (concat "(" label ")"))
9940 (setq desc nil)))
9941 (t (setq link nil)))))
9943 ;; We are in the agenda, link to referenced location
9944 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9945 (let ((m (or (get-text-property (point) 'org-hd-marker)
9946 (get-text-property (point) 'org-marker))))
9947 (when m
9948 (org-with-point-at m
9949 (setq agenda-link
9950 (if (called-interactively-p 'any)
9951 (call-interactively 'org-store-link)
9952 (org-store-link nil)))))))
9954 ((eq major-mode 'calendar-mode)
9955 (let ((cd (calendar-cursor-to-date)))
9956 (setq link
9957 (format-time-string
9958 (car org-time-stamp-formats)
9959 (apply 'encode-time
9960 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9961 nil nil nil))))
9962 (org-store-link-props :type "calendar" :date cd)))
9964 ((eq major-mode 'help-mode)
9965 (setq link (concat "help:" (save-excursion
9966 (goto-char (point-min))
9967 (looking-at "^[^ ]+")
9968 (match-string 0))))
9969 (org-store-link-props :type "help"))
9971 ((eq major-mode 'w3-mode)
9972 (setq cpltxt (if (and (buffer-name)
9973 (not (string-match "Untitled" (buffer-name))))
9974 (buffer-name)
9975 (url-view-url t))
9976 link (url-view-url t))
9977 (org-store-link-props :type "w3" :url (url-view-url t)))
9979 ((eq major-mode 'image-mode)
9980 (setq cpltxt (concat "file:"
9981 (abbreviate-file-name buffer-file-name))
9982 link cpltxt)
9983 (org-store-link-props :type "image" :file buffer-file-name))
9985 ;; In dired, store a link to the file of the current line
9986 ((derived-mode-p 'dired-mode)
9987 (let ((file (dired-get-filename nil t)))
9988 (setq file (if file
9989 (abbreviate-file-name
9990 (expand-file-name (dired-get-filename nil t)))
9991 ;; otherwise, no file so use current directory.
9992 default-directory))
9993 (setq cpltxt (concat "file:" file)
9994 link cpltxt)))
9996 ((setq search (run-hook-with-args-until-success
9997 'org-create-file-search-functions))
9998 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9999 "::" search))
10000 (setq cpltxt (or description link)))
10002 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
10003 (org-with-limited-levels
10004 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
10005 (cond
10006 ;; Store a link using the target at point
10007 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
10008 (setq cpltxt
10009 (concat "file:"
10010 (abbreviate-file-name
10011 (buffer-file-name (buffer-base-buffer)))
10012 "::" (match-string 1))
10013 link cpltxt))
10014 ((and (featurep 'org-id)
10015 (or (eq org-id-link-to-org-use-id t)
10016 (and (called-interactively-p 'any)
10017 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
10018 (and (eq org-id-link-to-org-use-id
10019 'create-if-interactive-and-no-custom-id)
10020 (not custom-id))))
10021 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
10022 ;; Store a link using the ID at point
10023 (setq link (condition-case nil
10024 (prog1 (org-id-store-link)
10025 (setq desc (or (plist-get org-store-link-plist
10026 :description)
10027 "")))
10028 (error
10029 ;; Probably before first headline, link only to file
10030 (concat "file:"
10031 (abbreviate-file-name
10032 (buffer-file-name (buffer-base-buffer))))))))
10034 ;; Just link to current headline
10035 (setq cpltxt (concat "file:"
10036 (abbreviate-file-name
10037 (buffer-file-name (buffer-base-buffer)))))
10038 ;; Add a context search string
10039 (when (org-xor org-context-in-file-links arg)
10040 (let* ((element (org-element-at-point))
10041 (name (org-element-property :name element)))
10042 (setq txt (cond
10043 ((org-at-heading-p) nil)
10044 (name)
10045 ((org-region-active-p)
10046 (buffer-substring (region-beginning) (region-end)))))
10047 (when (or (null txt) (string-match "\\S-" txt))
10048 (setq cpltxt
10049 (concat cpltxt "::"
10050 (condition-case nil
10051 (org-make-org-heading-search-string txt)
10052 (error "")))
10053 desc (or name
10054 (nth 4 (ignore-errors (org-heading-components)))
10055 "NONE")))))
10056 (when (string-match "::\\'" cpltxt)
10057 (setq cpltxt (substring cpltxt 0 -2)))
10058 (setq link cpltxt)))))
10060 ((buffer-file-name (buffer-base-buffer))
10061 ;; Just link to this file here.
10062 (setq cpltxt (concat "file:"
10063 (abbreviate-file-name
10064 (buffer-file-name (buffer-base-buffer)))))
10065 ;; Add a context string.
10066 (when (org-xor org-context-in-file-links arg)
10067 (setq txt (if (org-region-active-p)
10068 (buffer-substring (region-beginning) (region-end))
10069 (buffer-substring (point-at-bol) (point-at-eol))))
10070 ;; Only use search option if there is some text.
10071 (when (string-match "\\S-" txt)
10072 (setq cpltxt
10073 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10074 desc "NONE")))
10075 (setq link cpltxt))
10077 ((called-interactively-p 'interactive)
10078 (user-error "No method for storing a link from this buffer"))
10080 (t (setq link nil)))
10082 ;; We're done setting link and desc, clean up
10083 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10084 (setq link (or link cpltxt)
10085 desc (or desc cpltxt))
10086 (cond ((not desc))
10087 ((equal desc "NONE") (setq desc nil))
10088 (t (setq desc
10089 (replace-regexp-in-string
10090 org-bracket-link-analytic-regexp
10091 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10092 desc))))
10093 ;; Return the link
10094 (if (not (and (or (called-interactively-p 'any)
10095 executing-kbd-macro)
10096 link))
10097 (or agenda-link (and link (org-make-link-string link desc)))
10098 (push (list link desc) org-stored-links)
10099 (message "Stored: %s" (or desc link))
10100 (when custom-id
10101 (setq link (concat "file:" (abbreviate-file-name
10102 (buffer-file-name)) "::#" custom-id))
10103 (push (list link desc) org-stored-links))
10104 (car org-stored-links)))))
10106 (defun org-store-link-props (&rest plist)
10107 "Store link properties, extract names, addresses and dates."
10108 (let ((x (plist-get plist :from)))
10109 (when x
10110 (let ((adr (mail-extract-address-components x)))
10111 (setq plist (plist-put plist :fromname (car adr)))
10112 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10113 (let ((x (plist-get plist :to)))
10114 (when x
10115 (let ((adr (mail-extract-address-components x)))
10116 (setq plist (plist-put plist :toname (car adr)))
10117 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10118 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10119 (when x
10120 (setq plist (plist-put plist :date-timestamp
10121 (format-time-string
10122 (org-time-stamp-format t) x)))
10123 (setq plist (plist-put plist :date-timestamp-inactive
10124 (format-time-string
10125 (org-time-stamp-format t t) x)))))
10126 (let ((from (plist-get plist :from))
10127 (to (plist-get plist :to)))
10128 (when (and from to org-from-is-user-regexp)
10129 (setq plist
10130 (plist-put plist :fromto
10131 (if (string-match org-from-is-user-regexp from)
10132 (concat "to %t")
10133 (concat "from %f"))))))
10134 (setq org-store-link-plist plist))
10136 (defun org-add-link-props (&rest plist)
10137 "Add these properties to the link property list."
10138 (let (key value)
10139 (while plist
10140 (setq key (pop plist) value (pop plist))
10141 (setq org-store-link-plist
10142 (plist-put org-store-link-plist key value)))))
10144 (defun org-email-link-description (&optional fmt)
10145 "Return the description part of an email link.
10146 This takes information from `org-store-link-plist' and formats it
10147 according to FMT (default from `org-email-link-description-format')."
10148 (setq fmt (or fmt org-email-link-description-format))
10149 (let* ((p org-store-link-plist)
10150 (to (plist-get p :toaddress))
10151 (from (plist-get p :fromaddress))
10152 (table
10153 (list
10154 (cons "%c" (plist-get p :fromto))
10155 (cons "%F" (plist-get p :from))
10156 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10157 (cons "%T" (plist-get p :to))
10158 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10159 (cons "%s" (plist-get p :subject))
10160 (cons "%d" (plist-get p :date))
10161 (cons "%m" (plist-get p :message-id)))))
10162 (when (string-match "%c" fmt)
10163 ;; Check if the user wrote this message
10164 (if (and org-from-is-user-regexp from to
10165 (save-match-data (string-match org-from-is-user-regexp from)))
10166 (setq fmt (replace-match "to %t" t t fmt))
10167 (setq fmt (replace-match "from %f" t t fmt))))
10168 (org-replace-escapes fmt table)))
10170 (defun org-make-org-heading-search-string (&optional string)
10171 "Make search string for the current headline or STRING."
10172 (let ((s (or string
10173 (and (derived-mode-p 'org-mode)
10174 (save-excursion
10175 (org-back-to-heading t)
10176 (org-element-property :raw-value (org-element-at-point))))))
10177 (lines org-context-in-file-links))
10178 (or string (setq s (concat "*" s))) ; Add * for headlines
10179 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10180 (when (and string (integerp lines) (> lines 0))
10181 (let ((slines (org-split-string s "\n")))
10182 (when (< lines (length slines))
10183 (setq s (mapconcat
10184 'identity
10185 (reverse (nthcdr (- (length slines) lines)
10186 (reverse slines))) "\n")))))
10187 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10189 (defun org-make-link-string (link &optional description)
10190 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10191 (unless (org-string-nw-p link) (error "Empty link"))
10192 (let ((uri (cond ((string-match org-link-types-re link)
10193 (concat (match-string 1 link)
10194 (org-link-escape (substring link (match-end 1)))))
10195 ;; For readability, url-encode internal links only
10196 ;; when absolutely needed (i.e, when they contain
10197 ;; square brackets). File links however, are
10198 ;; encoded since, e.g., spaces are significant.
10199 ((or (file-name-absolute-p link)
10200 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10201 (org-link-escape link))
10202 (t link)))
10203 (description
10204 (and (org-string-nw-p description)
10205 ;; Remove brackets from description, as they are fatal.
10206 (replace-regexp-in-string
10207 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10208 (org-trim description)))))
10209 (format "[[%s]%s]"
10211 (if description (format "[%s]" description) ""))))
10213 (defconst org-link-escape-chars
10214 ;;%20 %5B %5D %25
10215 '(?\s ?\[ ?\] ?%)
10216 "List of characters that should be escaped in a link when stored to Org.
10217 This is the list that is used for internal purposes.")
10219 (defun org-link-escape (text &optional table merge)
10220 "Return percent escaped representation of TEXT.
10221 TEXT is a string with the text to escape.
10222 Optional argument TABLE is a list with characters that should be
10223 escaped. When nil, `org-link-escape-chars' is used.
10224 If optional argument MERGE is set, merge TABLE into
10225 `org-link-escape-chars'."
10226 (let ((characters-to-encode
10227 (cond ((null table) org-link-escape-chars)
10228 (merge (append org-link-escape-chars table))
10229 (t table))))
10230 (mapconcat
10231 (lambda (c)
10232 (if (or (memq c characters-to-encode)
10233 (and org-url-hexify-p (or (< c 32) (> c 126))))
10234 (mapconcat (lambda (e) (format "%%%.2X" e))
10235 (or (encode-coding-char c 'utf-8)
10236 (error "Unable to percent escape character: %c" c))
10238 (char-to-string c)))
10239 text "")))
10241 (defun org-link-unescape (str)
10242 "Unhex hexified Unicode parts in string STR.
10243 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10244 reciprocal of `org-link-escape', which see."
10245 (if (org-string-nw-p str)
10246 (replace-regexp-in-string
10247 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10248 str))
10250 (defun org-link-unescape-compound (hex)
10251 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10252 Note: this function also decodes single byte encodings like
10253 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10254 (save-match-data
10255 (let* ((bytes (cdr (split-string hex "%")))
10256 (ret "")
10257 (eat 0)
10258 (sum 0))
10259 (while bytes
10260 (let* ((val (string-to-number (pop bytes) 16))
10261 (shift-xor
10262 (if (= 0 eat)
10263 (cond
10264 ((>= val 252) (cons 6 252))
10265 ((>= val 248) (cons 5 248))
10266 ((>= val 240) (cons 4 240))
10267 ((>= val 224) (cons 3 224))
10268 ((>= val 192) (cons 2 192))
10269 (t (cons 0 0)))
10270 (cons 6 128))))
10271 (when (>= val 192) (setq eat (car shift-xor)))
10272 (setq val (logxor val (cdr shift-xor)))
10273 (setq sum (+ (lsh sum (car shift-xor)) val))
10274 (when (> eat 0) (setq eat (- eat 1)))
10275 (cond
10276 ((= 0 eat) ;multi byte
10277 (setq ret (concat ret (char-to-string sum)))
10278 (setq sum 0))
10279 ((not bytes) ; single byte(s)
10280 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10281 ret)))
10283 (defun org-link-unescape-single-byte-sequence (hex)
10284 "Unhexify hex-encoded single byte character sequences."
10285 (mapconcat (lambda (byte)
10286 (char-to-string (string-to-number byte 16)))
10287 (cdr (split-string hex "%")) ""))
10289 (defun org-xor (a b)
10290 "Exclusive or."
10291 (if a (not b) b))
10293 (defun org-fixup-message-id-for-http (s)
10294 "Replace special characters in a message id, so it can be used in an http query."
10295 (when (string-match "%" s)
10296 (setq s (mapconcat (lambda (c)
10297 (if (eq c ?%)
10298 "%25"
10299 (char-to-string c)))
10300 s "")))
10301 (while (string-match "<" s)
10302 (setq s (replace-match "%3C" t t s)))
10303 (while (string-match ">" s)
10304 (setq s (replace-match "%3E" t t s)))
10305 (while (string-match "@" s)
10306 (setq s (replace-match "%40" t t s)))
10309 (defun org-link-prettify (link)
10310 "Return a human-readable representation of LINK.
10311 The car of LINK must be a raw link.
10312 The cdr of LINK must be either a link description or nil."
10313 (let ((desc (or (cadr link) "<no description>")))
10314 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10315 "<" (car link) ">")))
10317 ;;;###autoload
10318 (defun org-insert-link-global ()
10319 "Insert a link like Org mode does.
10320 This command can be called in any mode to insert a link in Org syntax."
10321 (interactive)
10322 (org-load-modules-maybe)
10323 (org-run-like-in-org-mode 'org-insert-link))
10325 (defun org-insert-all-links (arg &optional pre post)
10326 "Insert all links in `org-stored-links'.
10327 When a universal prefix, do not delete the links from `org-stored-links'.
10328 When `ARG' is a number, insert the last N link(s).
10329 `PRE' and `POST' are optional arguments to define a string to
10330 prepend or to append."
10331 (interactive "P")
10332 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10333 (links (copy-sequence org-stored-links))
10334 (pr (or pre "- "))
10335 (po (or post "\n"))
10336 (cnt 1) l)
10337 (if (null org-stored-links)
10338 (message "No link to insert")
10339 (while (and (or (listp arg) (>= arg cnt))
10340 (setq l (if (listp arg)
10341 (pop links)
10342 (pop org-stored-links))))
10343 (setq cnt (1+ cnt))
10344 (insert pr)
10345 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10346 (insert po)))))
10348 (defun org-insert-last-stored-link (arg)
10349 "Insert the last link stored in `org-stored-links'."
10350 (interactive "p")
10351 (org-insert-all-links arg "" "\n"))
10353 (defun org-link-fontify-links-to-this-file ()
10354 "Fontify links to the current file in `org-stored-links'."
10355 (let ((f (buffer-file-name)) a b)
10356 (setq a (mapcar (lambda(l)
10357 (let ((ll (car l)))
10358 (when (and (string-match "^file:\\(.+\\)::" ll)
10359 (equal f (expand-file-name (match-string 1 ll))))
10360 ll)))
10361 org-stored-links))
10362 (when (featurep 'org-id)
10363 (setq b (mapcar (lambda(l)
10364 (let ((ll (car l)))
10365 (when (and (string-match "^id:\\(.+\\)$" ll)
10366 (equal f (expand-file-name
10367 (or (org-id-find-id-file
10368 (match-string 1 ll)) ""))))
10369 ll)))
10370 org-stored-links)))
10371 (mapcar (lambda(l)
10372 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10373 (delq nil (append a b)))))
10375 (defvar org--links-history nil)
10376 (defun org-insert-link (&optional complete-file link-location default-description)
10377 "Insert a link. At the prompt, enter the link.
10379 Completion can be used to insert any of the link protocol prefixes like
10380 http or ftp in use.
10382 The history can be used to select a link previously stored with
10383 `org-store-link'. When the empty string is entered (i.e. if you just
10384 press RET at the prompt), the link defaults to the most recently
10385 stored link. As SPC triggers completion in the minibuffer, you need to
10386 use M-SPC or C-q SPC to force the insertion of a space character.
10388 You will also be prompted for a description, and if one is given, it will
10389 be displayed in the buffer instead of the link.
10391 If there is already a link at point, this command will allow you to edit link
10392 and description parts.
10394 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10395 be selected using completion. The path to the file will be relative to the
10396 current directory if the file is in the current directory or a subdirectory.
10397 Otherwise, the link will be the absolute path as completed in the minibuffer
10398 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10399 option `org-link-file-path-type'.
10401 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10402 the current directory or below.
10404 With three \\[universal-argument] prefixes, negate the meaning of
10405 `org-keep-stored-link-after-insertion'.
10407 If `org-make-link-description-function' is non-nil, this function will be
10408 called with the link target, and the result will be the default
10409 link description.
10411 If the LINK-LOCATION parameter is non-nil, this value will be
10412 used as the link location instead of reading one interactively.
10414 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10415 be used as the default description."
10416 (interactive "P")
10417 (let* ((wcf (current-window-configuration))
10418 (origbuf (current-buffer))
10419 (region (when (org-region-active-p)
10420 (buffer-substring (region-beginning) (region-end))))
10421 (remove (and region (list (region-beginning) (region-end))))
10422 (desc region)
10423 (link link-location)
10424 (abbrevs org-link-abbrev-alist-local)
10425 entry all-prefixes auto-desc)
10426 (cond
10427 (link-location) ; specified by arg, just use it.
10428 ((org-in-regexp org-bracket-link-regexp 1)
10429 ;; We do have a link at point, and we are going to edit it.
10430 (setq remove (list (match-beginning 0) (match-end 0)))
10431 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10432 (setq link (read-string "Link: "
10433 (org-link-unescape
10434 (match-string-no-properties 1)))))
10435 ((or (org-in-regexp org-angle-link-re)
10436 (org-in-regexp org-plain-link-re))
10437 ;; Convert to bracket link
10438 (setq remove (list (match-beginning 0) (match-end 0))
10439 link (read-string "Link: "
10440 (org-remove-angle-brackets (match-string 0)))))
10441 ((member complete-file '((4) (16)))
10442 ;; Completing read for file names.
10443 (setq link (org-file-complete-link complete-file)))
10445 ;; Read link, with completion for stored links.
10446 (org-link-fontify-links-to-this-file)
10447 (org-switch-to-buffer-other-window "*Org Links*")
10448 (with-current-buffer "*Org Links*"
10449 (erase-buffer)
10450 (insert "Insert a link.
10451 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10452 (when org-stored-links
10453 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10454 (insert (mapconcat 'org-link-prettify
10455 (reverse org-stored-links) "\n")))
10456 (goto-char (point-min)))
10457 (let ((cw (selected-window)))
10458 (select-window (get-buffer-window "*Org Links*" 'visible))
10459 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10460 (unless (pos-visible-in-window-p (point-max))
10461 (org-fit-window-to-buffer))
10462 (and (window-live-p cw) (select-window cw)))
10463 (setq all-prefixes (append (mapcar 'car abbrevs)
10464 (mapcar 'car org-link-abbrev-alist)
10465 (org-link-types)))
10466 (unwind-protect
10467 ;; Fake a link history, containing the stored links.
10468 (let ((org--links-history
10469 (append (mapcar #'car org-stored-links)
10470 org-insert-link-history)))
10471 (setq link
10472 (org-completing-read
10473 "Link: "
10474 (append
10475 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10476 (mapcar #'car org-stored-links))
10477 nil nil nil
10478 'org--links-history
10479 (caar org-stored-links)))
10480 (unless (org-string-nw-p link) (user-error "No link selected"))
10481 (dolist (l org-stored-links)
10482 (when (equal link (cadr l))
10483 (setq link (car l))
10484 (setq auto-desc t)))
10485 (when (or (member link all-prefixes)
10486 (and (equal ":" (substring link -1))
10487 (member (substring link 0 -1) all-prefixes)
10488 (setq link (substring link 0 -1))))
10489 (setq link (with-current-buffer origbuf
10490 (org-link-try-special-completion link)))))
10491 (set-window-configuration wcf)
10492 (kill-buffer "*Org Links*"))
10493 (setq entry (assoc link org-stored-links))
10494 (or entry (push link org-insert-link-history))
10495 (setq desc (or desc (nth 1 entry)))))
10497 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10498 (not org-keep-stored-link-after-insertion))
10499 (setq org-stored-links (delq (assoc link org-stored-links)
10500 org-stored-links)))
10502 (when (and (string-match org-plain-link-re link)
10503 (not (string-match org-ts-regexp link)))
10504 ;; URL-like link, normalize the use of angular brackets.
10505 (setq link (org-remove-angle-brackets link)))
10507 ;; Check if we are linking to the current file with a search
10508 ;; option If yes, simplify the link by using only the search
10509 ;; option.
10510 (when (and buffer-file-name
10511 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10512 (let* ((path (match-string 1 link))
10513 (case-fold-search nil)
10514 (search (match-string 2 link)))
10515 (save-match-data
10516 (when (equal (file-truename buffer-file-name) (file-truename path))
10517 ;; We are linking to this same file, with a search option
10518 (setq link search)))))
10520 ;; Check if we can/should use a relative path. If yes, simplify the link
10521 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10522 (let* ((type (match-string 1 link))
10523 (path (match-string 2 link))
10524 (origpath path)
10525 (case-fold-search nil))
10526 (cond
10527 ((or (eq org-link-file-path-type 'absolute)
10528 (equal complete-file '(16)))
10529 (setq path (abbreviate-file-name (expand-file-name path))))
10530 ((eq org-link-file-path-type 'noabbrev)
10531 (setq path (expand-file-name path)))
10532 ((eq org-link-file-path-type 'relative)
10533 (setq path (file-relative-name path)))
10535 (save-match-data
10536 (if (string-match (concat "^" (regexp-quote
10537 (expand-file-name
10538 (file-name-as-directory
10539 default-directory))))
10540 (expand-file-name path))
10541 ;; We are linking a file with relative path name.
10542 (setq path (substring (expand-file-name path)
10543 (match-end 0)))
10544 (setq path (abbreviate-file-name (expand-file-name path)))))))
10545 (setq link (concat type path))
10546 (when (equal desc origpath)
10547 (setq desc path))))
10549 (if org-make-link-description-function
10550 (setq desc
10551 (or (condition-case nil
10552 (funcall org-make-link-description-function link desc)
10553 (error (progn (message "Can't get link description from `%s'"
10554 (symbol-name org-make-link-description-function))
10555 (sit-for 2) nil)))
10556 (read-string "Description: " default-description)))
10557 (if default-description (setq desc default-description)
10558 (setq desc (or (and auto-desc desc)
10559 (read-string "Description: " desc)))))
10561 (unless (string-match "\\S-" desc) (setq desc nil))
10562 (when remove (apply 'delete-region remove))
10563 (insert (org-make-link-string link desc))
10564 ;; Redisplay so as the new link has proper invisible characters.
10565 (sit-for 0)))
10567 (defun org-link-try-special-completion (type)
10568 "If there is completion support for link type TYPE, offer it."
10569 (let ((fun (org-link-get-parameter type :complete)))
10570 (if (functionp fun)
10571 (funcall fun)
10572 (read-string "Link (no completion support): " (concat type ":")))))
10574 (defun org-file-complete-link (&optional arg)
10575 "Create a file link using completion."
10576 (let ((file (read-file-name "File: "))
10577 (pwd (file-name-as-directory (expand-file-name ".")))
10578 (pwd1 (file-name-as-directory (abbreviate-file-name
10579 (expand-file-name ".")))))
10580 (cond ((equal arg '(16))
10581 (concat "file:"
10582 (abbreviate-file-name (expand-file-name file))))
10583 ((string-match
10584 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10585 (concat "file:" (match-string 1 file)))
10586 ((string-match
10587 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10588 (expand-file-name file))
10589 (concat "file:"
10590 (match-string 1 (expand-file-name file))))
10591 (t (concat "file:" file)))))
10593 (defun org-completing-read (&rest args)
10594 "Completing-read with SPACE being a normal character."
10595 (let ((enable-recursive-minibuffers t)
10596 (minibuffer-local-completion-map
10597 (copy-keymap minibuffer-local-completion-map)))
10598 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10599 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10600 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10601 'org-time-stamp-inactive)
10602 (apply #'completing-read args)))
10604 ;;; Opening/following a link
10606 (defvar org-link-search-failed nil)
10608 (defvar org-open-link-functions nil
10609 "Hook for functions finding a plain text link.
10610 These functions must take a single argument, the link content.
10611 They will be called for links that look like [[link text][description]]
10612 when LINK TEXT does not have a protocol like \"http:\" and does not look
10613 like a filename (e.g. \"./blue.png\").
10615 These functions will be called *before* Org attempts to resolve the
10616 link by doing text searches in the current buffer - so if you want a
10617 link \"[[target]]\" to still find \"<<target>>\", your function should
10618 handle this as a special case.
10620 When the function does handle the link, it must return a non-nil value.
10621 If it decides that it is not responsible for this link, it must return
10622 nil to indicate that that Org can continue with other options like
10623 exact and fuzzy text search.")
10625 (defun org-next-link (&optional search-backward)
10626 "Move forward to the next link.
10627 If the link is in hidden text, expose it."
10628 (interactive "P")
10629 (when (and org-link-search-failed (eq this-command last-command))
10630 (goto-char (point-min))
10631 (message "Link search wrapped back to beginning of buffer"))
10632 (setq org-link-search-failed nil)
10633 (let* ((pos (point))
10634 (ct (org-context))
10635 (a (assoc :link ct))
10636 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10637 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10638 ((looking-at org-any-link-re)
10639 ;; Don't stay stuck at link without an org-link face
10640 (forward-char (if search-backward -1 1))))
10641 (if (funcall srch-fun org-any-link-re nil t)
10642 (progn
10643 (goto-char (match-beginning 0))
10644 (when (outline-invisible-p) (org-show-context)))
10645 (goto-char pos)
10646 (setq org-link-search-failed t)
10647 (message "No further link found"))))
10649 (defun org-previous-link ()
10650 "Move backward to the previous link.
10651 If the link is in hidden text, expose it."
10652 (interactive)
10653 (funcall 'org-next-link t))
10655 (defun org-translate-link (s)
10656 "Translate a link string if a translation function has been defined."
10657 (with-temp-buffer
10658 (insert (org-trim s))
10659 (org-trim (org-element-interpret-data (org-element-context)))))
10661 (defun org-translate-link-from-planner (type path)
10662 "Translate a link from Emacs Planner syntax so that Org can follow it.
10663 This is still an experimental function, your mileage may vary."
10664 (cond
10665 ((member type '("http" "https" "news" "ftp"))
10666 ;; standard Internet links are the same.
10667 nil)
10668 ((and (equal type "irc") (string-match "^//" path))
10669 ;; Planner has two / at the beginning of an irc link, we have 1.
10670 ;; We should have zero, actually....
10671 (setq path (substring path 1)))
10672 ((and (equal type "lisp") (string-match "^/" path))
10673 ;; Planner has a slash, we do not.
10674 (setq type "elisp" path (substring path 1)))
10675 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10676 ;; A typical message link. Planner has the id after the final slash,
10677 ;; we separate it with a hash mark
10678 (setq path (concat (match-string 1 path) "#"
10679 (org-remove-angle-brackets (match-string 2 path))))))
10680 (cons type path))
10682 (defun org-find-file-at-mouse (ev)
10683 "Open file link or URL at mouse."
10684 (interactive "e")
10685 (mouse-set-point ev)
10686 (org-open-at-point 'in-emacs))
10688 (defun org-open-at-mouse (ev)
10689 "Open file link or URL at mouse.
10690 See the docstring of `org-open-file' for details."
10691 (interactive "e")
10692 (mouse-set-point ev)
10693 (when (eq major-mode 'org-agenda-mode)
10694 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10695 (org-open-at-point))
10697 (defvar org-window-config-before-follow-link nil
10698 "The window configuration before following a link.
10699 This is saved in case the need arises to restore it.")
10701 ;;;###autoload
10702 (defun org-open-at-point-global ()
10703 "Follow a link or time-stamp like Org mode does.
10704 This command can be called in any mode to follow an external link
10705 or a time-stamp that has Org mode syntax. Its behavior is
10706 undefined when called on internal links (e.g., fuzzy links).
10707 Raise an error when there is nothing to follow. "
10708 (interactive)
10709 (cond ((org-in-regexp org-any-link-re)
10710 (org-open-link-from-string (match-string-no-properties 0)))
10711 ((or (org-in-regexp org-ts-regexp-both nil t)
10712 (org-in-regexp org-tsr-regexp-both nil t))
10713 (org-follow-timestamp-link))
10714 (t (user-error "No link found"))))
10716 ;;;###autoload
10717 (defun org-open-link-from-string (s &optional arg reference-buffer)
10718 "Open a link in the string S, as if it was in Org-mode."
10719 (interactive "sLink: \nP")
10720 (let ((reference-buffer (or reference-buffer (current-buffer))))
10721 (with-temp-buffer
10722 (let ((org-inhibit-startup (not reference-buffer)))
10723 (org-mode)
10724 (insert s)
10725 (goto-char (point-min))
10726 (when reference-buffer
10727 (setq org-link-abbrev-alist-local
10728 (with-current-buffer reference-buffer
10729 org-link-abbrev-alist-local)))
10730 (org-open-at-point arg reference-buffer)))))
10732 (defvar org-open-at-point-functions nil
10733 "Hook that is run when following a link at point.
10735 Functions in this hook must return t if they identify and follow
10736 a link at point. If they don't find anything interesting at point,
10737 they must return nil.")
10739 (defvar org-link-search-inhibit-query nil)
10740 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10741 (defun org--open-doi-link (path)
10742 "Open a \"doi\" type link.
10743 PATH is a the path to search for, as a string."
10744 (browse-url (url-encode-url (concat org-doi-server-url path))))
10746 (defun org--open-elisp-link (path)
10747 "Open a \"elisp\" type link.
10748 PATH is the sexp to evaluate, as a string."
10749 (let ((cmd path))
10750 (if (or (and (org-string-nw-p
10751 org-confirm-elisp-link-not-regexp)
10752 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10753 (not org-confirm-elisp-link-function)
10754 (funcall org-confirm-elisp-link-function
10755 (format "Execute \"%s\" as elisp? "
10756 (org-add-props cmd nil 'face 'org-warning))))
10757 (message "%s => %s" cmd
10758 (if (eq (string-to-char cmd) ?\()
10759 (eval (read cmd))
10760 (call-interactively (read cmd))))
10761 (user-error "Abort"))))
10763 (defun org--open-help-link (path)
10764 "Open a \"help\" type link.
10765 PATH is a symbol name, as a string."
10766 (pcase (intern path)
10767 ((and (pred fboundp) variable) (describe-function variable))
10768 ((and (pred boundp) function) (describe-variable function))
10769 (name (user-error "Unknown function or variable: %s" name))))
10771 (defun org--open-shell-link (path)
10772 "Open a \"shell\" type link.
10773 PATH is the command to execute, as a string."
10774 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10775 (cmd path))
10776 (if (or (and (org-string-nw-p
10777 org-confirm-shell-link-not-regexp)
10778 (string-match
10779 org-confirm-shell-link-not-regexp cmd))
10780 (not org-confirm-shell-link-function)
10781 (funcall org-confirm-shell-link-function
10782 (format "Execute \"%s\" in shell? "
10783 (org-add-props cmd nil
10784 'face 'org-warning))))
10785 (progn
10786 (message "Executing %s" cmd)
10787 (shell-command cmd buf)
10788 (when (featurep 'midnight)
10789 (setq clean-buffer-list-kill-buffer-names
10790 (cons (buffer-name buf)
10791 clean-buffer-list-kill-buffer-names))))
10792 (user-error "Abort"))))
10794 (defun org-open-at-point (&optional arg reference-buffer)
10795 "Open link, timestamp, footnote or tags at point.
10797 When point is on a link, follow it. Normally, files will be
10798 opened by an appropriate application. If the optional prefix
10799 argument ARG is non-nil, Emacs will visit the file. With
10800 a double prefix argument, try to open outside of Emacs, in the
10801 application the system uses for this file type.
10803 When point is on a timestamp, open the agenda at the day
10804 specified.
10806 When point is a footnote definition, move to the first reference
10807 found. If it is on a reference, move to the associated
10808 definition.
10810 When point is on a headline, display a list of every link in the
10811 entry, so it is possible to pick one, or all, of them. If point
10812 is on a tag, call `org-tags-view' instead.
10814 When optional argument REFERENCE-BUFFER is non-nil, it should
10815 specify a buffer from where the link search should happen. This
10816 is used internally by `org-open-link-from-string'.
10818 On top of syntactically correct links, this function will open
10819 the link at point in comments or comment blocks and the first
10820 link in a property drawer line."
10821 (interactive "P")
10822 ;; On a code block, open block's results.
10823 (unless (call-interactively 'org-babel-open-src-block-result)
10824 (org-load-modules-maybe)
10825 (setq org-window-config-before-follow-link (current-window-configuration))
10826 (org-remove-occur-highlights nil nil t)
10827 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10828 (let* ((context
10829 ;; Only consider supported types, even if they are not
10830 ;; the closest one.
10831 (org-element-lineage
10832 (org-element-context)
10833 '(clock comment comment-block footnote-definition
10834 footnote-reference headline inlinetask keyword link
10835 node-property timestamp)
10837 (type (org-element-type context))
10838 (value (org-element-property :value context)))
10839 (cond
10840 ((not context) (user-error "No link found"))
10841 ;; Exception: open timestamps and links in properties
10842 ;; drawers, keywords and comments.
10843 ((memq type '(comment comment-block keyword node-property))
10844 (call-interactively #'org-open-at-point-global))
10845 ;; On a headline or an inlinetask, but not on a timestamp,
10846 ;; a link, a footnote reference or on tags.
10847 ((and (memq type '(headline inlinetask))
10848 ;; Not on tags.
10849 (progn (save-excursion (beginning-of-line)
10850 (looking-at org-complex-heading-regexp))
10851 (or (not (match-beginning 5))
10852 (< (point) (match-beginning 5)))))
10853 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10854 (links (car data))
10855 (links-end (cdr data)))
10856 (if links
10857 (dolist (link (if (stringp links) (list links) links))
10858 (search-forward link nil links-end)
10859 (goto-char (match-beginning 0))
10860 (org-open-at-point))
10861 (require 'org-attach)
10862 (org-attach-reveal 'if-exists))))
10863 ;; On a clock line, make sure point is on the timestamp
10864 ;; before opening it.
10865 ((and (eq type 'clock)
10866 value
10867 (>= (point) (org-element-property :begin value))
10868 (<= (point) (org-element-property :end value)))
10869 (org-follow-timestamp-link))
10870 ;; Do nothing on white spaces after an object.
10871 ((>= (point)
10872 (save-excursion
10873 (goto-char (org-element-property :end context))
10874 (skip-chars-backward " \t")
10875 (point)))
10876 (user-error "No link found"))
10877 ((eq type 'timestamp) (org-follow-timestamp-link))
10878 ;; On tags within a headline or an inlinetask.
10879 ((and (memq type '(headline inlinetask))
10880 (progn (save-excursion (beginning-of-line)
10881 (looking-at org-complex-heading-regexp))
10882 (and (match-beginning 5)
10883 (>= (point) (match-beginning 5)))))
10884 (org-tags-view arg (substring (match-string 5) 0 -1)))
10885 ((eq type 'link)
10886 ;; When link is located within the description of another
10887 ;; link (e.g., an inline image), always open the parent
10888 ;; link.
10889 (let* ((link (let ((up (org-element-property :parent context)))
10890 (if (eq (org-element-type up) 'link) up context)))
10891 (type (org-element-property :type link))
10892 (path (org-link-unescape (org-element-property :path link))))
10893 ;; Switch back to REFERENCE-BUFFER needed when called in
10894 ;; a temporary buffer through `org-open-link-from-string'.
10895 (with-current-buffer (or reference-buffer (current-buffer))
10896 (cond
10897 ((equal type "file")
10898 (if (string-match "[*?{]" (file-name-nondirectory path))
10899 (dired path)
10900 ;; Look into `org-link-parameters' in order to find
10901 ;; a DEDICATED-FUNCTION to open file. The function
10902 ;; will be applied on raw link instead of parsed
10903 ;; link due to the limitation in `org-add-link-type'
10904 ;; ("open" function called with a single argument).
10905 ;; If no such function is found, fallback to
10906 ;; `org-open-file'.
10907 (let* ((option (org-element-property :search-option link))
10908 (app (org-element-property :application link))
10909 (dedicated-function
10910 (org-link-get-parameter
10911 (if app (concat type "+" app) type)
10912 :follow)))
10913 (if dedicated-function
10914 (funcall dedicated-function
10915 (concat path
10916 (and option (concat "::" option))))
10917 (apply #'org-open-file
10918 path
10919 (cond (arg)
10920 ((equal app "emacs") 'emacs)
10921 ((equal app "sys") 'system))
10922 (cond ((not option) nil)
10923 ((string-match-p "\\`[0-9]+\\'" option)
10924 (list (string-to-number option)))
10925 (t (list nil
10926 (org-link-unescape option)))))))))
10927 ((functionp (org-link-get-parameter type :follow))
10928 (funcall (org-link-get-parameter type :follow) path))
10929 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10930 (unless (run-hook-with-args-until-success
10931 'org-open-link-functions path)
10932 (if (not arg) (org-mark-ring-push)
10933 (switch-to-buffer-other-window
10934 (org-get-buffer-for-internal-link (current-buffer))))
10935 (let ((destination
10936 (org-with-wide-buffer
10937 (if (equal type "radio")
10938 (org-search-radio-target
10939 (org-element-property :path link))
10940 (org-link-search
10941 (if (member type '("custom-id" "coderef"))
10942 (org-element-property :raw-link link)
10943 path)
10944 ;; Prevent fuzzy links from matching
10945 ;; themselves.
10946 (and (equal type "fuzzy")
10947 (+ 2 (org-element-property :begin link)))))
10948 (point))))
10949 (unless (and (<= (point-min) destination)
10950 (>= (point-max) destination))
10951 (widen))
10952 (goto-char destination))))
10953 (t (browse-url-at-point))))))
10954 ;; On a footnote reference or at a footnote definition's label.
10955 ((or (eq type 'footnote-reference)
10956 (and (eq type 'footnote-definition)
10957 (save-excursion
10958 ;; Do not validate action when point is on the
10959 ;; spaces right after the footnote label, in
10960 ;; order to be on par with behaviour on links.
10961 (skip-chars-forward " \t")
10962 (let ((begin
10963 (org-element-property :contents-begin context)))
10964 (if begin (< (point) begin)
10965 (= (org-element-property :post-affiliated context)
10966 (line-beginning-position)))))))
10967 (org-footnote-action))
10968 (t (user-error "No link found")))))
10969 (run-hook-with-args 'org-follow-link-hook)))
10971 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10972 "Offer links in the current entry and return the selected link.
10973 If there is only one link, return it.
10974 If NTH is an integer, return the NTH link found.
10975 If ZERO is a string, check also this string for a link, and if
10976 there is one, return it."
10977 (with-current-buffer buffer
10978 (save-excursion
10979 (save-restriction
10980 (widen)
10981 (goto-char marker)
10982 (let ((cnt ?0)
10983 have-zero end links link c)
10984 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10985 (push (match-string 0 zero) links)
10986 (setq cnt (1- cnt) have-zero t))
10987 (save-excursion
10988 (org-back-to-heading t)
10989 (setq end (save-excursion (outline-next-heading) (point)))
10990 (while (re-search-forward org-any-link-re end t)
10991 (push (match-string 0) links))
10992 (setq links (org-uniquify (reverse links))))
10993 (cond
10994 ((null links)
10995 (message "No links"))
10996 ((equal (length links) 1)
10997 (setq link (car links)))
10998 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10999 (setq link (nth (if have-zero nth (1- nth)) links)))
11000 (t ; we have to select a link
11001 (save-excursion
11002 (save-window-excursion
11003 (delete-other-windows)
11004 (with-output-to-temp-buffer "*Select Link*"
11005 (dolist (l links)
11006 (cond
11007 ((not (string-match org-bracket-link-regexp l))
11008 (princ (format "[%c] %s\n" (cl-incf cnt)
11009 (org-remove-angle-brackets l))))
11010 ((match-end 3)
11011 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
11012 (match-string 3 l) (match-string 1 l))))
11013 (t (princ (format "[%c] %s\n" (cl-incf cnt)
11014 (match-string 1 l)))))))
11015 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
11016 (message "Select link to open, RET to open all:")
11017 (setq c (read-char-exclusive))
11018 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
11019 (when (equal c ?q) (user-error "Abort"))
11020 (if (equal c ?\C-m)
11021 (setq link links)
11022 (setq nth (- c ?0))
11023 (when have-zero (setq nth (1+ nth)))
11024 (unless (and (integerp nth) (>= (length links) nth))
11025 (user-error "Invalid link selection"))
11026 (setq link (nth (1- nth) links)))))
11027 (cons link end))))))
11029 ;; TODO: These functions are deprecated since `org-open-at-point'
11030 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
11031 (defun org-open-file-with-system (path)
11032 "Open file at PATH using the system way of opening it."
11033 (org-open-file path 'system))
11034 (defun org-open-file-with-emacs (path)
11035 "Open file at PATH in Emacs."
11036 (org-open-file path 'emacs))
11039 ;;; File search
11041 (defvar org-create-file-search-functions nil
11042 "List of functions to construct the right search string for a file link.
11043 These functions are called in turn with point at the location to
11044 which the link should point.
11046 A function in the hook should first test if it would like to
11047 handle this file type, for example by checking the `major-mode'
11048 or the file extension. If it decides not to handle this file, it
11049 should just return nil to give other functions a chance. If it
11050 does handle the file, it must return the search string to be used
11051 when following the link. The search string will be part of the
11052 file link, given after a double colon, and `org-open-at-point'
11053 will automatically search for it. If special measures must be
11054 taken to make the search successful, another function should be
11055 added to the companion hook `org-execute-file-search-functions',
11056 which see.
11058 A function in this hook may also use `setq' to set the variable
11059 `description' to provide a suggestion for the descriptive text to
11060 be used for this link when it gets inserted into an Org buffer
11061 with \\[org-insert-link].")
11063 (defvar org-execute-file-search-functions nil
11064 "List of functions to execute a file search triggered by a link.
11066 Functions added to this hook must accept a single argument, the
11067 search string that was part of the file link, the part after the
11068 double colon. The function must first check if it would like to
11069 handle this search, for example by checking the `major-mode' or
11070 the file extension. If it decides not to handle this search, it
11071 should just return nil to give other functions a chance. If it
11072 does handle the search, it must return a non-nil value to keep
11073 other functions from trying.
11075 Each function can access the current prefix argument through the
11076 variable `current-prefix-arg'. Note that a single prefix is used
11077 to force opening a link in Emacs, so it may be good to only use a
11078 numeric or double prefix to guide the search function.
11080 In case this is needed, a function in this hook can also restore
11081 the window configuration before `org-open-at-point' was called using:
11083 \(set-window-configuration org-window-config-before-follow-link)")
11085 (defun org-search-radio-target (target)
11086 "Search a radio target matching TARGET in current buffer.
11087 White spaces are not significant."
11088 (let ((re (format "<<<%s>>>"
11089 (mapconcat #'regexp-quote
11090 (org-split-string target "[ \t\n]+")
11091 "[ \t]+\\(?:\n[ \t]*\\)?")))
11092 (origin (point)))
11093 (goto-char (point-min))
11094 (catch :radio-match
11095 (while (re-search-forward re nil t)
11096 (backward-char)
11097 (let ((object (org-element-context)))
11098 (when (eq (org-element-type object) 'radio-target)
11099 (goto-char (org-element-property :begin object))
11100 (org-show-context 'link-search)
11101 (throw :radio-match nil))))
11102 (goto-char origin)
11103 (user-error "No match for radio target: %s" target))))
11105 (defun org-link-search (s &optional avoid-pos stealth)
11106 "Search for a search string S.
11108 If S starts with \"#\", it triggers a custom ID search.
11110 If S is enclosed within parenthesis, it initiates a coderef
11111 search.
11113 If S is surrounded by forward slashes, it is interpreted as
11114 a regular expression. In Org mode files, this will create an
11115 `org-occur' sparse tree. In ordinary files, `occur' will be used
11116 to list matches. If the current buffer is in `dired-mode', grep
11117 will be used to search in all files.
11119 When AVOID-POS is given, ignore matches near that position.
11121 When optional argument STEALTH is non-nil, do not modify
11122 visibility around point, thus ignoring `org-show-context-detail'
11123 variable.
11125 Search is case-insensitive and ignores white spaces. Return type
11126 of matched result, with is either `dedicated' or `fuzzy'."
11127 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11128 (let* ((case-fold-search t)
11129 (origin (point))
11130 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11131 (words (org-split-string s "[ \t\n]+"))
11132 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11133 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11134 type)
11135 (cond
11136 ;; Check if there are any special search functions.
11137 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11138 ((eq (string-to-char s) ?#)
11139 ;; Look for a custom ID S if S starts with "#".
11140 (let* ((id (substring normalized 1))
11141 (match (org-find-property "CUSTOM_ID" id)))
11142 (if match (progn (goto-char match) (setf type 'dedicated))
11143 (error "No match for custom ID: %s" id))))
11144 ((string-match "\\`(\\(.*\\))\\'" normalized)
11145 ;; Look for coderef targets if S is enclosed within parenthesis.
11146 (let ((coderef (match-string-no-properties 1 normalized))
11147 (re (substring s-single-re 1 -1)))
11148 (goto-char (point-min))
11149 (catch :coderef-match
11150 (while (re-search-forward re nil t)
11151 (let ((element (org-element-at-point)))
11152 (when (and (memq (org-element-type element)
11153 '(example-block src-block))
11154 ;; Build proper regexp according to current
11155 ;; block's label format.
11156 (let ((label-fmt
11157 (regexp-quote
11158 (or (org-element-property :label-fmt element)
11159 org-coderef-label-format))))
11160 (save-excursion
11161 (beginning-of-line)
11162 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11163 (format label-fmt coderef))))))
11164 (setq type 'dedicated)
11165 (goto-char (match-beginning 1))
11166 (throw :coderef-match nil))))
11167 (goto-char origin)
11168 (error "No match for coderef: %s" coderef))))
11169 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11170 ;; Look for a regular expression.
11171 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11172 (match-string 1 s)))
11173 ;; Fuzzy links.
11175 (let ((starred (eq (string-to-char normalized) ?*)))
11176 (cond
11177 ;; Look for targets, only if not in a headline search.
11178 ((and (not starred)
11179 (let ((target (format "<<%s>>" s-multi-re)))
11180 (catch :target-match
11181 (goto-char (point-min))
11182 (while (re-search-forward target nil t)
11183 (backward-char)
11184 (let ((context (org-element-context)))
11185 (when (eq (org-element-type context) 'target)
11186 (setq type 'dedicated)
11187 (goto-char (org-element-property :begin context))
11188 (throw :target-match t))))
11189 nil))))
11190 ;; Look for elements named after S, only if not in a headline
11191 ;; search.
11192 ((and (not starred)
11193 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11194 (catch :name-match
11195 (goto-char (point-min))
11196 (while (re-search-forward name nil t)
11197 (let ((element (org-element-at-point)))
11198 (when (equal (org-split-string
11199 (org-element-property :name element)
11200 "[ \t]+")
11201 words)
11202 (setq type 'dedicated)
11203 (beginning-of-line)
11204 (throw :name-match t))))
11205 nil))))
11206 ;; Regular text search. Prefer headlines in Org mode
11207 ;; buffers.
11208 ((and (derived-mode-p 'org-mode)
11209 (let* ((wspace "[ \t]")
11210 (wspaceopt (concat wspace "*"))
11211 (cookie (concat "\\(?:"
11212 wspaceopt
11213 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11214 wspaceopt
11215 "\\)"))
11216 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11217 (re (concat
11218 org-outline-regexp-bol
11219 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11220 "\\(?:\\[#.\\][ \t]+\\)?"
11221 "\\(?:" org-comment-string "[ \t]+\\)?"
11222 sep "?"
11223 (let ((title (mapconcat #'regexp-quote
11224 words
11225 sep)))
11226 (if starred (substring title 1) title))
11227 sep "?"
11228 "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
11229 "[ \t]*$")))
11230 (goto-char (point-min))
11231 (re-search-forward re nil t)))
11232 (goto-char (match-beginning 0))
11233 (setq type 'dedicated))
11234 ;; Offer to create non-existent headline depending on
11235 ;; `org-link-search-must-match-exact-headline'.
11236 ((and (derived-mode-p 'org-mode)
11237 (not org-link-search-inhibit-query)
11238 (eq org-link-search-must-match-exact-headline 'query-to-create)
11239 (yes-or-no-p "No match - create this as a new heading? "))
11240 (goto-char (point-max))
11241 (unless (bolp) (newline))
11242 (org-insert-heading nil t t)
11243 (insert s "\n")
11244 (beginning-of-line 0))
11245 ;; Only headlines are looked after. No need to process
11246 ;; further: throw an error.
11247 ((and (derived-mode-p 'org-mode)
11248 (or starred org-link-search-must-match-exact-headline))
11249 (goto-char origin)
11250 (error "No match for fuzzy expression: %s" normalized))
11251 ;; Regular text search.
11252 ((catch :fuzzy-match
11253 (goto-char (point-min))
11254 (while (re-search-forward s-multi-re nil t)
11255 ;; Skip match if it contains AVOID-POS or it is included
11256 ;; in a link with a description but outside the
11257 ;; description.
11258 (unless (or (and avoid-pos
11259 (<= (match-beginning 0) avoid-pos)
11260 (> (match-end 0) avoid-pos))
11261 (and (save-match-data
11262 (org-in-regexp org-bracket-link-regexp))
11263 (match-beginning 3)
11264 (or (> (match-beginning 3) (point))
11265 (<= (match-end 3) (point)))
11266 (org-element-lineage
11267 (save-match-data (org-element-context))
11268 '(link) t)))
11269 (goto-char (match-beginning 0))
11270 (setq type 'fuzzy)
11271 (throw :fuzzy-match t)))
11272 nil))
11273 ;; All failed. Throw an error.
11274 (t (goto-char origin)
11275 (error "No match for fuzzy expression: %s" normalized))))))
11276 ;; Disclose surroundings of match, if appropriate.
11277 (when (and (derived-mode-p 'org-mode) (not stealth))
11278 (org-show-context 'link-search))
11279 type))
11281 (defun org-get-buffer-for-internal-link (buffer)
11282 "Return a buffer to be used for displaying the link target of internal links."
11283 (cond
11284 ((not org-display-internal-link-with-indirect-buffer)
11285 buffer)
11286 ((string-match "(Clone)$" (buffer-name buffer))
11287 (message "Buffer is already a clone, not making another one")
11288 ;; we also do not modify visibility in this case
11289 buffer)
11290 (t ; make a new indirect buffer for displaying the link
11291 (let* ((bn (buffer-name buffer))
11292 (ibn (concat bn "(Clone)"))
11293 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11294 (with-current-buffer ib (org-overview))
11295 ib))))
11297 (defun org-do-occur (regexp &optional cleanup)
11298 "Call the Emacs command `occur'.
11299 If CLEANUP is non-nil, remove the printout of the regular expression
11300 in the *Occur* buffer. This is useful if the regex is long and not useful
11301 to read."
11302 (occur regexp)
11303 (when cleanup
11304 (let ((cwin (selected-window)) win beg end)
11305 (when (setq win (get-buffer-window "*Occur*"))
11306 (select-window win))
11307 (goto-char (point-min))
11308 (when (re-search-forward "match[a-z]+" nil t)
11309 (setq beg (match-end 0))
11310 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11311 (setq end (1- (match-beginning 0)))))
11312 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11313 (goto-char (point-min))
11314 (select-window cwin))))
11316 ;;; The mark ring for links jumps
11318 (defvar org-mark-ring nil
11319 "Mark ring for positions before jumps in Org-mode.")
11320 (defvar org-mark-ring-last-goto nil
11321 "Last position in the mark ring used to go back.")
11322 ;; Fill and close the ring
11323 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11324 (dotimes (_ org-mark-ring-length)
11325 (push (make-marker) org-mark-ring))
11326 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11327 org-mark-ring)
11329 (defun org-mark-ring-push (&optional pos buffer)
11330 "Put the current position or POS into the mark ring and rotate it."
11331 (interactive)
11332 (setq pos (or pos (point)))
11333 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11334 (move-marker (car org-mark-ring)
11335 (or pos (point))
11336 (or buffer (current-buffer)))
11337 (message "%s"
11338 (substitute-command-keys
11339 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11341 (defun org-mark-ring-goto (&optional n)
11342 "Jump to the previous position in the mark ring.
11343 With prefix arg N, jump back that many stored positions. When
11344 called several times in succession, walk through the entire ring.
11345 Org mode commands jumping to a different position in the current file,
11346 or to another Org file, automatically push the old position onto the ring."
11347 (interactive "p")
11348 (let (p m)
11349 (if (eq last-command this-command)
11350 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11351 (setq p org-mark-ring))
11352 (setq org-mark-ring-last-goto p)
11353 (setq m (car p))
11354 (pop-to-buffer-same-window (marker-buffer m))
11355 (goto-char m)
11356 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11358 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11359 ;;; Emacs 24.4+
11360 (defun org-remove-angle-brackets (s)
11361 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11362 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11364 (defun org-add-angle-brackets (s)
11365 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11366 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11368 (defun org-remove-double-quotes (s)
11369 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11370 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11373 ;;; Following specific links
11375 (defvar org-agenda-buffer-tmp-name)
11376 (defvar org-agenda-start-on-weekday)
11377 (defun org-follow-timestamp-link ()
11378 "Open an agenda view for the time-stamp date/range at point."
11379 (cond
11380 ((org-at-date-range-p t)
11381 (let ((org-agenda-start-on-weekday)
11382 (t1 (match-string 1))
11383 (t2 (match-string 2)) tt1 tt2)
11384 (setq tt1 (time-to-days (org-time-string-to-time t1))
11385 tt2 (time-to-days (org-time-string-to-time t2)))
11386 (let ((org-agenda-buffer-tmp-name
11387 (format "*Org Agenda(a:%s)"
11388 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11389 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11390 ((org-at-timestamp-p t)
11391 (let ((org-agenda-buffer-tmp-name
11392 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11393 (org-agenda-list nil (time-to-days (org-time-string-to-time
11394 (substring (match-string 1) 0 10)))
11395 1)))
11396 (t (error "This should not happen"))))
11399 ;;; Following file links
11400 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11401 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11402 (declare-function mailcap-mime-info
11403 "mailcap" (string &optional request no-decode))
11404 (defvar org-wait nil)
11405 (defun org-open-file (path &optional in-emacs line search)
11406 "Open the file at PATH.
11407 First, this expands any special file name abbreviations. Then the
11408 configuration variable `org-file-apps' is checked if it contains an
11409 entry for this file type, and if yes, the corresponding command is launched.
11411 If no application is found, Emacs simply visits the file.
11413 With optional prefix argument IN-EMACS, Emacs will visit the file.
11414 With a double \\[universal-argument] \\[universal-argument] \
11415 prefix arg, Org tries to avoid opening in Emacs
11416 and to use an external application to visit the file.
11418 Optional LINE specifies a line to go to, optional SEARCH a string
11419 to search for. If LINE or SEARCH is given, the file will be
11420 opened in Emacs, unless an entry from org-file-apps that makes
11421 use of groups in a regexp matches.
11423 If you want to change the way frames are used when following a
11424 link, please customize `org-link-frame-setup'.
11426 If the file does not exist, an error is thrown."
11427 (let* ((file (if (equal path "")
11428 buffer-file-name
11429 (substitute-in-file-name (expand-file-name path))))
11430 (file-apps (append org-file-apps (org-default-apps)))
11431 (apps (cl-remove-if
11432 'org-file-apps-entry-match-against-dlink-p file-apps))
11433 (apps-dlink (cl-remove-if-not
11434 'org-file-apps-entry-match-against-dlink-p file-apps))
11435 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11436 (dirp (unless remp (file-directory-p file)))
11437 (file (if (and dirp org-open-directory-means-index-dot-org)
11438 (concat (file-name-as-directory file) "index.org")
11439 file))
11440 (a-m-a-p (assq 'auto-mode apps))
11441 (dfile (downcase file))
11442 ;; Reconstruct the original link from the PATH, LINE and
11443 ;; SEARCH args.
11444 (link (cond (line (concat file "::" (number-to-string line)))
11445 (search (concat file "::" search))
11446 (t file)))
11447 (dlink (downcase link))
11448 (old-buffer (current-buffer))
11449 (old-pos (point))
11450 (old-mode major-mode)
11451 (ext
11452 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11453 (match-string 1 dfile)))
11454 cmd link-match-data)
11455 (cond
11456 ((member in-emacs '((16) system))
11457 (setq cmd (cdr (assq 'system apps))))
11458 (in-emacs (setq cmd 'emacs))
11460 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11461 (and dirp (cdr (assq 'directory apps)))
11462 ;; First, try matching against apps-dlink if we
11463 ;; get a match here, store the match data for
11464 ;; later.
11465 (let ((match (assoc-default dlink apps-dlink
11466 'string-match)))
11467 (if match
11468 (progn (setq link-match-data (match-data))
11469 match)
11470 (progn (setq in-emacs (or in-emacs line search))
11471 nil))) ; if we have no match in apps-dlink,
11472 ; always open the file in emacs if line or search
11473 ; is given (for backwards compatibility)
11474 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11475 'string-match)
11476 (cdr (assoc ext apps))
11477 (cdr (assq t apps))))))
11478 (when (eq cmd 'system)
11479 (setq cmd (cdr (assoc 'system apps))))
11480 (when (eq cmd 'default)
11481 (setq cmd (cdr (assoc t apps))))
11482 (when (eq cmd 'mailcap)
11483 (require 'mailcap)
11484 (mailcap-parse-mailcaps)
11485 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11486 (command (mailcap-mime-info mime-type)))
11487 (if (stringp command)
11488 (setq cmd command)
11489 (setq cmd 'emacs))))
11490 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11491 (not (file-exists-p file))
11492 (not org-open-non-existing-files))
11493 (user-error "No such file: %s" file))
11494 (cond
11495 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11496 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11497 (while (string-match "['\"]%s['\"]" cmd)
11498 (setq cmd (replace-match "%s" t t cmd)))
11499 (while (string-match "%s" cmd)
11500 (setq cmd (replace-match
11501 (save-match-data
11502 (shell-quote-argument
11503 (convert-standard-filename file)))
11504 t t cmd)))
11506 ;; Replace "%1", "%2" etc. in command with group matches from regex
11507 (save-match-data
11508 (let ((match-index 1)
11509 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11510 (set-match-data link-match-data)
11511 (while (<= match-index number-of-groups)
11512 (let ((regex (concat "%" (number-to-string match-index)))
11513 (replace-with (match-string match-index dlink)))
11514 (while (string-match regex cmd)
11515 (setq cmd (replace-match replace-with t t cmd))))
11516 (setq match-index (+ match-index 1)))))
11518 (save-window-excursion
11519 (message "Running %s...done" cmd)
11520 (start-process-shell-command cmd nil cmd)
11521 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11522 ((or (stringp cmd)
11523 (eq cmd 'emacs))
11524 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11525 (widen)
11526 (cond (line (org-goto-line line)
11527 (when (derived-mode-p 'org-mode) (org-reveal)))
11528 (search (org-link-search search))))
11529 ((functionp cmd)
11530 (save-match-data
11531 (set-match-data link-match-data)
11532 (condition-case nil
11533 (funcall cmd file link)
11534 ;; FIXME: Remove this check when most default installations
11535 ;; of Emacs have at least Org 9.0.
11536 ((debug wrong-number-of-arguments wrong-type-argument
11537 invalid-function)
11538 (user-error "Please see Org News for version 9.0 about \
11539 `org-file-apps'--Lisp error: %S" cmd)))))
11540 ((consp cmd)
11541 ;; FIXME: Remove this check when most default installations of
11542 ;; Emacs have at least Org 9.0.
11543 ;; Heads-up instead of silently fall back to
11544 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11545 ;; with sexp instead of a function for `cmd'.
11546 (user-error "Please see Org News for version 9.0 about \
11547 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11548 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11549 (and (derived-mode-p 'org-mode)
11550 (eq old-mode 'org-mode)
11551 (or (not (eq old-buffer (current-buffer)))
11552 (not (eq old-pos (point))))
11553 (org-mark-ring-push old-pos old-buffer))))
11555 (defun org-file-apps-entry-match-against-dlink-p (entry)
11556 "This function returns non-nil if `entry' uses a regular
11557 expression which should be matched against the whole link by
11558 org-open-file.
11560 It assumes that is the case when the entry uses a regular
11561 expression which has at least one grouping construct and the
11562 action is either a lisp form or a command string containing
11563 `%1', i.e. using at least one subexpression match as a
11564 parameter."
11565 (let ((selector (car entry))
11566 (action (cdr entry)))
11567 (if (stringp selector)
11568 (and (> (regexp-opt-depth selector) 0)
11569 (or (and (stringp action)
11570 (string-match "%[0-9]" action))
11571 (consp action)))
11572 nil)))
11574 (defun org-default-apps ()
11575 "Return the default applications for this operating system."
11576 (cond
11577 ((eq system-type 'darwin)
11578 org-file-apps-defaults-macosx)
11579 ((eq system-type 'windows-nt)
11580 org-file-apps-defaults-windowsnt)
11581 (t org-file-apps-defaults-gnu)))
11583 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11584 "Convert extensions to regular expressions in the cars of LIST.
11585 Also, weed out any non-string entries, because the return value is used
11586 only for regexp matching.
11587 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11588 point to the symbol `emacs', indicating that the file should
11589 be opened in Emacs."
11590 (append
11591 (delq nil
11592 (mapcar (lambda (x)
11593 (unless (not (stringp (car x)))
11594 (if (string-match "\\W" (car x))
11596 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11597 list))
11598 (when add-auto-mode
11599 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11601 (defvar ange-ftp-name-format)
11602 (defun org-file-remote-p (file)
11603 "Test whether FILE specifies a location on a remote system.
11604 Return non-nil if the location is indeed remote.
11606 For example, the filename \"/user@host:/foo\" specifies a location
11607 on the system \"/user@host:\"."
11608 (cond ((fboundp 'file-remote-p)
11609 (file-remote-p file))
11610 ((fboundp 'tramp-handle-file-remote-p)
11611 (tramp-handle-file-remote-p file))
11612 ((and (boundp 'ange-ftp-name-format)
11613 (string-match (car ange-ftp-name-format) file))
11614 t)))
11617 ;;;; Refiling
11619 (defun org-get-org-file ()
11620 "Read a filename, with default directory `org-directory'."
11621 (let ((default (or org-default-notes-file remember-data-file)))
11622 (read-file-name (format "File name [%s]: " default)
11623 (file-name-as-directory org-directory)
11624 default)))
11626 (defun org-notes-order-reversed-p ()
11627 "Check if the current file should receive notes in reversed order."
11628 (cond
11629 ((not org-reverse-note-order) nil)
11630 ((eq t org-reverse-note-order) t)
11631 ((not (listp org-reverse-note-order)) nil)
11632 (t (catch 'exit
11633 (dolist (entry org-reverse-note-order)
11634 (when (string-match (car entry) buffer-file-name)
11635 (throw 'exit (cdr entry))))))))
11637 (defvar org-refile-target-table nil
11638 "The list of refile targets, created by `org-refile'.")
11640 (defvar org-agenda-new-buffers nil
11641 "Buffers created to visit agenda files.")
11643 (defvar org-refile-cache nil
11644 "Cache for refile targets.")
11646 (defvar org-refile-markers nil
11647 "All the markers used for caching refile locations.")
11649 (defun org-refile-marker (pos)
11650 "Get a new refile marker, but only if caching is in use."
11651 (if (not org-refile-use-cache)
11653 (let ((m (make-marker)))
11654 (move-marker m pos)
11655 (push m org-refile-markers)
11656 m)))
11658 (defun org-refile-cache-clear ()
11659 "Clear the refile cache and disable all the markers."
11660 (dolist (m org-refile-markers) (move-marker m nil))
11661 (setq org-refile-markers nil)
11662 (setq org-refile-cache nil)
11663 (message "Refile cache has been cleared"))
11665 (defun org-refile-cache-check-set (set)
11666 "Check if all the markers in the cache still have live buffers."
11667 (let (marker)
11668 (catch 'exit
11669 (while (and set (setq marker (nth 3 (pop set))))
11670 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11671 (when (and marker (null (marker-buffer marker)))
11672 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11673 (sit-for 3)
11674 (throw 'exit nil)))
11675 t)))
11677 (defun org-refile-cache-put (set &rest identifiers)
11678 "Push the refile targets SET into the cache, under IDENTIFIERS."
11679 (let* ((key (sha1 (prin1-to-string identifiers)))
11680 (entry (assoc key org-refile-cache)))
11681 (if entry
11682 (setcdr entry set)
11683 (push (cons key set) org-refile-cache))))
11685 (defun org-refile-cache-get (&rest identifiers)
11686 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11687 (cond
11688 ((not org-refile-cache) nil)
11689 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11691 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11692 org-refile-cache))))
11693 (and set (org-refile-cache-check-set set) set)))))
11695 (defvar org-outline-path-cache nil
11696 "Alist between buffer positions and outline paths.
11697 It value is an alist (POSITION . PATH) where POSITION is the
11698 buffer position at the beginning of an entry and PATH is a list
11699 of strings describing the outline path for that entry, in reverse
11700 order.")
11702 (defun org-refile-get-targets (&optional default-buffer)
11703 "Produce a table with refile targets."
11704 (let ((case-fold-search nil)
11705 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11706 (entries (or org-refile-targets '((nil . (:level . 1)))))
11707 targets tgs files desc descre)
11708 (message "Getting targets...")
11709 (with-current-buffer (or default-buffer (current-buffer))
11710 (dolist (entry entries)
11711 (setq files (car entry) desc (cdr entry))
11712 (cond
11713 ((null files) (setq files (list (current-buffer))))
11714 ((eq files 'org-agenda-files)
11715 (setq files (org-agenda-files 'unrestricted)))
11716 ((and (symbolp files) (fboundp files))
11717 (setq files (funcall files)))
11718 ((and (symbolp files) (boundp files))
11719 (setq files (symbol-value files))))
11720 (when (stringp files) (setq files (list files)))
11721 (cond
11722 ((eq (car desc) :tag)
11723 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11724 ((eq (car desc) :todo)
11725 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11726 ((eq (car desc) :regexp)
11727 (setq descre (cdr desc)))
11728 ((eq (car desc) :level)
11729 (setq descre (concat "^\\*\\{" (number-to-string
11730 (if org-odd-levels-only
11731 (1- (* 2 (cdr desc)))
11732 (cdr desc)))
11733 "\\}[ \t]")))
11734 ((eq (car desc) :maxlevel)
11735 (setq descre (concat "^\\*\\{1," (number-to-string
11736 (if org-odd-levels-only
11737 (1- (* 2 (cdr desc)))
11738 (cdr desc)))
11739 "\\}[ \t]")))
11740 (t (error "Bad refiling target description %s" desc)))
11741 (dolist (f files)
11742 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11744 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11745 (progn
11746 (when (bufferp f)
11747 (setq f (buffer-file-name (buffer-base-buffer f))))
11748 (setq f (and f (expand-file-name f)))
11749 (when (eq org-refile-use-outline-path 'file)
11750 (push (list (file-name-nondirectory f) f nil nil) tgs))
11751 (org-with-wide-buffer
11752 (goto-char (point-min))
11753 (setq org-outline-path-cache nil)
11754 (while (re-search-forward descre nil t)
11755 (beginning-of-line)
11756 (looking-at org-complex-heading-regexp)
11757 (let ((begin (point))
11758 (heading (match-string-no-properties 4)))
11759 (unless (or (and
11760 org-refile-target-verify-function
11761 (not
11762 (funcall org-refile-target-verify-function)))
11763 (not heading))
11764 (let ((re (format org-complex-heading-regexp-format
11765 (regexp-quote heading)))
11766 (target
11767 (if (not org-refile-use-outline-path) heading
11768 (mapconcat
11769 #'org-protect-slash
11770 (append
11771 (pcase org-refile-use-outline-path
11772 (`file (list (file-name-nondirectory
11773 (buffer-file-name
11774 (buffer-base-buffer)))))
11775 (`full-file-path
11776 (list (buffer-file-name
11777 (buffer-base-buffer))))
11778 (_ nil))
11779 (org-get-outline-path t t))
11780 "/"))))
11781 (push (list target f re (org-refile-marker (point)))
11782 tgs)))
11783 (when (= (point) begin)
11784 ;; Verification function has not moved point.
11785 (end-of-line)))))))
11786 (when org-refile-use-cache
11787 (org-refile-cache-put tgs (buffer-file-name) descre))
11788 (setq targets (append tgs targets))))))
11789 (message "Getting targets...done")
11790 (nreverse targets)))
11792 (defun org-protect-slash (s)
11793 (while (string-match "/" s)
11794 (setq s (replace-match "\\" t t s)))
11797 (defun org--get-outline-path-1 (&optional use-cache)
11798 "Return outline path to current headline.
11800 Outline path is a list of strings, in reverse order. When
11801 optional argument USE-CACHE is non-nil, make use of a cache. See
11802 `org-get-outline-path' for details.
11804 Assume buffer is widened and point is on a headline."
11805 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11806 (let ((p (point))
11807 (heading (progn
11808 (looking-at org-complex-heading-regexp)
11809 (if (not (match-end 4)) ""
11810 ;; Remove statistics cookies.
11811 (org-trim
11812 (org-link-display-format
11813 (replace-regexp-in-string
11814 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11815 (match-string-no-properties 4))))))))
11816 (if (org-up-heading-safe)
11817 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11818 (when use-cache
11819 (push (cons p path) org-outline-path-cache))
11820 path)
11821 ;; This is a new root node. Since we assume we are moving
11822 ;; forward, we can drop previous cache so as to limit number
11823 ;; of associations there.
11824 (let ((path (list heading)))
11825 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11826 path)))))
11828 (defun org-get-outline-path (&optional with-self use-cache)
11829 "Return the outline path to the current entry.
11831 An outline path is a list of ancestors for current headline, as
11832 a list of strings. Statistics cookies are removed and links are
11833 replaced with their description, if any, or their path otherwise.
11835 When optional argument WITH-SELF is non-nil, the path also
11836 includes the current headline.
11838 When optional argument USE-CACHE is non-nil, cache outline paths
11839 between calls to this function so as to avoid backtracking. This
11840 argument is useful when planning to find more than one outline
11841 path in the same document. In that case, there are two
11842 conditions to satisfy:
11843 - `org-outline-path-cache' is set to nil before starting the
11844 process;
11845 - outline paths are computed by increasing buffer positions."
11846 (org-with-wide-buffer
11847 (and (or (and with-self (org-back-to-heading t))
11848 (org-up-heading-safe))
11849 (reverse (org--get-outline-path-1 use-cache)))))
11851 (defun org-format-outline-path (path &optional width prefix separator)
11852 "Format the outline path PATH for display.
11853 WIDTH is the maximum number of characters that is available.
11854 PREFIX is a prefix to be included in the returned string,
11855 such as the file name.
11856 SEPARATOR is inserted between the different parts of the path,
11857 the default is \"/\"."
11858 (setq width (or width 79))
11859 (setq path (delq nil path))
11860 (unless (> width 0)
11861 (user-error "Argument `width' must be positive"))
11862 (setq separator (or separator "/"))
11863 (let* ((org-odd-levels-only nil)
11864 (fpath (concat
11865 prefix (and prefix path separator)
11866 (mapconcat
11867 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11868 (cl-loop for head in path
11869 for n from 0
11870 collect (org-add-props
11871 head nil 'face
11872 (nth (% n org-n-level-faces) org-level-faces)))
11873 separator))))
11874 (when (> (length fpath) width)
11875 (if (< width 7)
11876 ;; It's unlikely that `width' will be this small, but don't
11877 ;; waste characters by adding ".." if it is.
11878 (setq fpath (substring fpath 0 width))
11879 (setf (substring fpath (- width 2)) "..")))
11880 fpath))
11882 (defun org-display-outline-path (&optional file current separator just-return-string)
11883 "Display the current outline path in the echo area.
11885 If FILE is non-nil, prepend the output with the file name.
11886 If CURRENT is non-nil, append the current heading to the output.
11887 SEPARATOR is passed through to `org-format-outline-path'. It separates
11888 the different parts of the path and defaults to \"/\".
11889 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11890 (interactive "P")
11891 (let* (case-fold-search
11892 (bfn (buffer-file-name (buffer-base-buffer)))
11893 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11894 res)
11895 (when current (setq path (append path
11896 (save-excursion
11897 (org-back-to-heading t)
11898 (when (looking-at org-complex-heading-regexp)
11899 (list (match-string 4)))))))
11900 (setq res
11901 (org-format-outline-path
11902 path
11903 (1- (frame-width))
11904 (and file bfn (concat (file-name-nondirectory bfn) separator))
11905 separator))
11906 (if just-return-string
11907 (org-no-properties res)
11908 (org-unlogged-message "%s" res))))
11910 (defvar org-refile-history nil
11911 "History for refiling operations.")
11913 (defvar org-after-refile-insert-hook nil
11914 "Hook run after `org-refile' has inserted its stuff at the new location.
11915 Note that this is still *before* the stuff will be removed from
11916 the *old* location.")
11918 (defvar org-capture-last-stored-marker)
11919 (defvar org-refile-keep nil
11920 "Non-nil means `org-refile' will copy instead of refile.")
11922 (defun org-copy ()
11923 "Like `org-refile', but copy."
11924 (interactive)
11925 (let ((org-refile-keep t))
11926 (funcall 'org-refile nil nil nil "Copy")))
11928 (defun org-refile (&optional arg default-buffer rfloc msg)
11929 "Move the entry or entries at point to another heading.
11930 The list of target headings is compiled using the information in
11931 `org-refile-targets', which see.
11933 At the target location, the entry is filed as a subitem of the
11934 target heading. Depending on `org-reverse-note-order', the new
11935 subitem will either be the first or the last subitem.
11937 If there is an active region, all entries in that region will be
11938 refiled. However, the region must fulfill the requirement that
11939 the first heading sets the top-level of the moved text.
11941 With prefix arg ARG, the command will only visit the target
11942 location and not actually move anything.
11944 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11945 refiling operation has put the subtree.
11947 With a numeric prefix argument of `2', refile to the running clock.
11949 With a numeric prefix argument of `3', emulate `org-refile-keep'
11950 being set to t and copy to the target location, don't move it.
11951 Beware that keeping refiled entries may result in duplicated ID
11952 properties.
11954 RFLOC can be a refile location obtained in a different way.
11956 MSG is a string to replace \"Refile\" in the default prompt with
11957 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11959 See also `org-refile-use-outline-path'.
11961 If you are using target caching (see `org-refile-use-cache'), you
11962 have to clear the target cache in order to find new targets.
11963 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11964 prefix argument (`C-u C-u C-u C-c C-w')."
11965 (interactive "P")
11966 (if (member arg '(0 (64)))
11967 (org-refile-cache-clear)
11968 (let* ((actionmsg (cond (msg msg)
11969 ((equal arg 3) "Refile (and keep)")
11970 (t "Refile")))
11971 (regionp (org-region-active-p))
11972 (region-start (and regionp (region-beginning)))
11973 (region-end (and regionp (region-end)))
11974 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11975 pos it nbuf file level reversed)
11976 (setq last-command nil)
11977 (when regionp
11978 (goto-char region-start)
11979 (or (bolp) (goto-char (point-at-bol)))
11980 (setq region-start (point))
11981 (unless (or (org-kill-is-subtree-p
11982 (buffer-substring region-start region-end))
11983 (prog1 org-refile-active-region-within-subtree
11984 (let ((s (point-at-eol)))
11985 (org-toggle-heading)
11986 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11987 (user-error "The region is not a (sequence of) subtree(s)")))
11988 (if (equal arg '(16))
11989 (org-refile-goto-last-stored)
11990 (when (or
11991 (and (equal arg 2)
11992 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11993 (prog1
11994 (setq it (list (or org-clock-heading "running clock")
11995 (buffer-file-name
11996 (marker-buffer org-clock-hd-marker))
11998 (marker-position org-clock-hd-marker)))
11999 (setq arg nil)))
12000 (setq it
12001 (or rfloc
12002 (let (heading-text)
12003 (save-excursion
12004 (unless (and arg (listp arg))
12005 (org-back-to-heading t)
12006 (setq heading-text
12007 (replace-regexp-in-string
12008 org-bracket-link-regexp
12009 "\\3"
12010 (or (nth 4 (org-heading-components))
12011 ""))))
12012 (org-refile-get-location
12013 (cond ((and arg (listp arg)) "Goto")
12014 (regionp (concat actionmsg " region to"))
12015 (t (concat actionmsg " subtree \""
12016 heading-text "\" to")))
12017 default-buffer
12018 (and (not (equal '(4) arg))
12019 org-refile-allow-creating-parent-nodes)))))))
12020 (setq file (nth 1 it)
12021 pos (nth 3 it))
12022 (when (and (not arg)
12024 (equal (buffer-file-name) file)
12025 (if regionp
12026 (and (>= pos region-start)
12027 (<= pos region-end))
12028 (and (>= pos (point))
12029 (< pos (save-excursion
12030 (org-end-of-subtree t t))))))
12031 (error "Cannot refile to position inside the tree or region"))
12032 (setq nbuf (or (find-buffer-visiting file)
12033 (find-file-noselect file)))
12034 (if (and arg (not (equal arg 3)))
12035 (progn
12036 (pop-to-buffer-same-window nbuf)
12037 (goto-char pos)
12038 (org-show-context 'org-goto))
12039 (if regionp
12040 (progn
12041 (org-kill-new (buffer-substring region-start region-end))
12042 (org-save-markers-in-region region-start region-end))
12043 (org-copy-subtree 1 nil t))
12044 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
12045 (find-file-noselect file)))
12046 (setq reversed (org-notes-order-reversed-p))
12047 (save-excursion
12048 (save-restriction
12049 (widen)
12050 (if pos
12051 (progn
12052 (goto-char pos)
12053 (looking-at org-outline-regexp)
12054 (setq level (org-get-valid-level (funcall outline-level) 1))
12055 (goto-char
12056 (if reversed
12057 (or (outline-next-heading) (point-max))
12058 (or (save-excursion (org-get-next-sibling))
12059 (org-end-of-subtree t t)
12060 (point-max)))))
12061 (setq level 1)
12062 (if (not reversed)
12063 (goto-char (point-max))
12064 (goto-char (point-min))
12065 (or (outline-next-heading) (goto-char (point-max)))))
12066 (unless (bolp) (newline))
12067 (org-paste-subtree level nil nil t)
12068 (when org-log-refile
12069 (org-add-log-setup 'refile nil nil org-log-refile)
12070 (unless (eq org-log-refile 'note)
12071 (save-excursion (org-add-log-note))))
12072 (and org-auto-align-tags
12073 (let ((org-loop-over-headlines-in-active-region nil))
12074 (org-set-tags nil t)))
12075 (let ((bookmark-name (plist-get org-bookmark-names-plist
12076 :last-refile)))
12077 (when bookmark-name
12078 (with-demoted-errors
12079 (bookmark-set bookmark-name))))
12080 ;; If we are refiling for capture, make sure that the
12081 ;; last-capture pointers point here
12082 (when (bound-and-true-p org-capture-is-refiling)
12083 (let ((bookmark-name (plist-get org-bookmark-names-plist
12084 :last-capture-marker)))
12085 (when bookmark-name
12086 (with-demoted-errors
12087 (bookmark-set bookmark-name))))
12088 (move-marker org-capture-last-stored-marker (point)))
12089 (when (fboundp 'deactivate-mark) (deactivate-mark))
12090 (run-hooks 'org-after-refile-insert-hook))))
12091 (unless org-refile-keep
12092 (if regionp
12093 (delete-region (point) (+ (point) (- region-end region-start)))
12094 (delete-region
12095 (and (org-back-to-heading t) (point))
12096 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12097 (when (featurep 'org-inlinetask)
12098 (org-inlinetask-remove-END-maybe))
12099 (setq org-markers-to-move nil)
12100 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12102 (defun org-refile-goto-last-stored ()
12103 "Go to the location where the last refile was stored."
12104 (interactive)
12105 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12106 (message "This is the location of the last refile"))
12108 (defun org-refile--get-location (refloc tbl)
12109 "When user refile to REFLOC, find the associated target in TBL.
12110 Also check `org-refile-target-table'."
12111 (car (delq
12113 (mapcar
12114 (lambda (r) (or (assoc r tbl)
12115 (assoc r org-refile-target-table)))
12116 (list (replace-regexp-in-string "/$" "" refloc)
12117 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12119 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12120 "Prompt the user for a refile location, using PROMPT.
12121 PROMPT should not be suffixed with a colon and a space, because
12122 this function appends the default value from
12123 `org-refile-history' automatically, if that is not empty."
12124 (let ((org-refile-targets org-refile-targets)
12125 (org-refile-use-outline-path org-refile-use-outline-path))
12126 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12127 (unless org-refile-target-table
12128 (user-error "No refile targets"))
12129 (let* ((cbuf (current-buffer))
12130 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12131 (cfunc (if (and org-refile-use-outline-path
12132 org-outline-path-complete-in-steps)
12133 #'org-olpath-completing-read
12134 #'completing-read))
12135 (extra (if org-refile-use-outline-path "/" ""))
12136 (cbnex (concat (buffer-name) extra))
12137 (filename (and cfn (expand-file-name cfn)))
12138 (tbl (mapcar
12139 (lambda (x)
12140 (if (and (not (member org-refile-use-outline-path
12141 '(file full-file-path)))
12142 (not (equal filename (nth 1 x))))
12143 (cons (concat (car x) extra " ("
12144 (file-name-nondirectory (nth 1 x)) ")")
12145 (cdr x))
12146 (cons (concat (car x) extra) (cdr x))))
12147 org-refile-target-table))
12148 (completion-ignore-case t)
12149 cdef
12150 (prompt (concat prompt
12151 (or (and (car org-refile-history)
12152 (concat " (default " (car org-refile-history) ")"))
12153 (and (assoc cbnex tbl) (setq cdef cbnex)
12154 (concat " (default " cbnex ")"))) ": "))
12155 pa answ parent-target child parent old-hist)
12156 (setq old-hist org-refile-history)
12157 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12158 nil 'org-refile-history (or cdef (car org-refile-history))))
12159 (if (setq pa (org-refile--get-location answ tbl))
12160 (progn
12161 (org-refile-check-position pa)
12162 (when (or (not org-refile-history)
12163 (not (eq old-hist org-refile-history))
12164 (not (equal (car pa) (car org-refile-history))))
12165 (setq org-refile-history
12166 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12167 org-refile-history
12168 (cdr org-refile-history))))
12169 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12170 (pop org-refile-history)))
12172 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12173 (progn
12174 (setq parent (match-string 1 answ)
12175 child (match-string 2 answ))
12176 (setq parent-target (org-refile--get-location parent tbl))
12177 (when (and parent-target
12178 (or (eq new-nodes t)
12179 (and (eq new-nodes 'confirm)
12180 (y-or-n-p (format "Create new node \"%s\"? "
12181 child)))))
12182 (org-refile-new-child parent-target child)))
12183 (user-error "Invalid target location")))))
12185 (declare-function org-string-nw-p "org-macs" (s))
12186 (defun org-refile-check-position (refile-pointer)
12187 "Check if the refile pointer matches the headline to which it points."
12188 (let* ((file (nth 1 refile-pointer))
12189 (re (nth 2 refile-pointer))
12190 (pos (nth 3 refile-pointer))
12191 buffer)
12192 (if (and (not (markerp pos)) (not file))
12193 (user-error "Please indicate a target file in the refile path")
12194 (when (org-string-nw-p re)
12195 (setq buffer (if (markerp pos)
12196 (marker-buffer pos)
12197 (or (find-buffer-visiting file)
12198 (find-file-noselect file))))
12199 (with-current-buffer buffer
12200 (save-excursion
12201 (save-restriction
12202 (widen)
12203 (goto-char pos)
12204 (beginning-of-line 1)
12205 (unless (looking-at-p re)
12206 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12208 (defun org-refile-new-child (parent-target child)
12209 "Use refile target PARENT-TARGET to add new CHILD below it."
12210 (unless parent-target
12211 (error "Cannot find parent for new node"))
12212 (let ((file (nth 1 parent-target))
12213 (pos (nth 3 parent-target))
12214 level)
12215 (with-current-buffer (or (find-buffer-visiting file)
12216 (find-file-noselect file))
12217 (save-excursion
12218 (save-restriction
12219 (widen)
12220 (if pos
12221 (goto-char pos)
12222 (goto-char (point-max))
12223 (unless (bolp) (newline)))
12224 (when (looking-at org-outline-regexp)
12225 (setq level (funcall outline-level))
12226 (org-end-of-subtree t t))
12227 (org-back-over-empty-lines)
12228 (insert "\n" (make-string
12229 (if pos (org-get-valid-level level 1) 1) ?*)
12230 " " child "\n")
12231 (beginning-of-line 0)
12232 (list (concat (car parent-target) "/" child) file "" (point)))))))
12234 (defun org-olpath-completing-read (prompt collection &rest args)
12235 "Read an outline path like a file name."
12236 (let ((thetable collection))
12237 (apply #'completing-read
12238 prompt
12239 (lambda (string predicate &optional flag)
12240 (cond
12241 ((eq flag nil) (try-completion string thetable))
12242 ((eq flag t)
12243 (let ((l (length string)))
12244 (mapcar (lambda (x)
12245 (let ((r (substring x l))
12246 (f (if (string-match " ([^)]*)$" x)
12247 (match-string 0 x)
12248 "")))
12249 (if (string-match "/" r)
12250 (concat string (substring r 0 (match-end 0)) f)
12251 x)))
12252 (all-completions string thetable predicate))))
12253 ;; Exact match?
12254 ((eq flag 'lambda) (assoc string thetable))))
12255 args)))
12257 ;;;; Dynamic blocks
12259 (defun org-find-dblock (name)
12260 "Find the first dynamic block with name NAME in the buffer.
12261 If not found, stay at current position and return nil."
12262 (let ((case-fold-search t) pos)
12263 (save-excursion
12264 (goto-char (point-min))
12265 (setq pos (and (re-search-forward
12266 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12267 (match-beginning 0))))
12268 (when pos (goto-char pos))
12269 pos))
12271 (defun org-create-dblock (plist)
12272 "Create a dynamic block section, with parameters taken from PLIST.
12273 PLIST must contain a :name entry which is used as the name of the block."
12274 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12275 (end-of-line 1)
12276 (newline))
12277 (let ((col (current-column))
12278 (name (plist-get plist :name)))
12279 (insert "#+BEGIN: " name)
12280 (while plist
12281 (if (eq (car plist) :name)
12282 (setq plist (cddr plist))
12283 (insert " " (prin1-to-string (pop plist)))))
12284 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12285 (beginning-of-line -2)))
12287 (defun org-prepare-dblock ()
12288 "Prepare dynamic block for refresh.
12289 This empties the block, puts the cursor at the insert position and returns
12290 the property list including an extra property :name with the block name."
12291 (unless (looking-at org-dblock-start-re)
12292 (user-error "Not at a dynamic block"))
12293 (let* ((begdel (1+ (match-end 0)))
12294 (name (org-no-properties (match-string 1)))
12295 (params (append (list :name name)
12296 (read (concat "(" (match-string 3) ")")))))
12297 (save-excursion
12298 (beginning-of-line 1)
12299 (skip-chars-forward " \t")
12300 (setq params (plist-put params :indentation-column (current-column))))
12301 (unless (re-search-forward org-dblock-end-re nil t)
12302 (error "Dynamic block not terminated"))
12303 (setq params
12304 (append params
12305 (list :content (buffer-substring
12306 begdel (match-beginning 0)))))
12307 (delete-region begdel (match-beginning 0))
12308 (goto-char begdel)
12309 (open-line 1)
12310 params))
12312 (defun org-map-dblocks (&optional command)
12313 "Apply COMMAND to all dynamic blocks in the current buffer.
12314 If COMMAND is not given, use `org-update-dblock'."
12315 (let ((cmd (or command 'org-update-dblock)))
12316 (save-excursion
12317 (goto-char (point-min))
12318 (while (re-search-forward org-dblock-start-re nil t)
12319 (goto-char (match-beginning 0))
12320 (save-excursion
12321 (condition-case nil
12322 (funcall cmd)
12323 (error (message "Error during update of dynamic block"))))
12324 (unless (re-search-forward org-dblock-end-re nil t)
12325 (error "Dynamic block not terminated"))))))
12327 (defun org-dblock-update (&optional arg)
12328 "User command for updating dynamic blocks.
12329 Update the dynamic block at point. With prefix ARG, update all dynamic
12330 blocks in the buffer."
12331 (interactive "P")
12332 (if arg
12333 (org-update-all-dblocks)
12334 (or (looking-at org-dblock-start-re)
12335 (org-beginning-of-dblock))
12336 (org-update-dblock)))
12338 (defun org-update-dblock ()
12339 "Update the dynamic block at point.
12340 This means to empty the block, parse for parameters and then call
12341 the correct writing function."
12342 (interactive)
12343 (save-excursion
12344 (let* ((win (selected-window))
12345 (pos (point))
12346 (line (org-current-line))
12347 (params (org-prepare-dblock))
12348 (name (plist-get params :name))
12349 (indent (plist-get params :indentation-column))
12350 (cmd (intern (concat "org-dblock-write:" name))))
12351 (message "Updating dynamic block `%s' at line %d..." name line)
12352 (funcall cmd params)
12353 (message "Updating dynamic block `%s' at line %d...done" name line)
12354 (goto-char pos)
12355 (when (and indent (> indent 0))
12356 (setq indent (make-string indent ?\ ))
12357 (save-excursion
12358 (select-window win)
12359 (org-beginning-of-dblock)
12360 (forward-line 1)
12361 (while (not (looking-at org-dblock-end-re))
12362 (insert indent)
12363 (beginning-of-line 2))
12364 (when (looking-at org-dblock-end-re)
12365 (and (looking-at "[ \t]+")
12366 (replace-match ""))
12367 (insert indent)))))))
12369 (defun org-beginning-of-dblock ()
12370 "Find the beginning of the dynamic block at point.
12371 Error if there is no such block at point."
12372 (let ((pos (point))
12373 beg)
12374 (end-of-line 1)
12375 (if (and (re-search-backward org-dblock-start-re nil t)
12376 (setq beg (match-beginning 0))
12377 (re-search-forward org-dblock-end-re nil t)
12378 (> (match-end 0) pos))
12379 (goto-char beg)
12380 (goto-char pos)
12381 (error "Not in a dynamic block"))))
12383 (defun org-update-all-dblocks ()
12384 "Update all dynamic blocks in the buffer.
12385 This function can be used in a hook."
12386 (interactive)
12387 (when (derived-mode-p 'org-mode)
12388 (org-map-dblocks 'org-update-dblock)))
12391 ;;;; Completion
12393 (declare-function org-export-backend-options "ox" (cl-x) t)
12394 (defun org-get-export-keywords ()
12395 "Return a list of all currently understood export keywords.
12396 Export keywords include options, block names, attributes and
12397 keywords relative to each registered export back-end."
12398 (let (keywords)
12399 (dolist (backend
12400 (bound-and-true-p org-export-registered-backends)
12401 (delq nil keywords))
12402 ;; Back-end name (for keywords, like #+LATEX:)
12403 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12404 (dolist (option-entry (org-export-backend-options backend))
12405 ;; Back-end options.
12406 (push (nth 1 option-entry) keywords)))))
12408 (defconst org-options-keywords
12409 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12410 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12411 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12412 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12413 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12415 (defcustom org-structure-template-alist
12416 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12417 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12418 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12419 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12420 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12421 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12422 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12423 ("L" "#+LaTeX: ")
12424 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12425 ("H" "#+HTML: ")
12426 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12427 ("A" "#+ASCII: ")
12428 ("i" "#+INDEX: ?")
12429 ("I" "#+INCLUDE: %file ?"))
12430 "Structure completion elements.
12431 This is a list of abbreviation keys and values. The value gets inserted
12432 if you type `<' followed by the key and then press the completion key,
12433 usually `TAB'. %file will be replaced by a file name after prompting
12434 for the file using completion. The cursor will be placed at the position
12435 of the `?' in the template.
12436 There are two templates for each key, the first uses the original Org syntax,
12437 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12438 the default when the /org-mtags.el/ module has been loaded. See also the
12439 variable `org-mtags-prefer-muse-templates'."
12440 :group 'org-completion
12441 :type '(repeat
12442 (list
12443 (string :tag "Key")
12444 (string :tag "Template")))
12445 :version "25.1"
12446 :package-version '(Org . "8.3"))
12448 (defun org-try-structure-completion ()
12449 "Try to complete a structure template before point.
12450 This looks for strings like \"<e\" on an otherwise empty line and
12451 expands them."
12452 (let ((l (buffer-substring (point-at-bol) (point)))
12454 (when (and (looking-at "[ \t]*$")
12455 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12456 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12457 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12458 (match-beginning 1)) a)
12459 t)))
12461 (defun org-complete-expand-structure-template (start cell)
12462 "Expand a structure template."
12463 (let ((rpl (nth 1 cell))
12464 (ind ""))
12465 (delete-region start (point))
12466 (when (string-match "\\`[ \t]*#\\+" rpl)
12467 (cond
12468 ((bolp))
12469 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12470 (setq ind (buffer-substring (point-at-bol) (point))))
12471 (t (newline))))
12472 (setq start (point))
12473 (when (string-match "%file" rpl)
12474 (setq rpl (replace-match
12475 (concat
12476 "\""
12477 (save-match-data
12478 (abbreviate-file-name (read-file-name "Include file: ")))
12479 "\"")
12480 t t rpl)))
12481 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12482 (concat "\n" ind)))
12483 (insert rpl)
12484 (when (re-search-backward "\\?" start t) (delete-char 1))))
12486 ;;;; TODO, DEADLINE, Comments
12488 (defun org-toggle-comment ()
12489 "Change the COMMENT state of an entry."
12490 (interactive)
12491 (save-excursion
12492 (org-back-to-heading)
12493 (looking-at org-complex-heading-regexp)
12494 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12495 (skip-chars-forward " \t")
12496 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12497 (if (org-in-commented-heading-p t)
12498 (delete-region (point)
12499 (progn (search-forward " " (line-end-position) 'move)
12500 (skip-chars-forward " \t")
12501 (point)))
12502 (insert org-comment-string)
12503 (unless (eolp) (insert " ")))))
12505 (defvar org-last-todo-state-is-todo nil
12506 "This is non-nil when the last TODO state change led to a TODO state.
12507 If the last change removed the TODO tag or switched to DONE, then
12508 this is nil.")
12510 (defvar org-setting-tags nil) ; dynamically skipped
12512 (defvar org-todo-setup-filter-hook nil
12513 "Hook for functions that pre-filter todo specs.
12514 Each function takes a todo spec and returns either nil or the spec
12515 transformed into canonical form." )
12517 (defvar org-todo-get-default-hook nil
12518 "Hook for functions that get a default item for todo.
12519 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12520 nil or a string to be used for the todo mark." )
12522 (defvar org-agenda-headline-snapshot-before-repeat)
12524 (defun org-current-effective-time ()
12525 "Return current time adjusted for `org-extend-today-until' variable."
12526 (let* ((ct (org-current-time))
12527 (dct (decode-time ct))
12528 (ct1
12529 (cond
12530 (org-use-last-clock-out-time-as-effective-time
12531 (or (org-clock-get-last-clock-out-time) ct))
12532 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12533 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12534 (t ct))))
12535 ct1))
12537 (defun org-todo-yesterday (&optional arg)
12538 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12539 (interactive "P")
12540 (if (eq major-mode 'org-agenda-mode)
12541 (apply 'org-agenda-todo-yesterday arg)
12542 (let* ((org-use-effective-time t)
12543 (hour (nth 2 (decode-time (org-current-time))))
12544 (org-extend-today-until (1+ hour)))
12545 (org-todo arg))))
12547 (defvar org-block-entry-blocking ""
12548 "First entry preventing the TODO state change.")
12550 (defun org-cancel-repeater ()
12551 "Cancel a repeater by setting its numeric value to zero."
12552 (interactive)
12553 (save-excursion
12554 (org-back-to-heading t)
12555 (let ((bound1 (point))
12556 (bound0 (save-excursion (outline-next-heading) (point))))
12557 (when (and (re-search-forward
12558 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12559 org-deadline-time-regexp "\\)\\|\\("
12560 org-ts-regexp "\\)")
12561 bound0 t)
12562 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12563 bound1 t))
12564 (replace-match "0" t nil nil 1)))))
12566 (defvar org-state) ;; dynamically scoped into this function
12567 (defun org-todo (&optional arg)
12568 "Change the TODO state of an item.
12569 The state of an item is given by a keyword at the start of the heading,
12570 like
12571 *** TODO Write paper
12572 *** DONE Call mom
12574 The different keywords are specified in the variable `org-todo-keywords'.
12575 By default the available states are \"TODO\" and \"DONE\".
12576 So for this example: when the item starts with TODO, it is changed to DONE.
12577 When it starts with DONE, the DONE is removed. And when neither TODO nor
12578 DONE are present, add TODO at the beginning of the heading.
12580 With \\[universal-argument] prefix arg, use completion to determine the new \
12581 state.
12582 With numeric prefix arg, switch to that state.
12583 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12584 keywords (nextset).
12585 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12586 With a numeric prefix arg of 0, inhibit note taking for the change.
12587 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12589 When called through ELisp, arg is also interpreted in the following way:
12590 `none' -> empty state
12591 \"\"(empty string) -> switch to empty state
12592 `done' -> switch to DONE
12593 `nextset' -> switch to the next set of keywords
12594 `previousset' -> switch to the previous set of keywords
12595 \"WAITING\" -> switch to the specified keyword, but only if it
12596 really is a member of `org-todo-keywords'."
12597 (interactive "P")
12598 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12599 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12600 'region-start-level 'region))
12601 org-loop-over-headlines-in-active-region)
12602 (org-map-entries
12603 `(org-todo ,arg)
12604 org-loop-over-headlines-in-active-region
12605 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12606 (when (equal arg '(16)) (setq arg 'nextset))
12607 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12608 (let ((org-blocker-hook org-blocker-hook)
12609 commentp
12610 case-fold-search)
12611 (when (equal arg '(64))
12612 (setq arg nil org-blocker-hook nil))
12613 (when (and org-blocker-hook
12614 (or org-inhibit-blocking
12615 (org-entry-get nil "NOBLOCKING")))
12616 (setq org-blocker-hook nil))
12617 (save-excursion
12618 (catch 'exit
12619 (org-back-to-heading t)
12620 (when (org-in-commented-heading-p t)
12621 (org-toggle-comment)
12622 (setq commentp t))
12623 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12624 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12625 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12626 (let* ((match-data (match-data))
12627 (startpos (point-at-bol))
12628 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12629 (org-log-done org-log-done)
12630 (org-log-repeat org-log-repeat)
12631 (org-todo-log-states org-todo-log-states)
12632 (org-inhibit-logging
12633 (if (equal arg 0)
12634 (progn (setq arg nil) 'note) org-inhibit-logging))
12635 (this (match-string 1))
12636 (hl-pos (match-beginning 0))
12637 (head (org-get-todo-sequence-head this))
12638 (ass (assoc head org-todo-kwd-alist))
12639 (interpret (nth 1 ass))
12640 (done-word (nth 3 ass))
12641 (final-done-word (nth 4 ass))
12642 (org-last-state (or this ""))
12643 (completion-ignore-case t)
12644 (member (member this org-todo-keywords-1))
12645 (tail (cdr member))
12646 (org-state (cond
12647 ((and org-todo-key-trigger
12648 (or (and (equal arg '(4))
12649 (eq org-use-fast-todo-selection 'prefix))
12650 (and (not arg) org-use-fast-todo-selection
12651 (not (eq org-use-fast-todo-selection
12652 'prefix)))))
12653 ;; Use fast selection
12654 (org-fast-todo-selection))
12655 ((and (equal arg '(4))
12656 (or (not org-use-fast-todo-selection)
12657 (not org-todo-key-trigger)))
12658 ;; Read a state with completion
12659 (completing-read
12660 "State: " (mapcar #'list org-todo-keywords-1)
12661 nil t))
12662 ((eq arg 'right)
12663 (if this
12664 (if tail (car tail) nil)
12665 (car org-todo-keywords-1)))
12666 ((eq arg 'left)
12667 (unless (equal member org-todo-keywords-1)
12668 (if this
12669 (nth (- (length org-todo-keywords-1)
12670 (length tail) 2)
12671 org-todo-keywords-1)
12672 (org-last org-todo-keywords-1))))
12673 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12674 (setq arg nil))) ; hack to fall back to cycling
12675 (arg
12676 ;; user or caller requests a specific state
12677 (cond
12678 ((equal arg "") nil)
12679 ((eq arg 'none) nil)
12680 ((eq arg 'done) (or done-word (car org-done-keywords)))
12681 ((eq arg 'nextset)
12682 (or (car (cdr (member head org-todo-heads)))
12683 (car org-todo-heads)))
12684 ((eq arg 'previousset)
12685 (let ((org-todo-heads (reverse org-todo-heads)))
12686 (or (car (cdr (member head org-todo-heads)))
12687 (car org-todo-heads))))
12688 ((car (member arg org-todo-keywords-1)))
12689 ((stringp arg)
12690 (user-error "State `%s' not valid in this file" arg))
12691 ((nth (1- (prefix-numeric-value arg))
12692 org-todo-keywords-1))))
12693 ((null member) (or head (car org-todo-keywords-1)))
12694 ((equal this final-done-word) nil) ;; -> make empty
12695 ((null tail) nil) ;; -> first entry
12696 ((memq interpret '(type priority))
12697 (if (eq this-command last-command)
12698 (car tail)
12699 (if (> (length tail) 0)
12700 (or done-word (car org-done-keywords))
12701 nil)))
12703 (car tail))))
12704 (org-state (or
12705 (run-hook-with-args-until-success
12706 'org-todo-get-default-hook org-state org-last-state)
12707 org-state))
12708 (next (if org-state (concat " " org-state " ") " "))
12709 (change-plist (list :type 'todo-state-change :from this :to org-state
12710 :position startpos))
12711 dolog now-done-p)
12712 (when org-blocker-hook
12713 (setq org-last-todo-state-is-todo
12714 (not (member this org-done-keywords)))
12715 (unless (save-excursion
12716 (save-match-data
12717 (org-with-wide-buffer
12718 (run-hook-with-args-until-failure
12719 'org-blocker-hook change-plist))))
12720 (if (called-interactively-p 'interactive)
12721 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12722 this org-state org-block-entry-blocking)
12723 ;; fail silently
12724 (message "TODO state change from %s to %s blocked (by \"%s\")"
12725 this org-state org-block-entry-blocking)
12726 (throw 'exit nil))))
12727 (store-match-data match-data)
12728 (replace-match next t t)
12729 (cond ((equal this org-state)
12730 (message "TODO state was already %s" (org-trim next)))
12731 ((pos-visible-in-window-p hl-pos)
12732 (message "TODO state changed to %s" (org-trim next))))
12733 (unless head
12734 (setq head (org-get-todo-sequence-head org-state)
12735 ass (assoc head org-todo-kwd-alist)
12736 interpret (nth 1 ass)
12737 done-word (nth 3 ass)
12738 final-done-word (nth 4 ass)))
12739 (when (memq arg '(nextset previousset))
12740 (message "Keyword-Set %d/%d: %s"
12741 (- (length org-todo-sets) -1
12742 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12743 (length org-todo-sets)
12744 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12745 (setq org-last-todo-state-is-todo
12746 (not (member org-state org-done-keywords)))
12747 (setq now-done-p (and (member org-state org-done-keywords)
12748 (not (member this org-done-keywords))))
12749 (and logging (org-local-logging logging))
12750 (when (and (or org-todo-log-states org-log-done)
12751 (not (eq org-inhibit-logging t))
12752 (not (memq arg '(nextset previousset))))
12753 ;; we need to look at recording a time and note
12754 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12755 (nth 2 (assoc this org-todo-log-states))))
12756 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12757 (setq dolog 'time))
12758 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12759 (and org-state
12760 (member org-state org-not-done-keywords)
12761 (not (member this org-not-done-keywords))))
12762 ;; This is now a todo state and was not one before
12763 ;; If there was a CLOSED time stamp, get rid of it.
12764 (org-add-planning-info nil nil 'closed))
12765 (when (and now-done-p org-log-done)
12766 ;; It is now done, and it was not done before
12767 (org-add-planning-info 'closed (org-current-effective-time))
12768 (when (and (not dolog) (eq 'note org-log-done))
12769 (org-add-log-setup 'done org-state this 'note)))
12770 (when (and org-state dolog)
12771 ;; This is a non-nil state, and we need to log it
12772 (org-add-log-setup 'state org-state this dolog)))
12773 ;; Fixup tag positioning
12774 (org-todo-trigger-tag-changes org-state)
12775 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12776 (when org-provide-todo-statistics
12777 (org-update-parent-todo-statistics))
12778 (run-hooks 'org-after-todo-state-change-hook)
12779 (when (and arg (not (member org-state org-done-keywords)))
12780 (setq head (org-get-todo-sequence-head org-state)))
12781 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12782 ;; Do we need to trigger a repeat?
12783 (when now-done-p
12784 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12785 ;; This is for the agenda, take a snapshot of the headline.
12786 (save-match-data
12787 (setq org-agenda-headline-snapshot-before-repeat
12788 (org-get-heading))))
12789 (org-auto-repeat-maybe org-state))
12790 ;; Fixup cursor location if close to the keyword
12791 (when (and (outline-on-heading-p)
12792 (not (bolp))
12793 (save-excursion (beginning-of-line 1)
12794 (looking-at org-todo-line-regexp))
12795 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12796 (goto-char (or (match-end 2) (match-end 1)))
12797 (and (looking-at " ") (just-one-space)))
12798 (when org-trigger-hook
12799 (save-excursion
12800 (run-hook-with-args 'org-trigger-hook change-plist)))
12801 (when commentp (org-toggle-comment))))))))
12803 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12804 "Block turning an entry into a TODO, using the hierarchy.
12805 This checks whether the current task should be blocked from state
12806 changes. Such blocking occurs when:
12808 1. The task has children which are not all in a completed state.
12810 2. A task has a parent with the property :ORDERED:, and there
12811 are siblings prior to the current task with incomplete
12812 status.
12814 3. The parent of the task is blocked because it has siblings that should
12815 be done first, or is child of a block grandparent TODO entry."
12817 (if (not org-enforce-todo-dependencies)
12818 t ; if locally turned off don't block
12819 (catch 'dont-block
12820 ;; If this is not a todo state change, or if this entry is already DONE,
12821 ;; do not block
12822 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12823 (member (plist-get change-plist :from)
12824 (cons 'done org-done-keywords))
12825 (member (plist-get change-plist :to)
12826 (cons 'todo org-not-done-keywords))
12827 (not (plist-get change-plist :to)))
12828 (throw 'dont-block t))
12829 ;; If this task has children, and any are undone, it's blocked
12830 (save-excursion
12831 (org-back-to-heading t)
12832 (let ((this-level (funcall outline-level)))
12833 (outline-next-heading)
12834 (let ((child-level (funcall outline-level)))
12835 (while (and (not (eobp))
12836 (> child-level this-level))
12837 ;; this todo has children, check whether they are all
12838 ;; completed
12839 (when (and (not (org-entry-is-done-p))
12840 (org-entry-is-todo-p))
12841 (setq org-block-entry-blocking (org-get-heading))
12842 (throw 'dont-block nil))
12843 (outline-next-heading)
12844 (setq child-level (funcall outline-level))))))
12845 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12846 ;; any previous siblings are undone, it's blocked
12847 (save-excursion
12848 (org-back-to-heading t)
12849 (let* ((pos (point))
12850 (parent-pos (and (org-up-heading-safe) (point))))
12851 (unless parent-pos (throw 'dont-block t)) ; no parent
12852 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12853 (forward-line 1)
12854 (re-search-forward org-not-done-heading-regexp pos t))
12855 (setq org-block-entry-blocking (match-string 0))
12856 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12857 ;; Search further up the hierarchy, to see if an ancestor is blocked
12858 (while t
12859 (goto-char parent-pos)
12860 (unless (looking-at org-not-done-heading-regexp)
12861 (throw 'dont-block t)) ; do not block, parent is not a TODO
12862 (setq pos (point))
12863 (setq parent-pos (and (org-up-heading-safe) (point)))
12864 (unless parent-pos (throw 'dont-block t)) ; no parent
12865 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12866 (forward-line 1)
12867 (re-search-forward org-not-done-heading-regexp pos t)
12868 (setq org-block-entry-blocking (org-get-heading)))
12869 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12871 (defcustom org-track-ordered-property-with-tag nil
12872 "Should the ORDERED property also be shown as a tag?
12873 The ORDERED property decides if an entry should require subtasks to be
12874 completed in sequence. Since a property is not very visible, setting
12875 this option means that toggling the ORDERED property with the command
12876 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12877 not relevant for the behavior, but it makes things more visible.
12879 Note that toggling the tag with tags commands will not change the property
12880 and therefore not influence behavior!
12882 This can be t, meaning the tag ORDERED should be used, It can also be a
12883 string to select a different tag for this task."
12884 :group 'org-todo
12885 :type '(choice
12886 (const :tag "No tracking" nil)
12887 (const :tag "Track with ORDERED tag" t)
12888 (string :tag "Use other tag")))
12890 (defun org-toggle-ordered-property ()
12891 "Toggle the ORDERED property of the current entry.
12892 For better visibility, you can track the value of this property with a tag.
12893 See variable `org-track-ordered-property-with-tag'."
12894 (interactive)
12895 (let* ((t1 org-track-ordered-property-with-tag)
12896 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12897 (save-excursion
12898 (org-back-to-heading)
12899 (if (org-entry-get nil "ORDERED")
12900 (progn
12901 (org-delete-property "ORDERED")
12902 (and tag (org-toggle-tag tag 'off))
12903 (message "Subtasks can be completed in arbitrary order"))
12904 (org-entry-put nil "ORDERED" "t")
12905 (and tag (org-toggle-tag tag 'on))
12906 (message "Subtasks must be completed in sequence")))))
12908 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12909 (defun org-block-todo-from-checkboxes (change-plist)
12910 "Block turning an entry into a TODO, using checkboxes.
12911 This checks whether the current task should be blocked from state
12912 changes because there are unchecked boxes in this entry."
12913 (if (not org-enforce-todo-checkbox-dependencies)
12914 t ; if locally turned off don't block
12915 (catch 'dont-block
12916 ;; If this is not a todo state change, or if this entry is already DONE,
12917 ;; do not block
12918 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12919 (member (plist-get change-plist :from)
12920 (cons 'done org-done-keywords))
12921 (member (plist-get change-plist :to)
12922 (cons 'todo org-not-done-keywords))
12923 (not (plist-get change-plist :to)))
12924 (throw 'dont-block t))
12925 ;; If this task has checkboxes that are not checked, it's blocked
12926 (save-excursion
12927 (org-back-to-heading t)
12928 (let ((beg (point)) end)
12929 (outline-next-heading)
12930 (setq end (point))
12931 (goto-char beg)
12932 (when (org-list-search-forward
12933 (concat (org-item-beginning-re)
12934 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12935 "\\[[- ]\\]")
12936 end t)
12937 (when (boundp 'org-blocked-by-checkboxes)
12938 (setq org-blocked-by-checkboxes t))
12939 (throw 'dont-block nil))))
12940 t))) ; do not block
12942 (defun org-entry-blocked-p ()
12943 "Non-nil if entry at point is blocked."
12944 (and (not (org-entry-get nil "NOBLOCKING"))
12945 (member (org-entry-get nil "TODO") org-not-done-keywords)
12946 (not (run-hook-with-args-until-failure
12947 'org-blocker-hook
12948 (list :type 'todo-state-change
12949 :position (point)
12950 :from 'todo
12951 :to 'done)))))
12953 (defun org-update-statistics-cookies (all)
12954 "Update the statistics cookie, either from TODO or from checkboxes.
12955 This should be called with the cursor in a line with a statistics cookie."
12956 (interactive "P")
12957 (if all
12958 (progn
12959 (org-update-checkbox-count 'all)
12960 (org-map-entries 'org-update-parent-todo-statistics))
12961 (if (not (org-at-heading-p))
12962 (org-update-checkbox-count)
12963 (let ((pos (point-marker))
12964 end l1 l2)
12965 (ignore-errors (org-back-to-heading t))
12966 (if (not (org-at-heading-p))
12967 (org-update-checkbox-count)
12968 (setq l1 (org-outline-level))
12969 (setq end (save-excursion
12970 (outline-next-heading)
12971 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12972 (point)))
12973 (if (and (save-excursion
12974 (re-search-forward
12975 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12976 (not (save-excursion (re-search-forward
12977 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12978 (org-update-checkbox-count)
12979 (if (and l2 (> l2 l1))
12980 (progn
12981 (goto-char end)
12982 (org-update-parent-todo-statistics))
12983 (goto-char pos)
12984 (beginning-of-line 1)
12985 (while (re-search-forward
12986 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12987 (point-at-eol) t)
12988 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12989 (goto-char pos)
12990 (move-marker pos nil)))))
12992 (defvar org-entry-property-inherited-from) ;; defined below
12993 (defun org-update-parent-todo-statistics ()
12994 "Update any statistics cookie in the parent of the current headline.
12995 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12996 the entire subtree and this will travel up the hierarchy and update
12997 statistics everywhere."
12998 (let* ((prop (save-excursion (org-up-heading-safe)
12999 (org-entry-get nil "COOKIE_DATA" 'inherit)))
13000 (recursive (or (not org-hierarchical-todo-statistics)
13001 (and prop (string-match "\\<recursive\\>" prop))))
13002 (lim (or (and prop (marker-position org-entry-property-inherited-from))
13004 (first t)
13005 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
13006 level ltoggle l1 new ndel
13007 (cnt-all 0) (cnt-done 0) is-percent kwd
13008 checkbox-beg cookie-present)
13009 (catch 'exit
13010 (save-excursion
13011 (beginning-of-line 1)
13012 (setq ltoggle (funcall outline-level))
13013 ;; Three situations are to consider:
13015 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
13016 ;; to the top-level ancestor on the headline;
13018 ;; 2. If parent has "recursive" property, repeat up to the
13019 ;; headline setting that property, taking inheritance into
13020 ;; account;
13022 ;; 3. Else, move up to direct parent and proceed only once.
13023 (while (and (setq level (org-up-heading-safe))
13024 (or recursive first)
13025 (>= (point) lim))
13026 (setq first nil cookie-present nil)
13027 (unless (and level
13028 (not (string-match
13029 "\\<checkbox\\>"
13030 (downcase (or (org-entry-get nil "COOKIE_DATA")
13031 "")))))
13032 (throw 'exit nil))
13033 (while (re-search-forward box-re (point-at-eol) t)
13034 (setq cnt-all 0 cnt-done 0 cookie-present t)
13035 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
13036 (save-match-data
13037 (unless (outline-next-heading) (throw 'exit nil))
13038 (while (and (looking-at org-complex-heading-regexp)
13039 (> (setq l1 (length (match-string 1))) level))
13040 (setq kwd (and (or recursive (= l1 ltoggle))
13041 (match-string 2)))
13042 (if (or (eq org-provide-todo-statistics 'all-headlines)
13043 (and (eq org-provide-todo-statistics t)
13044 (or (member kwd org-done-keywords)))
13045 (and (listp org-provide-todo-statistics)
13046 (stringp (car org-provide-todo-statistics))
13047 (or (member kwd org-provide-todo-statistics)
13048 (member kwd org-done-keywords)))
13049 (and (listp org-provide-todo-statistics)
13050 (listp (car org-provide-todo-statistics))
13051 (or (member kwd (car org-provide-todo-statistics))
13052 (and (member kwd org-done-keywords)
13053 (member kwd (cadr org-provide-todo-statistics))))))
13054 (setq cnt-all (1+ cnt-all))
13055 (and (eq org-provide-todo-statistics t)
13057 (setq cnt-all (1+ cnt-all))))
13058 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13059 (member kwd org-done-keywords))
13060 (and (listp org-provide-todo-statistics)
13061 (listp (car org-provide-todo-statistics))
13062 (member kwd org-done-keywords)
13063 (member kwd (cadr org-provide-todo-statistics)))
13064 (and (listp org-provide-todo-statistics)
13065 (stringp (car org-provide-todo-statistics))
13066 (member kwd org-done-keywords)))
13067 (setq cnt-done (1+ cnt-done)))
13068 (outline-next-heading)))
13069 (setq new
13070 (if is-percent
13071 (format "[%d%%]" (floor (* 100.0 cnt-done)
13072 (max 1 cnt-all)))
13073 (format "[%d/%d]" cnt-done cnt-all))
13074 ndel (- (match-end 0) checkbox-beg))
13075 (goto-char checkbox-beg)
13076 (insert new)
13077 (delete-region (point) (+ (point) ndel))
13078 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13079 (when cookie-present
13080 (run-hook-with-args 'org-after-todo-statistics-hook
13081 cnt-done (- cnt-all cnt-done))))))
13082 (run-hooks 'org-todo-statistics-hook)))
13084 (defvar org-after-todo-statistics-hook nil
13085 "Hook that is called after a TODO statistics cookie has been updated.
13086 Each function is called with two arguments: the number of not-done entries
13087 and the number of done entries.
13089 For example, the following function, when added to this hook, will switch
13090 an entry to DONE when all children are done, and back to TODO when new
13091 entries are set to a TODO status. Note that this hook is only called
13092 when there is a statistics cookie in the headline!
13094 \(defun org-summary-todo (n-done n-not-done)
13095 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13096 \(let (org-log-done org-log-states) ; turn off logging
13097 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13100 (defvar org-todo-statistics-hook nil
13101 "Hook that is run whenever Org thinks TODO statistics should be updated.
13102 This hook runs even if there is no statistics cookie present, in which case
13103 `org-after-todo-statistics-hook' would not run.")
13105 (defun org-todo-trigger-tag-changes (state)
13106 "Apply the changes defined in `org-todo-state-tags-triggers'."
13107 (let ((l org-todo-state-tags-triggers)
13108 changes)
13109 (when (or (not state) (equal state ""))
13110 (setq changes (append changes (cdr (assoc "" l)))))
13111 (when (and (stringp state) (> (length state) 0))
13112 (setq changes (append changes (cdr (assoc state l)))))
13113 (when (member state org-not-done-keywords)
13114 (setq changes (append changes (cdr (assoc 'todo l)))))
13115 (when (member state org-done-keywords)
13116 (setq changes (append changes (cdr (assoc 'done l)))))
13117 (dolist (c changes)
13118 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13120 (defun org-local-logging (value)
13121 "Get logging settings from a property VALUE."
13122 ;; Directly set the variables, they are already local.
13123 (setq org-log-done nil
13124 org-log-repeat nil
13125 org-todo-log-states nil)
13126 (dolist (w (org-split-string value))
13127 (let (a)
13128 (cond
13129 ((setq a (assoc w org-startup-options))
13130 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13131 (set (nth 1 a) (nth 2 a))))
13132 ((setq a (org-extract-log-state-settings w))
13133 (and (member (car a) org-todo-keywords-1)
13134 (push a org-todo-log-states)))))))
13136 (defun org-get-todo-sequence-head (kwd)
13137 "Return the head of the TODO sequence to which KWD belongs.
13138 If KWD is not set, check if there is a text property remembering the
13139 right sequence."
13140 (let (p)
13141 (cond
13142 ((not kwd)
13143 (or (get-text-property (point-at-bol) 'org-todo-head)
13144 (progn
13145 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13146 nil (point-at-eol)))
13147 (get-text-property p 'org-todo-head))))
13148 ((not (member kwd org-todo-keywords-1))
13149 (car org-todo-keywords-1))
13150 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13152 (defun org-fast-todo-selection ()
13153 "Fast TODO keyword selection with single keys.
13154 Returns the new TODO keyword, or nil if no state change should occur."
13155 (let* ((fulltable org-todo-key-alist)
13156 (done-keywords org-done-keywords) ;; needed for the faces.
13157 (maxlen (apply 'max (mapcar
13158 (lambda (x)
13159 (if (stringp (car x)) (string-width (car x)) 0))
13160 fulltable)))
13161 (expert nil)
13162 (fwidth (+ maxlen 3 1 3))
13163 (ncol (/ (- (window-width) 4) fwidth))
13164 tg cnt e c tbl
13165 groups ingroup)
13166 (save-excursion
13167 (save-window-excursion
13168 (if expert
13169 (set-buffer (get-buffer-create " *Org todo*"))
13170 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13171 (erase-buffer)
13172 (setq-local org-done-keywords done-keywords)
13173 (setq tbl fulltable cnt 0)
13174 (while (setq e (pop tbl))
13175 (cond
13176 ((equal e '(:startgroup))
13177 (push '() groups) (setq ingroup t)
13178 (unless (= cnt 0)
13179 (setq cnt 0)
13180 (insert "\n"))
13181 (insert "{ "))
13182 ((equal e '(:endgroup))
13183 (setq ingroup nil cnt 0)
13184 (insert "}\n"))
13185 ((equal e '(:newline))
13186 (unless (= cnt 0)
13187 (setq cnt 0)
13188 (insert "\n")
13189 (setq e (car tbl))
13190 (while (equal (car tbl) '(:newline))
13191 (insert "\n")
13192 (setq tbl (cdr tbl)))))
13194 (setq tg (car e) c (cdr e))
13195 (when ingroup (push tg (car groups)))
13196 (setq tg (org-add-props tg nil 'face
13197 (org-get-todo-face tg)))
13198 (when (and (= cnt 0) (not ingroup)) (insert " "))
13199 (insert "[" c "] " tg (make-string
13200 (- fwidth 4 (length tg)) ?\ ))
13201 (when (= (setq cnt (1+ cnt)) ncol)
13202 (insert "\n")
13203 (when ingroup (insert " "))
13204 (setq cnt 0)))))
13205 (insert "\n")
13206 (goto-char (point-min))
13207 (unless expert (org-fit-window-to-buffer))
13208 (message "[a-z..]:Set [SPC]:clear")
13209 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13210 (cond
13211 ((or (= c ?\C-g)
13212 (and (= c ?q) (not (rassoc c fulltable))))
13213 (setq quit-flag t))
13214 ((= c ?\ ) nil)
13215 ((setq e (rassoc c fulltable) tg (car e))
13217 (t (setq quit-flag t)))))))
13219 (defun org-entry-is-todo-p ()
13220 (member (org-get-todo-state) org-not-done-keywords))
13222 (defun org-entry-is-done-p ()
13223 (member (org-get-todo-state) org-done-keywords))
13225 (defun org-get-todo-state ()
13226 "Return the TODO keyword of the current subtree."
13227 (save-excursion
13228 (org-back-to-heading t)
13229 (and (looking-at org-todo-line-regexp)
13230 (match-end 2)
13231 (match-string 2))))
13233 (defun org-at-date-range-p (&optional inactive-ok)
13234 "Non-nil if point is inside a date range.
13236 When optional argument INACTIVE-OK is non-nil, also consider
13237 inactive time ranges.
13239 When this function returns a non-nil value, match data is set
13240 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13241 on INACTIVE-OK."
13242 (interactive)
13243 (save-excursion
13244 (catch 'exit
13245 (let ((pos (point)))
13246 (skip-chars-backward "^[<\r\n")
13247 (skip-chars-backward "<[")
13248 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13249 (>= (match-end 0) pos)
13250 (throw 'exit t))
13251 (skip-chars-backward "^<[\r\n")
13252 (skip-chars-backward "<[")
13253 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13254 (>= (match-end 0) pos)
13255 (throw 'exit t)))
13256 nil)))
13258 (defun org-get-repeat (&optional tagline)
13259 "Check if there is a deadline/schedule with repeater in this entry."
13260 (save-match-data
13261 (save-excursion
13262 (org-back-to-heading t)
13263 (and (re-search-forward (if tagline
13264 (concat tagline "\\s-*" org-repeat-re)
13265 org-repeat-re)
13266 (org-entry-end-position) t)
13267 (match-string-no-properties 1)))))
13269 (defvar org-last-changed-timestamp)
13270 (defvar org-last-inserted-timestamp)
13271 (defvar org-log-post-message)
13272 (defvar org-log-note-purpose)
13273 (defvar org-log-note-how nil)
13274 (defvar org-log-note-extra)
13275 (defun org-auto-repeat-maybe (done-word)
13276 "Check if the current headline contains a repeated time-stamp.
13278 If yes, set TODO state back to what it was and change the base date
13279 of repeating deadline/scheduled time stamps to new date.
13281 This function is run automatically after each state change to a DONE state."
13282 (let* ((repeat (org-get-repeat))
13283 (aa (assoc org-last-state org-todo-kwd-alist))
13284 (interpret (nth 1 aa))
13285 (head (nth 2 aa))
13286 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13287 (msg "Entry repeats: ")
13288 (org-log-done nil)
13289 (org-todo-log-states nil))
13290 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13291 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13292 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13293 org-todo-repeat-to-state)))
13294 (unless (and to-state (member to-state org-todo-keywords-1))
13295 (setq to-state (if (eq interpret 'type) org-last-state head)))
13296 (org-todo to-state))
13297 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13298 (org-entry-put nil "LAST_REPEAT" (format-time-string
13299 (org-time-stamp-format t t))))
13300 (when org-log-repeat
13301 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13302 (memq 'org-add-log-note post-command-hook))
13303 ;; We are already setup for some record.
13304 (when (eq org-log-repeat 'note)
13305 ;; Make sure we take a note, not only a time stamp.
13306 (setq org-log-note-how 'note))
13307 ;; Set up for taking a record.
13308 (org-add-log-setup 'state
13309 (or done-word (car org-done-keywords))
13310 org-last-state
13311 org-log-repeat)))
13312 (org-back-to-heading t)
13313 (org-add-planning-info nil nil 'closed)
13314 (let ((end (save-excursion (outline-next-heading) (point))))
13315 (while (re-search-forward org-ts-regexp end t)
13316 (when (save-match-data
13317 (or (org-at-planning-p)
13318 (org-at-property-p)
13319 (eq (org-element-type (save-excursion
13320 (backward-char)
13321 (org-element-context)))
13322 'timestamp)))
13323 (let ((type (cond ((match-end 1) org-scheduled-string)
13324 ((match-end 3) org-deadline-string)
13325 (t "Plain:")))
13326 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13327 (cond
13328 ((not
13329 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13330 ;; Time-stamps without a repeater are usually skipped.
13331 ;; However, a SCHEDULED time-stamp without one is
13332 ;; removed, as it is considered as no longer relevant.
13333 (when (equal type org-scheduled-string)
13334 (org-remove-timestamp-with-keyword type)))
13336 (let ((n (string-to-number (match-string 2 ts)))
13337 (what (match-string 3 ts)))
13338 (when (equal what "w") (setq n (* n 7) what "d"))
13339 (when (and (equal what "h")
13340 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13341 ts)))
13342 (user-error
13343 "Cannot repeat in Repeat in %d hour(s) because no hour \
13344 has been set"
13346 ;; Preparation, see if we need to modify the start
13347 ;; date for the change.
13348 (when (match-end 1)
13349 (let ((time (save-match-data (org-time-string-to-time ts))))
13350 (cond
13351 ((equal (match-string 1 ts) ".")
13352 ;; Shift starting date to today
13353 (org-timestamp-change
13354 (- (org-today) (time-to-days time))
13355 'day))
13356 ((equal (match-string 1 ts) "+")
13357 (let ((nshiftmax 10)
13358 (nshift 0))
13359 (while (or (= nshift 0)
13360 (not (time-less-p (current-time) time)))
13361 (when (= (cl-incf nshift) nshiftmax)
13362 (or (y-or-n-p
13363 (format "%d repeater intervals were not \
13364 enough to shift date past today. Continue? "
13365 nshift))
13366 (user-error "Abort")))
13367 (org-timestamp-change n (cdr (assoc what whata)))
13368 (org-at-timestamp-p t)
13369 (setq ts (match-string 1))
13370 (setq time
13371 (save-match-data
13372 (org-time-string-to-time ts)))))
13373 (org-timestamp-change (- n) (cdr (assoc what whata)))
13374 ;; Rematch, so that we have everything in
13375 ;; place for the real shift.
13376 (org-at-timestamp-p t)
13377 (setq ts (match-string 1))
13378 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13379 ts)))))
13380 (save-excursion
13381 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13382 (setq msg
13383 (concat
13384 msg type " " org-last-changed-timestamp " ")))))))))
13385 (setq org-log-post-message msg)
13386 (message "%s" msg))))
13388 (defun org-show-todo-tree (arg)
13389 "Make a compact tree which shows all headlines marked with TODO.
13390 The tree will show the lines where the regexp matches, and all higher
13391 headlines above the match.
13392 With a \\[universal-argument] prefix, prompt for a regexp to match.
13393 With a numeric prefix N, construct a sparse tree for the Nth element
13394 of `org-todo-keywords-1'."
13395 (interactive "P")
13396 (let ((case-fold-search nil)
13397 (kwd-re
13398 (cond ((null arg) org-not-done-regexp)
13399 ((equal arg '(4))
13400 (let ((kwd
13401 (completing-read "Keyword (or KWD1|KWD2|...): "
13402 (mapcar #'list org-todo-keywords-1))))
13403 (concat "\\("
13404 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13405 "\\)\\>")))
13406 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13407 (regexp-quote (nth (1- (prefix-numeric-value arg))
13408 org-todo-keywords-1)))
13409 (t (user-error "Invalid prefix argument: %s" arg)))))
13410 (message "%d TODO entries found"
13411 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13413 (defun org-deadline (arg &optional time)
13414 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13415 With one universal prefix argument, remove any deadline from the item.
13416 With two universal prefix arguments, prompt for a warning delay.
13417 With argument TIME, set the deadline at the corresponding date. TIME
13418 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13419 (interactive "P")
13420 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13421 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13422 'region-start-level 'region))
13423 org-loop-over-headlines-in-active-region)
13424 (org-map-entries
13425 `(org-deadline ',arg ,time)
13426 org-loop-over-headlines-in-active-region
13427 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13428 (let* ((old-date (org-entry-get nil "DEADLINE"))
13429 (old-date-time (when old-date (org-time-string-to-time old-date)))
13430 (repeater (and old-date
13431 (string-match
13432 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13433 old-date)
13434 (match-string 1 old-date))))
13435 (cond
13436 ((equal arg '(4))
13437 (when (and old-date org-log-redeadline)
13438 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13439 (org-remove-timestamp-with-keyword org-deadline-string)
13440 (message "Item no longer has a deadline."))
13441 ((equal arg '(16))
13442 (save-excursion
13443 (org-back-to-heading t)
13444 (if (re-search-forward
13445 org-deadline-time-regexp
13446 (save-excursion (outline-next-heading) (point)) t)
13447 (let* ((rpl0 (match-string 1))
13448 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13449 (replace-match
13450 (concat org-deadline-string
13451 " <" rpl
13452 (format " -%dd"
13453 (abs
13454 (- (time-to-days
13455 (save-match-data
13456 (org-read-date nil t nil "Warn starting from" old-date-time)))
13457 (time-to-days old-date-time))))
13458 ">") t t))
13459 (user-error "No deadline information to update"))))
13461 (org-add-planning-info 'deadline time 'closed)
13462 (when (and old-date
13463 org-log-redeadline
13464 (not (equal old-date org-last-inserted-timestamp)))
13465 (org-add-log-setup
13466 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13467 (when repeater
13468 (save-excursion
13469 (org-back-to-heading t)
13470 (when (re-search-forward (concat org-deadline-string " "
13471 org-last-inserted-timestamp)
13472 (save-excursion
13473 (outline-next-heading) (point)) t)
13474 (goto-char (1- (match-end 0)))
13475 (insert " " repeater)
13476 (setq org-last-inserted-timestamp
13477 (concat (substring org-last-inserted-timestamp 0 -1)
13478 " " repeater
13479 (substring org-last-inserted-timestamp -1))))))
13480 (message "Deadline on %s" org-last-inserted-timestamp))))))
13482 (defun org-schedule (arg &optional time)
13483 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13484 With one universal prefix argument, remove any scheduling date from the item.
13485 With two universal prefix arguments, prompt for a delay cookie.
13486 With argument TIME, scheduled at the corresponding date. TIME can
13487 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13488 (interactive "P")
13489 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13490 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13491 'region-start-level 'region))
13492 org-loop-over-headlines-in-active-region)
13493 (org-map-entries
13494 `(org-schedule ',arg ,time)
13495 org-loop-over-headlines-in-active-region
13496 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13497 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13498 (old-date-time (when old-date (org-time-string-to-time old-date)))
13499 (repeater (and old-date
13500 (string-match
13501 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13502 old-date)
13503 (match-string 1 old-date))))
13504 (cond
13505 ((equal arg '(4))
13506 (progn
13507 (when (and old-date org-log-reschedule)
13508 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13509 (org-remove-timestamp-with-keyword org-scheduled-string)
13510 (message "Item is no longer scheduled.")))
13511 ((equal arg '(16))
13512 (save-excursion
13513 (org-back-to-heading t)
13514 (if (re-search-forward
13515 org-scheduled-time-regexp
13516 (save-excursion (outline-next-heading) (point)) t)
13517 (let* ((rpl0 (match-string 1))
13518 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13519 (replace-match
13520 (concat org-scheduled-string
13521 " <" rpl
13522 (format " -%dd"
13523 (abs
13524 (- (time-to-days
13525 (save-match-data
13526 (org-read-date nil t nil "Delay until" old-date-time)))
13527 (time-to-days old-date-time))))
13528 ">") t t))
13529 (user-error "No scheduled information to update"))))
13531 (org-add-planning-info 'scheduled time 'closed)
13532 (when (and old-date
13533 org-log-reschedule
13534 (not (equal old-date org-last-inserted-timestamp)))
13535 (org-add-log-setup
13536 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13537 (when repeater
13538 (save-excursion
13539 (org-back-to-heading t)
13540 (when (re-search-forward (concat org-scheduled-string " "
13541 org-last-inserted-timestamp)
13542 (save-excursion
13543 (outline-next-heading) (point)) t)
13544 (goto-char (1- (match-end 0)))
13545 (insert " " repeater)
13546 (setq org-last-inserted-timestamp
13547 (concat (substring org-last-inserted-timestamp 0 -1)
13548 " " repeater
13549 (substring org-last-inserted-timestamp -1))))))
13550 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13552 (defun org-get-scheduled-time (pom &optional inherit)
13553 "Get the scheduled time as a time tuple, of a format suitable
13554 for calling org-schedule with, or if there is no scheduling,
13555 returns nil."
13556 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13557 (when time
13558 (apply 'encode-time (org-parse-time-string time)))))
13560 (defun org-get-deadline-time (pom &optional inherit)
13561 "Get the deadline as a time tuple, of a format suitable for
13562 calling org-deadline with, or if there is no scheduling, returns
13563 nil."
13564 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13565 (when time
13566 (apply 'encode-time (org-parse-time-string time)))))
13568 (defun org-remove-timestamp-with-keyword (keyword)
13569 "Remove all time stamps with KEYWORD in the current entry."
13570 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13571 beg)
13572 (save-excursion
13573 (org-back-to-heading t)
13574 (setq beg (point))
13575 (outline-next-heading)
13576 (while (re-search-backward re beg t)
13577 (replace-match "")
13578 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13579 (equal (char-before) ?\ ))
13580 (backward-delete-char 1)
13581 (when (string-match "^[ \t]*$" (buffer-substring
13582 (point-at-bol) (point-at-eol)))
13583 (delete-region (point-at-bol)
13584 (min (point-max) (1+ (point-at-eol))))))))))
13586 (defvar org-time-was-given) ; dynamically scoped parameter
13587 (defvar org-end-time-was-given) ; dynamically scoped parameter
13589 (defun org-at-planning-p ()
13590 "Non-nil when point is on a planning info line."
13591 ;; This is as accurate and faster than `org-element-at-point' since
13592 ;; planning info location is fixed in the section.
13593 (org-with-wide-buffer
13594 (beginning-of-line)
13595 (and (looking-at-p org-planning-line-re)
13596 (eq (point)
13597 (ignore-errors
13598 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13599 (org-back-to-heading t)
13600 (org-with-limited-levels (org-back-to-heading t)))
13601 (line-beginning-position 2))))))
13603 (defun org-add-planning-info (what &optional time &rest remove)
13604 "Insert new timestamp with keyword in the planning line.
13605 WHAT indicates what kind of time stamp to add. It is a symbol
13606 among `closed', `deadline', `scheduled' and nil. TIME indicates
13607 the time to use. If none is given, the user is prompted for
13608 a date. REMOVE indicates what kind of entries to remove. An old
13609 WHAT entry will also be removed."
13610 (let (org-time-was-given org-end-time-was-given default-time default-input)
13611 (catch 'exit
13612 (when (and (memq what '(scheduled deadline))
13613 (or (not time)
13614 (and (stringp time)
13615 (string-match "^[-+]+[0-9]" time))))
13616 ;; Try to get a default date/time from existing timestamp
13617 (save-excursion
13618 (org-back-to-heading t)
13619 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13620 (when (re-search-forward (if (eq what 'scheduled)
13621 org-scheduled-time-regexp
13622 org-deadline-time-regexp)
13623 end t)
13624 (setq ts (match-string 1)
13625 default-time (apply 'encode-time (org-parse-time-string ts))
13626 default-input (and ts (org-get-compact-tod ts)))))))
13627 (when what
13628 (setq time
13629 (if (stringp time)
13630 ;; This is a string (relative or absolute), set
13631 ;; proper date.
13632 (apply #'encode-time
13633 (org-read-date-analyze
13634 time default-time (decode-time default-time)))
13635 ;; If necessary, get the time from the user
13636 (or time (org-read-date nil 'to-time nil nil
13637 default-time default-input)))))
13639 (org-with-wide-buffer
13640 (org-back-to-heading t)
13641 (forward-line)
13642 (unless (bolp) (insert "\n"))
13643 (cond ((looking-at-p org-planning-line-re)
13644 ;; Move to current indentation.
13645 (skip-chars-forward " \t")
13646 ;; Check if we have to remove something.
13647 (dolist (type (if what (cons what remove) remove))
13648 (save-excursion
13649 (when (re-search-forward
13650 (cl-case type
13651 (closed org-closed-time-regexp)
13652 (deadline org-deadline-time-regexp)
13653 (scheduled org-scheduled-time-regexp)
13654 (otherwise
13655 (error "Invalid planning type: %s" type)))
13656 (line-end-position) t)
13657 ;; Delete until next keyword or end of line.
13658 (delete-region
13659 (match-beginning 0)
13660 (if (re-search-forward org-keyword-time-not-clock-regexp
13661 (line-end-position)
13663 (match-beginning 0)
13664 (line-end-position))))))
13665 ;; If there is nothing more to add and no more keyword
13666 ;; is left, remove the line completely.
13667 (if (and (looking-at-p "[ \t]*$") (not what))
13668 (delete-region (line-beginning-position)
13669 (line-beginning-position 2))
13670 ;; If we removed last keyword, do not leave trailing
13671 ;; white space at the end of line.
13672 (let ((p (point)))
13673 (save-excursion
13674 (end-of-line)
13675 (unless (= (skip-chars-backward " \t" p) 0)
13676 (delete-region (point) (line-end-position)))))))
13677 ((not what) (throw 'exit nil)) ; Nothing to do.
13678 (t (insert-before-markers "\n")
13679 (backward-char 1)
13680 (when org-adapt-indentation
13681 (indent-to-column (1+ (org-outline-level))))))
13682 (when what
13683 ;; Insert planning keyword.
13684 (insert (cl-case what
13685 (closed org-closed-string)
13686 (deadline org-deadline-string)
13687 (scheduled org-scheduled-string)
13688 (otherwise (error "Invalid planning type: %s" what)))
13689 " ")
13690 ;; Insert associated timestamp.
13691 (let ((ts (org-insert-time-stamp
13692 time
13693 (or org-time-was-given
13694 (and (eq what 'closed) org-log-done-with-time))
13695 (eq what 'closed)
13696 nil nil (list org-end-time-was-given))))
13697 (unless (eolp) (insert " "))
13698 ts))))))
13700 (defvar org-log-note-marker (make-marker)
13701 "Marker pointing at the entry where the note is to be inserted.")
13702 (defvar org-log-note-purpose nil)
13703 (defvar org-log-note-state nil)
13704 (defvar org-log-note-previous-state nil)
13705 (defvar org-log-note-extra nil)
13706 (defvar org-log-note-window-configuration nil)
13707 (defvar org-log-note-return-to (make-marker))
13708 (defvar org-log-note-effective-time nil
13709 "Remembered current time so that dynamically scoped
13710 `org-extend-today-until' affects timestamps in state change log")
13712 (defvar org-log-post-message nil
13713 "Message to be displayed after a log note has been stored.
13714 The auto-repeater uses this.")
13716 (defun org-add-note ()
13717 "Add a note to the current entry.
13718 This is done in the same way as adding a state change note."
13719 (interactive)
13720 (org-add-log-setup 'note))
13722 (defun org-log-beginning (&optional create)
13723 "Return expected start of log notes in current entry.
13724 When optional argument CREATE is non-nil, the function creates
13725 a drawer to store notes, if necessary. Returned position ignores
13726 narrowing."
13727 (org-with-wide-buffer
13728 (let ((drawer (org-log-into-drawer)))
13729 (cond
13730 (drawer
13731 (org-end-of-meta-data)
13732 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13733 (end (if (org-at-heading-p) (point)
13734 (save-excursion (outline-next-heading) (point))))
13735 (case-fold-search t))
13736 (catch 'exit
13737 ;; Try to find existing drawer.
13738 (while (re-search-forward regexp end t)
13739 (let ((element (org-element-at-point)))
13740 (when (eq (org-element-type element) 'drawer)
13741 (let ((cend (org-element-property :contents-end element)))
13742 (when (and (not org-log-states-order-reversed) cend)
13743 (goto-char cend)))
13744 (throw 'exit nil))))
13745 ;; No drawer found. Create one, if permitted.
13746 (when create
13747 (unless (bolp) (insert "\n"))
13748 (let ((beg (point)))
13749 (insert ":" drawer ":\n:END:\n")
13750 (org-indent-region beg (point)))
13751 (end-of-line -1)))))
13753 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13754 (skip-chars-forward " \t\n")
13755 (beginning-of-line)
13756 (unless org-log-states-order-reversed
13757 (org-skip-over-state-notes)
13758 (skip-chars-backward " \t\n")
13759 (forward-line)))))
13760 (if (bolp) (point) (line-beginning-position 2))))
13762 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13763 "Set up the post command hook to take a note.
13764 If this is about to TODO state change, the new state is expected in STATE.
13765 HOW is an indicator what kind of note should be created.
13766 EXTRA is additional text that will be inserted into the notes buffer."
13767 (move-marker org-log-note-marker (point))
13768 (setq org-log-note-purpose purpose
13769 org-log-note-state state
13770 org-log-note-previous-state prev-state
13771 org-log-note-how how
13772 org-log-note-extra extra
13773 org-log-note-effective-time (org-current-effective-time))
13774 (add-hook 'post-command-hook 'org-add-log-note 'append))
13776 (defun org-skip-over-state-notes ()
13777 "Skip past the list of State notes in an entry."
13778 (when (ignore-errors (goto-char (org-in-item-p)))
13779 (let* ((struct (org-list-struct))
13780 (prevs (org-list-prevs-alist struct))
13781 (regexp
13782 (concat "[ \t]*- +"
13783 (replace-regexp-in-string
13784 " +" " +"
13785 (org-replace-escapes
13786 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13787 `(("%d" . ,org-ts-regexp-inactive)
13788 ("%D" . ,org-ts-regexp)
13789 ("%s" . "\"\\S-+\"")
13790 ("%S" . "\"\\S-+\"")
13791 ("%t" . ,org-ts-regexp-inactive)
13792 ("%T" . ,org-ts-regexp)
13793 ("%u" . ".*?")
13794 ("%U" . ".*?")))))))
13795 (while (looking-at-p regexp)
13796 (goto-char (or (org-list-get-next-item (point) struct prevs)
13797 (org-list-get-item-end (point) struct)))))))
13799 (defun org-add-log-note (&optional _purpose)
13800 "Pop up a window for taking a note, and add this note later."
13801 (remove-hook 'post-command-hook 'org-add-log-note)
13802 (setq org-log-note-window-configuration (current-window-configuration))
13803 (delete-other-windows)
13804 (move-marker org-log-note-return-to (point))
13805 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13806 (goto-char org-log-note-marker)
13807 (org-switch-to-buffer-other-window "*Org Note*")
13808 (erase-buffer)
13809 (if (memq org-log-note-how '(time state))
13810 (let (current-prefix-arg) (org-store-log-note))
13811 (let ((org-inhibit-startup t)) (org-mode))
13812 (insert (format "# Insert note for %s.
13813 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13814 (cond
13815 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13816 ((eq org-log-note-purpose 'done) "closed todo item")
13817 ((eq org-log-note-purpose 'state)
13818 (format "state change from \"%s\" to \"%s\""
13819 (or org-log-note-previous-state "")
13820 (or org-log-note-state "")))
13821 ((eq org-log-note-purpose 'reschedule)
13822 "rescheduling")
13823 ((eq org-log-note-purpose 'delschedule)
13824 "no longer scheduled")
13825 ((eq org-log-note-purpose 'redeadline)
13826 "changing deadline")
13827 ((eq org-log-note-purpose 'deldeadline)
13828 "removing deadline")
13829 ((eq org-log-note-purpose 'refile)
13830 "refiling")
13831 ((eq org-log-note-purpose 'note)
13832 "this entry")
13833 (t (error "This should not happen")))))
13834 (when org-log-note-extra (insert org-log-note-extra))
13835 (setq-local org-finish-function 'org-store-log-note)
13836 (run-hooks 'org-log-buffer-setup-hook)))
13838 (defvar org-note-abort nil) ; dynamically scoped
13839 (defun org-store-log-note ()
13840 "Finish taking a log note, and insert it to where it belongs."
13841 (let ((txt (prog1 (buffer-string)
13842 (kill-buffer)))
13843 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13844 lines)
13845 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13846 (setq txt (replace-match "" t t txt)))
13847 (when (string-match "\\s-+\\'" txt)
13848 (setq txt (replace-match "" t t txt)))
13849 (setq lines (org-split-string txt "\n"))
13850 (when (org-string-nw-p note)
13851 (setq note
13852 (org-replace-escapes
13853 note
13854 (list (cons "%u" (user-login-name))
13855 (cons "%U" user-full-name)
13856 (cons "%t" (format-time-string
13857 (org-time-stamp-format 'long 'inactive)
13858 org-log-note-effective-time))
13859 (cons "%T" (format-time-string
13860 (org-time-stamp-format 'long nil)
13861 org-log-note-effective-time))
13862 (cons "%d" (format-time-string
13863 (org-time-stamp-format nil 'inactive)
13864 org-log-note-effective-time))
13865 (cons "%D" (format-time-string
13866 (org-time-stamp-format nil nil)
13867 org-log-note-effective-time))
13868 (cons "%s" (cond
13869 ((not org-log-note-state) "")
13870 ((string-match-p org-ts-regexp
13871 org-log-note-state)
13872 (format "\"[%s]\""
13873 (substring org-log-note-state 1 -1)))
13874 (t (format "\"%s\"" org-log-note-state))))
13875 (cons "%S"
13876 (cond
13877 ((not org-log-note-previous-state) "")
13878 ((string-match-p org-ts-regexp
13879 org-log-note-previous-state)
13880 (format "\"[%s]\""
13881 (substring
13882 org-log-note-previous-state 1 -1)))
13883 (t (format "\"%s\""
13884 org-log-note-previous-state)))))))
13885 (when lines (setq note (concat note " \\\\")))
13886 (push note lines))
13887 (when (and lines (not (or current-prefix-arg org-note-abort)))
13888 (with-current-buffer (marker-buffer org-log-note-marker)
13889 (org-with-wide-buffer
13890 ;; Find location for the new note.
13891 (goto-char org-log-note-marker)
13892 (set-marker org-log-note-marker nil)
13893 (goto-char (org-log-beginning t))
13894 ;; Make sure point is at the beginning of an empty line.
13895 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13896 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13897 ;; In an existing list, add a new item at the top level.
13898 ;; Otherwise, indent line like a regular one.
13899 (let ((itemp (org-in-item-p)))
13900 (if itemp
13901 (indent-line-to
13902 (let ((struct (save-excursion
13903 (goto-char itemp) (org-list-struct))))
13904 (org-list-get-ind (org-list-get-top-point struct) struct)))
13905 (org-indent-line)))
13906 (insert (org-list-bullet-string "-") (pop lines))
13907 (let ((ind (org-list-item-body-column (line-beginning-position))))
13908 (dolist (line lines)
13909 (insert "\n")
13910 (indent-line-to ind)
13911 (insert line)))
13912 (message "Note stored")
13913 (org-back-to-heading t)
13914 (org-cycle-hide-drawers 'children))
13915 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13916 ;; from within `org-add-log-note' because `buffer-undo-list'
13917 ;; is then modified outside of `org-with-remote-undo'.
13918 (when (eq this-command 'org-agenda-todo)
13919 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13920 ;; Don't add undo information when called from `org-agenda-todo'.
13921 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13922 (set-window-configuration org-log-note-window-configuration)
13923 (with-current-buffer (marker-buffer org-log-note-return-to)
13924 (goto-char org-log-note-return-to))
13925 (move-marker org-log-note-return-to nil)
13926 (when org-log-post-message (message "%s" org-log-post-message))))
13928 (defun org-remove-empty-drawer-at (pos)
13929 "Remove an empty drawer at position POS.
13930 POS may also be a marker."
13931 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13932 (org-with-wide-buffer
13933 (goto-char pos)
13934 (let ((drawer (org-element-at-point)))
13935 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13936 (not (org-element-property :contents-begin drawer)))
13937 (delete-region (org-element-property :begin drawer)
13938 (progn (goto-char (org-element-property :end drawer))
13939 (skip-chars-backward " \r\t\n")
13940 (forward-line)
13941 (point))))))))
13943 (defvar org-ts-type nil)
13944 (defun org-sparse-tree (&optional arg type)
13945 "Create a sparse tree, prompt for the details.
13946 This command can create sparse trees. You first need to select the type
13947 of match used to create the tree:
13949 t Show all TODO entries.
13950 T Show entries with a specific TODO keyword.
13951 m Show entries selected by a tags/property match.
13952 p Enter a property name and its value (both with completion on existing
13953 names/values) and show entries with that property.
13954 r Show entries matching a regular expression (`/' can be used as well).
13955 b Show deadlines and scheduled items before a date.
13956 a Show deadlines and scheduled items after a date.
13957 d Show deadlines due within `org-deadline-warning-days'.
13958 D Show deadlines and scheduled items between a date range."
13959 (interactive "P")
13960 (setq type (or type org-sparse-tree-default-date-type))
13961 (setq org-ts-type type)
13962 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13963 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13964 \[c]ycle through date types: %s"
13965 (cl-case type
13966 (all "all timestamps")
13967 (scheduled "only scheduled")
13968 (deadline "only deadline")
13969 (active "only active timestamps")
13970 (inactive "only inactive timestamps")
13971 (closed "with a closed time-stamp")
13972 (otherwise "scheduled/deadline")))
13973 (let ((answer (read-char-exclusive)))
13974 (cl-case answer
13976 (org-sparse-tree
13978 (cadr
13979 (memq type '(nil all scheduled deadline active inactive closed)))))
13980 (?d (call-interactively 'org-check-deadlines))
13981 (?b (call-interactively 'org-check-before-date))
13982 (?a (call-interactively 'org-check-after-date))
13983 (?D (call-interactively 'org-check-dates-range))
13984 (?t (call-interactively 'org-show-todo-tree))
13985 (?T (org-show-todo-tree '(4)))
13986 (?m (call-interactively 'org-match-sparse-tree))
13987 ((?p ?P)
13988 (let* ((kwd (completing-read
13989 "Property: " (mapcar #'list (org-buffer-property-keys))))
13990 (value (completing-read
13991 "Value: " (mapcar #'list (org-property-values kwd)))))
13992 (unless (string-match "\\`{.*}\\'" value)
13993 (setq value (concat "\"" value "\"")))
13994 (org-match-sparse-tree arg (concat kwd "=" value))))
13995 ((?r ?R ?/) (call-interactively 'org-occur))
13996 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13998 (defvar-local org-occur-highlights nil
13999 "List of overlays used for occur matches.")
14000 (defvar-local org-occur-parameters nil
14001 "Parameters of the active org-occur calls.
14002 This is a list, each call to org-occur pushes as cons cell,
14003 containing the regular expression and the callback, onto the list.
14004 The list can contain several entries if `org-occur' has been called
14005 several time with the KEEP-PREVIOUS argument. Otherwise, this list
14006 will only contain one set of parameters. When the highlights are
14007 removed (for example with `C-c C-c', or with the next edit (depending
14008 on `org-remove-highlights-with-change'), this variable is emptied
14009 as well.")
14011 (defun org-occur (regexp &optional keep-previous callback)
14012 "Make a compact tree which shows all matches of REGEXP.
14014 The tree will show the lines where the regexp matches, and any other context
14015 defined in `org-show-context-detail', which see.
14017 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
14018 done by a previous call to `org-occur' will be kept, to allow stacking of
14019 calls to this command.
14021 Optional argument CALLBACK can be a function of no argument. In this case,
14022 it is called with point at the end of the match, match data being set
14023 accordingly. Current match is shown only if the return value is non-nil.
14024 The function must neither move point nor alter narrowing."
14025 (interactive "sRegexp: \nP")
14026 (when (equal regexp "")
14027 (user-error "Regexp cannot be empty"))
14028 (unless keep-previous
14029 (org-remove-occur-highlights nil nil t))
14030 (push (cons regexp callback) org-occur-parameters)
14031 (let ((cnt 0))
14032 (save-excursion
14033 (goto-char (point-min))
14034 (when (or (not keep-previous) ; do not want to keep
14035 (not org-occur-highlights)) ; no previous matches
14036 ;; hide everything
14037 (org-overview))
14038 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
14039 (isearch-no-upper-case-p regexp t)
14040 org-occur-case-fold-search)))
14041 (while (re-search-forward regexp nil t)
14042 (when (or (not callback)
14043 (save-match-data (funcall callback)))
14044 (setq cnt (1+ cnt))
14045 (when org-highlight-sparse-tree-matches
14046 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14047 (org-show-context 'occur-tree)))))
14048 (when org-remove-highlights-with-change
14049 (add-hook 'before-change-functions 'org-remove-occur-highlights
14050 nil 'local))
14051 (unless org-sparse-tree-open-archived-trees
14052 (org-hide-archived-subtrees (point-min) (point-max)))
14053 (run-hooks 'org-occur-hook)
14054 (when (called-interactively-p 'interactive)
14055 (message "%d match(es) for regexp %s" cnt regexp))
14056 cnt))
14058 (defun org-occur-next-match (&optional n _reset)
14059 "Function for `next-error-function' to find sparse tree matches.
14060 N is the number of matches to move, when negative move backwards.
14061 This function always goes back to the starting point when no
14062 match is found."
14063 (let* ((limit (if (< n 0) (point-min) (point-max)))
14064 (search-func (if (< n 0)
14065 'previous-single-char-property-change
14066 'next-single-char-property-change))
14067 (n (abs n))
14068 (pos (point))
14070 (catch 'exit
14071 (while (setq p1 (funcall search-func (point) 'org-type))
14072 (when (equal p1 limit)
14073 (goto-char pos)
14074 (user-error "No more matches"))
14075 (when (equal (get-char-property p1 'org-type) 'org-occur)
14076 (setq n (1- n))
14077 (when (= n 0)
14078 (goto-char p1)
14079 (throw 'exit (point))))
14080 (goto-char p1))
14081 (goto-char p1)
14082 (user-error "No more matches"))))
14084 (defun org-show-context (&optional key)
14085 "Make sure point and context are visible.
14086 Optional argument KEY, when non-nil, is a symbol. See
14087 `org-show-context-detail' for allowed values and how much is to
14088 be shown."
14089 (org-show-set-visibility
14090 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14091 ((cdr (assq key org-show-context-detail)))
14092 (t (cdr (assq 'default org-show-context-detail))))))
14094 (defun org-show-set-visibility (detail)
14095 "Set visibility around point according to DETAIL.
14096 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14097 `tree', `canonical' or t. See `org-show-context-detail' for more
14098 information."
14099 ;; Show current heading and possibly its entry, following headline
14100 ;; or all children.
14101 (if (and (org-at-heading-p) (not (eq detail 'local)))
14102 (org-flag-heading nil)
14103 (org-show-entry)
14104 ;; If point is hidden within a drawer or a block, make sure to
14105 ;; expose it.
14106 (dolist (o (overlays-at (point)))
14107 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14108 (delete-overlay o)))
14109 (unless (org-before-first-heading-p)
14110 (org-with-limited-levels
14111 (cl-case detail
14112 ((tree canonical t) (org-show-children))
14113 ((nil minimal ancestors))
14114 (t (save-excursion
14115 (outline-next-heading)
14116 (org-flag-heading nil)))))))
14117 ;; Show all siblings.
14118 (when (eq detail 'lineage) (org-show-siblings))
14119 ;; Show ancestors, possibly with their children.
14120 (when (memq detail '(ancestors lineage tree canonical t))
14121 (save-excursion
14122 (while (org-up-heading-safe)
14123 (org-flag-heading nil)
14124 (when (memq detail '(canonical t)) (org-show-entry))
14125 (when (memq detail '(tree canonical t)) (org-show-children))))))
14127 (defvar org-reveal-start-hook nil
14128 "Hook run before revealing a location.")
14130 (defun org-reveal (&optional siblings)
14131 "Show current entry, hierarchy above it, and the following headline.
14133 This can be used to show a consistent set of context around
14134 locations exposed with `org-show-context'.
14136 With optional argument SIBLINGS, on each level of the hierarchy all
14137 siblings are shown. This repairs the tree structure to what it would
14138 look like when opened with hierarchical calls to `org-cycle'.
14140 With double optional argument \\[universal-argument] \\[universal-argument], \
14141 go to the parent and show the
14142 entire tree."
14143 (interactive "P")
14144 (run-hooks 'org-reveal-start-hook)
14145 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14146 ((equal siblings '(16))
14147 (save-excursion
14148 (when (org-up-heading-safe)
14149 (org-show-subtree)
14150 (run-hook-with-args 'org-cycle-hook 'subtree))))
14151 (t (org-show-set-visibility 'lineage))))
14153 (defun org-highlight-new-match (beg end)
14154 "Highlight from BEG to END and mark the highlight is an occur headline."
14155 (let ((ov (make-overlay beg end)))
14156 (overlay-put ov 'face 'secondary-selection)
14157 (overlay-put ov 'org-type 'org-occur)
14158 (push ov org-occur-highlights)))
14160 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14161 "Remove the occur highlights from the buffer.
14162 BEG and END are ignored. If NOREMOVE is nil, remove this function
14163 from the `before-change-functions' in the current buffer."
14164 (interactive)
14165 (unless org-inhibit-highlight-removal
14166 (mapc #'delete-overlay org-occur-highlights)
14167 (setq org-occur-highlights nil)
14168 (setq org-occur-parameters nil)
14169 (unless noremove
14170 (remove-hook 'before-change-functions
14171 'org-remove-occur-highlights 'local))))
14173 ;;;; Priorities
14175 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14176 "Regular expression matching the priority indicator.")
14178 (defvar org-remove-priority-next-time nil)
14180 (defun org-priority-up ()
14181 "Increase the priority of the current item."
14182 (interactive)
14183 (org-priority 'up))
14185 (defun org-priority-down ()
14186 "Decrease the priority of the current item."
14187 (interactive)
14188 (org-priority 'down))
14190 (defun org-priority (&optional action _show)
14191 "Change the priority of an item.
14192 ACTION can be `set', `up', `down', or a character."
14193 (interactive "P")
14194 (if (equal action '(4))
14195 (org-show-priority)
14196 (unless org-enable-priority-commands
14197 (user-error "Priority commands are disabled"))
14198 (setq action (or action 'set))
14199 (let (current new news have remove)
14200 (save-excursion
14201 (org-back-to-heading t)
14202 (when (looking-at org-priority-regexp)
14203 (setq current (string-to-char (match-string 2))
14204 have t))
14205 (cond
14206 ((eq action 'remove)
14207 (setq remove t new ?\ ))
14208 ((or (eq action 'set)
14209 (integerp action))
14210 (if (not (eq action 'set))
14211 (setq new action)
14212 (message "Priority %c-%c, SPC to remove: "
14213 org-highest-priority org-lowest-priority)
14214 (save-match-data
14215 (setq new (read-char-exclusive))))
14216 (when (and (= (upcase org-highest-priority) org-highest-priority)
14217 (= (upcase org-lowest-priority) org-lowest-priority))
14218 (setq new (upcase new)))
14219 (cond ((equal new ?\ ) (setq remove t))
14220 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14221 (user-error "Priority must be between `%c' and `%c'"
14222 org-highest-priority org-lowest-priority))))
14223 ((eq action 'up)
14224 (setq new (if have
14225 (1- current) ; normal cycling
14226 ;; last priority was empty
14227 (if (eq last-command this-command)
14228 org-lowest-priority ; wrap around empty to lowest
14229 ;; default
14230 (if org-priority-start-cycle-with-default
14231 org-default-priority
14232 (1- org-default-priority))))))
14233 ((eq action 'down)
14234 (setq new (if have
14235 (1+ current) ; normal cycling
14236 ;; last priority was empty
14237 (if (eq last-command this-command)
14238 org-highest-priority ; wrap around empty to highest
14239 ;; default
14240 (if org-priority-start-cycle-with-default
14241 org-default-priority
14242 (1+ org-default-priority))))))
14243 (t (user-error "Invalid action")))
14244 (when (or (< (upcase new) org-highest-priority)
14245 (> (upcase new) org-lowest-priority))
14246 (if (and (memq action '(up down))
14247 (not have) (not (eq last-command this-command)))
14248 ;; `new' is from default priority
14249 (error
14250 "The default can not be set, see `org-default-priority' why")
14251 ;; normal cycling: `new' is beyond highest/lowest priority
14252 ;; and is wrapped around to the empty priority
14253 (setq remove t)))
14254 (setq news (format "%c" new))
14255 (if have
14256 (if remove
14257 (replace-match "" t t nil 1)
14258 (replace-match news t t nil 2))
14259 (if remove
14260 (user-error "No priority cookie found in line")
14261 (let ((case-fold-search nil))
14262 (looking-at org-todo-line-regexp))
14263 (if (match-end 2)
14264 (progn
14265 (goto-char (match-end 2))
14266 (insert " [#" news "]"))
14267 (goto-char (match-beginning 3))
14268 (insert "[#" news "] "))))
14269 (org-set-tags nil 'align))
14270 (if remove
14271 (message "Priority removed")
14272 (message "Priority of current item set to %s" news)))))
14274 (defun org-show-priority ()
14275 "Show the priority of the current item.
14276 This priority is composed of the main priority given with the [#A] cookies,
14277 and by additional input from the age of a schedules or deadline entry."
14278 (interactive)
14279 (let ((pri (if (eq major-mode 'org-agenda-mode)
14280 (org-get-at-bol 'priority)
14281 (save-excursion
14282 (save-match-data
14283 (beginning-of-line)
14284 (and (looking-at org-heading-regexp)
14285 (org-get-priority (match-string 0))))))))
14286 (message "Priority is %d" (if pri pri -1000))))
14288 (defun org-get-priority (s)
14289 "Find priority cookie and return priority."
14290 (save-match-data
14291 (if (functionp org-get-priority-function)
14292 (funcall org-get-priority-function)
14293 (if (not (string-match org-priority-regexp s))
14294 (* 1000 (- org-lowest-priority org-default-priority))
14295 (* 1000 (- org-lowest-priority
14296 (string-to-char (match-string 2 s))))))))
14298 ;;;; Tags
14300 (defvar org-agenda-archives-mode)
14301 (defvar org-map-continue-from nil
14302 "Position from where mapping should continue.
14303 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14305 (defvar org-scanner-tags nil
14306 "The current tag list while the tags scanner is running.")
14308 (defvar org-trust-scanner-tags nil
14309 "Should `org-get-tags-at' use the tags for the scanner.
14310 This is for internal dynamical scoping only.
14311 When this is non-nil, the function `org-get-tags-at' will return the value
14312 of `org-scanner-tags' instead of building the list by itself. This
14313 can lead to large speed-ups when the tags scanner is used in a file with
14314 many entries, and when the list of tags is retrieved, for example to
14315 obtain a list of properties. Building the tags list for each entry in such
14316 a file becomes an N^2 operation - but with this variable set, it scales
14317 as N.")
14319 (defvar org--matcher-tags-todo-only nil)
14321 (defun org-scan-tags (action matcher todo-only &optional start-level)
14322 "Scan headline tags with inheritance and produce output ACTION.
14324 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14325 or `agenda' to produce an entry list for an agenda view. It can also be
14326 a Lisp form or a function that should be called at each matched headline, in
14327 this case the return value is a list of all return values from these calls.
14329 MATCHER is a function accepting three arguments, returning
14330 a non-nil value whenever a given set of tags qualifies a headline
14331 for inclusion. See `org-make-tags-matcher' for more information.
14332 As a special case, it can also be set to t (respectively nil) in
14333 order to match all (respectively none) headline.
14335 When TODO-ONLY is non-nil, only lines with a not-done TODO
14336 keyword are included in the output.
14338 START-LEVEL can be a string with asterisks, reducing the scope to
14339 headlines matching this string."
14340 (require 'org-agenda)
14341 (let* ((re (concat "^"
14342 (if start-level
14343 ;; Get the correct level to match
14344 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14345 org-outline-regexp)
14346 " *\\(\\<\\("
14347 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14348 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14349 (props (list 'face 'default
14350 'done-face 'org-agenda-done
14351 'undone-face 'default
14352 'mouse-face 'highlight
14353 'org-not-done-regexp org-not-done-regexp
14354 'org-todo-regexp org-todo-regexp
14355 'org-complex-heading-regexp org-complex-heading-regexp
14356 'help-echo
14357 (format "mouse-2 or RET jump to org file %s"
14358 (abbreviate-file-name
14359 (or (buffer-file-name (buffer-base-buffer))
14360 (buffer-name (buffer-base-buffer)))))))
14361 (org-map-continue-from nil)
14362 lspos tags tags-list
14363 (tags-alist (list (cons 0 org-file-tags)))
14364 (llast 0) rtn rtn1 level category i txt
14365 todo marker entry priority
14366 ts-date ts-date-type ts-date-pair)
14367 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14368 (setq action (list 'lambda nil action)))
14369 (save-excursion
14370 (goto-char (point-min))
14371 (when (eq action 'sparse-tree)
14372 (org-overview)
14373 (org-remove-occur-highlights))
14374 (while (let (case-fold-search)
14375 (re-search-forward re nil t))
14376 (setq org-map-continue-from nil)
14377 (catch :skip
14378 (setq todo
14379 ;; TODO: is the 1-2 difference a bug?
14380 (when (match-end 1) (match-string-no-properties 2))
14381 tags (when (match-end 4) (match-string-no-properties 4)))
14382 (goto-char (setq lspos (match-beginning 0)))
14383 (setq level (org-reduced-level (org-outline-level))
14384 category (org-get-category))
14385 (when (eq action 'agenda)
14386 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14387 ts-date (car ts-date-pair)
14388 ts-date-type (cdr ts-date-pair)))
14389 (setq i llast llast level)
14390 ;; remove tag lists from same and sublevels
14391 (while (>= i level)
14392 (when (setq entry (assoc i tags-alist))
14393 (setq tags-alist (delete entry tags-alist)))
14394 (setq i (1- i)))
14395 ;; add the next tags
14396 (when tags
14397 (setq tags (org-split-string tags ":")
14398 tags-alist
14399 (cons (cons level tags) tags-alist)))
14400 ;; compile tags for current headline
14401 (setq tags-list
14402 (if org-use-tag-inheritance
14403 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14404 tags)
14405 org-scanner-tags tags-list)
14406 (when org-use-tag-inheritance
14407 (setcdr (car tags-alist)
14408 (mapcar (lambda (x)
14409 (setq x (copy-sequence x))
14410 (org-add-prop-inherited x))
14411 (cdar tags-alist))))
14412 (when (and tags org-use-tag-inheritance
14413 (or (not (eq t org-use-tag-inheritance))
14414 org-tags-exclude-from-inheritance))
14415 ;; Selective inheritance, remove uninherited ones.
14416 (setcdr (car tags-alist)
14417 (org-remove-uninherited-tags (cdar tags-alist))))
14418 (when (and
14420 ;; eval matcher only when the todo condition is OK
14421 (and (or (not todo-only) (member todo org-not-done-keywords))
14422 (if (functionp matcher)
14423 (let ((case-fold-search t) (org-trust-scanner-tags t))
14424 (funcall matcher todo tags-list level))
14425 matcher))
14427 ;; Call the skipper, but return t if it does not
14428 ;; skip, so that the `and' form continues evaluating.
14429 (progn
14430 (unless (eq action 'sparse-tree) (org-agenda-skip))
14433 ;; Check if timestamps are deselecting this entry
14434 (or (not todo-only)
14435 (and (member todo org-not-done-keywords)
14436 (or (not org-agenda-tags-todo-honor-ignore-options)
14437 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14439 ;; select this headline
14440 (cond
14441 ((eq action 'sparse-tree)
14442 (and org-highlight-sparse-tree-matches
14443 (org-get-heading) (match-end 0)
14444 (org-highlight-new-match
14445 (match-beginning 1) (match-end 1)))
14446 (org-show-context 'tags-tree))
14447 ((eq action 'agenda)
14448 (setq txt (org-agenda-format-item
14450 (concat
14451 (if (eq org-tags-match-list-sublevels 'indented)
14452 (make-string (1- level) ?.) "")
14453 (org-get-heading))
14454 (make-string level ?\s)
14455 category
14456 tags-list)
14457 priority (org-get-priority txt))
14458 (goto-char lspos)
14459 (setq marker (org-agenda-new-marker))
14460 (org-add-props txt props
14461 'org-marker marker 'org-hd-marker marker 'org-category category
14462 'todo-state todo
14463 'ts-date ts-date
14464 'priority priority
14465 'type (concat "tagsmatch" ts-date-type))
14466 (push txt rtn))
14467 ((functionp action)
14468 (setq org-map-continue-from nil)
14469 (save-excursion
14470 (setq rtn1 (funcall action))
14471 (push rtn1 rtn)))
14472 (t (user-error "Invalid action")))
14474 ;; if we are to skip sublevels, jump to end of subtree
14475 (unless org-tags-match-list-sublevels
14476 (org-end-of-subtree t)
14477 (backward-char 1))))
14478 ;; Get the correct position from where to continue
14479 (if org-map-continue-from
14480 (goto-char org-map-continue-from)
14481 (and (= (point) lspos) (end-of-line 1)))))
14482 (when (and (eq action 'sparse-tree)
14483 (not org-sparse-tree-open-archived-trees))
14484 (org-hide-archived-subtrees (point-min) (point-max)))
14485 (nreverse rtn)))
14487 (defun org-remove-uninherited-tags (tags)
14488 "Remove all tags that are not inherited from the list TAGS."
14489 (cond
14490 ((eq org-use-tag-inheritance t)
14491 (if org-tags-exclude-from-inheritance
14492 (org-delete-all org-tags-exclude-from-inheritance tags)
14493 tags))
14494 ((not org-use-tag-inheritance) nil)
14495 ((stringp org-use-tag-inheritance)
14496 (delq nil (mapcar
14497 (lambda (x)
14498 (if (and (string-match org-use-tag-inheritance x)
14499 (not (member x org-tags-exclude-from-inheritance)))
14500 x nil))
14501 tags)))
14502 ((listp org-use-tag-inheritance)
14503 (delq nil (mapcar
14504 (lambda (x)
14505 (if (member x org-use-tag-inheritance) x nil))
14506 tags)))))
14508 (defun org-match-sparse-tree (&optional todo-only match)
14509 "Create a sparse tree according to tags string MATCH.
14510 MATCH can contain positive and negative selection of tags, like
14511 \"+WORK+URGENT-WITHBOSS\".
14512 If optional argument TODO-ONLY is non-nil, only select lines that are
14513 also TODO lines."
14514 (interactive "P")
14515 (org-agenda-prepare-buffers (list (current-buffer)))
14516 (let ((org--matcher-tags-todo-only todo-only))
14517 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14518 org--matcher-tags-todo-only)))
14520 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14522 (defvar org-cached-props nil)
14523 (defun org-cached-entry-get (pom property)
14524 (if (or (eq t org-use-property-inheritance)
14525 (and (stringp org-use-property-inheritance)
14526 (let ((case-fold-search t))
14527 (string-match-p org-use-property-inheritance property)))
14528 (and (listp org-use-property-inheritance)
14529 (member-ignore-case property org-use-property-inheritance)))
14530 ;; Caching is not possible, check it directly.
14531 (org-entry-get pom property 'inherit)
14532 ;; Get all properties, so we can do complicated checks easily.
14533 (cdr (assoc-string property
14534 (or org-cached-props
14535 (setq org-cached-props (org-entry-properties pom)))
14536 t))))
14538 (defun org-global-tags-completion-table (&optional files)
14539 "Return the list of all tags in all agenda buffer/files.
14540 Optional FILES argument is a list of files which can be used
14541 instead of the agenda files."
14542 (save-excursion
14543 (org-uniquify
14544 (delq nil
14545 (apply #'append
14546 (mapcar
14547 (lambda (file)
14548 (set-buffer (find-file-noselect file))
14549 (mapcar (lambda (x)
14550 (and (stringp (car-safe x))
14551 (list (car-safe x))))
14552 (or org-current-tag-alist (org-get-buffer-tags))))
14553 (if (car-safe files) files
14554 (org-agenda-files))))))))
14556 (defun org-make-tags-matcher (match)
14557 "Create the TAGS/TODO matcher form for the selection string MATCH.
14559 Returns a cons of the selection string MATCH and a function
14560 implementing the matcher.
14562 The matcher is to be called at an Org entry, with point on the
14563 headline, and returns non-nil if the entry matches the selection
14564 string MATCH. It must be called with three arguments: the TODO
14565 keyword at the entry (or nil if none), the list of all tags at
14566 the entry including inherited ones and the reduced level of the
14567 headline. Additionally, the category of the entry, if any, must
14568 be specified as the text property `org-category' on the headline.
14570 This function sets the variable `org--matcher-tags-todo-only' to
14571 a non-nil value if the matcher restricts matching to TODO
14572 entries, otherwise it is not touched.
14574 See also `org-scan-tags'."
14575 (unless match
14576 ;; Get a new match request, with completion against the global
14577 ;; tags table and the local tags in current buffer.
14578 (let ((org-last-tags-completion-table
14579 (org-uniquify
14580 (delq nil (append (org-get-buffer-tags)
14581 (org-global-tags-completion-table))))))
14582 (setq match
14583 (completing-read
14584 "Match: "
14585 'org-tags-completion-function nil nil nil 'org-tags-history))))
14587 (let ((match0 match)
14588 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14589 (start 0)
14590 tagsmatch todomatch tagsmatcher todomatcher)
14592 ;; Expand group tags.
14593 (setq match (org-tags-expand match))
14595 ;; Check if there is a TODO part of this match, which would be the
14596 ;; part after a "/". To make sure that this slash is not part of
14597 ;; a property value to be matched against, we also check that
14598 ;; there is no / after that slash. First, find the last slash.
14599 (let ((s 0))
14600 (while (string-match "/+" match s)
14601 (setq start (match-beginning 0))
14602 (setq s (match-end 0))))
14603 (if (and (string-match "/+" match start)
14604 (not (string-match-p "\"" match start)))
14605 ;; Match contains also a TODO-matching request.
14606 (progn
14607 (setq tagsmatch (substring match 0 (match-beginning 0)))
14608 (setq todomatch (substring match (match-end 0)))
14609 (when (string-match "\\`!" todomatch)
14610 (setq org--matcher-tags-todo-only t)
14611 (setq todomatch (substring todomatch 1)))
14612 (when (string-match "\\`\\s-*\\'" todomatch)
14613 (setq todomatch nil)))
14614 ;; Only matching tags.
14615 (setq tagsmatch match)
14616 (setq todomatch nil))
14618 ;; Make the tags matcher.
14619 (when (org-string-nw-p tagsmatch)
14620 (let ((orlist nil)
14621 (orterms (org-split-string tagsmatch "|"))
14622 term)
14623 (while (setq term (pop orterms))
14624 (while (and (equal (substring term -1) "\\") orterms)
14625 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14626 (while (string-match re term)
14627 (let* ((rest (substring term (match-end 0)))
14628 (minus (and (match-end 1)
14629 (equal (match-string 1 term) "-")))
14630 (tag (save-match-data
14631 (replace-regexp-in-string
14632 "\\\\-" "-" (match-string 2 term))))
14633 (regexp (eq (string-to-char tag) ?{))
14634 (levelp (match-end 4))
14635 (propp (match-end 5))
14637 (cond
14638 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14639 (levelp
14640 `(,(org-op-to-function (match-string 3 term))
14641 level
14642 ,(string-to-number (match-string 4 term))))
14643 (propp
14644 (let* ((gv (pcase (upcase (match-string 5 term))
14645 ("CATEGORY"
14646 '(get-text-property (point) 'org-category))
14647 ("TODO" 'todo)
14648 (p `(org-cached-entry-get nil ,p))))
14649 (pv (match-string 7 term))
14650 (regexp (eq (string-to-char pv) ?{))
14651 (strp (eq (string-to-char pv) ?\"))
14652 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14653 (po (org-op-to-function (match-string 6 term)
14654 (if timep 'time strp))))
14655 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14656 (when timep (setq pv (org-matcher-time pv)))
14657 (cond ((and regexp (eq po 'org<>))
14658 `(not (string-match ,pv (or ,gv ""))))
14659 (regexp `(string-match ,pv (or ,gv "")))
14660 (strp `(,po (or ,gv "") ,pv))
14662 `(,po
14663 (string-to-number (or ,gv ""))
14664 ,(string-to-number pv))))))
14665 (t `(member ,tag tags-list)))))
14666 (push (if minus `(not ,mm) mm) tagsmatcher)
14667 (setq term rest)))
14668 (push `(and ,@tagsmatcher) orlist)
14669 (setq tagsmatcher nil))
14670 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14672 ;; Make the TODO matcher.
14673 (when (org-string-nw-p todomatch)
14674 (let ((orlist nil))
14675 (dolist (term (org-split-string todomatch "|"))
14676 (while (string-match re term)
14677 (let* ((minus (and (match-end 1)
14678 (equal (match-string 1 term) "-")))
14679 (kwd (match-string 2 term))
14680 (regexp (eq (string-to-char kwd) ?{))
14681 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14682 `(equal todo ,kwd))))
14683 (push (if minus `(not ,mm) mm) todomatcher))
14684 (setq term (substring term (match-end 0))))
14685 (push (if (> (length todomatcher) 1)
14686 (cons 'and todomatcher)
14687 (car todomatcher))
14688 orlist)
14689 (setq todomatcher nil))
14690 (setq todomatcher (cons 'or orlist))))
14692 ;; Return the string and function of the matcher. If no
14693 ;; tags-specific or todo-specific matcher exists, match
14694 ;; everything.
14695 (let ((matcher (if (and tagsmatcher todomatcher)
14696 `(and ,tagsmatcher ,todomatcher)
14697 (or tagsmatcher todomatcher t))))
14698 (when org--matcher-tags-todo-only
14699 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14700 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14702 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14703 "Expand group tags in MATCH.
14705 This replaces every group tag in MATCH with a regexp tag search.
14706 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14707 will be replaced like this:
14709 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14710 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14711 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14713 Replacing by a regexp preserves the structure of the match.
14714 E.g., this expansion
14716 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14718 will match anything tagged with \"Lab\" and \"Home\", or tagged
14719 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14721 A group tag in MATCH can contain regular expressions of its own.
14722 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14723 will be replaced like this:
14725 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14727 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14728 assumed to be a single group tag, and the function will return
14729 the list of tags in this group.
14731 When DOWNCASE is non-nil, expand downcased TAGS."
14732 (if org-group-tags
14733 (let* ((case-fold-search t)
14734 (stable org-mode-syntax-table)
14735 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14736 (taggroups (if downcased
14737 (mapcar (lambda (tg) (mapcar #'downcase tg))
14738 taggroups)
14739 taggroups))
14740 (taggroups-keys (mapcar #'car taggroups))
14741 (return-match (if downcased (downcase match) match))
14742 (count 0)
14743 (work-already-expanded tags-already-expanded)
14744 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14745 ;; @ and _ are allowed as word-components in tags.
14746 (modify-syntax-entry ?@ "w" stable)
14747 (modify-syntax-entry ?_ "w" stable)
14748 ;; Temporarily replace regexp-expressions in the match-expression.
14749 (while (string-match "{.+?}" return-match)
14750 (cl-incf count)
14751 (push (match-string 0 return-match) regexps-in-match)
14752 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14753 (while (and taggroups-keys
14754 (with-syntax-table stable
14755 (string-match
14756 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14757 (regexp-opt taggroups-keys) "\\>\\)")
14758 return-match)))
14759 (let* ((dir (match-string 1 return-match))
14760 (tag (match-string 2 return-match))
14761 (tag (if downcased (downcase tag) tag)))
14762 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14763 (member tag work-already-expanded))
14764 (setq tags-in-group (assoc tag taggroups))
14765 (push tag work-already-expanded)
14766 ;; Recursively expand each tag in the group, if the tag hasn't
14767 ;; already been expanded. Restore the match-data after all recursive calls.
14768 (save-match-data
14769 (let (tags-expanded)
14770 (dolist (x (cdr tags-in-group))
14771 (if (and (member x taggroups-keys)
14772 (not (member x work-already-expanded)))
14773 (setq tags-expanded
14774 (delete-dups
14775 (append
14776 (org-tags-expand x t downcased
14777 work-already-expanded)
14778 tags-expanded)))
14779 (setq tags-expanded
14780 (append (list x) tags-expanded)))
14781 (setq work-already-expanded
14782 (delete-dups
14783 (append tags-expanded
14784 work-already-expanded))))
14785 (setq tags-in-group
14786 (delete-dups (cons (car tags-in-group)
14787 tags-expanded)))))
14788 ;; Filter tag-regexps from tags.
14789 (setq regexp-in-group-escaped
14790 (delq nil (mapcar (lambda (x)
14791 (if (stringp x)
14792 (and (equal "{" (substring x 0 1))
14793 (equal "}" (substring x -1))
14796 tags-in-group))
14797 regexp-in-group
14798 (mapcar (lambda (x)
14799 (substring x 1 -1))
14800 regexp-in-group-escaped)
14801 tags-in-group
14802 (delq nil (mapcar (lambda (x)
14803 (if (stringp x)
14804 (and (not (equal "{" (substring x 0 1)))
14805 (not (equal "}" (substring x -1)))
14808 tags-in-group)))
14809 ;; If single-as-list, do no more in the while-loop.
14810 (if (not single-as-list)
14811 (progn
14812 (when regexp-in-group
14813 (setq regexp-in-group
14814 (concat "\\|"
14815 (mapconcat 'identity regexp-in-group
14816 "\\|"))))
14817 (setq tags-in-group
14818 (concat dir
14819 "{\\<"
14820 (regexp-opt tags-in-group)
14821 "\\>"
14822 regexp-in-group
14823 "}"))
14824 (when (stringp tags-in-group)
14825 (org-add-props tags-in-group '(grouptag t)))
14826 (setq return-match
14827 (replace-match tags-in-group t t return-match)))
14828 (setq tags-in-group
14829 (append regexp-in-group-escaped tags-in-group))))
14830 (setq taggroups-keys (delete tag taggroups-keys))))
14831 ;; Add the regular expressions back into the match-expression again.
14832 (while regexps-in-match
14833 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14834 (pop regexps-in-match)
14835 return-match t t))
14836 (cl-decf count))
14837 (if single-as-list
14838 (if tags-in-group tags-in-group (list return-match))
14839 return-match))
14840 (if single-as-list
14841 (list (if downcased (downcase match) match))
14842 match)))
14844 (defun org-op-to-function (op &optional stringp)
14845 "Turn an operator into the appropriate function."
14846 (setq op
14847 (cond
14848 ((equal op "<" ) '(< string< org-time<))
14849 ((equal op ">" ) '(> org-string> org-time>))
14850 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14851 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14852 ((member op '("=" "==")) '(= string= org-time=))
14853 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14854 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14856 (defun org<> (a b) (not (= a b)))
14857 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14858 (defun org-string>= (a b) (not (string< a b)))
14859 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14860 (defun org-string<> (a b) (not (string= a b)))
14861 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14862 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14863 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14864 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14865 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14866 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14867 (defun org-2ft (s)
14868 "Convert S to a floating point time.
14869 If S is already a number, just return it. If it is a string, parse
14870 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14871 (cond
14872 ((numberp s) s)
14873 ((stringp s)
14874 (condition-case nil
14875 (float-time (apply 'encode-time (org-parse-time-string s)))
14876 (error 0.)))
14877 (t 0.)))
14879 (defun org-time-today ()
14880 "Time in seconds today at 0:00.
14881 Returns the float number of seconds since the beginning of the
14882 epoch to the beginning of today (00:00)."
14883 (float-time (apply 'encode-time
14884 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14886 (defun org-matcher-time (s)
14887 "Interpret a time comparison value."
14888 (save-match-data
14889 (cond
14890 ((string= s "<now>") (float-time))
14891 ((string= s "<today>") (org-time-today))
14892 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14893 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14894 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14895 (+ (org-time-today)
14896 (* (string-to-number (match-string 1 s))
14897 (cdr (assoc (match-string 2 s)
14898 '(("d" . 86400.0) ("w" . 604800.0)
14899 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14900 (t (org-2ft s)))))
14902 (defun org-match-any-p (re list)
14903 "Does re match any element of list?"
14904 (setq list (mapcar (lambda (x) (string-match re x)) list))
14905 (delq nil list))
14907 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14908 (defvar org-tags-overlay (make-overlay 1 1))
14909 (delete-overlay org-tags-overlay)
14911 (defun org-get-local-tags-at (&optional pos)
14912 "Get a list of tags defined in the current headline."
14913 (org-get-tags-at pos 'local))
14915 (defun org-get-local-tags ()
14916 "Get a list of tags defined in the current headline."
14917 (org-get-tags-at nil 'local))
14919 (defun org-get-tags-at (&optional pos local)
14920 "Get a list of all headline tags applicable at POS.
14921 POS defaults to point. If tags are inherited, the list contains
14922 the targets in the same sequence as the headlines appear, i.e.
14923 the tags of the current headline come last.
14924 When LOCAL is non-nil, only return tags from the current headline,
14925 ignore inherited ones."
14926 (interactive)
14927 (if (and org-trust-scanner-tags
14928 (or (not pos) (equal pos (point)))
14929 (not local))
14930 org-scanner-tags
14931 (let (tags ltags lastpos parent)
14932 (save-excursion
14933 (save-restriction
14934 (widen)
14935 (goto-char (or pos (point)))
14936 (save-match-data
14937 (catch 'done
14938 (condition-case nil
14939 (progn
14940 (org-back-to-heading t)
14941 (while (not (equal lastpos (point)))
14942 (setq lastpos (point))
14943 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14944 (setq ltags (org-split-string
14945 (match-string-no-properties 1) ":"))
14946 (when parent
14947 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14948 (setq tags (append
14949 (if parent
14950 (org-remove-uninherited-tags ltags)
14951 ltags)
14952 tags)))
14953 (or org-use-tag-inheritance (throw 'done t))
14954 (when local (throw 'done t))
14955 (or (org-up-heading-safe) (error nil))
14956 (setq parent t)))
14957 (error nil)))))
14958 (if local
14959 tags
14960 (reverse (delete-dups
14961 (reverse (append
14962 (org-remove-uninherited-tags
14963 org-file-tags)
14964 tags)))))))))
14966 (defun org-add-prop-inherited (s)
14967 (add-text-properties 0 (length s) '(inherited t) s)
14970 (defun org-toggle-tag (tag &optional onoff)
14971 "Toggle the tag TAG for the current line.
14972 If ONOFF is `on' or `off', don't toggle but set to this state."
14973 (let (res current)
14974 (save-excursion
14975 (org-back-to-heading t)
14976 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14977 (point-at-eol) t)
14978 (progn
14979 (setq current (match-string 1))
14980 (replace-match ""))
14981 (setq current ""))
14982 (setq current (nreverse (org-split-string current ":")))
14983 (cond
14984 ((eq onoff 'on)
14985 (setq res t)
14986 (or (member tag current) (push tag current)))
14987 ((eq onoff 'off)
14988 (or (not (member tag current)) (setq current (delete tag current))))
14989 (t (if (member tag current)
14990 (setq current (delete tag current))
14991 (setq res t)
14992 (push tag current))))
14993 (end-of-line 1)
14994 (if current
14995 (progn
14996 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14997 (org-set-tags nil t))
14998 (delete-horizontal-space))
14999 (run-hooks 'org-after-tags-change-hook))
15000 res))
15002 (defun org-align-tags-here (to-col)
15003 ;; Assumes that this is a headline
15004 "Align tags on the current headline to TO-COL."
15005 (let ((pos (point)) (col (current-column)) ncol tags-l p)
15006 (beginning-of-line 1)
15007 (if (and (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15008 (< pos (match-beginning 2)))
15009 (progn
15010 (setq tags-l (string-width (match-string 2)))
15011 (goto-char (match-beginning 1))
15012 (insert " ")
15013 (delete-region (point) (1+ (match-beginning 2)))
15014 (setq ncol (max (current-column)
15015 (1+ col)
15016 (if (> to-col 0)
15017 to-col
15018 (- (abs to-col) tags-l))))
15019 (setq p (point))
15020 (insert (make-string (- ncol (current-column)) ?\ ))
15021 (setq ncol (current-column))
15022 (when indent-tabs-mode (tabify p (point-at-eol)))
15023 (org-move-to-column (min ncol col)))
15024 (goto-char pos))))
15026 (defun org-set-tags-command (&optional arg just-align)
15027 "Call the set-tags command for the current entry."
15028 (interactive "P")
15029 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
15030 (org-set-tags arg just-align)
15031 (save-excursion
15032 (unless (and (org-region-active-p)
15033 org-loop-over-headlines-in-active-region)
15034 (org-back-to-heading t))
15035 (org-set-tags arg just-align))))
15037 (defun org-set-tags-to (data)
15038 "Set the tags of the current entry to DATA, replacing the current tags.
15039 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
15040 If DATA is nil or the empty string, any tags will be removed."
15041 (interactive "sTags: ")
15042 (setq data
15043 (cond
15044 ((eq data nil) "")
15045 ((equal data "") "")
15046 ((stringp data)
15047 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
15048 ":"))
15049 ((listp data)
15050 (concat ":" (mapconcat 'identity data ":") ":"))))
15051 (when data
15052 (save-excursion
15053 (org-back-to-heading t)
15054 (when (looking-at org-complex-heading-regexp)
15055 (if (match-end 5)
15056 (progn
15057 (goto-char (match-beginning 5))
15058 (insert data)
15059 (delete-region (point) (point-at-eol))
15060 (org-set-tags nil 'align))
15061 (goto-char (point-at-eol))
15062 (insert " " data)
15063 (org-set-tags nil 'align)))
15064 (beginning-of-line 1)
15065 (when (looking-at ".*?\\([ \t]+\\)$")
15066 (delete-region (match-beginning 1) (match-end 1))))))
15068 (defun org-align-all-tags ()
15069 "Align the tags in all headings."
15070 (interactive)
15071 (save-excursion
15072 (or (ignore-errors (org-back-to-heading t))
15073 (outline-next-heading))
15074 (if (org-at-heading-p)
15075 (org-set-tags t)
15076 (message "No headings"))))
15078 (defvar org-indent-indentation-per-level)
15079 (defun org-set-tags (&optional arg just-align)
15080 "Set the tags for the current headline.
15081 With prefix ARG, realign all tags in headings in the current buffer.
15082 When JUST-ALIGN is non-nil, only align tags."
15083 (interactive "P")
15084 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15085 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15086 'region-start-level
15087 'region))
15088 org-loop-over-headlines-in-active-region)
15089 (org-map-entries
15090 ;; We don't use ARG and JUST-ALIGN here because these args
15091 ;; are not useful when looping over headlines.
15092 #'org-set-tags
15093 org-loop-over-headlines-in-active-region
15095 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15096 (let ((org-setting-tags t))
15097 (if arg
15098 (save-excursion
15099 (goto-char (point-min))
15100 (while (re-search-forward org-outline-regexp-bol nil t)
15101 (org-set-tags nil t)
15102 (end-of-line))
15103 (message "All tags realigned to column %d" org-tags-column))
15104 (let* ((current (org-get-tags-string))
15105 (col (current-column))
15106 (tags
15107 (if just-align current
15108 ;; Get a new set of tags from the user.
15109 (save-excursion
15110 (let* ((seen)
15111 (table
15112 (setq
15113 org-last-tags-completion-table
15114 ;; Uniquify tags in alists, yet preserve
15115 ;; structure (i.e., keywords).
15116 (delq nil
15117 (mapcar
15118 (lambda (pair)
15119 (let ((head (car pair)))
15120 (cond ((symbolp head) pair)
15121 ((member head seen) nil)
15122 (t (push head seen)
15123 pair))))
15124 (append
15125 (or org-current-tag-alist
15126 (org-get-buffer-tags))
15127 (and
15128 org-complete-tags-always-offer-all-agenda-tags
15129 (org-global-tags-completion-table
15130 (org-agenda-files))))))))
15131 (current-tags (org-split-string current ":"))
15132 (inherited-tags
15133 (nreverse (nthcdr (length current-tags)
15134 (nreverse (org-get-tags-at))))))
15135 (replace-regexp-in-string
15136 "\\([-+&]+\\|,\\)"
15138 (if (or (eq t org-use-fast-tag-selection)
15139 (and org-use-fast-tag-selection
15140 (delq nil (mapcar #'cdr table))))
15141 (org-fast-tag-selection
15142 current-tags inherited-tags table
15143 (and org-fast-tag-selection-include-todo
15144 org-todo-key-alist))
15145 (let ((org-add-colon-after-tag-completion
15146 (< 1 (length table))))
15147 (org-trim
15148 (completing-read
15149 "Tags: "
15150 #'org-tags-completion-function
15151 nil nil current 'org-tags-history))))))))))
15153 (when org-tags-sort-function
15154 (setq tags
15155 (mapconcat
15156 #'identity
15157 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15158 org-tags-sort-function)
15159 ":")))
15161 (if (not (org-string-nw-p tags)) (setq tags "")
15162 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
15163 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
15165 ;; Insert new tags at the correct column
15166 (beginning-of-line)
15167 (let ((level (if (looking-at org-outline-regexp)
15168 (- (match-end 0) (point) 1)
15169 1)))
15170 (cond
15171 ((and (equal current "") (equal tags "")))
15172 ((re-search-forward
15173 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15174 (line-end-position)
15176 (if (equal tags "") (replace-match "" t t)
15177 (goto-char (match-beginning 0))
15178 (let* ((c0 (current-column))
15179 ;; Compute offset for the case of org-indent-mode
15180 ;; active.
15181 (di (if (bound-and-true-p org-indent-mode)
15182 (* (1- org-indent-indentation-per-level)
15183 (1- level))
15185 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15186 (tc (+ org-tags-column
15187 (if (> org-tags-column 0) (- di) di)))
15188 (c1 (max (1+ c0)
15189 (if (> tc 0) tc
15190 (- (- tc) (string-width tags)))))
15191 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15192 (replace-match rpl t t)
15193 (when indent-tabs-mode (tabify p0 (point))))))
15194 (t (error "Tags alignment failed"))))
15195 (org-move-to-column col))
15196 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15198 (defun org-change-tag-in-region (beg end tag off)
15199 "Add or remove TAG for each entry in the region.
15200 This works in the agenda, and also in an Org buffer."
15201 (interactive
15202 (list (region-beginning) (region-end)
15203 (let ((org-last-tags-completion-table
15204 (if (derived-mode-p 'org-mode)
15205 (org-uniquify
15206 (delq nil (append (org-get-buffer-tags)
15207 (org-global-tags-completion-table))))
15208 (org-global-tags-completion-table))))
15209 (completing-read
15210 "Tag: " 'org-tags-completion-function nil nil nil
15211 'org-tags-history))
15212 (progn
15213 (message "[s]et or [r]emove? ")
15214 (equal (read-char-exclusive) ?r))))
15215 (when (fboundp 'deactivate-mark) (deactivate-mark))
15216 (let ((agendap (equal major-mode 'org-agenda-mode))
15217 l1 l2 m buf pos newhead (cnt 0))
15218 (goto-char end)
15219 (setq l2 (1- (org-current-line)))
15220 (goto-char beg)
15221 (setq l1 (org-current-line))
15222 (cl-loop for l from l1 to l2 do
15223 (org-goto-line l)
15224 (setq m (get-text-property (point) 'org-hd-marker))
15225 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15226 (and agendap m))
15227 (setq buf (if agendap (marker-buffer m) (current-buffer))
15228 pos (if agendap m (point)))
15229 (with-current-buffer buf
15230 (save-excursion
15231 (save-restriction
15232 (goto-char pos)
15233 (setq cnt (1+ cnt))
15234 (org-toggle-tag tag (if off 'off 'on))
15235 (setq newhead (org-get-heading)))))
15236 (and agendap (org-agenda-change-all-lines newhead m))))
15237 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15239 (defun org-tags-completion-function (string _predicate &optional flag)
15240 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15241 (confirm (lambda (x) (stringp (car x)))))
15242 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15243 (setq s1 (match-string 1 string)
15244 s2 (match-string 2 string))
15245 (setq s1 "" s2 string))
15246 (cond
15247 ((eq flag nil)
15248 ;; try completion
15249 (setq rtn (try-completion s2 ctable confirm))
15250 (when (stringp rtn)
15251 (setq rtn
15252 (concat s1 s2 (substring rtn (length s2))
15253 (if (and org-add-colon-after-tag-completion
15254 (assoc rtn ctable))
15255 ":" ""))))
15256 rtn)
15257 ((eq flag t)
15258 ;; all-completions
15259 (all-completions s2 ctable confirm))
15260 ((eq flag 'lambda)
15261 ;; exact match?
15262 (assoc s2 ctable)))))
15264 (defun org-fast-tag-insert (kwd tags face &optional end)
15265 "Insert KDW, and the TAGS, the latter with face FACE.
15266 Also insert END."
15267 (insert (format "%-12s" (concat kwd ":"))
15268 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15269 (or end "")))
15271 (defun org-fast-tag-show-exit (flag)
15272 (save-excursion
15273 (org-goto-line 3)
15274 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15275 (replace-match ""))
15276 (when flag
15277 (end-of-line 1)
15278 (org-move-to-column (- (window-width) 19) t)
15279 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15281 (defun org-set-current-tags-overlay (current prefix)
15282 "Add an overlay to CURRENT tag with PREFIX."
15283 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15284 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15285 (org-overlay-display org-tags-overlay (concat prefix s))))
15287 (defvar org-last-tag-selection-key nil)
15288 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15289 "Fast tag selection with single keys.
15290 CURRENT is the current list of tags in the headline, INHERITED is the
15291 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15292 possibly with grouping information. TODO-TABLE is a similar table with
15293 TODO keywords, should these have keys assigned to them.
15294 If the keys are nil, a-z are automatically assigned.
15295 Returns the new tags string, or nil to not change the current settings."
15296 (let* ((fulltable (append table todo-table))
15297 (maxlen (apply 'max (mapcar
15298 (lambda (x)
15299 (if (stringp (car x)) (string-width (car x)) 0))
15300 fulltable)))
15301 (buf (current-buffer))
15302 (expert (eq org-fast-tag-selection-single-key 'expert))
15303 (buffer-tags nil)
15304 (fwidth (+ maxlen 3 1 3))
15305 (ncol (/ (- (window-width) 4) fwidth))
15306 (i-face 'org-done)
15307 (c-face 'org-todo)
15308 tg cnt e c char c1 c2 ntable tbl rtn
15309 ov-start ov-end ov-prefix
15310 (exit-after-next org-fast-tag-selection-single-key)
15311 (done-keywords org-done-keywords)
15312 groups ingroup intaggroup)
15313 (save-excursion
15314 (beginning-of-line 1)
15315 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15316 (setq ov-start (match-beginning 1)
15317 ov-end (match-end 1)
15318 ov-prefix "")
15319 (setq ov-start (1- (point-at-eol))
15320 ov-end (1+ ov-start))
15321 (skip-chars-forward "^\n\r")
15322 (setq ov-prefix
15323 (concat
15324 (buffer-substring (1- (point)) (point))
15325 (if (> (current-column) org-tags-column)
15327 (make-string (- org-tags-column (current-column)) ?\ ))))))
15328 (move-overlay org-tags-overlay ov-start ov-end)
15329 (save-window-excursion
15330 (if expert
15331 (set-buffer (get-buffer-create " *Org tags*"))
15332 (delete-other-windows)
15333 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15334 (org-switch-to-buffer-other-window " *Org tags*"))
15335 (erase-buffer)
15336 (setq-local org-done-keywords done-keywords)
15337 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15338 (org-fast-tag-insert "Current" current c-face "\n\n")
15339 (org-fast-tag-show-exit exit-after-next)
15340 (org-set-current-tags-overlay current ov-prefix)
15341 (setq tbl fulltable char ?a cnt 0)
15342 (while (setq e (pop tbl))
15343 (cond
15344 ((eq (car e) :startgroup)
15345 (push '() groups) (setq ingroup t)
15346 (unless (zerop cnt)
15347 (setq cnt 0)
15348 (insert "\n"))
15349 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15350 ((eq (car e) :endgroup)
15351 (setq ingroup nil cnt 0)
15352 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15353 ((eq (car e) :startgrouptag)
15354 (setq intaggroup t)
15355 (unless (zerop cnt)
15356 (setq cnt 0)
15357 (insert "\n"))
15358 (insert "[ "))
15359 ((eq (car e) :endgrouptag)
15360 (setq intaggroup nil cnt 0)
15361 (insert "]\n"))
15362 ((equal e '(:newline))
15363 (unless (zerop cnt)
15364 (setq cnt 0)
15365 (insert "\n")
15366 (setq e (car tbl))
15367 (while (equal (car tbl) '(:newline))
15368 (insert "\n")
15369 (setq tbl (cdr tbl)))))
15370 ((equal e '(:grouptags)) (insert " : "))
15372 (setq tg (copy-sequence (car e)) c2 nil)
15373 (if (cdr e)
15374 (setq c (cdr e))
15375 ;; automatically assign a character.
15376 (setq c1 (string-to-char
15377 (downcase (substring
15378 tg (if (= (string-to-char tg) ?@) 1 0)))))
15379 (if (or (rassoc c1 ntable) (rassoc c1 table))
15380 (while (or (rassoc char ntable) (rassoc char table))
15381 (setq char (1+ char)))
15382 (setq c2 c1))
15383 (setq c (or c2 char)))
15384 (when ingroup (push tg (car groups)))
15385 (setq tg (org-add-props tg nil 'face
15386 (cond
15387 ((not (assoc tg table))
15388 (org-get-todo-face tg))
15389 ((member tg current) c-face)
15390 ((member tg inherited) i-face))))
15391 (when (equal (caar tbl) :grouptags)
15392 (org-add-props tg nil 'face 'org-tag-group))
15393 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15394 (insert "[" c "] " tg (make-string
15395 (- fwidth 4 (length tg)) ?\ ))
15396 (push (cons tg c) ntable)
15397 (when (= (cl-incf cnt) ncol)
15398 (insert "\n")
15399 (when (or ingroup intaggroup) (insert " "))
15400 (setq cnt 0)))))
15401 (setq ntable (nreverse ntable))
15402 (insert "\n")
15403 (goto-char (point-min))
15404 (unless expert (org-fit-window-to-buffer))
15405 (setq rtn
15406 (catch 'exit
15407 (while t
15408 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15409 (if (not groups) "no " "")
15410 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15411 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15412 (setq org-last-tag-selection-key c)
15413 (cond
15414 ((= c ?\r) (throw 'exit t))
15415 ((= c ?!)
15416 (setq groups (not groups))
15417 (goto-char (point-min))
15418 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15419 ((= c ?\C-c)
15420 (if (not expert)
15421 (org-fast-tag-show-exit
15422 (setq exit-after-next (not exit-after-next)))
15423 (setq expert nil)
15424 (delete-other-windows)
15425 (set-window-buffer (split-window-vertically) " *Org tags*")
15426 (org-switch-to-buffer-other-window " *Org tags*")
15427 (org-fit-window-to-buffer)))
15428 ((or (= c ?\C-g)
15429 (and (= c ?q) (not (rassoc c ntable))))
15430 (delete-overlay org-tags-overlay)
15431 (setq quit-flag t))
15432 ((= c ?\ )
15433 (setq current nil)
15434 (when exit-after-next (setq exit-after-next 'now)))
15435 ((= c ?\t)
15436 (condition-case nil
15437 (setq tg (completing-read
15438 "Tag: "
15439 (or buffer-tags
15440 (with-current-buffer buf
15441 (setq buffer-tags
15442 (org-get-buffer-tags))))))
15443 (quit (setq tg "")))
15444 (when (string-match "\\S-" tg)
15445 (cl-pushnew (list tg) buffer-tags :test #'equal)
15446 (if (member tg current)
15447 (setq current (delete tg current))
15448 (push tg current)))
15449 (when exit-after-next (setq exit-after-next 'now)))
15450 ((setq e (rassoc c todo-table) tg (car e))
15451 (with-current-buffer buf
15452 (save-excursion (org-todo tg)))
15453 (when exit-after-next (setq exit-after-next 'now)))
15454 ((setq e (rassoc c ntable) tg (car e))
15455 (if (member tg current)
15456 (setq current (delete tg current))
15457 (cl-loop for g in groups do
15458 (when (member tg g)
15459 (dolist (x g) (setq current (delete x current)))))
15460 (push tg current))
15461 (when exit-after-next (setq exit-after-next 'now))))
15463 ;; Create a sorted list
15464 (setq current
15465 (sort current
15466 (lambda (a b)
15467 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15468 (when (eq exit-after-next 'now) (throw 'exit t))
15469 (goto-char (point-min))
15470 (beginning-of-line 2)
15471 (delete-region (point) (point-at-eol))
15472 (org-fast-tag-insert "Current" current c-face)
15473 (org-set-current-tags-overlay current ov-prefix)
15474 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15475 (setq tg (match-string 1))
15476 (add-text-properties
15477 (match-beginning 1) (match-end 1)
15478 (list 'face
15479 (cond
15480 ((member tg current) c-face)
15481 ((member tg inherited) i-face)
15482 (t (get-text-property (match-beginning 1) 'face))))))
15483 (goto-char (point-min)))))
15484 (delete-overlay org-tags-overlay)
15485 (if rtn
15486 (mapconcat 'identity current ":")
15487 nil))))
15489 (defun org-get-tags-string ()
15490 "Get the TAGS string in the current headline."
15491 (unless (org-at-heading-p t)
15492 (user-error "Not on a heading"))
15493 (save-excursion
15494 (beginning-of-line 1)
15495 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15496 (match-string-no-properties 1)
15497 "")))
15499 (defun org-get-tags ()
15500 "Get the list of tags specified in the current headline."
15501 (org-split-string (org-get-tags-string) ":"))
15503 (defun org-get-buffer-tags ()
15504 "Get a table of all tags used in the buffer, for completion."
15505 (org-with-wide-buffer
15506 (goto-char (point-min))
15507 (let ((tag-re (concat org-outline-regexp-bol
15508 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15509 tags)
15510 (while (re-search-forward tag-re nil t)
15511 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15512 (push tag tags)))
15513 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15515 ;;;; The mapping API
15517 (defvar org-agenda-skip-comment-trees)
15518 (defvar org-agenda-skip-function)
15519 (defun org-map-entries (func &optional match scope &rest skip)
15520 "Call FUNC at each headline selected by MATCH in SCOPE.
15522 FUNC is a function or a lisp form. The function will be called without
15523 arguments, with the cursor positioned at the beginning of the headline.
15524 The return values of all calls to the function will be collected and
15525 returned as a list.
15527 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15528 does not need to preserve point. After evaluation, the cursor will be
15529 moved to the end of the line (presumably of the headline of the
15530 processed entry) and search continues from there. Under some
15531 circumstances, this may not produce the wanted results. For example,
15532 if you have removed (e.g. archived) the current (sub)tree it could
15533 mean that the next entry will be skipped entirely. In such cases, you
15534 can specify the position from where search should continue by making
15535 FUNC set the variable `org-map-continue-from' to the desired buffer
15536 position.
15538 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15539 Only headlines that are matched by this query will be considered during
15540 the iteration. When MATCH is nil or t, all headlines will be
15541 visited by the iteration.
15543 SCOPE determines the scope of this command. It can be any of:
15545 nil The current buffer, respecting the restriction if any
15546 tree The subtree started with the entry at point
15547 region The entries within the active region, if any
15548 region-start-level
15549 The entries within the active region, but only those at
15550 the same level than the first one.
15551 file The current buffer, without restriction
15552 file-with-archives
15553 The current buffer, and any archives associated with it
15554 agenda All agenda files
15555 agenda-with-archives
15556 All agenda files with any archive files associated with them
15557 \(file1 file2 ...)
15558 If this is a list, all files in the list will be scanned
15560 The remaining args are treated as settings for the skipping facilities of
15561 the scanner. The following items can be given here:
15563 archive skip trees with the archive tag
15564 comment skip trees with the COMMENT keyword
15565 function or Emacs Lisp form:
15566 will be used as value for `org-agenda-skip-function', so
15567 whenever the function returns a position, FUNC will not be
15568 called for that entry and search will continue from the
15569 position returned
15571 If your function needs to retrieve the tags including inherited tags
15572 at the *current* entry, you can use the value of the variable
15573 `org-scanner-tags' which will be much faster than getting the value
15574 with `org-get-tags-at'. If your function gets properties with
15575 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15576 to t around the call to `org-entry-properties' to get the same speedup.
15577 Note that if your function moves around to retrieve tags and properties at
15578 a *different* entry, you cannot use these techniques."
15579 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15580 (not (org-region-active-p)))
15581 (let* ((org-agenda-archives-mode nil) ; just to make sure
15582 (org-agenda-skip-archived-trees (memq 'archive skip))
15583 (org-agenda-skip-comment-trees (memq 'comment skip))
15584 (org-agenda-skip-function
15585 (car (org-delete-all '(comment archive) skip)))
15586 (org-tags-match-list-sublevels t)
15587 (start-level (eq scope 'region-start-level))
15588 matcher res
15589 org-todo-keywords-for-agenda
15590 org-done-keywords-for-agenda
15591 org-todo-keyword-alist-for-agenda
15592 org-tag-alist-for-agenda
15593 org--matcher-tags-todo-only)
15595 (cond
15596 ((eq match t) (setq matcher t))
15597 ((eq match nil) (setq matcher t))
15598 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15600 (save-excursion
15601 (save-restriction
15602 (cond ((eq scope 'tree)
15603 (org-back-to-heading t)
15604 (org-narrow-to-subtree)
15605 (setq scope nil))
15606 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15607 (org-region-active-p))
15608 ;; If needed, set start-level to a string like "2"
15609 (when start-level
15610 (save-excursion
15611 (goto-char (region-beginning))
15612 (unless (org-at-heading-p) (outline-next-heading))
15613 (setq start-level (org-current-level))))
15614 (narrow-to-region (region-beginning)
15615 (save-excursion
15616 (goto-char (region-end))
15617 (unless (and (bolp) (org-at-heading-p))
15618 (outline-next-heading))
15619 (point)))
15620 (setq scope nil)))
15622 (if (not scope)
15623 (progn
15624 (org-agenda-prepare-buffers
15625 (and buffer-file-name (list buffer-file-name)))
15626 (setq res
15627 (org-scan-tags
15628 func matcher org--matcher-tags-todo-only start-level)))
15629 ;; Get the right scope
15630 (cond
15631 ((and scope (listp scope) (symbolp (car scope)))
15632 (setq scope (eval scope)))
15633 ((eq scope 'agenda)
15634 (setq scope (org-agenda-files t)))
15635 ((eq scope 'agenda-with-archives)
15636 (setq scope (org-agenda-files t))
15637 (setq scope (org-add-archive-files scope)))
15638 ((eq scope 'file)
15639 (setq scope (and buffer-file-name (list buffer-file-name))))
15640 ((eq scope 'file-with-archives)
15641 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15642 (org-agenda-prepare-buffers scope)
15643 (dolist (file scope)
15644 (with-current-buffer (org-find-base-buffer-visiting file)
15645 (save-excursion
15646 (save-restriction
15647 (widen)
15648 (goto-char (point-min))
15649 (setq res
15650 (append
15652 (org-scan-tags
15653 func matcher org--matcher-tags-todo-only))))))))))
15654 res)))
15656 ;;; Properties API
15658 (defconst org-special-properties
15659 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15660 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15661 "The special properties valid in Org mode.
15662 These are properties that are not defined in the property drawer,
15663 but in some other way.")
15665 (defconst org-default-properties
15666 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15667 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15668 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15669 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15670 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15671 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15672 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15673 "Some properties that are used by Org mode for various purposes.
15674 Being in this list makes sure that they are offered for completion.")
15676 (defun org--valid-property-p (property)
15677 "Non nil when string PROPERTY is a valid property name."
15678 (not
15679 (or (equal property "")
15680 (string-match-p "\\s-" property))))
15682 (defun org--update-property-plist (key val props)
15683 "Associate KEY to VAL in alist PROPS.
15684 Modifications are made by side-effect. Return new alist."
15685 (let* ((appending (string= (substring key -1) "+"))
15686 (key (if appending (substring key 0 -1) key))
15687 (old (assoc-string key props t)))
15688 (if (not old) (cons (cons key val) props)
15689 (setcdr old (if appending (concat (cdr old) " " val) val))
15690 props)))
15692 (defun org-get-property-block (&optional beg force)
15693 "Return the (beg . end) range of the body of the property drawer.
15694 BEG is the beginning of the current subtree, or of the part
15695 before the first headline. If it is not given, it will be found.
15696 If the drawer does not exist, create it if FORCE is non-nil, or
15697 return nil."
15698 (org-with-wide-buffer
15699 (when beg (goto-char beg))
15700 (unless (org-before-first-heading-p)
15701 (let ((beg (cond (beg)
15702 ((or (not (featurep 'org-inlinetask))
15703 (org-inlinetask-in-task-p))
15704 (org-back-to-heading t))
15705 (t (org-with-limited-levels (org-back-to-heading t))))))
15706 (forward-line)
15707 (when (looking-at-p org-planning-line-re) (forward-line))
15708 (cond ((looking-at org-property-drawer-re)
15709 (forward-line)
15710 (cons (point) (progn (goto-char (match-end 0))
15711 (line-beginning-position))))
15712 (force
15713 (goto-char beg)
15714 (org-insert-property-drawer)
15715 (let ((pos (save-excursion (search-forward ":END:")
15716 (line-beginning-position))))
15717 (cons pos pos))))))))
15719 (defun org-at-property-p ()
15720 "Non-nil when point is inside a property drawer.
15721 See `org-property-re' for match data, if applicable."
15722 (save-excursion
15723 (beginning-of-line)
15724 (and (looking-at org-property-re)
15725 (let ((property-drawer (save-match-data (org-get-property-block))))
15726 (and property-drawer
15727 (>= (point) (car property-drawer))
15728 (< (point) (cdr property-drawer)))))))
15730 (defun org-property-action ()
15731 "Do an action on properties."
15732 (interactive)
15733 (unless (org-at-property-p) (user-error "Not at a property"))
15734 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15735 (let ((c (read-char-exclusive)))
15736 (cl-case c
15737 (?s (call-interactively #'org-set-property))
15738 (?d (call-interactively #'org-delete-property))
15739 (?D (call-interactively #'org-delete-property-globally))
15740 (?c (call-interactively #'org-compute-property-at-point))
15741 (otherwise (user-error "No such property action %c" c)))))
15743 (defun org-inc-effort ()
15744 "Increment the value of the effort property in the current entry."
15745 (interactive)
15746 (org-set-effort nil t))
15748 (defvar org-clock-effort) ; Defined in org-clock.el.
15749 (defvar org-clock-current-task) ; Defined in org-clock.el.
15750 (defun org-set-effort (&optional value increment)
15751 "Set the effort property of the current entry.
15752 With numerical prefix arg, use the nth allowed value, 0 stands for the
15753 10th allowed value.
15755 When INCREMENT is non-nil, set the property to the next allowed value."
15756 (interactive "P")
15757 (when (equal value 0) (setq value 10))
15758 (let* ((completion-ignore-case t)
15759 (prop org-effort-property)
15760 (cur (org-entry-get nil prop))
15761 (allowed (org-property-get-allowed-values nil prop 'table))
15762 (existing (mapcar 'list (org-property-values prop)))
15763 (heading (nth 4 (org-heading-components)))
15765 (val (cond
15766 ((stringp value) value)
15767 ((and allowed (integerp value))
15768 (or (car (nth (1- value) allowed))
15769 (car (org-last allowed))))
15770 ((and allowed increment)
15771 (or (cl-caadr (member (list cur) allowed))
15772 (user-error "Allowed effort values are not set")))
15773 (allowed
15774 (message "Select 1-9,0, [RET%s]: %s"
15775 (if cur (concat "=" cur) "")
15776 (mapconcat 'car allowed " "))
15777 (setq rpl (read-char-exclusive))
15778 (if (equal rpl ?\r)
15780 (setq rpl (- rpl ?0))
15781 (when (equal rpl 0) (setq rpl 10))
15782 (if (and (> rpl 0) (<= rpl (length allowed)))
15783 (car (nth (1- rpl) allowed))
15784 (org-completing-read "Effort: " allowed nil))))
15786 (org-completing-read
15787 (concat "Effort" (and cur (string-match "\\S-" cur)
15788 (concat " [" cur "]"))
15789 ": ")
15790 existing nil nil "" nil cur)))))
15791 (unless (equal (org-entry-get nil prop) val)
15792 (org-entry-put nil prop val))
15793 (org-refresh-property
15794 '((effort . identity)
15795 (effort-minutes . org-duration-string-to-minutes))
15796 val)
15797 (when (equal heading (bound-and-true-p org-clock-current-task))
15798 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15799 (org-clock-update-mode-line))
15800 (message "%s is now %s" prop val)))
15802 (defun org-entry-properties (&optional pom which)
15803 "Get all properties of the current entry.
15805 When POM is a buffer position, get all properties from the entry
15806 there instead.
15808 This includes the TODO keyword, the tags, time strings for
15809 deadline, scheduled, and clocking, and any additional properties
15810 defined in the entry.
15812 If WHICH is nil or `all', get all properties. If WHICH is
15813 `special' or `standard', only get that subclass. If WHICH is
15814 a string, only get that property.
15816 Return value is an alist. Keys are properties, as upcased
15817 strings."
15818 (org-with-point-at pom
15819 (when (and (derived-mode-p 'org-mode)
15820 (ignore-errors (org-back-to-heading t)))
15821 (catch 'exit
15822 (let* ((beg (point))
15823 (specific (and (stringp which) (upcase which)))
15824 (which (cond ((not specific) which)
15825 ((member specific org-special-properties) 'special)
15826 (t 'standard)))
15827 props)
15828 ;; Get the special properties, like TODO and TAGS.
15829 (when (memq which '(nil all special))
15830 (when (or (not specific) (string= specific "CLOCKSUM"))
15831 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15832 (when clocksum
15833 (push (cons "CLOCKSUM"
15834 (org-minutes-to-clocksum-string clocksum))
15835 props)))
15836 (when specific (throw 'exit props)))
15837 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15838 (let ((clocksumt (get-text-property (point)
15839 :org-clock-minutes-today)))
15840 (when clocksumt
15841 (push (cons "CLOCKSUM_T"
15842 (org-minutes-to-clocksum-string clocksumt))
15843 props)))
15844 (when specific (throw 'exit props)))
15845 (when (or (not specific) (string= specific "ITEM"))
15846 (when (looking-at org-complex-heading-regexp)
15847 (push (cons "ITEM"
15848 (let ((title (match-string-no-properties 4)))
15849 (if (org-string-nw-p title)
15850 (org-remove-tabs title)
15851 "")))
15852 props))
15853 (when specific (throw 'exit props)))
15854 (when (or (not specific) (string= specific "TODO"))
15855 (let ((case-fold-search nil))
15856 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15857 (push (cons "TODO" (match-string-no-properties 2)) props)))
15858 (when specific (throw 'exit props)))
15859 (when (or (not specific) (string= specific "PRIORITY"))
15860 (push (cons "PRIORITY"
15861 (if (looking-at org-priority-regexp)
15862 (match-string-no-properties 2)
15863 (char-to-string org-default-priority)))
15864 props)
15865 (when specific (throw 'exit props)))
15866 (when (or (not specific) (string= specific "FILE"))
15867 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15868 props)
15869 (when specific (throw 'exit props)))
15870 (when (or (not specific) (string= specific "TAGS"))
15871 (let ((value (org-string-nw-p (org-get-tags-string))))
15872 (when value (push (cons "TAGS" value) props)))
15873 (when specific (throw 'exit props)))
15874 (when (or (not specific) (string= specific "ALLTAGS"))
15875 (let ((value (org-get-tags-at)))
15876 (when value
15877 (push (cons "ALLTAGS"
15878 (format ":%s:" (mapconcat #'identity value ":")))
15879 props)))
15880 (when specific (throw 'exit props)))
15881 (when (or (not specific) (string= specific "BLOCKED"))
15882 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15883 (when specific (throw 'exit props)))
15884 (when (or (not specific)
15885 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15886 (forward-line)
15887 (when (looking-at-p org-planning-line-re)
15888 (end-of-line)
15889 (let ((bol (line-beginning-position))
15890 ;; Backward compatibility: time keywords used to
15891 ;; be configurable (before 8.3). Make sure we
15892 ;; get the correct keyword.
15893 (key-assoc `(("CLOSED" . ,org-closed-string)
15894 ("DEADLINE" . ,org-deadline-string)
15895 ("SCHEDULED" . ,org-scheduled-string))))
15896 (dolist (pair (if specific (list (assoc specific key-assoc))
15897 key-assoc))
15898 (save-excursion
15899 (when (search-backward (cdr pair) bol t)
15900 (goto-char (match-end 0))
15901 (skip-chars-forward " \t")
15902 (and (looking-at org-ts-regexp-both)
15903 (push (cons (car pair)
15904 (match-string-no-properties 0))
15905 props)))))))
15906 (when specific (throw 'exit props)))
15907 (when (or (not specific)
15908 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15909 (let ((find-ts
15910 (lambda (end ts)
15911 ;; Fix next time-stamp before END. TS is the
15912 ;; list of time-stamps found so far.
15913 (let ((ts ts)
15914 (regexp (cond
15915 ((string= specific "TIMESTAMP")
15916 org-ts-regexp)
15917 ((string= specific "TIMESTAMP_IA")
15918 org-ts-regexp-inactive)
15919 ((assoc "TIMESTAMP_IA" ts)
15920 org-ts-regexp)
15921 ((assoc "TIMESTAMP" ts)
15922 org-ts-regexp-inactive)
15923 (t org-ts-regexp-both))))
15924 (catch 'next
15925 (while (re-search-forward regexp end t)
15926 (backward-char)
15927 (let ((object (org-element-context)))
15928 ;; Accept to match timestamps in node
15929 ;; properties, too.
15930 (when (memq (org-element-type object)
15931 '(node-property timestamp))
15932 (let ((type
15933 (org-element-property :type object)))
15934 (cond
15935 ((and (memq type '(active active-range))
15936 (not (equal specific "TIMESTAMP_IA")))
15937 (unless (assoc "TIMESTAMP" ts)
15938 (push (cons "TIMESTAMP"
15939 (org-element-property
15940 :raw-value object))
15942 (when specific (throw 'exit ts))))
15943 ((and (memq type '(inactive inactive-range))
15944 (not (string= specific "TIMESTAMP")))
15945 (unless (assoc "TIMESTAMP_IA" ts)
15946 (push (cons "TIMESTAMP_IA"
15947 (org-element-property
15948 :raw-value object))
15950 (when specific (throw 'exit ts))))))
15951 ;; Both timestamp types are found,
15952 ;; move to next part.
15953 (when (= (length ts) 2) (throw 'next ts)))))
15954 ts)))))
15955 (goto-char beg)
15956 ;; First look for timestamps within headline.
15957 (let ((ts (funcall find-ts (line-end-position) nil)))
15958 (if (= (length ts) 2) (setq props (nconc ts props))
15959 (forward-line)
15960 ;; Then find timestamps in the section, skipping
15961 ;; planning line.
15962 (when (looking-at-p org-planning-line-re)
15963 (forward-line))
15964 (let ((end (save-excursion (outline-next-heading))))
15965 (setq props (nconc (funcall find-ts end ts) props))))))))
15966 ;; Get the standard properties, like :PROP:.
15967 (when (memq which '(nil all standard))
15968 ;; If we are looking after a specific property, delegate
15969 ;; to `org-entry-get', which is faster. However, make an
15970 ;; exception for "CATEGORY", since it can be also set
15971 ;; through keywords (i.e. #+CATEGORY).
15972 (if (and specific (not (equal specific "CATEGORY")))
15973 (let ((value (org-entry-get beg specific nil t)))
15974 (throw 'exit (and value (list (cons specific value)))))
15975 (let ((range (org-get-property-block beg)))
15976 (when range
15977 (let ((end (cdr range)) seen-base)
15978 (goto-char (car range))
15979 ;; Unlike to `org--update-property-plist', we
15980 ;; handle the case where base values is found
15981 ;; after its extension. We also forbid standard
15982 ;; properties to be named as special properties.
15983 (while (re-search-forward org-property-re end t)
15984 (let* ((key (upcase (match-string-no-properties 2)))
15985 (extendp (string-match-p "\\+\\'" key))
15986 (key-base (if extendp (substring key 0 -1) key))
15987 (value (match-string-no-properties 3)))
15988 (cond
15989 ((member-ignore-case key-base org-special-properties))
15990 (extendp
15991 (setq props
15992 (org--update-property-plist key value props)))
15993 ((member key seen-base))
15994 (t (push key seen-base)
15995 (let ((p (assoc-string key props t)))
15996 (if p (setcdr p (concat value " " (cdr p)))
15997 (push (cons key value) props))))))))))))
15998 (unless (assoc "CATEGORY" props)
15999 (push (cons "CATEGORY" (org-get-category beg)) props)
16000 (when (string= specific "CATEGORY") (throw 'exit props)))
16001 ;; Return value.
16002 props)))))
16004 (defun org-property--local-values (property literal-nil)
16005 "Return value for PROPERTY in current entry.
16006 Value is a list whose car is the base value for PROPERTY and cdr
16007 a list of accumulated values. Return nil if neither is found in
16008 the entry. Also return nil when PROPERTY is set to \"nil\",
16009 unless LITERAL-NIL is non-nil."
16010 (let ((range (org-get-property-block)))
16011 (when range
16012 (goto-char (car range))
16013 (let* ((case-fold-search t)
16014 (end (cdr range))
16015 (value
16016 ;; Base value.
16017 (save-excursion
16018 (let ((v (and (re-search-forward
16019 (org-re-property property nil t) end t)
16020 (match-string-no-properties 3))))
16021 (list (if literal-nil v (org-not-nil v)))))))
16022 ;; Find additional values.
16023 (let* ((property+ (org-re-property (concat property "+") nil t)))
16024 (while (re-search-forward property+ end t)
16025 (push (match-string-no-properties 3) value)))
16026 ;; Return final values.
16027 (and (not (equal value '(nil))) (nreverse value))))))
16029 (defun org-entry-get (pom property &optional inherit literal-nil)
16030 "Get value of PROPERTY for entry or content at point-or-marker POM.
16032 If INHERIT is non-nil and the entry does not have the property,
16033 then also check higher levels of the hierarchy. If INHERIT is
16034 the symbol `selective', use inheritance only if the setting in
16035 `org-use-property-inheritance' selects PROPERTY for inheritance.
16037 If the property is present but empty, the return value is the
16038 empty string. If the property is not present at all, nil is
16039 returned. In any other case, return the value as a string.
16040 Search is case-insensitive.
16042 If LITERAL-NIL is set, return the string value \"nil\" as
16043 a string, do not interpret it as the list atom nil. This is used
16044 for inheritance when a \"nil\" value can supersede a non-nil
16045 value higher up the hierarchy."
16046 (org-with-point-at pom
16047 (cond
16048 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
16049 ;; We need a special property. Use `org-entry-properties' to
16050 ;; retrieve it, but specify the wanted property.
16051 (cdr (assoc-string property (org-entry-properties nil property))))
16052 ((and inherit
16053 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
16054 (org-entry-get-with-inheritance property literal-nil))
16056 (let* ((local (org-property--local-values property literal-nil))
16057 (value (and local (mapconcat #'identity (delq nil local) " "))))
16058 (if literal-nil value (org-not-nil value)))))))
16060 (defun org-property-or-variable-value (var &optional inherit)
16061 "Check if there is a property fixing the value of VAR.
16062 If yes, return this value. If not, return the current value of the variable."
16063 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16064 (if (and prop (stringp prop) (string-match "\\S-" prop))
16065 (read prop)
16066 (symbol-value var))))
16068 (defun org-entry-delete (pom property)
16069 "Delete PROPERTY from entry at point-or-marker POM.
16070 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16071 non-nil when a property was removed."
16072 (unless (member property org-special-properties)
16073 (org-with-point-at pom
16074 (let ((range (org-get-property-block)))
16075 (when range
16076 (let* ((begin (car range))
16077 (origin (cdr range))
16078 (end (copy-marker origin))
16079 (re (org-re-property
16080 (concat (regexp-quote property) "\\+?") t t)))
16081 (goto-char begin)
16082 (while (re-search-forward re end t)
16083 (delete-region (match-beginning 0) (line-beginning-position 2)))
16084 ;; If drawer is empty, remove it altogether.
16085 (when (= begin end)
16086 (delete-region (line-beginning-position 0)
16087 (line-beginning-position 2)))
16088 ;; Return non-nil if some property was removed.
16089 (prog1 (/= end origin) (set-marker end nil))))))))
16091 ;; Multi-values properties are properties that contain multiple values
16092 ;; These values are assumed to be single words, separated by whitespace.
16093 (defun org-entry-add-to-multivalued-property (pom property value)
16094 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16095 (let* ((old (org-entry-get pom property))
16096 (values (and old (org-split-string old "[ \t]"))))
16097 (setq value (org-entry-protect-space value))
16098 (unless (member value values)
16099 (setq values (append values (list value)))
16100 (org-entry-put pom property
16101 (mapconcat 'identity values " ")))))
16103 (defun org-entry-remove-from-multivalued-property (pom property value)
16104 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16105 (let* ((old (org-entry-get pom property))
16106 (values (and old (org-split-string old "[ \t]"))))
16107 (setq value (org-entry-protect-space value))
16108 (when (member value values)
16109 (setq values (delete value values))
16110 (org-entry-put pom property
16111 (mapconcat 'identity values " ")))))
16113 (defun org-entry-member-in-multivalued-property (pom property value)
16114 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16115 (let* ((old (org-entry-get pom property))
16116 (values (and old (org-split-string old "[ \t]"))))
16117 (setq value (org-entry-protect-space value))
16118 (member value values)))
16120 (defun org-entry-get-multivalued-property (pom property)
16121 "Return a list of values in a multivalued property."
16122 (let* ((value (org-entry-get pom property))
16123 (values (and value (org-split-string value "[ \t]"))))
16124 (mapcar 'org-entry-restore-space values)))
16126 (defun org-entry-put-multivalued-property (pom property &rest values)
16127 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16128 VALUES should be a list of strings. Spaces will be protected."
16129 (org-entry-put pom property
16130 (mapconcat 'org-entry-protect-space values " "))
16131 (let* ((value (org-entry-get pom property))
16132 (values (and value (org-split-string value "[ \t]"))))
16133 (mapcar 'org-entry-restore-space values)))
16135 (defun org-entry-protect-space (s)
16136 "Protect spaces and newline in string S."
16137 (while (string-match " " s)
16138 (setq s (replace-match "%20" t t s)))
16139 (while (string-match "\n" s)
16140 (setq s (replace-match "%0A" t t s)))
16143 (defun org-entry-restore-space (s)
16144 "Restore spaces and newline in string S."
16145 (while (string-match "%20" s)
16146 (setq s (replace-match " " t t s)))
16147 (while (string-match "%0A" s)
16148 (setq s (replace-match "\n" t t s)))
16151 (defvar org-entry-property-inherited-from (make-marker)
16152 "Marker pointing to the entry from where a property was inherited.
16153 Each call to `org-entry-get-with-inheritance' will set this marker to the
16154 location of the entry where the inheritance search matched. If there was
16155 no match, the marker will point nowhere.
16156 Note that also `org-entry-get' calls this function, if the INHERIT flag
16157 is set.")
16159 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16160 "Get PROPERTY of entry or content at point, search higher levels if needed.
16161 The search will stop at the first ancestor which has the property defined.
16162 If the value found is \"nil\", return nil to show that the property
16163 should be considered as undefined (this is the meaning of nil here).
16164 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16165 (move-marker org-entry-property-inherited-from nil)
16166 (org-with-wide-buffer
16167 (let (value)
16168 (catch 'exit
16169 (while t
16170 (let ((v (org-property--local-values property literal-nil)))
16171 (when v
16172 (setq value
16173 (concat (mapconcat #'identity (delq nil v) " ")
16174 (and value " ")
16175 value)))
16176 (cond
16177 ((car v)
16178 (org-back-to-heading t)
16179 (move-marker org-entry-property-inherited-from (point))
16180 (throw 'exit nil))
16181 ((org-up-heading-safe))
16183 (let ((global
16184 (cdr (or (assoc-string property org-file-properties t)
16185 (assoc-string property org-global-properties t)
16186 (assoc-string property org-global-properties-fixed t)))))
16187 (cond ((not global))
16188 (value (setq value (concat global " " value)))
16189 (t (setq value global))))
16190 (throw 'exit nil))))))
16191 (if literal-nil value (org-not-nil value)))))
16193 (defvar org-property-changed-functions nil
16194 "Hook called when the value of a property has changed.
16195 Each hook function should accept two arguments, the name of the property
16196 and the new value.")
16198 (defun org-entry-put (pom property value)
16199 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16201 If the value is nil, it is converted to the empty string. If it
16202 is not a string, an error is raised. Also raise an error on
16203 invalid property names.
16205 PROPERTY can be any regular property (see
16206 `org-special-properties'). It can also be \"TODO\",
16207 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16209 For the last two properties, VALUE may have any of the special
16210 values \"earlier\" and \"later\". The function then increases or
16211 decreases scheduled or deadline date by one day."
16212 (cond ((null value) (setq value ""))
16213 ((not (stringp value)) (error "Properties values should be strings"))
16214 ((not (org--valid-property-p property))
16215 (user-error "Invalid property name: \"%s\"" property)))
16216 (org-with-point-at pom
16217 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16218 (org-back-to-heading t)
16219 (org-with-limited-levels (org-back-to-heading t)))
16220 (let ((beg (point)))
16221 (cond
16222 ((equal property "TODO")
16223 (cond ((not (org-string-nw-p value)) (setq value 'none))
16224 ((not (member value org-todo-keywords-1))
16225 (user-error "\"%s\" is not a valid TODO state" value)))
16226 (org-todo value)
16227 (org-set-tags nil 'align))
16228 ((equal property "PRIORITY")
16229 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16230 (org-set-tags nil 'align))
16231 ((equal property "SCHEDULED")
16232 (forward-line)
16233 (if (and (looking-at-p org-planning-line-re)
16234 (re-search-forward
16235 org-scheduled-time-regexp (line-end-position) t))
16236 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16237 ((string= value "later") (org-timestamp-change 1 'day))
16238 ((string= value "") (org-schedule '(4)))
16239 (t (org-schedule nil value)))
16240 (if (member value '("earlier" "later" ""))
16241 (call-interactively #'org-schedule)
16242 (org-schedule nil value))))
16243 ((equal property "DEADLINE")
16244 (forward-line)
16245 (if (and (looking-at-p org-planning-line-re)
16246 (re-search-forward
16247 org-deadline-time-regexp (line-end-position) t))
16248 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16249 ((string= value "later") (org-timestamp-change 1 'day))
16250 ((string= value "") (org-deadline '(4)))
16251 (t (org-deadline nil value)))
16252 (if (member value '("earlier" "later" ""))
16253 (call-interactively #'org-deadline)
16254 (org-deadline nil value))))
16255 ((member property org-special-properties)
16256 (error "The %s property cannot be set with `org-entry-put'" property))
16258 (let* ((range (org-get-property-block beg 'force))
16259 (end (cdr range))
16260 (case-fold-search t))
16261 (goto-char (car range))
16262 (if (re-search-forward (org-re-property property nil t) end t)
16263 (progn (delete-region (match-beginning 0) (match-end 0))
16264 (goto-char (match-beginning 0)))
16265 (goto-char end)
16266 (insert "\n")
16267 (backward-char))
16268 (insert ":" property ":")
16269 (when value (insert " " value))
16270 (org-indent-line)))))
16271 (run-hook-with-args 'org-property-changed-functions property value)))
16273 (defun org-buffer-property-keys
16274 (&optional specials defaults columns ignore-malformed)
16275 "Get all property keys in the current buffer.
16277 When SPECIALS is non-nil, also list the special properties that
16278 reflect things like tags and TODO state.
16280 When DEFAULTS is non-nil, also include properties that has
16281 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16282 DESCRIPTION, LOCATION, and LOGGING and others.
16284 When COLUMNS in non-nil, also include property names given in
16285 COLUMN formats in the current buffer.
16287 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16288 automatically performed, such drawers will be silently ignored."
16289 (let ((case-fold-search t)
16290 (props (append
16291 (and specials org-special-properties)
16292 (and defaults (cons org-effort-property org-default-properties))
16293 nil)))
16294 (org-with-wide-buffer
16295 (goto-char (point-min))
16296 (while (re-search-forward org-property-start-re nil t)
16297 (let ((range (org-get-property-block)))
16298 (catch 'skip
16299 (unless range
16300 (when (and (not ignore-malformed)
16301 (not (org-before-first-heading-p))
16302 (y-or-n-p (format "Malformed drawer at %d, repair?"
16303 (line-beginning-position))))
16304 (org-get-property-block nil t))
16305 (throw 'skip nil))
16306 (goto-char (car range))
16307 (let ((begin (car range))
16308 (end (cdr range)))
16309 ;; Make sure that found property block is not located
16310 ;; before current point, as it would generate an infloop.
16311 ;; It can happen, for example, in the following
16312 ;; situation:
16314 ;; * Headline
16315 ;; :PROPERTIES:
16316 ;; ...
16317 ;; :END:
16318 ;; *************** Inlinetask
16319 ;; #+BEGIN_EXAMPLE
16320 ;; :PROPERTIES:
16321 ;; #+END_EXAMPLE
16323 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16324 (while (< (point) end)
16325 (let ((p (progn (looking-at org-property-re)
16326 (match-string-no-properties 2))))
16327 ;; Only add true property name, not extension symbol.
16328 (push (if (not (string-match-p "\\+\\'" p)) p
16329 (substring p 0 -1))
16330 props))
16331 (forward-line))))
16332 (outline-next-heading)))
16333 (when columns
16334 (goto-char (point-min))
16335 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16336 (let ((element (org-element-at-point)))
16337 (when (memq (org-element-type element) '(keyword node-property))
16338 (let ((value (org-element-property :value element))
16339 (start 0))
16340 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16341 (setq start (match-end 0))
16342 (let ((p (match-string-no-properties 1 value)))
16343 (unless (member-ignore-case p org-special-properties)
16344 (push p props))))))))))
16345 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16347 (defun org-property-values (key)
16348 "List all non-nil values of property KEY in current buffer."
16349 (org-with-wide-buffer
16350 (goto-char (point-min))
16351 (let ((case-fold-search t)
16352 (re (org-re-property key))
16353 values)
16354 (while (re-search-forward re nil t)
16355 (push (org-entry-get (point) key) values))
16356 (delete-dups values))))
16358 (defun org-insert-property-drawer ()
16359 "Insert a property drawer into the current entry."
16360 (org-with-wide-buffer
16361 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16362 (org-back-to-heading t)
16363 (org-with-limited-levels (org-back-to-heading t)))
16364 (forward-line)
16365 (when (looking-at-p org-planning-line-re) (forward-line))
16366 (unless (looking-at-p org-property-drawer-re)
16367 ;; Make sure we start editing a line from current entry, not from
16368 ;; next one. It prevents extending text properties or overlays
16369 ;; belonging to the latter.
16370 (when (bolp) (backward-char))
16371 (let ((begin (1+ (point)))
16372 (inhibit-read-only t))
16373 (insert "\n:PROPERTIES:\n:END:")
16374 (when (eobp) (insert "\n"))
16375 (org-indent-region begin (point))))))
16377 (defun org-insert-drawer (&optional arg drawer)
16378 "Insert a drawer at point.
16380 When optional argument ARG is non-nil, insert a property drawer.
16382 Optional argument DRAWER, when non-nil, is a string representing
16383 drawer's name. Otherwise, the user is prompted for a name.
16385 If a region is active, insert the drawer around that region
16386 instead.
16388 Point is left between drawer's boundaries."
16389 (interactive "P")
16390 (let* ((drawer (if arg "PROPERTIES"
16391 (or drawer (read-from-minibuffer "Drawer: ")))))
16392 (cond
16393 ;; With C-u, fall back on `org-insert-property-drawer'
16394 (arg (org-insert-property-drawer))
16395 ;; Check validity of suggested drawer's name.
16396 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16397 (user-error "Invalid drawer name"))
16398 ;; With an active region, insert a drawer at point.
16399 ((not (org-region-active-p))
16400 (progn
16401 (unless (bolp) (insert "\n"))
16402 (insert (format ":%s:\n\n:END:\n" drawer))
16403 (forward-line -2)))
16404 ;; Otherwise, insert the drawer at point
16406 (let ((rbeg (region-beginning))
16407 (rend (copy-marker (region-end))))
16408 (unwind-protect
16409 (progn
16410 (goto-char rbeg)
16411 (beginning-of-line)
16412 (when (save-excursion
16413 (re-search-forward org-outline-regexp-bol rend t))
16414 (user-error "Drawers cannot contain headlines"))
16415 ;; Position point at the beginning of the first
16416 ;; non-blank line in region. Insert drawer's opening
16417 ;; there, then indent it.
16418 (org-skip-whitespace)
16419 (beginning-of-line)
16420 (insert ":" drawer ":\n")
16421 (forward-line -1)
16422 (indent-for-tab-command)
16423 ;; Move point to the beginning of the first blank line
16424 ;; after the last non-blank line in region. Insert
16425 ;; drawer's closing, then indent it.
16426 (goto-char rend)
16427 (skip-chars-backward " \r\t\n")
16428 (insert "\n:END:")
16429 (deactivate-mark t)
16430 (indent-for-tab-command)
16431 (unless (eolp) (insert "\n")))
16432 ;; Clear marker, whatever the outcome of insertion is.
16433 (set-marker rend nil)))))))
16435 (defvar org-property-set-functions-alist nil
16436 "Property set function alist.
16437 Each entry should have the following format:
16439 (PROPERTY . READ-FUNCTION)
16441 The read function will be called with the same argument as
16442 `org-completing-read'.")
16444 (defun org-set-property-function (property)
16445 "Get the function that should be used to set PROPERTY.
16446 This is computed according to `org-property-set-functions-alist'."
16447 (or (cdr (assoc property org-property-set-functions-alist))
16448 'org-completing-read))
16450 (defun org-read-property-value (property)
16451 "Read PROPERTY value from user."
16452 (let* ((completion-ignore-case t)
16453 (allowed (org-property-get-allowed-values nil property 'table))
16454 (cur (org-entry-get nil property))
16455 (prompt (concat property " value"
16456 (if (and cur (string-match "\\S-" cur))
16457 (concat " [" cur "]") "") ": "))
16458 (set-function (org-set-property-function property))
16459 (val (if allowed
16460 (funcall set-function prompt allowed nil
16461 (not (get-text-property 0 'org-unrestricted
16462 (caar allowed))))
16463 (funcall set-function prompt
16464 (mapcar 'list (org-property-values property))
16465 nil nil "" nil cur))))
16466 (org-trim val)))
16468 (defvar org-last-set-property nil)
16469 (defvar org-last-set-property-value nil)
16470 (defun org-read-property-name ()
16471 "Read a property name."
16472 (let ((completion-ignore-case t)
16473 (default-prop (or (and (org-at-property-p)
16474 (match-string-no-properties 2))
16475 org-last-set-property)))
16476 (org-completing-read
16477 (concat "Property"
16478 (if default-prop (concat " [" default-prop "]") "")
16479 ": ")
16480 (mapcar #'list (org-buffer-property-keys nil t t))
16481 nil nil nil nil default-prop)))
16483 (defun org-set-property-and-value (use-last)
16484 "Allow to set [PROPERTY]: [value] direction from prompt.
16485 When use-default, don't even ask, just use the last
16486 \"[PROPERTY]: [value]\" string from the history."
16487 (interactive "P")
16488 (let* ((completion-ignore-case t)
16489 (pv (or (and use-last org-last-set-property-value)
16490 (org-completing-read
16491 "Enter a \"[Property]: [value]\" pair: "
16492 nil nil nil nil nil
16493 org-last-set-property-value)))
16494 prop val)
16495 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16496 (setq prop (match-string 1 pv)
16497 val (match-string 2 pv))
16498 (org-set-property prop val))))
16500 (defun org-set-property (property value)
16501 "In the current entry, set PROPERTY to VALUE.
16503 When called interactively, this will prompt for a property name, offering
16504 completion on existing and default properties. And then it will prompt
16505 for a value, offering completion either on allowed values (via an inherited
16506 xxx_ALL property) or on existing values in other instances of this property
16507 in the current file.
16509 Throw an error when trying to set a property with an invalid name."
16510 (interactive (list nil nil))
16511 (let ((property (or property (org-read-property-name))))
16512 ;; `org-entry-put' also makes the following check, but this one
16513 ;; avoids polluting `org-last-set-property' and
16514 ;; `org-last-set-property-value' needlessly.
16515 (unless (org--valid-property-p property)
16516 (user-error "Invalid property name: \"%s\"" property))
16517 (let ((value (or value (org-read-property-value property)))
16518 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16519 (setq org-last-set-property property)
16520 (setq org-last-set-property-value (concat property ": " value))
16521 ;; Possibly postprocess the inserted value:
16522 (when fn (setq value (funcall fn value)))
16523 (unless (equal (org-entry-get nil property) value)
16524 (org-entry-put nil property value)))))
16526 (defun org-find-property (property &optional value)
16527 "Find first entry in buffer that sets PROPERTY.
16529 When optional argument VALUE is non-nil, only consider an entry
16530 if it contains PROPERTY set to this value. If PROPERTY should be
16531 explicitly set to nil, use string \"nil\" for VALUE.
16533 Return position where the entry begins, or nil if there is no
16534 such entry. If narrowing is in effect, only search the visible
16535 part of the buffer."
16536 (save-excursion
16537 (goto-char (point-min))
16538 (let ((case-fold-search t)
16539 (re (org-re-property property nil (not value) value)))
16540 (catch 'exit
16541 (while (re-search-forward re nil t)
16542 (when (if value (org-at-property-p)
16543 (org-entry-get (point) property nil t))
16544 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16546 (defun org-delete-property (property)
16547 "In the current entry, delete PROPERTY."
16548 (interactive
16549 (let* ((completion-ignore-case t)
16550 (cat (org-entry-get (point) "CATEGORY"))
16551 (props0 (org-entry-properties nil 'standard))
16552 (props (if cat props0
16553 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16554 (prop (if (< 1 (length props))
16555 (completing-read "Property: " props nil t)
16556 (caar props))))
16557 (list prop)))
16558 (if (not property)
16559 (message "No property to delete in this entry")
16560 (org-entry-delete nil property)
16561 (message "Property \"%s\" deleted" property)))
16563 (defun org-delete-property-globally (property)
16564 "Remove PROPERTY globally, from all entries.
16565 This function ignores narrowing, if any."
16566 (interactive
16567 (let* ((completion-ignore-case t)
16568 (prop (completing-read
16569 "Globally remove property: "
16570 (mapcar #'list (org-buffer-property-keys)))))
16571 (list prop)))
16572 (org-with-wide-buffer
16573 (goto-char (point-min))
16574 (let ((count 0)
16575 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16576 (while (re-search-forward re nil t)
16577 (when (org-entry-delete (point) property) (cl-incf count)))
16578 (message "Property \"%s\" removed from %d entries" property count))))
16580 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16582 (defun org-compute-property-at-point ()
16583 "Compute the property at point.
16584 This looks for an enclosing column format, extracts the operator and
16585 then applies it to the property in the column format's scope."
16586 (interactive)
16587 (unless (org-at-property-p)
16588 (user-error "Not at a property"))
16589 (let ((prop (match-string-no-properties 2)))
16590 (org-columns-get-format-and-top-level)
16591 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16592 (user-error "No operator defined for property %s" prop))
16593 (org-columns-compute prop)))
16595 (defvar org-property-allowed-value-functions nil
16596 "Hook for functions supplying allowed values for a specific property.
16597 The functions must take a single argument, the name of the property, and
16598 return a flat list of allowed values. If \":ETC\" is one of
16599 the values, this means that these values are intended as defaults for
16600 completion, but that other values should be allowed too.
16601 The functions must return nil if they are not responsible for this
16602 property.")
16604 (defun org-property-get-allowed-values (pom property &optional table)
16605 "Get allowed values for the property PROPERTY.
16606 When TABLE is non-nil, return an alist that can directly be used for
16607 completion."
16608 (let (vals)
16609 (cond
16610 ((equal property "TODO")
16611 (setq vals (org-with-point-at pom
16612 (append org-todo-keywords-1 '("")))))
16613 ((equal property "PRIORITY")
16614 (let ((n org-lowest-priority))
16615 (while (>= n org-highest-priority)
16616 (push (char-to-string n) vals)
16617 (setq n (1- n)))))
16618 ((equal property "CATEGORY"))
16619 ((member property org-special-properties))
16620 ((setq vals (run-hook-with-args-until-success
16621 'org-property-allowed-value-functions property)))
16623 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16624 (when (and vals (string-match "\\S-" vals))
16625 (setq vals (car (read-from-string (concat "(" vals ")"))))
16626 (setq vals (mapcar (lambda (x)
16627 (cond ((stringp x) x)
16628 ((numberp x) (number-to-string x))
16629 ((symbolp x) (symbol-name x))
16630 (t "???")))
16631 vals)))))
16632 (when (member ":ETC" vals)
16633 (setq vals (remove ":ETC" vals))
16634 (org-add-props (car vals) '(org-unrestricted t)))
16635 (if table (mapcar 'list vals) vals)))
16637 (defun org-property-previous-allowed-value (&optional _previous)
16638 "Switch to the next allowed value for this property."
16639 (interactive)
16640 (org-property-next-allowed-value t))
16642 (defun org-property-next-allowed-value (&optional previous)
16643 "Switch to the next allowed value for this property."
16644 (interactive)
16645 (unless (org-at-property-p)
16646 (user-error "Not at a property"))
16647 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16648 (key (match-string 2))
16649 (value (match-string 3))
16650 (allowed (or (org-property-get-allowed-values (point) key)
16651 (and (member value '("[ ]" "[-]" "[X]"))
16652 '("[ ]" "[X]"))))
16653 (heading (save-match-data (nth 4 (org-heading-components))))
16654 nval)
16655 (unless allowed
16656 (user-error "Allowed values for this property have not been defined"))
16657 (when previous (setq allowed (reverse allowed)))
16658 (when (member value allowed)
16659 (setq nval (car (cdr (member value allowed)))))
16660 (setq nval (or nval (car allowed)))
16661 (when (equal nval value)
16662 (user-error "Only one allowed value for this property"))
16663 (org-at-property-p)
16664 (replace-match (concat " :" key ": " nval) t t)
16665 (org-indent-line)
16666 (beginning-of-line 1)
16667 (skip-chars-forward " \t")
16668 (when (equal prop org-effort-property)
16669 (org-refresh-property
16670 '((effort . identity)
16671 (effort-minutes . org-duration-string-to-minutes))
16672 nval)
16673 (when (string= org-clock-current-task heading)
16674 (setq org-clock-effort nval)
16675 (org-clock-update-mode-line)))
16676 (run-hook-with-args 'org-property-changed-functions key nval)))
16678 (defun org-find-olp (path &optional this-buffer)
16679 "Return a marker pointing to the entry at outline path OLP.
16680 If anything goes wrong, throw an error.
16681 You can wrap this call to catch the error like this:
16683 \(condition-case msg
16684 \(org-mobile-locate-entry (match-string 4))
16685 \(error (nth 1 msg)))
16687 The return value will then be either a string with the error message,
16688 or a marker if everything is OK.
16690 If THIS-BUFFER is set, the outline path does not contain a file,
16691 only headings."
16692 (let* ((file (if this-buffer buffer-file-name (pop path)))
16693 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16694 (level 1)
16695 (lmin 1)
16696 (lmax 1)
16697 end found flevel)
16698 (unless buffer (error "File not found :%s" file))
16699 (with-current-buffer buffer
16700 (org-with-wide-buffer
16701 (goto-char (point-min))
16702 (dolist (heading path)
16703 (let ((re (format org-complex-heading-regexp-format
16704 (regexp-quote heading)))
16705 (cnt 0))
16706 (while (re-search-forward re end t)
16707 (setq level (- (match-end 1) (match-beginning 1)))
16708 (when (and (>= level lmin) (<= level lmax))
16709 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16710 (when (= cnt 0)
16711 (error "Heading not found on level %d: %s" lmax heading))
16712 (when (> cnt 1)
16713 (error "Heading not unique on level %d: %s" lmax heading))
16714 (goto-char found)
16715 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16716 (setq end (save-excursion (org-end-of-subtree t t)))))
16717 (when (org-at-heading-p)
16718 (point-marker))))))
16720 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16721 "Find node HEADING in BUFFER.
16722 Return a marker to the heading if it was found, or nil if not.
16723 If POS-ONLY is set, return just the position instead of a marker.
16725 The heading text must match exact, but it may have a TODO keyword,
16726 a priority cookie and tags in the standard locations."
16727 (with-current-buffer (or buffer (current-buffer))
16728 (save-excursion
16729 (save-restriction
16730 (widen)
16731 (goto-char (point-min))
16732 (let (case-fold-search)
16733 (when (re-search-forward
16734 (format org-complex-heading-regexp-format
16735 (regexp-quote heading)) nil t)
16736 (if pos-only
16737 (match-beginning 0)
16738 (move-marker (make-marker) (match-beginning 0)))))))))
16740 (defun org-find-exact-heading-in-directory (heading &optional dir)
16741 "Find Org node headline HEADING in all .org files in directory DIR.
16742 When the target headline is found, return a marker to this location."
16743 (let ((files (directory-files (or dir default-directory)
16744 t "\\`[^.#].*\\.org\\'"))
16745 visiting m buffer)
16746 (catch 'found
16747 (dolist (file files)
16748 (message "trying %s" file)
16749 (setq visiting (org-find-base-buffer-visiting file))
16750 (setq buffer (or visiting (find-file-noselect file)))
16751 (setq m (org-find-exact-headline-in-buffer
16752 heading buffer))
16753 (when (and (not m) (not visiting)) (kill-buffer buffer))
16754 (and m (throw 'found m))))))
16756 (defun org-find-entry-with-id (ident)
16757 "Locate the entry that contains the ID property with exact value IDENT.
16758 IDENT can be a string, a symbol or a number, this function will search for
16759 the string representation of it.
16760 Return the position where this entry starts, or nil if there is no such entry."
16761 (interactive "sID: ")
16762 (let ((id (cond
16763 ((stringp ident) ident)
16764 ((symbolp ident) (symbol-name ident))
16765 ((numberp ident) (number-to-string ident))
16766 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16767 (org-with-wide-buffer (org-find-property "ID" id))))
16769 ;;;; Timestamps
16771 (defvar org-last-changed-timestamp nil)
16772 (defvar org-last-inserted-timestamp nil
16773 "The last time stamp inserted with `org-insert-time-stamp'.")
16774 (defvar org-ts-what) ; dynamically scoped parameter
16776 (defun org-time-stamp (arg &optional inactive)
16777 "Prompt for a date/time and insert a time stamp.
16779 If the user specifies a time like HH:MM or if this command is
16780 called with at least one prefix argument, the time stamp contains
16781 the date and the time. Otherwise, only the date is included.
16783 All parts of a date not specified by the user are filled in from
16784 the timestamp at point, if any, or the current date/time
16785 otherwise.
16787 If there is already a timestamp at the cursor, it is replaced.
16789 With two universal prefix arguments, insert an active timestamp
16790 with the current time without prompting the user.
16792 When called from lisp, the timestamp is inactive if INACTIVE is
16793 non-nil."
16794 (interactive "P")
16795 (let* ((ts (cond
16796 ((org-at-date-range-p t)
16797 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16798 ((org-at-timestamp-p t) (match-string 0))))
16799 ;; Default time is either the timestamp at point or today.
16800 ;; When entering a range, only the range start is considered.
16801 (default-time (if (not ts) (current-time)
16802 (apply #'encode-time (org-parse-time-string ts))))
16803 (default-input (and ts (org-get-compact-tod ts)))
16804 (repeater (and ts
16805 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16806 (match-string 0 ts)))
16807 org-time-was-given
16808 org-end-time-was-given
16809 (time
16810 (and (if (equal arg '(16)) (current-time)
16811 ;; Preserve `this-command' and `last-command'.
16812 (let ((this-command this-command)
16813 (last-command last-command))
16814 (org-read-date
16815 arg 'totime nil nil default-time default-input
16816 inactive))))))
16817 (cond
16818 ((and ts
16819 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16820 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16821 (insert "--")
16822 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16824 ;; Make sure we're on a timestamp. When in the middle of a date
16825 ;; range, move arbitrarily to range end.
16826 (unless (org-at-timestamp-p t)
16827 (skip-chars-forward "-")
16828 (org-at-timestamp-p t))
16829 (replace-match "")
16830 (setq org-last-changed-timestamp
16831 (org-insert-time-stamp
16832 time (or org-time-was-given arg)
16833 inactive nil nil (list org-end-time-was-given)))
16834 (when repeater
16835 (backward-char)
16836 (insert " " repeater)
16837 (setq org-last-changed-timestamp
16838 (concat (substring org-last-inserted-timestamp 0 -1)
16839 " " repeater ">")))
16840 (message "Timestamp updated"))
16841 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16842 (t (org-insert-time-stamp
16843 time (or org-time-was-given arg) inactive nil nil
16844 (list org-end-time-was-given))))))
16846 ;; FIXME: can we use this for something else, like computing time differences?
16847 (defun org-get-compact-tod (s)
16848 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16849 (let* ((t1 (match-string 1 s))
16850 (h1 (string-to-number (match-string 2 s)))
16851 (m1 (string-to-number (match-string 3 s)))
16852 (t2 (and (match-end 4) (match-string 5 s)))
16853 (h2 (and t2 (string-to-number (match-string 6 s))))
16854 (m2 (and t2 (string-to-number (match-string 7 s))))
16855 dh dm)
16856 (if (not t2)
16858 (setq dh (- h2 h1) dm (- m2 m1))
16859 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16860 (concat t1 "+" (number-to-string dh)
16861 (and (/= 0 dm) (format ":%02d" dm)))))))
16863 (defun org-time-stamp-inactive (&optional arg)
16864 "Insert an inactive time stamp.
16865 An inactive time stamp is enclosed in square brackets instead of angle
16866 brackets. It is inactive in the sense that it does not trigger agenda entries,
16867 does not link to the calendar and cannot be changed with the S-cursor keys.
16868 So these are more for recording a certain time/date."
16869 (interactive "P")
16870 (org-time-stamp arg 'inactive))
16872 (defvar org-date-ovl (make-overlay 1 1))
16873 (overlay-put org-date-ovl 'face 'org-date-selected)
16874 (delete-overlay org-date-ovl)
16876 (defvar org-ans1) ; dynamically scoped parameter
16877 (defvar org-ans2) ; dynamically scoped parameter
16879 (defvar org-plain-time-of-day-regexp) ; defined below
16881 (defvar org-overriding-default-time nil) ; dynamically scoped
16882 (defvar org-read-date-overlay nil)
16883 (defvar org-dcst nil) ; dynamically scoped
16884 (defvar org-read-date-history nil)
16885 (defvar org-read-date-final-answer nil)
16886 (defvar org-read-date-analyze-futurep nil)
16887 (defvar org-read-date-analyze-forced-year nil)
16888 (defvar org-read-date-inactive)
16890 (defvar org-read-date-minibuffer-local-map
16891 (let* ((map (make-sparse-keymap)))
16892 (set-keymap-parent map minibuffer-local-map)
16893 (org-defkey map (kbd ".")
16894 (lambda () (interactive)
16895 ;; Are we at the beginning of the prompt?
16896 (if (looking-back "^[^:]+: "
16897 (let ((inhibit-field-text-motion t))
16898 (line-beginning-position)))
16899 (org-eval-in-calendar '(calendar-goto-today))
16900 (insert "."))))
16901 (org-defkey map (kbd "C-.")
16902 (lambda () (interactive)
16903 (org-eval-in-calendar '(calendar-goto-today))))
16904 (org-defkey map [(meta shift left)]
16905 (lambda () (interactive)
16906 (org-eval-in-calendar '(calendar-backward-month 1))))
16907 (org-defkey map [(meta shift right)]
16908 (lambda () (interactive)
16909 (org-eval-in-calendar '(calendar-forward-month 1))))
16910 (org-defkey map [(meta shift up)]
16911 (lambda () (interactive)
16912 (org-eval-in-calendar '(calendar-backward-year 1))))
16913 (org-defkey map [(meta shift down)]
16914 (lambda () (interactive)
16915 (org-eval-in-calendar '(calendar-forward-year 1))))
16916 (org-defkey map [?\e (shift left)]
16917 (lambda () (interactive)
16918 (org-eval-in-calendar '(calendar-backward-month 1))))
16919 (org-defkey map [?\e (shift right)]
16920 (lambda () (interactive)
16921 (org-eval-in-calendar '(calendar-forward-month 1))))
16922 (org-defkey map [?\e (shift up)]
16923 (lambda () (interactive)
16924 (org-eval-in-calendar '(calendar-backward-year 1))))
16925 (org-defkey map [?\e (shift down)]
16926 (lambda () (interactive)
16927 (org-eval-in-calendar '(calendar-forward-year 1))))
16928 (org-defkey map [(shift up)]
16929 (lambda () (interactive)
16930 (org-eval-in-calendar '(calendar-backward-week 1))))
16931 (org-defkey map [(shift down)]
16932 (lambda () (interactive)
16933 (org-eval-in-calendar '(calendar-forward-week 1))))
16934 (org-defkey map [(shift left)]
16935 (lambda () (interactive)
16936 (org-eval-in-calendar '(calendar-backward-day 1))))
16937 (org-defkey map [(shift right)]
16938 (lambda () (interactive)
16939 (org-eval-in-calendar '(calendar-forward-day 1))))
16940 (org-defkey map "!"
16941 (lambda () (interactive)
16942 (org-eval-in-calendar '(diary-view-entries))
16943 (message "")))
16944 (org-defkey map ">"
16945 (lambda () (interactive)
16946 (org-eval-in-calendar '(calendar-scroll-left 1))))
16947 (org-defkey map "<"
16948 (lambda () (interactive)
16949 (org-eval-in-calendar '(calendar-scroll-right 1))))
16950 (org-defkey map "\C-v"
16951 (lambda () (interactive)
16952 (org-eval-in-calendar
16953 '(calendar-scroll-left-three-months 1))))
16954 (org-defkey map "\M-v"
16955 (lambda () (interactive)
16956 (org-eval-in-calendar
16957 '(calendar-scroll-right-three-months 1))))
16958 map)
16959 "Keymap for minibuffer commands when using `org-read-date'.")
16961 (defvar org-def)
16962 (defvar org-defdecode)
16963 (defvar org-with-time)
16965 (defvar calendar-setup) ; Dynamically scoped.
16966 (defun org-read-date (&optional with-time to-time from-string prompt
16967 default-time default-input inactive)
16968 "Read a date, possibly a time, and make things smooth for the user.
16969 The prompt will suggest to enter an ISO date, but you can also enter anything
16970 which will at least partially be understood by `parse-time-string'.
16971 Unrecognized parts of the date will default to the current day, month, year,
16972 hour and minute. If this command is called to replace a timestamp at point,
16973 or to enter the second timestamp of a range, the default time is taken
16974 from the existing stamp. Furthermore, the command prefers the future,
16975 so if you are giving a date where the year is not given, and the day-month
16976 combination is already past in the current year, it will assume you
16977 mean next year. For details, see the manual. A few examples:
16979 3-2-5 --> 2003-02-05
16980 feb 15 --> currentyear-02-15
16981 2/15 --> currentyear-02-15
16982 sep 12 9 --> 2009-09-12
16983 12:45 --> today 12:45
16984 22 sept 0:34 --> currentyear-09-22 0:34
16985 12 --> currentyear-currentmonth-12
16986 Fri --> nearest Friday after today
16987 -Tue --> last Tuesday
16988 etc.
16990 Furthermore you can specify a relative date by giving, as the *first* thing
16991 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16992 change in days weeks, months, years.
16993 With a single plus or minus, the date is relative to today. With a double
16994 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16995 +4d --> four days from today
16996 +4 --> same as above
16997 +2w --> two weeks from today
16998 ++5 --> five days from default date
17000 The function understands only English month and weekday abbreviations.
17002 While prompting, a calendar is popped up - you can also select the
17003 date with the mouse (button 1). The calendar shows a period of three
17004 months. To scroll it to other months, use the keys `>' and `<'.
17005 If you don't like the calendar, turn it off with
17006 (setq org-read-date-popup-calendar nil)
17008 With optional argument TO-TIME, the date will immediately be converted
17009 to an internal time.
17010 With an optional argument WITH-TIME, the prompt will suggest to
17011 also insert a time. Note that when WITH-TIME is not set, you can
17012 still enter a time, and this function will inform the calling routine
17013 about this change. The calling routine may then choose to change the
17014 format used to insert the time stamp into the buffer to include the time.
17015 With optional argument FROM-STRING, read from this string instead from
17016 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17017 the time/date that is used for everything that is not specified by the
17018 user."
17019 (require 'parse-time)
17020 (let* ((org-with-time with-time)
17021 (org-time-stamp-rounding-minutes
17022 (if (equal org-with-time '(16))
17023 '(0 0)
17024 org-time-stamp-rounding-minutes))
17025 (org-dcst org-display-custom-times)
17026 (ct (org-current-time))
17027 (org-def (or org-overriding-default-time default-time ct))
17028 (org-defdecode (decode-time org-def))
17029 (cur-frame (selected-frame))
17030 (mouse-autoselect-window nil) ; Don't let the mouse jump
17031 (calendar-setup
17032 (and (eq calendar-setup 'calendar-only) 'calendar-only))
17033 (calendar-move-hook nil)
17034 (calendar-view-diary-initially-flag nil)
17035 (calendar-view-holidays-initially-flag nil)
17036 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
17037 ;; Rationalize `org-def' and `org-defdecode', if required.
17038 (when (< (nth 2 org-defdecode) org-extend-today-until)
17039 (setf (nth 2 org-defdecode) -1)
17040 (setf (nth 1 org-defdecode) 59)
17041 (setq org-def (apply #'encode-time org-defdecode))
17042 (setq org-defdecode (decode-time org-def)))
17043 (let* ((timestr (format-time-string
17044 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
17045 org-def))
17046 (prompt (concat (if prompt (concat prompt " ") "")
17047 (format "Date+time [%s]: " timestr))))
17048 (cond
17049 (from-string (setq ans from-string))
17050 (org-read-date-popup-calendar
17051 (save-excursion
17052 (save-window-excursion
17053 (calendar)
17054 (when (eq calendar-setup 'calendar-only)
17055 (setq cal-frame
17056 (window-frame (get-buffer-window "*Calendar*" 'visible)))
17057 (select-frame cal-frame))
17058 (org-eval-in-calendar '(setq cursor-type nil) t)
17059 (unwind-protect
17060 (progn
17061 (calendar-forward-day (- (time-to-days org-def)
17062 (calendar-absolute-from-gregorian
17063 (calendar-current-date))))
17064 (org-eval-in-calendar nil t)
17065 (let* ((old-map (current-local-map))
17066 (map (copy-keymap calendar-mode-map))
17067 (minibuffer-local-map
17068 (copy-keymap org-read-date-minibuffer-local-map)))
17069 (org-defkey map (kbd "RET") 'org-calendar-select)
17070 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17071 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17072 (unwind-protect
17073 (progn
17074 (use-local-map map)
17075 (setq org-read-date-inactive inactive)
17076 (add-hook 'post-command-hook 'org-read-date-display)
17077 (setq org-ans0
17078 (read-string prompt
17079 default-input
17080 'org-read-date-history
17081 nil))
17082 ;; org-ans0: from prompt
17083 ;; org-ans1: from mouse click
17084 ;; org-ans2: from calendar motion
17085 (setq ans
17086 (concat org-ans0 " " (or org-ans1 org-ans2))))
17087 (remove-hook 'post-command-hook 'org-read-date-display)
17088 (use-local-map old-map)
17089 (when org-read-date-overlay
17090 (delete-overlay org-read-date-overlay)
17091 (setq org-read-date-overlay nil)))))
17092 (bury-buffer "*Calendar*")
17093 (when cal-frame
17094 (delete-frame cal-frame)
17095 (select-frame-set-input-focus cur-frame))))))
17097 (t ; Naked prompt only
17098 (unwind-protect
17099 (setq ans (read-string prompt default-input
17100 'org-read-date-history timestr))
17101 (when org-read-date-overlay
17102 (delete-overlay org-read-date-overlay)
17103 (setq org-read-date-overlay nil))))))
17105 (setq final (org-read-date-analyze ans org-def org-defdecode))
17107 (when org-read-date-analyze-forced-year
17108 (message "Year was forced into %s"
17109 (if org-read-date-force-compatible-dates
17110 "compatible range (1970-2037)"
17111 "range representable on this machine"))
17112 (ding))
17114 ;; One round trip to get rid of 34th of August and stuff like that....
17115 (setq final (decode-time (apply 'encode-time final)))
17117 (setq org-read-date-final-answer ans)
17119 (if to-time
17120 (apply 'encode-time final)
17121 (if (and (boundp 'org-time-was-given) org-time-was-given)
17122 (format "%04d-%02d-%02d %02d:%02d"
17123 (nth 5 final) (nth 4 final) (nth 3 final)
17124 (nth 2 final) (nth 1 final))
17125 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17127 (defun org-read-date-display ()
17128 "Display the current date prompt interpretation in the minibuffer."
17129 (when org-read-date-display-live
17130 (when org-read-date-overlay
17131 (delete-overlay org-read-date-overlay))
17132 (when (minibufferp (current-buffer))
17133 (save-excursion
17134 (end-of-line 1)
17135 (while (not (equal (buffer-substring
17136 (max (point-min) (- (point) 4)) (point))
17137 " "))
17138 (insert " ")))
17139 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17140 " " (or org-ans1 org-ans2)))
17141 (org-end-time-was-given nil)
17142 (f (org-read-date-analyze ans org-def org-defdecode))
17143 (fmts (if org-dcst
17144 org-time-stamp-custom-formats
17145 org-time-stamp-formats))
17146 (fmt (if (or org-with-time
17147 (and (boundp 'org-time-was-given) org-time-was-given))
17148 (cdr fmts)
17149 (car fmts)))
17150 (txt (format-time-string fmt (apply 'encode-time f)))
17151 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17152 (txt (concat "=> " txt)))
17153 (when (and org-end-time-was-given
17154 (string-match org-plain-time-of-day-regexp txt))
17155 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17156 org-end-time-was-given
17157 (substring txt (match-end 0)))))
17158 (when org-read-date-analyze-futurep
17159 (setq txt (concat txt " (=>F)")))
17160 (setq org-read-date-overlay
17161 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17162 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17164 (defun org-read-date-analyze (ans def defdecode)
17165 "Analyze the combined answer of the date prompt."
17166 ;; FIXME: cleanup and comment
17167 ;; Pass `current-time' result to `decode-time' (instead of calling
17168 ;; without arguments) so that only `current-time' has to be
17169 ;; overriden in tests.
17170 (let ((org-def def)
17171 (org-defdecode defdecode)
17172 (nowdecode (decode-time (current-time)))
17173 delta deltan deltaw deltadef year month day
17174 hour minute second wday pm h2 m2 tl wday1
17175 iso-year iso-weekday iso-week iso-date futurep kill-year)
17176 (setq org-read-date-analyze-futurep nil
17177 org-read-date-analyze-forced-year nil)
17178 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17179 (setq ans "+0"))
17181 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17182 (setq ans (replace-match "" t t ans)
17183 deltan (car delta)
17184 deltaw (nth 1 delta)
17185 deltadef (nth 2 delta)))
17187 ;; Check if there is an iso week date in there. If yes, store the
17188 ;; info and postpone interpreting it until the rest of the parsing
17189 ;; is done.
17190 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17191 (setq iso-year (when (match-end 1)
17192 (org-small-year-to-year
17193 (string-to-number (match-string 1 ans))))
17194 iso-weekday (when (match-end 3)
17195 (string-to-number (match-string 3 ans)))
17196 iso-week (string-to-number (match-string 2 ans)))
17197 (setq ans (replace-match "" t t ans)))
17199 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17200 (when (string-match
17201 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17202 (setq year (if (match-end 2)
17203 (string-to-number (match-string 2 ans))
17204 (progn (setq kill-year t)
17205 (string-to-number (format-time-string "%Y"))))
17206 month (string-to-number (match-string 3 ans))
17207 day (string-to-number (match-string 4 ans)))
17208 (setq year (org-small-year-to-year year))
17209 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17210 t nil ans)))
17212 ;; Help matching dotted european dates
17213 (when (string-match
17214 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17215 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17216 (setq kill-year t)
17217 (string-to-number (format-time-string "%Y")))
17218 day (string-to-number (match-string 1 ans))
17219 month (string-to-number (match-string 2 ans))
17220 ans (replace-match (format "%04d-%02d-%02d" year month day)
17221 t nil ans)))
17223 ;; Help matching american dates, like 5/30 or 5/30/7
17224 (when (string-match
17225 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17226 (setq year (if (match-end 4)
17227 (string-to-number (match-string 4 ans))
17228 (progn (setq kill-year t)
17229 (string-to-number (format-time-string "%Y"))))
17230 month (string-to-number (match-string 1 ans))
17231 day (string-to-number (match-string 2 ans)))
17232 (setq year (org-small-year-to-year year))
17233 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17234 t nil ans)))
17235 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17236 ;; If there is a time with am/pm, and *no* time without it, we convert
17237 ;; so that matching will be successful.
17238 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17239 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17240 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17241 (setq hour (string-to-number (match-string 1 ans))
17242 minute (if (match-end 3)
17243 (string-to-number (match-string 3 ans))
17245 pm (equal ?p
17246 (string-to-char (downcase (match-string 4 ans)))))
17247 (if (and (= hour 12) (not pm))
17248 (setq hour 0)
17249 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17250 (setq ans (replace-match (format "%02d:%02d" hour minute)
17251 t t ans))))
17253 ;; Check if a time range is given as a duration
17254 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17255 (setq hour (string-to-number (match-string 1 ans))
17256 h2 (+ hour (string-to-number (match-string 3 ans)))
17257 minute (string-to-number (match-string 2 ans))
17258 m2 (+ minute (if (match-end 5) (string-to-number
17259 (match-string 5 ans))0)))
17260 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17261 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17262 t t ans)))
17264 ;; Check if there is a time range
17265 (when (boundp 'org-end-time-was-given)
17266 (setq org-time-was-given nil)
17267 (when (and (string-match org-plain-time-of-day-regexp ans)
17268 (match-end 8))
17269 (setq org-end-time-was-given (match-string 8 ans))
17270 (setq ans (concat (substring ans 0 (match-beginning 7))
17271 (substring ans (match-end 7))))))
17273 (setq tl (parse-time-string ans)
17274 day (or (nth 3 tl) (nth 3 org-defdecode))
17275 month
17276 (cond ((nth 4 tl))
17277 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17278 ;; Day was specified. Make sure DAY+MONTH
17279 ;; combination happens in the future.
17280 ((nth 3 tl)
17281 (setq futurep t)
17282 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17283 (nth 4 nowdecode)))
17284 (t (nth 4 org-defdecode)))
17285 year
17286 (cond ((and (not kill-year) (nth 5 tl)))
17287 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17288 ;; Month was guessed in the future and is at least
17289 ;; equal to NOWDECODE's. Fix year accordingly.
17290 (futurep
17291 (if (or (> month (nth 4 nowdecode))
17292 (>= day (nth 3 nowdecode)))
17293 (nth 5 nowdecode)
17294 (1+ (nth 5 nowdecode))))
17295 ;; Month was specified. Make sure MONTH+YEAR
17296 ;; combination happens in the future.
17297 ((nth 4 tl)
17298 (setq futurep t)
17299 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17300 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17301 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17302 (t (nth 5 nowdecode))))
17303 (t (nth 5 org-defdecode)))
17304 hour (or (nth 2 tl) (nth 2 org-defdecode))
17305 minute (or (nth 1 tl) (nth 1 org-defdecode))
17306 second (or (nth 0 tl) 0)
17307 wday (nth 6 tl))
17309 (when (and (eq org-read-date-prefer-future 'time)
17310 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17311 (equal day (nth 3 nowdecode))
17312 (equal month (nth 4 nowdecode))
17313 (equal year (nth 5 nowdecode))
17314 (nth 2 tl)
17315 (or (< (nth 2 tl) (nth 2 nowdecode))
17316 (and (= (nth 2 tl) (nth 2 nowdecode))
17317 (nth 1 tl)
17318 (< (nth 1 tl) (nth 1 nowdecode)))))
17319 (setq day (1+ day)
17320 futurep t))
17322 ;; Special date definitions below
17323 (cond
17324 (iso-week
17325 ;; There was an iso week
17326 (require 'cal-iso)
17327 (setq futurep nil)
17328 (setq year (or iso-year year)
17329 day (or iso-weekday wday 1)
17330 wday nil ; to make sure that the trigger below does not match
17331 iso-date (calendar-gregorian-from-absolute
17332 (calendar-iso-to-absolute
17333 (list iso-week day year))))
17334 ; FIXME: Should we also push ISO weeks into the future?
17335 ; (when (and org-read-date-prefer-future
17336 ; (not iso-year)
17337 ; (< (calendar-absolute-from-gregorian iso-date)
17338 ; (time-to-days (current-time))))
17339 ; (setq year (1+ year)
17340 ; iso-date (calendar-gregorian-from-absolute
17341 ; (calendar-iso-to-absolute
17342 ; (list iso-week day year)))))
17343 (setq month (car iso-date)
17344 year (nth 2 iso-date)
17345 day (nth 1 iso-date)))
17346 (deltan
17347 (setq futurep nil)
17348 (unless deltadef
17349 ;; Pass `current-time' result to `decode-time' (instead of
17350 ;; calling without arguments) so that only `current-time' has
17351 ;; to be overriden in tests.
17352 (let ((now (decode-time (current-time))))
17353 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17354 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17355 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17356 ((equal deltaw "m") (setq month (+ month deltan)))
17357 ((equal deltaw "y") (setq year (+ year deltan)))))
17358 ((and wday (not (nth 3 tl)))
17359 ;; Weekday was given, but no day, so pick that day in the week
17360 ;; on or after the derived date.
17361 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17362 (unless (equal wday wday1)
17363 (setq day (+ day (% (- wday wday1 -7) 7))))))
17364 (when (and (boundp 'org-time-was-given)
17365 (nth 2 tl))
17366 (setq org-time-was-given t))
17367 (when (< year 100) (setq year (+ 2000 year)))
17368 ;; Check of the date is representable
17369 (if org-read-date-force-compatible-dates
17370 (progn
17371 (when (< year 1970)
17372 (setq year 1970 org-read-date-analyze-forced-year t))
17373 (when (> year 2037)
17374 (setq year 2037 org-read-date-analyze-forced-year t)))
17375 (condition-case nil
17376 (ignore (encode-time second minute hour day month year))
17377 (error
17378 (setq year (nth 5 org-defdecode))
17379 (setq org-read-date-analyze-forced-year t))))
17380 (setq org-read-date-analyze-futurep futurep)
17381 (list second minute hour day month year)))
17383 (defvar parse-time-weekdays)
17384 (defun org-read-date-get-relative (s today default)
17385 "Check string S for special relative date string.
17386 TODAY and DEFAULT are internal times, for today and for a default.
17387 Return shift list (N what def-flag)
17388 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17389 N is the number of WHATs to shift.
17390 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17391 the DEFAULT date rather than TODAY."
17392 (require 'parse-time)
17393 (when (and
17394 (string-match
17395 (concat
17396 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17397 "\\([0-9]+\\)?"
17398 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17399 "\\([ \t]\\|$\\)") s)
17400 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17401 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17402 (string-to-char (substring (match-string 1 s) -1))
17403 ?+))
17404 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17405 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17406 (what (if (match-end 3) (match-string 3 s) "d"))
17407 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17408 (date (if rel default today))
17409 (wday (nth 6 (decode-time date)))
17410 delta)
17411 (if wday1
17412 (progn
17413 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17414 (when (= delta 0) (setq delta 7))
17415 (when (= dir ?-)
17416 (setq delta (- delta 7))
17417 (when (= delta 0) (setq delta -7)))
17418 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17419 (list delta "d" rel))
17420 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17422 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17423 "Turn a user-specified date into the internal representation.
17424 The internal representation needed by the calendar is (month day year).
17425 This is a wrapper to handle the brain-dead convention in calendar that
17426 user function argument order change dependent on argument order."
17427 (pcase calendar-date-style
17428 (`american (list arg1 arg2 arg3))
17429 (`european (list arg2 arg1 arg3))
17430 (`iso (list arg2 arg3 arg1))))
17432 (defun org-eval-in-calendar (form &optional keepdate)
17433 "Eval FORM in the calendar window and return to current window.
17434 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17435 (let ((sf (selected-frame))
17436 (sw (selected-window)))
17437 (select-window (get-buffer-window "*Calendar*" t))
17438 (eval form)
17439 (when (and (not keepdate) (calendar-cursor-to-date))
17440 (let* ((date (calendar-cursor-to-date))
17441 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17442 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17443 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17444 (select-window sw)
17445 (select-frame-set-input-focus sf)))
17447 (defun org-calendar-select ()
17448 "Return to `org-read-date' with the date currently selected.
17449 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17450 (interactive)
17451 (when (calendar-cursor-to-date)
17452 (let* ((date (calendar-cursor-to-date))
17453 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17454 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17455 (when (active-minibuffer-window) (exit-minibuffer))))
17457 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17458 "Insert a date stamp for the date given by the internal TIME.
17459 See `format-time-string' for the format of TIME.
17460 WITH-HM means use the stamp format that includes the time of the day.
17461 INACTIVE means use square brackets instead of angular ones, so that the
17462 stamp will not contribute to the agenda.
17463 PRE and POST are optional strings to be inserted before and after the
17464 stamp.
17465 The command returns the inserted time stamp."
17466 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17467 stamp)
17468 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17469 (insert-before-markers (or pre ""))
17470 (when (listp extra)
17471 (setq extra (car extra))
17472 (if (and (stringp extra)
17473 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17474 (setq extra (format "-%02d:%02d"
17475 (string-to-number (match-string 1 extra))
17476 (string-to-number (match-string 2 extra))))
17477 (setq extra nil)))
17478 (when extra
17479 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17480 (insert-before-markers (setq stamp (format-time-string fmt time)))
17481 (insert-before-markers (or post ""))
17482 (setq org-last-inserted-timestamp stamp)))
17484 (defun org-toggle-time-stamp-overlays ()
17485 "Toggle the use of custom time stamp formats."
17486 (interactive)
17487 (setq org-display-custom-times (not org-display-custom-times))
17488 (unless org-display-custom-times
17489 (let ((p (point-min)) (bmp (buffer-modified-p)))
17490 (while (setq p (next-single-property-change p 'display))
17491 (when (and (get-text-property p 'display)
17492 (eq (get-text-property p 'face) 'org-date))
17493 (remove-text-properties
17494 p (setq p (next-single-property-change p 'display))
17495 '(display t))))
17496 (set-buffer-modified-p bmp)))
17497 (org-restart-font-lock)
17498 (setq org-table-may-need-update t)
17499 (if org-display-custom-times
17500 (message "Time stamps are overlaid with custom format")
17501 (message "Time stamp overlays removed")))
17503 (defun org-display-custom-time (beg end)
17504 "Overlay modified time stamp format over timestamp between BEG and END."
17505 (let* ((ts (buffer-substring beg end))
17506 t1 w1 with-hm tf time str w2 (off 0))
17507 (save-match-data
17508 (setq t1 (org-parse-time-string ts t))
17509 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17510 (setq off (- (match-end 0) (match-beginning 0)))))
17511 (setq end (- end off))
17512 (setq w1 (- end beg)
17513 with-hm (and (nth 1 t1) (nth 2 t1))
17514 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17515 time (org-fix-decoded-time t1)
17516 str (org-add-props
17517 (format-time-string
17518 (substring tf 1 -1) (apply 'encode-time time))
17519 nil 'mouse-face 'highlight)
17520 w2 (length str))
17521 (unless (= w2 w1)
17522 (add-text-properties (1+ beg) (+ 2 beg)
17523 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17524 (put-text-property beg end 'display str)))
17526 (defun org-fix-decoded-time (time)
17527 "Set 0 instead of nil for the first 6 elements of time.
17528 Don't touch the rest."
17529 (let ((n 0))
17530 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17532 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17533 "Difference between TIMESTAMP-STRING and now in days.
17534 If SECONDS is non-nil, return the difference in seconds."
17535 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17536 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17537 (funcall fdiff (current-time)))))
17539 (defun org-deadline-close-p (timestamp-string &optional ndays)
17540 "Is the time in TIMESTAMP-STRING close to the current date?"
17541 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17542 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17543 (not (org-entry-is-done-p))))
17545 (defun org-get-wdays (ts &optional delay zero-delay)
17546 "Get the deadline lead time appropriate for timestring TS.
17547 When DELAY is non-nil, get the delay time for scheduled items
17548 instead of the deadline lead time. When ZERO-DELAY is non-nil
17549 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17550 don't try to find the delay cookie in the scheduled timestamp."
17551 (let ((tv (if delay org-scheduled-delay-days
17552 org-deadline-warning-days)))
17553 (cond
17554 ((or (and delay (< tv 0))
17555 (and delay zero-delay (<= tv 0))
17556 (and (not delay) (<= tv 0)))
17557 ;; Enforce this value no matter what
17558 (- tv))
17559 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17560 ;; lead time is specified.
17561 (floor (* (string-to-number (match-string 1 ts))
17562 (cdr (assoc (match-string 2 ts)
17563 '(("d" . 1) ("w" . 7)
17564 ("m" . 30.4) ("y" . 365.25)
17565 ("h" . 0.041667)))))))
17566 ;; go for the default.
17567 (t tv))))
17569 (defun org-calendar-select-mouse (ev)
17570 "Return to `org-read-date' with the date currently selected.
17571 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17572 (interactive "e")
17573 (mouse-set-point ev)
17574 (when (calendar-cursor-to-date)
17575 (let* ((date (calendar-cursor-to-date))
17576 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17577 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17578 (when (active-minibuffer-window) (exit-minibuffer))))
17580 (defun org-check-deadlines (ndays)
17581 "Check if there are any deadlines due or past due.
17582 A deadline is considered due if it happens within `org-deadline-warning-days'
17583 days from today's date. If the deadline appears in an entry marked DONE,
17584 it is not shown. The prefix arg NDAYS can be used to test that many
17585 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17586 (interactive "P")
17587 (let* ((org-warn-days
17588 (cond
17589 ((equal ndays '(4)) 100000)
17590 (ndays (prefix-numeric-value ndays))
17591 (t (abs org-deadline-warning-days))))
17592 (case-fold-search nil)
17593 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17594 (callback
17595 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17596 (message "%d deadlines past-due or due within %d days"
17597 (org-occur regexp nil callback)
17598 org-warn-days)))
17600 (defsubst org-re-timestamp (type)
17601 "Return a regexp for timestamp TYPE.
17602 Allowed values for TYPE are:
17604 all: all timestamps
17605 active: only active timestamps (<...>)
17606 inactive: only inactive timestamps ([...])
17607 scheduled: only scheduled timestamps
17608 deadline: only deadline timestamps
17609 closed: only closed time-stamps
17611 When TYPE is nil, fall back on returning a regexp that matches
17612 both scheduled and deadline timestamps."
17613 (cl-case type
17614 (all org-ts-regexp-both)
17615 (active org-ts-regexp)
17616 (inactive org-ts-regexp-inactive)
17617 (scheduled org-scheduled-time-regexp)
17618 (deadline org-deadline-time-regexp)
17619 (closed org-closed-time-regexp)
17620 (otherwise
17621 (concat "\\<"
17622 (regexp-opt (list org-deadline-string org-scheduled-string))
17623 " *<\\([^>]+\\)>"))))
17625 (defun org-check-before-date (d)
17626 "Check if there are deadlines or scheduled entries before date D."
17627 (interactive (list (org-read-date)))
17628 (let* ((case-fold-search nil)
17629 (regexp (org-re-timestamp org-ts-type))
17630 (ts-type org-ts-type)
17631 (callback
17632 (lambda ()
17633 (let ((match (match-string 1)))
17634 (and (if (memq ts-type '(active inactive all))
17635 (eq (org-element-type (save-excursion
17636 (backward-char)
17637 (org-element-context)))
17638 'timestamp)
17639 (org-at-planning-p))
17640 (time-less-p
17641 (org-time-string-to-time match)
17642 (org-time-string-to-time d)))))))
17643 (message "%d entries before %s"
17644 (org-occur regexp nil callback)
17645 d)))
17647 (defun org-check-after-date (d)
17648 "Check if there are deadlines or scheduled entries after date D."
17649 (interactive (list (org-read-date)))
17650 (let* ((case-fold-search nil)
17651 (regexp (org-re-timestamp org-ts-type))
17652 (ts-type org-ts-type)
17653 (callback
17654 (lambda ()
17655 (let ((match (match-string 1)))
17656 (and (if (memq ts-type '(active inactive all))
17657 (eq (org-element-type (save-excursion
17658 (backward-char)
17659 (org-element-context)))
17660 'timestamp)
17661 (org-at-planning-p))
17662 (not (time-less-p
17663 (org-time-string-to-time match)
17664 (org-time-string-to-time d))))))))
17665 (message "%d entries after %s"
17666 (org-occur regexp nil callback)
17667 d)))
17669 (defun org-check-dates-range (start-date end-date)
17670 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17671 (interactive (list (org-read-date nil nil nil "Range starts")
17672 (org-read-date nil nil nil "Range end")))
17673 (let ((case-fold-search nil)
17674 (regexp (org-re-timestamp org-ts-type))
17675 (callback
17676 (let ((type org-ts-type))
17677 (lambda ()
17678 (let ((match (match-string 1)))
17679 (and
17680 (if (memq type '(active inactive all))
17681 (eq (org-element-type (save-excursion
17682 (backward-char)
17683 (org-element-context)))
17684 'timestamp)
17685 (org-at-planning-p))
17686 (not (time-less-p
17687 (org-time-string-to-time match)
17688 (org-time-string-to-time start-date)))
17689 (time-less-p
17690 (org-time-string-to-time match)
17691 (org-time-string-to-time end-date))))))))
17692 (message "%d entries between %s and %s"
17693 (org-occur regexp nil callback) start-date end-date)))
17695 (defun org-evaluate-time-range (&optional to-buffer)
17696 "Evaluate a time range by computing the difference between start and end.
17697 Normally the result is just printed in the echo area, but with prefix arg
17698 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17699 If the time range is actually in a table, the result is inserted into the
17700 next column.
17701 For time difference computation, a year is assumed to be exactly 365
17702 days in order to avoid rounding problems."
17703 (interactive "P")
17705 (org-clock-update-time-maybe)
17706 (save-excursion
17707 (unless (org-at-date-range-p t)
17708 (goto-char (point-at-bol))
17709 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17710 (unless (org-at-date-range-p t)
17711 (user-error "Not at a time-stamp range, and none found in current line")))
17712 (let* ((ts1 (match-string 1))
17713 (ts2 (match-string 2))
17714 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17715 (match-end (match-end 0))
17716 (time1 (org-time-string-to-time ts1))
17717 (time2 (org-time-string-to-time ts2))
17718 (t1 (float-time time1))
17719 (t2 (float-time time2))
17720 (diff (abs (- t2 t1)))
17721 (negative (< (- t2 t1) 0))
17722 ;; (ys (floor (* 365 24 60 60)))
17723 (ds (* 24 60 60))
17724 (hs (* 60 60))
17725 (fy "%dy %dd %02d:%02d")
17726 (fy1 "%dy %dd")
17727 (fd "%dd %02d:%02d")
17728 (fd1 "%dd")
17729 (fh "%02d:%02d")
17730 y d h m align)
17731 (if havetime
17732 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17734 d (floor (/ diff ds)) diff (mod diff ds)
17735 h (floor (/ diff hs)) diff (mod diff hs)
17736 m (floor (/ diff 60)))
17737 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17739 d (floor (+ (/ diff ds) 0.5))
17740 h 0 m 0))
17741 (if (not to-buffer)
17742 (message "%s" (org-make-tdiff-string y d h m))
17743 (if (org-at-table-p)
17744 (progn
17745 (goto-char match-end)
17746 (setq align t)
17747 (and (looking-at " *|") (goto-char (match-end 0))))
17748 (goto-char match-end))
17749 (when (looking-at
17750 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17751 (replace-match ""))
17752 (when negative (insert " -"))
17753 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17754 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17755 (insert " " (format fh h m))))
17756 (when align (org-table-align))
17757 (message "Time difference inserted")))))
17759 (defun org-make-tdiff-string (y d h m)
17760 (let ((fmt "")
17761 (l nil))
17762 (when (> y 0)
17763 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17764 (push y l))
17765 (when (> d 0)
17766 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17767 (push d l))
17768 (when (> h 0)
17769 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17770 (push h l))
17771 (when (> m 0)
17772 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17773 (push m l))
17774 (apply 'format fmt (nreverse l))))
17776 (defun org-time-string-to-time (s &optional buffer pos)
17777 "Convert a timestamp string into internal time."
17778 (condition-case errdata
17779 (apply 'encode-time (org-parse-time-string s))
17780 (error (error "Bad timestamp `%s'%s\nError was: %s"
17781 s (if (not (and buffer pos))
17783 (format-message " at %d in buffer `%s'" pos buffer))
17784 (cdr errdata)))))
17786 (defun org-time-string-to-seconds (s)
17787 "Convert a timestamp string to a number of seconds."
17788 (float-time (org-time-string-to-time s)))
17790 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17792 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17793 "Convert time stamp S to an absolute day number.
17795 If DAYNR in non-nil, and there is a specifier for a cyclic time
17796 stamp, get the closest date to DAYNR. If PREFER is
17797 `past' (respectively `future') return a date past (respectively
17798 after) or equal to DAYNR.
17800 POS is the location of time stamp S, as a buffer position in
17801 BUFFER.
17803 Diary sexp timestamps are matched against DAYNR, when non-nil.
17804 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17805 signalled."
17806 (cond
17807 ((string-match "\\`%%\\((.*)\\)" s)
17808 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17809 ;; only able to match individual dates. If it fails, raise an
17810 ;; error.
17811 (if (and daynr
17812 (org-diary-sexp-entry
17813 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17814 daynr
17815 (signal 'org-diary-sexp-no-match (list s))))
17816 ((and daynr show-all) (org-closest-date s daynr prefer))
17817 (t (time-to-days
17818 (condition-case errdata
17819 (apply #'encode-time (org-parse-time-string s))
17820 (error (error "Bad timestamp `%s'%s\nError was: %s"
17822 (if (not (and buffer pos)) ""
17823 (format-message " at %d in buffer `%s'" pos buffer))
17824 (cdr errdata))))))))
17826 (defun org-days-to-iso-week (days)
17827 "Return the iso week number."
17828 (require 'cal-iso)
17829 (car (calendar-iso-from-absolute days)))
17831 (defun org-small-year-to-year (year)
17832 "Convert 2-digit years into 4-digit years.
17833 YEAR is expanded into one of the 30 next years, if possible, or
17834 into a past one. Any year larger than 99 is returned unchanged."
17835 (if (>= year 100) year
17836 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17837 (century (/ current 100))
17838 (offset (- year (% current 100))))
17839 (cond ((> offset 30) (+ (* (1- century) 100) year))
17840 ((> offset -70) (+ (* century 100) year))
17841 (t (+ (* (1+ century) 100) year))))))
17843 (defun org-time-from-absolute (d)
17844 "Return the time corresponding to date D.
17845 D may be an absolute day number, or a calendar-type list (month day year)."
17846 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17847 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17849 (defvar org-agenda-current-date)
17850 (defun org-calendar-holiday ()
17851 "List of holidays, for Diary display in Org mode."
17852 (require 'holidays)
17853 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17854 (and hl (mapconcat #'identity hl "; "))))
17856 (defun org-diary-sexp-entry (sexp entry d)
17857 "Process a SEXP diary ENTRY for date D."
17858 (require 'diary-lib)
17859 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17860 ;; dynamically.
17861 (let* ((sexp `(let ((entry ,entry)
17862 (date ',d))
17863 ,(car (read-from-string sexp))))
17864 (result (if calendar-debug-sexp (eval sexp)
17865 (condition-case nil
17866 (eval sexp)
17867 (error
17868 (beep)
17869 (message "Bad sexp at line %d in %s: %s"
17870 (org-current-line)
17871 (buffer-file-name) sexp)
17872 (sleep-for 2))))))
17873 (cond ((stringp result) (split-string result "; "))
17874 ((and (consp result)
17875 (not (consp (cdr result)))
17876 (stringp (cdr result))) (cdr result))
17877 ((and (consp result)
17878 (stringp (car result))) result)
17879 (result entry))))
17881 (defun org-diary-to-ical-string (frombuf)
17882 "Get iCalendar entries from diary entries in buffer FROMBUF.
17883 This uses the icalendar.el library."
17884 (let* ((tmpdir temporary-file-directory)
17885 (tmpfile (make-temp-name
17886 (expand-file-name "orgics" tmpdir)))
17887 buf rtn b e)
17888 (with-current-buffer frombuf
17889 (icalendar-export-region (point-min) (point-max) tmpfile)
17890 (setq buf (find-buffer-visiting tmpfile))
17891 (set-buffer buf)
17892 (goto-char (point-min))
17893 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17894 (setq b (match-beginning 0)))
17895 (goto-char (point-max))
17896 (when (re-search-backward "^END:VEVENT" nil t)
17897 (setq e (match-end 0)))
17898 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17899 (kill-buffer buf)
17900 (delete-file tmpfile)
17901 rtn))
17903 (defun org-closest-date (start current prefer)
17904 "Return closest date to CURRENT starting from START.
17906 CURRENT and START are both time stamps.
17908 When PREFER is `past', return a date that is either CURRENT or
17909 past. When PREFER is `future', return a date that is either
17910 CURRENT or future.
17912 Only time stamps with a repeater are modified. Any other time
17913 stamp stay unchanged. In any case, return value is an absolute
17914 day number."
17915 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17916 ;; No repeater. Do not shift time stamp.
17917 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17918 (let ((value (string-to-number (match-string 1 start)))
17919 (type (match-string 2 start)))
17920 (if (= 0 value)
17921 ;; Repeater with a 0-value is considered as void.
17922 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17923 (let* ((base (org-date-to-gregorian start))
17924 (target (org-date-to-gregorian current))
17925 (sday (calendar-absolute-from-gregorian base))
17926 (cday (calendar-absolute-from-gregorian target))
17927 n1 n2)
17928 ;; If START is already past CURRENT, just return START.
17929 (if (<= cday sday) sday
17930 ;; Compute closest date before (N1) and closest date past
17931 ;; (N2) CURRENT.
17932 (pcase type
17933 ("h"
17934 (let ((missing-hours
17935 (mod (+ (- (* 24 (- cday sday))
17936 (nth 2 (org-parse-time-string start)))
17937 org-extend-today-until)
17938 value)))
17939 (setf n1 (if (= missing-hours 0) cday
17940 (- cday (1+ (/ missing-hours 24)))))
17941 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17942 ((or "d" "w")
17943 (let ((value (if (equal type "w") (* 7 value) value)))
17944 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17945 (setf n2 (+ n1 value))))
17946 ("m"
17947 (let* ((add-months
17948 (lambda (d n)
17949 ;; Add N months to gregorian date D, i.e.,
17950 ;; a list (MONTH DAY YEAR). Return a valid
17951 ;; gregorian date.
17952 (let ((m (+ (nth 0 d) n)))
17953 (list (mod m 12)
17954 (nth 1 d)
17955 (+ (/ m 12) (nth 2 d))))))
17956 (months ; Complete months to TARGET.
17957 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17958 (- (nth 0 target) (nth 0 base))
17959 ;; If START's day is greater than
17960 ;; TARGET's, remove incomplete month.
17961 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17962 value)
17963 value))
17964 (before (funcall add-months base months)))
17965 (setf n1 (calendar-absolute-from-gregorian before))
17966 (setf n2
17967 (calendar-absolute-from-gregorian
17968 (funcall add-months before value)))))
17970 (let* ((d (nth 1 base))
17971 (m (nth 0 base))
17972 (y (nth 2 base))
17973 (years ; Complete years to TARGET.
17974 (* (/ (- (nth 2 target)
17976 ;; If START's month and day are
17977 ;; greater than TARGET's, remove
17978 ;; incomplete year.
17979 (if (or (> (nth 0 target) m)
17980 (and (= (nth 0 target) m)
17981 (> (nth 1 target) d)))
17984 value)
17985 value))
17986 (before (list m d (+ y years))))
17987 (setf n1 (calendar-absolute-from-gregorian before))
17988 (setf n2 (calendar-absolute-from-gregorian
17989 (list m d (+ (nth 2 before) value)))))))
17990 ;; Handle PREFER parameter, if any.
17991 (cond
17992 ((eq prefer 'past) (if (= cday n2) n2 n1))
17993 ((eq prefer 'future) (if (= cday n1) n1 n2))
17994 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17996 (defun org-date-to-gregorian (d)
17997 "Turn any specification of date D into a Gregorian date for the calendar."
17998 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17999 ((and (listp d) (= (length d) 3)) d)
18000 ((stringp d)
18001 (let ((d (org-parse-time-string d)))
18002 (list (nth 4 d) (nth 3 d) (nth 5 d))))
18003 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
18005 (defun org-parse-time-string (s &optional nodefault)
18006 "Parse the standard Org time string.
18007 This should be a lot faster than the normal `parse-time-string'.
18008 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18009 hour and minute fields will be nil if not given."
18010 (cond ((string-match org-ts-regexp0 s)
18011 (list 0
18012 (when (or (match-beginning 8) (not nodefault))
18013 (string-to-number (or (match-string 8 s) "0")))
18014 (when (or (match-beginning 7) (not nodefault))
18015 (string-to-number (or (match-string 7 s) "0")))
18016 (string-to-number (match-string 4 s))
18017 (string-to-number (match-string 3 s))
18018 (string-to-number (match-string 2 s))
18019 nil nil nil))
18020 ((string-match "^<[^>]+>$" s)
18021 (decode-time (seconds-to-time (org-matcher-time s))))
18022 (t (error "Not a standard Org time string: %s" s))))
18024 (defun org-timestamp-up (&optional arg)
18025 "Increase the date item at the cursor by one.
18026 If the cursor is on the year, change the year. If it is on the month,
18027 the day or the time, change that.
18028 With prefix ARG, change by that many units."
18029 (interactive "p")
18030 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
18032 (defun org-timestamp-down (&optional arg)
18033 "Decrease the date item at the cursor by one.
18034 If the cursor is on the year, change the year. If it is on the month,
18035 the day or the time, change that.
18036 With prefix ARG, change by that many units."
18037 (interactive "p")
18038 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
18040 (defun org-timestamp-up-day (&optional arg)
18041 "Increase the date in the time stamp by one day.
18042 With prefix ARG, change that many days."
18043 (interactive "p")
18044 (if (and (not (org-at-timestamp-p t))
18045 (org-at-heading-p))
18046 (org-todo 'up)
18047 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
18049 (defun org-timestamp-down-day (&optional arg)
18050 "Decrease the date in the time stamp by one day.
18051 With prefix ARG, change that many days."
18052 (interactive "p")
18053 (if (and (not (org-at-timestamp-p t))
18054 (org-at-heading-p))
18055 (org-todo 'down)
18056 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
18058 (defun org-at-timestamp-p (&optional inactive-ok)
18059 "Non-nil if point is inside a timestamp.
18061 When optional argument INACTIVE-OK is non-nil, also consider
18062 inactive timestamps.
18064 When this function returns a non-nil value, match data is set
18065 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18066 INACTIVE-OK."
18067 (interactive)
18068 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18069 (pos (point))
18070 (ans (or (looking-at tsr)
18071 (save-excursion
18072 (skip-chars-backward "^[<\n\r\t")
18073 (when (> (point) (point-min)) (backward-char 1))
18074 (and (looking-at tsr)
18075 (> (- (match-end 0) pos) -1))))))
18076 (and ans
18077 (boundp 'org-ts-what)
18078 (setq org-ts-what
18079 (cond
18080 ((= pos (match-beginning 0)) 'bracket)
18081 ;; Point is considered to be "on the bracket" whether
18082 ;; it's really on it or right after it.
18083 ((= pos (1- (match-end 0))) 'bracket)
18084 ((= pos (match-end 0)) 'after)
18085 ((org-pos-in-match-range pos 2) 'year)
18086 ((org-pos-in-match-range pos 3) 'month)
18087 ((org-pos-in-match-range pos 7) 'hour)
18088 ((org-pos-in-match-range pos 8) 'minute)
18089 ((or (org-pos-in-match-range pos 4)
18090 (org-pos-in-match-range pos 5)) 'day)
18091 ((and (> pos (or (match-end 8) (match-end 5)))
18092 (< pos (match-end 0)))
18093 (- pos (or (match-end 8) (match-end 5))))
18094 (t 'day))))
18095 ans))
18097 (defun org-toggle-timestamp-type ()
18098 "Toggle the type (<active> or [inactive]) of a time stamp."
18099 (interactive)
18100 (when (org-at-timestamp-p t)
18101 (let ((beg (match-beginning 0)) (end (match-end 0))
18102 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18103 (save-excursion
18104 (goto-char beg)
18105 (while (re-search-forward "[][<>]" end t)
18106 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18107 t t)))
18108 (message "Timestamp is now %sactive"
18109 (if (equal (char-after beg) ?<) "" "in")))))
18111 (defun org-at-clock-log-p nil
18112 "Is the cursor on the clock log line?"
18113 (save-excursion
18114 (move-beginning-of-line 1)
18115 (looking-at org-clock-line-re)))
18117 (defvar org-clock-history) ; defined in org-clock.el
18118 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18119 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18120 "Change the date in the time stamp at point.
18121 The date will be changed by N times WHAT. WHAT can be `day', `month',
18122 `year', `minute', `second'. If WHAT is not given, the cursor position
18123 in the timestamp determines what will be changed.
18124 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18125 (let ((origin (point)) origin-cat
18126 with-hm inactive
18127 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18128 org-ts-what
18129 extra rem
18130 ts time time0 fixnext clrgx)
18131 (unless (org-at-timestamp-p t)
18132 (user-error "Not at a timestamp"))
18133 (if (and (not what) (eq org-ts-what 'bracket))
18134 (org-toggle-timestamp-type)
18135 ;; Point isn't on brackets. Remember the part of the time-stamp
18136 ;; the point was in. Indeed, size of time-stamps may change,
18137 ;; but point must be kept in the same category nonetheless.
18138 (setq origin-cat org-ts-what)
18139 (when (and (not what) (not (eq org-ts-what 'day))
18140 org-display-custom-times
18141 (get-text-property (point) 'display)
18142 (not (get-text-property (1- (point)) 'display)))
18143 (setq org-ts-what 'day))
18144 (setq org-ts-what (or what org-ts-what)
18145 inactive (= (char-after (match-beginning 0)) ?\[)
18146 ts (match-string 0))
18147 (replace-match "")
18148 (when (string-match
18149 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18151 (setq extra (match-string 1 ts))
18152 (when suppress-tmp-delay
18153 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18154 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18155 (setq with-hm t))
18156 (setq time0 (org-parse-time-string ts))
18157 (when (and updown
18158 (eq org-ts-what 'minute)
18159 (not current-prefix-arg))
18160 ;; This looks like s-up and s-down. Change by one rounding step.
18161 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18162 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18163 (setcar (cdr time0) (+ (nth 1 time0)
18164 (if (> n 0) (- rem) (- dm rem))))))
18165 (setq time
18166 (apply #'encode-time
18167 (or (car time0) 0)
18168 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18169 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18170 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18171 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18172 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18173 (nthcdr 6 time0)))
18174 (when (and (member org-ts-what '(hour minute))
18175 extra
18176 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18177 (setq extra (org-modify-ts-extra
18178 extra
18179 (if (eq org-ts-what 'hour) 2 5)
18180 n dm)))
18181 (when (integerp org-ts-what)
18182 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18183 (when (eq what 'calendar)
18184 (let ((cal-date (org-get-date-from-calendar)))
18185 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18186 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18187 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18188 (setcar time0 (or (car time0) 0))
18189 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18190 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18191 (setq time (apply 'encode-time time0))))
18192 ;; Insert the new time-stamp, and ensure point stays in the same
18193 ;; category as before (i.e. not after the last position in that
18194 ;; category).
18195 (let ((pos (point)))
18196 ;; Stay before inserted string. `save-excursion' is of no use.
18197 (setq org-last-changed-timestamp
18198 (org-insert-time-stamp time with-hm inactive nil nil extra))
18199 (goto-char pos))
18200 (save-match-data
18201 (looking-at org-ts-regexp3)
18202 (goto-char (cond
18203 ;; `day' category ends before `hour' if any, or at
18204 ;; the end of the day name.
18205 ((eq origin-cat 'day)
18206 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18207 ((eq origin-cat 'hour) (min (match-end 7) origin))
18208 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18209 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18210 ;; `year' and `month' have both fixed size: point
18211 ;; couldn't have moved into another part.
18212 (t origin))))
18213 ;; Update clock if on a CLOCK line.
18214 (org-clock-update-time-maybe)
18215 ;; Maybe adjust the closest clock in `org-clock-history'
18216 (when org-clock-adjust-closest
18217 (if (not (and (org-at-clock-log-p)
18218 (< 1 (length (delq nil (mapcar 'marker-position
18219 org-clock-history))))))
18220 (message "No clock to adjust")
18221 (cond ((save-excursion ; fix previous clock?
18222 (re-search-backward org-ts-regexp0 nil t)
18223 (looking-back (concat org-clock-string " \\[")
18224 (line-beginning-position)))
18225 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18226 ((save-excursion ; fix next clock?
18227 (re-search-backward org-ts-regexp0 nil t)
18228 (looking-at (concat org-ts-regexp0 "\\] =>")))
18229 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18230 (save-window-excursion
18231 ;; Find closest clock to point, adjust the previous/next one in history
18232 (let* ((p (save-excursion (org-back-to-heading t)))
18233 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18234 (clfixnth
18235 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18236 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18237 (if (not clfixpos)
18238 (message "No clock to adjust")
18239 (save-excursion
18240 (org-goto-marker-or-bmk clfixpos)
18241 (org-show-subtree)
18242 (when (re-search-forward clrgx nil t)
18243 (goto-char (match-beginning 1))
18244 (let (org-clock-adjust-closest)
18245 (org-timestamp-change n org-ts-what updown))
18246 (message "Clock adjusted in %s for heading: %s"
18247 (file-name-nondirectory (buffer-file-name))
18248 (org-get-heading t t)))))))))
18249 ;; Try to recenter the calendar window, if any.
18250 (when (and org-calendar-follow-timestamp-change
18251 (get-buffer-window "*Calendar*" t)
18252 (memq org-ts-what '(day month year)))
18253 (org-recenter-calendar (time-to-days time))))))
18255 (defun org-modify-ts-extra (s pos n dm)
18256 "Change the different parts of the lead-time and repeat fields in timestamp."
18257 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18258 ng h m new rem)
18259 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18260 (cond
18261 ((or (org-pos-in-match-range pos 2)
18262 (org-pos-in-match-range pos 3))
18263 (setq m (string-to-number (match-string 3 s))
18264 h (string-to-number (match-string 2 s)))
18265 (if (org-pos-in-match-range pos 2)
18266 (setq h (+ h n))
18267 (setq n (* dm (with-no-warnings (signum n))))
18268 (unless (= 0 (setq rem (% m dm)))
18269 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18270 (setq m (+ m n)))
18271 (when (< m 0) (setq m (+ m 60) h (1- h)))
18272 (when (> m 59) (setq m (- m 60) h (1+ h)))
18273 (setq h (mod h 24))
18274 (setq ng 1 new (format "-%02d:%02d" h m)))
18275 ((org-pos-in-match-range pos 6)
18276 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18277 ((org-pos-in-match-range pos 5)
18278 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18280 ((org-pos-in-match-range pos 9)
18281 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18282 ((org-pos-in-match-range pos 8)
18283 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18285 (when ng
18286 (setq s (concat
18287 (substring s 0 (match-beginning ng))
18289 (substring s (match-end ng))))))
18292 (defun org-recenter-calendar (d)
18293 "If the calendar is visible, recenter it to date D."
18294 (let ((cwin (get-buffer-window "*Calendar*" t)))
18295 (when cwin
18296 (let ((calendar-move-hook nil))
18297 (with-selected-window cwin
18298 (calendar-goto-date
18299 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18301 (defun org-goto-calendar (&optional arg)
18302 "Go to the Emacs calendar at the current date.
18303 If there is a time stamp in the current line, go to that date.
18304 A prefix ARG can be used to force the current date."
18305 (interactive "P")
18306 (let ((tsr org-ts-regexp) diff
18307 (calendar-move-hook nil)
18308 (calendar-view-holidays-initially-flag nil)
18309 (calendar-view-diary-initially-flag nil))
18310 (when (or (org-at-timestamp-p)
18311 (save-excursion
18312 (beginning-of-line 1)
18313 (looking-at (concat ".*" tsr))))
18314 (let ((d1 (time-to-days (current-time)))
18315 (d2 (time-to-days
18316 (org-time-string-to-time (match-string 1)))))
18317 (setq diff (- d2 d1))))
18318 (calendar)
18319 (calendar-goto-today)
18320 (when (and diff (not arg)) (calendar-forward-day diff))))
18322 (defun org-get-date-from-calendar ()
18323 "Return a list (month day year) of date at point in calendar."
18324 (with-current-buffer "*Calendar*"
18325 (save-match-data
18326 (calendar-cursor-to-date))))
18328 (defun org-date-from-calendar ()
18329 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18330 If there is already a time stamp at the cursor position, update it."
18331 (interactive)
18332 (if (org-at-timestamp-p t)
18333 (org-timestamp-change 0 'calendar)
18334 (let ((cal-date (org-get-date-from-calendar)))
18335 (org-insert-time-stamp
18336 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18338 (defcustom org-effort-durations
18339 `(("min" . 1)
18340 ("h" . 60)
18341 ("d" . ,(* 60 8))
18342 ("w" . ,(* 60 8 5))
18343 ("m" . ,(* 60 8 5 4))
18344 ("y" . ,(* 60 8 5 40)))
18345 "Conversion factor to minutes for an effort modifier.
18347 Each entry has the form (MODIFIER . MINUTES).
18349 In an effort string, a number followed by MODIFIER is multiplied
18350 by the specified number of MINUTES to obtain an effort in
18351 minutes.
18353 For example, if the value of this variable is ((\"hours\" . 60)), then an
18354 effort string \"2hours\" is equivalent to 120 minutes."
18355 :group 'org-agenda
18356 :version "25.1"
18357 :package-version '(Org . "8.3")
18358 :type '(alist :key-type (string :tag "Modifier")
18359 :value-type (number :tag "Minutes")))
18361 (defun org-minutes-to-clocksum-string (m)
18362 "Format number of minutes as a clocksum string.
18363 The format is determined by `org-time-clocksum-format',
18364 `org-time-clocksum-use-fractional' and
18365 `org-time-clocksum-fractional-format' and
18366 `org-time-clocksum-use-effort-durations'."
18367 (let ((clocksum "")
18368 (m (round m)) ; Don't allow fractions of minutes
18369 h d w mo y fmt n)
18370 (setq h (if org-time-clocksum-use-effort-durations
18371 (cdr (assoc "h" org-effort-durations)) 60)
18372 d (if org-time-clocksum-use-effort-durations
18373 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18374 w (if org-time-clocksum-use-effort-durations
18375 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18376 mo (if org-time-clocksum-use-effort-durations
18377 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18378 y (if org-time-clocksum-use-effort-durations
18379 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18380 ;; fractional format
18381 (if org-time-clocksum-use-fractional
18382 (cond
18383 ;; single format string
18384 ((stringp org-time-clocksum-fractional-format)
18385 (format org-time-clocksum-fractional-format (/ m (float h))))
18386 ;; choice of fractional formats for different time units
18387 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18388 (> (/ (truncate m) (* y d h)) 0))
18389 (format fmt (/ m (* y d (float h)))))
18390 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18391 (> (/ (truncate m) (* mo d h)) 0))
18392 (format fmt (/ m (* mo d (float h)))))
18393 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18394 (> (/ (truncate m) (* w d h)) 0))
18395 (format fmt (/ m (* w d (float h)))))
18396 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18397 (> (/ (truncate m) (* d h)) 0))
18398 (format fmt (/ m (* d (float h)))))
18399 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18400 (> (/ (truncate m) h) 0))
18401 (format fmt (/ m (float h))))
18402 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18403 (format fmt m))
18404 ;; fall back to smallest time unit with a format
18405 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18406 (format fmt (/ m (float h))))
18407 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18408 (format fmt (/ m (* d (float h)))))
18409 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18410 (format fmt (/ m (* w d (float h)))))
18411 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18412 (format fmt (/ m (* mo d (float h)))))
18413 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18414 (format fmt (/ m (* y d (float h))))))
18415 ;; standard (non-fractional) format, with single format string
18416 (if (stringp org-time-clocksum-format)
18417 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18418 ;; separate formats components
18419 (and (setq fmt (plist-get org-time-clocksum-format :years))
18420 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18421 (plist-get org-time-clocksum-format :require-years))
18422 (setq clocksum (concat clocksum (format fmt n))
18423 m (- m (* n y d h))))
18424 (and (setq fmt (plist-get org-time-clocksum-format :months))
18425 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18426 (plist-get org-time-clocksum-format :require-months))
18427 (setq clocksum (concat clocksum (format fmt n))
18428 m (- m (* n mo d h))))
18429 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18430 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18431 (plist-get org-time-clocksum-format :require-weeks))
18432 (setq clocksum (concat clocksum (format fmt n))
18433 m (- m (* n w d h))))
18434 (and (setq fmt (plist-get org-time-clocksum-format :days))
18435 (or (> (setq n (/ (truncate m) (* d h))) 0)
18436 (plist-get org-time-clocksum-format :require-days))
18437 (setq clocksum (concat clocksum (format fmt n))
18438 m (- m (* n d h))))
18439 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18440 (or (> (setq n (/ (truncate m) h)) 0)
18441 (plist-get org-time-clocksum-format :require-hours))
18442 (setq clocksum (concat clocksum (format fmt n))
18443 m (- m (* n h))))
18444 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18445 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18446 (setq clocksum (concat clocksum (format fmt m))))
18447 ;; return formatted time duration
18448 clocksum))))
18450 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18451 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18452 "Org mode version 8.0")
18454 (defun org-hours-to-clocksum-string (n)
18455 (org-minutes-to-clocksum-string (* n 60)))
18457 (defun org-hh:mm-string-to-minutes (s)
18458 "Convert a string H:MM to a number of minutes.
18459 If the string is just a number, interpret it as minutes.
18460 In fact, the first hh:mm or number in the string will be taken,
18461 there can be extra stuff in the string.
18462 If no number is found, the return value is 0."
18463 (cond
18464 ((integerp s) s)
18465 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18466 (+ (* (string-to-number (match-string 1 s)) 60)
18467 (string-to-number (match-string 2 s))))
18468 ((string-match "\\([0-9]+\\)" s)
18469 (string-to-number (match-string 1 s)))
18470 (t 0)))
18472 (defcustom org-image-actual-width t
18473 "Should we use the actual width of images when inlining them?
18475 When set to t, always use the image width.
18477 When set to a number, use imagemagick (when available) to set
18478 the image's width to this value.
18480 When set to a number in a list, try to get the width from any
18481 #+ATTR.* keyword if it matches a width specification like
18483 #+ATTR_HTML: :width 300px
18485 and fall back on that number if none is found.
18487 When set to nil, try to get the width from an #+ATTR.* keyword
18488 and fall back on the original width if none is found.
18490 This requires Emacs >= 24.1, build with imagemagick support."
18491 :group 'org-appearance
18492 :version "24.4"
18493 :package-version '(Org . "8.0")
18494 :type '(choice
18495 (const :tag "Use the image width" t)
18496 (integer :tag "Use a number of pixels")
18497 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18498 (const :tag "Use #+ATTR* or don't resize" nil)))
18500 (defcustom org-agenda-inhibit-startup nil
18501 "Inhibit startup when preparing agenda buffers.
18502 When this variable is t, the initialization of the Org agenda
18503 buffers is inhibited: e.g. the visibility state is not set, the
18504 tables are not re-aligned, etc."
18505 :type 'boolean
18506 :version "24.3"
18507 :group 'org-agenda)
18509 (defcustom org-agenda-ignore-properties nil
18510 "Avoid updating text properties when building the agenda.
18511 Properties are used to prepare buffers for effort estimates,
18512 appointments, statistics and subtree-local categories.
18513 If you don't use these in the agenda, you can add them to this
18514 list and agenda building will be a bit faster.
18515 The value is a list, with zero or more of the symbols `effort', `appt',
18516 `stats' or `category'."
18517 :type '(set :greedy t
18518 (const effort)
18519 (const appt)
18520 (const stats)
18521 (const category))
18522 :version "25.1"
18523 :package-version '(Org . "8.3")
18524 :group 'org-agenda)
18526 (defun org-duration-string-to-minutes (s &optional output-to-string)
18527 "Convert a duration string S to minutes.
18529 A bare number is interpreted as minutes, modifiers can be set by
18530 customizing `org-effort-durations' (which see).
18532 Entries containing a colon are interpreted as H:MM by
18533 `org-hh:mm-string-to-minutes'."
18534 (let ((result 0)
18535 (re (concat "\\([0-9.]+\\) *\\("
18536 (regexp-opt (mapcar 'car org-effort-durations))
18537 "\\)")))
18538 (while (string-match re s)
18539 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18540 (string-to-number (match-string 1 s))))
18541 (setq s (replace-match "" nil t s)))
18542 (setq result (floor result))
18543 (cl-incf result (org-hh:mm-string-to-minutes s))
18544 (if output-to-string (number-to-string result) result)))
18546 ;;;; Files
18548 (defun org-save-all-org-buffers ()
18549 "Save all Org buffers without user confirmation."
18550 (interactive)
18551 (message "Saving all Org buffers...")
18552 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18553 (when (featurep 'org-id) (org-id-locations-save))
18554 (message "Saving all Org buffers... done"))
18556 (defun org-revert-all-org-buffers ()
18557 "Revert all Org buffers.
18558 Prompt for confirmation when there are unsaved changes.
18559 Be sure you know what you are doing before letting this function
18560 overwrite your changes.
18562 This function is useful in a setup where one tracks org files
18563 with a version control system, to revert on one machine after pulling
18564 changes from another. I believe the procedure must be like this:
18566 1. M-x org-save-all-org-buffers
18567 2. Pull changes from the other machine, resolve conflicts
18568 3. M-x org-revert-all-org-buffers"
18569 (interactive)
18570 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18571 (user-error "Abort"))
18572 (save-excursion
18573 (save-window-excursion
18574 (dolist (b (buffer-list))
18575 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18576 (with-current-buffer b buffer-file-name))
18577 (pop-to-buffer-same-window b)
18578 (revert-buffer t 'no-confirm)))
18579 (when (and (featurep 'org-id) org-id-track-globally)
18580 (org-id-locations-load)))))
18582 ;;;; Agenda files
18584 ;;;###autoload
18585 (defun org-switchb (&optional arg)
18586 "Switch between Org buffers.
18588 With \\[universal-argument] prefix, restrict available buffers to files.
18590 With \\[universal-argument] \\[universal-argument] \
18591 prefix, restrict available buffers to agenda files."
18592 (interactive "P")
18593 (let ((blist (org-buffer-list
18594 (cond ((equal arg '(4)) 'files)
18595 ((equal arg '(16)) 'agenda)))))
18596 (pop-to-buffer-same-window
18597 (completing-read "Org buffer: "
18598 (mapcar #'list (mapcar #'buffer-name blist))
18599 nil t))))
18601 (defun org-buffer-list (&optional predicate exclude-tmp)
18602 "Return a list of Org buffers.
18603 PREDICATE can be `export', `files' or `agenda'.
18605 export restrict the list to Export buffers.
18606 files restrict the list to buffers visiting Org files.
18607 agenda restrict the list to buffers visiting agenda files.
18609 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18610 (let* ((bfn nil)
18611 (agenda-files (and (eq predicate 'agenda)
18612 (mapcar 'file-truename (org-agenda-files t))))
18613 (filter
18614 (cond
18615 ((eq predicate 'files)
18616 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18617 ((eq predicate 'export)
18618 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18619 ((eq predicate 'agenda)
18620 (lambda (b)
18621 (with-current-buffer b
18622 (and (derived-mode-p 'org-mode)
18623 (setq bfn (buffer-file-name b))
18624 (member (file-truename bfn) agenda-files)))))
18625 (t (lambda (b) (with-current-buffer b
18626 (or (derived-mode-p 'org-mode)
18627 (string-match "\\*Org .*Export"
18628 (buffer-name b)))))))))
18629 (delq nil
18630 (mapcar
18631 (lambda(b)
18632 (if (and (funcall filter b)
18633 (or (not exclude-tmp)
18634 (not (string-match "tmp" (buffer-name b)))))
18636 nil))
18637 (buffer-list)))))
18639 (defun org-agenda-files (&optional unrestricted archives)
18640 "Get the list of agenda files.
18641 Optional UNRESTRICTED means return the full list even if a restriction
18642 is currently in place.
18643 When ARCHIVES is t, include all archive files that are really being
18644 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18645 `org-agenda-archives-mode' is t."
18646 (let ((files
18647 (cond
18648 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18649 ((stringp org-agenda-files) (org-read-agenda-file-list))
18650 ((listp org-agenda-files) org-agenda-files)
18651 (t (error "Invalid value of `org-agenda-files'")))))
18652 (setq files (apply 'append
18653 (mapcar (lambda (f)
18654 (if (file-directory-p f)
18655 (directory-files
18656 f t org-agenda-file-regexp)
18657 (list f)))
18658 files)))
18659 (when org-agenda-skip-unavailable-files
18660 (setq files (delq nil
18661 (mapcar (function
18662 (lambda (file)
18663 (and (file-readable-p file) file)))
18664 files))))
18665 (when (or (eq archives t)
18666 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18667 (setq files (org-add-archive-files files)))
18668 files))
18670 (defun org-agenda-file-p (&optional file)
18671 "Return non-nil, if FILE is an agenda file.
18672 If FILE is omitted, use the file associated with the current
18673 buffer."
18674 (let ((fname (or file (buffer-file-name))))
18675 (and fname
18676 (member (file-truename fname)
18677 (mapcar #'file-truename (org-agenda-files t))))))
18679 (defun org-edit-agenda-file-list ()
18680 "Edit the list of agenda files.
18681 Depending on setup, this either uses customize to edit the variable
18682 `org-agenda-files', or it visits the file that is holding the list. In the
18683 latter case, the buffer is set up in a way that saving it automatically kills
18684 the buffer and restores the previous window configuration."
18685 (interactive)
18686 (if (stringp org-agenda-files)
18687 (let ((cw (current-window-configuration)))
18688 (find-file org-agenda-files)
18689 (setq-local org-window-configuration cw)
18690 (add-hook 'after-save-hook
18691 (lambda ()
18692 (set-window-configuration
18693 (prog1 org-window-configuration
18694 (kill-buffer (current-buffer))))
18695 (org-install-agenda-files-menu)
18696 (message "New agenda file list installed"))
18697 nil 'local)
18698 (message "%s" (substitute-command-keys
18699 "Edit list and finish with \\[save-buffer]")))
18700 (customize-variable 'org-agenda-files)))
18702 (defun org-store-new-agenda-file-list (list)
18703 "Set new value for the agenda file list and save it correctly."
18704 (if (stringp org-agenda-files)
18705 (let ((fe (org-read-agenda-file-list t)) b u)
18706 (while (setq b (find-buffer-visiting org-agenda-files))
18707 (kill-buffer b))
18708 (with-temp-file org-agenda-files
18709 (insert
18710 (mapconcat
18711 (lambda (f) ;; Keep un-expanded entries.
18712 (if (setq u (assoc f fe))
18713 (cdr u)
18715 list "\n")
18716 "\n")))
18717 (let ((org-mode-hook nil) (org-inhibit-startup t)
18718 (org-insert-mode-line-in-empty-file nil))
18719 (setq org-agenda-files list)
18720 (customize-save-variable 'org-agenda-files org-agenda-files))))
18722 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18723 "Read the list of agenda files from a file.
18724 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18725 filenames, used by `org-store-new-agenda-file-list' to write back
18726 un-expanded file names."
18727 (when (file-directory-p org-agenda-files)
18728 (error "`org-agenda-files' cannot be a single directory"))
18729 (when (stringp org-agenda-files)
18730 (with-temp-buffer
18731 (insert-file-contents org-agenda-files)
18732 (mapcar
18733 (lambda (f)
18734 (let ((e (expand-file-name (substitute-in-file-name f)
18735 org-directory)))
18736 (if pair-with-expansion
18737 (cons e f)
18738 e)))
18739 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18741 ;;;###autoload
18742 (defun org-cycle-agenda-files ()
18743 "Cycle through the files in `org-agenda-files'.
18744 If the current buffer visits an agenda file, find the next one in the list.
18745 If the current buffer does not, find the first agenda file."
18746 (interactive)
18747 (let* ((fs (or (org-agenda-files t)
18748 (user-error "No agenda files")))
18749 (files (copy-sequence fs))
18750 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18751 file)
18752 (when tcf
18753 (while (and (setq file (pop files))
18754 (not (equal (file-truename file) tcf)))))
18755 (find-file (car (or files fs)))
18756 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18758 (defun org-agenda-file-to-front (&optional to-end)
18759 "Move/add the current file to the top of the agenda file list.
18760 If the file is not present in the list, it is added to the front. If it is
18761 present, it is moved there. With optional argument TO-END, add/move to the
18762 end of the list."
18763 (interactive "P")
18764 (let ((org-agenda-skip-unavailable-files nil)
18765 (file-alist (mapcar (lambda (x)
18766 (cons (file-truename x) x))
18767 (org-agenda-files t)))
18768 (ctf (file-truename
18769 (or buffer-file-name
18770 (user-error "Please save the current buffer to a file"))))
18771 x had)
18772 (setq x (assoc ctf file-alist) had x)
18774 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18775 (if to-end
18776 (setq file-alist (append (delq x file-alist) (list x)))
18777 (setq file-alist (cons x (delq x file-alist))))
18778 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18779 (org-install-agenda-files-menu)
18780 (message "File %s to %s of agenda file list"
18781 (if had "moved" "added") (if to-end "end" "front"))))
18783 (defun org-remove-file (&optional file)
18784 "Remove current file from the list of files in variable `org-agenda-files'.
18785 These are the files which are being checked for agenda entries.
18786 Optional argument FILE means use this file instead of the current."
18787 (interactive)
18788 (let* ((org-agenda-skip-unavailable-files nil)
18789 (file (or file buffer-file-name
18790 (user-error "Current buffer does not visit a file")))
18791 (true-file (file-truename file))
18792 (afile (abbreviate-file-name file))
18793 (files (delq nil (mapcar
18794 (lambda (x)
18795 (unless (equal true-file
18796 (file-truename x))
18798 (org-agenda-files t)))))
18799 (if (not (= (length files) (length (org-agenda-files t))))
18800 (progn
18801 (org-store-new-agenda-file-list files)
18802 (org-install-agenda-files-menu)
18803 (message "Removed from Org Agenda list: %s" afile))
18804 (message "File was not in list: %s (not removed)" afile))))
18806 (defun org-file-menu-entry (file)
18807 (vector file (list 'find-file file) t))
18809 (defun org-check-agenda-file (file)
18810 "Make sure FILE exists. If not, ask user what to do."
18811 (unless (file-exists-p file)
18812 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18813 (abbreviate-file-name file))
18814 (let ((r (downcase (read-char-exclusive))))
18815 (cond
18816 ((equal r ?r)
18817 (org-remove-file file)
18818 (throw 'nextfile t))
18819 (t (user-error "Abort"))))))
18821 (defun org-get-agenda-file-buffer (file)
18822 "Get an agenda buffer visiting FILE.
18823 If the buffer needs to be created, add it to the list of buffers
18824 which might be released later."
18825 (let ((buf (org-find-base-buffer-visiting file)))
18826 (if buf
18827 buf ; just return it
18828 ;; Make a new buffer and remember it
18829 (setq buf (find-file-noselect file))
18830 (when buf (push buf org-agenda-new-buffers))
18831 buf)))
18833 (defun org-release-buffers (blist)
18834 "Release all buffers in list, asking the user for confirmation when needed.
18835 When a buffer is unmodified, it is just killed. When modified, it is saved
18836 \(if the user agrees) and then killed."
18837 (let (file)
18838 (dolist (buf blist)
18839 (setq file (buffer-file-name buf))
18840 (when (and (buffer-modified-p buf)
18841 file
18842 (y-or-n-p (format "Save file %s? " file)))
18843 (with-current-buffer buf (save-buffer)))
18844 (kill-buffer buf))))
18846 (defun org-agenda-prepare-buffers (files)
18847 "Create buffers for all agenda files, protect archived trees and comments."
18848 (interactive)
18849 (let ((pa '(:org-archived t))
18850 (pc '(:org-comment t))
18851 (pall '(:org-archived t :org-comment t))
18852 (inhibit-read-only t)
18853 (org-inhibit-startup org-agenda-inhibit-startup)
18854 (rea (concat ":" org-archive-tag ":"))
18855 re pos)
18856 (setq org-tag-alist-for-agenda nil
18857 org-tag-groups-alist-for-agenda nil)
18858 (save-excursion
18859 (save-restriction
18860 (dolist (file files)
18861 (catch 'nextfile
18862 (if (bufferp file)
18863 (set-buffer file)
18864 (org-check-agenda-file file)
18865 (set-buffer (org-get-agenda-file-buffer file)))
18866 (widen)
18867 (org-set-regexps-and-options 'tags-only)
18868 (setq pos (point))
18869 (or (memq 'category org-agenda-ignore-properties)
18870 (org-refresh-category-properties))
18871 (or (memq 'stats org-agenda-ignore-properties)
18872 (org-refresh-stats-properties))
18873 (or (memq 'effort org-agenda-ignore-properties)
18874 (org-refresh-effort-properties))
18875 (or (memq 'appt org-agenda-ignore-properties)
18876 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18877 (setq org-todo-keywords-for-agenda
18878 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18879 (setq org-done-keywords-for-agenda
18880 (append org-done-keywords-for-agenda org-done-keywords))
18881 (setq org-todo-keyword-alist-for-agenda
18882 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18883 (setq org-tag-alist-for-agenda
18884 (org-uniquify
18885 (append org-tag-alist-for-agenda
18886 org-current-tag-alist)))
18887 ;; Merge current file's tag groups into global
18888 ;; `org-tag-groups-alist-for-agenda'.
18889 (when org-group-tags
18890 (dolist (alist org-tag-groups-alist)
18891 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18892 (if old
18893 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18894 (push alist org-tag-groups-alist-for-agenda)))))
18895 (org-with-silent-modifications
18896 (save-excursion
18897 (remove-text-properties (point-min) (point-max) pall)
18898 (when org-agenda-skip-archived-trees
18899 (goto-char (point-min))
18900 (while (re-search-forward rea nil t)
18901 (when (org-at-heading-p t)
18902 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18903 (goto-char (point-min))
18904 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18905 (while (re-search-forward re nil t)
18906 (when (save-match-data (org-in-commented-heading-p t))
18907 (add-text-properties
18908 (match-beginning 0) (org-end-of-subtree t) pc)))))
18909 (goto-char pos)))))
18910 (setq org-todo-keywords-for-agenda
18911 (org-uniquify org-todo-keywords-for-agenda))
18912 (setq org-todo-keyword-alist-for-agenda
18913 (org-uniquify org-todo-keyword-alist-for-agenda))))
18916 ;;;; CDLaTeX minor mode
18918 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18919 "Keymap for the minor `org-cdlatex-mode'.")
18921 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18922 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18923 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18924 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18925 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18927 (defvar org-cdlatex-texmathp-advice-is-done nil
18928 "Flag remembering if we have applied the advice to texmathp already.")
18930 (define-minor-mode org-cdlatex-mode
18931 "Toggle the minor `org-cdlatex-mode'.
18932 This mode supports entering LaTeX environment and math in LaTeX fragments
18933 in Org-mode.
18934 \\{org-cdlatex-mode-map}"
18935 nil " OCDL" nil
18936 (when org-cdlatex-mode
18937 (require 'cdlatex)
18938 (run-hooks 'cdlatex-mode-hook)
18939 (cdlatex-compute-tables))
18940 (unless org-cdlatex-texmathp-advice-is-done
18941 (setq org-cdlatex-texmathp-advice-is-done t)
18942 (defadvice texmathp (around org-math-always-on activate)
18943 "Always return t in Org buffers.
18944 This is because we want to insert math symbols without dollars even outside
18945 the LaTeX math segments. If Orgmode thinks that point is actually inside
18946 an embedded LaTeX fragment, let texmathp do its job.
18947 \\[org-cdlatex-mode-map]"
18948 (interactive)
18949 (let (p)
18950 (cond
18951 ((not (derived-mode-p 'org-mode)) ad-do-it)
18952 ((eq this-command 'cdlatex-math-symbol)
18953 (setq ad-return-value t
18954 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18956 (let ((p (org-inside-LaTeX-fragment-p)))
18957 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18958 (setq ad-return-value t
18959 texmathp-why '("Org-mode embedded math" . 0))
18960 (when p ad-do-it)))))))))
18962 (defun turn-on-org-cdlatex ()
18963 "Unconditionally turn on `org-cdlatex-mode'."
18964 (org-cdlatex-mode 1))
18966 (defun org-try-cdlatex-tab ()
18967 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18968 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18969 - inside a LaTeX fragment, or
18970 - after the first word in a line, where an abbreviation expansion could
18971 insert a LaTeX environment."
18972 (when org-cdlatex-mode
18973 (cond
18974 ;; Before any word on the line: No expansion possible.
18975 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18976 ;; Just after first word on the line: Expand it. Make sure it
18977 ;; cannot happen on headlines, though.
18978 ((save-excursion
18979 (skip-chars-backward "a-zA-Z0-9*")
18980 (skip-chars-backward " \t")
18981 (and (bolp) (not (org-at-heading-p))))
18982 (cdlatex-tab) t)
18983 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18985 (defun org-cdlatex-underscore-caret (&optional _arg)
18986 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18987 Revert to the normal definition outside of these fragments."
18988 (interactive "P")
18989 (if (org-inside-LaTeX-fragment-p)
18990 (call-interactively 'cdlatex-sub-superscript)
18991 (let (org-cdlatex-mode)
18992 (call-interactively (key-binding (vector last-input-event))))))
18994 (defun org-cdlatex-math-modify (&optional _arg)
18995 "Execute `cdlatex-math-modify' in LaTeX fragments.
18996 Revert to the normal definition outside of these fragments."
18997 (interactive "P")
18998 (if (org-inside-LaTeX-fragment-p)
18999 (call-interactively 'cdlatex-math-modify)
19000 (let (org-cdlatex-mode)
19001 (call-interactively (key-binding (vector last-input-event))))))
19003 (defun org-cdlatex-environment-indent (&optional environment item)
19004 "Execute `cdlatex-environment' and indent the inserted environment.
19006 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
19008 The inserted environment is indented to current indentation
19009 unless point is at the beginning of the line, in which the
19010 environment remains unintended."
19011 (interactive)
19012 ;; cdlatex-environment always return nil. Therefore, capture output
19013 ;; first and determine if an environment was selected.
19014 (let* ((beg (point-marker))
19015 (end (copy-marker (point) t))
19016 (inserted (progn
19017 (ignore-errors (cdlatex-environment environment item))
19018 (< beg end)))
19019 ;; Figure out how many lines to move forward after the
19020 ;; environment has been inserted.
19021 (lines (when inserted
19022 (save-excursion
19023 (- (cl-loop while (< beg (point))
19024 with x = 0
19025 do (forward-line -1)
19026 (cl-incf x)
19027 finally return x)
19028 (if (progn (goto-char beg)
19029 (and (progn (skip-chars-forward " \t") (eolp))
19030 (progn (skip-chars-backward " \t") (bolp))))
19031 1 0)))))
19032 (env (org-trim (delete-and-extract-region beg end))))
19033 (when inserted
19034 ;; Get indentation of next line unless at column 0.
19035 (let ((ind (if (bolp) 0
19036 (save-excursion
19037 (org-return-indent)
19038 (prog1 (org-get-indentation)
19039 (when (progn (skip-chars-forward " \t") (eolp))
19040 (delete-region beg (point)))))))
19041 (bol (progn (skip-chars-backward " \t") (bolp))))
19042 ;; Insert a newline before environment unless at column zero
19043 ;; to "escape" the current line. Insert a newline if
19044 ;; something is one the same line as \end{ENVIRONMENT}.
19045 (insert
19046 (concat (unless bol "\n") env
19047 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
19048 (unless (zerop ind)
19049 (save-excursion
19050 (goto-char beg)
19051 (while (< (point) end)
19052 (unless (eolp) (indent-line-to ind))
19053 (forward-line))))
19054 (goto-char beg)
19055 (forward-line lines)
19056 (indent-line-to ind)))
19057 (set-marker beg nil)
19058 (set-marker end nil)))
19061 ;;;; LaTeX fragments
19063 (defun org-inside-LaTeX-fragment-p ()
19064 "Test if point is inside a LaTeX fragment.
19065 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19066 sequence appearing also before point.
19067 Even though the matchers for math are configurable, this function assumes
19068 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19069 delimiters are skipped when they have been removed by customization.
19070 The return value is nil, or a cons cell with the delimiter and the
19071 position of this delimiter.
19073 This function does a reasonably good job, but can locally be fooled by
19074 for example currency specifications. For example it will assume being in
19075 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19076 fragments that are properly closed, but during editing, we have to live
19077 with the uncertainty caused by missing closing delimiters. This function
19078 looks only before point, not after."
19079 (catch 'exit
19080 (let ((pos (point))
19081 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19082 (lim (progn
19083 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19084 (point)))
19085 dd-on str (start 0) m re)
19086 (goto-char pos)
19087 (when dodollar
19088 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19089 re (nth 1 (assoc "$" org-latex-regexps)))
19090 (while (string-match re str start)
19091 (cond
19092 ((= (match-end 0) (length str))
19093 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19094 ((= (match-end 0) (- (length str) 5))
19095 (throw 'exit nil))
19096 (t (setq start (match-end 0))))))
19097 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19098 (goto-char pos)
19099 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19100 (and (match-beginning 2) (throw 'exit nil))
19101 ;; count $$
19102 (while (re-search-backward "\\$\\$" lim t)
19103 (setq dd-on (not dd-on)))
19104 (goto-char pos)
19105 (when dd-on (cons "$$" m))))))
19107 (defun org-inside-latex-macro-p ()
19108 "Is point inside a LaTeX macro or its arguments?"
19109 (save-match-data
19110 (org-in-regexp
19111 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19113 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19114 "Build an overlay between BEG and END using IMAGE file.
19115 Argument IMAGETYPE is the extension of the displayed image,
19116 as a string. It defaults to \"png\"."
19117 (let ((ov (make-overlay beg end))
19118 (imagetype (or (intern imagetype) 'png)))
19119 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19120 (overlay-put ov 'evaporate t)
19121 (overlay-put ov
19122 'modification-hooks
19123 (list (lambda (o _flag _beg _end &optional _l)
19124 (delete-overlay o))))
19125 (overlay-put ov
19126 'display
19127 (list 'image :type imagetype :file image :ascent 'center))))
19129 (defun org--list-latex-overlays (&optional beg end)
19130 "List all Org LaTeX overlays in current buffer.
19131 Limit to overlays between BEG and END when those are provided."
19132 (cl-remove-if-not
19133 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19134 (overlays-in (or beg (point-min)) (or end (point-max)))))
19136 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19137 "Remove all overlays with LaTeX fragment images in current buffer.
19138 When optional arguments BEG and END are non-nil, remove all
19139 overlays between them instead. Return a non-nil value when some
19140 overlays were removed, nil otherwise."
19141 (let ((overlays (org--list-latex-overlays beg end)))
19142 (mapc #'delete-overlay overlays)
19143 overlays))
19145 (defun org-toggle-latex-fragment (&optional arg)
19146 "Preview the LaTeX fragment at point, or all locally or globally.
19148 If the cursor is on a LaTeX fragment, create the image and overlay
19149 it over the source code, if there is none. Remove it otherwise.
19150 If there is no fragment at point, display all fragments in the
19151 current section.
19153 With prefix ARG, preview or clear image for all fragments in the
19154 current subtree or in the whole buffer when used before the first
19155 headline. With a double prefix ARG \\[universal-argument] \
19156 \\[universal-argument] preview or clear images
19157 for all fragments in the buffer."
19158 (interactive "P")
19159 (when (display-graphic-p)
19160 (catch 'exit
19161 (save-excursion
19162 (let (beg end msg)
19163 (cond
19164 ((or (equal arg '(16))
19165 (and (equal arg '(4))
19166 (org-with-limited-levels (org-before-first-heading-p))))
19167 (if (org-remove-latex-fragment-image-overlays)
19168 (progn (message "LaTeX fragments images removed from buffer")
19169 (throw 'exit nil))
19170 (setq msg "Creating images for buffer...")))
19171 ((equal arg '(4))
19172 (org-with-limited-levels (org-back-to-heading t))
19173 (setq beg (point))
19174 (setq end (progn (org-end-of-subtree t) (point)))
19175 (if (org-remove-latex-fragment-image-overlays beg end)
19176 (progn
19177 (message "LaTeX fragment images removed from subtree")
19178 (throw 'exit nil))
19179 (setq msg "Creating images for subtree...")))
19180 ((let ((datum (org-element-context)))
19181 (when (memq (org-element-type datum)
19182 '(latex-environment latex-fragment))
19183 (setq beg (org-element-property :begin datum))
19184 (setq end (org-element-property :end datum))
19185 (if (org-remove-latex-fragment-image-overlays beg end)
19186 (progn (message "LaTeX fragment image removed")
19187 (throw 'exit nil))
19188 (setq msg "Creating image...")))))
19190 (org-with-limited-levels
19191 (setq beg (if (org-at-heading-p) (line-beginning-position)
19192 (outline-previous-heading)
19193 (point)))
19194 (setq end (progn (outline-next-heading) (point)))
19195 (if (org-remove-latex-fragment-image-overlays beg end)
19196 (progn
19197 (message "LaTeX fragment images removed from section")
19198 (throw 'exit nil))
19199 (setq msg "Creating images for section...")))))
19200 (let ((file (buffer-file-name (buffer-base-buffer))))
19201 (org-format-latex
19202 (concat org-preview-latex-image-directory "org-ltximg")
19203 beg end
19204 ;; Emacs cannot overlay images from remote hosts. Create
19205 ;; it in `temporary-file-directory' instead.
19206 (if (or (not file) (file-remote-p file))
19207 temporary-file-directory
19208 default-directory)
19209 'overlays msg 'forbuffer org-preview-latex-default-process))
19210 (message (concat msg "done")))))))
19212 (defun org-format-latex
19213 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19214 "Replace LaTeX fragments with links to an image.
19216 The function takes care of creating the replacement image.
19218 Only consider fragments between BEG and END when those are
19219 provided.
19221 When optional argument OVERLAYS is non-nil, display the image on
19222 top of the fragment instead of replacing it.
19224 PROCESSING-TYPE is the conversion method to use, as a symbol.
19226 Some of the options can be changed using the variable
19227 `org-format-latex-options', which see."
19228 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19229 (unless (eq processing-type 'verbatim)
19230 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19231 (cnt 0)
19232 checkdir-flag)
19233 (goto-char (or beg (point-min)))
19234 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19235 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19236 (overlay-recenter (or end (point-max))))
19237 (while (re-search-forward math-regexp end t)
19238 (unless (and overlays
19239 (eq (get-char-property (point) 'org-overlay-type)
19240 'org-latex-overlay))
19241 (let* ((context (org-element-context))
19242 (type (org-element-type context)))
19243 (when (memq type '(latex-environment latex-fragment))
19244 (let ((block-type (eq type 'latex-environment))
19245 (value (org-element-property :value context))
19246 (beg (org-element-property :begin context))
19247 (end (save-excursion
19248 (goto-char (org-element-property :end context))
19249 (skip-chars-backward " \r\t\n")
19250 (point))))
19251 (cond
19252 ((eq processing-type 'mathjax)
19253 ;; Prepare for MathJax processing.
19254 (if (not (string-match "\\`\\$\\$?" value))
19255 (goto-char end)
19256 (delete-region beg end)
19257 (if (string= (match-string 0 value) "$$")
19258 (insert "\\[" (substring value 2 -2) "\\]")
19259 (insert "\\(" (substring value 1 -1) "\\)"))))
19260 ((assq processing-type org-preview-latex-process-alist)
19261 ;; Process to an image.
19262 (cl-incf cnt)
19263 (goto-char beg)
19264 (let* ((processing-info
19265 (cdr (assq processing-type org-preview-latex-process-alist)))
19266 (face (face-at-point))
19267 ;; Get the colors from the face at point.
19269 (let ((color (plist-get org-format-latex-options
19270 :foreground)))
19271 (if (and forbuffer (eq color 'auto))
19272 (face-attribute face :foreground nil 'default)
19273 color)))
19275 (let ((color (plist-get org-format-latex-options
19276 :background)))
19277 (if (and forbuffer (eq color 'auto))
19278 (face-attribute face :background nil 'default)
19279 color)))
19280 (hash (sha1 (prin1-to-string
19281 (list org-format-latex-header
19282 org-latex-default-packages-alist
19283 org-latex-packages-alist
19284 org-format-latex-options
19285 forbuffer value fg bg))))
19286 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19287 (absprefix (expand-file-name prefix dir))
19288 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19289 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19290 (sep (and block-type "\n\n"))
19291 (link (concat sep "[[file:" linkfile "]]" sep))
19292 (options
19293 (org-combine-plists
19294 org-format-latex-options
19295 `(:foreground ,fg :background ,bg))))
19296 (when msg (message msg cnt))
19297 (unless checkdir-flag ; Ensure the directory exists.
19298 (setq checkdir-flag t)
19299 (let ((todir (file-name-directory absprefix)))
19300 (unless (file-directory-p todir)
19301 (make-directory todir t))))
19302 (unless (file-exists-p movefile)
19303 (org-create-formula-image
19304 value movefile options forbuffer processing-type))
19305 (if overlays
19306 (progn
19307 (dolist (o (overlays-in beg end))
19308 (when (eq (overlay-get o 'org-overlay-type)
19309 'org-latex-overlay)
19310 (delete-overlay o)))
19311 (org--format-latex-make-overlay beg end movefile imagetype)
19312 (goto-char end))
19313 (delete-region beg end)
19314 (insert
19315 (org-add-props link
19316 (list 'org-latex-src
19317 (replace-regexp-in-string "\"" "" value)
19318 'org-latex-src-embed-type
19319 (if block-type 'paragraph 'character)))))))
19320 ((eq processing-type 'mathml)
19321 ;; Process to MathML.
19322 (unless (org-format-latex-mathml-available-p)
19323 (user-error "LaTeX to MathML converter not configured"))
19324 (cl-incf cnt)
19325 (when msg (message msg cnt))
19326 (goto-char beg)
19327 (delete-region beg end)
19328 (insert (org-format-latex-as-mathml
19329 value block-type prefix dir)))
19331 (error "Unknown conversion process %s for LaTeX fragments"
19332 processing-type)))))))))))
19334 (defun org-create-math-formula (latex-frag &optional mathml-file)
19335 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19336 Use `org-latex-to-mathml-convert-command'. If the conversion is
19337 sucessful, return the portion between \"<math...> </math>\"
19338 elements otherwise return nil. When MATHML-FILE is specified,
19339 write the results in to that file. When invoked as an
19340 interactive command, prompt for LATEX-FRAG, with initial value
19341 set to the current active region and echo the results for user
19342 inspection."
19343 (interactive (list (let ((frag (when (org-region-active-p)
19344 (buffer-substring-no-properties
19345 (region-beginning) (region-end)))))
19346 (read-string "LaTeX Fragment: " frag nil frag))))
19347 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19348 (let* ((tmp-in-file
19349 (let ((file (file-relative-name
19350 (make-temp-name (expand-file-name "ltxmathml-in")))))
19351 (write-region latex-frag nil file)
19352 file))
19353 (tmp-out-file (file-relative-name
19354 (make-temp-name (expand-file-name "ltxmathml-out"))))
19355 (cmd (format-spec
19356 org-latex-to-mathml-convert-command
19357 `((?j . ,(and org-latex-to-mathml-jar-file
19358 (shell-quote-argument
19359 (expand-file-name
19360 org-latex-to-mathml-jar-file))))
19361 (?I . ,(shell-quote-argument tmp-in-file))
19362 (?i . ,latex-frag)
19363 (?o . ,(shell-quote-argument tmp-out-file)))))
19364 mathml shell-command-output)
19365 (when (called-interactively-p 'any)
19366 (unless (org-format-latex-mathml-available-p)
19367 (user-error "LaTeX to MathML converter not configured")))
19368 (message "Running %s" cmd)
19369 (setq shell-command-output (shell-command-to-string cmd))
19370 (setq mathml
19371 (when (file-readable-p tmp-out-file)
19372 (with-current-buffer (find-file-noselect tmp-out-file t)
19373 (goto-char (point-min))
19374 (when (re-search-forward
19375 (concat
19376 (regexp-quote
19377 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19378 "[^>]*?>"
19379 "\\(.\\|\n\\)*"
19380 "</math>")
19381 nil t)
19382 (prog1 (match-string 0) (kill-buffer))))))
19383 (cond
19384 (mathml
19385 (setq mathml
19386 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19387 (when mathml-file
19388 (write-region mathml nil mathml-file))
19389 (when (called-interactively-p 'any)
19390 (message mathml)))
19391 ((message "LaTeX to MathML conversion failed")
19392 (message shell-command-output)))
19393 (delete-file tmp-in-file)
19394 (when (file-exists-p tmp-out-file)
19395 (delete-file tmp-out-file))
19396 mathml))
19398 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19399 prefix &optional dir)
19400 "Use `org-create-math-formula' but check local cache first."
19401 (let* ((absprefix (expand-file-name prefix dir))
19402 (print-length nil) (print-level nil)
19403 (formula-id (concat
19404 "formula-"
19405 (sha1
19406 (prin1-to-string
19407 (list latex-frag
19408 org-latex-to-mathml-convert-command)))))
19409 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19410 (formula-cache-dir (file-name-directory formula-cache)))
19412 (unless (file-directory-p formula-cache-dir)
19413 (make-directory formula-cache-dir t))
19415 (unless (file-exists-p formula-cache)
19416 (org-create-math-formula latex-frag formula-cache))
19418 (if (file-exists-p formula-cache)
19419 ;; Successful conversion. Return the link to MathML file.
19420 (org-add-props
19421 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19422 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19423 'org-latex-src-embed-type (if latex-frag-type
19424 'paragraph 'character)))
19425 ;; Failed conversion. Return the LaTeX fragment verbatim
19426 latex-frag)))
19428 (declare-function org-export-get-backend "ox" (name))
19429 (declare-function org-export--get-global-options "ox" (&optional backend))
19430 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19431 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19432 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19433 (defun org-create-formula--latex-header ()
19434 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19435 (let ((info (org-combine-plists (org-export--get-global-options
19436 (org-export-get-backend 'latex))
19437 (org-export--get-inbuffer-options
19438 (org-export-get-backend 'latex)))))
19439 (org-latex-guess-babel-language
19440 (org-latex-guess-inputenc
19441 (org-splice-latex-header
19442 org-format-latex-header
19443 org-latex-default-packages-alist
19444 org-latex-packages-alist t
19445 (plist-get info :latex-header)))
19446 info)))
19448 (defun org--get-display-dpi ()
19449 "Get the DPI of the display.
19451 Assumes that the display has the same pixel width in the
19452 horizontal and vertical directions."
19453 (if (display-graphic-p)
19454 (round (/ (display-pixel-height)
19455 (/ (display-mm-height) 25.4)))
19456 (error "Attempt to calculate the dpi of a non-graphic display")))
19458 (defun org-create-formula-image
19459 (string tofile options buffer &optional processing-type)
19460 "Create an image from LaTeX source using external processes.
19462 The LaTeX STRING is saved to a temporary LaTeX file, then
19463 converted to an image file by process PROCESSING-TYPE defined in
19464 `org-preview-latex-process-alist'. A nil value defaults to
19465 `org-preview-latex-default-process'.
19467 The generated image file is eventually moved to TOFILE.
19469 The OPTIONS argument controls the size, foreground color and
19470 background color of the generated image.
19472 When BUFFER non-nil, this function is used for LaTeX previewing.
19473 Otherwise, it is used to deal with LaTeX snippets showed in
19474 a HTML file."
19475 (let* ((processing-type (or processing-type
19476 org-preview-latex-default-process))
19477 (processing-info
19478 (cdr (assq processing-type org-preview-latex-process-alist)))
19479 (programs (plist-get processing-info :programs))
19480 (error-message (or (plist-get processing-info :message) ""))
19481 (use-xcolor (plist-get processing-info :use-xcolor))
19482 (image-input-type (plist-get processing-info :image-input-type))
19483 (image-output-type (plist-get processing-info :image-output-type))
19484 (post-clean (or (plist-get processing-info :post-clean)
19485 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19486 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19487 (latex-header (or (plist-get processing-info :latex-header)
19488 (org-create-formula--latex-header)))
19489 (latex-compiler (plist-get processing-info :latex-compiler))
19490 (image-converter (plist-get processing-info :image-converter))
19491 (tmpdir temporary-file-directory)
19492 (texfilebase (make-temp-name
19493 (expand-file-name "orgtex" tmpdir)))
19494 (texfile (concat texfilebase ".tex"))
19495 (font-height (face-attribute 'default :height nil))
19496 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19497 '(1.0 . 1.0)))
19498 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19499 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19500 (dpi (* scale (floor (if buffer font-height 140.0))))
19501 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19502 "Black"))
19503 (bg (or (plist-get options (if buffer :background :html-background))
19504 "Transparent"))
19505 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19506 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19507 (dolist (program programs)
19508 (org-check-external-command program error-message))
19509 (if use-xcolor
19510 (progn (if (eq fg 'default)
19511 (setq fg (org-latex-color :foreground))
19512 (setq fg (org-latex-color-format fg)))
19513 (if (eq bg 'default)
19514 (setq bg (org-latex-color :background))
19515 (setq bg (org-latex-color-format
19516 (if (string= bg "Transparent") "white" bg))))
19517 (with-temp-file texfile
19518 (insert latex-header)
19519 (insert "\n\\begin{document}\n"
19520 "\\definecolor{fg}{rgb}{" fg "}\n"
19521 "\\definecolor{bg}{rgb}{" bg "}\n"
19522 "\n\\pagecolor{bg}\n"
19523 "\n{\\color{fg}\n"
19524 string
19525 "\n}\n"
19526 "\n\\end{document}\n")))
19527 (if (eq fg 'default)
19528 (setq fg (org-dvipng-color :foreground))
19529 (unless (string= fg "Transparent")
19530 (setq fg (org-dvipng-color-format fg))))
19531 (if (eq bg 'default)
19532 (setq bg (org-dvipng-color :background))
19533 (unless (string= bg "Transparent")
19534 (setq bg (org-dvipng-color-format bg))))
19535 (with-temp-file texfile
19536 (insert latex-header)
19537 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19539 (let* ((err-msg (format "Please adjust '%s' part of \
19540 `org-preview-latex-process-alist'."
19541 processing-type))
19542 (image-input-file
19543 (org-compile-file
19544 texfile latex-compiler image-input-type err-msg log-buf))
19545 (image-output-file
19546 (org-compile-file
19547 image-input-file image-converter image-output-type err-msg log-buf
19548 `((?F . ,(shell-quote-argument fg))
19549 (?B . ,(shell-quote-argument bg))
19550 (?D . ,(shell-quote-argument (format "%s" dpi)))
19551 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19552 (copy-file image-output-file tofile 'replace)
19553 (dolist (e post-clean)
19554 (when (file-exists-p (concat texfilebase e))
19555 (delete-file (concat texfilebase e))))
19556 image-output-file)))
19558 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19559 "Fill a LaTeX header template TPL.
19560 In the template, the following place holders will be recognized:
19562 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19563 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19564 [PACKAGES] \\usepackage statements for PKG
19565 [NO-PACKAGES] do not include PKG
19566 [EXTRA] the string EXTRA
19567 [NO-EXTRA] do not include EXTRA
19569 For backward compatibility, if both the positive and the negative place
19570 holder is missing, the positive one (without the \"NO-\") will be
19571 assumed to be present at the end of the template.
19572 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19573 EXTRA is a string.
19574 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19575 (let (rpl (end ""))
19576 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19577 (setq rpl (if (or (match-end 1) (not def-pkg))
19578 "" (org-latex-packages-to-string def-pkg snippets-p t))
19579 tpl (replace-match rpl t t tpl))
19580 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19582 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19583 (setq rpl (if (or (match-end 1) (not pkg))
19584 "" (org-latex-packages-to-string pkg snippets-p t))
19585 tpl (replace-match rpl t t tpl))
19586 (when pkg (setq end
19587 (concat end "\n"
19588 (org-latex-packages-to-string pkg snippets-p)))))
19590 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19591 (setq rpl (if (or (match-end 1) (not extra))
19592 "" (concat extra "\n"))
19593 tpl (replace-match rpl t t tpl))
19594 (when (and extra (string-match "\\S-" extra))
19595 (setq end (concat end "\n" extra))))
19597 (if (string-match "\\S-" end)
19598 (concat tpl "\n" end)
19599 tpl)))
19601 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19602 "Turn an alist of packages into a string with the \\usepackage macros."
19603 (setq pkg (mapconcat (lambda(p)
19604 (cond
19605 ((stringp p) p)
19606 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19607 (format "%% Package %s omitted" (cadr p)))
19608 ((equal "" (car p))
19609 (format "\\usepackage{%s}" (cadr p)))
19611 (format "\\usepackage[%s]{%s}"
19612 (car p) (cadr p)))))
19614 "\n"))
19615 (if newline (concat pkg "\n") pkg))
19617 (defun org-dvipng-color (attr)
19618 "Return a RGB color specification for dvipng."
19619 (apply #'format "rgb %s %s %s"
19620 (mapcar #'org-normalize-color
19621 (color-values (face-attribute 'default attr nil)))))
19623 (defun org-dvipng-color-format (color-name)
19624 "Convert COLOR-NAME to a RGB color value for dvipng."
19625 (apply 'format "rgb %s %s %s"
19626 (mapcar 'org-normalize-color
19627 (color-values color-name))))
19629 (defun org-latex-color (attr)
19630 "Return a RGB color for the LaTeX color package."
19631 (apply #'format "%s,%s,%s"
19632 (mapcar #'org-normalize-color
19633 (color-values (face-attribute 'default attr nil)))))
19635 (defun org-latex-color-format (color-name)
19636 "Convert COLOR-NAME to a RGB color value."
19637 (apply 'format "%s,%s,%s"
19638 (mapcar 'org-normalize-color
19639 (color-values color-name))))
19641 (defun org-normalize-color (value)
19642 "Return string to be used as color value for an RGB component."
19643 (format "%g" (/ value 65535.0)))
19647 ;; Image display
19649 (defvar-local org-inline-image-overlays nil)
19651 (defun org-toggle-inline-images (&optional include-linked)
19652 "Toggle the display of inline images.
19653 INCLUDE-LINKED is passed to `org-display-inline-images'."
19654 (interactive "P")
19655 (if org-inline-image-overlays
19656 (progn
19657 (org-remove-inline-images)
19658 (when (called-interactively-p 'interactive)
19659 (message "Inline image display turned off")))
19660 (org-display-inline-images include-linked)
19661 (when (called-interactively-p 'interactive)
19662 (message (if org-inline-image-overlays
19663 (format "%d images displayed inline"
19664 (length org-inline-image-overlays))
19665 "No images to display inline")))))
19667 (defun org-redisplay-inline-images ()
19668 "Refresh the display of inline images."
19669 (interactive)
19670 (if (not org-inline-image-overlays)
19671 (org-toggle-inline-images)
19672 (org-toggle-inline-images)
19673 (org-toggle-inline-images)))
19675 (defun org-display-inline-images (&optional include-linked refresh beg end)
19676 "Display inline images.
19678 An inline image is a link which follows either of these
19679 conventions:
19681 1. Its path is a file with an extension matching return value
19682 from `image-file-name-regexp' and it has no contents.
19684 2. Its description consists in a single link of the previous
19685 type.
19687 When optional argument INCLUDE-LINKED is non-nil, also links with
19688 a text description part will be inlined. This can be nice for
19689 a quick look at those images, but it does not reflect what
19690 exported files will look like.
19692 When optional argument REFRESH is non-nil, refresh existing
19693 images between BEG and END. This will create new image displays
19694 only if necessary. BEG and END default to the buffer
19695 boundaries."
19696 (interactive "P")
19697 (when (display-graphic-p)
19698 (unless refresh
19699 (org-remove-inline-images)
19700 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19701 (org-with-wide-buffer
19702 (goto-char (or beg (point-min)))
19703 (let ((case-fold-search t)
19704 (file-extension-re (image-file-name-regexp)))
19705 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19706 (let ((link (save-match-data (org-element-context))))
19707 ;; Check if we're at an inline image.
19708 (when (and (equal (org-element-property :type link) "file")
19709 (or include-linked
19710 (not (org-element-property :contents-begin link)))
19711 (let ((parent (org-element-property :parent link)))
19712 (or (not (eq (org-element-type parent) 'link))
19713 (not (cdr (org-element-contents parent)))))
19714 (string-match-p file-extension-re
19715 (org-element-property :path link)))
19716 (let ((file (expand-file-name
19717 (org-link-unescape
19718 (org-element-property :path link)))))
19719 (when (file-exists-p file)
19720 (let ((width
19721 ;; Apply `org-image-actual-width' specifications.
19722 (cond
19723 ((not (image-type-available-p 'imagemagick)) nil)
19724 ((eq org-image-actual-width t) nil)
19725 ((listp org-image-actual-width)
19727 ;; First try to find a width among
19728 ;; attributes associated to the paragraph
19729 ;; containing link.
19730 (let ((paragraph
19731 (let ((e link))
19732 (while (and (setq e (org-element-property
19733 :parent e))
19734 (not (eq (org-element-type e)
19735 'paragraph))))
19736 e)))
19737 (when paragraph
19738 (save-excursion
19739 (goto-char (org-element-property :begin paragraph))
19740 (when
19741 (re-search-forward
19742 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19743 (org-element-property
19744 :post-affiliated paragraph)
19746 (string-to-number (match-string 1))))))
19747 ;; Otherwise, fall-back to provided number.
19748 (car org-image-actual-width)))
19749 ((numberp org-image-actual-width)
19750 org-image-actual-width)))
19751 (old (get-char-property-and-overlay
19752 (org-element-property :begin link)
19753 'org-image-overlay)))
19754 (if (and (car-safe old) refresh)
19755 (image-refresh (overlay-get (cdr old) 'display))
19756 (let ((image (create-image file
19757 (and width 'imagemagick)
19759 :width width)))
19760 (when image
19761 (let* ((link
19762 ;; If inline image is the description
19763 ;; of another link, be sure to
19764 ;; consider the latter as the one to
19765 ;; apply the overlay on.
19766 (let ((parent
19767 (org-element-property :parent link)))
19768 (if (eq (org-element-type parent) 'link)
19769 parent
19770 link)))
19771 (ov (make-overlay
19772 (org-element-property :begin link)
19773 (progn
19774 (goto-char
19775 (org-element-property :end link))
19776 (skip-chars-backward " \t")
19777 (point)))))
19778 (overlay-put ov 'display image)
19779 (overlay-put ov 'face 'default)
19780 (overlay-put ov 'org-image-overlay t)
19781 (overlay-put
19782 ov 'modification-hooks
19783 (list 'org-display-inline-remove-overlay))
19784 (push ov org-inline-image-overlays)))))))))))))))
19786 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19787 "Remove inline-display overlay if a corresponding region is modified."
19788 (let ((inhibit-modification-hooks t))
19789 (when (and ov after)
19790 (delete ov org-inline-image-overlays)
19791 (delete-overlay ov))))
19793 (defun org-remove-inline-images ()
19794 "Remove inline display of images."
19795 (interactive)
19796 (mapc #'delete-overlay org-inline-image-overlays)
19797 (setq org-inline-image-overlays nil))
19799 ;;;; Key bindings
19801 ;; Outline functions from `outline-mode-prefix-map'
19802 ;; that can be remapped in Org:
19803 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19804 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19805 (define-key org-mode-map [remap outline-forward-same-level]
19806 'org-forward-heading-same-level)
19807 (define-key org-mode-map [remap outline-backward-same-level]
19808 'org-backward-heading-same-level)
19809 (define-key org-mode-map [remap outline-show-branches]
19810 'org-kill-note-or-show-branches)
19811 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19812 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19813 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19814 (define-key org-mode-map [remap outline-next-visible-heading]
19815 'org-next-visible-heading)
19816 (define-key org-mode-map [remap outline-previous-visible-heading]
19817 'org-previous-visible-heading)
19818 (define-key org-mode-map [remap show-children] 'org-show-children)
19820 ;; Outline functions from `outline-mode-prefix-map' that can not
19821 ;; be remapped in Org:
19823 ;; - the column "key binding" shows whether the Outline function is still
19824 ;; available in Org mode on the same key that it has been bound to in
19825 ;; Outline mode:
19826 ;; - "overridden": key used for a different functionality in Org mode
19827 ;; - else: key still bound to the same Outline function in Org mode
19829 ;; | Outline function | key binding | Org replacement |
19830 ;; |------------------------------------+-------------+--------------------------|
19831 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19832 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19833 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19834 ;; | `show-entry' | overridden | no replacement |
19835 ;; | `show-branches' | `C-c C-k' | still same function |
19836 ;; | `show-subtree' | overridden | visibility cycling |
19837 ;; | `show-all' | overridden | no replacement |
19838 ;; | `hide-subtree' | overridden | visibility cycling |
19839 ;; | `hide-body' | overridden | no replacement |
19840 ;; | `hide-entry' | overridden | visibility cycling |
19841 ;; | `hide-leaves' | overridden | no replacement |
19842 ;; | `hide-sublevels' | overridden | no replacement |
19843 ;; | `hide-other' | overridden | no replacement |
19845 ;; Make `C-c C-x' a prefix key
19846 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19848 ;; TAB key with modifiers
19849 (org-defkey org-mode-map "\C-i" 'org-cycle)
19850 (org-defkey org-mode-map [(tab)] 'org-cycle)
19851 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19852 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19853 ;; The following line is necessary under Suse GNU/Linux
19854 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19855 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19856 (define-key org-mode-map [backtab] 'org-shifttab)
19858 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19859 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19860 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19862 ;; Cursor keys with modifiers
19863 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19864 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19865 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19866 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19868 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19869 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19870 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19871 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19872 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19873 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19875 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19876 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19877 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19878 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19880 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19881 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19882 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19883 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19885 ;; Babel keys
19886 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19887 (dolist (pair org-babel-key-bindings)
19888 (define-key org-babel-map (car pair) (cdr pair)))
19890 ;;; Extra keys for tty access.
19891 ;; We only set them when really needed because otherwise the
19892 ;; menus don't show the simple keys
19894 (when (or org-use-extra-keys (not window-system))
19895 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19896 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19897 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19898 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19899 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19900 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19901 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19902 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19903 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19904 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19905 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19906 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19907 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19908 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19909 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19910 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19911 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19912 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19913 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19914 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19915 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19916 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19917 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19918 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19919 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19920 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19921 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19922 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19924 ;; All the other keys
19926 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19927 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19928 (if (boundp 'narrow-map)
19929 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19930 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19931 (if (boundp 'narrow-map)
19932 (org-defkey narrow-map "b" 'org-narrow-to-block)
19933 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19934 (if (boundp 'narrow-map)
19935 (org-defkey narrow-map "e" 'org-narrow-to-element)
19936 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19937 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19938 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19939 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19940 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19941 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19942 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19943 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19944 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19945 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19946 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19947 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19948 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19949 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19950 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19951 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19952 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19953 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19954 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19955 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19956 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19957 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19958 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19959 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19960 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19961 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19962 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19963 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19964 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19965 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19966 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19967 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19968 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19969 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19970 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19971 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19972 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19973 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19974 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19975 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19976 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19977 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19978 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19979 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19980 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19981 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19982 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19983 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19984 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19985 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19986 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19987 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19988 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19989 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19990 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19991 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19992 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19993 (org-defkey org-mode-map "\C-c^" 'org-sort)
19994 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19995 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19996 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19997 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19998 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19999 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
20000 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
20001 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
20002 (org-defkey org-mode-map "\C-m" 'org-return)
20003 (org-defkey org-mode-map "\C-j" 'org-return-indent)
20004 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
20005 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
20006 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
20007 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
20008 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
20009 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
20010 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
20011 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
20012 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
20013 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
20014 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
20015 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
20016 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
20017 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
20018 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
20019 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
20020 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
20021 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
20022 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
20023 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
20024 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
20025 (org-defkey org-mode-map "\M-h" 'org-mark-element)
20026 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
20027 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
20029 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
20030 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
20031 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
20033 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
20034 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
20035 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
20036 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
20037 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
20038 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
20039 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
20040 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
20041 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
20042 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
20043 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
20044 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
20045 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
20046 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
20047 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
20048 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
20049 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
20050 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
20051 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
20052 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
20053 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
20054 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
20056 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
20057 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
20058 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
20059 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
20060 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
20062 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20064 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20066 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20067 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20069 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20072 (defconst org-speed-commands-default
20074 ("Outline Navigation")
20075 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20076 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20077 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20078 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20079 ("F" . org-next-block)
20080 ("B" . org-previous-block)
20081 ("u" . (org-speed-move-safe 'outline-up-heading))
20082 ("j" . org-goto)
20083 ("g" . (org-refile t))
20084 ("Outline Visibility")
20085 ("c" . org-cycle)
20086 ("C" . org-shifttab)
20087 (" " . org-display-outline-path)
20088 ("s" . org-narrow-to-subtree)
20089 ("=" . org-columns)
20090 ("Outline Structure Editing")
20091 ("U" . org-metaup)
20092 ("D" . org-metadown)
20093 ("r" . org-metaright)
20094 ("l" . org-metaleft)
20095 ("R" . org-shiftmetaright)
20096 ("L" . org-shiftmetaleft)
20097 ("i" . (progn (forward-char 1) (call-interactively
20098 'org-insert-heading-respect-content)))
20099 ("^" . org-sort)
20100 ("w" . org-refile)
20101 ("a" . org-archive-subtree-default-with-confirmation)
20102 ("@" . org-mark-subtree)
20103 ("#" . org-toggle-comment)
20104 ("Clock Commands")
20105 ("I" . org-clock-in)
20106 ("O" . org-clock-out)
20107 ("Meta Data Editing")
20108 ("t" . org-todo)
20109 ("," . (org-priority))
20110 ("0" . (org-priority ?\ ))
20111 ("1" . (org-priority ?A))
20112 ("2" . (org-priority ?B))
20113 ("3" . (org-priority ?C))
20114 (":" . org-set-tags-command)
20115 ("e" . org-set-effort)
20116 ("E" . org-inc-effort)
20117 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20118 (org-entry-put (point) "APPT_WARNTIME" m)))
20119 ("Agenda Views etc")
20120 ("v" . org-agenda)
20121 ("/" . org-sparse-tree)
20122 ("Misc")
20123 ("o" . org-open-at-point)
20124 ("?" . org-speed-command-help)
20125 ("<" . (org-agenda-set-restriction-lock 'subtree))
20126 (">" . (org-agenda-remove-restriction-lock))
20128 "The default speed commands.")
20130 (defun org-print-speed-command (e)
20131 (if (> (length (car e)) 1)
20132 (progn
20133 (princ "\n")
20134 (princ (car e))
20135 (princ "\n")
20136 (princ (make-string (length (car e)) ?-))
20137 (princ "\n"))
20138 (princ (car e))
20139 (princ " ")
20140 (if (symbolp (cdr e))
20141 (princ (symbol-name (cdr e)))
20142 (prin1 (cdr e)))
20143 (princ "\n")))
20145 (defun org-speed-command-help ()
20146 "Show the available speed commands."
20147 (interactive)
20148 (if (not org-use-speed-commands)
20149 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20150 (with-output-to-temp-buffer "*Help*"
20151 (princ "User-defined Speed commands\n===========================\n")
20152 (mapc #'org-print-speed-command org-speed-commands-user)
20153 (princ "\n")
20154 (princ "Built-in Speed commands\n=======================\n")
20155 (mapc #'org-print-speed-command org-speed-commands-default))
20156 (with-current-buffer "*Help*"
20157 (setq truncate-lines t))))
20159 (defun org-speed-move-safe (cmd)
20160 "Execute CMD, but make sure that the cursor always ends up in a headline.
20161 If not, return to the original position and throw an error."
20162 (interactive)
20163 (let ((pos (point)))
20164 (call-interactively cmd)
20165 (unless (and (bolp) (org-at-heading-p))
20166 (goto-char pos)
20167 (error "Boundary reached while executing %s" cmd))))
20169 (defvar org-self-insert-command-undo-counter 0)
20171 (defvar org-table-auto-blank-field) ; defined in org-table.el
20172 (defvar org-speed-command nil)
20174 (defun org-speed-command-activate (keys)
20175 "Hook for activating single-letter speed commands.
20176 `org-speed-commands-default' specifies a minimal command set.
20177 Use `org-speed-commands-user' for further customization."
20178 (when (or (and (bolp) (looking-at org-outline-regexp))
20179 (and (functionp org-use-speed-commands)
20180 (funcall org-use-speed-commands)))
20181 (cdr (assoc keys (append org-speed-commands-user
20182 org-speed-commands-default)))))
20184 (defun org-babel-speed-command-activate (keys)
20185 "Hook for activating single-letter code block commands."
20186 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20187 (cdr (assoc keys org-babel-key-bindings))))
20189 (defcustom org-speed-command-hook
20190 '(org-speed-command-default-hook org-babel-speed-command-hook)
20191 "Hook for activating speed commands at strategic locations.
20192 Hook functions are called in sequence until a valid handler is
20193 found.
20195 Each hook takes a single argument, a user-pressed command key
20196 which is also a `self-insert-command' from the global map.
20198 Within the hook, examine the cursor position and the command key
20199 and return nil or a valid handler as appropriate. Handler could
20200 be one of an interactive command, a function, or a form.
20202 Set `org-use-speed-commands' to non-nil value to enable this
20203 hook. The default setting is `org-speed-command-activate'."
20204 :group 'org-structure
20205 :version "24.1"
20206 :type 'hook)
20208 (defun org-self-insert-command (N)
20209 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20210 If the cursor is in a table looking at whitespace, the whitespace is
20211 overwritten, and the table is not marked as requiring realignment."
20212 (interactive "p")
20213 (org-check-before-invisible-edit 'insert)
20214 (cond
20215 ((and org-use-speed-commands
20216 (let ((kv (this-command-keys-vector)))
20217 (setq org-speed-command
20218 (run-hook-with-args-until-success
20219 'org-speed-command-hook
20220 (make-string 1 (aref kv (1- (length kv))))))))
20221 (cond
20222 ((commandp org-speed-command)
20223 (setq this-command org-speed-command)
20224 (call-interactively org-speed-command))
20225 ((functionp org-speed-command)
20226 (funcall org-speed-command))
20227 ((and org-speed-command (listp org-speed-command))
20228 (eval org-speed-command))
20229 (t (let (org-use-speed-commands)
20230 (call-interactively 'org-self-insert-command)))))
20231 ((and
20232 (org-at-table-p)
20233 (progn
20234 ;; Check if we blank the field, and if that triggers align.
20235 (and (featurep 'org-table) org-table-auto-blank-field
20236 (memq last-command
20237 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20238 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20239 ;; Got extra space, this field does not determine
20240 ;; column width.
20241 (let (org-table-may-need-update) (org-table-blank-field))
20242 ;; No extra space, this field may determine column
20243 ;; width.
20244 (org-table-blank-field)))
20246 (eq N 1)
20247 (looking-at "[^|\n]* \\( \\)|"))
20248 ;; There is room for insertion without re-aligning the table.
20249 (delete-region (match-beginning 1) (match-end 1))
20250 (self-insert-command N))
20252 (setq org-table-may-need-update t)
20253 (self-insert-command N)
20254 (org-fix-tags-on-the-fly)
20255 (when org-self-insert-cluster-for-undo
20256 (if (not (eq last-command 'org-self-insert-command))
20257 (setq org-self-insert-command-undo-counter 1)
20258 (if (>= org-self-insert-command-undo-counter 20)
20259 (setq org-self-insert-command-undo-counter 1)
20260 (and (> org-self-insert-command-undo-counter 0)
20261 buffer-undo-list (listp buffer-undo-list)
20262 (not (cadr buffer-undo-list)) ; remove nil entry
20263 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20264 (setq org-self-insert-command-undo-counter
20265 (1+ org-self-insert-command-undo-counter))))))))
20267 (defun org-check-before-invisible-edit (kind)
20268 "Check is editing if kind KIND would be dangerous with invisible text around.
20269 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20270 ;; First, try to get out of here as quickly as possible, to reduce overhead
20271 (when (and org-catch-invisible-edits
20272 (or (not (boundp 'visible-mode)) (not visible-mode))
20273 (or (get-char-property (point) 'invisible)
20274 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20275 ;; OK, we need to take a closer look
20276 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20277 (invisible-before-point (unless (bobp) (get-char-property
20278 (1- (point)) 'invisible)))
20279 (border-and-ok-direction
20281 ;; Check if we are acting predictably before invisible text
20282 (and invisible-at-point (not invisible-before-point)
20283 (memq kind '(insert delete-backward)))
20284 ;; Check if we are acting predictably after invisible text
20285 ;; This works not well, and I have turned it off. It seems
20286 ;; better to always show and stop after invisible text.
20287 ;; (and (not invisible-at-point) invisible-before-point
20288 ;; (memq kind '(insert delete)))
20290 (when (or (memq invisible-at-point '(outline org-hide-block t))
20291 (memq invisible-before-point '(outline org-hide-block t)))
20292 (when (eq org-catch-invisible-edits 'error)
20293 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20294 (if (and org-custom-properties-overlays
20295 (y-or-n-p "Display invisible properties in this buffer? "))
20296 (org-toggle-custom-properties-visibility)
20297 ;; Make the area visible
20298 (save-excursion
20299 (when invisible-before-point
20300 (goto-char (previous-single-char-property-change
20301 (point) 'invisible)))
20302 (outline-show-subtree))
20303 (cond
20304 ((eq org-catch-invisible-edits 'show)
20305 ;; That's it, we do the edit after showing
20306 (message
20307 "Unfolding invisible region around point before editing")
20308 (sit-for 1))
20309 ((and (eq org-catch-invisible-edits 'smart)
20310 border-and-ok-direction)
20311 (message "Unfolding invisible region around point before editing"))
20313 ;; Don't do the edit, make the user repeat it in full visibility
20314 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20316 (defun org-fix-tags-on-the-fly ()
20317 (when (and (equal (char-after (point-at-bol)) ?*)
20318 (org-at-heading-p))
20319 (org-align-tags-here org-tags-column)))
20321 (defun org-delete-backward-char (N)
20322 "Like `delete-backward-char', insert whitespace at field end in tables.
20323 When deleting backwards, in tables this function will insert whitespace in
20324 front of the next \"|\" separator, to keep the table aligned. The table will
20325 still be marked for re-alignment if the field did fill the entire column,
20326 because, in this case the deletion might narrow the column."
20327 (interactive "p")
20328 (save-match-data
20329 (org-check-before-invisible-edit 'delete-backward)
20330 (if (and (org-at-table-p)
20331 (eq N 1)
20332 (string-match "|" (buffer-substring (point-at-bol) (point)))
20333 (looking-at ".*?|"))
20334 (let ((pos (point))
20335 (noalign (looking-at "[^|\n\r]* |"))
20336 (c org-table-may-need-update))
20337 (backward-delete-char N)
20338 (unless overwrite-mode
20339 (skip-chars-forward "^|")
20340 (insert " ")
20341 (goto-char (1- pos)))
20342 ;; noalign: if there were two spaces at the end, this field
20343 ;; does not determine the width of the column.
20344 (when noalign (setq org-table-may-need-update c)))
20345 (backward-delete-char N)
20346 (org-fix-tags-on-the-fly))))
20348 (defun org-delete-char (N)
20349 "Like `delete-char', but insert whitespace at field end in tables.
20350 When deleting characters, in tables this function will insert whitespace in
20351 front of the next \"|\" separator, to keep the table aligned. The table will
20352 still be marked for re-alignment if the field did fill the entire column,
20353 because, in this case the deletion might narrow the column."
20354 (interactive "p")
20355 (save-match-data
20356 (org-check-before-invisible-edit 'delete)
20357 (if (and (org-at-table-p)
20358 (not (bolp))
20359 (not (= (char-after) ?|))
20360 (eq N 1))
20361 (if (looking-at ".*?|")
20362 (let ((pos (point))
20363 (noalign (looking-at "[^|\n\r]* |"))
20364 (c org-table-may-need-update))
20365 (replace-match
20366 (concat (substring (match-string 0) 1 -1) " |") nil t)
20367 (goto-char pos)
20368 ;; noalign: if there were two spaces at the end, this field
20369 ;; does not determine the width of the column.
20370 (when noalign (setq org-table-may-need-update c)))
20371 (delete-char N))
20372 (delete-char N)
20373 (org-fix-tags-on-the-fly))))
20375 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20376 (put 'org-self-insert-command 'delete-selection
20377 (lambda ()
20378 (not (run-hook-with-args-until-success
20379 'self-insert-uses-region-functions))))
20380 (put 'orgtbl-self-insert-command 'delete-selection
20381 (lambda ()
20382 (not (run-hook-with-args-until-success
20383 'self-insert-uses-region-functions))))
20384 (put 'org-delete-char 'delete-selection 'supersede)
20385 (put 'org-delete-backward-char 'delete-selection 'supersede)
20386 (put 'org-yank 'delete-selection 'yank)
20388 ;; Make `flyspell-mode' delay after some commands
20389 (put 'org-self-insert-command 'flyspell-delayed t)
20390 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20391 (put 'org-delete-char 'flyspell-delayed t)
20392 (put 'org-delete-backward-char 'flyspell-delayed t)
20394 ;; Make pabbrev-mode expand after Org mode commands
20395 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20396 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20398 (defun org-remap (map &rest commands)
20399 "In MAP, remap the functions given in COMMANDS.
20400 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20401 (let (new old)
20402 (while commands
20403 (setq old (pop commands) new (pop commands))
20404 (if (fboundp 'command-remapping)
20405 (org-defkey map (vector 'remap old) new)
20406 (substitute-key-definition old new map global-map)))))
20408 (defun org-transpose-words ()
20409 "Transpose words for Org.
20410 This uses the `org-mode-transpose-word-syntax-table' syntax
20411 table, which interprets characters in `org-emphasis-alist' as
20412 word constituents."
20413 (interactive)
20414 (with-syntax-table org-mode-transpose-word-syntax-table
20415 (call-interactively 'transpose-words)))
20416 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20418 (when (eq org-enable-table-editor 'optimized)
20419 ;; If the user wants maximum table support, we need to hijack
20420 ;; some standard editing functions
20421 (org-remap org-mode-map
20422 'self-insert-command 'org-self-insert-command
20423 'delete-char 'org-delete-char
20424 'delete-backward-char 'org-delete-backward-char)
20425 (org-defkey org-mode-map "|" 'org-force-self-insert))
20427 (defvar org-ctrl-c-ctrl-c-hook nil
20428 "Hook for functions attaching themselves to `C-c C-c'.
20430 This can be used to add additional functionality to the C-c C-c
20431 key which executes context-dependent commands. This hook is run
20432 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20433 run after the last test.
20435 Each function will be called with no arguments. The function
20436 must check if the context is appropriate for it to act. If yes,
20437 it should do its thing and then return a non-nil value. If the
20438 context is wrong, just do nothing and return nil.")
20440 (defvar org-ctrl-c-ctrl-c-final-hook nil
20441 "Hook for functions attaching themselves to `C-c C-c'.
20443 This can be used to add additional functionality to the C-c C-c
20444 key which executes context-dependent commands. This hook is run
20445 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20446 before the first test.
20448 Each function will be called with no arguments. The function
20449 must check if the context is appropriate for it to act. If yes,
20450 it should do its thing and then return a non-nil value. If the
20451 context is wrong, just do nothing and return nil.")
20453 (defvar org-tab-first-hook nil
20454 "Hook for functions to attach themselves to TAB.
20455 See `org-ctrl-c-ctrl-c-hook' for more information.
20456 This hook runs as the first action when TAB is pressed, even before
20457 `org-cycle' messes around with the `outline-regexp' to cater for
20458 inline tasks and plain list item folding.
20459 If any function in this hook returns t, any other actions that
20460 would have been caused by TAB (such as table field motion or visibility
20461 cycling) will not occur.")
20463 (defvar org-tab-after-check-for-table-hook nil
20464 "Hook for functions to attach themselves to TAB.
20465 See `org-ctrl-c-ctrl-c-hook' for more information.
20466 This hook runs after it has been established that the cursor is not in a
20467 table, but before checking if the cursor is in a headline or if global cycling
20468 should be done.
20469 If any function in this hook returns t, not other actions like visibility
20470 cycling will be done.")
20472 (defvar org-tab-after-check-for-cycling-hook nil
20473 "Hook for functions to attach themselves to TAB.
20474 See `org-ctrl-c-ctrl-c-hook' for more information.
20475 This hook runs after it has been established that not table field motion and
20476 not visibility should be done because of current context. This is probably
20477 the place where a package like yasnippets can hook in.")
20479 (defvar org-tab-before-tab-emulation-hook nil
20480 "Hook for functions to attach themselves to TAB.
20481 See `org-ctrl-c-ctrl-c-hook' for more information.
20482 This hook runs after every other options for TAB have been exhausted, but
20483 before indentation and \t insertion takes place.")
20485 (defvar org-metaleft-hook nil
20486 "Hook for functions attaching themselves to `M-left'.
20487 See `org-ctrl-c-ctrl-c-hook' for more information.")
20488 (defvar org-metaright-hook nil
20489 "Hook for functions attaching themselves to `M-right'.
20490 See `org-ctrl-c-ctrl-c-hook' for more information.")
20491 (defvar org-metaup-hook nil
20492 "Hook for functions attaching themselves to `M-up'.
20493 See `org-ctrl-c-ctrl-c-hook' for more information.")
20494 (defvar org-metadown-hook nil
20495 "Hook for functions attaching themselves to `M-down'.
20496 See `org-ctrl-c-ctrl-c-hook' for more information.")
20497 (defvar org-shiftmetaleft-hook nil
20498 "Hook for functions attaching themselves to `M-S-left'.
20499 See `org-ctrl-c-ctrl-c-hook' for more information.")
20500 (defvar org-shiftmetaright-hook nil
20501 "Hook for functions attaching themselves to `M-S-right'.
20502 See `org-ctrl-c-ctrl-c-hook' for more information.")
20503 (defvar org-shiftmetaup-hook nil
20504 "Hook for functions attaching themselves to `M-S-up'.
20505 See `org-ctrl-c-ctrl-c-hook' for more information.")
20506 (defvar org-shiftmetadown-hook nil
20507 "Hook for functions attaching themselves to `M-S-down'.
20508 See `org-ctrl-c-ctrl-c-hook' for more information.")
20509 (defvar org-metareturn-hook nil
20510 "Hook for functions attaching themselves to `M-RET'.
20511 See `org-ctrl-c-ctrl-c-hook' for more information.")
20512 (defvar org-shiftup-hook nil
20513 "Hook for functions attaching themselves to `S-up'.
20514 See `org-ctrl-c-ctrl-c-hook' for more information.")
20515 (defvar org-shiftup-final-hook nil
20516 "Hook for functions attaching themselves to `S-up'.
20517 This one runs after all other options except shift-select have been excluded.
20518 See `org-ctrl-c-ctrl-c-hook' for more information.")
20519 (defvar org-shiftdown-hook nil
20520 "Hook for functions attaching themselves to `S-down'.
20521 See `org-ctrl-c-ctrl-c-hook' for more information.")
20522 (defvar org-shiftdown-final-hook nil
20523 "Hook for functions attaching themselves to `S-down'.
20524 This one runs after all other options except shift-select have been excluded.
20525 See `org-ctrl-c-ctrl-c-hook' for more information.")
20526 (defvar org-shiftleft-hook nil
20527 "Hook for functions attaching themselves to `S-left'.
20528 See `org-ctrl-c-ctrl-c-hook' for more information.")
20529 (defvar org-shiftleft-final-hook nil
20530 "Hook for functions attaching themselves to `S-left'.
20531 This one runs after all other options except shift-select have been excluded.
20532 See `org-ctrl-c-ctrl-c-hook' for more information.")
20533 (defvar org-shiftright-hook nil
20534 "Hook for functions attaching themselves to `S-right'.
20535 See `org-ctrl-c-ctrl-c-hook' for more information.")
20536 (defvar org-shiftright-final-hook nil
20537 "Hook for functions attaching themselves to `S-right'.
20538 This one runs after all other options except shift-select have been excluded.
20539 See `org-ctrl-c-ctrl-c-hook' for more information.")
20541 (defun org-modifier-cursor-error ()
20542 "Throw an error, a modified cursor command was applied in wrong context."
20543 (user-error "This command is active in special context like tables, headlines or items"))
20545 (defun org-shiftselect-error ()
20546 "Throw an error because Shift-Cursor command was applied in wrong context."
20547 (if (and (boundp 'shift-select-mode) shift-select-mode)
20548 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20549 (user-error "This command works only in special context like headlines or timestamps")))
20551 (defun org-call-for-shift-select (cmd)
20552 (let ((this-command-keys-shift-translated t))
20553 (call-interactively cmd)))
20555 (defun org-shifttab (&optional arg)
20556 "Global visibility cycling or move to previous table field.
20557 Call `org-table-previous-field' within a table.
20558 When ARG is nil, cycle globally through visibility states.
20559 When ARG is a numeric prefix, show contents of this level."
20560 (interactive "P")
20561 (cond
20562 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20563 ((integerp arg)
20564 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20565 (message "Content view to level: %d" arg)
20566 (org-content (prefix-numeric-value arg2))
20567 (org-cycle-show-empty-lines t)
20568 (setq org-cycle-global-status 'overview)))
20569 (t (call-interactively 'org-global-cycle))))
20571 (defun org-shiftmetaleft ()
20572 "Promote subtree or delete table column.
20573 Calls `org-promote-subtree', `org-outdent-item-tree', or
20574 `org-table-delete-column', depending on context. See the
20575 individual commands for more information."
20576 (interactive)
20577 (cond
20578 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20579 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20580 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20581 ((if (not (org-region-active-p)) (org-at-item-p)
20582 (save-excursion (goto-char (region-beginning))
20583 (org-at-item-p)))
20584 (call-interactively 'org-outdent-item-tree))
20585 (t (org-modifier-cursor-error))))
20587 (defun org-shiftmetaright ()
20588 "Demote subtree or insert table column.
20589 Calls `org-demote-subtree', `org-indent-item-tree', or
20590 `org-table-insert-column', depending on context. See the
20591 individual commands for more information."
20592 (interactive)
20593 (cond
20594 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20595 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20596 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20597 ((if (not (org-region-active-p)) (org-at-item-p)
20598 (save-excursion (goto-char (region-beginning))
20599 (org-at-item-p)))
20600 (call-interactively 'org-indent-item-tree))
20601 (t (org-modifier-cursor-error))))
20603 (defun org-shiftmetaup (&optional _arg)
20604 "Drag the line at point up.
20605 In a table, kill the current row.
20606 On a clock timestamp, update the value of the timestamp like `S-<up>'
20607 but also adjust the previous clocked item in the clock history.
20608 Everywhere else, drag the line at point up."
20609 (interactive "P")
20610 (cond
20611 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20612 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20613 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20614 (call-interactively 'org-timestamp-up)))
20615 (t (call-interactively 'org-drag-line-backward))))
20617 (defun org-shiftmetadown (&optional _arg)
20618 "Drag the line at point down.
20619 In a table, insert an empty row at the current line.
20620 On a clock timestamp, update the value of the timestamp like `S-<down>'
20621 but also adjust the previous clocked item in the clock history.
20622 Everywhere else, drag the line at point down."
20623 (interactive "P")
20624 (cond
20625 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20626 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20627 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20628 (call-interactively 'org-timestamp-down)))
20629 (t (call-interactively 'org-drag-line-forward))))
20631 (defsubst org-hidden-tree-error ()
20632 (user-error
20633 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20635 (defun org-metaleft (&optional _arg)
20636 "Promote heading, list item at point or move table column left.
20638 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20639 depending on context. With no specific context, calls the Emacs
20640 default `backward-word'. See the individual commands for more
20641 information.
20643 This function runs the hook `org-metaleft-hook' as a first step,
20644 and returns at first non-nil value."
20645 (interactive "P")
20646 (cond
20647 ((run-hook-with-args-until-success 'org-metaleft-hook))
20648 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20649 ((org-with-limited-levels
20650 (or (org-at-heading-p)
20651 (and (org-region-active-p)
20652 (save-excursion
20653 (goto-char (region-beginning))
20654 (org-at-heading-p)))))
20655 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20656 (call-interactively 'org-do-promote))
20657 ;; At an inline task.
20658 ((org-at-heading-p)
20659 (call-interactively 'org-inlinetask-promote))
20660 ((or (org-at-item-p)
20661 (and (org-region-active-p)
20662 (save-excursion
20663 (goto-char (region-beginning))
20664 (org-at-item-p))))
20665 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20666 (call-interactively 'org-outdent-item))
20667 (t (call-interactively 'backward-word))))
20669 (defun org-metaright (&optional _arg)
20670 "Demote heading, list item at point or move table column right.
20672 In front of a drawer or a block keyword, indent it correctly.
20674 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20675 `org-indnet-drawer' or `org-indent-block' depending on context.
20676 With no specific context, calls the Emacs default `forward-word'.
20677 See the individual commands for more information.
20679 This function runs the hook `org-metaright-hook' as a first step,
20680 and returns at first non-nil value."
20681 (interactive "P")
20682 (cond
20683 ((run-hook-with-args-until-success 'org-metaright-hook))
20684 ((org-at-table-p) (call-interactively 'org-table-move-column))
20685 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20686 ((org-at-block-p) (call-interactively 'org-indent-block))
20687 ((org-with-limited-levels
20688 (or (org-at-heading-p)
20689 (and (org-region-active-p)
20690 (save-excursion
20691 (goto-char (region-beginning))
20692 (org-at-heading-p)))))
20693 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20694 (call-interactively 'org-do-demote))
20695 ;; At an inline task.
20696 ((org-at-heading-p)
20697 (call-interactively 'org-inlinetask-demote))
20698 ((or (org-at-item-p)
20699 (and (org-region-active-p)
20700 (save-excursion
20701 (goto-char (region-beginning))
20702 (org-at-item-p))))
20703 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20704 (call-interactively 'org-indent-item))
20705 (t (call-interactively 'forward-word))))
20707 (defun org-check-for-hidden (what)
20708 "Check if there are hidden headlines/items in the current visual line.
20709 WHAT can be either `headlines' or `items'. If the current line is
20710 an outline or item heading and it has a folded subtree below it,
20711 this function returns t, nil otherwise."
20712 (let ((re (cond
20713 ((eq what 'headlines) org-outline-regexp-bol)
20714 ((eq what 'items) (org-item-beginning-re))
20715 (t (error "This should not happen"))))
20716 beg end)
20717 (save-excursion
20718 (catch 'exit
20719 (unless (org-region-active-p)
20720 (setq beg (point-at-bol))
20721 (beginning-of-line 2)
20722 (while (and (not (eobp)) ;; this is like `next-line'
20723 (get-char-property (1- (point)) 'invisible))
20724 (beginning-of-line 2))
20725 (setq end (point))
20726 (goto-char beg)
20727 (goto-char (point-at-eol))
20728 (setq end (max end (point)))
20729 (while (re-search-forward re end t)
20730 (when (get-char-property (match-beginning 0) 'invisible)
20731 (throw 'exit t))))
20732 nil))))
20734 (defun org-metaup (&optional _arg)
20735 "Move subtree up or move table row up.
20736 Calls `org-move-subtree-up' or `org-table-move-row' or
20737 `org-move-item-up', depending on context. See the individual commands
20738 for more information."
20739 (interactive "P")
20740 (cond
20741 ((run-hook-with-args-until-success 'org-metaup-hook))
20742 ((org-region-active-p)
20743 (let* ((a (min (region-beginning) (region-end)))
20744 (b (1- (max (region-beginning) (region-end))))
20745 (c (save-excursion (goto-char a)
20746 (move-beginning-of-line 0)))
20747 (d (save-excursion (goto-char a)
20748 (move-end-of-line 0) (point))))
20749 (transpose-regions a b c d)
20750 (goto-char c)))
20751 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20752 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20753 ((org-at-item-p) (call-interactively 'org-move-item-up))
20754 (t (org-drag-element-backward))))
20756 (defun org-metadown (&optional _arg)
20757 "Move subtree down or move table row down.
20758 Calls `org-move-subtree-down' or `org-table-move-row' or
20759 `org-move-item-down', depending on context. See the individual
20760 commands for more information."
20761 (interactive "P")
20762 (cond
20763 ((run-hook-with-args-until-success 'org-metadown-hook))
20764 ((org-region-active-p)
20765 (let* ((a (min (region-beginning) (region-end)))
20766 (b (max (region-beginning) (region-end)))
20767 (c (save-excursion (goto-char b)
20768 (move-beginning-of-line 1)))
20769 (d (save-excursion (goto-char b)
20770 (move-end-of-line 1) (1+ (point)))))
20771 (transpose-regions a b c d)
20772 (goto-char d)))
20773 ((org-at-table-p) (call-interactively 'org-table-move-row))
20774 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20775 ((org-at-item-p) (call-interactively 'org-move-item-down))
20776 (t (org-drag-element-forward))))
20778 (defun org-shiftup (&optional arg)
20779 "Increase item in timestamp or increase priority of current headline.
20780 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20781 depending on context. See the individual commands for more information."
20782 (interactive "P")
20783 (cond
20784 ((run-hook-with-args-until-success 'org-shiftup-hook))
20785 ((and org-support-shift-select (org-region-active-p))
20786 (org-call-for-shift-select 'previous-line))
20787 ((org-at-timestamp-p t)
20788 (call-interactively (if org-edit-timestamp-down-means-later
20789 'org-timestamp-down 'org-timestamp-up)))
20790 ((and (not (eq org-support-shift-select 'always))
20791 org-enable-priority-commands
20792 (org-at-heading-p))
20793 (call-interactively 'org-priority-up))
20794 ((and (not org-support-shift-select) (org-at-item-p))
20795 (call-interactively 'org-previous-item))
20796 ((org-clocktable-try-shift 'up arg))
20797 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20798 (org-support-shift-select
20799 (org-call-for-shift-select 'previous-line))
20800 (t (org-shiftselect-error))))
20802 (defun org-shiftdown (&optional arg)
20803 "Decrease item in timestamp or decrease priority of current headline.
20804 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20805 depending on context. See the individual commands for more information."
20806 (interactive "P")
20807 (cond
20808 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20809 ((and org-support-shift-select (org-region-active-p))
20810 (org-call-for-shift-select 'next-line))
20811 ((org-at-timestamp-p t)
20812 (call-interactively (if org-edit-timestamp-down-means-later
20813 'org-timestamp-up 'org-timestamp-down)))
20814 ((and (not (eq org-support-shift-select 'always))
20815 org-enable-priority-commands
20816 (org-at-heading-p))
20817 (call-interactively 'org-priority-down))
20818 ((and (not org-support-shift-select) (org-at-item-p))
20819 (call-interactively 'org-next-item))
20820 ((org-clocktable-try-shift 'down arg))
20821 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20822 (org-support-shift-select
20823 (org-call-for-shift-select 'next-line))
20824 (t (org-shiftselect-error))))
20826 (defun org-shiftright (&optional arg)
20827 "Cycle the thing at point or in the current line, depending on context.
20828 Depending on context, this does one of the following:
20830 - switch a timestamp at point one day into the future
20831 - on a headline, switch to the next TODO keyword.
20832 - on an item, switch entire list to the next bullet type
20833 - on a property line, switch to the next allowed value
20834 - on a clocktable definition line, move time block into the future"
20835 (interactive "P")
20836 (cond
20837 ((run-hook-with-args-until-success 'org-shiftright-hook))
20838 ((and org-support-shift-select (org-region-active-p))
20839 (org-call-for-shift-select 'forward-char))
20840 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20841 ((and (not (eq org-support-shift-select 'always))
20842 (org-at-heading-p))
20843 (let ((org-inhibit-logging
20844 (not org-treat-S-cursor-todo-selection-as-state-change))
20845 (org-inhibit-blocking
20846 (not org-treat-S-cursor-todo-selection-as-state-change)))
20847 (org-call-with-arg 'org-todo 'right)))
20848 ((or (and org-support-shift-select
20849 (not (eq org-support-shift-select 'always))
20850 (org-at-item-bullet-p))
20851 (and (not org-support-shift-select) (org-at-item-p)))
20852 (org-call-with-arg 'org-cycle-list-bullet nil))
20853 ((and (not (eq org-support-shift-select 'always))
20854 (org-at-property-p))
20855 (call-interactively 'org-property-next-allowed-value))
20856 ((org-clocktable-try-shift 'right arg))
20857 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20858 (org-support-shift-select
20859 (org-call-for-shift-select 'forward-char))
20860 (t (org-shiftselect-error))))
20862 (defun org-shiftleft (&optional arg)
20863 "Cycle the thing at point or in the current line, depending on context.
20864 Depending on context, this does one of the following:
20866 - switch a timestamp at point one day into the past
20867 - on a headline, switch to the previous TODO keyword.
20868 - on an item, switch entire list to the previous bullet type
20869 - on a property line, switch to the previous allowed value
20870 - on a clocktable definition line, move time block into the past"
20871 (interactive "P")
20872 (cond
20873 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20874 ((and org-support-shift-select (org-region-active-p))
20875 (org-call-for-shift-select 'backward-char))
20876 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20877 ((and (not (eq org-support-shift-select 'always))
20878 (org-at-heading-p))
20879 (let ((org-inhibit-logging
20880 (not org-treat-S-cursor-todo-selection-as-state-change))
20881 (org-inhibit-blocking
20882 (not org-treat-S-cursor-todo-selection-as-state-change)))
20883 (org-call-with-arg 'org-todo 'left)))
20884 ((or (and org-support-shift-select
20885 (not (eq org-support-shift-select 'always))
20886 (org-at-item-bullet-p))
20887 (and (not org-support-shift-select) (org-at-item-p)))
20888 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20889 ((and (not (eq org-support-shift-select 'always))
20890 (org-at-property-p))
20891 (call-interactively 'org-property-previous-allowed-value))
20892 ((org-clocktable-try-shift 'left arg))
20893 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20894 (org-support-shift-select
20895 (org-call-for-shift-select 'backward-char))
20896 (t (org-shiftselect-error))))
20898 (defun org-shiftcontrolright ()
20899 "Switch to next TODO set."
20900 (interactive)
20901 (cond
20902 ((and org-support-shift-select (org-region-active-p))
20903 (org-call-for-shift-select 'forward-word))
20904 ((and (not (eq org-support-shift-select 'always))
20905 (org-at-heading-p))
20906 (org-call-with-arg 'org-todo 'nextset))
20907 (org-support-shift-select
20908 (org-call-for-shift-select 'forward-word))
20909 (t (org-shiftselect-error))))
20911 (defun org-shiftcontrolleft ()
20912 "Switch to previous TODO set."
20913 (interactive)
20914 (cond
20915 ((and org-support-shift-select (org-region-active-p))
20916 (org-call-for-shift-select 'backward-word))
20917 ((and (not (eq org-support-shift-select 'always))
20918 (org-at-heading-p))
20919 (org-call-with-arg 'org-todo 'previousset))
20920 (org-support-shift-select
20921 (org-call-for-shift-select 'backward-word))
20922 (t (org-shiftselect-error))))
20924 (defun org-shiftcontrolup (&optional n)
20925 "Change timestamps synchronously up in CLOCK log lines.
20926 Optional argument N tells to change by that many units."
20927 (interactive "P")
20928 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20929 (let (org-support-shift-select)
20930 (org-clock-timestamps-up n))
20931 (user-error "Not at a clock log")))
20933 (defun org-shiftcontroldown (&optional n)
20934 "Change timestamps synchronously down in CLOCK log lines.
20935 Optional argument N tells to change by that many units."
20936 (interactive "P")
20937 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20938 (let (org-support-shift-select)
20939 (org-clock-timestamps-down n))
20940 (user-error "Not at a clock log")))
20942 (defun org-increase-number-at-point (&optional inc)
20943 "Increment the number at point.
20944 With an optional prefix numeric argument INC, increment using
20945 this numeric value."
20946 (interactive "p")
20947 (if (not (number-at-point))
20948 (user-error "Not on a number")
20949 (unless inc (setq inc 1))
20950 (let ((pos (point))
20951 (beg (skip-chars-backward "-+^/*0-9eE."))
20952 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20953 (setq nap (buffer-substring-no-properties
20954 (+ pos beg) (+ pos beg end)))
20955 (delete-region (+ pos beg) (+ pos beg end))
20956 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20957 (when (org-at-table-p)
20958 (org-table-align)
20959 (org-table-end-of-field 1))))
20961 (defun org-decrease-number-at-point (&optional inc)
20962 "Decrement the number at point.
20963 With an optional prefix numeric argument INC, decrement using
20964 this numeric value."
20965 (interactive "p")
20966 (org-increase-number-at-point (- (or inc 1))))
20968 (defun org-ctrl-c-ret ()
20969 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20970 (interactive)
20971 (cond
20972 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20973 (t (call-interactively 'org-insert-heading))))
20975 (defun org-find-visible ()
20976 (let ((s (point)))
20977 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20978 (get-char-property s 'invisible)))
20980 (defun org-find-invisible ()
20981 (let ((s (point)))
20982 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20983 (not (get-char-property s 'invisible))))
20986 (defun org-copy-visible (beg end)
20987 "Copy the visible parts of the region."
20988 (interactive "r")
20989 (let (snippets s)
20990 (save-excursion
20991 (save-restriction
20992 (narrow-to-region beg end)
20993 (setq s (goto-char (point-min)))
20994 (while (not (= (point) (point-max)))
20995 (goto-char (org-find-invisible))
20996 (push (buffer-substring s (point)) snippets)
20997 (setq s (goto-char (org-find-visible))))))
20998 (kill-new (apply 'concat (nreverse snippets)))))
21000 (defun org-copy-special ()
21001 "Copy region in table or copy current subtree.
21002 Calls `org-table-copy' or `org-copy-subtree', depending on context.
21003 See the individual commands for more information."
21004 (interactive)
21005 (call-interactively
21006 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
21008 (defun org-cut-special ()
21009 "Cut region in table or cut current subtree.
21010 Calls `org-table-copy' or `org-cut-subtree', depending on context.
21011 See the individual commands for more information."
21012 (interactive)
21013 (call-interactively
21014 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
21016 (defun org-paste-special (arg)
21017 "Paste rectangular region into table, or past subtree relative to level.
21018 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
21019 See the individual commands for more information."
21020 (interactive "P")
21021 (if (org-at-table-p)
21022 (org-table-paste-rectangle)
21023 (org-paste-subtree arg)))
21025 (defsubst org-in-fixed-width-region-p ()
21026 "Is point in a fixed-width region?"
21027 (save-match-data
21028 (eq 'fixed-width (org-element-type (org-element-at-point)))))
21030 (defun org-edit-special (&optional arg)
21031 "Call a special editor for the element at point.
21032 When at a table, call the formula editor with `org-table-edit-formulas'.
21033 When in a source code block, call `org-edit-src-code'.
21034 When in a fixed-width region, call `org-edit-fixed-width-region'.
21035 When in an export block, call `org-edit-export-block'.
21036 When at an #+INCLUDE keyword, visit the included file.
21037 When at a footnote reference, call `org-edit-footnote-reference'
21038 On a link, call `ffap' to visit the link at point.
21039 Otherwise, return a user error."
21040 (interactive "P")
21041 (let ((element (org-element-at-point)))
21042 (cl-assert (not buffer-read-only) nil
21043 "Buffer is read-only: %s" (buffer-name))
21044 (pcase (org-element-type element)
21045 (`src-block
21046 (if (not arg) (org-edit-src-code)
21047 (let* ((info (org-babel-get-src-block-info))
21048 (lang (nth 0 info))
21049 (params (nth 2 info))
21050 (session (cdr (assq :session params))))
21051 (if (not session) (org-edit-src-code)
21052 ;; At a src-block with a session and function called with
21053 ;; an ARG: switch to the buffer related to the inferior
21054 ;; process.
21055 (switch-to-buffer
21056 (funcall (intern (concat "org-babel-prep-session:" lang))
21057 session params))))))
21058 (`keyword
21059 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21060 (org-open-link-from-string
21061 (format "[[%s]]"
21062 (expand-file-name
21063 (let ((value (org-element-property :value element)))
21064 (cond ((not (org-string-nw-p value))
21065 (user-error "No file to edit"))
21066 ((string-match "\\`\"\\(.*?\\)\"" value)
21067 (match-string 1 value))
21068 ((string-match "\\`[^ \t\"]\\S-*" value)
21069 (match-string 0 value))
21070 (t (user-error "No valid file specified")))))))
21071 (user-error "No special environment to edit here")))
21072 (`table
21073 (if (eq (org-element-property :type element) 'table.el)
21074 (org-edit-table.el)
21075 (call-interactively 'org-table-edit-formulas)))
21076 ;; Only Org tables contain `table-row' type elements.
21077 (`table-row (call-interactively 'org-table-edit-formulas))
21078 (`example-block (org-edit-src-code))
21079 (`export-block (org-edit-export-block))
21080 (`fixed-width (org-edit-fixed-width-region))
21082 ;; No notable element at point. Though, we may be at a link or
21083 ;; a footnote reference, which are objects. Thus, scan deeper.
21084 (let ((context (org-element-context element)))
21085 (pcase (org-element-type context)
21086 (`footnote-reference (org-edit-footnote-reference))
21087 (`inline-src-block (org-edit-inline-src-code))
21088 (`link (call-interactively #'ffap))
21089 (_ (user-error "No special environment to edit here"))))))))
21091 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21092 (defun org-ctrl-c-ctrl-c (&optional arg)
21093 "Set tags in headline, or update according to changed information at point.
21095 This command does many different things, depending on context:
21097 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21098 this is what we do.
21100 - If the cursor is on a statistics cookie, update it.
21102 - If the cursor is in a headline, prompt for tags and insert them
21103 into the current line, aligned to `org-tags-column'. When called
21104 with prefix arg, realign all tags in the current buffer.
21106 - If the cursor is in one of the special #+KEYWORD lines, this
21107 triggers scanning the buffer for these lines and updating the
21108 information.
21110 - If the cursor is inside a table, realign the table. This command
21111 works even if the automatic table editor has been turned off.
21113 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21114 the entire table.
21116 - If the cursor is at a footnote reference or definition, jump to
21117 the corresponding definition or references, respectively.
21119 - If the cursor is a the beginning of a dynamic block, update it.
21121 - If the current buffer is a capture buffer, close note and file it.
21123 - If the cursor is on a <<<target>>>, update radio targets and
21124 corresponding links in this buffer.
21126 - If the cursor is on a numbered item in a plain list, renumber the
21127 ordered list.
21129 - If the cursor is on a checkbox, toggle it.
21131 - If the cursor is on a code block, evaluate it. The variable
21132 `org-confirm-babel-evaluate' can be used to control prompting
21133 before code block evaluation, by default every code block
21134 evaluation requires confirmation. Code block evaluation can be
21135 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21136 (interactive "P")
21137 (cond
21138 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21139 org-occur-highlights)
21140 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21141 (org-remove-occur-highlights)
21142 (message "Temporary highlights/overlays removed from current buffer"))
21143 ((and (local-variable-p 'org-finish-function (current-buffer))
21144 (fboundp org-finish-function))
21145 (funcall org-finish-function))
21146 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21148 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21149 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21150 (user-error "C-c C-c can do nothing useful at this location"))
21151 (let* ((context (org-element-context))
21152 (type (org-element-type context)))
21153 (cl-case type
21154 ;; When at a link, act according to the parent instead.
21155 (link (setq context (org-element-property :parent context))
21156 (setq type (org-element-type context)))
21157 ;; Unsupported object types: refer to the first supported
21158 ;; element or object containing it.
21159 ((bold code entity export-snippet inline-babel-call inline-src-block
21160 italic latex-fragment line-break macro strike-through subscript
21161 superscript underline verbatim)
21162 (setq context
21163 (org-element-lineage
21164 context '(radio-target paragraph verse-block table-cell)))))
21165 ;; For convenience: at the first line of a paragraph on the
21166 ;; same line as an item, apply function on that item instead.
21167 (when (eq type 'paragraph)
21168 (let ((parent (org-element-property :parent context)))
21169 (when (and (eq (org-element-type parent) 'item)
21170 (= (line-beginning-position)
21171 (org-element-property :begin parent)))
21172 (setq context parent type 'item))))
21173 ;; Act according to type of element or object at point.
21174 (cl-case type
21175 (clock (org-clock-update-time-maybe))
21176 (dynamic-block
21177 (save-excursion
21178 (goto-char (org-element-property :post-affiliated context))
21179 (org-update-dblock)))
21180 (footnote-definition
21181 (goto-char (org-element-property :post-affiliated context))
21182 (call-interactively 'org-footnote-action))
21183 (footnote-reference (call-interactively 'org-footnote-action))
21184 ((headline inlinetask)
21185 (save-excursion (goto-char (org-element-property :begin context))
21186 (call-interactively 'org-set-tags)))
21187 (item
21188 ;; At an item: a double C-u set checkbox to "[-]"
21189 ;; unconditionally, whereas a single one will toggle its
21190 ;; presence. Without a universal argument, if the item
21191 ;; has a checkbox, toggle it. Otherwise repair the list.
21192 (let* ((box (org-element-property :checkbox context))
21193 (struct (org-element-property :structure context))
21194 (old-struct (copy-tree struct))
21195 (parents (org-list-parents-alist struct))
21196 (prevs (org-list-prevs-alist struct))
21197 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21198 (org-list-set-checkbox
21199 (org-element-property :begin context) struct
21200 (cond ((equal arg '(16)) "[-]")
21201 ((and (not box) (equal arg '(4))) "[ ]")
21202 ((or (not box) (equal arg '(4))) nil)
21203 ((eq box 'on) "[ ]")
21204 (t "[X]")))
21205 ;; Mimic `org-list-write-struct' but with grabbing
21206 ;; a return value from `org-list-struct-fix-box'.
21207 (org-list-struct-fix-ind struct parents 2)
21208 (org-list-struct-fix-item-end struct)
21209 (org-list-struct-fix-bul struct prevs)
21210 (org-list-struct-fix-ind struct parents)
21211 (let ((block-item
21212 (org-list-struct-fix-box struct parents prevs orderedp)))
21213 (if (and box (equal struct old-struct))
21214 (if (equal arg '(16))
21215 (message "Checkboxes already reset")
21216 (user-error "Cannot toggle this checkbox: %s"
21217 (if (eq box 'on)
21218 "all subitems checked"
21219 "unchecked subitems")))
21220 (org-list-struct-apply-struct struct old-struct)
21221 (org-update-checkbox-count-maybe))
21222 (when block-item
21223 (message "Checkboxes were removed due to empty box at line %d"
21224 (org-current-line block-item))))))
21225 (keyword
21226 (let ((org-inhibit-startup-visibility-stuff t)
21227 (org-startup-align-all-tables nil))
21228 (when (boundp 'org-table-coordinate-overlays)
21229 (mapc #'delete-overlay org-table-coordinate-overlays)
21230 (setq org-table-coordinate-overlays nil))
21231 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21232 (message "Local setup has been refreshed"))
21233 (plain-list
21234 ;; At a plain list, with a double C-u argument, set
21235 ;; checkboxes of each item to "[-]", whereas a single one
21236 ;; will toggle their presence according to the state of the
21237 ;; first item in the list. Without an argument, repair the
21238 ;; list.
21239 (let* ((begin (org-element-property :contents-begin context))
21240 (beginm (move-marker (make-marker) begin))
21241 (struct (org-element-property :structure context))
21242 (old-struct (copy-tree struct))
21243 (first-box (save-excursion
21244 (goto-char begin)
21245 (looking-at org-list-full-item-re)
21246 (match-string-no-properties 3)))
21247 (new-box (cond ((equal arg '(16)) "[-]")
21248 ((equal arg '(4)) (unless first-box "[ ]"))
21249 ((equal first-box "[X]") "[ ]")
21250 (t "[X]"))))
21251 (cond
21252 (arg
21253 (dolist (pos
21254 (org-list-get-all-items
21255 begin struct (org-list-prevs-alist struct)))
21256 (org-list-set-checkbox pos struct new-box)))
21257 ((and first-box (eq (point) begin))
21258 ;; For convenience, when point is at bol on the first
21259 ;; item of the list and no argument is provided, simply
21260 ;; toggle checkbox of that item, if any.
21261 (org-list-set-checkbox begin struct new-box)))
21262 (org-list-write-struct
21263 struct (org-list-parents-alist struct) old-struct)
21264 (org-update-checkbox-count-maybe)
21265 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21266 ((property-drawer node-property)
21267 (call-interactively 'org-property-action))
21268 ((radio-target target)
21269 (call-interactively 'org-update-radio-target-regexp))
21270 (statistics-cookie
21271 (call-interactively 'org-update-statistics-cookies))
21272 ((table table-cell table-row)
21273 ;; At a table, recalculate every field and align it. Also
21274 ;; send the table if necessary. If the table has
21275 ;; a `table.el' type, just give up. At a table row or
21276 ;; cell, maybe recalculate line but always align table.
21277 (if (eq (org-element-property :type context) 'table.el)
21278 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21279 Use \\[org-edit-special] to edit table.el tables"))
21280 (let ((org-enable-table-editor t))
21281 (if (or (eq type 'table)
21282 ;; Check if point is at a TBLFM line.
21283 (and (eq type 'table-row)
21284 (= (point) (org-element-property :end context))))
21285 (save-excursion
21286 (if (org-at-TBLFM-p)
21287 (progn (require 'org-table)
21288 (org-table-calc-current-TBLFM))
21289 (goto-char (org-element-property :contents-begin context))
21290 (org-call-with-arg 'org-table-recalculate (or arg t))
21291 (orgtbl-send-table 'maybe)))
21292 (org-table-maybe-eval-formula)
21293 (cond (arg (call-interactively 'org-table-recalculate))
21294 ((org-table-maybe-recalculate-line))
21295 (t (org-table-align)))))))
21296 (timestamp (org-timestamp-change 0 'day))
21297 (otherwise
21298 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21299 (user-error
21300 "C-c C-c can do nothing useful at this location")))))))))
21302 (defun org-mode-restart ()
21303 (interactive)
21304 (let ((indent-status (bound-and-true-p org-indent-mode)))
21305 (funcall major-mode)
21306 (hack-local-variables)
21307 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21308 (org-indent-mode -1)))
21309 (message "%s restarted" major-mode))
21311 (defun org-kill-note-or-show-branches ()
21312 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21313 (interactive)
21314 (if (not org-finish-function)
21315 (progn
21316 (outline-hide-subtree)
21317 (call-interactively 'outline-show-branches))
21318 (let ((org-note-abort t))
21319 (funcall org-finish-function))))
21321 (defun org-delete-indentation (&optional ARG)
21322 "Join current line to previous and fix whitespace at join.
21324 If previous line is a headline add to headline title. Otherwise
21325 the function calls `delete-indentation'.
21327 With argument, join this line to following line."
21328 (interactive "*P")
21329 (if (save-excursion
21330 (if ARG (beginning-of-line)
21331 (forward-line -1))
21332 (looking-at org-complex-heading-regexp))
21333 ;; At headline.
21334 (let ((tags-column (when (match-beginning 5)
21335 (save-excursion (goto-char (match-beginning 5))
21336 (current-column))))
21337 (string (concat " " (progn (when ARG (forward-line 1))
21338 (org-trim (delete-and-extract-region
21339 (line-beginning-position)
21340 (line-end-position)))))))
21341 (unless (bobp) (delete-region (point) (1- (point))))
21342 (goto-char (or (match-end 4)
21343 (match-beginning 5)
21344 (match-end 0)))
21345 (skip-chars-backward " \t")
21346 (save-excursion (insert string))
21347 ;; Adjust alignment of tags.
21348 (when tags-column
21349 (org-align-tags-here (if org-auto-align-tags
21350 org-tags-column
21351 tags-column))))
21352 (delete-indentation ARG)))
21354 (defun org-open-line (n)
21355 "Insert a new row in tables, call `open-line' elsewhere.
21356 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21357 (interactive "*p")
21358 (cond
21359 ((not org-special-ctrl-o)
21360 (open-line n))
21361 ((org-at-table-p)
21362 (org-table-insert-row))
21364 (open-line n))))
21366 (defun org-return (&optional indent)
21367 "Goto next table row or insert a newline.
21369 Calls `org-table-next-row' or `newline', depending on context.
21371 When optional INDENT argument is non-nil, call
21372 `newline-and-indent' instead of `newline'.
21374 When `org-return-follows-link' is non-nil and point is on
21375 a timestamp or a link, call `org-open-at-point'. However, it
21376 will not happen if point is in a table or on a \"dead\"
21377 object (e.g., within a comment). In these case, you need to use
21378 `org-open-at-point' directly."
21379 (interactive)
21380 (let ((context (if org-return-follows-link (org-element-context)
21381 (org-element-at-point))))
21382 (cond
21383 ;; In a table, call `org-table-next-row'.
21384 ((or (and (eq (org-element-type context) 'table)
21385 (>= (point) (org-element-property :contents-begin context))
21386 (< (point) (org-element-property :contents-end context)))
21387 (org-element-lineage context '(table-row table-cell) t))
21388 (org-table-justify-field-maybe)
21389 (call-interactively #'org-table-next-row))
21390 ;; On a link or a timestamp, call `org-open-at-point' if
21391 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21392 ;; locations, e.g., in a comment, as `org-open-at-point'.
21393 ((and org-return-follows-link
21394 (or (org-in-regexp org-ts-regexp-both nil t)
21395 (org-in-regexp org-tsr-regexp-both nil t)
21396 (org-in-regexp org-any-link-re nil t)))
21397 (call-interactively #'org-open-at-point))
21398 ;; Insert newline in heading, but preserve tags.
21399 ((and (not (bolp))
21400 (save-excursion (beginning-of-line)
21401 (looking-at org-complex-heading-regexp)))
21402 ;; At headline. Split line. However, if point is on keyword,
21403 ;; priority cookie or tags, do not break any of them: add
21404 ;; a newline after the headline instead.
21405 (let ((tags-column (and (match-beginning 5)
21406 (save-excursion (goto-char (match-beginning 5))
21407 (current-column))))
21408 (string
21409 (when (and (match-end 4)
21410 (>= (point)
21411 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21412 (<= (point) (match-end 4)))
21413 (delete-and-extract-region (point) (match-end 4)))))
21414 (when (and tags-column string) ; Adjust tag alignment.
21415 (org-align-tags-here
21416 (if org-auto-align-tags org-tags-column tags-column)))
21417 (end-of-line)
21418 (org-show-entry)
21419 (if indent (newline-and-indent) (newline))
21420 (when string (save-excursion (insert (org-trim string))))))
21421 ;; In a list, make sure indenting keeps trailing text within.
21422 ((and indent
21423 (not (eolp))
21424 (org-element-lineage context '(item)))
21425 (let ((trailing-data
21426 (delete-and-extract-region (point) (line-end-position))))
21427 (newline-and-indent)
21428 (save-excursion (insert trailing-data))))
21429 (t (if indent (newline-and-indent) (newline))))))
21431 (defun org-return-indent ()
21432 "Goto next table row or insert a newline and indent.
21433 Calls `org-table-next-row' or `newline-and-indent', depending on
21434 context. See the individual commands for more information."
21435 (interactive)
21436 (org-return t))
21438 (defun org-ctrl-c-star ()
21439 "Compute table, or change heading status of lines.
21440 Calls `org-table-recalculate' or `org-toggle-heading',
21441 depending on context."
21442 (interactive)
21443 (cond
21444 ((org-at-table-p)
21445 (call-interactively 'org-table-recalculate))
21447 ;; Convert all lines in region to list items
21448 (call-interactively 'org-toggle-heading))))
21450 (defun org-ctrl-c-minus ()
21451 "Insert separator line in table or modify bullet status of line.
21452 Also turns a plain line or a region of lines into list items.
21453 Calls `org-table-insert-hline', `org-toggle-item', or
21454 `org-cycle-list-bullet', depending on context."
21455 (interactive)
21456 (cond
21457 ((org-at-table-p)
21458 (call-interactively 'org-table-insert-hline))
21459 ((org-region-active-p)
21460 (call-interactively 'org-toggle-item))
21461 ((org-in-item-p)
21462 (call-interactively 'org-cycle-list-bullet))
21464 (call-interactively 'org-toggle-item))))
21466 (defun org-toggle-heading (&optional nstars)
21467 "Convert headings to normal text, or items or text to headings.
21468 If there is no active region, only convert the current line.
21470 With a \\[universal-argument] prefix, convert the whole list at
21471 point into heading.
21473 In a region:
21475 - If the first non blank line is a headline, remove the stars
21476 from all headlines in the region.
21478 - If it is a normal line, turn each and every normal line (i.e.,
21479 not an heading or an item) in the region into headings. If you
21480 want to convert only the first line of this region, use one
21481 universal prefix argument.
21483 - If it is a plain list item, turn all plain list items into headings.
21485 When converting a line into a heading, the number of stars is chosen
21486 such that the lines become children of the current entry. However,
21487 when a numeric prefix argument is given, its value determines the
21488 number of stars to add."
21489 (interactive "P")
21490 (let ((skip-blanks
21491 (function
21492 ;; Return beginning of first non-blank line, starting from
21493 ;; line at POS.
21494 (lambda (pos)
21495 (save-excursion
21496 (goto-char pos)
21497 (while (org-at-comment-p) (forward-line))
21498 (skip-chars-forward " \r\t\n")
21499 (point-at-bol)))))
21500 beg end toggled)
21501 ;; Determine boundaries of changes. If a universal prefix has
21502 ;; been given, put the list in a region. If region ends at a bol,
21503 ;; do not consider the last line to be in the region.
21505 (when (and current-prefix-arg (org-at-item-p))
21506 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21507 (org-mark-element))
21509 (if (org-region-active-p)
21510 (setq beg (funcall skip-blanks (region-beginning))
21511 end (copy-marker (save-excursion
21512 (goto-char (region-end))
21513 (if (bolp) (point) (point-at-eol)))))
21514 (setq beg (funcall skip-blanks (point-at-bol))
21515 end (copy-marker (point-at-eol))))
21516 ;; Ensure inline tasks don't count as headings.
21517 (org-with-limited-levels
21518 (save-excursion
21519 (goto-char beg)
21520 (cond
21521 ;; Case 1. Started at an heading: de-star headings.
21522 ((org-at-heading-p)
21523 (while (< (point) end)
21524 (when (org-at-heading-p t)
21525 (looking-at org-outline-regexp) (replace-match "")
21526 (setq toggled t))
21527 (forward-line)))
21528 ;; Case 2. Started at an item: change items into headlines.
21529 ;; One star will be added by `org-list-to-subtree'.
21530 ((org-at-item-p)
21531 (while (< (point) end)
21532 (when (org-at-item-p)
21533 ;; Pay attention to cases when region ends before list.
21534 (let* ((struct (org-list-struct))
21535 (list-end
21536 (min (org-list-get-bottom-point struct) (1+ end))))
21537 (save-restriction
21538 (narrow-to-region (point) list-end)
21539 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21540 (setq toggled t))
21541 (forward-line)))
21542 ;; Case 3. Started at normal text: make every line an heading,
21543 ;; skipping headlines and items.
21544 (t (let* ((stars
21545 (make-string
21546 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21547 (add-stars
21548 (cond (nstars "") ; stars from prefix only
21549 ((equal stars "") "*") ; before first heading
21550 (org-odd-levels-only "**") ; inside heading, odd
21551 (t "*"))) ; inside heading, oddeven
21552 (rpl (concat stars add-stars " "))
21553 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21554 (while (< (point) (if (equal nstars '(4)) lend end))
21555 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21556 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21557 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21558 (forward-line)))))))
21559 (unless toggled (message "Cannot toggle heading from here"))))
21561 (defun org-meta-return (&optional _arg)
21562 "Insert a new heading or wrap a region in a table.
21563 Calls `org-insert-heading' or `org-table-wrap-region', depending
21564 on context. See the individual commands for more information."
21565 (interactive)
21566 (org-check-before-invisible-edit 'insert)
21567 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21568 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21569 #'org-insert-heading))))
21571 ;;; Menu entries
21573 (defsubst org-in-subtree-not-table-p ()
21574 "Are we in a subtree and not in a table?"
21575 (and (not (org-before-first-heading-p))
21576 (not (org-at-table-p))))
21578 ;; Define the Org mode menus
21579 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21580 '("Tbl"
21581 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21582 ["Next Field" org-cycle (org-at-table-p)]
21583 ["Previous Field" org-shifttab (org-at-table-p)]
21584 ["Next Row" org-return (org-at-table-p)]
21585 "--"
21586 ["Blank Field" org-table-blank-field (org-at-table-p)]
21587 ["Edit Field" org-table-edit-field (org-at-table-p)]
21588 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21589 "--"
21590 ("Column"
21591 ["Move Column Left" org-metaleft (org-at-table-p)]
21592 ["Move Column Right" org-metaright (org-at-table-p)]
21593 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21594 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21595 ("Row"
21596 ["Move Row Up" org-metaup (org-at-table-p)]
21597 ["Move Row Down" org-metadown (org-at-table-p)]
21598 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21599 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21600 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21601 "--"
21602 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21603 ("Rectangle"
21604 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21605 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21606 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21607 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21608 "--"
21609 ("Calculate"
21610 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21611 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21612 ["Edit Formulas" org-edit-special (org-at-table-p)]
21613 "--"
21614 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21615 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21616 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21617 "--"
21618 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21619 "--"
21620 ["Sum Column/Rectangle" org-table-sum
21621 (or (org-at-table-p) (org-region-active-p))]
21622 ["Which Column?" org-table-current-column (org-at-table-p)])
21623 ["Debug Formulas"
21624 org-table-toggle-formula-debugger
21625 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21626 ["Show Col/Row Numbers"
21627 org-table-toggle-coordinate-overlays
21628 :style toggle
21629 :selected (bound-and-true-p org-table-overlay-coordinates)]
21630 "--"
21631 ["Create" org-table-create (and (not (org-at-table-p))
21632 org-enable-table-editor)]
21633 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21634 ["Import from File" org-table-import (not (org-at-table-p))]
21635 ["Export to File" org-table-export (org-at-table-p)]
21636 "--"
21637 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21638 "--"
21639 ("Plot"
21640 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21641 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21643 (easy-menu-define org-org-menu org-mode-map "Org menu"
21644 '("Org"
21645 ("Show/Hide"
21646 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21647 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21648 ["Sparse Tree..." org-sparse-tree t]
21649 ["Reveal Context" org-reveal t]
21650 ["Show All" outline-show-all t]
21651 "--"
21652 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21653 "--"
21654 ["New Heading" org-insert-heading t]
21655 ("Navigate Headings"
21656 ["Up" outline-up-heading t]
21657 ["Next" outline-next-visible-heading t]
21658 ["Previous" outline-previous-visible-heading t]
21659 ["Next Same Level" outline-forward-same-level t]
21660 ["Previous Same Level" outline-backward-same-level t]
21661 "--"
21662 ["Jump" org-goto t])
21663 ("Edit Structure"
21664 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21665 "--"
21666 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21667 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21668 "--"
21669 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21670 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21671 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21672 "--"
21673 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21674 "--"
21675 ["Copy visible text" org-copy-visible t]
21676 "--"
21677 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21678 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21679 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21680 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21681 "--"
21682 ["Sort Region/Children" org-sort t]
21683 "--"
21684 ["Convert to odd levels" org-convert-to-odd-levels t]
21685 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21686 ("Editing"
21687 ["Emphasis..." org-emphasize t]
21688 ["Edit Source Example" org-edit-special t]
21689 "--"
21690 ["Footnote new/jump" org-footnote-action t]
21691 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21692 ("Archive"
21693 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21694 "--"
21695 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21696 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21697 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21699 "--"
21700 ("Hyperlinks"
21701 ["Store Link (Global)" org-store-link t]
21702 ["Find existing link to here" org-occur-link-in-agenda-files t]
21703 ["Insert Link" org-insert-link t]
21704 ["Follow Link" org-open-at-point t]
21705 "--"
21706 ["Next link" org-next-link t]
21707 ["Previous link" org-previous-link t]
21708 "--"
21709 ["Descriptive Links"
21710 org-toggle-link-display
21711 :style radio
21712 :selected org-descriptive-links
21714 ["Literal Links"
21715 org-toggle-link-display
21716 :style radio
21717 :selected (not org-descriptive-links)])
21718 "--"
21719 ("TODO Lists"
21720 ["TODO/DONE/-" org-todo t]
21721 ("Select keyword"
21722 ["Next keyword" org-shiftright (org-at-heading-p)]
21723 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21724 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21725 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21726 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21727 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21728 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21729 "--"
21730 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21731 :selected org-enforce-todo-dependencies :style toggle :active t]
21732 "Settings for tree at point"
21733 ["Do Children sequentially" org-toggle-ordered-property :style radio
21734 :selected (org-entry-get nil "ORDERED")
21735 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21736 ["Do Children parallel" org-toggle-ordered-property :style radio
21737 :selected (not (org-entry-get nil "ORDERED"))
21738 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21739 "--"
21740 ["Set Priority" org-priority t]
21741 ["Priority Up" org-shiftup t]
21742 ["Priority Down" org-shiftdown t]
21743 "--"
21744 ["Get news from all feeds" org-feed-update-all t]
21745 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21746 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21747 ("TAGS and Properties"
21748 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21749 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21750 "--"
21751 ["Set property" org-set-property (not (org-before-first-heading-p))]
21752 ["Column view of properties" org-columns t]
21753 ["Insert Column View DBlock" org-columns-insert-dblock t])
21754 ("Dates and Scheduling"
21755 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21756 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21757 ("Change Date"
21758 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21759 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21760 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21761 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21762 ["Compute Time Range" org-evaluate-time-range t]
21763 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21764 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21765 "--"
21766 ["Custom time format" org-toggle-time-stamp-overlays
21767 :style radio :selected org-display-custom-times]
21768 "--"
21769 ["Goto Calendar" org-goto-calendar t]
21770 ["Date from Calendar" org-date-from-calendar t]
21771 "--"
21772 ["Start/Restart Timer" org-timer-start t]
21773 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21774 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21775 ["Insert Timer String" org-timer t]
21776 ["Insert Timer Item" org-timer-item t])
21777 ("Logging work"
21778 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21779 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21780 ["Clock out" org-clock-out t]
21781 ["Clock cancel" org-clock-cancel t]
21782 "--"
21783 ["Mark as default task" org-clock-mark-default-task t]
21784 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21785 ["Goto running clock" org-clock-goto t]
21786 "--"
21787 ["Display times" org-clock-display t]
21788 ["Create clock table" org-clock-report t]
21789 "--"
21790 ["Record DONE time"
21791 (progn (setq org-log-done (not org-log-done))
21792 (message "Switching to %s will %s record a timestamp"
21793 (car org-done-keywords)
21794 (if org-log-done "automatically" "not")))
21795 :style toggle :selected org-log-done])
21796 "--"
21797 ["Agenda Command..." org-agenda t]
21798 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21799 ("File List for Agenda")
21800 ("Special views current file"
21801 ["TODO Tree" org-show-todo-tree t]
21802 ["Check Deadlines" org-check-deadlines t]
21803 ["Timeline" org-timeline t]
21804 ["Tags/Property tree" org-match-sparse-tree t])
21805 "--"
21806 ["Export/Publish..." org-export-dispatch t]
21807 ("LaTeX"
21808 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21809 :selected org-cdlatex-mode]
21810 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21811 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21812 ["Modify math symbol" org-cdlatex-math-modify
21813 (org-inside-LaTeX-fragment-p)]
21814 ["Insert citation" org-reftex-citation t])
21815 "--"
21816 ("MobileOrg"
21817 ["Push Files and Views" org-mobile-push t]
21818 ["Get Captured and Flagged" org-mobile-pull t]
21819 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21820 "--"
21821 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21822 "--"
21823 ("Documentation"
21824 ["Show Version" org-version t]
21825 ["Info Documentation" org-info t])
21826 ("Customize"
21827 ["Browse Org Group" org-customize t]
21828 "--"
21829 ["Expand This Menu" org-create-customize-menu
21830 (fboundp 'customize-menu-create)])
21831 ["Send bug report" org-submit-bug-report t]
21832 "--"
21833 ("Refresh/Reload"
21834 ["Refresh setup current buffer" org-mode-restart t]
21835 ["Reload Org (after update)" org-reload t]
21836 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21839 (defun org-info (&optional node)
21840 "Read documentation for Org in the info system.
21841 With optional NODE, go directly to that node."
21842 (interactive)
21843 (info (format "(org)%s" (or node ""))))
21845 ;;;###autoload
21846 (defun org-submit-bug-report ()
21847 "Submit a bug report on Org via mail.
21849 Don't hesitate to report any problems or inaccurate documentation.
21851 If you don't have setup sending mail from (X)Emacs, please copy the
21852 output buffer into your mail program, as it gives us important
21853 information about your Org version and configuration."
21854 (interactive)
21855 (require 'reporter)
21856 (defvar reporter-prompt-for-summary-p)
21857 (org-load-modules-maybe)
21858 (org-require-autoloaded-modules)
21859 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21860 (reporter-submit-bug-report
21861 "emacs-orgmode@gnu.org"
21862 (org-version nil 'full)
21863 (let (list)
21864 (save-window-excursion
21865 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21866 (delete-other-windows)
21867 (erase-buffer)
21868 (insert "You are about to submit a bug report to the Org mailing list.
21870 We would like to add your full Org and Outline configuration to the
21871 bug report. This greatly simplifies the work of the maintainer and
21872 other experts on the mailing list.
21874 HOWEVER, some variables you have customized may contain private
21875 information. The names of customers, colleagues, or friends, might
21876 appear in the form of file names, tags, todo states, or search strings.
21877 If you answer yes to the prompt, you might want to check and remove
21878 such private information before sending the email.")
21879 (add-text-properties (point-min) (point-max) '(face org-warning))
21880 (when (yes-or-no-p "Include your Org configuration ")
21881 (mapatoms
21882 (lambda (v)
21883 (and (boundp v)
21884 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21885 (or (and (symbol-value v)
21886 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21887 (and
21888 (get v 'custom-type) (get v 'standard-value)
21889 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21890 (push v list)))))
21891 (kill-buffer (get-buffer "*Warn about privacy*"))
21892 list))
21893 nil nil
21894 "Remember to cover the basics, that is, what you expected to happen and
21895 what in fact did happen. You don't know how to make a good report? See
21897 http://orgmode.org/manual/Feedback.html#Feedback
21899 Your bug report will be posted to the Org mailing list.
21900 ------------------------------------------------------------------------")
21901 (save-excursion
21902 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21903 (replace-match "\\1Bug: \\3 [\\2]")))))
21906 (defun org-install-agenda-files-menu ()
21907 (let ((bl (buffer-list)))
21908 (save-excursion
21909 (while bl
21910 (set-buffer (pop bl))
21911 (when (derived-mode-p 'org-mode) (setq bl nil)))
21912 (when (derived-mode-p 'org-mode)
21913 (easy-menu-change
21914 '("Org") "File List for Agenda"
21915 (append
21916 (list
21917 ["Edit File List" (org-edit-agenda-file-list) t]
21918 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21919 ["Remove Current File from List" org-remove-file t]
21920 ["Cycle through agenda files" org-cycle-agenda-files t]
21921 ["Occur in all agenda files" org-occur-in-agenda-files t]
21922 "--")
21923 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21925 ;;;; Documentation
21927 (defun org-require-autoloaded-modules ()
21928 (interactive)
21929 (mapc #'require
21930 '(org-agenda org-archive org-attach org-clock org-colview org-id
21931 org-table org-timer)))
21933 ;;;###autoload
21934 (defun org-reload (&optional uncompiled)
21935 "Reload all org lisp files.
21936 With prefix arg UNCOMPILED, load the uncompiled versions."
21937 (interactive "P")
21938 (require 'loadhist)
21939 (let* ((org-dir (org-find-library-dir "org"))
21940 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21941 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21942 (remove-re (format "\\`%s\\'"
21943 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21944 (feats (delete-dups
21945 (mapcar 'file-name-sans-extension
21946 (mapcar 'file-name-nondirectory
21947 (delq nil
21948 (mapcar 'feature-file
21949 features))))))
21950 (lfeat (append
21951 (sort
21952 (setq feats
21953 (delq nil (mapcar
21954 (lambda (f)
21955 (if (and (string-match feature-re f)
21956 (not (string-match remove-re f)))
21957 f nil))
21958 feats)))
21959 'string-lessp)
21960 (list "org-version" "org")))
21961 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21962 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21963 load-uncore load-misses)
21964 (setq load-misses
21965 (delq 't
21966 (mapcar (lambda (f)
21967 (or (org-load-noerror-mustsuffix (concat org-dir f))
21968 (and (string= org-dir contrib-dir)
21969 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21970 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21971 (add-to-list 'load-uncore f 'append)
21974 lfeat)))
21975 (when load-uncore
21976 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21977 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21978 (if load-misses
21979 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21980 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21981 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21983 ;;;###autoload
21984 (defun org-customize ()
21985 "Call the customize function with org as argument."
21986 (interactive)
21987 (org-load-modules-maybe)
21988 (org-require-autoloaded-modules)
21989 (customize-browse 'org))
21991 (defun org-create-customize-menu ()
21992 "Create a full customization menu for Org-mode, insert it into the menu."
21993 (interactive)
21994 (org-load-modules-maybe)
21995 (org-require-autoloaded-modules)
21996 (if (fboundp 'customize-menu-create)
21997 (progn
21998 (easy-menu-change
21999 '("Org") "Customize"
22000 `(["Browse Org group" org-customize t]
22001 "--"
22002 ,(customize-menu-create 'org)
22003 ["Set" Custom-set t]
22004 ["Save" Custom-save t]
22005 ["Reset to Current" Custom-reset-current t]
22006 ["Reset to Saved" Custom-reset-saved t]
22007 ["Reset to Standard Settings" Custom-reset-standard t]))
22008 (message "\"Org\"-menu now contains full customization menu"))
22009 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22011 ;;;; Miscellaneous stuff
22013 ;;; Generally useful functions
22015 (defun org-get-at-eol (property n)
22016 "Get text property PROPERTY at the end of line less N characters."
22017 (get-text-property (- (point-at-eol) n) property))
22019 (defun org-find-text-property-in-string (prop s)
22020 "Return the first non-nil value of property PROP in string S."
22021 (or (get-text-property 0 prop s)
22022 (get-text-property (or (next-single-property-change 0 prop s) 0)
22023 prop s)))
22025 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22026 "Display the given MESSAGE as a warning."
22027 (if (fboundp 'display-warning)
22028 (display-warning 'org message :warning)
22029 (let ((buf (get-buffer-create "*Org warnings*")))
22030 (with-current-buffer buf
22031 (goto-char (point-max))
22032 (insert "Warning (Org): " message)
22033 (unless (bolp)
22034 (newline)))
22035 (display-buffer buf)
22036 (sit-for 0))))
22038 (defun org-eval (form)
22039 "Eval FORM and return result."
22040 (condition-case error
22041 (eval form)
22042 (error (format "%%![Error: %s]" error))))
22044 (defun org-in-clocktable-p ()
22045 "Check if the cursor is in a clocktable."
22046 (let ((pos (point)) start)
22047 (save-excursion
22048 (end-of-line 1)
22049 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22050 (setq start (match-beginning 0))
22051 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22052 (>= (match-end 0) pos)
22053 start))))
22055 (defun org-in-verbatim-emphasis ()
22056 (save-match-data
22057 (and (org-in-regexp org-emph-re 2)
22058 (>= (point) (match-beginning 3))
22059 (<= (point) (match-end 4))
22060 (member (match-string 3) '("=" "~")))))
22062 (defun org-overlay-display (ovl text &optional face evap)
22063 "Make overlay OVL display TEXT with face FACE."
22064 (overlay-put ovl 'display text)
22065 (if face (overlay-put ovl 'face face))
22066 (if evap (overlay-put ovl 'evaporate t)))
22068 (defun org-overlay-before-string (ovl text &optional face evap)
22069 "Make overlay OVL display TEXT with face FACE."
22070 (if face (org-add-props text nil 'face face))
22071 (overlay-put ovl 'before-string text)
22072 (if evap (overlay-put ovl 'evaporate t)))
22074 (defun org-find-overlays (prop &optional pos delete)
22075 "Find all overlays specifying PROP at POS or point.
22076 If DELETE is non-nil, delete all those overlays."
22077 (let (found)
22078 (dolist (ov (overlays-at (or pos (point))) found)
22079 (cond ((not (overlay-get ov prop)))
22080 (delete (delete-overlay ov))
22081 (t (push ov found))))))
22083 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22084 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22085 (if (and marker (marker-buffer marker)
22086 (buffer-live-p (marker-buffer marker)))
22087 (progn
22088 (pop-to-buffer-same-window (marker-buffer marker))
22089 (when (or (> marker (point-max)) (< marker (point-min)))
22090 (widen))
22091 (goto-char marker)
22092 (org-show-context 'org-goto))
22093 (if bookmark
22094 (bookmark-jump bookmark)
22095 (error "Cannot find location"))))
22097 (defun org-quote-csv-field (s)
22098 "Quote field for inclusion in CSV material."
22099 (if (string-match "[\",]" s)
22100 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22103 (defun org-force-self-insert (N)
22104 "Needed to enforce self-insert under remapping."
22105 (interactive "p")
22106 (self-insert-command N))
22108 (defun org-string-width (s)
22109 "Compute width of string, ignoring invisible characters.
22110 This ignores character with invisibility property `org-link', and also
22111 characters with property `org-cwidth', because these will become invisible
22112 upon the next fontification round."
22113 (let (b l)
22114 (when (or (eq t buffer-invisibility-spec)
22115 (assq 'org-link buffer-invisibility-spec))
22116 (while (setq b (text-property-any 0 (length s)
22117 'invisible 'org-link s))
22118 (setq s (concat (substring s 0 b)
22119 (substring s (or (next-single-property-change
22120 b 'invisible s)
22121 (length s)))))))
22122 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22123 (setq s (concat (substring s 0 b)
22124 (substring s (or (next-single-property-change
22125 b 'org-cwidth s)
22126 (length s))))))
22127 (setq l (string-width s) b -1)
22128 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22129 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22132 (defun org-shorten-string (s maxlength)
22133 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22134 If the string is shorter or has length MAXLENGTH, just return the
22135 original string. If it is longer, the functions finds a space in the
22136 string, breaks this string off at that locations and adds three dots
22137 as ellipsis. Including the ellipsis, the string will not be longer
22138 than MAXLENGTH. If finding a good breaking point in the string does
22139 not work, the string is just chopped off in the middle of a word
22140 if necessary."
22141 (if (<= (length s) maxlength)
22143 (let* ((n (max (- maxlength 4) 1))
22144 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22145 (if (string-match re s)
22146 (concat (match-string 1 s) "...")
22147 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22149 (defun org-get-indentation (&optional line)
22150 "Get the indentation of the current line, interpreting tabs.
22151 When LINE is given, assume it represents a line and compute its indentation."
22152 (if line
22153 (when (string-match "^ *" (org-remove-tabs line))
22154 (match-end 0))
22155 (save-excursion
22156 (beginning-of-line 1)
22157 (skip-chars-forward " \t")
22158 (current-column))))
22160 (defun org-get-string-indentation (s)
22161 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22162 (let ((n -1) (i 0) (w tab-width) c)
22163 (catch 'exit
22164 (while (< (setq n (1+ n)) (length s))
22165 (setq c (aref s n))
22166 (cond ((= c ?\ ) (setq i (1+ i)))
22167 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22168 (t (throw 'exit t)))))
22171 (defun org-remove-tabs (s &optional width)
22172 "Replace tabulators in S with spaces.
22173 Assumes that s is a single line, starting in column 0."
22174 (setq width (or width tab-width))
22175 (while (string-match "\t" s)
22176 (setq s (replace-match
22177 (make-string
22178 (- (* width (/ (+ (match-beginning 0) width) width))
22179 (match-beginning 0)) ?\ )
22180 t t s)))
22183 (defun org-fix-indentation (line ind)
22184 "Fix indentation in LINE.
22185 IND is a cons cell with target and minimum indentation.
22186 If the current indentation in LINE is smaller than the minimum,
22187 leave it alone. If it is larger than ind, set it to the target."
22188 (let* ((l (org-remove-tabs line))
22189 (i (org-get-indentation l))
22190 (i1 (car ind)) (i2 (cdr ind)))
22191 (when (>= i i2) (setq l (substring line i2)))
22192 (if (> i1 0)
22193 (concat (make-string i1 ?\ ) l)
22194 l)))
22196 (defun org-remove-indentation (code &optional n)
22197 "Remove maximum common indentation in string CODE and return it.
22198 N may optionally be the number of columns to remove. Return CODE
22199 as-is if removal failed."
22200 (with-temp-buffer
22201 (insert code)
22202 (if (org-do-remove-indentation n) (buffer-string) code)))
22204 (defun org-do-remove-indentation (&optional n)
22205 "Remove the maximum common indentation from the buffer.
22206 When optional argument N is a positive integer, remove exactly
22207 that much characters from indentation, if possible. Return nil
22208 if it fails."
22209 (catch :exit
22210 (goto-char (point-min))
22211 ;; Find maximum common indentation, if not specified.
22212 (let ((n (or n
22213 (let ((min-ind (point-max)))
22214 (save-excursion
22215 (while (re-search-forward "^[ \t]*\\S-" nil t)
22216 (let ((ind (1- (current-column))))
22217 (if (zerop ind) (throw :exit nil)
22218 (setq min-ind (min min-ind ind))))))
22219 min-ind))))
22220 (if (zerop n) (throw :exit nil)
22221 ;; Remove exactly N indentation, but give up if not possible.
22222 (while (not (eobp))
22223 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22224 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22225 ((< ind n) (throw :exit nil))
22226 (t (indent-line-to (- ind n))))
22227 (forward-line)))
22228 ;; Signal success.
22229 t))))
22231 (defun org-fill-template (template alist)
22232 "Find each %key of ALIST in TEMPLATE and replace it."
22233 (let ((case-fold-search nil))
22234 (dolist (entry (sort (copy-sequence alist)
22235 (lambda (a b) (< (length (car a)) (length (car b))))))
22236 (setq template
22237 (replace-regexp-in-string
22238 (concat "%" (regexp-quote (car entry)))
22239 (or (cdr entry) "") template t t)))
22240 template))
22242 (defun org-base-buffer (buffer)
22243 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22244 (if (not buffer)
22245 buffer
22246 (or (buffer-base-buffer buffer)
22247 buffer)))
22249 (defun org-wrap (string &optional width lines)
22250 "Wrap string to either a number of lines, or a width in characters.
22251 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22252 that costs. If there is a word longer than WIDTH, the text is actually
22253 wrapped to the length of that word.
22254 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22255 many lines, whatever width that takes.
22256 The return value is a list of lines, without newlines at the end."
22257 (let* ((words (org-split-string string "[ \t\n]+"))
22258 (maxword (apply 'max (mapcar 'org-string-width words)))
22259 w ll)
22260 (cond (width
22261 (org-do-wrap words (max maxword width)))
22262 (lines
22263 (setq w maxword)
22264 (setq ll (org-do-wrap words maxword))
22265 (if (<= (length ll) lines)
22267 (setq ll words)
22268 (while (> (length ll) lines)
22269 (setq w (1+ w))
22270 (setq ll (org-do-wrap words w)))
22271 ll))
22272 (t (error "Cannot wrap this")))))
22274 (defun org-do-wrap (words width)
22275 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22276 (let (lines line)
22277 (while words
22278 (setq line (pop words))
22279 (while (and words (< (+ (length line) (length (car words))) width))
22280 (setq line (concat line " " (pop words))))
22281 (setq lines (push line lines)))
22282 (nreverse lines)))
22284 (defun org-split-string (string &optional separators)
22285 "Splits STRING into substrings at SEPARATORS.
22286 SEPARATORS is a regular expression.
22287 No empty strings are returned if there are matches at the beginning
22288 and end of string."
22289 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22290 (let ((start 0) notfirst list)
22291 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22292 (if (and notfirst
22293 (= start (match-beginning 0))
22294 (< start (length string)))
22295 (1+ start) start))
22296 (< (match-beginning 0) (length string)))
22297 (setq notfirst t)
22298 (or (eq (match-beginning 0) 0)
22299 (and (eq (match-beginning 0) (match-end 0))
22300 (eq (match-beginning 0) start))
22301 (push (substring string start (match-beginning 0)) list))
22302 (setq start (match-end 0)))
22303 (or (eq start (length string))
22304 (push (substring string start) list))
22305 (nreverse list)))
22307 (defun org-quote-vert (s)
22308 "Replace \"|\" with \"\\vert\"."
22309 (while (string-match "|" s)
22310 (setq s (replace-match "\\vert" t t s)))
22313 (defun org-uuidgen-p (s)
22314 "Is S an ID created by UUIDGEN?"
22315 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22317 (defun org-in-src-block-p (&optional inside)
22318 "Whether point is in a code source block.
22319 When INSIDE is non-nil, don't consider we are within a src block
22320 when point is at #+BEGIN_SRC or #+END_SRC."
22321 (let ((case-fold-search t))
22322 (or (and (eq (get-char-property (point) 'src-block) t))
22323 (and (not inside)
22324 (save-match-data
22325 (save-excursion
22326 (beginning-of-line)
22327 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22329 (defun org-context ()
22330 "Return a list of contexts of the current cursor position.
22331 If several contexts apply, all are returned.
22332 Each context entry is a list with a symbol naming the context, and
22333 two positions indicating start and end of the context. Possible
22334 contexts are:
22336 :headline anywhere in a headline
22337 :headline-stars on the leading stars in a headline
22338 :todo-keyword on a TODO keyword (including DONE) in a headline
22339 :tags on the TAGS in a headline
22340 :priority on the priority cookie in a headline
22341 :item on the first line of a plain list item
22342 :item-bullet on the bullet/number of a plain list item
22343 :checkbox on the checkbox in a plain list item
22344 :table in an Org table
22345 :table-special on a special filed in a table
22346 :table-table in a table.el table
22347 :clocktable in a clocktable
22348 :src-block in a source block
22349 :link on a hyperlink
22350 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22351 :target on a <<target>>
22352 :radio-target on a <<<radio-target>>>
22353 :latex-fragment on a LaTeX fragment
22354 :latex-preview on a LaTeX fragment with overlaid preview image
22356 This function expects the position to be visible because it uses font-lock
22357 faces as a help to recognize the following contexts: :table-special, :link,
22358 and :keyword."
22359 (let* ((f (get-text-property (point) 'face))
22360 (faces (if (listp f) f (list f)))
22361 (case-fold-search t)
22362 (p (point)) clist o)
22363 ;; First the large context
22364 (cond
22365 ((org-at-heading-p t)
22366 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22367 (when (progn
22368 (beginning-of-line 1)
22369 (looking-at org-todo-line-tags-regexp))
22370 (push (org-point-in-group p 1 :headline-stars) clist)
22371 (push (org-point-in-group p 2 :todo-keyword) clist)
22372 (push (org-point-in-group p 4 :tags) clist))
22373 (goto-char p)
22374 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22375 (when (looking-at "\\[#[A-Z0-9]\\]")
22376 (push (org-point-in-group p 0 :priority) clist)))
22378 ((org-at-item-p)
22379 (push (org-point-in-group p 2 :item-bullet) clist)
22380 (push (list :item (point-at-bol)
22381 (save-excursion (org-end-of-item) (point)))
22382 clist)
22383 (and (org-at-item-checkbox-p)
22384 (push (org-point-in-group p 0 :checkbox) clist)))
22386 ((org-at-table-p)
22387 (push (list :table (org-table-begin) (org-table-end)) clist)
22388 (when (memq 'org-formula faces)
22389 (push (list :table-special
22390 (previous-single-property-change p 'face)
22391 (next-single-property-change p 'face)) clist)))
22392 ((org-at-table-p 'any)
22393 (push (list :table-table) clist)))
22394 (goto-char p)
22396 (let ((case-fold-search t))
22397 ;; New the "medium" contexts: clocktables, source blocks
22398 (cond ((org-in-clocktable-p)
22399 (push (list :clocktable
22400 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22401 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22402 (match-beginning 1))
22403 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22404 (match-end 0))) clist))
22405 ((org-in-src-block-p)
22406 (push (list :src-block
22407 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22408 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22409 (match-beginning 1))
22410 (and (search-forward "#+END_SRC" nil t)
22411 (match-beginning 0))) clist))))
22412 (goto-char p)
22414 ;; Now the small context
22415 (cond
22416 ((org-at-timestamp-p)
22417 (push (org-point-in-group p 0 :timestamp) clist))
22418 ((memq 'org-link faces)
22419 (push (list :link
22420 (previous-single-property-change p 'face)
22421 (next-single-property-change p 'face)) clist))
22422 ((memq 'org-special-keyword faces)
22423 (push (list :keyword
22424 (previous-single-property-change p 'face)
22425 (next-single-property-change p 'face)) clist))
22426 ((org-at-target-p)
22427 (push (org-point-in-group p 0 :target) clist)
22428 (goto-char (1- (match-beginning 0)))
22429 (when (looking-at org-radio-target-regexp)
22430 (push (org-point-in-group p 0 :radio-target) clist))
22431 (goto-char p))
22432 ((setq o (cl-some
22433 (lambda (o)
22434 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22436 (overlays-at (point))))
22437 (push (list :latex-fragment
22438 (overlay-start o) (overlay-end o)) clist)
22439 (push (list :latex-preview
22440 (overlay-start o) (overlay-end o)) clist))
22441 ((org-inside-LaTeX-fragment-p)
22442 ;; FIXME: positions wrong.
22443 (push (list :latex-fragment (point) (point)) clist)))
22445 (setq clist (nreverse (delq nil clist)))
22446 clist))
22448 (defun org-in-regexp (regexp &optional nlines visually)
22449 "Check if point is inside a match of REGEXP.
22451 Normally only the current line is checked, but you can include
22452 NLINES extra lines around point into the search. If VISUALLY is
22453 set, require that the cursor is not after the match but really
22454 on, so that the block visually is on the match.
22456 Return nil or a cons cell (BEG . END) where BEG and END are,
22457 respectively, the positions at the beginning and the end of the
22458 match."
22459 (catch :exit
22460 (let ((pos (point))
22461 (eol (line-end-position (if nlines (1+ nlines) 1))))
22462 (save-excursion
22463 (beginning-of-line (- 1 (or nlines 0)))
22464 (while (and (re-search-forward regexp eol t)
22465 (<= (match-beginning 0) pos))
22466 (let ((end (match-end 0)))
22467 (when (or (> end pos) (and (= end pos) (not visually)))
22468 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22470 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22471 "Non-nil when point is between matches of START-RE and END-RE.
22473 Also return a non-nil value when point is on one of the matches.
22475 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22476 buffer positions. Default values are the positions of headlines
22477 surrounding the point.
22479 The functions returns a cons cell whose car (resp. cdr) is the
22480 position before START-RE (resp. after END-RE)."
22481 (save-match-data
22482 (let ((pos (point))
22483 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22484 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22485 beg end)
22486 (save-excursion
22487 ;; Point is on a block when on START-RE or if START-RE can be
22488 ;; found before it...
22489 (and (or (org-in-regexp start-re)
22490 (re-search-backward start-re limit-up t))
22491 (setq beg (match-beginning 0))
22492 ;; ... and END-RE after it...
22493 (goto-char (match-end 0))
22494 (re-search-forward end-re limit-down t)
22495 (> (setq end (match-end 0)) pos)
22496 ;; ... without another START-RE in-between.
22497 (goto-char (match-beginning 0))
22498 (not (re-search-backward start-re (1+ beg) t))
22499 ;; Return value.
22500 (cons beg end))))))
22502 (defun org-in-block-p (names)
22503 "Non-nil when point belongs to a block whose name belongs to NAMES.
22505 NAMES is a list of strings containing names of blocks.
22507 Return first block name matched, or nil. Beware that in case of
22508 nested blocks, the returned name may not belong to the closest
22509 block from point."
22510 (save-match-data
22511 (catch 'exit
22512 (let ((case-fold-search t)
22513 (lim-up (save-excursion (outline-previous-heading)))
22514 (lim-down (save-excursion (outline-next-heading))))
22515 (dolist (name names)
22516 (let ((n (regexp-quote name)))
22517 (when (org-between-regexps-p
22518 (concat "^[ \t]*#\\+begin_" n)
22519 (concat "^[ \t]*#\\+end_" n)
22520 lim-up lim-down)
22521 (throw 'exit n)))))
22522 nil)))
22524 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22525 "Call `multi-occur' with buffers for all agenda files."
22526 (interactive "sOrg-files matching: ")
22527 (let* ((files (org-agenda-files))
22528 (tnames (mapcar #'file-truename files))
22529 (extra org-agenda-text-search-extra-files))
22530 (when (eq (car extra) 'agenda-archives)
22531 (setq extra (cdr extra))
22532 (setq files (org-add-archive-files files)))
22533 (dolist (f extra)
22534 (unless (member (file-truename f) tnames)
22535 (unless (member f files) (setq files (append files (list f))))
22536 (setq tnames (append tnames (list (file-truename f))))))
22537 (multi-occur
22538 (mapcar (lambda (x)
22539 (with-current-buffer
22540 ;; FIXME: Why not just (find-file-noselect x)?
22541 ;; Is it to avoid the "revert buffer" prompt?
22542 (or (get-file-buffer x) (find-file-noselect x))
22543 (widen)
22544 (current-buffer)))
22545 files)
22546 regexp)))
22548 (add-hook 'occur-mode-find-occurrence-hook
22549 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22551 (defun org-occur-link-in-agenda-files ()
22552 "Create a link and search for it in the agendas.
22553 The link is not stored in `org-stored-links', it is just created
22554 for the search purpose."
22555 (interactive)
22556 (let ((link (condition-case nil
22557 (org-store-link nil)
22558 (error "Unable to create a link to here"))))
22559 (org-occur-in-agenda-files (regexp-quote link))))
22561 (defun org-reverse-string (string)
22562 "Return the reverse of STRING."
22563 (apply 'string (reverse (string-to-list string))))
22565 ;; defsubst org-uniquify must be defined before first use
22567 (defun org-uniquify-alist (alist)
22568 "Merge elements of ALIST with the same key.
22570 For example, in this alist:
22572 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22573 => \\='((a 1 3) (b 2))
22575 merge (a 1) and (a 3) into (a 1 3).
22577 The function returns the new ALIST."
22578 (let (rtn)
22579 (dolist (e alist rtn)
22580 (let (n)
22581 (if (not (assoc (car e) rtn))
22582 (push e rtn)
22583 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22584 (setq rtn (assq-delete-all (car e) rtn))
22585 (push n rtn))))))
22587 (defun org-delete-all (elts list)
22588 "Remove all elements in ELTS from LIST.
22589 Comparison is done with `equal'. It is a destructive operation
22590 that may remove elements by altering the list structure."
22591 (while elts
22592 (setq list (delete (pop elts) list)))
22593 list)
22595 (defun org-back-over-empty-lines ()
22596 "Move backwards over whitespace, to the beginning of the first empty line.
22597 Returns the number of empty lines passed."
22598 (let ((pos (point)))
22599 (if (cdr (assoc 'heading org-blank-before-new-entry))
22600 (skip-chars-backward " \t\n\r")
22601 (unless (eobp)
22602 (forward-line -1)))
22603 (beginning-of-line 2)
22604 (goto-char (min (point) pos))
22605 (count-lines (point) pos)))
22607 (defun org-skip-whitespace ()
22608 (skip-chars-forward " \t\n\r"))
22610 (defun org-point-in-group (point group &optional context)
22611 "Check if POINT is in match-group GROUP.
22612 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22613 match. If the match group does not exist or point is not inside it,
22614 return nil."
22615 (and (match-beginning group)
22616 (>= point (match-beginning group))
22617 (<= point (match-end group))
22618 (if context
22619 (list context (match-beginning group) (match-end group))
22620 t)))
22622 (defun org-switch-to-buffer-other-window (&rest args)
22623 "Switch to buffer in a second window on the current frame.
22624 In particular, do not allow pop-up frames.
22625 Returns the newly created buffer."
22626 (org-no-popups
22627 (apply 'switch-to-buffer-other-window args)))
22629 (defun org-combine-plists (&rest plists)
22630 "Create a single property list from all plists in PLISTS.
22631 The process starts by copying the first list, and then setting properties
22632 from the other lists. Settings in the last list are the most significant
22633 ones and overrule settings in the other lists."
22634 (let ((rtn (copy-sequence (pop plists)))
22635 p v ls)
22636 (while plists
22637 (setq ls (pop plists))
22638 (while ls
22639 (setq p (pop ls) v (pop ls))
22640 (setq rtn (plist-put rtn p v))))
22641 rtn))
22643 (defun org-replace-escapes (string table)
22644 "Replace %-escapes in STRING with values in TABLE.
22645 TABLE is an association list with keys like \"%a\" and string values.
22646 The sequences in STRING may contain normal field width and padding information,
22647 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22648 so values can contain further %-escapes if they are define later in TABLE."
22649 (let ((tbl (copy-alist table))
22650 (case-fold-search nil)
22651 (pchg 0)
22652 re rpl)
22653 (dolist (e tbl)
22654 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22655 (when (and (cdr e) (string-match re (cdr e)))
22656 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22657 (safe "SREF"))
22658 (add-text-properties 0 3 (list 'sref sref) safe)
22659 (setcdr e (replace-match safe t t (cdr e)))))
22660 (while (string-match re string)
22661 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22662 (cdr e)))
22663 (setq string (replace-match rpl t t string))))
22664 (while (setq pchg (next-property-change pchg string))
22665 (let ((sref (get-text-property pchg 'sref string)))
22666 (when (and sref (string-match "SREF" string pchg))
22667 (setq string (replace-match sref t t string)))))
22668 string))
22670 (defun org-sublist (list start end)
22671 "Return a section of LIST, from START to END.
22673 Counting starts at 1."
22674 (cl-subseq list (1- start) end))
22675 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22677 (defun org-find-base-buffer-visiting (file)
22678 "Like `find-buffer-visiting' but always return the base buffer and
22679 not an indirect buffer."
22680 (let ((buf (or (get-file-buffer file)
22681 (find-buffer-visiting file))))
22682 (if buf
22683 (or (buffer-base-buffer buf) buf)
22684 nil)))
22686 ;;; TODO: Only called once, from ox-odt which should probably use
22687 ;;; org-export-inline-image-p or something.
22688 (defun org-file-image-p (file)
22689 "Return non-nil if FILE is an image."
22690 (save-match-data
22691 (string-match (image-file-name-regexp) file)))
22693 (defun org-get-cursor-date (&optional with-time)
22694 "Return the date at cursor in as a time.
22695 This works in the calendar and in the agenda, anywhere else it just
22696 returns the current time.
22697 If WITH-TIME is non-nil, returns the time of the event at point (in
22698 the agenda) or the current time of the day."
22699 (let (date day defd tp hod mod)
22700 (when with-time
22701 (setq tp (get-text-property (point) 'time))
22702 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22703 (setq hod (string-to-number (match-string 1 tp))
22704 mod (string-to-number (match-string 2 tp))))
22705 (or tp (let ((now (decode-time)))
22706 (setq hod (nth 2 now)
22707 mod (nth 1 now)))))
22708 (cond
22709 ((eq major-mode 'calendar-mode)
22710 (setq date (calendar-cursor-to-date)
22711 defd (encode-time 0 (or mod 0) (or hod 0)
22712 (nth 1 date) (nth 0 date) (nth 2 date))))
22713 ((eq major-mode 'org-agenda-mode)
22714 (setq day (get-text-property (point) 'day))
22715 (when day
22716 (setq date (calendar-gregorian-from-absolute day)
22717 defd (encode-time 0 (or mod 0) (or hod 0)
22718 (nth 1 date) (nth 0 date) (nth 2 date))))))
22719 (or defd (current-time))))
22721 (defun org-mark-subtree (&optional up)
22722 "Mark the current subtree.
22723 This puts point at the start of the current subtree, and mark at
22724 the end. If a numeric prefix UP is given, move up into the
22725 hierarchy of headlines by UP levels before marking the subtree."
22726 (interactive "P")
22727 (org-with-limited-levels
22728 (cond ((org-at-heading-p) (beginning-of-line))
22729 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22730 (t (outline-previous-visible-heading 1))))
22731 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22732 (if (called-interactively-p 'any)
22733 (call-interactively 'org-mark-element)
22734 (org-mark-element)))
22736 (defun org-file-newer-than-p (file time)
22737 "Non-nil if FILE is newer than TIME.
22738 FILE is a filename, as a string, TIME is a list of integers, as
22739 returned by, e.g., `current-time'."
22740 (and (file-exists-p file)
22741 ;; Only compare times up to whole seconds as some file-systems
22742 ;; (e.g. HFS+) do not retain any finer granularity. As
22743 ;; a consequence, make sure we return non-nil when the two
22744 ;; times are equal.
22745 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22746 (cl-subseq time 0 2)))))
22748 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22749 "Compile a SOURCE file using PROCESS.
22751 PROCESS is either a function or a list of shell commands, as
22752 strings. EXT is a file extension, without the leading dot, as
22753 a string. It is used to check if the process actually succeeded.
22755 PROCESS must create a file with the same base name and directory
22756 as SOURCE, but ending with EXT. The function then returns its
22757 filename. Otherwise, it raises an error. The error message can
22758 then be refined by providing string ERR-MSG, which is appended to
22759 the standard message.
22761 If PROCESS is a function, it is called with a single argument:
22762 the SOURCE file.
22764 If it is a list of commands, each of them is called using
22765 `shell-command'. By default, in each command, %b, %f, %F and %o
22766 are replaced with, respectively, SOURCE base name, name, full
22767 name and directory. It is possible, however, to use more
22768 place-holders by specifying them in optional argument SPEC, as an
22769 alist following the pattern (CHARACTER . REPLACEMENT-STRING).
22771 When PROCESS is a list of commands, optional argument LOG-BUF can
22772 be set to a buffer or a buffer name. `shell-command' then uses
22773 it for output.
22775 `default-directory' is set to SOURCE directory during the whole
22776 process."
22777 (let* ((source-name (file-name-nondirectory source))
22778 (base-name (file-name-sans-extension source-name))
22779 (full-name (file-truename source))
22780 (out-dir (file-name-directory source))
22781 (time (current-time))
22782 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22783 (save-window-excursion
22784 (let ((default-directory (file-name-directory full-name)))
22785 (pcase process
22786 ((pred functionp) (funcall process (shell-quote-argument source)))
22787 ((pred consp)
22788 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22789 (spec (append spec
22790 `((?b . ,(shell-quote-argument base-name))
22791 (?f . ,(shell-quote-argument source-name))
22792 (?F . ,(shell-quote-argument full-name))
22793 (?o . ,(shell-quote-argument out-dir))))))
22794 (dolist (command process)
22795 (shell-command (format-spec command spec) log-buf))))
22796 (_ (error "No valid command to process %S%s" source err-msg)))))
22797 ;; Check for process failure.
22798 (let ((output (concat out-dir base-name "." ext)))
22799 (unless (org-file-newer-than-p output time)
22800 (error (format "File %S wasn't produced%s" output err-msg)))
22801 output)))
22803 ;;; Indentation
22805 (defun org--get-expected-indentation (element contentsp)
22806 "Expected indentation column for current line, according to ELEMENT.
22807 ELEMENT is an element containing point. CONTENTSP is non-nil
22808 when indentation is to be computed according to contents of
22809 ELEMENT."
22810 (let ((type (org-element-type element))
22811 (start (org-element-property :begin element))
22812 (post-affiliated (org-element-property :post-affiliated element)))
22813 (org-with-wide-buffer
22814 (cond
22815 (contentsp
22816 (cl-case type
22817 ((diary-sexp footnote-definition) 0)
22818 ((headline inlinetask nil)
22819 (if (not org-adapt-indentation) 0
22820 (let ((level (org-current-level)))
22821 (if level (1+ level) 0))))
22822 ((item plain-list) (org-list-item-body-column post-affiliated))
22824 (goto-char start)
22825 (org-get-indentation))))
22826 ((memq type '(headline inlinetask nil))
22827 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22828 (org--get-expected-indentation element t)
22830 ((memq type '(diary-sexp footnote-definition)) 0)
22831 ;; First paragraph of a footnote definition or an item.
22832 ;; Indent like parent.
22833 ((< (line-beginning-position) start)
22834 (org--get-expected-indentation
22835 (org-element-property :parent element) t))
22836 ;; At first line: indent according to previous sibling, if any,
22837 ;; ignoring footnote definitions and inline tasks, or parent's
22838 ;; contents.
22839 ((= (line-beginning-position) start)
22840 (catch 'exit
22841 (while t
22842 (if (= (point-min) start) (throw 'exit 0)
22843 (goto-char (1- start))
22844 (let* ((previous (org-element-at-point))
22845 (parent previous))
22846 (while (and parent (<= (org-element-property :end parent) start))
22847 (setq previous parent
22848 parent (org-element-property :parent parent)))
22849 (cond
22850 ((not previous) (throw 'exit 0))
22851 ((> (org-element-property :end previous) start)
22852 (throw 'exit (org--get-expected-indentation previous t)))
22853 ((memq (org-element-type previous)
22854 '(footnote-definition inlinetask))
22855 (setq start (org-element-property :begin previous)))
22856 (t (goto-char (org-element-property :begin previous))
22857 (throw 'exit
22858 (if (bolp) (org-get-indentation)
22859 ;; At first paragraph in an item or
22860 ;; a footnote definition.
22861 (org--get-expected-indentation
22862 (org-element-property :parent previous) t))))))))))
22863 ;; Otherwise, move to the first non-blank line above.
22865 (beginning-of-line)
22866 (let ((pos (point)))
22867 (skip-chars-backward " \r\t\n")
22868 (cond
22869 ;; Two blank lines end a footnote definition or a plain
22870 ;; list. When we indent an empty line after them, the
22871 ;; containing list or footnote definition is over, so it
22872 ;; qualifies as a previous sibling. Therefore, we indent
22873 ;; like its first line.
22874 ((and (memq type '(footnote-definition plain-list))
22875 (> (count-lines (point) pos) 2))
22876 (goto-char start)
22877 (org-get-indentation))
22878 ;; Line above is the first one of a paragraph at the
22879 ;; beginning of an item or a footnote definition. Indent
22880 ;; like parent.
22881 ((< (line-beginning-position) start)
22882 (org--get-expected-indentation
22883 (org-element-property :parent element) t))
22884 ;; Line above is the beginning of an element, i.e., point
22885 ;; was originally on the blank lines between element's start
22886 ;; and contents.
22887 ((= (line-beginning-position) post-affiliated)
22888 (org--get-expected-indentation element t))
22889 ;; POS is after contents in a greater element. Indent like
22890 ;; the beginning of the element.
22892 ;; As a special case, if point is at the end of a footnote
22893 ;; definition or an item, indent like the very last element
22894 ;; within. If that last element is an item, indent like its
22895 ;; contents.
22896 ((and (not (eq type 'paragraph))
22897 (let ((cend (org-element-property :contents-end element)))
22898 (and cend (<= cend pos))))
22899 (if (memq type '(footnote-definition item plain-list))
22900 (let ((last (org-element-at-point)))
22901 (org--get-expected-indentation
22902 last (eq (org-element-type last) 'item)))
22903 (goto-char start)
22904 (org-get-indentation)))
22905 ;; In any other case, indent like the current line.
22906 (t (org-get-indentation)))))))))
22908 (defun org--align-node-property ()
22909 "Align node property at point.
22910 Alignment is done according to `org-property-format', which see."
22911 (when (save-excursion
22912 (beginning-of-line)
22913 (looking-at org-property-re))
22914 (replace-match
22915 (concat (match-string 4)
22916 (org-trim
22917 (format org-property-format (match-string 1) (match-string 3))))
22918 t t)))
22920 (defun org-indent-line ()
22921 "Indent line depending on context.
22923 Indentation is done according to the following rules:
22925 - Footnote definitions, diary sexps, headlines and inline tasks
22926 have to start at column 0.
22928 - On the very first line of an element, consider, in order, the
22929 next rules until one matches:
22931 1. If there's a sibling element before, ignoring footnote
22932 definitions and inline tasks, indent like its first line.
22934 2. If element has a parent, indent like its contents. More
22935 precisely, if parent is an item, indent after the
22936 description part, if any, or the bullet (see
22937 `org-list-description-max-indent'). Else, indent like
22938 parent's first line.
22940 3. Otherwise, indent relatively to current level, if
22941 `org-adapt-indentation' is non-nil, or to left margin.
22943 - On a blank line at the end of an element, indent according to
22944 the type of the element. More precisely
22946 1. If element is a plain list, an item, or a footnote
22947 definition, indent like the very last element within.
22949 2. If element is a paragraph, indent like its last non blank
22950 line.
22952 3. Otherwise, indent like its very first line.
22954 - In the code part of a source block, use language major mode
22955 to indent current line if `org-src-tab-acts-natively' is
22956 non-nil. If it is nil, do nothing.
22958 - Otherwise, indent like the first non-blank line above.
22960 The function doesn't indent an item as it could break the whole
22961 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22962 \\[org-shiftmetaright].
22964 Also align node properties according to `org-property-format'."
22965 (interactive)
22966 (cond
22967 (orgstruct-is-++
22968 (let ((indent-line-function
22969 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22970 (indent-according-to-mode)))
22971 ((org-at-heading-p) 'noindent)
22973 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22974 (type (org-element-type element)))
22975 (cond ((and (memq type '(plain-list item))
22976 (= (line-beginning-position)
22977 (org-element-property :post-affiliated element)))
22978 'noindent)
22979 ((and (eq type 'src-block)
22980 org-src-tab-acts-natively
22981 (> (line-beginning-position)
22982 (org-element-property :post-affiliated element))
22983 (< (line-beginning-position)
22984 (org-with-wide-buffer
22985 (goto-char (org-element-property :end element))
22986 (skip-chars-backward " \r\t\n")
22987 (line-beginning-position))))
22988 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22990 (let ((column (org--get-expected-indentation element nil)))
22991 ;; Preserve current column.
22992 (if (<= (current-column) (current-indentation))
22993 (indent-line-to column)
22994 (save-excursion (indent-line-to column))))
22995 ;; Align node property. Also preserve current column.
22996 (when (eq type 'node-property)
22997 (let ((column (current-column)))
22998 (org--align-node-property)
22999 (org-move-to-column column)))))))))
23001 (defun org-indent-region (start end)
23002 "Indent each non-blank line in the region.
23003 Called from a program, START and END specify the region to
23004 indent. The function will not indent contents of example blocks,
23005 verse blocks and export blocks as leading white spaces are
23006 assumed to be significant there."
23007 (interactive "r")
23008 (save-excursion
23009 (goto-char start)
23010 (skip-chars-forward " \r\t\n")
23011 (unless (eobp) (beginning-of-line))
23012 (let ((indent-to
23013 (lambda (ind pos)
23014 ;; Set IND as indentation for all lines between point and
23015 ;; POS. Blank lines are ignored. Leave point after POS
23016 ;; once done.
23017 (let ((limit (copy-marker pos)))
23018 (while (< (point) limit)
23019 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
23020 (forward-line))
23021 (set-marker limit nil))))
23022 (end (copy-marker end)))
23023 (while (< (point) end)
23024 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23025 (let* ((element (org-element-at-point))
23026 (type (org-element-type element))
23027 (element-end (copy-marker (org-element-property :end element)))
23028 (ind (org--get-expected-indentation element nil)))
23029 (cond
23030 ((or (memq type '(paragraph table table-row))
23031 (not (or (org-element-property :contents-begin element)
23032 (memq type
23033 '(example-block export-block src-block)))))
23034 ;; Elements here are indented as a single block. Also
23035 ;; align node properties.
23036 (when (eq type 'node-property)
23037 (org--align-node-property)
23038 (beginning-of-line))
23039 (funcall indent-to ind (min element-end end)))
23041 ;; Elements in this category consist of three parts:
23042 ;; before the contents, the contents, and after the
23043 ;; contents. The contents are treated specially,
23044 ;; according to the element type, or not indented at
23045 ;; all. Other parts are indented as a single block.
23046 (let* ((post (copy-marker
23047 (org-element-property :post-affiliated element)))
23048 (cbeg
23049 (copy-marker
23050 (cond
23051 ((not (org-element-property :contents-begin element))
23052 ;; Fake contents for source blocks.
23053 (org-with-wide-buffer
23054 (goto-char post)
23055 (forward-line)
23056 (point)))
23057 ((memq type '(footnote-definition item plain-list))
23058 ;; Contents in these elements could start on
23059 ;; the same line as the beginning of the
23060 ;; element. Make sure we start indenting
23061 ;; from the second line.
23062 (org-with-wide-buffer
23063 (goto-char post)
23064 (end-of-line)
23065 (skip-chars-forward " \r\t\n")
23066 (if (eobp) (point) (line-beginning-position))))
23067 (t (org-element-property :contents-begin element)))))
23068 (cend (copy-marker
23069 (or (org-element-property :contents-end element)
23070 ;; Fake contents for source blocks.
23071 (org-with-wide-buffer
23072 (goto-char element-end)
23073 (skip-chars-backward " \r\t\n")
23074 (line-beginning-position)))
23075 t)))
23076 ;; Do not change items indentation individually as it
23077 ;; might break the list as a whole. On the other
23078 ;; hand, when at a plain list, indent it as a whole.
23079 (cond ((eq type 'plain-list)
23080 (let ((offset (- ind (org-get-indentation))))
23081 (unless (zerop offset)
23082 (indent-rigidly (org-element-property :begin element)
23083 (org-element-property :end element)
23084 offset))
23085 (goto-char cbeg)))
23086 ((eq type 'item) (goto-char cbeg))
23087 (t (funcall indent-to ind (min cbeg end))))
23088 (when (< (point) end)
23089 (cl-case type
23090 ((example-block export-block verse-block))
23091 (src-block
23092 ;; In a source block, indent source code
23093 ;; according to language major mode, but only if
23094 ;; `org-src-tab-acts-natively' is non-nil.
23095 (when (and (< (point) end) org-src-tab-acts-natively)
23096 (ignore-errors
23097 (org-babel-do-in-edit-buffer
23098 (indent-region (point-min) (point-max))))))
23099 (t (org-indent-region (point) (min cend end))))
23100 (goto-char (min cend end))
23101 (when (< (point) end)
23102 (funcall indent-to ind (min element-end end))))
23103 (set-marker post nil)
23104 (set-marker cbeg nil)
23105 (set-marker cend nil))))
23106 (set-marker element-end nil))))
23107 (set-marker end nil))))
23109 (defun org-indent-drawer ()
23110 "Indent the drawer at point."
23111 (interactive)
23112 (unless (save-excursion
23113 (beginning-of-line)
23114 (looking-at-p org-drawer-regexp))
23115 (user-error "Not at a drawer"))
23116 (let ((element (org-element-at-point)))
23117 (unless (memq (org-element-type element) '(drawer property-drawer))
23118 (user-error "Not at a drawer"))
23119 (org-with-wide-buffer
23120 (org-indent-region (org-element-property :begin element)
23121 (org-element-property :end element))))
23122 (message "Drawer at point indented"))
23124 (defun org-indent-block ()
23125 "Indent the block at point."
23126 (interactive)
23127 (unless (save-excursion
23128 (beginning-of-line)
23129 (let ((case-fold-search t))
23130 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23131 (user-error "Not at a block"))
23132 (let ((element (org-element-at-point)))
23133 (unless (memq (org-element-type element)
23134 '(comment-block center-block dynamic-block example-block
23135 export-block quote-block special-block
23136 src-block verse-block))
23137 (user-error "Not at a block"))
23138 (org-with-wide-buffer
23139 (org-indent-region (org-element-property :begin element)
23140 (org-element-property :end element))))
23141 (message "Block at point indented"))
23144 ;;; Filling
23146 ;; We use our own fill-paragraph and auto-fill functions.
23148 ;; `org-fill-paragraph' relies on adaptive filling and context
23149 ;; checking. Appropriate `fill-prefix' is computed with
23150 ;; `org-adaptive-fill-function'.
23152 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23153 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23154 ;; `org-adaptive-fill-function' value. Internally,
23155 ;; `org-comment-line-break-function' breaks the line.
23157 ;; `org-setup-filling' installs filling and auto-filling related
23158 ;; variables during `org-mode' initialization.
23160 (defvar org-element-paragraph-separate) ; org-element.el
23161 (defun org-setup-filling ()
23162 (require 'org-element)
23163 ;; Prevent auto-fill from inserting unwanted new items.
23164 (when (boundp 'fill-nobreak-predicate)
23165 (setq-local
23166 fill-nobreak-predicate
23167 (org-uniquify
23168 (append fill-nobreak-predicate
23169 '(org-fill-line-break-nobreak-p
23170 org-fill-paragraph-with-timestamp-nobreak-p)))))
23171 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23172 (setq-local paragraph-start paragraph-ending)
23173 (setq-local paragraph-separate paragraph-ending))
23174 (setq-local fill-paragraph-function 'org-fill-paragraph)
23175 (setq-local auto-fill-inhibit-regexp nil)
23176 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23177 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23178 (setq-local comment-line-break-function 'org-comment-line-break-function))
23180 (defun org-fill-line-break-nobreak-p ()
23181 "Non-nil when a new line at point would create an Org line break."
23182 (save-excursion
23183 (skip-chars-backward "[ \t]")
23184 (skip-chars-backward "\\\\")
23185 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23187 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23188 "Non-nil when a new line at point would split a timestamp."
23189 (and (org-at-timestamp-p t)
23190 (not (looking-at org-ts-regexp-both))))
23192 (declare-function message-in-body-p "message" ())
23193 (defvar orgtbl-line-start-regexp) ; From org-table.el
23194 (defun org-adaptive-fill-function ()
23195 "Compute a fill prefix for the current line.
23196 Return fill prefix, as a string, or nil if current line isn't
23197 meant to be filled. For convenience, if `adaptive-fill-regexp'
23198 matches in paragraphs or comments, use it."
23199 (catch 'exit
23200 (when (derived-mode-p 'message-mode)
23201 (save-excursion
23202 (beginning-of-line)
23203 (cond ((not (message-in-body-p)) (throw 'exit nil))
23204 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23205 ((looking-at message-cite-prefix-regexp)
23206 (throw 'exit (match-string-no-properties 0)))
23207 ((looking-at org-outline-regexp)
23208 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23209 (org-with-wide-buffer
23210 (unless (org-at-heading-p)
23211 (let* ((p (line-beginning-position))
23212 (element (save-excursion
23213 (beginning-of-line)
23214 (org-element-at-point)))
23215 (type (org-element-type element))
23216 (post-affiliated (org-element-property :post-affiliated element)))
23217 (unless (< p post-affiliated)
23218 (cl-case type
23219 (comment
23220 (save-excursion
23221 (beginning-of-line)
23222 (looking-at "[ \t]*")
23223 (concat (match-string 0) "# ")))
23224 (footnote-definition "")
23225 ((item plain-list)
23226 (make-string (org-list-item-body-column post-affiliated) ?\s))
23227 (paragraph
23228 ;; Fill prefix is usually the same as the current line,
23229 ;; unless the paragraph is at the beginning of an item.
23230 (let ((parent (org-element-property :parent element)))
23231 (save-excursion
23232 (beginning-of-line)
23233 (cond ((eq (org-element-type parent) 'item)
23234 (make-string (org-list-item-body-column
23235 (org-element-property :begin parent))
23236 ?\s))
23237 ((and adaptive-fill-regexp
23238 ;; Locally disable
23239 ;; `adaptive-fill-function' to let
23240 ;; `fill-context-prefix' handle
23241 ;; `adaptive-fill-regexp' variable.
23242 (let (adaptive-fill-function)
23243 (fill-context-prefix
23244 post-affiliated
23245 (org-element-property :end element)))))
23246 ((looking-at "[ \t]+") (match-string 0))
23247 (t "")))))
23248 (comment-block
23249 ;; Only fill contents if P is within block boundaries.
23250 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23251 (forward-line)
23252 (point)))
23253 (cend (save-excursion
23254 (goto-char (org-element-property :end element))
23255 (skip-chars-backward " \r\t\n")
23256 (line-beginning-position))))
23257 (when (and (>= p cbeg) (< p cend))
23258 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23259 (match-string 0)
23260 "")))))))))))
23262 (declare-function message-goto-body "message" ())
23263 (defvar message-cite-prefix-regexp) ; From message.el
23264 (defun org-fill-paragraph (&optional justify)
23265 "Fill element at point, when applicable.
23267 This function only applies to comment blocks, comments, example
23268 blocks and paragraphs. Also, as a special case, re-align table
23269 when point is at one.
23271 If JUSTIFY is non-nil (interactively, with prefix argument),
23272 justify as well. If `sentence-end-double-space' is non-nil, then
23273 period followed by one space does not end a sentence, so don't
23274 break a line there. The variable `fill-column' controls the
23275 width for filling.
23277 For convenience, when point is at a plain list, an item or
23278 a footnote definition, try to fill the first paragraph within."
23279 (interactive)
23280 (if (and (derived-mode-p 'message-mode)
23281 (or (not (message-in-body-p))
23282 (save-excursion (move-beginning-of-line 1)
23283 (looking-at message-cite-prefix-regexp))))
23284 ;; First ensure filling is correct in message-mode.
23285 (let ((fill-paragraph-function
23286 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23287 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23288 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23289 (paragraph-separate
23290 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23291 (fill-paragraph nil))
23292 (with-syntax-table org-mode-transpose-word-syntax-table
23293 ;; Move to end of line in order to get the first paragraph
23294 ;; within a plain list or a footnote definition.
23295 (let ((element (save-excursion
23296 (end-of-line)
23297 (or (ignore-errors (org-element-at-point))
23298 (user-error "An element cannot be parsed line %d"
23299 (line-number-at-pos (point)))))))
23300 ;; First check if point is in a blank line at the beginning of
23301 ;; the buffer. In that case, ignore filling.
23302 (cl-case (org-element-type element)
23303 ;; Use major mode filling function is src blocks.
23304 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23305 ;; Align Org tables, leave table.el tables as-is.
23306 (table-row (org-table-align) t)
23307 (table
23308 (when (eq (org-element-property :type element) 'org)
23309 (save-excursion
23310 (goto-char (org-element-property :post-affiliated element))
23311 (org-table-align)))
23313 (paragraph
23314 ;; Paragraphs may contain `line-break' type objects.
23315 (let ((beg (max (point-min)
23316 (org-element-property :contents-begin element)))
23317 (end (min (point-max)
23318 (org-element-property :contents-end element))))
23319 ;; Do nothing if point is at an affiliated keyword.
23320 (if (< (line-end-position) beg) t
23321 (when (derived-mode-p 'message-mode)
23322 ;; In `message-mode', do not fill following citation
23323 ;; in current paragraph nor text before message body.
23324 (let ((body-start (save-excursion (message-goto-body))))
23325 (when body-start (setq beg (max body-start beg))))
23326 (when (save-excursion
23327 (re-search-forward
23328 (concat "^" message-cite-prefix-regexp) end t))
23329 (setq end (match-beginning 0))))
23330 ;; Fill paragraph, taking line breaks into account.
23331 (save-excursion
23332 (goto-char beg)
23333 (let ((cuts (list beg)))
23334 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23335 (when (eq 'line-break
23336 (org-element-type
23337 (save-excursion (backward-char)
23338 (org-element-context))))
23339 (push (point) cuts)))
23340 (dolist (c (delq end cuts))
23341 (fill-region-as-paragraph c end justify)
23342 (setq end c))))
23343 t)))
23344 ;; Contents of `comment-block' type elements should be
23345 ;; filled as plain text, but only if point is within block
23346 ;; markers.
23347 (comment-block
23348 (let* ((case-fold-search t)
23349 (beg (save-excursion
23350 (goto-char (org-element-property :begin element))
23351 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23352 (forward-line)
23353 (point)))
23354 (end (save-excursion
23355 (goto-char (org-element-property :end element))
23356 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23357 (line-beginning-position))))
23358 (if (or (< (point) beg) (> (point) end)) t
23359 (fill-region-as-paragraph
23360 (save-excursion (end-of-line)
23361 (re-search-backward "^[ \t]*$" beg 'move)
23362 (line-beginning-position))
23363 (save-excursion (beginning-of-line)
23364 (re-search-forward "^[ \t]*$" end 'move)
23365 (line-beginning-position))
23366 justify))))
23367 ;; Fill comments.
23368 (comment
23369 (let ((begin (org-element-property :post-affiliated element))
23370 (end (org-element-property :end element)))
23371 (when (and (>= (point) begin) (<= (point) end))
23372 (let ((begin (save-excursion
23373 (end-of-line)
23374 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23375 (progn (forward-line) (point))
23376 begin)))
23377 (end (save-excursion
23378 (end-of-line)
23379 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23380 (1- (line-beginning-position))
23381 (skip-chars-backward " \r\t\n")
23382 (line-end-position)))))
23383 ;; Do not fill comments when at a blank line.
23384 (when (> end begin)
23385 (let ((fill-prefix
23386 (save-excursion
23387 (beginning-of-line)
23388 (looking-at "[ \t]*#")
23389 (let ((comment-prefix (match-string 0)))
23390 (goto-char (match-end 0))
23391 (if (looking-at adaptive-fill-regexp)
23392 (concat comment-prefix (match-string 0))
23393 (concat comment-prefix " "))))))
23394 (save-excursion
23395 (fill-region-as-paragraph begin end justify))))))
23397 ;; Ignore every other element.
23398 (otherwise t))))))
23400 (defun org-auto-fill-function ()
23401 "Auto-fill function."
23402 ;; Check if auto-filling is meaningful.
23403 (let ((fc (current-fill-column)))
23404 (when (and fc (> (current-column) fc))
23405 (let* ((fill-prefix (org-adaptive-fill-function))
23406 ;; Enforce empty fill prefix, if required. Otherwise, it
23407 ;; will be computed again.
23408 (adaptive-fill-mode (not (equal fill-prefix ""))))
23409 (when fill-prefix (do-auto-fill))))))
23411 (defun org-comment-line-break-function (&optional soft)
23412 "Break line at point and indent, continuing comment if within one.
23413 The inserted newline is marked hard if variable
23414 `use-hard-newlines' is true, unless optional argument SOFT is
23415 non-nil."
23416 (if soft (insert-and-inherit ?\n) (newline 1))
23417 (save-excursion (forward-char -1) (delete-horizontal-space))
23418 (delete-horizontal-space)
23419 (indent-to-left-margin)
23420 (insert-before-markers-and-inherit fill-prefix))
23423 ;;; Fixed Width Areas
23425 (defun org-toggle-fixed-width ()
23426 "Toggle fixed-width markup.
23428 Add or remove fixed-width markup on current line, whenever it
23429 makes sense. Return an error otherwise.
23431 If a region is active and if it contains only fixed-width areas
23432 or blank lines, remove all fixed-width markup in it. If the
23433 region contains anything else, convert all non-fixed-width lines
23434 to fixed-width ones.
23436 Blank lines at the end of the region are ignored unless the
23437 region only contains such lines."
23438 (interactive)
23439 (if (not (org-region-active-p))
23440 ;; No region:
23442 ;; Remove fixed width marker only in a fixed-with element.
23444 ;; Add fixed width maker in paragraphs, in blank lines after
23445 ;; elements or at the beginning of a headline or an inlinetask,
23446 ;; and before any one-line elements (e.g., a clock).
23447 (progn
23448 (beginning-of-line)
23449 (let* ((element (org-element-at-point))
23450 (type (org-element-type element)))
23451 (cond
23452 ((and (eq type 'fixed-width)
23453 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23454 (replace-match
23455 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23456 ((and (memq type '(babel-call clock comment diary-sexp headline
23457 horizontal-rule keyword paragraph
23458 planning))
23459 (<= (org-element-property :post-affiliated element) (point)))
23460 (skip-chars-forward " \t")
23461 (insert ": "))
23462 ((and (looking-at-p "[ \t]*$")
23463 (or (eq type 'inlinetask)
23464 (save-excursion
23465 (skip-chars-forward " \r\t\n")
23466 (<= (org-element-property :end element) (point)))))
23467 (delete-region (point) (line-end-position))
23468 (org-indent-line)
23469 (insert ": "))
23470 (t (user-error "Cannot insert a fixed-width line here")))))
23471 ;; Region active.
23472 (let* ((begin (save-excursion
23473 (goto-char (region-beginning))
23474 (line-beginning-position)))
23475 (end (copy-marker
23476 (save-excursion
23477 (goto-char (region-end))
23478 (unless (eolp) (beginning-of-line))
23479 (if (save-excursion (re-search-backward "\\S-" begin t))
23480 (progn (skip-chars-backward " \r\t\n") (point))
23481 (point)))))
23482 (all-fixed-width-p
23483 (catch 'not-all-p
23484 (save-excursion
23485 (goto-char begin)
23486 (skip-chars-forward " \r\t\n")
23487 (when (eobp) (throw 'not-all-p nil))
23488 (while (< (point) end)
23489 (let ((element (org-element-at-point)))
23490 (if (eq (org-element-type element) 'fixed-width)
23491 (goto-char (org-element-property :end element))
23492 (throw 'not-all-p nil))))
23493 t))))
23494 (if all-fixed-width-p
23495 (save-excursion
23496 (goto-char begin)
23497 (while (< (point) end)
23498 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23499 (replace-match
23500 "" nil nil nil
23501 (if (= (line-end-position) (match-end 0)) 0 1)))
23502 (forward-line)))
23503 (let ((min-ind (point-max)))
23504 ;; Find minimum indentation across all lines.
23505 (save-excursion
23506 (goto-char begin)
23507 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23508 (setq min-ind 0)
23509 (catch 'zerop
23510 (while (< (point) end)
23511 (unless (looking-at-p "[ \t]*$")
23512 (let ((ind (org-get-indentation)))
23513 (setq min-ind (min min-ind ind))
23514 (when (zerop ind) (throw 'zerop t))))
23515 (forward-line)))))
23516 ;; Loop over all lines and add fixed-width markup everywhere
23517 ;; but in fixed-width lines.
23518 (save-excursion
23519 (goto-char begin)
23520 (while (< (point) end)
23521 (cond
23522 ((org-at-heading-p)
23523 (insert ": ")
23524 (forward-line)
23525 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23526 (insert ":")
23527 (forward-line)))
23528 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23529 (let* ((element (org-element-at-point))
23530 (element-end (org-element-property :end element)))
23531 (if (eq (org-element-type element) 'fixed-width)
23532 (progn (goto-char element-end)
23533 (skip-chars-backward " \r\t\n")
23534 (forward-line))
23535 (let ((limit (min end element-end)))
23536 (while (< (point) limit)
23537 (org-move-to-column min-ind t)
23538 (insert ": ")
23539 (forward-line))))))
23541 (org-move-to-column min-ind t)
23542 (insert ": ")
23543 (forward-line)))))))
23544 (set-marker end nil))))
23547 ;;; Comments
23549 ;; Org comments syntax is quite complex. It requires the entire line
23550 ;; to be just a comment. Also, even with the right syntax at the
23551 ;; beginning of line, some some elements (i.e. verse-block or
23552 ;; example-block) don't accept comments. Usual Emacs comment commands
23553 ;; cannot cope with those requirements. Therefore, Org replaces them.
23555 ;; Org still relies on `comment-dwim', but cannot trust
23556 ;; `comment-only-p'. So, `comment-region-function' and
23557 ;; `uncomment-region-function' both point
23558 ;; to`org-comment-or-uncomment-region'. Eventually,
23559 ;; `org-insert-comment' takes care of insertion of comments at the
23560 ;; beginning of line.
23562 ;; `org-setup-comments-handling' install comments related variables
23563 ;; during `org-mode' initialization.
23565 (defun org-setup-comments-handling ()
23566 (interactive)
23567 (setq-local comment-use-syntax nil)
23568 (setq-local comment-start "# ")
23569 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23570 (setq-local comment-insert-comment-function 'org-insert-comment)
23571 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23572 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23574 (defun org-insert-comment ()
23575 "Insert an empty comment above current line.
23576 If the line is empty, insert comment at its beginning. When
23577 point is within a source block, comment according to the related
23578 major mode."
23579 (if (let ((element (org-element-at-point)))
23580 (and (eq (org-element-type element) 'src-block)
23581 (< (save-excursion
23582 (goto-char (org-element-property :post-affiliated element))
23583 (line-end-position))
23584 (point))
23585 (> (save-excursion
23586 (goto-char (org-element-property :end element))
23587 (skip-chars-backward " \r\t\n")
23588 (line-beginning-position))
23589 (point))))
23590 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23591 (beginning-of-line)
23592 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23593 (open-line 1))
23594 (org-indent-line)
23595 (insert "# ")))
23597 (defvar comment-empty-lines) ; From newcomment.el.
23598 (defun org-comment-or-uncomment-region (beg end &rest _)
23599 "Comment or uncomment each non-blank line in the region.
23600 Uncomment each non-blank line between BEG and END if it only
23601 contains commented lines. Otherwise, comment them. If region is
23602 strictly within a source block, use appropriate comment syntax."
23603 (if (let ((element (org-element-at-point)))
23604 (and (eq (org-element-type element) 'src-block)
23605 (< (save-excursion
23606 (goto-char (org-element-property :post-affiliated element))
23607 (line-end-position))
23608 beg)
23609 (>= (save-excursion
23610 (goto-char (org-element-property :end element))
23611 (skip-chars-backward " \r\t\n")
23612 (line-beginning-position))
23613 end)))
23614 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23615 (save-restriction
23616 ;; Restrict region
23617 (narrow-to-region (save-excursion (goto-char beg)
23618 (skip-chars-forward " \r\t\n" end)
23619 (line-beginning-position))
23620 (save-excursion (goto-char end)
23621 (skip-chars-backward " \r\t\n" beg)
23622 (line-end-position)))
23623 (let ((uncommentp
23624 ;; UNCOMMENTP is non-nil when every non blank line between
23625 ;; BEG and END is a comment.
23626 (save-excursion
23627 (goto-char (point-min))
23628 (while (and (not (eobp))
23629 (let ((element (org-element-at-point)))
23630 (and (eq (org-element-type element) 'comment)
23631 (goto-char (min (point-max)
23632 (org-element-property
23633 :end element)))))))
23634 (eobp))))
23635 (if uncommentp
23636 ;; Only blank lines and comments in region: uncomment it.
23637 (save-excursion
23638 (goto-char (point-min))
23639 (while (not (eobp))
23640 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23641 (replace-match "" nil nil nil 1))
23642 (forward-line)))
23643 ;; Comment each line in region.
23644 (let ((min-indent (point-max)))
23645 ;; First find the minimum indentation across all lines.
23646 (save-excursion
23647 (goto-char (point-min))
23648 (while (and (not (eobp)) (not (zerop min-indent)))
23649 (unless (looking-at "[ \t]*$")
23650 (setq min-indent (min min-indent (current-indentation))))
23651 (forward-line)))
23652 ;; Then loop over all lines.
23653 (save-excursion
23654 (goto-char (point-min))
23655 (while (not (eobp))
23656 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23657 ;; Don't get fooled by invisible text (e.g. link path)
23658 ;; when moving to column MIN-INDENT.
23659 (let ((buffer-invisibility-spec nil))
23660 (org-move-to-column min-indent t))
23661 (insert comment-start))
23662 (forward-line)))))))))
23664 (defun org-comment-dwim (_arg)
23665 "Call `comment-dwim' within a source edit buffer if needed."
23666 (interactive "*P")
23667 (if (org-in-src-block-p)
23668 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23669 (call-interactively 'comment-dwim)))
23672 ;;; Timestamps API
23674 ;; This section contains tools to operate on timestamp objects, as
23675 ;; returned by, e.g. `org-element-context'.
23677 (defun org-timestamp--to-internal-time (timestamp &optional end)
23678 "Encode TIMESTAMP object into Emacs internal time.
23679 Use end of date range or time range when END is non-nil."
23680 (apply #'encode-time
23681 (cons 0
23682 (mapcar
23683 (lambda (prop) (or (org-element-property prop timestamp) 0))
23684 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23685 '(:minute-start :hour-start :day-start :month-start
23686 :year-start))))))
23688 (defun org-timestamp-has-time-p (timestamp)
23689 "Non-nil when TIMESTAMP has a time specified."
23690 (org-element-property :hour-start timestamp))
23692 (defun org-timestamp-format (timestamp format &optional end utc)
23693 "Format a TIMESTAMP object into a string.
23695 FORMAT is a format specifier to be passed to
23696 `format-time-string'.
23698 When optional argument END is non-nil, use end of date-range or
23699 time-range, if possible.
23701 When optional argument UTC is non-nil, time will be expressed as
23702 Universal Time."
23703 (format-time-string
23704 format (org-timestamp--to-internal-time timestamp end)
23705 (and utc t)))
23707 (defun org-timestamp-split-range (timestamp &optional end)
23708 "Extract a TIMESTAMP object from a date or time range.
23710 END, when non-nil, means extract the end of the range.
23711 Otherwise, extract its start.
23713 Return a new timestamp object."
23714 (let ((type (org-element-property :type timestamp)))
23715 (if (memq type '(active inactive diary)) timestamp
23716 (let ((split-ts (org-element-copy timestamp)))
23717 ;; Set new type.
23718 (org-element-put-property
23719 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23720 ;; Copy start properties over end properties if END is
23721 ;; non-nil. Otherwise, copy end properties over `start' ones.
23722 (let ((p-alist '((:minute-start . :minute-end)
23723 (:hour-start . :hour-end)
23724 (:day-start . :day-end)
23725 (:month-start . :month-end)
23726 (:year-start . :year-end))))
23727 (dolist (p-cell p-alist)
23728 (org-element-put-property
23729 split-ts
23730 (funcall (if end #'car #'cdr) p-cell)
23731 (org-element-property
23732 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23733 ;; Eventually refresh `:raw-value'.
23734 (org-element-put-property split-ts :raw-value nil)
23735 (org-element-put-property
23736 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23738 (defun org-timestamp-translate (timestamp &optional boundary)
23739 "Translate TIMESTAMP object to custom format.
23741 Format string is defined in `org-time-stamp-custom-formats',
23742 which see.
23744 When optional argument BOUNDARY is non-nil, it is either the
23745 symbol `start' or `end'. In this case, only translate the
23746 starting or ending part of TIMESTAMP if it is a date or time
23747 range. Otherwise, translate both parts.
23749 Return timestamp as-is if `org-display-custom-times' is nil or if
23750 it has a `diary' type."
23751 (let ((type (org-element-property :type timestamp)))
23752 (if (or (not org-display-custom-times) (eq type 'diary))
23753 (org-element-interpret-data timestamp)
23754 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23755 org-time-stamp-custom-formats)))
23756 (if (and (not boundary) (memq type '(active-range inactive-range)))
23757 (concat (org-timestamp-format timestamp fmt)
23758 "--"
23759 (org-timestamp-format timestamp fmt t))
23760 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23764 ;;; Other stuff.
23766 (defvar reftex-docstruct-symbol)
23767 (defvar reftex-cite-format)
23768 (defvar org--rds)
23770 (defun org-reftex-citation ()
23771 "Use reftex-citation to insert a citation into the buffer.
23772 This looks for a line like
23774 #+BIBLIOGRAPHY: foo plain option:-d
23776 and derives from it that foo.bib is the bibliography file relevant
23777 for this document. It then installs the necessary environment for RefTeX
23778 to work in this buffer and calls `reftex-citation' to insert a citation
23779 into the buffer.
23781 Export of such citations to both LaTeX and HTML is handled by the contributed
23782 package ox-bibtex by Taru Karttunen."
23783 (interactive)
23784 (let ((reftex-docstruct-symbol 'org--rds)
23785 (reftex-cite-format "\\cite{%l}")
23786 org--rds bib)
23787 (save-excursion
23788 (save-restriction
23789 (widen)
23790 (let ((case-fold-search t)
23791 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23792 (if (not (save-excursion
23793 (or (re-search-forward re nil t)
23794 (re-search-backward re nil t))))
23795 (user-error "No bibliography defined in file")
23796 (setq bib (concat (match-string 1) ".bib")
23797 org--rds (list (list 'bib bib)))))))
23798 (call-interactively 'reftex-citation)))
23800 ;;;; Functions extending outline functionality
23802 (defun org-beginning-of-line (&optional arg)
23803 "Go to the beginning of the current line. If that is invisible, continue
23804 to a visible line beginning. This makes the function of C-a more intuitive.
23805 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23806 first attempt, and only move to after the tags when the cursor is already
23807 beyond the end of the headline."
23808 (interactive "P")
23809 (let ((pos (point))
23810 (special (if (consp org-special-ctrl-a/e)
23811 (car org-special-ctrl-a/e)
23812 org-special-ctrl-a/e))
23813 deactivate-mark refpos)
23814 (call-interactively (if (bound-and-true-p visual-line-mode)
23815 #'beginning-of-visual-line
23816 #'move-beginning-of-line))
23817 (cond
23818 ((or arg (not special)))
23819 ((and (looking-at org-complex-heading-regexp)
23820 (eq (char-after (match-end 1)) ?\s))
23821 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23822 (point-at-eol)))
23823 (goto-char
23824 (if (eq special t)
23825 (cond ((> pos refpos) refpos)
23826 ((= pos (point)) refpos)
23827 (t (point)))
23828 (cond ((> pos (point)) (point))
23829 ((not (eq last-command this-command)) (point))
23830 (t refpos)))))
23831 ((org-at-item-p)
23832 ;; Being at an item and not looking at an the item means point
23833 ;; was previously moved to beginning of a visual line, which
23834 ;; doesn't contain the item. Therefore, do nothing special,
23835 ;; just stay here.
23836 (when (looking-at org-list-full-item-re)
23837 ;; Set special position at first white space character after
23838 ;; bullet, and check-box, if any.
23839 (let ((after-bullet
23840 (let ((box (match-end 3)))
23841 (if (not box) (match-end 1)
23842 (let ((after (char-after box)))
23843 (if (and after (= after ? )) (1+ box) box))))))
23844 ;; Special case: Move point to special position when
23845 ;; currently after it or at beginning of line.
23846 (if (eq special t)
23847 (when (or (> pos after-bullet) (= (point) pos))
23848 (goto-char after-bullet))
23849 ;; Reversed case: Move point to special position when
23850 ;; point was already at beginning of line and command is
23851 ;; repeated.
23852 (when (and (= (point) pos) (eq last-command this-command))
23853 (goto-char after-bullet))))))))
23854 (setq disable-point-adjustment
23855 (or (not (invisible-p (point)))
23856 (not (invisible-p (max (point-min) (1- (point))))))))
23858 (defun org-end-of-line (&optional arg)
23859 "Go to the end of the line.
23860 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23861 tags on the first attempt, and only move to after the tags when
23862 the cursor is already beyond the end of the headline."
23863 (interactive "P")
23864 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23865 org-special-ctrl-a/e))
23866 (move-fun (cond ((bound-and-true-p visual-line-mode)
23867 'end-of-visual-line)
23868 ((fboundp 'move-end-of-line) 'move-end-of-line)
23869 (t 'end-of-line)))
23870 deactivate-mark)
23871 (if (or (not special) arg) (call-interactively move-fun)
23872 (let* ((element (save-excursion (beginning-of-line)
23873 (org-element-at-point)))
23874 (type (org-element-type element)))
23875 (cond
23876 ((memq type '(headline inlinetask))
23877 (let ((pos (point)))
23878 (beginning-of-line 1)
23879 (if (looking-at ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$")
23880 (if (eq special t)
23881 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23882 (goto-char (match-beginning 1))
23883 (goto-char (match-end 0)))
23884 (if (or (< pos (match-end 0))
23885 (not (eq this-command last-command)))
23886 (goto-char (match-end 0))
23887 (goto-char (match-beginning 1))))
23888 (call-interactively move-fun))))
23889 ((outline-invisible-p (line-end-position))
23890 ;; If element is hidden, `move-end-of-line' would put point
23891 ;; after it. Use `end-of-line' to stay on current line.
23892 (call-interactively 'end-of-line))
23893 (t (call-interactively move-fun))))))
23894 (setq disable-point-adjustment
23895 (or (not (invisible-p (point)))
23896 (not (invisible-p (max (point-min) (1- (point))))))))
23898 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23899 (define-key org-mode-map "\C-e" 'org-end-of-line)
23901 (defun org-backward-sentence (&optional _arg)
23902 "Go to beginning of sentence, or beginning of table field.
23903 This will call `backward-sentence' or `org-table-beginning-of-field',
23904 depending on context."
23905 (interactive)
23906 (let* ((element (org-element-at-point))
23907 (contents-begin (org-element-property :contents-begin element))
23908 (table (org-element-lineage element '(table) t)))
23909 (if (and table
23910 (> (point) contents-begin)
23911 (<= (point) (org-element-property :contents-end table)))
23912 (call-interactively #'org-table-beginning-of-field)
23913 (save-restriction
23914 (when (and contents-begin
23915 (< (point-min) contents-begin)
23916 (> (point) contents-begin))
23917 (narrow-to-region contents-begin
23918 (org-element-property :contents-end element)))
23919 (call-interactively #'backward-sentence)))))
23921 (defun org-forward-sentence (&optional _arg)
23922 "Go to end of sentence, or end of table field.
23923 This will call `forward-sentence' or `org-table-end-of-field',
23924 depending on context."
23925 (interactive)
23926 (let* ((element (org-element-at-point))
23927 (contents-end (org-element-property :contents-end element))
23928 (table (org-element-lineage element '(table) t)))
23929 (if (and table
23930 (>= (point) (org-element-property :contents-begin table))
23931 (< (point) contents-end))
23932 (call-interactively #'org-table-end-of-field)
23933 (save-restriction
23934 (when (and contents-end
23935 (> (point-max) contents-end)
23936 ;; Skip blank lines between elements.
23937 (< (org-element-property :end element)
23938 (save-excursion (goto-char contents-end)
23939 (skip-chars-forward " \r\t\n"))))
23940 (narrow-to-region (org-element-property :contents-begin element)
23941 contents-end))
23942 (call-interactively #'forward-sentence)))))
23944 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23945 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23947 (defun org-kill-line (&optional _arg)
23948 "Kill line, to tags or end of line."
23949 (interactive)
23950 (cond
23951 ((or (not org-special-ctrl-k)
23952 (bolp)
23953 (not (org-at-heading-p)))
23954 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23955 org-ctrl-k-protect-subtree
23956 (or (eq org-ctrl-k-protect-subtree 'error)
23957 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23958 (user-error "C-k aborted as it would kill a hidden subtree"))
23959 (call-interactively
23960 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23961 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23962 (kill-region (point) (match-beginning 1))
23963 (org-set-tags nil t))
23964 (t (kill-region (point) (point-at-eol)))))
23966 (define-key org-mode-map "\C-k" 'org-kill-line)
23968 (defun org-yank (&optional arg)
23969 "Yank. If the kill is a subtree, treat it specially.
23970 This command will look at the current kill and check if is a single
23971 subtree, or a series of subtrees[1]. If it passes the test, and if the
23972 cursor is at the beginning of a line or after the stars of a currently
23973 empty headline, then the yank is handled specially. How exactly depends
23974 on the value of the following variables.
23976 `org-yank-folded-subtrees'
23977 By default, this variable is non-nil, which results in subtree(s)
23978 being folded after insertion, but only if doing so would now
23979 swallow text after the yanked text.
23981 `org-yank-adjusted-subtrees'
23982 When non-nil (the default value is nil), the subtree will be
23983 promoted or demoted in order to fit into the local outline tree
23984 structure, which means that the level will be adjusted so that it
23985 becomes the smaller one of the two *visible* surrounding headings.
23987 Any prefix to this command will cause `yank' to be called directly with
23988 no special treatment. In particular, a simple \\[universal-argument] prefix \
23989 will just
23990 plainly yank the text as it is.
23992 \[1] The test checks if the first non-white line is a heading
23993 and if there are no other headings with fewer stars."
23994 (interactive "P")
23995 (org-yank-generic 'yank arg))
23997 (defun org-yank-generic (command arg)
23998 "Perform some yank-like command.
24000 This function implements the behavior described in the `org-yank'
24001 documentation. However, it has been generalized to work for any
24002 interactive command with similar behavior."
24004 ;; pretend to be command COMMAND
24005 (setq this-command command)
24007 (if arg
24008 (call-interactively command)
24010 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24011 (and (org-kill-is-subtree-p)
24012 (or (bolp)
24013 (and (looking-at "[ \t]*$")
24014 (string-match
24015 "\\`\\*+\\'"
24016 (buffer-substring (point-at-bol) (point)))))))
24017 swallowp)
24018 (cond
24019 ((and subtreep org-yank-folded-subtrees)
24020 (let ((beg (point))
24021 end)
24022 (if (and subtreep org-yank-adjusted-subtrees)
24023 (org-paste-subtree nil nil 'for-yank)
24024 (call-interactively command))
24026 (setq end (point))
24027 (goto-char beg)
24028 (when (and (bolp) subtreep
24029 (not (setq swallowp
24030 (org-yank-folding-would-swallow-text beg end))))
24031 (org-with-limited-levels
24032 (or (looking-at org-outline-regexp)
24033 (re-search-forward org-outline-regexp-bol end t))
24034 (while (and (< (point) end) (looking-at org-outline-regexp))
24035 (outline-hide-subtree)
24036 (org-cycle-show-empty-lines 'folded)
24037 (condition-case nil
24038 (outline-forward-same-level 1)
24039 (error (goto-char end))))))
24040 (when swallowp
24041 (message
24042 "Inserted text not folded because that would swallow text"))
24044 (goto-char end)
24045 (skip-chars-forward " \t\n\r")
24046 (beginning-of-line 1)
24047 (push-mark beg 'nomsg)))
24048 ((and subtreep org-yank-adjusted-subtrees)
24049 (let ((beg (point-at-bol)))
24050 (org-paste-subtree nil nil 'for-yank)
24051 (push-mark beg 'nomsg)))
24053 (call-interactively command))))))
24055 (defun org-yank-folding-would-swallow-text (beg end)
24056 "Would hide-subtree at BEG swallow any text after END?"
24057 (let (level)
24058 (org-with-limited-levels
24059 (save-excursion
24060 (goto-char beg)
24061 (when (or (looking-at org-outline-regexp)
24062 (re-search-forward org-outline-regexp-bol end t))
24063 (setq level (org-outline-level)))
24064 (goto-char end)
24065 (skip-chars-forward " \t\r\n\v\f")
24066 (not (or (eobp)
24067 (and (bolp) (looking-at-p org-outline-regexp)
24068 (<= (org-outline-level) level))))))))
24070 (define-key org-mode-map "\C-y" 'org-yank)
24072 (defun org-truely-invisible-p ()
24073 "Check if point is at a character currently not visible.
24074 This version does not only check the character property, but also
24075 `visible-mode'."
24076 ;; Early versions of noutline don't have `outline-invisible-p'.
24077 (unless (bound-and-true-p visible-mode)
24078 (outline-invisible-p)))
24080 (defun org-invisible-p2 ()
24081 "Check if point is at a character currently not visible."
24082 (save-excursion
24083 (when (and (eolp) (not (bobp))) (backward-char 1))
24084 ;; Early versions of noutline don't have `outline-invisible-p'.
24085 (outline-invisible-p)))
24087 (defun org-back-to-heading (&optional invisible-ok)
24088 "Call `outline-back-to-heading', but provide a better error message."
24089 (condition-case nil
24090 (outline-back-to-heading invisible-ok)
24091 (error (error "Before first headline at position %d in buffer %s"
24092 (point) (current-buffer)))))
24094 (defun org-before-first-heading-p ()
24095 "Before first heading?"
24096 (save-excursion
24097 (end-of-line)
24098 (null (re-search-backward org-outline-regexp-bol nil t))))
24100 (defun org-at-heading-p (&optional ignored)
24101 (outline-on-heading-p t))
24103 (defun org-in-commented-heading-p (&optional no-inheritance)
24104 "Non-nil if point is under a commented heading.
24105 This function also checks ancestors of the current headline,
24106 unless optional argument NO-INHERITANCE is non-nil."
24107 (cond
24108 ((org-before-first-heading-p) nil)
24109 ((let ((headline (nth 4 (org-heading-components))))
24110 (and headline
24111 (let ((case-fold-search nil))
24112 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24113 headline)))))
24114 (no-inheritance nil)
24116 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24118 (defun org-at-comment-p nil
24119 "Is cursor in a commented line?"
24120 (save-excursion
24121 (save-match-data
24122 (beginning-of-line)
24123 (looking-at "^[ \t]*# "))))
24125 (defun org-at-drawer-p nil
24126 "Is cursor at a drawer keyword?"
24127 (save-excursion
24128 (move-beginning-of-line 1)
24129 (looking-at org-drawer-regexp)))
24131 (defun org-at-block-p nil
24132 "Is cursor at a block keyword?"
24133 (save-excursion
24134 (move-beginning-of-line 1)
24135 (looking-at org-block-regexp)))
24137 (defun org-point-at-end-of-empty-headline ()
24138 "If point is at the end of an empty headline, return t, else nil.
24139 If the heading only contains a TODO keyword, it is still still considered
24140 empty."
24141 (and (looking-at "[ \t]*$")
24142 (when org-todo-line-regexp
24143 (save-excursion
24144 (beginning-of-line 1)
24145 (let ((case-fold-search nil))
24146 (looking-at org-todo-line-regexp)
24147 (string= (match-string 3) ""))))))
24149 (defun org-at-heading-or-item-p ()
24150 (or (org-at-heading-p) (org-at-item-p)))
24152 (defun org-at-target-p ()
24153 (or (org-in-regexp org-radio-target-regexp)
24154 (org-in-regexp org-target-regexp)))
24155 ;; Compatibility alias with Org versions < 7.8.03
24156 (defalias 'org-on-target-p 'org-at-target-p)
24158 (defun org-up-heading-all (arg)
24159 "Move to the heading line of which the present line is a subheading.
24160 This function considers both visible and invisible heading lines.
24161 With argument, move up ARG levels."
24162 (outline-up-heading arg t))
24164 (defun org-up-heading-safe ()
24165 "Move to the heading line of which the present line is a subheading.
24166 This version will not throw an error. It will return the level of the
24167 headline found, or nil if no higher level is found.
24169 Also, this function will be a lot faster than `outline-up-heading',
24170 because it relies on stars being the outline starters. This can really
24171 make a significant difference in outlines with very many siblings."
24172 (when (ignore-errors (org-back-to-heading t))
24173 (let ((level-up (1- (funcall outline-level))))
24174 (and (> level-up 0)
24175 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24176 (funcall outline-level)))))
24178 (defun org-first-sibling-p ()
24179 "Is this heading the first child of its parents?"
24180 (interactive)
24181 (let ((re org-outline-regexp-bol)
24182 level l)
24183 (unless (org-at-heading-p t)
24184 (user-error "Not at a heading"))
24185 (setq level (funcall outline-level))
24186 (save-excursion
24187 (if (not (re-search-backward re nil t))
24189 (setq l (funcall outline-level))
24190 (< l level)))))
24192 (defun org-goto-sibling (&optional previous)
24193 "Goto the next sibling, even if it is invisible.
24194 When PREVIOUS is set, go to the previous sibling instead. Returns t
24195 when a sibling was found. When none is found, return nil and don't
24196 move point."
24197 (let ((fun (if previous 're-search-backward 're-search-forward))
24198 (pos (point))
24199 (re org-outline-regexp-bol)
24200 level l)
24201 (when (ignore-errors (org-back-to-heading t))
24202 (setq level (funcall outline-level))
24203 (catch 'exit
24204 (or previous (forward-char 1))
24205 (while (funcall fun re nil t)
24206 (setq l (funcall outline-level))
24207 (when (< l level) (goto-char pos) (throw 'exit nil))
24208 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24209 (goto-char pos)
24210 nil))))
24212 (defun org-show-siblings ()
24213 "Show all siblings of the current headline."
24214 (save-excursion
24215 (while (org-goto-sibling) (org-flag-heading nil)))
24216 (save-excursion
24217 (while (org-goto-sibling 'previous)
24218 (org-flag-heading nil))))
24220 (defun org-goto-first-child ()
24221 "Goto the first child, even if it is invisible.
24222 Return t when a child was found. Otherwise don't move point and
24223 return nil."
24224 (let (level (pos (point)) (re org-outline-regexp-bol))
24225 (when (ignore-errors (org-back-to-heading t))
24226 (setq level (outline-level))
24227 (forward-char 1)
24228 (if (and (re-search-forward re nil t) (> (outline-level) level))
24229 (progn (goto-char (match-beginning 0)) t)
24230 (goto-char pos) nil))))
24232 (defun org-show-hidden-entry ()
24233 "Show an entry where even the heading is hidden."
24234 (save-excursion
24235 (org-show-entry)))
24237 (defun org-flag-heading (flag &optional entry)
24238 "Flag the current heading. FLAG non-nil means make invisible.
24239 When ENTRY is non-nil, show the entire entry."
24240 (save-excursion
24241 (org-back-to-heading t)
24242 ;; Check if we should show the entire entry
24243 (if entry
24244 (progn
24245 (org-show-entry)
24246 (save-excursion
24247 (and (outline-next-heading)
24248 (org-flag-heading nil))))
24249 (outline-flag-region (max (point-min) (1- (point)))
24250 (save-excursion (outline-end-of-heading) (point))
24251 flag))))
24253 (defun org-get-next-sibling ()
24254 "Move to next heading of the same level, and return point.
24255 If there is no such heading, return nil.
24256 This is like outline-next-sibling, but invisible headings are ok."
24257 (let ((level (funcall outline-level)))
24258 (outline-next-heading)
24259 (while (and (not (eobp)) (> (funcall outline-level) level))
24260 (outline-next-heading))
24261 (unless (or (eobp) (< (funcall outline-level) level))
24262 (point))))
24264 (defun org-get-last-sibling ()
24265 "Move to previous heading of the same level, and return point.
24266 If there is no such heading, return nil."
24267 (let ((opoint (point))
24268 (level (funcall outline-level)))
24269 (outline-previous-heading)
24270 (when (and (/= (point) opoint) (outline-on-heading-p t))
24271 (while (and (> (funcall outline-level) level)
24272 (not (bobp)))
24273 (outline-previous-heading))
24274 (unless (< (funcall outline-level) level)
24275 (point)))))
24277 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24278 "Goto to the end of a subtree."
24279 ;; This contains an exact copy of the original function, but it uses
24280 ;; `org-back-to-heading', to make it work also in invisible
24281 ;; trees. And is uses an invisible-ok argument.
24282 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24283 ;; Furthermore, when used inside Org, finding the end of a large subtree
24284 ;; with many children and grandchildren etc, this can be much faster
24285 ;; than the outline version.
24286 (org-back-to-heading invisible-ok)
24287 (let ((first t)
24288 (level (funcall outline-level)))
24289 (if (and (derived-mode-p 'org-mode) (< level 1000))
24290 ;; A true heading (not a plain list item), in Org
24291 ;; This means we can easily find the end by looking
24292 ;; only for the right number of stars. Using a regexp to do
24293 ;; this is so much faster than using a Lisp loop.
24294 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24295 (forward-char 1)
24296 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24297 ;; something else, do it the slow way
24298 (while (and (not (eobp))
24299 (or first (> (funcall outline-level) level)))
24300 (setq first nil)
24301 (outline-next-heading)))
24302 (unless to-heading
24303 (when (memq (preceding-char) '(?\n ?\^M))
24304 ;; Go to end of line before heading
24305 (forward-char -1)
24306 (when (memq (preceding-char) '(?\n ?\^M))
24307 ;; leave blank line before heading
24308 (forward-char -1)))))
24309 (point))
24311 (defun org-end-of-meta-data (&optional full)
24312 "Skip planning line and properties drawer in current entry.
24313 When optional argument FULL is non-nil, also skip empty lines,
24314 clocking lines and regular drawers at the beginning of the
24315 entry."
24316 (org-back-to-heading t)
24317 (forward-line)
24318 (when (looking-at-p org-planning-line-re) (forward-line))
24319 (when (looking-at org-property-drawer-re)
24320 (goto-char (match-end 0))
24321 (forward-line))
24322 (when (and full (not (org-at-heading-p)))
24323 (catch 'exit
24324 (let ((end (save-excursion (outline-next-heading) (point)))
24325 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24326 (while (not (eobp))
24327 (cond ((looking-at-p org-drawer-regexp)
24328 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24329 (forward-line)
24330 (throw 'exit t)))
24331 ((looking-at-p re) (forward-line))
24332 (t (throw 'exit t))))))))
24334 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24335 "Move forward to the ARG'th subheading at same level as this one.
24336 Stop at the first and last subheadings of a superior heading.
24337 Normally this only looks at visible headings, but when INVISIBLE-OK is
24338 non-nil it will also look at invisible ones."
24339 (interactive "p")
24340 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24341 (if (and arg (< arg 0))
24342 (goto-char (point-min))
24343 (outline-next-heading))
24344 (org-at-heading-p)
24345 (let ((level (- (match-end 0) (match-beginning 0) 1))
24346 (f (if (and arg (< arg 0))
24347 're-search-backward
24348 're-search-forward))
24349 (count (if arg (abs arg) 1))
24350 (result (point)))
24351 (while (and (prog1 (> count 0)
24352 (forward-char (if (and arg (< arg 0)) -1 1)))
24353 (funcall f org-outline-regexp-bol nil 'move))
24354 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24355 (cond ((< l level) (setq count 0))
24356 ((and (= l level)
24357 (or invisible-ok
24358 (progn
24359 (goto-char (line-beginning-position))
24360 (not (outline-invisible-p)))))
24361 (setq count (1- count))
24362 (when (eq l level)
24363 (setq result (point)))))))
24364 (goto-char result))
24365 (beginning-of-line 1)))
24367 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24368 "Move backward to the ARG'th subheading at same level as this one.
24369 Stop at the first and last subheadings of a superior heading."
24370 (interactive "p")
24371 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24373 (defun org-next-visible-heading (arg)
24374 "Move to the next visible heading.
24376 This function wraps `outline-next-visible-heading' with
24377 `org-with-limited-levels' in order to skip over inline tasks and
24378 respect customization of `org-odd-levels-only'."
24379 (interactive "p")
24380 (org-with-limited-levels
24381 (outline-next-visible-heading arg)))
24383 (defun org-previous-visible-heading (arg)
24384 "Move to the previous visible heading.
24386 This function wraps `outline-previous-visible-heading' with
24387 `org-with-limited-levels' in order to skip over inline tasks and
24388 respect customization of `org-odd-levels-only'."
24389 (interactive "p")
24390 (org-with-limited-levels
24391 (outline-previous-visible-heading arg)))
24393 (defun org-next-block (arg &optional backward block-regexp)
24394 "Jump to the next block.
24396 With a prefix argument ARG, jump forward ARG many blocks.
24398 When BACKWARD is non-nil, jump to the previous block.
24400 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24401 Match data is set according to this regexp when the function
24402 returns.
24404 Return point at beginning of the opening line of found block.
24405 Throw an error if no block is found."
24406 (interactive "p")
24407 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24408 (case-fold-search t)
24409 (search-fn (if backward #'re-search-backward #'re-search-forward))
24410 (count (or arg 1))
24411 (origin (point))
24412 last-element)
24413 (if backward (beginning-of-line) (end-of-line))
24414 (while (and (> count 0) (funcall search-fn re nil t))
24415 (let ((element (save-excursion
24416 (goto-char (match-beginning 0))
24417 (save-match-data (org-element-at-point)))))
24418 (when (and (memq (org-element-type element)
24419 '(center-block comment-block dynamic-block
24420 example-block export-block quote-block
24421 special-block src-block verse-block))
24422 (<= (match-beginning 0)
24423 (org-element-property :post-affiliated element)))
24424 (setq last-element element)
24425 (cl-decf count))))
24426 (if (= count 0)
24427 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24428 (save-match-data (org-show-context)))
24429 (goto-char origin)
24430 (user-error "No %s code blocks" (if backward "previous" "further")))))
24432 (defun org-previous-block (arg &optional block-regexp)
24433 "Jump to the previous block.
24434 With a prefix argument ARG, jump backward ARG many source blocks.
24435 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24436 (interactive "p")
24437 (org-next-block arg t block-regexp))
24439 (defun org-forward-paragraph ()
24440 "Move forward to beginning of next paragraph or equivalent.
24442 The function moves point to the beginning of the next visible
24443 structural element, which can be a paragraph, a table, a list
24444 item, etc. It also provides some special moves for convenience:
24446 - On an affiliated keyword, jump to the beginning of the
24447 relative element.
24448 - On an item or a footnote definition, move to the second
24449 element inside, if any.
24450 - On a table or a property drawer, jump after it.
24451 - On a verse or source block, stop after blank lines."
24452 (interactive)
24453 (when (eobp) (user-error "Cannot move further down"))
24454 (let* ((deactivate-mark nil)
24455 (element (org-element-at-point))
24456 (type (org-element-type element))
24457 (post-affiliated (org-element-property :post-affiliated element))
24458 (contents-begin (org-element-property :contents-begin element))
24459 (contents-end (org-element-property :contents-end element))
24460 (end (let ((end (org-element-property :end element)) (parent element))
24461 (while (and (setq parent (org-element-property :parent parent))
24462 (= (org-element-property :contents-end parent) end))
24463 (setq end (org-element-property :end parent)))
24464 end)))
24465 (cond ((not element)
24466 (skip-chars-forward " \r\t\n")
24467 (or (eobp) (beginning-of-line)))
24468 ;; On affiliated keywords, move to element's beginning.
24469 ((< (point) post-affiliated)
24470 (goto-char post-affiliated))
24471 ;; At a table row, move to the end of the table. Similarly,
24472 ;; at a node property, move to the end of the property
24473 ;; drawer.
24474 ((memq type '(node-property table-row))
24475 (goto-char (org-element-property
24476 :end (org-element-property :parent element))))
24477 ((memq type '(property-drawer table)) (goto-char end))
24478 ;; Consider blank lines as separators in verse and source
24479 ;; blocks to ease editing.
24480 ((memq type '(src-block verse-block))
24481 (when (eq type 'src-block)
24482 (setq contents-end
24483 (save-excursion (goto-char end)
24484 (skip-chars-backward " \r\t\n")
24485 (line-beginning-position))))
24486 (beginning-of-line)
24487 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24488 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24489 (goto-char end)
24490 (skip-chars-forward " \r\t\n")
24491 (if (= (point) contents-end) (goto-char end)
24492 (beginning-of-line))))
24493 ;; With no contents, just skip element.
24494 ((not contents-begin) (goto-char end))
24495 ;; If contents are invisible, skip the element altogether.
24496 ((outline-invisible-p (line-end-position))
24497 (cl-case type
24498 (headline
24499 (org-with-limited-levels (outline-next-visible-heading 1)))
24500 ;; At a plain list, make sure we move to the next item
24501 ;; instead of skipping the whole list.
24502 (plain-list (forward-char)
24503 (org-forward-paragraph))
24504 (otherwise (goto-char end))))
24505 ((>= (point) contents-end) (goto-char end))
24506 ((>= (point) contents-begin)
24507 ;; This can only happen on paragraphs and plain lists.
24508 (cl-case type
24509 (paragraph (goto-char end))
24510 ;; At a plain list, try to move to second element in
24511 ;; first item, if possible.
24512 (plain-list (end-of-line)
24513 (org-forward-paragraph))))
24514 ;; When contents start on the middle of a line (e.g. in
24515 ;; items and footnote definitions), try to reach first
24516 ;; element starting after current line.
24517 ((> (line-end-position) contents-begin)
24518 (end-of-line)
24519 (org-forward-paragraph))
24520 (t (goto-char contents-begin)))))
24522 (defun org-backward-paragraph ()
24523 "Move backward to start of previous paragraph or equivalent.
24525 The function moves point to the beginning of the current
24526 structural element, which can be a paragraph, a table, a list
24527 item, etc., or to the beginning of the previous visible one if
24528 point is already there. It also provides some special moves for
24529 convenience:
24531 - On an affiliated keyword, jump to the first one.
24532 - On a table or a property drawer, move to its beginning.
24533 - On a verse or source block, stop before blank lines."
24534 (interactive)
24535 (when (bobp) (user-error "Cannot move further up"))
24536 (let* ((deactivate-mark nil)
24537 (element (org-element-at-point))
24538 (type (org-element-type element))
24539 (contents-begin (org-element-property :contents-begin element))
24540 (contents-end (org-element-property :contents-end element))
24541 (post-affiliated (org-element-property :post-affiliated element))
24542 (begin (org-element-property :begin element)))
24543 (cond
24544 ((not element) (goto-char (point-min)))
24545 ((= (point) begin)
24546 (backward-char)
24547 (org-backward-paragraph))
24548 ((<= (point) post-affiliated) (goto-char begin))
24549 ((memq type '(node-property table-row))
24550 (goto-char (org-element-property
24551 :post-affiliated (org-element-property :parent element))))
24552 ((memq type '(property-drawer table)) (goto-char begin))
24553 ((memq type '(src-block verse-block))
24554 (when (eq type 'src-block)
24555 (setq contents-begin
24556 (save-excursion (goto-char begin) (forward-line) (point))))
24557 (if (= (point) contents-begin) (goto-char post-affiliated)
24558 ;; Inside a verse block, see blank lines as paragraph
24559 ;; separators.
24560 (let ((origin (point)))
24561 (skip-chars-backward " \r\t\n" contents-begin)
24562 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24563 (skip-chars-forward " \r\t\n" origin)
24564 (if (= (point) origin) (goto-char contents-begin)
24565 (beginning-of-line))))))
24566 ((not contents-begin) (goto-char (or post-affiliated begin)))
24567 ((eq type 'paragraph)
24568 (goto-char contents-begin)
24569 ;; When at first paragraph in an item or a footnote definition,
24570 ;; move directly to beginning of line.
24571 (let ((parent-contents
24572 (org-element-property
24573 :contents-begin (org-element-property :parent element))))
24574 (when (and parent-contents (= parent-contents contents-begin))
24575 (beginning-of-line))))
24576 ;; At the end of a greater element, move to the beginning of the
24577 ;; last element within.
24578 ((>= (point) contents-end)
24579 (goto-char (1- contents-end))
24580 (org-backward-paragraph))
24581 (t (goto-char (or post-affiliated begin))))
24582 ;; Ensure we never leave point invisible.
24583 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24585 (defun org-forward-element ()
24586 "Move forward by one element.
24587 Move to the next element at the same level, when possible."
24588 (interactive)
24589 (cond ((eobp) (user-error "Cannot move further down"))
24590 ((org-with-limited-levels (org-at-heading-p))
24591 (let ((origin (point)))
24592 (goto-char (org-end-of-subtree nil t))
24593 (unless (org-with-limited-levels (org-at-heading-p))
24594 (goto-char origin)
24595 (user-error "Cannot move further down"))))
24597 (let* ((elem (org-element-at-point))
24598 (end (org-element-property :end elem))
24599 (parent (org-element-property :parent elem)))
24600 (cond ((and parent (= (org-element-property :contents-end parent) end))
24601 (goto-char (org-element-property :end parent)))
24602 ((integer-or-marker-p end) (goto-char end))
24603 (t (message "No element at point")))))))
24605 (defun org-backward-element ()
24606 "Move backward by one element.
24607 Move to the previous element at the same level, when possible."
24608 (interactive)
24609 (cond ((bobp) (user-error "Cannot move further up"))
24610 ((org-with-limited-levels (org-at-heading-p))
24611 ;; At a headline, move to the previous one, if any, or stay
24612 ;; here.
24613 (let ((origin (point)))
24614 (org-with-limited-levels (org-backward-heading-same-level 1))
24615 ;; When current headline has no sibling above, move to its
24616 ;; parent.
24617 (when (= (point) origin)
24618 (or (org-with-limited-levels (org-up-heading-safe))
24619 (progn (goto-char origin)
24620 (user-error "Cannot move further up"))))))
24622 (let* ((elem (org-element-at-point))
24623 (beg (org-element-property :begin elem)))
24624 (cond
24625 ;; Move to beginning of current element if point isn't
24626 ;; there already.
24627 ((null beg) (message "No element at point"))
24628 ((/= (point) beg) (goto-char beg))
24629 (t (goto-char beg)
24630 (skip-chars-backward " \r\t\n")
24631 (unless (bobp)
24632 (let ((prev (org-element-at-point)))
24633 (goto-char (org-element-property :begin prev))
24634 (while (and (setq prev (org-element-property :parent prev))
24635 (<= (org-element-property :end prev) beg))
24636 (goto-char (org-element-property :begin prev)))))))))))
24638 (defun org-up-element ()
24639 "Move to upper element."
24640 (interactive)
24641 (if (org-with-limited-levels (org-at-heading-p))
24642 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24643 (let* ((elem (org-element-at-point))
24644 (parent (org-element-property :parent elem)))
24645 (if parent (goto-char (org-element-property :begin parent))
24646 (if (org-with-limited-levels (org-before-first-heading-p))
24647 (user-error "No surrounding element")
24648 (org-with-limited-levels (org-back-to-heading)))))))
24650 (defvar org-element-greater-elements)
24651 (defun org-down-element ()
24652 "Move to inner element."
24653 (interactive)
24654 (let ((element (org-element-at-point)))
24655 (cond
24656 ((memq (org-element-type element) '(plain-list table))
24657 (goto-char (org-element-property :contents-begin element))
24658 (forward-char))
24659 ((memq (org-element-type element) org-element-greater-elements)
24660 ;; If contents are hidden, first disclose them.
24661 (when (outline-invisible-p (line-end-position)) (org-cycle))
24662 (goto-char (or (org-element-property :contents-begin element)
24663 (user-error "No content for this element"))))
24664 (t (user-error "No inner element")))))
24666 (defun org-drag-element-backward ()
24667 "Move backward element at point."
24668 (interactive)
24669 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24670 (let* ((elem (org-element-at-point))
24671 (prev-elem
24672 (save-excursion
24673 (goto-char (org-element-property :begin elem))
24674 (skip-chars-backward " \r\t\n")
24675 (unless (bobp)
24676 (let* ((beg (org-element-property :begin elem))
24677 (prev (org-element-at-point))
24678 (up prev))
24679 (while (and (setq up (org-element-property :parent up))
24680 (<= (org-element-property :end up) beg))
24681 (setq prev up))
24682 prev)))))
24683 ;; Error out if no previous element or previous element is
24684 ;; a parent of the current one.
24685 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24686 (user-error "Cannot drag element backward")
24687 (let ((pos (point)))
24688 (org-element-swap-A-B prev-elem elem)
24689 (goto-char (+ (org-element-property :begin prev-elem)
24690 (- pos (org-element-property :begin elem)))))))))
24692 (defun org-drag-element-forward ()
24693 "Move forward element at point."
24694 (interactive)
24695 (let* ((pos (point))
24696 (elem (org-element-at-point)))
24697 (when (= (point-max) (org-element-property :end elem))
24698 (user-error "Cannot drag element forward"))
24699 (goto-char (org-element-property :end elem))
24700 (let ((next-elem (org-element-at-point)))
24701 (when (or (org-element-nested-p elem next-elem)
24702 (and (eq (org-element-type next-elem) 'headline)
24703 (not (eq (org-element-type elem) 'headline))))
24704 (goto-char pos)
24705 (user-error "Cannot drag element forward"))
24706 ;; Compute new position of point: it's shifted by NEXT-ELEM
24707 ;; body's length (without final blanks) and by the length of
24708 ;; blanks between ELEM and NEXT-ELEM.
24709 (let ((size-next (- (save-excursion
24710 (goto-char (org-element-property :end next-elem))
24711 (skip-chars-backward " \r\t\n")
24712 (forward-line)
24713 ;; Small correction if buffer doesn't end
24714 ;; with a newline character.
24715 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24716 (org-element-property :begin next-elem)))
24717 (size-blank (- (org-element-property :end elem)
24718 (save-excursion
24719 (goto-char (org-element-property :end elem))
24720 (skip-chars-backward " \r\t\n")
24721 (forward-line)
24722 (point)))))
24723 (org-element-swap-A-B elem next-elem)
24724 (goto-char (+ pos size-next size-blank))))))
24726 (defun org-drag-line-forward (arg)
24727 "Drag the line at point ARG lines forward."
24728 (interactive "p")
24729 (dotimes (_ (abs arg))
24730 (let ((c (current-column)))
24731 (if (< 0 arg)
24732 (progn
24733 (beginning-of-line 2)
24734 (transpose-lines 1)
24735 (beginning-of-line 0))
24736 (transpose-lines 1)
24737 (beginning-of-line -1))
24738 (org-move-to-column c))))
24740 (defun org-drag-line-backward (arg)
24741 "Drag the line at point ARG lines backward."
24742 (interactive "p")
24743 (org-drag-line-forward (- arg)))
24745 (defun org-mark-element ()
24746 "Put point at beginning of this element, mark at end.
24748 Interactively, if this command is repeated or (in Transient Mark
24749 mode) if the mark is active, it marks the next element after the
24750 ones already marked."
24751 (interactive)
24752 (let (deactivate-mark)
24753 (if (and (called-interactively-p 'any)
24754 (or (and (eq last-command this-command) (mark t))
24755 (and transient-mark-mode mark-active)))
24756 (set-mark
24757 (save-excursion
24758 (goto-char (mark))
24759 (goto-char (org-element-property :end (org-element-at-point)))))
24760 (let ((element (org-element-at-point)))
24761 (end-of-line)
24762 (push-mark (org-element-property :end element) t t)
24763 (goto-char (org-element-property :begin element))))))
24765 (defun org-narrow-to-element ()
24766 "Narrow buffer to current element."
24767 (interactive)
24768 (let ((elem (org-element-at-point)))
24769 (cond
24770 ((eq (car elem) 'headline)
24771 (narrow-to-region
24772 (org-element-property :begin elem)
24773 (org-element-property :end elem)))
24774 ((memq (car elem) org-element-greater-elements)
24775 (narrow-to-region
24776 (org-element-property :contents-begin elem)
24777 (org-element-property :contents-end elem)))
24779 (narrow-to-region
24780 (org-element-property :begin elem)
24781 (org-element-property :end elem))))))
24783 (defun org-transpose-element ()
24784 "Transpose current and previous elements, keeping blank lines between.
24785 Point is moved after both elements."
24786 (interactive)
24787 (org-skip-whitespace)
24788 (let ((end (org-element-property :end (org-element-at-point))))
24789 (org-drag-element-backward)
24790 (goto-char end)))
24792 (defun org-unindent-buffer ()
24793 "Un-indent the visible part of the buffer.
24794 Relative indentation (between items, inside blocks, etc.) isn't
24795 modified."
24796 (interactive)
24797 (unless (eq major-mode 'org-mode)
24798 (user-error "Cannot un-indent a buffer not in Org mode"))
24799 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24800 (unindent-tree
24801 (lambda (contents)
24802 (dolist (element (reverse contents))
24803 (if (memq (org-element-type element) '(headline section))
24804 (funcall unindent-tree (org-element-contents element))
24805 (save-excursion
24806 (save-restriction
24807 (narrow-to-region
24808 (org-element-property :begin element)
24809 (org-element-property :end element))
24810 (org-do-remove-indentation))))))))
24811 (funcall unindent-tree (org-element-contents parse-tree))))
24813 (defun org-show-children (&optional level)
24814 "Show all direct subheadings of this heading.
24815 Prefix arg LEVEL is how many levels below the current level
24816 should be shown. Default is enough to cause the following
24817 heading to appear."
24818 (interactive "p")
24819 ;; If `orgstruct-mode' is active, use the slower version.
24820 (if orgstruct-mode (call-interactively #'outline-show-children)
24821 (save-excursion
24822 (org-back-to-heading t)
24823 (let* ((current-level (funcall outline-level))
24824 (max-level (org-get-valid-level
24825 current-level
24826 (if level (prefix-numeric-value level) 1)))
24827 (end (save-excursion (org-end-of-subtree t t)))
24828 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24829 (past-first-child nil)
24830 ;; Make sure to skip inlinetasks.
24831 (re (format regexp-fmt
24832 current-level
24833 (cond
24834 ((not (featurep 'org-inlinetask)) "")
24835 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24837 (t (1- org-inlinetask-min-level))))))
24838 ;; Display parent heading.
24839 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24840 (forward-line)
24841 ;; Display children. First child may be deeper than expected
24842 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24843 ;; MAX-LEVEL accordingly.
24844 (while (re-search-forward re end t)
24845 (unless past-first-child
24846 (setq re (format regexp-fmt
24847 current-level
24848 (max (funcall outline-level) max-level)))
24849 (setq past-first-child t))
24850 (outline-flag-region
24851 (line-end-position 0) (line-end-position) nil))))))
24853 (defun org-show-subtree ()
24854 "Show everything after this heading at deeper levels."
24855 (interactive)
24856 (outline-flag-region
24857 (point)
24858 (save-excursion
24859 (org-end-of-subtree t t))
24860 nil))
24862 (defun org-show-entry ()
24863 "Show the body directly following this heading.
24864 Show the heading too, if it is currently invisible."
24865 (interactive)
24866 (save-excursion
24867 (ignore-errors
24868 (org-back-to-heading t)
24869 (outline-flag-region
24870 (max (point-min) (1- (point)))
24871 (save-excursion
24872 (if (re-search-forward
24873 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24874 (match-beginning 1)
24875 (point-max)))
24876 nil)
24877 (org-cycle-hide-drawers 'children))))
24879 (defun org-make-options-regexp (kwds &optional extra)
24880 "Make a regular expression for keyword lines.
24881 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24882 when non-nil, is a regexp matching keywords names."
24883 (concat "^[ \t]*#\\+\\("
24884 (regexp-opt kwds)
24885 (and extra (concat (and kwds "\\|") extra))
24886 "\\):[ \t]*\\(.*\\)"))
24888 ;;;; Integration with and fixes for other packages
24890 ;;; Imenu support
24892 (defvar-local org-imenu-markers nil
24893 "All markers currently used by Imenu.")
24895 (defun org-imenu-new-marker (&optional pos)
24896 "Return a new marker for use by Imenu, and remember the marker."
24897 (let ((m (make-marker)))
24898 (move-marker m (or pos (point)))
24899 (push m org-imenu-markers)
24902 (defun org-imenu-get-tree ()
24903 "Produce the index for Imenu."
24904 (dolist (x org-imenu-markers) (move-marker x nil))
24905 (setq org-imenu-markers nil)
24906 (let* ((case-fold-search nil)
24907 (n org-imenu-depth)
24908 (re (concat "^" (org-get-limited-outline-regexp)))
24909 (subs (make-vector (1+ n) nil))
24910 (last-level 0)
24911 m level head0 head)
24912 (save-excursion
24913 (save-restriction
24914 (widen)
24915 (goto-char (point-max))
24916 (while (re-search-backward re nil t)
24917 (setq level (org-reduced-level (funcall outline-level)))
24918 (when (and (<= level n)
24919 (looking-at org-complex-heading-regexp)
24920 (setq head0 (match-string-no-properties 4)))
24921 (setq head (org-link-display-format head0)
24922 m (org-imenu-new-marker))
24923 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24924 (if (>= level last-level)
24925 (push (cons head m) (aref subs level))
24926 (push (cons head (aref subs (1+ level))) (aref subs level))
24927 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24928 (setq last-level level)))))
24929 (aref subs 1)))
24931 (eval-after-load "imenu"
24932 '(progn
24933 (add-hook 'imenu-after-jump-hook
24934 (lambda ()
24935 (when (derived-mode-p 'org-mode)
24936 (org-show-context 'org-goto))))))
24938 (defun org-link-display-format (s)
24939 "Replace links in string S with their description.
24940 If there is no description, use the link target."
24941 (save-match-data
24942 (replace-regexp-in-string
24943 org-bracket-link-analytic-regexp
24944 (lambda (m)
24945 (if (match-end 5) (match-string 5 m)
24946 (concat (match-string 1 m) (match-string 3 m))))
24947 s nil t)))
24949 (defun org-toggle-link-display ()
24950 "Toggle the literal or descriptive display of links."
24951 (interactive)
24952 (if org-descriptive-links
24953 (progn (org-remove-from-invisibility-spec '(org-link))
24954 (org-restart-font-lock)
24955 (setq org-descriptive-links nil))
24956 (progn (add-to-invisibility-spec '(org-link))
24957 (org-restart-font-lock)
24958 (setq org-descriptive-links t))))
24960 ;; Speedbar support
24962 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24963 "Overlay marking the agenda restriction line in speedbar.")
24964 (overlay-put org-speedbar-restriction-lock-overlay
24965 'face 'org-agenda-restriction-lock)
24966 (overlay-put org-speedbar-restriction-lock-overlay
24967 'help-echo "Agendas are currently limited to this item.")
24968 (delete-overlay org-speedbar-restriction-lock-overlay)
24970 (defun org-speedbar-set-agenda-restriction ()
24971 "Restrict future agenda commands to the location at point in speedbar.
24972 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24973 (interactive)
24974 (require 'org-agenda)
24975 (let (p m tp np dir txt)
24976 (cond
24977 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24978 'org-imenu t))
24979 (setq m (get-text-property p 'org-imenu-marker))
24980 (with-current-buffer (marker-buffer m)
24981 (goto-char m)
24982 (org-agenda-set-restriction-lock 'subtree)))
24983 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24984 'speedbar-function 'speedbar-find-file))
24985 (setq tp (previous-single-property-change
24986 (1+ p) 'speedbar-function)
24987 np (next-single-property-change
24988 tp 'speedbar-function)
24989 dir (speedbar-line-directory)
24990 txt (buffer-substring-no-properties (or tp (point-min))
24991 (or np (point-max))))
24992 (with-current-buffer (find-file-noselect
24993 (let ((default-directory dir))
24994 (expand-file-name txt)))
24995 (unless (derived-mode-p 'org-mode)
24996 (user-error "Cannot restrict to non-Org-mode file"))
24997 (org-agenda-set-restriction-lock 'file)))
24998 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24999 (move-overlay org-speedbar-restriction-lock-overlay
25000 (point-at-bol) (point-at-eol))
25001 (setq current-prefix-arg nil)
25002 (org-agenda-maybe-redo)))
25004 (defvar speedbar-file-key-map)
25005 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25006 (eval-after-load "speedbar"
25007 '(progn
25008 (speedbar-add-supported-extension ".org")
25009 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25010 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25011 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25012 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25013 (add-hook 'speedbar-visiting-tag-hook
25014 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25016 ;;; Fixes and Hacks for problems with other packages
25018 (defun org--flyspell-object-check-p (element)
25019 "Non-nil when Flyspell can check object at point.
25020 ELEMENT is the element at point."
25021 (let ((object (save-excursion
25022 (when (looking-at-p "\\>") (backward-char))
25023 (org-element-context element))))
25024 (cl-case (org-element-type object)
25025 ;; Prevent checks in links due to keybinding conflict with
25026 ;; Flyspell.
25027 ((code entity export-snippet inline-babel-call
25028 inline-src-block line-break latex-fragment link macro
25029 statistics-cookie target timestamp verbatim)
25030 nil)
25031 (footnote-reference
25032 ;; Only in inline footnotes, within the definition.
25033 (and (eq (org-element-property :type object) 'inline)
25034 (< (save-excursion
25035 (goto-char (org-element-property :begin object))
25036 (search-forward ":" nil t 2))
25037 (point))))
25038 (otherwise t))))
25040 (defun org-mode-flyspell-verify ()
25041 "Function used for `flyspell-generic-check-word-predicate'."
25042 (if (org-at-heading-p)
25043 ;; At a headline or an inlinetask, check title only. This is
25044 ;; faster than relying on `org-element-at-point'.
25045 (and (save-excursion (beginning-of-line)
25046 (and (let ((case-fold-search t))
25047 (not (looking-at "\\*+ END[ \t]*$")))
25048 (looking-at org-complex-heading-regexp)))
25049 (match-beginning 4)
25050 (>= (point) (match-beginning 4))
25051 (or (not (match-beginning 5))
25052 (< (point) (match-beginning 5))))
25053 (let* ((element (org-element-at-point))
25054 (post-affiliated (org-element-property :post-affiliated element)))
25055 (cond
25056 ;; Ignore checks in all affiliated keywords but captions.
25057 ((< (point) post-affiliated)
25058 (and (save-excursion
25059 (beginning-of-line)
25060 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25061 (> (point) (match-end 0))
25062 (org--flyspell-object-check-p element)))
25063 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25064 ((let ((log (org-log-into-drawer)))
25065 (and log
25066 (let ((drawer (org-element-lineage element '(drawer))))
25067 (and drawer
25068 (eq (compare-strings
25069 log nil nil
25070 (org-element-property :drawer-name drawer) nil nil t)
25071 t)))))
25072 nil)
25074 (cl-case (org-element-type element)
25075 ((comment quote-section) t)
25076 (comment-block
25077 ;; Allow checks between block markers, not on them.
25078 (and (> (line-beginning-position) post-affiliated)
25079 (save-excursion
25080 (end-of-line)
25081 (skip-chars-forward " \r\t\n")
25082 (< (point) (org-element-property :end element)))))
25083 ;; Arbitrary list of keywords where checks are meaningful.
25084 ;; Make sure point is on the value part of the element.
25085 (keyword
25086 (and (member (org-element-property :key element)
25087 '("DESCRIPTION" "TITLE"))
25088 (save-excursion
25089 (search-backward ":" (line-beginning-position) t))))
25090 ;; Check is globally allowed in paragraphs verse blocks and
25091 ;; table rows (after affiliated keywords) but some objects
25092 ;; must not be affected.
25093 ((paragraph table-row verse-block)
25094 (let ((cbeg (org-element-property :contents-begin element))
25095 (cend (org-element-property :contents-end element)))
25096 (and cbeg (>= (point) cbeg) (< (point) cend)
25097 (org--flyspell-object-check-p element))))))))))
25098 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25100 (defun org-remove-flyspell-overlays-in (beg end)
25101 "Remove flyspell overlays in region."
25102 (and (bound-and-true-p flyspell-mode)
25103 (fboundp 'flyspell-delete-region-overlays)
25104 (flyspell-delete-region-overlays beg end)))
25106 (defvar flyspell-delayed-commands)
25107 (eval-after-load "flyspell"
25108 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25110 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25111 (eval-after-load "bookmark"
25112 '(if (boundp 'bookmark-after-jump-hook)
25113 ;; We can use the hook
25114 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25115 ;; Hook not available, use advice
25116 (defadvice bookmark-jump (after org-make-visible activate)
25117 "Make the position visible."
25118 (org-bookmark-jump-unhide))))
25120 ;; Make sure saveplace shows the location if it was hidden
25121 (eval-after-load "saveplace"
25122 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25123 "Make the position visible."
25124 (org-bookmark-jump-unhide)))
25126 ;; Make sure ecb shows the location if it was hidden
25127 (eval-after-load "ecb"
25128 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25129 "Make hierarchy visible when jumping into location from ECB tree buffer."
25130 (when (derived-mode-p 'org-mode)
25131 (org-show-context))))
25133 (defun org-bookmark-jump-unhide ()
25134 "Unhide the current position, to show the bookmark location."
25135 (and (derived-mode-p 'org-mode)
25136 (or (outline-invisible-p)
25137 (save-excursion (goto-char (max (point-min) (1- (point))))
25138 (outline-invisible-p)))
25139 (org-show-context 'bookmark-jump)))
25141 (defun org-mark-jump-unhide ()
25142 "Make the point visible with `org-show-context' after jumping to the mark."
25143 (when (and (derived-mode-p 'org-mode)
25144 (outline-invisible-p))
25145 (org-show-context 'mark-goto)))
25147 (eval-after-load "simple"
25148 '(defadvice pop-to-mark-command (after org-make-visible activate)
25149 "Make the point visible with `org-show-context'."
25150 (org-mark-jump-unhide)))
25152 (eval-after-load "simple"
25153 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25154 "Make the point visible with `org-show-context'."
25155 (org-mark-jump-unhide)))
25157 (eval-after-load "simple"
25158 '(defadvice pop-global-mark (after org-make-visible activate)
25159 "Make the point visible with `org-show-context'."
25160 (org-mark-jump-unhide)))
25162 ;; Make session.el ignore our circular variable
25163 (defvar session-globals-exclude)
25164 (eval-after-load "session"
25165 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25167 ;;;; Finish up
25169 (provide 'org)
25171 (run-hooks 'org-load-hook)
25173 ;;; org.el ends here