Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blob1cac276508705e5ac205be74ce00de285000ed9d
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2016 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda"
119 (&optional arg start-day span with-hour))
120 (declare-function org-agenda-redo "org-agenda" (&optional all))
121 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
122 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
123 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
124 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
127 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
128 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
129 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
130 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
131 (declare-function org-clock-update-time-maybe "org-clock" ())
132 (declare-function org-clocktable-shift "org-clock" (dir n))
133 (declare-function org-element-at-point "org-element" ())
134 (declare-function org-element-cache-refresh "org-element" (pos))
135 (declare-function org-element-cache-reset "org-element" (&optional all))
136 (declare-function org-element-contents "org-element" (element))
137 (declare-function org-element-context "org-element" (&optional element))
138 (declare-function org-element-copy "org-element" (datum))
139 (declare-function org-element-interpret-data "org-element" (data))
140 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
141 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
142 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
143 (declare-function org-element-property "org-element" (property element))
144 (declare-function org-element-put-property "org-element" (element property value))
145 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
146 (declare-function org-element-type "org-element" (element))
147 (declare-function org-element-update-syntax "org-element" ())
148 (declare-function org-id-find-id-file "org-id" (id))
149 (declare-function org-id-get-create "org-id" (&optional force))
150 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
151 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
152 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
153 (declare-function org-plot/gnuplot "org-plot" (&optional params))
154 (declare-function org-table-align "org-table" ())
155 (declare-function org-table-begin "org-table" (&optional table-type))
156 (declare-function org-table-beginning-of-field "org-table" (&optional n))
157 (declare-function org-table-blank-field "org-table" ())
158 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
159 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
160 (declare-function org-table-cut-region "org-table" (beg end))
161 (declare-function org-table-edit-field "org-table" (arg))
162 (declare-function org-table-end "org-table" (&optional table-type))
163 (declare-function org-table-end-of-field "org-table" (&optional n))
164 (declare-function org-table-insert-row "org-table" (&optional arg))
165 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
166 (declare-function org-table-maybe-eval-formula "org-table" ())
167 (declare-function org-table-maybe-recalculate-line "org-table" ())
168 (declare-function org-table-next-row "org-table" ())
169 (declare-function org-table-paste-rectangle "org-table" ())
170 (declare-function org-table-recalculate "org-table" (&optional all noalign))
171 (declare-function org-table-wrap-region "org-table" (arg))
172 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
173 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
174 (declare-function orgtbl-mode "org-table" (&optional arg))
176 (defsubst org-uniquify (list)
177 "Non-destructively remove duplicate elements from LIST."
178 (let ((res (copy-sequence list))) (delete-dups res)))
180 (defsubst org-get-at-bol (property)
181 "Get text property PROPERTY at the beginning of line."
182 (get-text-property (point-at-bol) property))
184 (defsubst org-trim (s &optional keep-lead)
185 "Remove whitespace at the beginning and the end of string S.
186 When optional argument KEEP-LEAD is non-nil, removing blank lines
187 at the beginning of the string does not affect leading indentation."
188 (replace-regexp-in-string
189 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
190 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
192 ;; load languages based on value of `org-babel-load-languages'
193 (defvar org-babel-load-languages)
195 ;;;###autoload
196 (defun org-babel-do-load-languages (sym value)
197 "Load the languages defined in `org-babel-load-languages'."
198 (set-default sym value)
199 (dolist (pair org-babel-load-languages)
200 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
201 (if active
202 (require (intern (concat "ob-" lang)))
203 (funcall 'fmakunbound
204 (intern (concat "org-babel-execute:" lang)))
205 (funcall 'fmakunbound
206 (intern (concat "org-babel-expand-body:" lang)))))))
208 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
209 ;;;###autoload
210 (defun org-babel-load-file (file &optional compile)
211 "Load Emacs Lisp source code blocks in the Org FILE.
212 This function exports the source code using `org-babel-tangle'
213 and then loads the resulting file using `load-file'. With prefix
214 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
215 file to byte-code before it is loaded."
216 (interactive "fFile to load: \nP")
217 (let* ((age (lambda (file)
218 (float-time
219 (time-subtract (current-time)
220 (nth 5 (or (file-attributes (file-truename file))
221 (file-attributes file)))))))
222 (base-name (file-name-sans-extension file))
223 (exported-file (concat base-name ".el")))
224 ;; tangle if the Org file is newer than the elisp file
225 (unless (and (file-exists-p exported-file)
226 (> (funcall age file) (funcall age exported-file)))
227 ;; Tangle-file traversal returns reversed list of tangled files
228 ;; and we want to evaluate the first target.
229 (setq exported-file
230 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
231 (message "%s %s"
232 (if compile
233 (progn (byte-compile-file exported-file 'load)
234 "Compiled and loaded")
235 (progn (load-file exported-file) "Loaded"))
236 exported-file)))
238 (defcustom org-babel-load-languages '((emacs-lisp . t))
239 "Languages which can be evaluated in Org buffers.
240 This list can be used to load support for any of the languages
241 below, note that each language will depend on a different set of
242 system executables and/or Emacs modes. When a language is
243 \"loaded\", then code blocks in that language can be evaluated
244 with `org-babel-execute-src-block' bound by default to C-c
245 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
246 be set to remove code block evaluation from the C-c C-c
247 keybinding. By default only Emacs Lisp (which has no
248 requirements) is loaded."
249 :group 'org-babel
250 :set 'org-babel-do-load-languages
251 :version "24.1"
252 :type '(alist :tag "Babel Languages"
253 :key-type
254 (choice
255 (const :tag "Awk" awk)
256 (const :tag "C" C)
257 (const :tag "R" R)
258 (const :tag "Asymptote" asymptote)
259 (const :tag "Calc" calc)
260 (const :tag "Clojure" clojure)
261 (const :tag "CSS" css)
262 (const :tag "Ditaa" ditaa)
263 (const :tag "Dot" dot)
264 (const :tag "Emacs Lisp" emacs-lisp)
265 (const :tag "Forth" forth)
266 (const :tag "Fortran" fortran)
267 (const :tag "Gnuplot" gnuplot)
268 (const :tag "Haskell" haskell)
269 (const :tag "IO" io)
270 (const :tag "J" J)
271 (const :tag "Java" java)
272 (const :tag "Javascript" js)
273 (const :tag "LaTeX" latex)
274 (const :tag "Ledger" ledger)
275 (const :tag "Lilypond" lilypond)
276 (const :tag "Lisp" lisp)
277 (const :tag "Makefile" makefile)
278 (const :tag "Maxima" maxima)
279 (const :tag "Matlab" matlab)
280 (const :tag "Mscgen" mscgen)
281 (const :tag "Ocaml" ocaml)
282 (const :tag "Octave" octave)
283 (const :tag "Org" org)
284 (const :tag "Perl" perl)
285 (const :tag "Pico Lisp" picolisp)
286 (const :tag "PlantUML" plantuml)
287 (const :tag "Python" python)
288 (const :tag "Ruby" ruby)
289 (const :tag "Sass" sass)
290 (const :tag "Scala" scala)
291 (const :tag "Scheme" scheme)
292 (const :tag "Screen" screen)
293 (const :tag "Shell Script" shell)
294 (const :tag "Shen" shen)
295 (const :tag "Sql" sql)
296 (const :tag "Sqlite" sqlite)
297 (const :tag "Stan" stan)
298 (const :tag "ebnf2ps" ebnf2ps))
299 :value-type (boolean :tag "Activate" :value t)))
301 ;;;; Customization variables
302 (defcustom org-clone-delete-id nil
303 "Remove ID property of clones of a subtree.
304 When non-nil, clones of a subtree don't inherit the ID property.
305 Otherwise they inherit the ID property with a new unique
306 identifier."
307 :type 'boolean
308 :version "24.1"
309 :group 'org-id)
311 ;;; Version
312 (org-check-version)
314 ;;;###autoload
315 (defun org-version (&optional here full message)
316 "Show the Org version.
317 Interactively, or when MESSAGE is non-nil, show it in echo area.
318 With prefix argument, or when HERE is non-nil, insert it at point.
319 In non-interactive uses, a reduced version string is output unless
320 FULL is given."
321 (interactive (list current-prefix-arg t (not current-prefix-arg)))
322 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
323 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
324 (load-suffixes (list ".el"))
325 (org-install-dir
326 (ignore-errors (org-find-library-dir "org-loaddefs"))))
327 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
328 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
329 (let* ((load-suffixes save-load-suffixes)
330 (release (org-release))
331 (git-version (org-git-version))
332 (version (format "Org mode version %s (%s @ %s)"
333 release
334 git-version
335 (if org-install-dir
336 (if (string= org-dir org-install-dir)
337 org-install-dir
338 (concat "mixed installation! "
339 org-install-dir
340 " and "
341 org-dir))
342 "org-loaddefs.el can not be found!")))
343 (version1 (if full version release)))
344 (when here (insert version1))
345 (when message (message "%s" version1))
346 version1)))
348 (defconst org-version (org-version))
351 ;;; Syntax Constants
353 ;;;; Block
355 (defconst org-block-regexp
356 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
357 "Regular expression for hiding blocks.")
359 (defconst org-dblock-start-re
360 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
361 "Matches the start line of a dynamic block, with parameters.")
363 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
364 "Matches the end of a dynamic block.")
366 ;;;; Clock and Planning
368 (defconst org-clock-string "CLOCK:"
369 "String used as prefix for timestamps clocking work hours on an item.")
371 (defvar org-closed-string "CLOSED:"
372 "String used as the prefix for timestamps logging closing a TODO entry.")
374 (defvar org-deadline-string "DEADLINE:"
375 "String to mark deadline entries.
376 \\<org-mode-map>
377 A deadline is this string, followed by a time stamp. It must be
378 a word, terminated by a colon. You can insert a schedule keyword
379 and a timestamp with `\\[org-deadline]'.")
381 (defvar org-scheduled-string "SCHEDULED:"
382 "String to mark scheduled TODO entries.
383 \\<org-mode-map>
384 A schedule is this string, followed by a time stamp. It must be
385 a word, terminated by a colon. You can insert a schedule keyword
386 and a timestamp with `\\[org-schedule]'.")
388 (defconst org-ds-keyword-length
389 (+ 2
390 (apply #'max
391 (mapcar #'length
392 (list org-deadline-string org-scheduled-string
393 org-clock-string org-closed-string))))
394 "Maximum length of the DEADLINE and SCHEDULED keywords.")
396 (defconst org-planning-line-re
397 (concat "^[ \t]*"
398 (regexp-opt
399 (list org-closed-string org-deadline-string org-scheduled-string)
401 "Matches a line with planning info.
402 Matched keyword is in group 1.")
404 (defconst org-clock-line-re
405 (concat "^[ \t]*" org-clock-string)
406 "Matches a line with clock info.")
408 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
409 "Matches the DEADLINE keyword.")
411 (defconst org-deadline-time-regexp
412 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
413 "Matches the DEADLINE keyword together with a time stamp.")
415 (defconst org-deadline-time-hour-regexp
416 (concat "\\<" org-deadline-string
417 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
418 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
420 (defconst org-deadline-line-regexp
421 (concat "\\<\\(" org-deadline-string "\\).*")
422 "Matches the DEADLINE keyword and the rest of the line.")
424 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
425 "Matches the SCHEDULED keyword.")
427 (defconst org-scheduled-time-regexp
428 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
429 "Matches the SCHEDULED keyword together with a time stamp.")
431 (defconst org-scheduled-time-hour-regexp
432 (concat "\\<" org-scheduled-string
433 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
434 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
436 (defconst org-closed-time-regexp
437 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
438 "Matches the CLOSED keyword together with a time stamp.")
440 (defconst org-keyword-time-regexp
441 (concat "\\<"
442 (regexp-opt
443 (list org-scheduled-string org-deadline-string org-closed-string
444 org-clock-string)
446 " *[[<]\\([^]>]+\\)[]>]")
447 "Matches any of the 4 keywords, together with the time stamp.")
449 (defconst org-keyword-time-not-clock-regexp
450 (concat
451 "\\<"
452 (regexp-opt
453 (list org-scheduled-string org-deadline-string org-closed-string) t)
454 " *[[<]\\([^]>]+\\)[]>]")
455 "Matches any of the 3 keywords, together with the time stamp.")
457 (defconst org-maybe-keyword-time-regexp
458 (concat "\\(\\<"
459 (regexp-opt
460 (list org-scheduled-string org-deadline-string org-closed-string
461 org-clock-string)
463 "\\)?"
464 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
465 "\\|"
466 "<%%([^\r\n>]*>\\)")
467 "Matches a timestamp, possibly preceded by a keyword.")
469 (defconst org-all-time-keywords
470 (mapcar (lambda (w) (substring w 0 -1))
471 (list org-scheduled-string org-deadline-string
472 org-clock-string org-closed-string))
473 "List of time keywords.")
475 ;;;; Drawer
477 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
478 "Matches first or last line of a hidden block.
479 Group 1 contains drawer's name or \"END\".")
481 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
482 "Regular expression matching the first line of a property drawer.")
484 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
485 "Regular expression matching the last line of a property drawer.")
487 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
488 "Regular expression matching the first line of a clock drawer.")
490 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
491 "Regular expression matching the last line of a clock drawer.")
493 (defconst org-property-drawer-re
494 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
495 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
496 "[ \t]*:END:[ \t]*$")
497 "Matches an entire property drawer.")
499 (defconst org-clock-drawer-re
500 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
501 org-clock-drawer-end-re "\\)\n?")
502 "Matches an entire clock drawer.")
504 ;;;; Headline
506 (defconst org-heading-keyword-regexp-format
507 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
508 "Printf format for a regexp matching a headline with some keyword.
509 This regexp will match the headline of any node which has the
510 exact keyword that is put into the format. The keyword isn't in
511 any group by default, but the stars and the body are.")
513 (defconst org-heading-keyword-maybe-regexp-format
514 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
515 "Printf format for a regexp matching a headline, possibly with some keyword.
516 This regexp can match any headline with the specified keyword, or
517 without a keyword. The keyword isn't in any group by default,
518 but the stars and the body are.")
520 (defconst org-archive-tag "ARCHIVE"
521 "The tag that marks a subtree as archived.
522 An archived subtree does not open during visibility cycling, and does
523 not contribute to the agenda listings.")
525 (defconst org-comment-string "COMMENT"
526 "Entries starting with this keyword will never be exported.
527 \\<org-mode-map>
528 An entry can be toggled between COMMENT and normal with
529 `\\[org-toggle-comment]'.")
532 ;;;; LaTeX Environments and Fragments
534 (defconst org-latex-regexps
535 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
536 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
537 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
538 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
539 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
540 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
541 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
542 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
543 "Regular expressions for matching embedded LaTeX.")
545 ;;;; Node Property
547 (defconst org-effort-property "Effort"
548 "The property that is being used to keep track of effort estimates.
549 Effort estimates given in this property need to have the format H:MM.")
551 ;;;; Table
553 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
554 "Detect an org-type or table-type table.")
556 (defconst org-table-line-regexp "^[ \t]*|"
557 "Detect an org-type table line.")
559 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
560 "Detect an org-type table line.")
562 (defconst org-table-hline-regexp "^[ \t]*|-"
563 "Detect an org-type table hline.")
565 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
566 "Detect a table-type table hline.")
568 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
569 "Detect the first line outside a table when searching from within it.
570 This works for both table types.")
572 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
573 "Detect a #+TBLFM line.")
575 ;;;; Timestamp
577 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
578 "Regular expression for fast time stamp matching.")
580 (defconst org-ts-regexp-inactive
581 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
582 "Regular expression for fast inactive time stamp matching.")
584 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
585 "Regular expression for fast time stamp matching.")
587 (defconst org-ts-regexp0
588 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
589 "Regular expression matching time strings for analysis.
590 This one does not require the space after the date, so it can be used
591 on a string that terminates immediately after the date.")
593 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
594 "Regular expression matching time strings for analysis.")
596 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
597 "Regular expression matching time stamps, with groups.")
599 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
600 "Regular expression matching time stamps (also [..]), with groups.")
602 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
603 "Regular expression matching a time stamp range.")
605 (defconst org-tr-regexp-both
606 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
607 "Regular expression matching a time stamp range.")
609 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
610 org-ts-regexp "\\)?")
611 "Regular expression matching a time stamp or time stamp range.")
613 (defconst org-tsr-regexp-both
614 (concat org-ts-regexp-both "\\(--?-?"
615 org-ts-regexp-both "\\)?")
616 "Regular expression matching a time stamp or time stamp range.
617 The time stamps may be either active or inactive.")
619 (defconst org-repeat-re
620 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
621 "Regular expression for specifying repeated events.
622 After a match, group 1 contains the repeat expression.")
624 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
625 "Formats for `format-time-string' which are used for time stamps.")
628 ;;; The custom variables
630 (defgroup org nil
631 "Outline-based notes management and organizer."
632 :tag "Org"
633 :group 'outlines
634 :group 'calendar)
636 (defcustom org-mode-hook nil
637 "Mode hook for Org mode, run after the mode was turned on."
638 :group 'org
639 :type 'hook)
641 (defcustom org-load-hook nil
642 "Hook that is run after org.el has been loaded."
643 :group 'org
644 :type 'hook)
646 (defcustom org-log-buffer-setup-hook nil
647 "Hook that is run after an Org log buffer is created."
648 :group 'org
649 :version "24.1"
650 :type 'hook)
652 (defvar org-modules) ; defined below
653 (defvar org-modules-loaded nil
654 "Have the modules been loaded already?")
656 (defun org-load-modules-maybe (&optional force)
657 "Load all extensions listed in `org-modules'."
658 (when (or force (not org-modules-loaded))
659 (dolist (ext org-modules)
660 (condition-case nil (require ext)
661 (error (message "Problems while trying to load feature `%s'" ext))))
662 (setq org-modules-loaded t)))
664 (defun org-set-modules (var value)
665 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
666 (set var value)
667 (when (featurep 'org)
668 (org-load-modules-maybe 'force)
669 (org-element-cache-reset 'all)))
671 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
672 "Modules that should always be loaded together with org.el.
674 If a description starts with <C>, the file is not part of Emacs
675 and loading it will require that you have downloaded and properly
676 installed the Org mode distribution.
678 You can also use this system to load external packages (i.e. neither Org
679 core modules, nor modules from the CONTRIB directory). Just add symbols
680 to the end of the list. If the package is called org-xyz.el, then you need
681 to add the symbol `xyz', and the package must have a call to:
683 (provide \\='org-xyz)
685 For export specific modules, see also `org-export-backends'."
686 :group 'org
687 :set 'org-set-modules
688 :version "24.4"
689 :package-version '(Org . "8.0")
690 :type
691 '(set :greedy t
692 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
693 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
694 (const :tag " crypt: Encryption of subtrees" org-crypt)
695 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
696 (const :tag " docview: Links to doc-view buffers" org-docview)
697 (const :tag " eww: Store link to url of eww" org-eww)
698 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
699 (const :tag " habit: Track your consistency with habits" org-habit)
700 (const :tag " id: Global IDs for identifying entries" org-id)
701 (const :tag " info: Links to Info nodes" org-info)
702 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
703 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
704 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
705 (const :tag " mouse: Additional mouse support" org-mouse)
706 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
707 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
708 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
710 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
711 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
712 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
713 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
714 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
715 (const :tag "C collector: Collect properties into tables" org-collector)
716 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
717 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
718 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
719 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
720 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
721 (const :tag "C eval: Include command output as text" org-eval)
722 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
723 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
724 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
725 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
726 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
727 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
728 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
729 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
730 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
731 (const :tag "C man: Support for links to manpages in Org mode" org-man)
732 (const :tag "C mew: Links to Mew folders/messages" org-mew)
733 (const :tag "C mtags: Support for muse-like tags" org-mtags)
734 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
735 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
736 (const :tag "C registry: A registry for Org links" org-registry)
737 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
738 (const :tag "C secretary: Team management with org-mode" org-secretary)
739 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
740 (const :tag "C toc: Table of contents for Org buffer" org-toc)
741 (const :tag "C track: Keep up with Org mode development" org-track)
742 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
743 (const :tag "C vm: Links to VM folders/messages" org-vm)
744 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
745 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
746 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
748 (defvar org-export-registered-backends) ; From ox.el.
749 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
750 (declare-function org-export-backend-name "ox" (backend) t)
751 (defcustom org-export-backends '(ascii html icalendar latex odt)
752 "List of export back-ends that should be always available.
754 If a description starts with <C>, the file is not part of Emacs
755 and loading it will require that you have downloaded and properly
756 installed the Org mode distribution.
758 Unlike to `org-modules', libraries in this list will not be
759 loaded along with Org, but only once the export framework is
760 needed.
762 This variable needs to be set before org.el is loaded. If you
763 need to make a change while Emacs is running, use the customize
764 interface or run the following code, where VAL stands for the new
765 value of the variable, after updating it:
767 (progn
768 (setq org-export-registered-backends
769 (cl-remove-if-not
770 (lambda (backend)
771 (let ((name (org-export-backend-name backend)))
772 (or (memq name val)
773 (catch \\='parentp
774 (dolist (b val)
775 (and (org-export-derived-backend-p b name)
776 (throw \\='parentp t)))))))
777 org-export-registered-backends))
778 (let ((new-list (mapcar #\\='org-export-backend-name
779 org-export-registered-backends)))
780 (dolist (backend val)
781 (cond
782 ((not (load (format \"ox-%s\" backend) t t))
783 (message \"Problems while trying to load export back-end \\=`%s\\='\"
784 backend))
785 ((not (memq backend new-list)) (push backend new-list))))
786 (set-default \\='org-export-backends new-list)))
788 Adding a back-end to this list will also pull the back-end it
789 depends on, if any."
790 :group 'org
791 :group 'org-export
792 :version "25.2"
793 :package-version '(Org . "9.0")
794 :initialize 'custom-initialize-set
795 :set (lambda (var val)
796 (if (not (featurep 'ox)) (set-default var val)
797 ;; Any back-end not required anymore (not present in VAL and not
798 ;; a parent of any back-end in the new value) is removed from the
799 ;; list of registered back-ends.
800 (setq org-export-registered-backends
801 (cl-remove-if-not
802 (lambda (backend)
803 (let ((name (org-export-backend-name backend)))
804 (or (memq name val)
805 (catch 'parentp
806 (dolist (b val)
807 (and (org-export-derived-backend-p b name)
808 (throw 'parentp t)))))))
809 org-export-registered-backends))
810 ;; Now build NEW-LIST of both new back-ends and required
811 ;; parents.
812 (let ((new-list (mapcar #'org-export-backend-name
813 org-export-registered-backends)))
814 (dolist (backend val)
815 (cond
816 ((not (load (format "ox-%s" backend) t t))
817 (message "Problems while trying to load export back-end `%s'"
818 backend))
819 ((not (memq backend new-list)) (push backend new-list))))
820 ;; Set VAR to that list with fixed dependencies.
821 (set-default var new-list))))
822 :type '(set :greedy t
823 (const :tag " ascii Export buffer to ASCII format" ascii)
824 (const :tag " beamer Export buffer to Beamer presentation" beamer)
825 (const :tag " html Export buffer to HTML format" html)
826 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
827 (const :tag " latex Export buffer to LaTeX format" latex)
828 (const :tag " man Export buffer to MAN format" man)
829 (const :tag " md Export buffer to Markdown format" md)
830 (const :tag " odt Export buffer to ODT format" odt)
831 (const :tag " org Export buffer to Org format" org)
832 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
833 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
834 (const :tag "C deck Export buffer to deck.js presentations" deck)
835 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
836 (const :tag "C groff Export buffer to Groff format" groff)
837 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
838 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
839 (const :tag "C s5 Export buffer to s5 presentations" s5)
840 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
842 (eval-after-load 'ox
843 '(dolist (backend org-export-backends)
844 (condition-case nil (require (intern (format "ox-%s" backend)))
845 (error (message "Problems while trying to load export back-end `%s'"
846 backend)))))
848 (defcustom org-support-shift-select nil
849 "Non-nil means make shift-cursor commands select text when possible.
850 \\<org-mode-map>\
852 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
853 start selecting a region, or enlarge regions started in this way.
854 In Org mode, in special contexts, these same keys are used for
855 other purposes, important enough to compete with shift selection.
856 Org tries to balance these needs by supporting `shift-select-mode'
857 outside these special contexts, under control of this variable.
859 The default of this variable is nil, to avoid confusing behavior. Shifted
860 cursor keys will then execute Org commands in the following contexts:
861 - on a headline, changing TODO state (left/right) and priority (up/down)
862 - on a time stamp, changing the time
863 - in a plain list item, changing the bullet type
864 - in a property definition line, switching between allowed values
865 - in the BEGIN line of a clock table (changing the time block).
866 Outside these contexts, the commands will throw an error.
868 When this variable is t and the cursor is not in a special
869 context, Org mode will support shift-selection for making and
870 enlarging regions. To make this more effective, the bullet
871 cycling will no longer happen anywhere in an item line, but only
872 if the cursor is exactly on the bullet.
874 If you set this variable to the symbol `always', then the keys
875 will not be special in headlines, property lines, and item lines,
876 to make shift selection work there as well. If this is what you
877 want, you can use the following alternative commands:
878 `\\[org-todo]' and `\\[org-priority]' \
879 to change TODO state and priority,
880 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
881 can be used to switch TODO sets,
882 `\\[org-ctrl-c-minus]' to cycle item bullet types,
883 and properties can be edited by hand or in column view.
885 However, when the cursor is on a timestamp, shift-cursor commands
886 will still edit the time stamp - this is just too good to give up."
887 :group 'org
888 :type '(choice
889 (const :tag "Never" nil)
890 (const :tag "When outside special context" t)
891 (const :tag "Everywhere except timestamps" always)))
893 (defcustom org-loop-over-headlines-in-active-region nil
894 "Shall some commands act upon headlines in the active region?
896 When set to t, some commands will be performed in all headlines
897 within the active region.
899 When set to `start-level', some commands will be performed in all
900 headlines within the active region, provided that these headlines
901 are of the same level than the first one.
903 When set to a string, those commands will be performed on the
904 matching headlines within the active region. Such string must be
905 a tags/property/todo match as it is used in the agenda tags view.
907 The list of commands is: `org-schedule', `org-deadline',
908 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
909 `org-archive-to-archive-sibling'. The archiving commands skip
910 already archived entries."
911 :type '(choice (const :tag "Don't loop" nil)
912 (const :tag "All headlines in active region" t)
913 (const :tag "In active region, headlines at the same level than the first one" start-level)
914 (string :tag "Tags/Property/Todo matcher"))
915 :version "24.1"
916 :group 'org-todo
917 :group 'org-archive)
919 (defgroup org-startup nil
920 "Options concerning startup of Org mode."
921 :tag "Org Startup"
922 :group 'org)
924 (defcustom org-startup-folded t
925 "Non-nil means entering Org mode will switch to OVERVIEW.
927 This can also be configured on a per-file basis by adding one of
928 the following lines anywhere in the buffer:
930 #+STARTUP: fold (or `overview', this is equivalent)
931 #+STARTUP: nofold (or `showall', this is equivalent)
932 #+STARTUP: content
933 #+STARTUP: showeverything
935 Set `org-agenda-inhibit-startup' to a non-nil value if you want
936 to ignore this option when Org opens agenda files for the first
937 time."
938 :group 'org-startup
939 :type '(choice
940 (const :tag "nofold: show all" nil)
941 (const :tag "fold: overview" t)
942 (const :tag "content: all headlines" content)
943 (const :tag "show everything, even drawers" showeverything)))
945 (defcustom org-startup-truncated t
946 "Non-nil means entering Org mode will set `truncate-lines'.
947 This is useful since some lines containing links can be very long and
948 uninteresting. Also tables look terrible when wrapped.
950 The variable `org-startup-truncated' allows to configure
951 truncation for Org mode different to the other modes that use the
952 variable `truncate-lines' and as a shortcut instead of putting
953 the variable `truncate-lines' into the `org-mode-hook'. If one
954 wants to configure truncation for Org mode not statically but
955 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
956 the variable `truncate-lines' has to be used because in such a
957 case it is too late to set the variable `org-startup-truncated'."
958 :group 'org-startup
959 :type 'boolean)
961 (defcustom org-startup-indented nil
962 "Non-nil means turn on `org-indent-mode' on startup.
963 This can also be configured on a per-file basis by adding one of
964 the following lines anywhere in the buffer:
966 #+STARTUP: indent
967 #+STARTUP: noindent"
968 :group 'org-structure
969 :type '(choice
970 (const :tag "Not" nil)
971 (const :tag "Globally (slow on startup in large files)" t)))
973 (defcustom org-use-sub-superscripts t
974 "Non-nil means interpret \"_\" and \"^\" for display.
976 If you want to control how Org exports those characters, see
977 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
978 used to be an alias for `org-export-with-sub-superscripts' in
979 Org <8.0, it is not anymore.
981 When this option is turned on, you can use TeX-like syntax for
982 sub- and superscripts within the buffer. Several characters after
983 \"_\" or \"^\" will be considered as a single item - so grouping
984 with {} is normally not needed. For example, the following things
985 will be parsed as single sub- or superscripts:
987 10^24 or 10^tau several digits will be considered 1 item.
988 10^-12 or 10^-tau a leading sign with digits or a word
989 x^2-y^3 will be read as x^2 - y^3, because items are
990 terminated by almost any nonword/nondigit char.
991 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
993 Still, ambiguity is possible. So when in doubt, use {} to enclose
994 the sub/superscript. If you set this variable to the symbol `{}',
995 the braces are *required* in order to trigger interpretations as
996 sub/superscript. This can be helpful in documents that need \"_\"
997 frequently in plain text."
998 :group 'org-startup
999 :version "24.4"
1000 :package-version '(Org . "8.0")
1001 :type '(choice
1002 (const :tag "Always interpret" t)
1003 (const :tag "Only with braces" {})
1004 (const :tag "Never interpret" nil)))
1006 (defcustom org-startup-with-beamer-mode nil
1007 "Non-nil means turn on `org-beamer-mode' on startup.
1008 This can also be configured on a per-file basis by adding one of
1009 the following lines anywhere in the buffer:
1011 #+STARTUP: beamer"
1012 :group 'org-startup
1013 :version "24.1"
1014 :type 'boolean)
1016 (defcustom org-startup-align-all-tables nil
1017 "Non-nil means align all tables when visiting a file.
1018 This is useful when the column width in tables is forced with <N> cookies
1019 in table fields. Such tables will look correct only after the first re-align.
1020 This can also be configured on a per-file basis by adding one of
1021 the following lines anywhere in the buffer:
1022 #+STARTUP: align
1023 #+STARTUP: noalign"
1024 :group 'org-startup
1025 :type 'boolean)
1027 (defcustom org-startup-with-inline-images nil
1028 "Non-nil means show inline images when loading a new Org file.
1029 This can also be configured on a per-file basis by adding one of
1030 the following lines anywhere in the buffer:
1031 #+STARTUP: inlineimages
1032 #+STARTUP: noinlineimages"
1033 :group 'org-startup
1034 :version "24.1"
1035 :type 'boolean)
1037 (defcustom org-startup-with-latex-preview nil
1038 "Non-nil means preview LaTeX fragments when loading a new Org file.
1040 This can also be configured on a per-file basis by adding one of
1041 the following lines anywhere in the buffer:
1042 #+STARTUP: latexpreview
1043 #+STARTUP: nolatexpreview"
1044 :group 'org-startup
1045 :version "24.4"
1046 :package-version '(Org . "8.0")
1047 :type 'boolean)
1049 (defcustom org-insert-mode-line-in-empty-file nil
1050 "Non-nil means insert the first line setting Org mode in empty files.
1051 When the function `org-mode' is called interactively in an empty file, this
1052 normally means that the file name does not automatically trigger Org mode.
1053 To ensure that the file will always be in Org mode in the future, a
1054 line enforcing Org mode will be inserted into the buffer, if this option
1055 has been set."
1056 :group 'org-startup
1057 :type 'boolean)
1059 (defcustom org-replace-disputed-keys nil
1060 "Non-nil means use alternative key bindings for some keys.
1061 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1062 These keys are also used by other packages like shift-selection-mode'
1063 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1064 If you want to use Org mode together with one of these other modes,
1065 or more generally if you would like to move some Org mode commands to
1066 other keys, set this variable and configure the keys with the variable
1067 `org-disputed-keys'.
1069 This option is only relevant at load-time of Org mode, and must be set
1070 *before* org.el is loaded. Changing it requires a restart of Emacs to
1071 become effective."
1072 :group 'org-startup
1073 :type 'boolean)
1075 (defcustom org-use-extra-keys nil
1076 "Non-nil means use extra key sequence definitions for certain commands.
1077 This happens automatically if `window-system' is nil. This
1078 variable lets you do the same manually. You must set it before
1079 loading Org."
1080 :group 'org-startup
1081 :type 'boolean)
1083 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1085 (defcustom org-disputed-keys
1086 '(([(shift up)] . [(meta p)])
1087 ([(shift down)] . [(meta n)])
1088 ([(shift left)] . [(meta -)])
1089 ([(shift right)] . [(meta +)])
1090 ([(control shift right)] . [(meta shift +)])
1091 ([(control shift left)] . [(meta shift -)]))
1092 "Keys for which Org mode and other modes compete.
1093 This is an alist, cars are the default keys, second element specifies
1094 the alternative to use when `org-replace-disputed-keys' is t.
1096 Keys can be specified in any syntax supported by `define-key'.
1097 The value of this option takes effect only at Org mode startup,
1098 therefore you'll have to restart Emacs to apply it after changing."
1099 :group 'org-startup
1100 :type 'alist)
1102 (defun org-key (key)
1103 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1104 Or return the original if not disputed."
1105 (when org-replace-disputed-keys
1106 (let* ((nkey (key-description key))
1107 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1108 org-disputed-keys)))
1109 (setq key (if x (cdr x) key))))
1110 key)
1112 (defun org-defkey (keymap key def)
1113 "Define a key, possibly translated, as returned by `org-key'."
1114 (define-key keymap (org-key key) def))
1116 (defcustom org-ellipsis nil
1117 "The ellipsis to use in the Org mode outline.
1119 When nil, just use the standard three dots.
1120 When a string, use that string instead.
1122 The change affects only Org mode (which will then use its own display table).
1123 Changing this requires executing `\\[org-mode]' in a buffer to become
1124 effective."
1125 :group 'org-startup
1126 :type '(choice (const :tag "Default" nil)
1127 (string :tag "String" :value "...#"))
1128 :safe #'string-or-null-p)
1130 (defvar org-display-table nil
1131 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1133 (defgroup org-keywords nil
1134 "Keywords in Org mode."
1135 :tag "Org Keywords"
1136 :group 'org)
1138 (defcustom org-closed-keep-when-no-todo nil
1139 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1140 :group 'org-todo
1141 :group 'org-keywords
1142 :version "24.4"
1143 :package-version '(Org . "8.0")
1144 :type 'boolean)
1146 (defgroup org-structure nil
1147 "Options concerning the general structure of Org files."
1148 :tag "Org Structure"
1149 :group 'org)
1151 (defgroup org-reveal-location nil
1152 "Options about how to make context of a location visible."
1153 :tag "Org Reveal Location"
1154 :group 'org-structure)
1156 (defcustom org-show-context-detail '((agenda . local)
1157 (bookmark-jump . lineage)
1158 (isearch . lineage)
1159 (default . ancestors))
1160 "Alist between context and visibility span when revealing a location.
1162 \\<org-mode-map>Some actions may move point into invisible
1163 locations. As a consequence, Org always expose a neighborhood
1164 around point. How much is shown depends on the initial action,
1165 or context. Valid contexts are
1167 agenda when exposing an entry from the agenda
1168 org-goto when using the command `org-goto' (`\\[org-goto]')
1169 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1170 tags-tree when constructing a sparse tree based on tags matches
1171 link-search when exposing search matches associated with a link
1172 mark-goto when exposing the jump goal of a mark
1173 bookmark-jump when exposing a bookmark location
1174 isearch when exiting from an incremental search
1175 default default for all contexts not set explicitly
1177 Allowed visibility spans are
1179 minimal show current headline; if point is not on headline,
1180 also show entry
1182 local show current headline, entry and next headline
1184 ancestors show current headline and its direct ancestors; if
1185 point is not on headline, also show entry
1187 lineage show current headline, its direct ancestors and all
1188 their children; if point is not on headline, also show
1189 entry and first child
1191 tree show current headline, its direct ancestors and all
1192 their children; if point is not on headline, also show
1193 entry and all children
1195 canonical show current headline, its direct ancestors along with
1196 their entries and children; if point is not located on
1197 the headline, also show current entry and all children
1199 As special cases, a nil or t value means show all contexts in
1200 `minimal' or `canonical' view, respectively.
1202 Some views can make displayed information very compact, but also
1203 make it harder to edit the location of the match. In such
1204 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1205 more context."
1206 :group 'org-reveal-location
1207 :version "25.2"
1208 :package-version '(Org . "9.0")
1209 :type '(choice
1210 (const :tag "Canonical" t)
1211 (const :tag "Minimal" nil)
1212 (repeat :greedy t :tag "Individual contexts"
1213 (cons
1214 (choice :tag "Context"
1215 (const agenda)
1216 (const org-goto)
1217 (const occur-tree)
1218 (const tags-tree)
1219 (const link-search)
1220 (const mark-goto)
1221 (const bookmark-jump)
1222 (const isearch)
1223 (const default))
1224 (choice :tag "Detail level"
1225 (const minimal)
1226 (const local)
1227 (const ancestors)
1228 (const lineage)
1229 (const tree)
1230 (const canonical))))))
1232 (defcustom org-indirect-buffer-display 'other-window
1233 "How should indirect tree buffers be displayed?
1235 This applies to indirect buffers created with the commands
1236 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1238 Valid values are:
1239 current-window Display in the current window
1240 other-window Just display in another window.
1241 dedicated-frame Create one new frame, and re-use it each time.
1242 new-frame Make a new frame each time. Note that in this case
1243 previously-made indirect buffers are kept, and you need to
1244 kill these buffers yourself."
1245 :group 'org-structure
1246 :group 'org-agenda-windows
1247 :type '(choice
1248 (const :tag "In current window" current-window)
1249 (const :tag "In current frame, other window" other-window)
1250 (const :tag "Each time a new frame" new-frame)
1251 (const :tag "One dedicated frame" dedicated-frame)))
1253 (defcustom org-use-speed-commands nil
1254 "Non-nil means activate single letter commands at beginning of a headline.
1255 This may also be a function to test for appropriate locations where speed
1256 commands should be active.
1258 For example, to activate speed commands when the point is on any
1259 star at the beginning of the headline, you can do this:
1261 (setq org-use-speed-commands
1262 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1263 :group 'org-structure
1264 :type '(choice
1265 (const :tag "Never" nil)
1266 (const :tag "At beginning of headline stars" t)
1267 (function)))
1269 (defcustom org-speed-commands-user nil
1270 "Alist of additional speed commands.
1271 This list will be checked before `org-speed-commands-default'
1272 when the variable `org-use-speed-commands' is non-nil
1273 and when the cursor is at the beginning of a headline.
1274 The car if each entry is a string with a single letter, which must
1275 be assigned to `self-insert-command' in the global map.
1276 The cdr is either a command to be called interactively, a function
1277 to be called, or a form to be evaluated.
1278 An entry that is just a list with a single string will be interpreted
1279 as a descriptive headline that will be added when listing the speed
1280 commands in the Help buffer using the `?' speed command."
1281 :group 'org-structure
1282 :type '(repeat :value ("k" . ignore)
1283 (choice :value ("k" . ignore)
1284 (list :tag "Descriptive Headline" (string :tag "Headline"))
1285 (cons :tag "Letter and Command"
1286 (string :tag "Command letter")
1287 (choice
1288 (function)
1289 (sexp))))))
1291 (defcustom org-bookmark-names-plist
1292 '(:last-capture "org-capture-last-stored"
1293 :last-refile "org-refile-last-stored"
1294 :last-capture-marker "org-capture-last-stored-marker")
1295 "Names for bookmarks automatically set by some Org commands.
1296 This can provide strings as names for a number of bookmarks Org sets
1297 automatically. The following keys are currently implemented:
1298 :last-capture
1299 :last-capture-marker
1300 :last-refile
1301 When a key does not show up in the property list, the corresponding bookmark
1302 is not set."
1303 :group 'org-structure
1304 :type 'plist)
1306 (defgroup org-cycle nil
1307 "Options concerning visibility cycling in Org mode."
1308 :tag "Org Cycle"
1309 :group 'org-structure)
1311 (defcustom org-cycle-skip-children-state-if-no-children t
1312 "Non-nil means skip CHILDREN state in entries that don't have any."
1313 :group 'org-cycle
1314 :type 'boolean)
1316 (defcustom org-cycle-max-level nil
1317 "Maximum level which should still be subject to visibility cycling.
1318 Levels higher than this will, for cycling, be treated as text, not a headline.
1319 When `org-odd-levels-only' is set, a value of N in this variable actually
1320 means 2N-1 stars as the limiting headline.
1321 When nil, cycle all levels.
1322 Note that the limiting level of cycling is also influenced by
1323 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1324 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1325 than its value."
1326 :group 'org-cycle
1327 :type '(choice
1328 (const :tag "No limit" nil)
1329 (integer :tag "Maximum level")))
1331 (defcustom org-hide-block-startup nil
1332 "Non-nil means entering Org mode will fold all blocks.
1333 This can also be set in on a per-file basis with
1335 #+STARTUP: hideblocks
1336 #+STARTUP: showblocks"
1337 :group 'org-startup
1338 :group 'org-cycle
1339 :type 'boolean)
1341 (defcustom org-cycle-global-at-bob nil
1342 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1344 This makes it possible to do global cycling without having to use `S-TAB'
1345 or `\\[universal-argument] TAB'. For this special case to work, the first \
1346 line of the buffer
1347 must not be a headline -- it may be empty or some other text.
1349 When used in this way, `org-cycle-hook' is disabled temporarily to make
1350 sure the cursor stays at the beginning of the buffer.
1352 When this option is nil, don't do anything special at the beginning of
1353 the buffer."
1354 :group 'org-cycle
1355 :type 'boolean)
1357 (defcustom org-cycle-level-after-item/entry-creation t
1358 "Non-nil means cycle entry level or item indentation in new empty entries.
1360 When the cursor is at the end of an empty headline, i.e., with only stars
1361 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1362 and then all possible ancestor states, before returning to the original state.
1363 This makes data entry extremely fast: M-RET to create a new headline,
1364 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1366 When the cursor is at the end of an empty plain list item, one TAB will
1367 make it a subitem, two or more tabs will back up to make this an item
1368 higher up in the item hierarchy."
1369 :group 'org-cycle
1370 :type 'boolean)
1372 (defcustom org-cycle-emulate-tab t
1373 "Where should `org-cycle' emulate TAB.
1374 nil Never
1375 white Only in completely white lines
1376 whitestart Only at the beginning of lines, before the first non-white char
1377 t Everywhere except in headlines
1378 exc-hl-bol Everywhere except at the start of a headline
1379 If TAB is used in a place where it does not emulate TAB, the current subtree
1380 visibility is cycled."
1381 :group 'org-cycle
1382 :type '(choice (const :tag "Never" nil)
1383 (const :tag "Only in completely white lines" white)
1384 (const :tag "Before first char in a line" whitestart)
1385 (const :tag "Everywhere except in headlines" t)
1386 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1388 (defcustom org-cycle-separator-lines 2
1389 "Number of empty lines needed to keep an empty line between collapsed trees.
1390 If you leave an empty line between the end of a subtree and the following
1391 headline, this empty line is hidden when the subtree is folded.
1392 Org mode will leave (exactly) one empty line visible if the number of
1393 empty lines is equal or larger to the number given in this variable.
1394 So the default 2 means at least 2 empty lines after the end of a subtree
1395 are needed to produce free space between a collapsed subtree and the
1396 following headline.
1398 If the number is negative, and the number of empty lines is at least -N,
1399 all empty lines are shown.
1401 Special case: when 0, never leave empty lines in collapsed view."
1402 :group 'org-cycle
1403 :type 'integer)
1404 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1406 (defcustom org-pre-cycle-hook nil
1407 "Hook that is run before visibility cycling is happening.
1408 The function(s) in this hook must accept a single argument which indicates
1409 the new state that will be set right after running this hook. The
1410 argument is a symbol. Before a global state change, it can have the values
1411 `overview', `content', or `all'. Before a local state change, it can have
1412 the values `folded', `children', or `subtree'."
1413 :group 'org-cycle
1414 :type 'hook)
1416 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1417 org-cycle-hide-drawers
1418 org-cycle-show-empty-lines
1419 org-optimize-window-after-visibility-change)
1420 "Hook that is run after `org-cycle' has changed the buffer visibility.
1421 The function(s) in this hook must accept a single argument which indicates
1422 the new state that was set by the most recent `org-cycle' command. The
1423 argument is a symbol. After a global state change, it can have the values
1424 `overview', `contents', or `all'. After a local state change, it can have
1425 the values `folded', `children', or `subtree'."
1426 :group 'org-cycle
1427 :type 'hook
1428 :version "25.2"
1429 :package-version '(Org . "8.3"))
1431 (defgroup org-edit-structure nil
1432 "Options concerning structure editing in Org mode."
1433 :tag "Org Edit Structure"
1434 :group 'org-structure)
1436 (defcustom org-odd-levels-only nil
1437 "Non-nil means skip even levels and only use odd levels for the outline.
1438 This has the effect that two stars are being added/taken away in
1439 promotion/demotion commands. It also influences how levels are
1440 handled by the exporters.
1441 Changing it requires restart of `font-lock-mode' to become effective
1442 for fontification also in regions already fontified.
1443 You may also set this on a per-file basis by adding one of the following
1444 lines to the buffer:
1446 #+STARTUP: odd
1447 #+STARTUP: oddeven"
1448 :group 'org-edit-structure
1449 :group 'org-appearance
1450 :type 'boolean)
1452 (defcustom org-adapt-indentation t
1453 "Non-nil means adapt indentation to outline node level.
1455 When this variable is set, Org assumes that you write outlines by
1456 indenting text in each node to align with the headline (after the
1457 stars). The following issues are influenced by this variable:
1459 - The indentation is increased by one space in a demotion
1460 command, and decreased by one in a promotion command. However,
1461 in the latter case, if shifting some line in the entry body
1462 would alter document structure (e.g., insert a new headline),
1463 indentation is not changed at all.
1465 - Property drawers and planning information is inserted indented
1466 when this variable is set. When nil, they will not be indented.
1468 - TAB indents a line relative to current level. The lines below
1469 a headline will be indented when this variable is set.
1471 Note that this is all about true indentation, by adding and
1472 removing space characters. See also `org-indent.el' which does
1473 level-dependent indentation in a virtual way, i.e. at display
1474 time in Emacs."
1475 :group 'org-edit-structure
1476 :type 'boolean)
1478 (defcustom org-special-ctrl-a/e nil
1479 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1481 When t, `C-a' will bring back the cursor to the beginning of the
1482 headline text, i.e. after the stars and after a possible TODO
1483 keyword. In an item, this will be the position after bullet and
1484 check-box, if any. When the cursor is already at that position,
1485 another `C-a' will bring it to the beginning of the line.
1487 `C-e' will jump to the end of the headline, ignoring the presence
1488 of tags in the headline. A second `C-e' will then jump to the
1489 true end of the line, after any tags. This also means that, when
1490 this variable is non-nil, `C-e' also will never jump beyond the
1491 end of the heading of a folded section, i.e. not after the
1492 ellipses.
1494 When set to the symbol `reversed', the first `C-a' or `C-e' works
1495 normally, going to the true line boundary first. Only a directly
1496 following, identical keypress will bring the cursor to the
1497 special positions.
1499 This may also be a cons cell where the behavior for `C-a' and
1500 `C-e' is set separately."
1501 :group 'org-edit-structure
1502 :type '(choice
1503 (const :tag "off" nil)
1504 (const :tag "on: after stars/bullet and before tags first" t)
1505 (const :tag "reversed: true line boundary first" reversed)
1506 (cons :tag "Set C-a and C-e separately"
1507 (choice :tag "Special C-a"
1508 (const :tag "off" nil)
1509 (const :tag "on: after stars/bullet first" t)
1510 (const :tag "reversed: before stars/bullet first" reversed))
1511 (choice :tag "Special C-e"
1512 (const :tag "off" nil)
1513 (const :tag "on: before tags first" t)
1514 (const :tag "reversed: after tags first" reversed)))))
1515 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1517 (defcustom org-special-ctrl-k nil
1518 "Non-nil means `C-k' will behave specially in headlines.
1519 When nil, `C-k' will call the default `kill-line' command.
1520 When t, the following will happen while the cursor is in the headline:
1522 - When the cursor is at the beginning of a headline, kill the entire
1523 line and possible the folded subtree below the line.
1524 - When in the middle of the headline text, kill the headline up to the tags.
1525 - When after the headline text, kill the tags."
1526 :group 'org-edit-structure
1527 :type 'boolean)
1529 (defcustom org-ctrl-k-protect-subtree nil
1530 "Non-nil means, do not delete a hidden subtree with C-k.
1531 When set to the symbol `error', simply throw an error when C-k is
1532 used to kill (part-of) a headline that has hidden text behind it.
1533 Any other non-nil value will result in a query to the user, if it is
1534 OK to kill that hidden subtree. When nil, kill without remorse."
1535 :group 'org-edit-structure
1536 :version "24.1"
1537 :type '(choice
1538 (const :tag "Do not protect hidden subtrees" nil)
1539 (const :tag "Protect hidden subtrees with a security query" t)
1540 (const :tag "Never kill a hidden subtree with C-k" error)))
1542 (defcustom org-special-ctrl-o t
1543 "Non-nil means, make `C-o' insert a row in tables."
1544 :group 'org-edit-structure
1545 :type 'boolean)
1547 (defcustom org-catch-invisible-edits nil
1548 "Check if in invisible region before inserting or deleting a character.
1549 Valid values are:
1551 nil Do not check, so just do invisible edits.
1552 error Throw an error and do nothing.
1553 show Make point visible, and do the requested edit.
1554 show-and-error Make point visible, then throw an error and abort the edit.
1555 smart Make point visible, and do insertion/deletion if it is
1556 adjacent to visible text and the change feels predictable.
1557 Never delete a previously invisible character or add in the
1558 middle or right after an invisible region. Basically, this
1559 allows insertion and backward-delete right before ellipses.
1560 FIXME: maybe in this case we should not even show?"
1561 :group 'org-edit-structure
1562 :version "24.1"
1563 :type '(choice
1564 (const :tag "Do not check" nil)
1565 (const :tag "Throw error when trying to edit" error)
1566 (const :tag "Unhide, but do not do the edit" show-and-error)
1567 (const :tag "Show invisible part and do the edit" show)
1568 (const :tag "Be smart and do the right thing" smart)))
1570 (defcustom org-yank-folded-subtrees t
1571 "Non-nil means when yanking subtrees, fold them.
1572 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1573 it starts with a heading and all other headings in it are either children
1574 or siblings, then fold all the subtrees. However, do this only if no
1575 text after the yank would be swallowed into a folded tree by this action."
1576 :group 'org-edit-structure
1577 :type 'boolean)
1579 (defcustom org-yank-adjusted-subtrees nil
1580 "Non-nil means when yanking subtrees, adjust the level.
1581 With this setting, `org-paste-subtree' is used to insert the subtree, see
1582 this function for details."
1583 :group 'org-edit-structure
1584 :type 'boolean)
1586 (defcustom org-M-RET-may-split-line '((default . t))
1587 "Non-nil means M-RET will split the line at the cursor position.
1588 When nil, it will go to the end of the line before making a
1589 new line.
1590 You may also set this option in a different way for different
1591 contexts. Valid contexts are:
1593 headline when creating a new headline
1594 item when creating a new item
1595 table in a table field
1596 default the value to be used for all contexts not explicitly
1597 customized"
1598 :group 'org-structure
1599 :group 'org-table
1600 :type '(choice
1601 (const :tag "Always" t)
1602 (const :tag "Never" nil)
1603 (repeat :greedy t :tag "Individual contexts"
1604 (cons
1605 (choice :tag "Context"
1606 (const headline)
1607 (const item)
1608 (const table)
1609 (const default))
1610 (boolean)))))
1613 (defcustom org-insert-heading-respect-content nil
1614 "Non-nil means insert new headings after the current subtree.
1615 \\<org-mode-map>
1616 When nil, the new heading is created directly after the current line.
1617 The commands `\\[org-insert-heading-respect-content]' and \
1618 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1619 for the duration of the command."
1620 :group 'org-structure
1621 :type 'boolean)
1623 (defcustom org-blank-before-new-entry '((heading . auto)
1624 (plain-list-item . auto))
1625 "Should `org-insert-heading' leave a blank line before new heading/item?
1626 The value is an alist, with `heading' and `plain-list-item' as CAR,
1627 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1628 which case Org will look at the surrounding headings/items and try to
1629 make an intelligent decision whether to insert a blank line or not."
1630 :group 'org-edit-structure
1631 :type '(list
1632 (cons (const heading)
1633 (choice (const :tag "Never" nil)
1634 (const :tag "Always" t)
1635 (const :tag "Auto" auto)))
1636 (cons (const plain-list-item)
1637 (choice (const :tag "Never" nil)
1638 (const :tag "Always" t)
1639 (const :tag "Auto" auto)))))
1641 (defcustom org-insert-heading-hook nil
1642 "Hook being run after inserting a new heading."
1643 :group 'org-edit-structure
1644 :type 'hook)
1646 (defcustom org-enable-fixed-width-editor t
1647 "Non-nil means lines starting with \":\" are treated as fixed-width.
1648 This currently only means they are never auto-wrapped.
1649 When nil, such lines will be treated like ordinary lines."
1650 :group 'org-edit-structure
1651 :type 'boolean)
1653 (defcustom org-goto-auto-isearch t
1654 "Non-nil means typing characters in `org-goto' starts incremental search.
1655 When nil, you can use these keybindings to navigate the buffer:
1657 q Quit the org-goto interface
1658 n Go to the next visible heading
1659 p Go to the previous visible heading
1660 f Go one heading forward on same level
1661 b Go one heading backward on same level
1662 u Go one heading up"
1663 :group 'org-edit-structure
1664 :type 'boolean)
1666 (defgroup org-sparse-trees nil
1667 "Options concerning sparse trees in Org mode."
1668 :tag "Org Sparse Trees"
1669 :group 'org-structure)
1671 (defcustom org-highlight-sparse-tree-matches t
1672 "Non-nil means highlight all matches that define a sparse tree.
1673 The highlights will automatically disappear the next time the buffer is
1674 changed by an edit command."
1675 :group 'org-sparse-trees
1676 :type 'boolean)
1678 (defcustom org-remove-highlights-with-change t
1679 "Non-nil means any change to the buffer will remove temporary highlights.
1680 \\<org-mode-map>\
1681 Such highlights are created by `org-occur' and `org-clock-display'.
1682 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1683 to get rid of the highlights.
1684 The highlights created by `org-toggle-latex-fragment' always need
1685 `\\[org-toggle-latex-fragment]' to be removed."
1686 :group 'org-sparse-trees
1687 :group 'org-time
1688 :type 'boolean)
1690 (defcustom org-occur-case-fold-search t
1691 "Non-nil means `org-occur' should be case-insensitive.
1692 If set to `smart' the search will be case-insensitive only if it
1693 doesn't specify any upper case character."
1694 :group 'org-sparse-trees
1695 :version "25.2"
1696 :type '(choice
1697 (const :tag "Case-sensitive" nil)
1698 (const :tag "Case-insensitive" t)
1699 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1701 (defcustom org-occur-hook '(org-first-headline-recenter)
1702 "Hook that is run after `org-occur' has constructed a sparse tree.
1703 This can be used to recenter the window to show as much of the structure
1704 as possible."
1705 :group 'org-sparse-trees
1706 :type 'hook)
1708 (defgroup org-imenu-and-speedbar nil
1709 "Options concerning imenu and speedbar in Org mode."
1710 :tag "Org Imenu and Speedbar"
1711 :group 'org-structure)
1713 (defcustom org-imenu-depth 2
1714 "The maximum level for Imenu access to Org headlines.
1715 This also applied for speedbar access."
1716 :group 'org-imenu-and-speedbar
1717 :type 'integer)
1719 (defgroup org-table nil
1720 "Options concerning tables in Org mode."
1721 :tag "Org Table"
1722 :group 'org)
1724 (defcustom org-enable-table-editor 'optimized
1725 "Non-nil means lines starting with \"|\" are handled by the table editor.
1726 When nil, such lines will be treated like ordinary lines.
1728 When equal to the symbol `optimized', the table editor will be optimized to
1729 do the following:
1730 - Automatic overwrite mode in front of whitespace in table fields.
1731 This makes the structure of the table stay in tact as long as the edited
1732 field does not exceed the column width.
1733 - Minimize the number of realigns. Normally, the table is aligned each time
1734 TAB or RET are pressed to move to another field. With optimization this
1735 happens only if changes to a field might have changed the column width.
1736 Optimization requires replacing the functions `self-insert-command',
1737 `delete-char', and `backward-delete-char' in Org buffers, with a
1738 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1739 good at guessing when a re-align will be necessary, but you can always
1740 force one with `\\[org-ctrl-c-ctrl-c]'.
1742 If you would like to use the optimized version in Org mode, but the
1743 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1745 This variable can be used to turn on and off the table editor during a session,
1746 but in order to toggle optimization, a restart is required.
1748 See also the variable `org-table-auto-blank-field'."
1749 :group 'org-table
1750 :type '(choice
1751 (const :tag "off" nil)
1752 (const :tag "on" t)
1753 (const :tag "on, optimized" optimized)))
1755 (defcustom org-self-insert-cluster-for-undo nil
1756 "Non-nil means cluster self-insert commands for undo when possible.
1757 If this is set, then, like in the Emacs command loop, 20 consecutive
1758 characters will be undone together.
1759 This is configurable, because there is some impact on typing performance."
1760 :group 'org-table
1761 :type 'boolean)
1763 (defcustom org-table-tab-recognizes-table.el t
1764 "Non-nil means TAB will automatically notice a table.el table.
1765 When it sees such a table, it moves point into it and - if necessary -
1766 calls `table-recognize-table'."
1767 :group 'org-table-editing
1768 :type 'boolean)
1770 (defgroup org-link nil
1771 "Options concerning links in Org mode."
1772 :tag "Org Link"
1773 :group 'org)
1775 (defvar-local org-link-abbrev-alist-local nil
1776 "Buffer-local version of `org-link-abbrev-alist', which see.
1777 The value of this is taken from the #+LINK lines.")
1779 (defcustom org-link-parameters
1780 '(("doi" :follow org--open-doi-link)
1781 ("elisp" :follow org--open-elisp-link)
1782 ("file" :complete org-file-complete-link)
1783 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1784 ("help" :follow org--open-help-link)
1785 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1786 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1787 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1788 ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
1789 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1790 ("shell" :follow org--open-shell-link))
1791 "An alist of properties that defines all the links in Org mode.
1792 The key in each association is a string of the link type.
1793 Subsequent optional elements make up a p-list of link properties.
1795 :follow - A function that takes the link path as an argument.
1797 :export - A function that takes the link path, description and
1798 export-backend as arguments.
1800 :store - A function responsible for storing the link. See the
1801 function `org-store-link-functions'.
1803 :complete - A function that inserts a link with completion. The
1804 function takes one optional prefix arg.
1806 :face - A face for the link, or a function that returns a face.
1807 The function takes one argument which is the link path. The
1808 default face is `org-link'.
1810 :mouse-face - The mouse-face. The default is `highlight'.
1812 :display - `full' will not fold the link in descriptive
1813 display. Default is `org-link'.
1815 :help-echo - A string or function that takes (window object position)
1816 as arguments and returns a string.
1818 :keymap - A keymap that is active on the link. The default is
1819 `org-mouse-map'.
1821 :htmlize-link - A function for the htmlize-link. Defaults
1822 to (list :uri \"type:path\")
1824 :activate-func - A function to run at the end of font-lock
1825 activation. The function must accept (link-start link-end path bracketp)
1826 as arguments."
1827 :group 'org-link
1828 :type '(alist :tag "Link display parameters"
1829 :value-type plist))
1831 (defun org-link-get-parameter (type key)
1832 "Get TYPE link property for KEY.
1833 TYPE is a string and KEY is a plist keyword."
1834 (plist-get
1835 (cdr (assoc type org-link-parameters))
1836 key))
1838 (defun org-link-set-parameters (type &rest parameters)
1839 "Set link TYPE properties to PARAMETERS.
1840 PARAMETERS should be :key val pairs."
1841 (let ((data (assoc type org-link-parameters)))
1842 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1843 (push (cons type parameters) org-link-parameters)
1844 (org-make-link-regexps)
1845 (org-element-update-syntax))))
1847 (defun org-link-types ()
1848 "Return a list of known link types."
1849 (mapcar #'car org-link-parameters))
1851 (defcustom org-link-abbrev-alist nil
1852 "Alist of link abbreviations.
1853 The car of each element is a string, to be replaced at the start of a link.
1854 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1855 links in Org buffers can have an optional tag after a double colon, e.g.,
1857 [[linkkey:tag][description]]
1859 The `linkkey' must be a single word, starting with a letter, followed
1860 by letters, numbers, `-' or `_'.
1862 If REPLACE is a string, the tag will simply be appended to create the link.
1863 If the string contains \"%s\", the tag will be inserted there. If the string
1864 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1865 at that point (see the function `url-hexify-string'). If the string contains
1866 the specifier \"%(my-function)\", then the custom function `my-function' will
1867 be invoked: this function takes the tag as its only argument and must return
1868 a string.
1870 REPLACE may also be a function that will be called with the tag as the
1871 only argument to create the link, which should be returned as a string.
1873 See the manual for examples."
1874 :group 'org-link
1875 :type '(repeat
1876 (cons
1877 (string :tag "Protocol")
1878 (choice
1879 (string :tag "Format")
1880 (function)))))
1882 (defcustom org-descriptive-links t
1883 "Non-nil means Org will display descriptive links.
1884 E.g. [[http://orgmode.org][Org website]] will be displayed as
1885 \"Org Website\", hiding the link itself and just displaying its
1886 description. When set to nil, Org will display the full links
1887 literally.
1889 You can interactively set the value of this variable by calling
1890 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1891 :group 'org-link
1892 :type 'boolean)
1894 (defcustom org-link-file-path-type 'adaptive
1895 "How the path name in file links should be stored.
1896 Valid values are:
1898 relative Relative to the current directory, i.e. the directory of the file
1899 into which the link is being inserted.
1900 absolute Absolute path, if possible with ~ for home directory.
1901 noabbrev Absolute path, no abbreviation of home directory.
1902 adaptive Use relative path for files in the current directory and sub-
1903 directories of it. For other files, use an absolute path."
1904 :group 'org-link
1905 :type '(choice
1906 (const relative)
1907 (const absolute)
1908 (const noabbrev)
1909 (const adaptive)))
1911 (defvaralias 'org-activate-links 'org-highlight-links)
1912 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1913 "Types of links that should be highlighted in Org files.
1915 This is a list of symbols, each one of them leading to the
1916 highlighting of a certain link type.
1918 You can still open links that are not highlighted.
1920 In principle, it does not hurt to turn on highlighting for all
1921 link types. There may be a small gain when turning off unused
1922 link types. The types are:
1924 bracket The recommended [[link][description]] or [[link]] links with hiding.
1925 angle Links in angular brackets that may contain whitespace like
1926 <bbdb:Carsten Dominik>.
1927 plain Plain links in normal text, no whitespace, like http://google.com.
1928 radio Text that is matched by a radio target, see manual for details.
1929 tag Tag settings in a headline (link to tag search).
1930 date Time stamps (link to calendar).
1931 footnote Footnote labels.
1933 If you set this variable during an Emacs session, use `org-mode-restart'
1934 in the Org buffer so that the change takes effect."
1935 :group 'org-link
1936 :group 'org-appearance
1937 :type '(set :greedy t
1938 (const :tag "Double bracket links" bracket)
1939 (const :tag "Angular bracket links" angle)
1940 (const :tag "Plain text links" plain)
1941 (const :tag "Radio target matches" radio)
1942 (const :tag "Tags" tag)
1943 (const :tag "Timestamps" date)
1944 (const :tag "Footnotes" footnote)))
1946 (defcustom org-make-link-description-function nil
1947 "Function to use for generating link descriptions from links.
1948 When nil, the link location will be used. This function must take
1949 two parameters: the first one is the link, the second one is the
1950 description generated by `org-insert-link'. The function should
1951 return the description to use."
1952 :group 'org-link
1953 :type '(choice (const nil) (function)))
1955 (defgroup org-link-store nil
1956 "Options concerning storing links in Org mode."
1957 :tag "Org Store Link"
1958 :group 'org-link)
1960 (defcustom org-url-hexify-p t
1961 "When non-nil, hexify URL when creating a link."
1962 :type 'boolean
1963 :version "24.3"
1964 :group 'org-link-store)
1966 (defcustom org-email-link-description-format "Email %c: %.30s"
1967 "Format of the description part of a link to an email or usenet message.
1968 The following %-escapes will be replaced by corresponding information:
1970 %F full \"From\" field
1971 %f name, taken from \"From\" field, address if no name
1972 %T full \"To\" field
1973 %t first name in \"To\" field, address if no name
1974 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1975 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1976 %s subject
1977 %d date
1978 %m message-id.
1980 You may use normal field width specification between the % and the letter.
1981 This is for example useful to limit the length of the subject.
1983 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1984 :group 'org-link-store
1985 :type 'string)
1987 (defcustom org-from-is-user-regexp
1988 (let (r1 r2)
1989 (when (and user-mail-address (not (string= user-mail-address "")))
1990 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1991 (when (and user-full-name (not (string= user-full-name "")))
1992 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1993 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1994 "Regexp matched against the \"From:\" header of an email or usenet message.
1995 It should match if the message is from the user him/herself."
1996 :group 'org-link-store
1997 :type 'regexp)
1999 (defcustom org-context-in-file-links t
2000 "Non-nil means file links from `org-store-link' contain context.
2001 \\<org-mode-map>
2002 A search string will be added to the file name with :: as separator
2003 and used to find the context when the link is activated by the command
2004 `org-open-at-point'. When this option is t, the entire active region
2005 will be placed in the search string of the file link. If set to a
2006 positive integer, only the first n lines of context will be stored.
2008 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2009 \\[org-store-link]')
2010 negates this setting for the duration of the command."
2011 :group 'org-link-store
2012 :type '(choice boolean integer))
2014 (defcustom org-keep-stored-link-after-insertion nil
2015 "Non-nil means keep link in list for entire session.
2016 \\<org-mode-map>
2017 The command `org-store-link' adds a link pointing to the current
2018 location to an internal list. These links accumulate during a session.
2019 The command `org-insert-link' can be used to insert links into any
2020 Org file (offering completion for all stored links).
2022 When this option is nil, every link which has been inserted once using
2023 `\\[org-insert-link]' will be removed from the list, to make completing the \
2024 unused
2025 links more efficient."
2026 :group 'org-link-store
2027 :type 'boolean)
2029 (defgroup org-link-follow nil
2030 "Options concerning following links in Org mode."
2031 :tag "Org Follow Link"
2032 :group 'org-link)
2034 (defcustom org-link-translation-function nil
2035 "Function to translate links with different syntax to Org syntax.
2036 This can be used to translate links created for example by the Planner
2037 or emacs-wiki packages to Org syntax.
2038 The function must accept two parameters, a TYPE containing the link
2039 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2040 which is everything after the link protocol. It should return a cons
2041 with possibly modified values of type and path.
2042 Org contains a function for this, so if you set this variable to
2043 `org-translate-link-from-planner', you should be able follow many
2044 links created by planner."
2045 :group 'org-link-follow
2046 :type '(choice (const nil) (function)))
2048 (defcustom org-follow-link-hook nil
2049 "Hook that is run after a link has been followed."
2050 :group 'org-link-follow
2051 :type 'hook)
2053 (defcustom org-tab-follows-link nil
2054 "Non-nil means on links TAB will follow the link.
2055 Needs to be set before org.el is loaded.
2056 This really should not be used, it does not make sense, and the
2057 implementation is bad."
2058 :group 'org-link-follow
2059 :type 'boolean)
2061 (defcustom org-return-follows-link nil
2062 "Non-nil means on links RET will follow the link.
2063 In tables, the special behavior of RET has precedence."
2064 :group 'org-link-follow
2065 :type 'boolean)
2067 (defcustom org-mouse-1-follows-link
2068 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2069 "Non-nil means mouse-1 on a link will follow the link.
2070 A longer mouse click will still set point. Needs to be set
2071 before org.el is loaded."
2072 :group 'org-link-follow
2073 :version "24.4"
2074 :package-version '(Org . "8.3")
2075 :type '(choice
2076 (const :tag "A double click follows the link" double)
2077 (const :tag "Unconditionally follow the link with mouse-1" t)
2078 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2080 (defcustom org-mark-ring-length 4
2081 "Number of different positions to be recorded in the ring.
2082 Changing this requires a restart of Emacs to work correctly."
2083 :group 'org-link-follow
2084 :type 'integer)
2086 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2087 "Non-nil means internal fuzzy links can only match headlines.
2089 When nil, the a fuzzy link may point to a target or a named
2090 construct in the document. When set to the special value
2091 `query-to-create', offer to create a new headline when none
2092 matched.
2094 Spaces and statistics cookies are ignored during heading searches."
2095 :group 'org-link-follow
2096 :version "24.1"
2097 :type '(choice
2098 (const :tag "Use fuzzy text search" nil)
2099 (const :tag "Match only exact headline" t)
2100 (const :tag "Match exact headline or query to create it"
2101 query-to-create))
2102 :safe #'symbolp)
2104 (defcustom org-link-frame-setup
2105 '((vm . vm-visit-folder-other-frame)
2106 (vm-imap . vm-visit-imap-folder-other-frame)
2107 (gnus . org-gnus-no-new-news)
2108 (file . find-file-other-window)
2109 (wl . wl-other-frame))
2110 "Setup the frame configuration for following links.
2111 When following a link with Emacs, it may often be useful to display
2112 this link in another window or frame. This variable can be used to
2113 set this up for the different types of links.
2114 For VM, use any of
2115 `vm-visit-folder'
2116 `vm-visit-folder-other-window'
2117 `vm-visit-folder-other-frame'
2118 For Gnus, use any of
2119 `gnus'
2120 `gnus-other-frame'
2121 `org-gnus-no-new-news'
2122 For FILE, use any of
2123 `find-file'
2124 `find-file-other-window'
2125 `find-file-other-frame'
2126 For Wanderlust use any of
2127 `wl'
2128 `wl-other-frame'
2129 For the calendar, use the variable `calendar-setup'.
2130 For BBDB, it is currently only possible to display the matches in
2131 another window."
2132 :group 'org-link-follow
2133 :type '(list
2134 (cons (const vm)
2135 (choice
2136 (const vm-visit-folder)
2137 (const vm-visit-folder-other-window)
2138 (const vm-visit-folder-other-frame)))
2139 (cons (const vm-imap)
2140 (choice
2141 (const vm-visit-imap-folder)
2142 (const vm-visit-imap-folder-other-window)
2143 (const vm-visit-imap-folder-other-frame)))
2144 (cons (const gnus)
2145 (choice
2146 (const gnus)
2147 (const gnus-other-frame)
2148 (const org-gnus-no-new-news)))
2149 (cons (const file)
2150 (choice
2151 (const find-file)
2152 (const find-file-other-window)
2153 (const find-file-other-frame)))
2154 (cons (const wl)
2155 (choice
2156 (const wl)
2157 (const wl-other-frame)))))
2159 (defcustom org-display-internal-link-with-indirect-buffer nil
2160 "Non-nil means use indirect buffer to display infile links.
2161 Activating internal links (from one location in a file to another location
2162 in the same file) normally just jumps to the location. When the link is
2163 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2164 is displayed in
2165 another window. When this option is set, the other window actually displays
2166 an indirect buffer clone of the current buffer, to avoid any visibility
2167 changes to the current buffer."
2168 :group 'org-link-follow
2169 :type 'boolean)
2171 (defcustom org-open-non-existing-files nil
2172 "Non-nil means `org-open-file' will open non-existing files.
2173 When nil, an error will be generated.
2174 This variable applies only to external applications because they
2175 might choke on non-existing files. If the link is to a file that
2176 will be opened in Emacs, the variable is ignored."
2177 :group 'org-link-follow
2178 :type 'boolean)
2180 (defcustom org-open-directory-means-index-dot-org nil
2181 "Non-nil means a link to a directory really means to index.org.
2182 When nil, following a directory link will run dired or open a finder/explorer
2183 window on that directory."
2184 :group 'org-link-follow
2185 :type 'boolean)
2187 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2188 "Non-nil means ask for confirmation before executing shell links.
2189 Shell links can be dangerous: just think about a link
2191 [[shell:rm -rf ~/*][Google Search]]
2193 This link would show up in your Org document as \"Google Search\",
2194 but really it would remove your entire home directory.
2195 Therefore we advise against setting this variable to nil.
2196 Just change it to `y-or-n-p' if you want to confirm with a
2197 single keystroke rather than having to type \"yes\"."
2198 :group 'org-link-follow
2199 :type '(choice
2200 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2201 (const :tag "with y-or-n (faster)" y-or-n-p)
2202 (const :tag "no confirmation (dangerous)" nil)))
2203 (put 'org-confirm-shell-link-function
2204 'safe-local-variable
2205 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2207 (defcustom org-confirm-shell-link-not-regexp ""
2208 "A regexp to skip confirmation for shell links."
2209 :group 'org-link-follow
2210 :version "24.1"
2211 :type 'regexp)
2213 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2214 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2215 Elisp links can be dangerous: just think about a link
2217 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2219 This link would show up in your Org document as \"Google Search\",
2220 but really it would remove your entire home directory.
2221 Therefore we advise against setting this variable to nil.
2222 Just change it to `y-or-n-p' if you want to confirm with a
2223 single keystroke rather than having to type \"yes\"."
2224 :group 'org-link-follow
2225 :type '(choice
2226 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2227 (const :tag "with y-or-n (faster)" y-or-n-p)
2228 (const :tag "no confirmation (dangerous)" nil)))
2229 (put 'org-confirm-shell-link-function
2230 'safe-local-variable
2231 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2233 (defcustom org-confirm-elisp-link-not-regexp ""
2234 "A regexp to skip confirmation for Elisp links."
2235 :group 'org-link-follow
2236 :version "24.1"
2237 :type 'regexp)
2239 (defconst org-file-apps-defaults-gnu
2240 '((remote . emacs)
2241 (system . mailcap)
2242 (t . mailcap))
2243 "Default file applications on a UNIX or GNU/Linux system.
2244 See `org-file-apps'.")
2246 (defconst org-file-apps-defaults-macosx
2247 '((remote . emacs)
2248 (system . "open %s")
2249 ("ps.gz" . "gv %s")
2250 ("eps.gz" . "gv %s")
2251 ("dvi" . "xdvi %s")
2252 ("fig" . "xfig %s")
2253 (t . "open %s"))
2254 "Default file applications on a MacOS X system.
2255 The system \"open\" is known as a default, but we use X11 applications
2256 for some files for which the OS does not have a good default.
2257 See `org-file-apps'.")
2259 (defconst org-file-apps-defaults-windowsnt
2260 (list '(remote . emacs)
2261 (cons 'system (lambda (file _path)
2262 (with-no-warnings (w32-shell-execute "open" file))))
2263 (cons t (lambda (file _path)
2264 (with-no-warnings (w32-shell-execute "open" file)))))
2265 "Default file applications on a Windows NT system.
2266 The system \"open\" is used for most files.
2267 See `org-file-apps'.")
2269 (defcustom org-file-apps
2270 '((auto-mode . emacs)
2271 ("\\.mm\\'" . default)
2272 ("\\.x?html?\\'" . default)
2273 ("\\.pdf\\'" . default))
2274 "External applications for opening `file:path' items in a document.
2275 \\<org-mode-map>\
2277 Org mode uses system defaults for different file types, but
2278 you can use this variable to set the application for a given file
2279 extension. The entries in this list are cons cells where the car identifies
2280 files and the cdr the corresponding command.
2282 Possible values for the file identifier are:
2284 \"string\" A string as a file identifier can be interpreted in different
2285 ways, depending on its contents:
2287 - Alphanumeric characters only:
2288 Match links with this file extension.
2289 Example: (\"pdf\" . \"evince %s\")
2290 to open PDFs with evince.
2292 - Regular expression: Match links where the
2293 filename matches the regexp. If you want to
2294 use groups here, use shy groups.
2296 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2297 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2298 to open *.html and *.xhtml with firefox.
2300 - Regular expression which contains (non-shy) groups:
2301 Match links where the whole link, including \"::\", and
2302 anything after that, matches the regexp.
2303 In a custom command string, %1, %2, etc. are replaced with
2304 the parts of the link that were matched by the groups.
2305 For backwards compatibility, if a command string is given
2306 that does not use any of the group matches, this case is
2307 handled identically to the second one (i.e. match against
2308 file name only).
2309 In a custom function, you can access the group matches with
2310 (match-string n link).
2312 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2313 \"evince -p %1 %s\")
2314 to open [[file:document.pdf::5]] with evince at page 5.
2316 `directory' Matches a directory
2317 `remote' Matches a remote file, accessible through tramp or efs.
2318 Remote files most likely should be visited through Emacs
2319 because external applications cannot handle such paths.
2320 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2321 so all files Emacs knows how to handle. Using this with
2322 command `emacs' will open most files in Emacs. Beware that this
2323 will also open html files inside Emacs, unless you add
2324 (\"html\" . default) to the list as well.
2325 `system' The system command to open files, like `open' on Windows
2326 and Mac OS X, and mailcap under GNU/Linux. This is the command
2327 that will be selected if you call `org-open-at-point' with a
2328 double prefix argument (`\\[universal-argument] \
2329 \\[universal-argument] \\[org-open-at-point]').
2330 t Default for files not matched by any of the other options.
2332 Possible values for the command are:
2334 `emacs' The file will be visited by the current Emacs process.
2335 `default' Use the default application for this file type, which is the
2336 association for t in the list, most likely in the system-specific
2337 part. This can be used to overrule an unwanted setting in the
2338 system-specific variable.
2339 `system' Use the system command for opening files, like \"open\".
2340 This command is specified by the entry whose car is `system'.
2341 Most likely, the system-specific version of this variable
2342 does define this command, but you can overrule/replace it
2343 here.
2344 `mailcap' Use command specified in the mailcaps.
2345 string A command to be executed by a shell; %s will be replaced
2346 by the path to the file.
2347 function A Lisp function, which will be called with two arguments:
2348 the file path and the original link string, without the
2349 \"file:\" prefix.
2351 For more examples, see the system specific constants
2352 `org-file-apps-defaults-macosx'
2353 `org-file-apps-defaults-windowsnt'
2354 `org-file-apps-defaults-gnu'."
2355 :group 'org-link-follow
2356 :type '(repeat
2357 (cons (choice :value ""
2358 (string :tag "Extension")
2359 (const :tag "System command to open files" system)
2360 (const :tag "Default for unrecognized files" t)
2361 (const :tag "Remote file" remote)
2362 (const :tag "Links to a directory" directory)
2363 (const :tag "Any files that have Emacs modes"
2364 auto-mode))
2365 (choice :value ""
2366 (const :tag "Visit with Emacs" emacs)
2367 (const :tag "Use default" default)
2368 (const :tag "Use the system command" system)
2369 (string :tag "Command")
2370 (function :tag "Function")))))
2372 (defcustom org-doi-server-url "http://dx.doi.org/"
2373 "The URL of the DOI server."
2374 :type 'string
2375 :version "24.3"
2376 :group 'org-link-follow)
2378 (defgroup org-refile nil
2379 "Options concerning refiling entries in Org mode."
2380 :tag "Org Refile"
2381 :group 'org)
2383 (defcustom org-directory "~/org"
2384 "Directory with Org files.
2385 This is just a default location to look for Org files. There is no need
2386 at all to put your files into this directory. It is used in the
2387 following situations:
2389 1. When a capture template specifies a target file that is not an
2390 absolute path. The path will then be interpreted relative to
2391 `org-directory'
2392 2. When the value of variable `org-agenda-files' is a single file, any
2393 relative paths in this file will be taken as relative to
2394 `org-directory'."
2395 :group 'org-refile
2396 :group 'org-capture
2397 :type 'directory)
2399 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2400 "Default target for storing notes.
2401 Used as a fall back file for org-capture.el, for templates that
2402 do not specify a target file."
2403 :group 'org-refile
2404 :group 'org-capture
2405 :type 'file)
2407 (defcustom org-goto-interface 'outline
2408 "The default interface to be used for `org-goto'.
2409 Allowed values are:
2410 outline The interface shows an outline of the relevant file
2411 and the correct heading is found by moving through
2412 the outline or by searching with incremental search.
2413 outline-path-completion Headlines in the current buffer are offered via
2414 completion. This is the interface also used by
2415 the refile command."
2416 :group 'org-refile
2417 :type '(choice
2418 (const :tag "Outline" outline)
2419 (const :tag "Outline-path-completion" outline-path-completion)))
2421 (defcustom org-goto-max-level 5
2422 "Maximum target level when running `org-goto' with refile interface."
2423 :group 'org-refile
2424 :type 'integer)
2426 (defcustom org-reverse-note-order nil
2427 "Non-nil means store new notes at the beginning of a file or entry.
2428 When nil, new notes will be filed to the end of a file or entry.
2429 This can also be a list with cons cells of regular expressions that
2430 are matched against file names, and values."
2431 :group 'org-capture
2432 :group 'org-refile
2433 :type '(choice
2434 (const :tag "Reverse always" t)
2435 (const :tag "Reverse never" nil)
2436 (repeat :tag "By file name regexp"
2437 (cons regexp boolean))))
2439 (defcustom org-log-refile nil
2440 "Information to record when a task is refiled.
2442 Possible values are:
2444 nil Don't add anything
2445 time Add a time stamp to the task
2446 note Prompt for a note and add it with template `org-log-note-headings'
2448 This option can also be set with on a per-file-basis with
2450 #+STARTUP: nologrefile
2451 #+STARTUP: logrefile
2452 #+STARTUP: lognoterefile
2454 You can have local logging settings for a subtree by setting the LOGGING
2455 property to one or more of these keywords.
2457 When bulk-refiling from the agenda, the value `note' is forbidden and
2458 will temporarily be changed to `time'."
2459 :group 'org-refile
2460 :group 'org-progress
2461 :version "24.1"
2462 :type '(choice
2463 (const :tag "No logging" nil)
2464 (const :tag "Record timestamp" time)
2465 (const :tag "Record timestamp with note." note)))
2467 (defcustom org-refile-targets nil
2468 "Targets for refiling entries with `\\[org-refile]'.
2469 This is a list of cons cells. Each cell contains:
2470 - a specification of the files to be considered, either a list of files,
2471 or a symbol whose function or variable value will be used to retrieve
2472 a file name or a list of file names. If you use `org-agenda-files' for
2473 that, all agenda files will be scanned for targets. Nil means consider
2474 headings in the current buffer.
2475 - A specification of how to find candidate refile targets. This may be
2476 any of:
2477 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2478 This tag has to be present in all target headlines, inheritance will
2479 not be considered.
2480 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2481 todo keyword.
2482 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2483 headlines that are refiling targets.
2484 - a cons cell (:level . N). Any headline of level N is considered a target.
2485 Note that, when `org-odd-levels-only' is set, level corresponds to
2486 order in hierarchy, not to the number of stars.
2487 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2488 Note that, when `org-odd-levels-only' is set, level corresponds to
2489 order in hierarchy, not to the number of stars.
2491 Each element of this list generates a set of possible targets.
2492 The union of these sets is presented (with completion) to
2493 the user by `org-refile'.
2495 You can set the variable `org-refile-target-verify-function' to a function
2496 to verify each headline found by the simple criteria above.
2498 When this variable is nil, all top-level headlines in the current buffer
2499 are used, equivalent to the value `((nil . (:level . 1))'."
2500 :group 'org-refile
2501 :type '(repeat
2502 (cons
2503 (choice :value org-agenda-files
2504 (const :tag "All agenda files" org-agenda-files)
2505 (const :tag "Current buffer" nil)
2506 (function) (variable) (file))
2507 (choice :tag "Identify target headline by"
2508 (cons :tag "Specific tag" (const :value :tag) (string))
2509 (cons :tag "TODO keyword" (const :value :todo) (string))
2510 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2511 (cons :tag "Level number" (const :value :level) (integer))
2512 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2514 (defcustom org-refile-target-verify-function nil
2515 "Function to verify if the headline at point should be a refile target.
2516 The function will be called without arguments, with point at the
2517 beginning of the headline. It should return t and leave point
2518 where it is if the headline is a valid target for refiling.
2520 If the target should not be selected, the function must return nil.
2521 In addition to this, it may move point to a place from where the search
2522 should be continued. For example, the function may decide that the entire
2523 subtree of the current entry should be excluded and move point to the end
2524 of the subtree."
2525 :group 'org-refile
2526 :type '(choice
2527 (const nil)
2528 (function)))
2530 (defcustom org-refile-use-cache nil
2531 "Non-nil means cache refile targets to speed up the process.
2532 \\<org-mode-map>\
2533 The cache for a particular file will be updated automatically when
2534 the buffer has been killed, or when any of the marker used for flagging
2535 refile targets no longer points at a live buffer.
2536 If you have added new entries to a buffer that might themselves be targets,
2537 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2538 if you find that easier, \
2539 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2540 \\[org-refile]'."
2541 :group 'org-refile
2542 :version "24.1"
2543 :type 'boolean)
2545 (defcustom org-refile-use-outline-path nil
2546 "Non-nil means provide refile targets as paths.
2547 So a level 3 headline will be available as level1/level2/level3.
2549 When the value is `file', also include the file name (without directory)
2550 into the path. In this case, you can also stop the completion after
2551 the file name, to get entries inserted as top level in the file.
2553 When `full-file-path', include the full file path."
2554 :group 'org-refile
2555 :type '(choice
2556 (const :tag "Not" nil)
2557 (const :tag "Yes" t)
2558 (const :tag "Start with file name" file)
2559 (const :tag "Start with full file path" full-file-path)))
2561 (defcustom org-outline-path-complete-in-steps t
2562 "Non-nil means complete the outline path in hierarchical steps.
2563 When Org uses the refile interface to select an outline path (see
2564 `org-refile-use-outline-path'), the completion of the path can be
2565 done in a single go, or it can be done in steps down the headline
2566 hierarchy. Going in steps is probably the best if you do not use
2567 a special completion package like `ido' or `icicles'. However,
2568 when using these packages, going in one step can be very fast,
2569 while still showing the whole path to the entry."
2570 :group 'org-refile
2571 :type 'boolean)
2573 (defcustom org-refile-allow-creating-parent-nodes nil
2574 "Non-nil means allow the creation of new nodes as refile targets.
2575 New nodes are then created by adding \"/new node name\" to the completion
2576 of an existing node. When the value of this variable is `confirm',
2577 new node creation must be confirmed by the user (recommended).
2578 When nil, the completion must match an existing entry.
2580 Note that, if the new heading is not seen by the criteria
2581 listed in `org-refile-targets', multiple instances of the same
2582 heading would be created by trying again to file under the new
2583 heading."
2584 :group 'org-refile
2585 :type '(choice
2586 (const :tag "Never" nil)
2587 (const :tag "Always" t)
2588 (const :tag "Prompt for confirmation" confirm)))
2590 (defcustom org-refile-active-region-within-subtree nil
2591 "Non-nil means also refile active region within a subtree.
2593 By default `org-refile' doesn't allow refiling regions if they
2594 don't contain a set of subtrees, but it might be convenient to
2595 do so sometimes: in that case, the first line of the region is
2596 converted to a headline before refiling."
2597 :group 'org-refile
2598 :version "24.1"
2599 :type 'boolean)
2601 (defgroup org-todo nil
2602 "Options concerning TODO items in Org mode."
2603 :tag "Org TODO"
2604 :group 'org)
2606 (defgroup org-progress nil
2607 "Options concerning Progress logging in Org mode."
2608 :tag "Org Progress"
2609 :group 'org-time)
2611 (defvar org-todo-interpretation-widgets
2612 '((:tag "Sequence (cycling hits every state)" sequence)
2613 (:tag "Type (cycling directly to DONE)" type))
2614 "The available interpretation symbols for customizing `org-todo-keywords'.
2615 Interested libraries should add to this list.")
2617 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2618 "List of TODO entry keyword sequences and their interpretation.
2619 \\<org-mode-map>This is a list of sequences.
2621 Each sequence starts with a symbol, either `sequence' or `type',
2622 indicating if the keywords should be interpreted as a sequence of
2623 action steps, or as different types of TODO items. The first
2624 keywords are states requiring action - these states will select a headline
2625 for inclusion into the global TODO list Org produces. If one of the
2626 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2627 signify that no further action is necessary. If \"|\" is not found,
2628 the last keyword is treated as the only DONE state of the sequence.
2630 The command `\\[org-todo]' cycles an entry through these states, and one
2631 additional state where no keyword is present. For details about this
2632 cycling, see the manual.
2634 TODO keywords and interpretation can also be set on a per-file basis with
2635 the special #+SEQ_TODO and #+TYP_TODO lines.
2637 Each keyword can optionally specify a character for fast state selection
2638 \(in combination with the variable `org-use-fast-todo-selection')
2639 and specifiers for state change logging, using the same syntax that
2640 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2641 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2642 indicates to record a time stamp each time this state is selected.
2644 Each keyword may also specify if a timestamp or a note should be
2645 recorded when entering or leaving the state, by adding additional
2646 characters in the parenthesis after the keyword. This looks like this:
2647 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2648 record only the time of the state change. With X and Y being either
2649 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2650 Y when leaving the state if and only if the *target* state does not
2651 define X. You may omit any of the fast-selection key or X or /Y,
2652 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2654 For backward compatibility, this variable may also be just a list
2655 of keywords. In this case the interpretation (sequence or type) will be
2656 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2657 :group 'org-todo
2658 :group 'org-keywords
2659 :type '(choice
2660 (repeat :tag "Old syntax, just keywords"
2661 (string :tag "Keyword"))
2662 (repeat :tag "New syntax"
2663 (cons
2664 (choice
2665 :tag "Interpretation"
2666 ;;Quick and dirty way to see
2667 ;;`org-todo-interpretations'. This takes the
2668 ;;place of item arguments
2669 :convert-widget
2670 (lambda (widget)
2671 (widget-put widget
2672 :args (mapcar
2673 (lambda (x)
2674 (widget-convert
2675 (cons 'const x)))
2676 org-todo-interpretation-widgets))
2677 widget))
2678 (repeat
2679 (string :tag "Keyword"))))))
2681 (defvar-local org-todo-keywords-1 nil
2682 "All TODO and DONE keywords active in a buffer.")
2683 (defvar org-todo-keywords-for-agenda nil)
2684 (defvar org-done-keywords-for-agenda nil)
2685 (defvar org-todo-keyword-alist-for-agenda nil)
2686 (defvar org-tag-alist-for-agenda nil
2687 "Alist of all tags from all agenda files.")
2688 (defvar org-tag-groups-alist-for-agenda nil
2689 "Alist of all groups tags from all current agenda files.")
2690 (defvar-local org-tag-groups-alist nil)
2691 (defvar org-agenda-contributing-files nil)
2692 (defvar-local org-current-tag-alist nil
2693 "Alist of all tag groups in current buffer.
2694 This variable takes into consideration `org-tag-alist',
2695 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2696 (defvar-local org-not-done-keywords nil)
2697 (defvar-local org-done-keywords nil)
2698 (defvar-local org-todo-heads nil)
2699 (defvar-local org-todo-sets nil)
2700 (defvar-local org-todo-log-states nil)
2701 (defvar-local org-todo-kwd-alist nil)
2702 (defvar-local org-todo-key-alist nil)
2703 (defvar-local org-todo-key-trigger nil)
2705 (defcustom org-todo-interpretation 'sequence
2706 "Controls how TODO keywords are interpreted.
2707 This variable is in principle obsolete and is only used for
2708 backward compatibility, if the interpretation of todo keywords is
2709 not given already in `org-todo-keywords'. See that variable for
2710 more information."
2711 :group 'org-todo
2712 :group 'org-keywords
2713 :type '(choice (const sequence)
2714 (const type)))
2716 (defcustom org-use-fast-todo-selection t
2717 "\\<org-mode-map>\
2718 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2719 This variable describes if and under what circumstances the cycling
2720 mechanism for TODO keywords will be replaced by a single-key, direct
2721 selection scheme.
2723 When nil, fast selection is never used.
2725 When the symbol `prefix', it will be used when `org-todo' is called
2726 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2727 in an Org buffer, and
2728 `\\[universal-argument] t' in an agenda buffer.
2730 When t, fast selection is used by default. In this case, the prefix
2731 argument forces cycling instead.
2733 In all cases, the special interface is only used if access keys have
2734 actually been assigned by the user, i.e. if keywords in the configuration
2735 are followed by a letter in parenthesis, like TODO(t)."
2736 :group 'org-todo
2737 :type '(choice
2738 (const :tag "Never" nil)
2739 (const :tag "By default" t)
2740 (const :tag "Only with C-u C-c C-t" prefix)))
2742 (defcustom org-provide-todo-statistics t
2743 "Non-nil means update todo statistics after insert and toggle.
2744 ALL-HEADLINES means update todo statistics by including headlines
2745 with no TODO keyword as well, counting them as not done.
2746 A list of TODO keywords means the same, but skip keywords that are
2747 not in this list.
2748 When set to a list of two lists, the first list contains keywords
2749 to consider as TODO keywords, the second list contains keywords
2750 to consider as DONE keywords.
2752 When this is set, todo statistics is updated in the parent of the
2753 current entry each time a todo state is changed."
2754 :group 'org-todo
2755 :type '(choice
2756 (const :tag "Yes, only for TODO entries" t)
2757 (const :tag "Yes, including all entries" all-headlines)
2758 (repeat :tag "Yes, for TODOs in this list"
2759 (string :tag "TODO keyword"))
2760 (list :tag "Yes, for TODOs and DONEs in these lists"
2761 (repeat (string :tag "TODO keyword"))
2762 (repeat (string :tag "DONE keyword")))
2763 (other :tag "No TODO statistics" nil)))
2765 (defcustom org-hierarchical-todo-statistics t
2766 "Non-nil means TODO statistics covers just direct children.
2767 When nil, all entries in the subtree are considered.
2768 This has only an effect if `org-provide-todo-statistics' is set.
2769 To set this to nil for only a single subtree, use a COOKIE_DATA
2770 property and include the word \"recursive\" into the value."
2771 :group 'org-todo
2772 :type 'boolean)
2774 (defcustom org-after-todo-state-change-hook nil
2775 "Hook which is run after the state of a TODO item was changed.
2776 The new state (a string with a TODO keyword, or nil) is available in the
2777 Lisp variable `org-state'."
2778 :group 'org-todo
2779 :type 'hook)
2781 (defvar org-blocker-hook nil
2782 "Hook for functions that are allowed to block a state change.
2784 Functions in this hook should not modify the buffer.
2785 Each function gets as its single argument a property list,
2786 see `org-trigger-hook' for more information about this list.
2788 If any of the functions in this hook returns nil, the state change
2789 is blocked.")
2791 (defvar org-trigger-hook nil
2792 "Hook for functions that are triggered by a state change.
2794 Each function gets as its single argument a property list with at
2795 least the following elements:
2797 (:type type-of-change :position pos-at-entry-start
2798 :from old-state :to new-state)
2800 Depending on the type, more properties may be present.
2802 This mechanism is currently implemented for:
2804 TODO state changes
2805 ------------------
2806 :type todo-state-change
2807 :from previous state (keyword as a string), or nil, or a symbol
2808 `todo' or `done', to indicate the general type of state.
2809 :to new state, like in :from")
2811 (defcustom org-enforce-todo-dependencies nil
2812 "Non-nil means undone TODO entries will block switching the parent to DONE.
2813 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2814 be blocked if any prior sibling is not yet done.
2815 Finally, if the parent is blocked because of ordered siblings of its own,
2816 the child will also be blocked."
2817 :set (lambda (var val)
2818 (set var val)
2819 (if val
2820 (add-hook 'org-blocker-hook
2821 'org-block-todo-from-children-or-siblings-or-parent)
2822 (remove-hook 'org-blocker-hook
2823 'org-block-todo-from-children-or-siblings-or-parent)))
2824 :group 'org-todo
2825 :type 'boolean)
2827 (defcustom org-enforce-todo-checkbox-dependencies nil
2828 "Non-nil means unchecked boxes will block switching the parent to DONE.
2829 When this is nil, checkboxes have no influence on switching TODO states.
2830 When non-nil, you first need to check off all check boxes before the TODO
2831 entry can be switched to DONE.
2832 This variable needs to be set before org.el is loaded, and you need to
2833 restart Emacs after a change to make the change effective. The only way
2834 to change is while Emacs is running is through the customize interface."
2835 :set (lambda (var val)
2836 (set var val)
2837 (if val
2838 (add-hook 'org-blocker-hook
2839 'org-block-todo-from-checkboxes)
2840 (remove-hook 'org-blocker-hook
2841 'org-block-todo-from-checkboxes)))
2842 :group 'org-todo
2843 :type 'boolean)
2845 (defcustom org-treat-insert-todo-heading-as-state-change nil
2846 "Non-nil means inserting a TODO heading is treated as state change.
2847 So when the command `\\[org-insert-todo-heading]' is used, state change
2848 logging will apply if appropriate. When nil, the new TODO item will
2849 be inserted directly, and no logging will take place."
2850 :group 'org-todo
2851 :type 'boolean)
2853 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2854 "Non-nil means switching TODO states with S-cursor counts as state change.
2855 This is the default behavior. However, setting this to nil allows a
2856 convenient way to select a TODO state and bypass any logging associated
2857 with that."
2858 :group 'org-todo
2859 :type 'boolean)
2861 (defcustom org-todo-state-tags-triggers nil
2862 "Tag changes that should be triggered by TODO state changes.
2863 This is a list. Each entry is
2865 (state-change (tag . flag) .......)
2867 State-change can be a string with a state, and empty string to indicate the
2868 state that has no TODO keyword, or it can be one of the symbols `todo'
2869 or `done', meaning any not-done or done state, respectively."
2870 :group 'org-todo
2871 :group 'org-tags
2872 :type '(repeat
2873 (cons (choice :tag "When changing to"
2874 (const :tag "Not-done state" todo)
2875 (const :tag "Done state" done)
2876 (string :tag "State"))
2877 (repeat
2878 (cons :tag "Tag action"
2879 (string :tag "Tag")
2880 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2882 (defcustom org-log-done nil
2883 "Information to record when a task moves to the DONE state.
2885 Possible values are:
2887 nil Don't add anything, just change the keyword
2888 time Add a time stamp to the task
2889 note Prompt for a note and add it with template `org-log-note-headings'
2891 This option can also be set with on a per-file-basis with
2893 #+STARTUP: nologdone
2894 #+STARTUP: logdone
2895 #+STARTUP: lognotedone
2897 You can have local logging settings for a subtree by setting the LOGGING
2898 property to one or more of these keywords."
2899 :group 'org-todo
2900 :group 'org-progress
2901 :type '(choice
2902 (const :tag "No logging" nil)
2903 (const :tag "Record CLOSED timestamp" time)
2904 (const :tag "Record CLOSED timestamp with note." note)))
2906 ;; Normalize old uses of org-log-done.
2907 (cond
2908 ((eq org-log-done t) (setq org-log-done 'time))
2909 ((and (listp org-log-done) (memq 'done org-log-done))
2910 (setq org-log-done 'note)))
2912 (defcustom org-log-reschedule nil
2913 "Information to record when the scheduling date of a tasks is modified.
2915 Possible values are:
2917 nil Don't add anything, just change the date
2918 time Add a time stamp to the task
2919 note Prompt for a note and add it with template `org-log-note-headings'
2921 This option can also be set with on a per-file-basis with
2923 #+STARTUP: nologreschedule
2924 #+STARTUP: logreschedule
2925 #+STARTUP: lognotereschedule"
2926 :group 'org-todo
2927 :group 'org-progress
2928 :type '(choice
2929 (const :tag "No logging" nil)
2930 (const :tag "Record timestamp" time)
2931 (const :tag "Record timestamp with note." note)))
2933 (defcustom org-log-redeadline nil
2934 "Information to record when the deadline date of a tasks is modified.
2936 Possible values are:
2938 nil Don't add anything, just change the date
2939 time Add a time stamp to the task
2940 note Prompt for a note and add it with template `org-log-note-headings'
2942 This option can also be set with on a per-file-basis with
2944 #+STARTUP: nologredeadline
2945 #+STARTUP: logredeadline
2946 #+STARTUP: lognoteredeadline
2948 You can have local logging settings for a subtree by setting the LOGGING
2949 property to one or more of these keywords."
2950 :group 'org-todo
2951 :group 'org-progress
2952 :type '(choice
2953 (const :tag "No logging" nil)
2954 (const :tag "Record timestamp" time)
2955 (const :tag "Record timestamp with note." note)))
2957 (defcustom org-log-note-clock-out nil
2958 "Non-nil means record a note when clocking out of an item.
2959 This can also be configured on a per-file basis by adding one of
2960 the following lines anywhere in the buffer:
2962 #+STARTUP: lognoteclock-out
2963 #+STARTUP: nolognoteclock-out"
2964 :group 'org-todo
2965 :group 'org-progress
2966 :type 'boolean)
2968 (defcustom org-log-done-with-time t
2969 "Non-nil means the CLOSED time stamp will contain date and time.
2970 When nil, only the date will be recorded."
2971 :group 'org-progress
2972 :type 'boolean)
2974 (defcustom org-log-note-headings
2975 '((done . "CLOSING NOTE %t")
2976 (state . "State %-12s from %-12S %t")
2977 (note . "Note taken on %t")
2978 (reschedule . "Rescheduled from %S on %t")
2979 (delschedule . "Not scheduled, was %S on %t")
2980 (redeadline . "New deadline from %S on %t")
2981 (deldeadline . "Removed deadline, was %S on %t")
2982 (refile . "Refiled on %t")
2983 (clock-out . ""))
2984 "Headings for notes added to entries.
2986 The value is an alist, with the car being a symbol indicating the
2987 note context, and the cdr is the heading to be used. The heading
2988 may also be the empty string. The following placeholders can be
2989 used:
2991 %t a time stamp.
2992 %T an active time stamp instead the default inactive one
2993 %d a short-format time stamp.
2994 %D an active short-format time stamp.
2995 %s the new TODO state or time stamp (inactive), in double quotes.
2996 %S the old TODO state or time stamp (inactive), in double quotes.
2997 %u the user name.
2998 %U full user name.
3000 In fact, it is not a good idea to change the `state' entry,
3001 because Agenda Log mode depends on the format of these entries."
3002 :group 'org-todo
3003 :group 'org-progress
3004 :type '(list :greedy t
3005 (cons (const :tag "Heading when closing an item" done) string)
3006 (cons (const :tag
3007 "Heading when changing todo state (todo sequence only)"
3008 state) string)
3009 (cons (const :tag "Heading when just taking a note" note) string)
3010 (cons (const :tag "Heading when rescheduling" reschedule) string)
3011 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3012 (cons (const :tag "Heading when changing deadline" redeadline) string)
3013 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3014 (cons (const :tag "Heading when refiling" refile) string)
3015 (cons (const :tag "Heading when clocking out" clock-out) string)))
3017 (unless (assq 'note org-log-note-headings)
3018 (push '(note . "%t") org-log-note-headings))
3020 (defcustom org-log-into-drawer nil
3021 "Non-nil means insert state change notes and time stamps into a drawer.
3022 When nil, state changes notes will be inserted after the headline and
3023 any scheduling and clock lines, but not inside a drawer.
3025 The value of this variable should be the name of the drawer to use.
3026 LOGBOOK is proposed as the default drawer for this purpose, you can
3027 also set this to a string to define the drawer of your choice.
3029 A value of t is also allowed, representing \"LOGBOOK\".
3031 A value of t or nil can also be set with on a per-file-basis with
3033 #+STARTUP: logdrawer
3034 #+STARTUP: nologdrawer
3036 If this variable is set, `org-log-state-notes-insert-after-drawers'
3037 will be ignored.
3039 You can set the property LOG_INTO_DRAWER to overrule this setting for
3040 a subtree.
3042 Do not check directly this variable in a Lisp program. Call
3043 function `org-log-into-drawer' instead."
3044 :group 'org-todo
3045 :group 'org-progress
3046 :type '(choice
3047 (const :tag "Not into a drawer" nil)
3048 (const :tag "LOGBOOK" t)
3049 (string :tag "Other")))
3051 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3053 (defun org-log-into-drawer ()
3054 "Name of the log drawer, as a string, or nil.
3055 This is the value of `org-log-into-drawer'. However, if the
3056 current entry has or inherits a LOG_INTO_DRAWER property, it will
3057 be used instead of the default value."
3058 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3059 (cond ((equal p "nil") nil)
3060 ((equal p "t") "LOGBOOK")
3061 ((stringp p) p)
3062 (p "LOGBOOK")
3063 ((stringp org-log-into-drawer) org-log-into-drawer)
3064 (org-log-into-drawer "LOGBOOK"))))
3066 (defcustom org-log-state-notes-insert-after-drawers nil
3067 "Non-nil means insert state change notes after any drawers in entry.
3068 Only the drawers that *immediately* follow the headline and the
3069 deadline/scheduled line are skipped.
3070 When nil, insert notes right after the heading and perhaps the line
3071 with deadline/scheduling if present.
3073 This variable will have no effect if `org-log-into-drawer' is
3074 set."
3075 :group 'org-todo
3076 :group 'org-progress
3077 :type 'boolean)
3079 (defcustom org-log-states-order-reversed t
3080 "Non-nil means the latest state note will be directly after heading.
3081 When nil, the state change notes will be ordered according to time.
3083 This option can also be set with on a per-file-basis with
3085 #+STARTUP: logstatesreversed
3086 #+STARTUP: nologstatesreversed"
3087 :group 'org-todo
3088 :group 'org-progress
3089 :type 'boolean)
3091 (defcustom org-todo-repeat-to-state nil
3092 "The TODO state to which a repeater should return the repeating task.
3093 By default this is the first task in a TODO sequence, or the previous state
3094 in a TODO_TYP set. But you can specify another task here.
3095 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3096 :group 'org-todo
3097 :version "24.1"
3098 :type '(choice (const :tag "Head of sequence" nil)
3099 (string :tag "Specific state")))
3101 (defcustom org-log-repeat 'time
3102 "Non-nil means record moving through the DONE state when triggering repeat.
3103 An auto-repeating task is immediately switched back to TODO when
3104 marked DONE. If you are not logging state changes (by adding \"@\"
3105 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3106 record a closing note, there will be no record of the task moving
3107 through DONE. This variable forces taking a note anyway.
3109 nil Don't force a record
3110 time Record a time stamp
3111 note Prompt for a note and add it with template `org-log-note-headings'
3113 This option can also be set with on a per-file-basis with
3115 #+STARTUP: nologrepeat
3116 #+STARTUP: logrepeat
3117 #+STARTUP: lognoterepeat
3119 You can have local logging settings for a subtree by setting the LOGGING
3120 property to one or more of these keywords."
3121 :group 'org-todo
3122 :group 'org-progress
3123 :type '(choice
3124 (const :tag "Don't force a record" nil)
3125 (const :tag "Force recording the DONE state" time)
3126 (const :tag "Force recording a note with the DONE state" note)))
3129 (defgroup org-priorities nil
3130 "Priorities in Org mode."
3131 :tag "Org Priorities"
3132 :group 'org-todo)
3134 (defcustom org-enable-priority-commands t
3135 "Non-nil means priority commands are active.
3136 When nil, these commands will be disabled, so that you never accidentally
3137 set a priority."
3138 :group 'org-priorities
3139 :type 'boolean)
3141 (defcustom org-highest-priority ?A
3142 "The highest priority of TODO items. A character like ?A, ?B etc.
3143 Must have a smaller ASCII number than `org-lowest-priority'."
3144 :group 'org-priorities
3145 :type 'character)
3147 (defcustom org-lowest-priority ?C
3148 "The lowest priority of TODO items. A character like ?A, ?B etc.
3149 Must have a larger ASCII number than `org-highest-priority'."
3150 :group 'org-priorities
3151 :type 'character)
3153 (defcustom org-default-priority ?B
3154 "The default priority of TODO items.
3155 This is the priority an item gets if no explicit priority is given.
3156 When starting to cycle on an empty priority the first step in the cycle
3157 depends on `org-priority-start-cycle-with-default'. The resulting first
3158 step priority must not exceed the range from `org-highest-priority' to
3159 `org-lowest-priority' which means that `org-default-priority' has to be
3160 in this range exclusive or inclusive the range boundaries. Else the
3161 first step refuses to set the default and the second will fall back
3162 to (depending on the command used) the highest or lowest priority."
3163 :group 'org-priorities
3164 :type 'character)
3166 (defcustom org-priority-start-cycle-with-default t
3167 "Non-nil means start with default priority when starting to cycle.
3168 When this is nil, the first step in the cycle will be (depending on the
3169 command used) one higher or lower than the default priority.
3170 See also `org-default-priority'."
3171 :group 'org-priorities
3172 :type 'boolean)
3174 (defcustom org-get-priority-function nil
3175 "Function to extract the priority from a string.
3176 The string is normally the headline. If this is nil Org computes the
3177 priority from the priority cookie like [#A] in the headline. It returns
3178 an integer, increasing by 1000 for each priority level.
3179 The user can set a different function here, which should take a string
3180 as an argument and return the numeric priority."
3181 :group 'org-priorities
3182 :version "24.1"
3183 :type '(choice
3184 (const nil)
3185 (function)))
3187 (defgroup org-time nil
3188 "Options concerning time stamps and deadlines in Org mode."
3189 :tag "Org Time"
3190 :group 'org)
3192 (defcustom org-time-stamp-rounding-minutes '(0 5)
3193 "Number of minutes to round time stamps to.
3194 \\<org-mode-map>\
3195 These are two values, the first applies when first creating a time stamp.
3196 The second applies when changing it with the commands `S-up' and `S-down'.
3197 When changing the time stamp, this means that it will change in steps
3198 of N minutes, as given by the second value.
3200 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3201 numbers should be factors of 60, so for example 5, 10, 15.
3203 When this is larger than 1, you can still force an exact time stamp by using
3204 a double prefix argument to a time stamp command like \
3205 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3206 and by using a prefix arg to `S-up/down' to specify the exact number
3207 of minutes to shift."
3208 :group 'org-time
3209 :get (lambda (var) ; Make sure both elements are there
3210 (if (integerp (default-value var))
3211 (list (default-value var) 5)
3212 (default-value var)))
3213 :type '(list
3214 (integer :tag "when inserting times")
3215 (integer :tag "when modifying times")))
3217 ;; Normalize old customizations of this variable.
3218 (when (integerp org-time-stamp-rounding-minutes)
3219 (setq org-time-stamp-rounding-minutes
3220 (list org-time-stamp-rounding-minutes
3221 org-time-stamp-rounding-minutes)))
3223 (defcustom org-display-custom-times nil
3224 "Non-nil means overlay custom formats over all time stamps.
3225 The formats are defined through the variable `org-time-stamp-custom-formats'.
3226 To turn this on on a per-file basis, insert anywhere in the file:
3227 #+STARTUP: customtime"
3228 :group 'org-time
3229 :set 'set-default
3230 :type 'sexp)
3231 (make-variable-buffer-local 'org-display-custom-times)
3233 (defcustom org-time-stamp-custom-formats
3234 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3235 "Custom formats for time stamps. See `format-time-string' for the syntax.
3236 These are overlaid over the default ISO format if the variable
3237 `org-display-custom-times' is set. Time like %H:%M should be at the
3238 end of the second format. The custom formats are also honored by export
3239 commands, if custom time display is turned on at the time of export."
3240 :group 'org-time
3241 :type 'sexp)
3243 (defun org-time-stamp-format (&optional long inactive)
3244 "Get the right format for a time string."
3245 (let ((f (if long (cdr org-time-stamp-formats)
3246 (car org-time-stamp-formats))))
3247 (if inactive
3248 (concat "[" (substring f 1 -1) "]")
3249 f)))
3251 (defcustom org-time-clocksum-format
3252 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3253 "The format string used when creating CLOCKSUM lines.
3254 This is also used when Org mode generates a time duration.
3256 The value can be a single format string containing two
3257 %-sequences, which will be filled with the number of hours and
3258 minutes in that order.
3260 Alternatively, the value can be a plist associating any of the
3261 keys :years, :months, :weeks, :days, :hours or :minutes with
3262 format strings. The time duration is formatted using only the
3263 time components that are needed and concatenating the results.
3264 If a time unit in absent, it falls back to the next smallest
3265 unit.
3267 The keys :require-years, :require-months, :require-days,
3268 :require-weeks, :require-hours, :require-minutes are also
3269 meaningful. A non-nil value for these keys indicates that the
3270 corresponding time component should always be included, even if
3271 its value is 0.
3274 For example,
3276 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3277 :require-minutes t)
3279 means durations longer than a day will be expressed in days,
3280 hours and minutes, and durations less than a day will always be
3281 expressed in hours and minutes (even for durations less than an
3282 hour).
3284 The value
3286 (:days \"%dd\" :minutes \"%dm\")
3288 means durations longer than a day will be expressed in days and
3289 minutes, and durations less than a day will be expressed entirely
3290 in minutes (even for durations longer than an hour)."
3291 :group 'org-time
3292 :group 'org-clock
3293 :version "24.4"
3294 :package-version '(Org . "8.0")
3295 :type '(choice (string :tag "Format string")
3296 (set :tag "Plist"
3297 (group :inline t (const :tag "Years" :years)
3298 (string :tag "Format string"))
3299 (group :inline t
3300 (const :tag "Always show years" :require-years)
3301 (const t))
3302 (group :inline t (const :tag "Months" :months)
3303 (string :tag "Format string"))
3304 (group :inline t
3305 (const :tag "Always show months" :require-months)
3306 (const t))
3307 (group :inline t (const :tag "Weeks" :weeks)
3308 (string :tag "Format string"))
3309 (group :inline t
3310 (const :tag "Always show weeks" :require-weeks)
3311 (const t))
3312 (group :inline t (const :tag "Days" :days)
3313 (string :tag "Format string"))
3314 (group :inline t
3315 (const :tag "Always show days" :require-days)
3316 (const t))
3317 (group :inline t (const :tag "Hours" :hours)
3318 (string :tag "Format string"))
3319 (group :inline t
3320 (const :tag "Always show hours" :require-hours)
3321 (const t))
3322 (group :inline t (const :tag "Minutes" :minutes)
3323 (string :tag "Format string"))
3324 (group :inline t
3325 (const :tag "Always show minutes" :require-minutes)
3326 (const t)))))
3328 (defcustom org-time-clocksum-use-fractional nil
3329 "When non-nil, `\\[org-clock-display]' uses fractional times.
3330 See `org-time-clocksum-format' for more on time clock formats."
3331 :group 'org-time
3332 :group 'org-clock
3333 :version "24.3"
3334 :type 'boolean)
3336 (defcustom org-time-clocksum-use-effort-durations nil
3337 "When non-nil, `\\[org-clock-display]' uses effort durations.
3338 E.g. by default, one day is considered to be a 8 hours effort,
3339 so a task that has been clocked for 16 hours will be displayed
3340 as during 2 days in the clock display or in the clocktable.
3342 See `org-effort-durations' on how to set effort durations
3343 and `org-time-clocksum-format' for more on time clock formats."
3344 :group 'org-time
3345 :group 'org-clock
3346 :version "24.4"
3347 :package-version '(Org . "8.0")
3348 :type 'boolean)
3350 (defcustom org-time-clocksum-fractional-format "%.2f"
3351 "The format string used when creating CLOCKSUM lines,
3352 or when Org mode generates a time duration, if
3353 `org-time-clocksum-use-fractional' is enabled.
3355 The value can be a single format string containing one
3356 %-sequence, which will be filled with the number of hours as
3357 a float.
3359 Alternatively, the value can be a plist associating any of the
3360 keys :years, :months, :weeks, :days, :hours or :minutes with
3361 a format string. The time duration is formatted using the
3362 largest time unit which gives a non-zero integer part. If all
3363 specified formats have zero integer part, the smallest time unit
3364 is used."
3365 :group 'org-time
3366 :type '(choice (string :tag "Format string")
3367 (set (group :inline t (const :tag "Years" :years)
3368 (string :tag "Format string"))
3369 (group :inline t (const :tag "Months" :months)
3370 (string :tag "Format string"))
3371 (group :inline t (const :tag "Weeks" :weeks)
3372 (string :tag "Format string"))
3373 (group :inline t (const :tag "Days" :days)
3374 (string :tag "Format string"))
3375 (group :inline t (const :tag "Hours" :hours)
3376 (string :tag "Format string"))
3377 (group :inline t (const :tag "Minutes" :minutes)
3378 (string :tag "Format string")))))
3380 (defcustom org-deadline-warning-days 14
3381 "Number of days before expiration during which a deadline becomes active.
3382 This variable governs the display in sparse trees and in the agenda.
3383 When 0 or negative, it means use this number (the absolute value of it)
3384 even if a deadline has a different individual lead time specified.
3386 Custom commands can set this variable in the options section."
3387 :group 'org-time
3388 :group 'org-agenda-daily/weekly
3389 :type 'integer)
3391 (defcustom org-scheduled-delay-days 0
3392 "Number of days before a scheduled item becomes active.
3393 This variable governs the display in sparse trees and in the agenda.
3394 The default value (i.e. 0) means: don't delay scheduled item.
3395 When negative, it means use this number (the absolute value of it)
3396 even if a scheduled item has a different individual delay time
3397 specified.
3399 Custom commands can set this variable in the options section."
3400 :group 'org-time
3401 :group 'org-agenda-daily/weekly
3402 :version "24.4"
3403 :package-version '(Org . "8.0")
3404 :type 'integer)
3406 (defcustom org-read-date-prefer-future t
3407 "Non-nil means assume future for incomplete date input from user.
3408 This affects the following situations:
3409 1. The user gives a month but not a year.
3410 For example, if it is April and you enter \"feb 2\", this will be read
3411 as Feb 2, *next* year. \"May 5\", however, will be this year.
3412 2. The user gives a day, but no month.
3413 For example, if today is the 15th, and you enter \"3\", Org will read
3414 this as the third of *next* month. However, if you enter \"17\",
3415 it will be considered as *this* month.
3417 If you set this variable to the symbol `time', then also the following
3418 will work:
3420 3. If the user gives a time.
3421 If the time is before now, it will be interpreted as tomorrow.
3423 Currently none of this works for ISO week specifications.
3425 When this option is nil, the current day, month and year will always be
3426 used as defaults.
3428 See also `org-agenda-jump-prefer-future'."
3429 :group 'org-time
3430 :type '(choice
3431 (const :tag "Never" nil)
3432 (const :tag "Check month and day" t)
3433 (const :tag "Check month, day, and time" time)))
3435 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3436 "Should the agenda jump command prefer the future for incomplete dates?
3437 The default is to do the same as configured in `org-read-date-prefer-future'.
3438 But you can also set a deviating value here.
3439 This may t or nil, or the symbol `org-read-date-prefer-future'."
3440 :group 'org-agenda
3441 :group 'org-time
3442 :version "24.1"
3443 :type '(choice
3444 (const :tag "Use org-read-date-prefer-future"
3445 org-read-date-prefer-future)
3446 (const :tag "Never" nil)
3447 (const :tag "Always" t)))
3449 (defcustom org-read-date-force-compatible-dates t
3450 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3452 Depending on the system Emacs is running on, certain dates cannot
3453 be represented with the type used internally to represent time.
3454 Dates between 1970-1-1 and 2038-1-1 can always be represented
3455 correctly. Some systems allow for earlier dates, some for later,
3456 some for both. One way to find out it to insert any date into an
3457 Org buffer, putting the cursor on the year and hitting S-up and
3458 S-down to test the range.
3460 When this variable is set to t, the date/time prompt will not let
3461 you specify dates outside the 1970-2037 range, so it is certain that
3462 these dates will work in whatever version of Emacs you are
3463 running, and also that you can move a file from one Emacs implementation
3464 to another. WHenever Org is forcing the year for you, it will display
3465 a message and beep.
3467 When this variable is nil, Org will check if the date is
3468 representable in the specific Emacs implementation you are using.
3469 If not, it will force a year, usually the current year, and beep
3470 to remind you. Currently this setting is not recommended because
3471 the likelihood that you will open your Org files in an Emacs that
3472 has limited date range is not negligible.
3474 A workaround for this problem is to use diary sexp dates for time
3475 stamps outside of this range."
3476 :group 'org-time
3477 :version "24.1"
3478 :type 'boolean)
3480 (defcustom org-read-date-display-live t
3481 "Non-nil means display current interpretation of date prompt live.
3482 This display will be in an overlay, in the minibuffer."
3483 :group 'org-time
3484 :type 'boolean)
3486 (defcustom org-read-date-popup-calendar t
3487 "Non-nil means pop up a calendar when prompting for a date.
3488 In the calendar, the date can be selected with mouse-1. However, the
3489 minibuffer will also be active, and you can simply enter the date as well.
3490 When nil, only the minibuffer will be available."
3491 :group 'org-time
3492 :type 'boolean)
3493 (defvaralias 'org-popup-calendar-for-date-prompt
3494 'org-read-date-popup-calendar)
3496 (defcustom org-extend-today-until 0
3497 "The hour when your day really ends. Must be an integer.
3498 This has influence for the following applications:
3499 - When switching the agenda to \"today\". It it is still earlier than
3500 the time given here, the day recognized as TODAY is actually yesterday.
3501 - When a date is read from the user and it is still before the time given
3502 here, the current date and time will be assumed to be yesterday, 23:59.
3503 Also, timestamps inserted in capture templates follow this rule.
3505 IMPORTANT: This is a feature whose implementation is and likely will
3506 remain incomplete. Really, it is only here because past midnight seems to
3507 be the favorite working time of John Wiegley :-)"
3508 :group 'org-time
3509 :type 'integer)
3511 (defcustom org-use-effective-time nil
3512 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3513 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3514 \"effective time\" of any timestamps between midnight and 8am will be
3515 23:59 of the previous day."
3516 :group 'org-time
3517 :version "24.1"
3518 :type 'boolean)
3520 (defcustom org-use-last-clock-out-time-as-effective-time nil
3521 "When non-nil, use the last clock out time for `org-todo'.
3522 Note that this option has precedence over the combined use of
3523 `org-use-effective-time' and `org-extend-today-until'."
3524 :group 'org-time
3525 :version "24.4"
3526 :package-version '(Org . "8.0")
3527 :type 'boolean)
3529 (defcustom org-edit-timestamp-down-means-later nil
3530 "Non-nil means S-down will increase the time in a time stamp.
3531 When nil, S-up will increase."
3532 :group 'org-time
3533 :type 'boolean)
3535 (defcustom org-calendar-follow-timestamp-change t
3536 "Non-nil means make the calendar window follow timestamp changes.
3537 When a timestamp is modified and the calendar window is visible, it will be
3538 moved to the new date."
3539 :group 'org-time
3540 :type 'boolean)
3542 (defgroup org-tags nil
3543 "Options concerning tags in Org mode."
3544 :tag "Org Tags"
3545 :group 'org)
3547 (defcustom org-tag-alist nil
3548 "Default tags available in Org files.
3550 The value of this variable is an alist. Associations either:
3552 (TAG)
3553 (TAG . SELECT)
3554 (SPECIAL)
3556 where TAG is a tag as a string, SELECT is a case-sensitive
3557 letter, used to select that tag through the fast tag selection
3558 interface, and SPECIAL is one of the following keywords:
3559 `:startgroup', `:startgrouptag', `:grouptags', `:engroup',
3560 `:endgrouptag' or `:newline'. These keywords are used to define
3561 a hierarchy of tags. See manual for details.
3563 When this variable is nil, Org mode bases tag input on what is
3564 already in the buffer. The value can be overridden locally by
3565 using a TAGS keyword, e.g.,
3567 #+TAGS: tag1 tag2
3569 See also `org-tag-persistent-alist' to sidestep this behavior."
3570 :group 'org-tags
3571 :type '(repeat
3572 (choice
3573 (cons (string :tag "Tag name")
3574 (character :tag "Access char"))
3575 (const :tag "Start radio group" (:startgroup))
3576 (const :tag "Start tag group, non distinct" (:startgrouptag))
3577 (const :tag "Group tags delimiter" (:grouptags))
3578 (const :tag "End radio group" (:endgroup))
3579 (const :tag "End tag group, non distinct" (:endgrouptag))
3580 (const :tag "New line" (:newline)))))
3582 (defcustom org-tag-persistent-alist nil
3583 "Tags always available in Org files.
3585 The value of this variable is an alist. Associations either:
3587 (TAG)
3588 (TAG . SELECT)
3589 (SPECIAL)
3591 where TAG is a tag as a string, SELECT is a character, used to
3592 select that tag through the fast tag selection interface, and
3593 SPECIAL is one of the following keywords: `:startgroup',
3594 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3595 `:newline'. These keywords are used to define a hierarchy of
3596 tags. See manual for details.
3598 Unlike to `org-tag-alist', tags defined in this variable do not
3599 depend on a local TAGS keyword. Instead, to disable these tags
3600 on a per-file basis, insert anywhere in the file:
3602 #+STARTUP: noptag"
3603 :group 'org-tags
3604 :type '(repeat
3605 (choice
3606 (cons (string :tag "Tag name")
3607 (character :tag "Access char"))
3608 (const :tag "Start radio group" (:startgroup))
3609 (const :tag "Start tag group, non distinct" (:startgrouptag))
3610 (const :tag "Group tags delimiter" (:grouptags))
3611 (const :tag "End radio group" (:endgroup))
3612 (const :tag "End tag group, non distinct" (:endgrouptag))
3613 (const :tag "New line" (:newline)))))
3615 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3616 "If non-nil, always offer completion for all tags of all agenda files.
3617 Instead of customizing this variable directly, you might want to
3618 set it locally for capture buffers, because there no list of
3619 tags in that file can be created dynamically (there are none).
3621 (add-hook \\='org-capture-mode-hook
3622 (lambda ()
3623 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3624 :group 'org-tags
3625 :version "24.1"
3626 :type 'boolean)
3628 (defvar org-file-tags nil
3629 "List of tags that can be inherited by all entries in the file.
3630 The tags will be inherited if the variable `org-use-tag-inheritance'
3631 says they should be.
3632 This variable is populated from #+FILETAGS lines.")
3634 (defcustom org-use-fast-tag-selection 'auto
3635 "Non-nil means use fast tag selection scheme.
3636 This is a special interface to select and deselect tags with single keys.
3637 When nil, fast selection is never used.
3638 When the symbol `auto', fast selection is used if and only if selection
3639 characters for tags have been configured, either through the variable
3640 `org-tag-alist' or through a #+TAGS line in the buffer.
3641 When t, fast selection is always used and selection keys are assigned
3642 automatically if necessary."
3643 :group 'org-tags
3644 :type '(choice
3645 (const :tag "Always" t)
3646 (const :tag "Never" nil)
3647 (const :tag "When selection characters are configured" auto)))
3649 (defcustom org-fast-tag-selection-single-key nil
3650 "Non-nil means fast tag selection exits after first change.
3651 When nil, you have to press RET to exit it.
3652 During fast tag selection, you can toggle this flag with `C-c'.
3653 This variable can also have the value `expert'. In this case, the window
3654 displaying the tags menu is not even shown, until you press C-c again."
3655 :group 'org-tags
3656 :type '(choice
3657 (const :tag "No" nil)
3658 (const :tag "Yes" t)
3659 (const :tag "Expert" expert)))
3661 (defvar org-fast-tag-selection-include-todo nil
3662 "Non-nil means fast tags selection interface will also offer TODO states.
3663 This is an undocumented feature, you should not rely on it.")
3665 (defcustom org-tags-column -77
3666 "The column to which tags should be indented in a headline.
3667 If this number is positive, it specifies the column. If it is negative,
3668 it means that the tags should be flushright to that column. For example,
3669 -80 works well for a normal 80 character screen.
3670 When 0, place tags directly after headline text, with only one space in
3671 between."
3672 :group 'org-tags
3673 :type 'integer)
3675 (defcustom org-auto-align-tags t
3676 "Non-nil keeps tags aligned when modifying headlines.
3677 Some operations (i.e. demoting) change the length of a headline and
3678 therefore shift the tags around. With this option turned on, after
3679 each such operation the tags are again aligned to `org-tags-column'."
3680 :group 'org-tags
3681 :type 'boolean)
3683 (defcustom org-use-tag-inheritance t
3684 "Non-nil means tags in levels apply also for sublevels.
3685 When nil, only the tags directly given in a specific line apply there.
3686 This may also be a list of tags that should be inherited, or a regexp that
3687 matches tags that should be inherited. Additional control is possible
3688 with the variable `org-tags-exclude-from-inheritance' which gives an
3689 explicit list of tags to be excluded from inheritance, even if the value of
3690 `org-use-tag-inheritance' would select it for inheritance.
3692 If this option is t, a match early-on in a tree can lead to a large
3693 number of matches in the subtree when constructing the agenda or creating
3694 a sparse tree. If you only want to see the first match in a tree during
3695 a search, check out the variable `org-tags-match-list-sublevels'."
3696 :group 'org-tags
3697 :type '(choice
3698 (const :tag "Not" nil)
3699 (const :tag "Always" t)
3700 (repeat :tag "Specific tags" (string :tag "Tag"))
3701 (regexp :tag "Tags matched by regexp")))
3703 (defcustom org-tags-exclude-from-inheritance nil
3704 "List of tags that should never be inherited.
3705 This is a way to exclude a few tags from inheritance. For way to do
3706 the opposite, to actively allow inheritance for selected tags,
3707 see the variable `org-use-tag-inheritance'."
3708 :group 'org-tags
3709 :type '(repeat (string :tag "Tag")))
3711 (defun org-tag-inherit-p (tag)
3712 "Check if TAG is one that should be inherited."
3713 (cond
3714 ((member tag org-tags-exclude-from-inheritance) nil)
3715 ((eq org-use-tag-inheritance t) t)
3716 ((not org-use-tag-inheritance) nil)
3717 ((stringp org-use-tag-inheritance)
3718 (string-match org-use-tag-inheritance tag))
3719 ((listp org-use-tag-inheritance)
3720 (member tag org-use-tag-inheritance))
3721 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3723 (defcustom org-tags-match-list-sublevels t
3724 "Non-nil means list also sublevels of headlines matching a search.
3725 This variable applies to tags/property searches, and also to stuck
3726 projects because this search is based on a tags match as well.
3728 When set to the symbol `indented', sublevels are indented with
3729 leading dots.
3731 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3732 the sublevels of a headline matching a tag search often also match
3733 the same search. Listing all of them can create very long lists.
3734 Setting this variable to nil causes subtrees of a match to be skipped.
3736 This variable is semi-obsolete and probably should always be true. It
3737 is better to limit inheritance to certain tags using the variables
3738 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3739 :group 'org-tags
3740 :type '(choice
3741 (const :tag "No, don't list them" nil)
3742 (const :tag "Yes, do list them" t)
3743 (const :tag "List them, indented with leading dots" indented)))
3745 (defcustom org-tags-sort-function nil
3746 "When set, tags are sorted using this function as a comparator."
3747 :group 'org-tags
3748 :type '(choice
3749 (const :tag "No sorting" nil)
3750 (const :tag "Alphabetical" string<)
3751 (const :tag "Reverse alphabetical" string>)
3752 (function :tag "Custom function" nil)))
3754 (defvar org-tags-history nil
3755 "History of minibuffer reads for tags.")
3756 (defvar org-last-tags-completion-table nil
3757 "The last used completion table for tags.")
3758 (defvar org-after-tags-change-hook nil
3759 "Hook that is run after the tags in a line have changed.")
3761 (defgroup org-properties nil
3762 "Options concerning properties in Org mode."
3763 :tag "Org Properties"
3764 :group 'org)
3766 (defcustom org-property-format "%-10s %s"
3767 "How property key/value pairs should be formatted by `indent-line'.
3768 When `indent-line' hits a property definition, it will format the line
3769 according to this format, mainly to make sure that the values are
3770 lined-up with respect to each other."
3771 :group 'org-properties
3772 :type 'string)
3774 (defcustom org-properties-postprocess-alist nil
3775 "Alist of properties and functions to adjust inserted values.
3776 Elements of this alist must be of the form
3778 ([string] [function])
3780 where [string] must be a property name and [function] must be a
3781 lambda expression: this lambda expression must take one argument,
3782 the value to adjust, and return the new value as a string.
3784 For example, this element will allow the property \"Remaining\"
3785 to be updated wrt the relation between the \"Effort\" property
3786 and the clock summary:
3788 ((\"Remaining\" (lambda(value)
3789 (let ((clocksum (org-clock-sum-current-item))
3790 (effort (org-duration-string-to-minutes
3791 (org-entry-get (point) \"Effort\"))))
3792 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3793 :group 'org-properties
3794 :version "24.1"
3795 :type '(alist :key-type (string :tag "Property")
3796 :value-type (function :tag "Function")))
3798 (defcustom org-use-property-inheritance nil
3799 "Non-nil means properties apply also for sublevels.
3801 This setting is chiefly used during property searches. Turning it on can
3802 cause significant overhead when doing a search, which is why it is not
3803 on by default.
3805 When nil, only the properties directly given in the current entry count.
3806 When t, every property is inherited. The value may also be a list of
3807 properties that should have inheritance, or a regular expression matching
3808 properties that should be inherited.
3810 However, note that some special properties use inheritance under special
3811 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3812 and the properties ending in \"_ALL\" when they are used as descriptor
3813 for valid values of a property.
3815 Note for programmers:
3816 When querying an entry with `org-entry-get', you can control if inheritance
3817 should be used. By default, `org-entry-get' looks only at the local
3818 properties. You can request inheritance by setting the inherit argument
3819 to t (to force inheritance) or to `selective' (to respect the setting
3820 in this variable)."
3821 :group 'org-properties
3822 :type '(choice
3823 (const :tag "Not" nil)
3824 (const :tag "Always" t)
3825 (repeat :tag "Specific properties" (string :tag "Property"))
3826 (regexp :tag "Properties matched by regexp")))
3828 (defun org-property-inherit-p (property)
3829 "Check if PROPERTY is one that should be inherited."
3830 (cond
3831 ((eq org-use-property-inheritance t) t)
3832 ((not org-use-property-inheritance) nil)
3833 ((stringp org-use-property-inheritance)
3834 (string-match org-use-property-inheritance property))
3835 ((listp org-use-property-inheritance)
3836 (member property org-use-property-inheritance))
3837 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3839 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3840 "The default column format, if no other format has been defined.
3841 This variable can be set on the per-file basis by inserting a line
3843 #+COLUMNS: %25ITEM ....."
3844 :group 'org-properties
3845 :type 'string)
3847 (defcustom org-columns-ellipses ".."
3848 "The ellipses to be used when a field in column view is truncated.
3849 When this is the empty string, as many characters as possible are shown,
3850 but then there will be no visual indication that the field has been truncated.
3851 When this is a string of length N, the last N characters of a truncated
3852 field are replaced by this string. If the column is narrower than the
3853 ellipses string, only part of the ellipses string will be shown."
3854 :group 'org-properties
3855 :type 'string)
3857 (defconst org-global-properties-fixed
3858 '(("VISIBILITY_ALL" . "folded children content all")
3859 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3860 "List of property/value pairs that can be inherited by any entry.
3862 These are fixed values, for the preset properties. The user variable
3863 that can be used to add to this list is `org-global-properties'.
3865 The entries in this list are cons cells where the car is a property
3866 name and cdr is a string with the value. If the value represents
3867 multiple items like an \"_ALL\" property, separate the items by
3868 spaces.")
3870 (defcustom org-global-properties nil
3871 "List of property/value pairs that can be inherited by any entry.
3873 This list will be combined with the constant `org-global-properties-fixed'.
3875 The entries in this list are cons cells where the car is a property
3876 name and cdr is a string with the value.
3878 You can set buffer-local values for the same purpose in the variable
3879 `org-file-properties' this by adding lines like
3881 #+PROPERTY: NAME VALUE"
3882 :group 'org-properties
3883 :type '(repeat
3884 (cons (string :tag "Property")
3885 (string :tag "Value"))))
3887 (defvar-local org-file-properties nil
3888 "List of property/value pairs that can be inherited by any entry.
3889 Valid for the current buffer.
3890 This variable is populated from #+PROPERTY lines.")
3892 (defgroup org-agenda nil
3893 "Options concerning agenda views in Org mode."
3894 :tag "Org Agenda"
3895 :group 'org)
3897 (defvar-local org-category nil
3898 "Variable used by org files to set a category for agenda display.
3899 Such files should use a file variable to set it, for example
3901 # -*- mode: org; org-category: \"ELisp\"
3903 or contain a special line
3905 #+CATEGORY: ELisp
3907 If the file does not specify a category, then file's base name
3908 is used instead.")
3909 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3911 (defcustom org-agenda-files nil
3912 "The files to be used for agenda display.
3914 If an entry is a directory, all files in that directory that are matched
3915 by `org-agenda-file-regexp' will be part of the file list.
3917 If the value of the variable is not a list but a single file name, then
3918 the list of agenda files is actually stored and maintained in that file,
3919 one agenda file per line. In this file paths can be given relative to
3920 `org-directory'. Tilde expansion and environment variable substitution
3921 are also made.
3923 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3924 and removed with `\\[org-remove-file]'."
3925 :group 'org-agenda
3926 :type '(choice
3927 (repeat :tag "List of files and directories" file)
3928 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3930 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3931 "Regular expression to match files for `org-agenda-files'.
3932 If any element in the list in that variable contains a directory instead
3933 of a normal file, all files in that directory that are matched by this
3934 regular expression will be included."
3935 :group 'org-agenda
3936 :type 'regexp)
3938 (defcustom org-agenda-text-search-extra-files nil
3939 "List of extra files to be searched by text search commands.
3940 These files will be searched in addition to the agenda files by the
3941 commands `org-search-view' (`\\[org-agenda] s') \
3942 and `org-occur-in-agenda-files'.
3943 Note that these files will only be searched for text search commands,
3944 not for the other agenda views like todo lists, tag searches or the weekly
3945 agenda. This variable is intended to list notes and possibly archive files
3946 that should also be searched by these two commands.
3947 In fact, if the first element in the list is the symbol `agenda-archives',
3948 then all archive files of all agenda files will be added to the search
3949 scope."
3950 :group 'org-agenda
3951 :type '(set :greedy t
3952 (const :tag "Agenda Archives" agenda-archives)
3953 (repeat :inline t (file))))
3955 (defvaralias 'org-agenda-multi-occur-extra-files
3956 'org-agenda-text-search-extra-files)
3958 (defcustom org-agenda-skip-unavailable-files nil
3959 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3960 A nil value means to remove them, after a query, from the list."
3961 :group 'org-agenda
3962 :type 'boolean)
3964 (defcustom org-calendar-to-agenda-key [?c]
3965 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3966 The command `org-calendar-goto-agenda' will be bound to this key. The
3967 default is the character `c' because then `c' can be used to switch back and
3968 forth between agenda and calendar."
3969 :group 'org-agenda
3970 :type 'sexp)
3972 (defcustom org-calendar-insert-diary-entry-key [?i]
3973 "The key to be installed in `calendar-mode-map' for adding diary entries.
3974 This option is irrelevant until `org-agenda-diary-file' has been configured
3975 to point to an Org file. When that is the case, the command
3976 `org-agenda-diary-entry' will be bound to the key given here, by default
3977 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3978 if you want to continue doing this, you need to change this to a different
3979 key."
3980 :group 'org-agenda
3981 :type 'sexp)
3983 (defcustom org-agenda-diary-file 'diary-file
3984 "File to which to add new entries with the `i' key in agenda and calendar.
3985 When this is the symbol `diary-file', the functionality in the Emacs
3986 calendar will be used to add entries to the `diary-file'. But when this
3987 points to a file, `org-agenda-diary-entry' will be used instead."
3988 :group 'org-agenda
3989 :type '(choice
3990 (const :tag "The standard Emacs diary file" diary-file)
3991 (file :tag "Special Org file diary entries")))
3993 (eval-after-load "calendar"
3994 '(progn
3995 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3996 'org-calendar-goto-agenda)
3997 (add-hook 'calendar-mode-hook
3998 (lambda ()
3999 (unless (eq org-agenda-diary-file 'diary-file)
4000 (define-key calendar-mode-map
4001 org-calendar-insert-diary-entry-key
4002 'org-agenda-diary-entry))))))
4004 (defgroup org-latex nil
4005 "Options for embedding LaTeX code into Org mode."
4006 :tag "Org LaTeX"
4007 :group 'org)
4009 (defcustom org-format-latex-options
4010 '(:foreground default :background default :scale 1.0
4011 :html-foreground "Black" :html-background "Transparent"
4012 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
4013 "Options for creating images from LaTeX fragments.
4014 This is a property list with the following properties:
4015 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
4016 `default' means use the foreground of the default face.
4017 `auto' means use the foreground from the text face.
4018 :background the background color, or \"Transparent\".
4019 `default' means use the background of the default face.
4020 `auto' means use the background from the text face.
4021 :scale a scaling factor for the size of the images, to get more pixels
4022 :html-foreground, :html-background, :html-scale
4023 the same numbers for HTML export.
4024 :matchers a list indicating which matchers should be used to
4025 find LaTeX fragments. Valid members of this list are:
4026 \"begin\" find environments
4027 \"$1\" find single characters surrounded by $.$
4028 \"$\" find math expressions surrounded by $...$
4029 \"$$\" find math expressions surrounded by $$....$$
4030 \"\\(\" find math expressions surrounded by \\(...\\)
4031 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4032 :group 'org-latex
4033 :type 'plist)
4035 (defcustom org-format-latex-signal-error t
4036 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4037 When nil, just push out a message."
4038 :group 'org-latex
4039 :version "24.1"
4040 :type 'boolean)
4042 (defcustom org-latex-to-mathml-jar-file nil
4043 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4044 Use this to specify additional executable file say a jar file.
4046 When using MathToWeb as the converter, specify the full-path to
4047 your mathtoweb.jar file."
4048 :group 'org-latex
4049 :version "24.1"
4050 :type '(choice
4051 (const :tag "None" nil)
4052 (file :tag "JAR file" :must-match t)))
4054 (defcustom org-latex-to-mathml-convert-command nil
4055 "Command to convert LaTeX fragments to MathML.
4056 Replace format-specifiers in the command as noted below and use
4057 `shell-command' to convert LaTeX to MathML.
4058 %j: Executable file in fully expanded form as specified by
4059 `org-latex-to-mathml-jar-file'.
4060 %I: Input LaTeX file in fully expanded form.
4061 %i: The latex fragment to be converted.
4062 %o: Output MathML file.
4064 This command is used by `org-create-math-formula'.
4066 When using MathToWeb as the converter, set this option to
4067 \"java -jar %j -unicode -force -df %o %I\".
4069 When using LaTeXML set this option to
4070 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4071 :group 'org-latex
4072 :version "24.1"
4073 :type '(choice
4074 (const :tag "None" nil)
4075 (string :tag "\nShell command")))
4077 (defcustom org-preview-latex-default-process 'dvipng
4078 "The default process to convert LaTeX fragments to image files.
4079 All available processes and theirs documents can be found in
4080 `org-preview-latex-process-alist', which see."
4081 :group 'org-latex
4082 :version "25.2"
4083 :package-version '(Org . "9.0")
4084 :type 'symbol)
4086 (defcustom org-preview-latex-process-alist
4087 '((dvipng
4088 :programs ("latex" "dvipng")
4089 :description "dvi > png"
4090 :message "you need to install the programs: latex and dvipng."
4091 :image-input-type "dvi"
4092 :image-output-type "png"
4093 :image-size-adjust (1.0 . 1.0)
4094 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4095 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %o%b.png %f"))
4096 (dvisvgm
4097 :programs ("latex" "dvisvgm")
4098 :description "dvi > svg"
4099 :message "you need to install the programs: latex and dvisvgm."
4100 :use-xcolor t
4101 :image-input-type "dvi"
4102 :image-output-type "svg"
4103 :image-size-adjust (1.7 . 1.5)
4104 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4105 :image-converter ("dvisvgm %f -n -b min -c %S -o %o%b.svg"))
4106 (imagemagick
4107 :programs ("latex" "convert")
4108 :description "pdf > png"
4109 :message "you need to install the programs: latex and imagemagick."
4110 :use-xcolor t
4111 :image-input-type "pdf"
4112 :image-output-type "png"
4113 :image-size-adjust (1.0 . 1.0)
4114 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4115 :image-converter
4116 ("convert -density %D -trim -antialias %f -quality 100 %o%b.png")))
4117 "Definitions of external processes for LaTeX previewing.
4118 Org mode can use some external commands to generate TeX snippet's images for
4119 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4120 `org-create-formula-image' how to call them.
4122 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4123 PROPERTIES accepts the following attributes:
4125 :programs list of strings, required programs.
4126 :description string, describe the process.
4127 :message string, message it when required programs cannot be found.
4128 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4129 :image-output-type string, output file type of image converter (e.g., \"png\").
4130 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4131 deal with background and foreground color of image.
4132 Otherwise, dvipng style background and foregroud color
4133 format are generated. You may then refer to them in
4134 command options with \"%F\" and \"%B\".
4135 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4136 image size showed in buffer and the cdr element is for
4137 HTML file. This option is only useful for process
4138 developers, users should use variable
4139 `org-format-latex-options' instead.
4140 :post-clean list of strings, files matched are to be cleaned up once
4141 the image is generated. When nil, the files with \".dvi\",
4142 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4143 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4144 be cleaned up.
4145 :latex-header list of strings, the LaTeX header of the snippet file.
4146 When nil, the fallback value is used instead, which is
4147 controlled by `org-format-latex-header',
4148 `org-latex-default-packages-alist' and
4149 `org-latex-packages-alist', which see.
4150 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4151 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4152 replaced with values defined below.
4153 :image-converter list of image converter commands strings. Each of them is
4154 given to the shell and supports any of the following
4155 place-holders defined below.
4157 Place-holders used by `:image-converter' and `:latex-compiler':
4159 %f input file name.
4160 %b base name of input file.
4161 %o base directory of input file.
4163 Place-holders only used by `:image-converter':
4165 %F foreground of image
4166 %B background of image
4167 %D dpi, which is used to adjust image size by some processing commands.
4168 %S the image size scale ratio, which is used to adjust image size by some
4169 processing commands."
4170 :group 'org-latex
4171 :version "25.2"
4172 :package-version '(Org . "9.0")
4173 :type '(alist :tag "LaTeX to image backends"
4174 :value-type (plist)))
4176 (defcustom org-preview-latex-image-directory "ltximg/"
4177 "Path to store latex preview images.
4178 A relative path here creates many directories relative to the
4179 processed org files paths. An absolute path puts all preview
4180 images at the same place."
4181 :group 'org-latex
4182 :version "25.2"
4183 :package-version '(Org . "9.0")
4184 :type 'string)
4186 (defun org-format-latex-mathml-available-p ()
4187 "Return t if `org-latex-to-mathml-convert-command' is usable."
4188 (save-match-data
4189 (when (and (boundp 'org-latex-to-mathml-convert-command)
4190 org-latex-to-mathml-convert-command)
4191 (let ((executable (car (split-string
4192 org-latex-to-mathml-convert-command))))
4193 (when (executable-find executable)
4194 (if (string-match
4195 "%j" org-latex-to-mathml-convert-command)
4196 (file-readable-p org-latex-to-mathml-jar-file)
4197 t))))))
4199 (defcustom org-format-latex-header "\\documentclass{article}
4200 \\usepackage[usenames]{color}
4201 \[PACKAGES]
4202 \[DEFAULT-PACKAGES]
4203 \\pagestyle{empty} % do not remove
4204 % The settings below are copied from fullpage.sty
4205 \\setlength{\\textwidth}{\\paperwidth}
4206 \\addtolength{\\textwidth}{-3cm}
4207 \\setlength{\\oddsidemargin}{1.5cm}
4208 \\addtolength{\\oddsidemargin}{-2.54cm}
4209 \\setlength{\\evensidemargin}{\\oddsidemargin}
4210 \\setlength{\\textheight}{\\paperheight}
4211 \\addtolength{\\textheight}{-\\headheight}
4212 \\addtolength{\\textheight}{-\\headsep}
4213 \\addtolength{\\textheight}{-\\footskip}
4214 \\addtolength{\\textheight}{-3cm}
4215 \\setlength{\\topmargin}{1.5cm}
4216 \\addtolength{\\topmargin}{-2.54cm}"
4217 "The document header used for processing LaTeX fragments.
4218 It is imperative that this header make sure that no page number
4219 appears on the page. The package defined in the variables
4220 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4221 will either replace the placeholder \"[PACKAGES]\" in this
4222 header, or they will be appended."
4223 :group 'org-latex
4224 :type 'string)
4226 (defun org-set-packages-alist (var val)
4227 "Set the packages alist and make sure it has 3 elements per entry."
4228 (set var (mapcar (lambda (x)
4229 (if (and (consp x) (= (length x) 2))
4230 (list (car x) (nth 1 x) t)
4232 val)))
4234 (defun org-get-packages-alist (var)
4235 "Get the packages alist and make sure it has 3 elements per entry."
4236 (mapcar (lambda (x)
4237 (if (and (consp x) (= (length x) 2))
4238 (list (car x) (nth 1 x) t)
4240 (default-value var)))
4242 (defcustom org-latex-default-packages-alist
4243 '(("AUTO" "inputenc" t ("pdflatex"))
4244 ("T1" "fontenc" t ("pdflatex"))
4245 ("" "graphicx" t)
4246 ("" "grffile" t)
4247 ("" "longtable" nil)
4248 ("" "wrapfig" nil)
4249 ("" "rotating" nil)
4250 ("normalem" "ulem" t)
4251 ("" "amsmath" t)
4252 ("" "textcomp" t)
4253 ("" "amssymb" t)
4254 ("" "capt-of" nil)
4255 ("" "hyperref" nil))
4256 "Alist of default packages to be inserted in the header.
4258 Change this only if one of the packages here causes an
4259 incompatibility with another package you are using.
4261 The packages in this list are needed by one part or another of
4262 Org mode to function properly:
4264 - inputenc, fontenc: for basic font and character selection
4265 - graphicx: for including images
4266 - grffile: allow periods and spaces in graphics file names
4267 - longtable: For multipage tables
4268 - wrapfig: for figure placement
4269 - rotating: for sideways figures and tables
4270 - ulem: for underline and strike-through
4271 - amsmath: for subscript and superscript and math environments
4272 - textcomp, amssymb: for various symbols used
4273 for interpreting the entities in `org-entities'. You can skip
4274 some of these packages if you don't use any of their symbols.
4275 - capt-of: for captions outside of floats
4276 - hyperref: for cross references
4278 Therefore you should not modify this variable unless you know
4279 what you are doing. The one reason to change it anyway is that
4280 you might be loading some other package that conflicts with one
4281 of the default packages. Each element is either a cell or
4282 a string.
4284 A cell is of the format
4286 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4288 If SNIPPET-FLAG is non-nil, the package also needs to be included
4289 when compiling LaTeX snippets into images for inclusion into
4290 non-LaTeX output. COMPILERS is a list of compilers that should
4291 include the package, see `org-latex-compiler'. If the document
4292 compiler is not in the list, and the list is non-nil, the package
4293 will not be inserted in the final document.
4295 A string will be inserted as-is in the header of the document."
4296 :group 'org-latex
4297 :group 'org-export-latex
4298 :set 'org-set-packages-alist
4299 :get 'org-get-packages-alist
4300 :version "25.2"
4301 :package-version '(Org . "8.3")
4302 :type '(repeat
4303 (choice
4304 (list :tag "options/package pair"
4305 (string :tag "options")
4306 (string :tag "package")
4307 (boolean :tag "Snippet"))
4308 (string :tag "A line of LaTeX"))))
4310 (defcustom org-latex-packages-alist nil
4311 "Alist of packages to be inserted in every LaTeX header.
4313 These will be inserted after `org-latex-default-packages-alist'.
4314 Each element is either a cell or a string.
4316 A cell is of the format:
4318 (\"options\" \"package\" SNIPPET-FLAG)
4320 SNIPPET-FLAG, when non-nil, indicates that this package is also
4321 needed when turning LaTeX snippets into images for inclusion into
4322 non-LaTeX output.
4324 A string will be inserted as-is in the header of the document.
4326 Make sure that you only list packages here which:
4328 - you want in every file;
4329 - do not conflict with the setup in `org-format-latex-header';
4330 - do not conflict with the default packages in
4331 `org-latex-default-packages-alist'."
4332 :group 'org-latex
4333 :group 'org-export-latex
4334 :set 'org-set-packages-alist
4335 :get 'org-get-packages-alist
4336 :type '(repeat
4337 (choice
4338 (list :tag "options/package pair"
4339 (string :tag "options")
4340 (string :tag "package")
4341 (boolean :tag "Snippet"))
4342 (string :tag "A line of LaTeX"))))
4344 (defgroup org-appearance nil
4345 "Settings for Org mode appearance."
4346 :tag "Org Appearance"
4347 :group 'org)
4349 (defcustom org-level-color-stars-only nil
4350 "Non-nil means fontify only the stars in each headline.
4351 When nil, the entire headline is fontified.
4352 Changing it requires restart of `font-lock-mode' to become effective
4353 also in regions already fontified."
4354 :group 'org-appearance
4355 :type 'boolean)
4357 (defcustom org-hide-leading-stars nil
4358 "Non-nil means hide the first N-1 stars in a headline.
4359 This works by using the face `org-hide' for these stars. This
4360 face is white for a light background, and black for a dark
4361 background. You may have to customize the face `org-hide' to
4362 make this work.
4363 Changing it requires restart of `font-lock-mode' to become effective
4364 also in regions already fontified.
4365 You may also set this on a per-file basis by adding one of the following
4366 lines to the buffer:
4368 #+STARTUP: hidestars
4369 #+STARTUP: showstars"
4370 :group 'org-appearance
4371 :type 'boolean)
4373 (defcustom org-hidden-keywords nil
4374 "List of symbols corresponding to keywords to be hidden the org buffer.
4375 For example, a value \\='(title) for this list will make the document's title
4376 appear in the buffer without the initial #+TITLE: keyword."
4377 :group 'org-appearance
4378 :version "24.1"
4379 :type '(set (const :tag "#+AUTHOR" author)
4380 (const :tag "#+DATE" date)
4381 (const :tag "#+EMAIL" email)
4382 (const :tag "#+TITLE" title)))
4384 (defcustom org-custom-properties nil
4385 "List of properties (as strings) with a special meaning.
4386 The default use of these custom properties is to let the user
4387 hide them with `org-toggle-custom-properties-visibility'."
4388 :group 'org-properties
4389 :group 'org-appearance
4390 :version "24.3"
4391 :type '(repeat (string :tag "Property Name")))
4393 (defcustom org-fontify-done-headline nil
4394 "Non-nil means change the face of a headline if it is marked DONE.
4395 Normally, only the TODO/DONE keyword indicates the state of a headline.
4396 When this is non-nil, the headline after the keyword is set to the
4397 `org-headline-done' as an additional indication."
4398 :group 'org-appearance
4399 :type 'boolean)
4401 (defcustom org-fontify-emphasized-text t
4402 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4403 Changing this variable requires a restart of Emacs to take effect."
4404 :group 'org-appearance
4405 :type 'boolean)
4407 (defcustom org-fontify-whole-heading-line nil
4408 "Non-nil means fontify the whole line for headings.
4409 This is useful when setting a background color for the
4410 org-level-* faces."
4411 :group 'org-appearance
4412 :type 'boolean)
4414 (defcustom org-highlight-latex-and-related nil
4415 "Non-nil means highlight LaTeX related syntax in the buffer.
4416 When non nil, the value should be a list containing any of the
4417 following symbols:
4418 `latex' Highlight LaTeX snippets and environments.
4419 `script' Highlight subscript and superscript.
4420 `entities' Highlight entities."
4421 :group 'org-appearance
4422 :version "24.4"
4423 :package-version '(Org . "8.0")
4424 :type '(choice
4425 (const :tag "No highlighting" nil)
4426 (set :greedy t :tag "Highlight"
4427 (const :tag "LaTeX snippets and environments" latex)
4428 (const :tag "Subscript and superscript" script)
4429 (const :tag "Entities" entities))))
4431 (defcustom org-hide-emphasis-markers nil
4432 "Non-nil mean font-lock should hide the emphasis marker characters."
4433 :group 'org-appearance
4434 :type 'boolean)
4436 (defcustom org-hide-macro-markers nil
4437 "Non-nil mean font-lock should hide the brackets marking macro calls."
4438 :group 'org-appearance
4439 :type 'boolean)
4441 (defcustom org-pretty-entities nil
4442 "Non-nil means show entities as UTF8 characters.
4443 When nil, the \\name form remains in the buffer."
4444 :group 'org-appearance
4445 :version "24.1"
4446 :type 'boolean)
4448 (defcustom org-pretty-entities-include-sub-superscripts t
4449 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4450 :group 'org-appearance
4451 :version "24.1"
4452 :type 'boolean)
4454 (defvar org-emph-re nil
4455 "Regular expression for matching emphasis.
4456 After a match, the match groups contain these elements:
4457 0 The match of the full regular expression, including the characters
4458 before and after the proper match
4459 1 The character before the proper match, or empty at beginning of line
4460 2 The proper match, including the leading and trailing markers
4461 3 The leading marker like * or /, indicating the type of highlighting
4462 4 The text between the emphasis markers, not including the markers
4463 5 The character after the match, empty at the end of a line")
4464 (defvar org-verbatim-re nil
4465 "Regular expression for matching verbatim text.")
4466 (defvar org-emphasis-regexp-components) ; defined just below
4467 (defvar org-emphasis-alist) ; defined just below
4468 (defun org-set-emph-re (var val)
4469 "Set variable and compute the emphasis regular expression."
4470 (set var val)
4471 (when (and (boundp 'org-emphasis-alist)
4472 (boundp 'org-emphasis-regexp-components)
4473 org-emphasis-alist org-emphasis-regexp-components)
4474 (let* ((e org-emphasis-regexp-components)
4475 (pre (car e))
4476 (post (nth 1 e))
4477 (border (nth 2 e))
4478 (body (nth 3 e))
4479 (nl (nth 4 e))
4480 (body1 (concat body "*?"))
4481 (markers (mapconcat 'car org-emphasis-alist ""))
4482 (vmarkers (mapconcat
4483 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4484 org-emphasis-alist "")))
4485 ;; make sure special characters appear at the right position in the class
4486 (if (string-match "\\^" markers)
4487 (setq markers (concat (replace-match "" t t markers) "^")))
4488 (if (string-match "-" markers)
4489 (setq markers (concat (replace-match "" t t markers) "-")))
4490 (if (string-match "\\^" vmarkers)
4491 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4492 (if (string-match "-" vmarkers)
4493 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4494 (if (> nl 0)
4495 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4496 (int-to-string nl) "\\}")))
4497 ;; Make the regexp
4498 (setq org-emph-re
4499 (concat "\\([" pre "]\\|^\\)"
4500 "\\("
4501 "\\([" markers "]\\)"
4502 "\\("
4503 "[^" border "]\\|"
4504 "[^" border "]"
4505 body1
4506 "[^" border "]"
4507 "\\)"
4508 "\\3\\)"
4509 "\\([" post "]\\|$\\)"))
4510 (setq org-verbatim-re
4511 (concat "\\([" pre "]\\|^\\)"
4512 "\\("
4513 "\\([" vmarkers "]\\)"
4514 "\\("
4515 "[^" border "]\\|"
4516 "[^" border "]"
4517 body1
4518 "[^" border "]"
4519 "\\)"
4520 "\\3\\)"
4521 "\\([" post "]\\|$\\)")))))
4523 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4524 ;; set this option proved cumbersome. See this message/thread:
4525 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4526 (defvar org-emphasis-regexp-components
4527 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4528 "Components used to build the regular expression for emphasis.
4529 This is a list with five entries. Terminology: In an emphasis string
4530 like \" *strong word* \", we call the initial space PREMATCH, the final
4531 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4532 and \"trong wor\" is the body. The different components in this variable
4533 specify what is allowed/forbidden in each part:
4535 pre Chars allowed as prematch. Beginning of line will be allowed too.
4536 post Chars allowed as postmatch. End of line will be allowed too.
4537 border The chars *forbidden* as border characters.
4538 body-regexp A regexp like \".\" to match a body character. Don't use
4539 non-shy groups here, and don't allow newline here.
4540 newline The maximum number of newlines allowed in an emphasis exp.
4542 You need to reload Org or to restart Emacs after customizing this.")
4544 (defcustom org-emphasis-alist
4545 '(("*" bold)
4546 ("/" italic)
4547 ("_" underline)
4548 ("=" org-verbatim verbatim)
4549 ("~" org-code verbatim)
4550 ("+" (:strike-through t)))
4551 "Alist of characters and faces to emphasize text.
4552 Text starting and ending with a special character will be emphasized,
4553 for example *bold*, _underlined_ and /italic/. This variable sets the
4554 marker characters and the face to be used by font-lock for highlighting
4555 in Org buffers.
4557 You need to reload Org or to restart Emacs after customizing this."
4558 :group 'org-appearance
4559 :set 'org-set-emph-re
4560 :version "24.4"
4561 :package-version '(Org . "8.0")
4562 :type '(repeat
4563 (list
4564 (string :tag "Marker character")
4565 (choice
4566 (face :tag "Font-lock-face")
4567 (plist :tag "Face property list"))
4568 (option (const verbatim)))))
4570 (defvar org-protecting-blocks '("src" "example" "export")
4571 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4572 This is needed for font-lock setup.")
4574 ;;; Functions and variables from their packages
4575 ;; Declared here to avoid compiler warnings
4576 (defvar mark-active)
4578 ;; Various packages
4579 (declare-function calc-eval "calc" (str &optional separator &rest args))
4580 (declare-function calendar-forward-day "cal-move" (arg))
4581 (declare-function calendar-goto-date "cal-move" (date))
4582 (declare-function calendar-goto-today "cal-move" ())
4583 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4584 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4585 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4586 (declare-function cdlatex-tab "ext:cdlatex" ())
4587 (declare-function dired-get-filename
4588 "dired"
4589 (&optional localp no-error-if-not-filep))
4590 (declare-function iswitchb-read-buffer
4591 "iswitchb"
4592 (prompt &optional
4593 default require-match _predicate start matches-set))
4594 (declare-function org-agenda-change-all-lines
4595 "org-agenda"
4596 (newhead hdmarker &optional fixface just-this))
4597 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4598 "org-agenda"
4599 (&optional end))
4600 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4601 (declare-function org-agenda-format-item
4602 "org-agenda"
4603 (extra txt &optional level category tags dotime
4604 remove-re habitp))
4605 (declare-function org-agenda-maybe-redo "org-agenda" ())
4606 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4607 (declare-function org-agenda-save-markers-for-cut-and-paste
4608 "org-agenda"
4609 (beg end))
4610 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4611 (declare-function org-agenda-skip "org-agenda" ())
4612 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4613 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4614 (declare-function org-indent-mode "org-indent" (&optional arg))
4615 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4616 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4617 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4618 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4619 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4620 (declare-function parse-time-string "parse-time" (string))
4621 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4623 (defvar align-mode-rules-list)
4624 (defvar calc-embedded-close-formula)
4625 (defvar calc-embedded-open-formula)
4626 (defvar calc-embedded-open-mode)
4627 (defvar font-lock-unfontify-region-function)
4628 (defvar iswitchb-temp-buflist)
4629 (defvar org-agenda-tags-todo-honor-ignore-options)
4630 (defvar remember-data-file)
4631 (defvar texmathp-why)
4633 ;;;###autoload
4634 (defun turn-on-orgtbl ()
4635 "Unconditionally turn on `orgtbl-mode'."
4636 (require 'org-table)
4637 (orgtbl-mode 1))
4639 (defun org-at-table-p (&optional table-type)
4640 "Non-nil if the cursor is inside an Org table.
4641 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4642 If `org-enable-table-editor' is nil, return nil unconditionally."
4643 (and
4644 org-enable-table-editor
4645 (save-excursion
4646 (beginning-of-line)
4647 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4648 (or (not (derived-mode-p 'org-mode))
4649 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4650 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4652 (defun org-at-table.el-p ()
4653 "Non-nil when point is at a table.el table."
4654 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4655 (let ((element (org-element-at-point)))
4656 (and (eq (org-element-type element) 'table)
4657 (eq (org-element-property :type element) 'table.el)))))
4659 (defun org-at-table-hline-p ()
4660 "Non-nil when point is inside a hline in a table.
4661 Assume point is already in a table. If `org-enable-table-editor'
4662 is nil, return nil unconditionally."
4663 (and org-enable-table-editor
4664 (save-excursion
4665 (beginning-of-line)
4666 (looking-at org-table-hline-regexp))))
4668 (defun org-table-map-tables (function &optional quietly)
4669 "Apply FUNCTION to the start of all tables in the buffer."
4670 (org-with-wide-buffer
4671 (goto-char (point-min))
4672 (while (re-search-forward org-table-any-line-regexp nil t)
4673 (unless quietly
4674 (message "Mapping tables: %d%%"
4675 (floor (* 100.0 (point)) (buffer-size))))
4676 (beginning-of-line 1)
4677 (when (and (looking-at org-table-line-regexp)
4678 ;; Exclude tables in src/example/verbatim/clocktable blocks
4679 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4680 (save-excursion (funcall function))
4681 (or (looking-at org-table-line-regexp)
4682 (forward-char 1)))
4683 (re-search-forward org-table-any-border-regexp nil 1)))
4684 (unless quietly (message "Mapping tables: done")))
4686 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4687 (declare-function org-clock-update-mode-line "org-clock" ())
4688 (declare-function org-resolve-clocks "org-clock"
4689 (&optional also-non-dangling-p prompt last-valid))
4691 (defun org-at-TBLFM-p (&optional pos)
4692 "Non-nil when point (or POS) is in #+TBLFM line."
4693 (save-excursion
4694 (goto-char (or pos (point)))
4695 (beginning-of-line)
4696 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4697 (eq (org-element-type (org-element-at-point)) 'table))))
4699 (defvar org-clock-start-time)
4700 (defvar org-clock-marker (make-marker)
4701 "Marker recording the last clock-in.")
4702 (defvar org-clock-hd-marker (make-marker)
4703 "Marker recording the last clock-in, but the headline position.")
4704 (defvar org-clock-heading ""
4705 "The heading of the current clock entry.")
4706 (defun org-clock-is-active ()
4707 "Return the buffer where the clock is currently running.
4708 Return nil if no clock is running."
4709 (marker-buffer org-clock-marker))
4711 (defun org-check-running-clock ()
4712 "Check if the current buffer contains the running clock.
4713 If yes, offer to stop it and to save the buffer with the changes."
4714 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4715 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4716 (buffer-name))))
4717 (org-clock-out)
4718 (when (y-or-n-p "Save changed buffer?")
4719 (save-buffer))))
4721 (defun org-clocktable-try-shift (dir n)
4722 "Check if this line starts a clock table, if yes, shift the time block."
4723 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4724 (org-clocktable-shift dir n)))
4726 ;;;###autoload
4727 (defun org-clock-persistence-insinuate ()
4728 "Set up hooks for clock persistence."
4729 (require 'org-clock)
4730 (add-hook 'org-mode-hook 'org-clock-load)
4731 (add-hook 'kill-emacs-hook 'org-clock-save))
4733 (defgroup org-archive nil
4734 "Options concerning archiving in Org mode."
4735 :tag "Org Archive"
4736 :group 'org-structure)
4738 (defcustom org-archive-location "%s_archive::"
4739 "The location where subtrees should be archived.
4741 The value of this variable is a string, consisting of two parts,
4742 separated by a double-colon. The first part is a filename and
4743 the second part is a headline.
4745 When the filename is omitted, archiving happens in the same file.
4746 %s in the filename will be replaced by the current file
4747 name (without the directory part). Archiving to a different file
4748 is useful to keep archived entries from contributing to the
4749 Org Agenda.
4751 The archived entries will be filed as subtrees of the specified
4752 headline. When the headline is omitted, the subtrees are simply
4753 filed away at the end of the file, as top-level entries. Also in
4754 the heading you can use %s to represent the file name, this can be
4755 useful when using the same archive for a number of different files.
4757 Here are a few examples:
4758 \"%s_archive::\"
4759 If the current file is Projects.org, archive in file
4760 Projects.org_archive, as top-level trees. This is the default.
4762 \"::* Archived Tasks\"
4763 Archive in the current file, under the top-level headline
4764 \"* Archived Tasks\".
4766 \"~/org/archive.org::\"
4767 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4769 \"~/org/archive.org::* From %s\"
4770 Archive in file ~/org/archive.org (absolute path), under headlines
4771 \"From FILENAME\" where file name is the current file name.
4773 \"~/org/datetree.org::datetree/* Finished Tasks\"
4774 The \"datetree/\" string is special, signifying to archive
4775 items to the datetree. Items are placed in either the CLOSED
4776 date of the item, or the current date if there is no CLOSED date.
4777 The heading will be a subentry to the current date. There doesn't
4778 need to be a heading, but there always needs to be a slash after
4779 datetree. For example, to store archived items directly in the
4780 datetree, use \"~/org/datetree.org::datetree/\".
4782 \"basement::** Finished Tasks\"
4783 Archive in file ./basement (relative path), as level 3 trees
4784 below the level 2 heading \"** Finished Tasks\".
4786 You may set this option on a per-file basis by adding to the buffer a
4787 line like
4789 #+ARCHIVE: basement::** Finished Tasks
4791 You may also define it locally for a subtree by setting an ARCHIVE property
4792 in the entry. If such a property is found in an entry, or anywhere up
4793 the hierarchy, it will be used."
4794 :group 'org-archive
4795 :type 'string)
4797 (defcustom org-agenda-skip-archived-trees t
4798 "Non-nil means the agenda will skip any items located in archived trees.
4799 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4800 variable is no longer recommended, you should leave it at the value t.
4801 Instead, use the key `v' to cycle the archives-mode in the agenda."
4802 :group 'org-archive
4803 :group 'org-agenda-skip
4804 :type 'boolean)
4806 (defcustom org-columns-skip-archived-trees t
4807 "Non-nil means ignore archived trees when creating column view."
4808 :group 'org-archive
4809 :group 'org-properties
4810 :type 'boolean)
4812 (defcustom org-cycle-open-archived-trees nil
4813 "Non-nil means `org-cycle' will open archived trees.
4814 An archived tree is a tree marked with the tag ARCHIVE.
4815 When nil, archived trees will stay folded. You can still open them with
4816 normal outline commands like `show-all', but not with the cycling commands."
4817 :group 'org-archive
4818 :group 'org-cycle
4819 :type 'boolean)
4821 (defcustom org-sparse-tree-open-archived-trees nil
4822 "Non-nil means sparse tree construction shows matches in archived trees.
4823 When nil, matches in these trees are highlighted, but the trees are kept in
4824 collapsed state."
4825 :group 'org-archive
4826 :group 'org-sparse-trees
4827 :type 'boolean)
4829 (defcustom org-sparse-tree-default-date-type nil
4830 "The default date type when building a sparse tree.
4831 When this is nil, a date is a scheduled or a deadline timestamp.
4832 Otherwise, these types are allowed:
4834 all: all timestamps
4835 active: only active timestamps (<...>)
4836 inactive: only inactive timestamps ([...])
4837 scheduled: only scheduled timestamps
4838 deadline: only deadline timestamps"
4839 :type '(choice (const :tag "Scheduled or deadline" nil)
4840 (const :tag "All timestamps" all)
4841 (const :tag "Only active timestamps" active)
4842 (const :tag "Only inactive timestamps" inactive)
4843 (const :tag "Only scheduled timestamps" scheduled)
4844 (const :tag "Only deadline timestamps" deadline)
4845 (const :tag "Only closed timestamps" closed))
4846 :version "25.2"
4847 :package-version '(Org . "8.3")
4848 :group 'org-sparse-trees)
4850 (defun org-cycle-hide-archived-subtrees (state)
4851 "Re-hide all archived subtrees after a visibility state change."
4852 (when (and (not org-cycle-open-archived-trees)
4853 (not (memq state '(overview folded))))
4854 (save-excursion
4855 (let* ((globalp (memq state '(contents all)))
4856 (beg (if globalp (point-min) (point)))
4857 (end (if globalp (point-max) (org-end-of-subtree t))))
4858 (org-hide-archived-subtrees beg end)
4859 (goto-char beg)
4860 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4861 (message "%s" (substitute-command-keys
4862 "Subtree is archived and stays closed. Use \
4863 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4865 (defun org-force-cycle-archived ()
4866 "Cycle subtree even if it is archived."
4867 (interactive)
4868 (setq this-command 'org-cycle)
4869 (let ((org-cycle-open-archived-trees t))
4870 (call-interactively 'org-cycle)))
4872 (defun org-hide-archived-subtrees (beg end)
4873 "Re-hide all archived subtrees after a visibility state change."
4874 (org-with-wide-buffer
4875 (let ((case-fold-search nil)
4876 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4877 (goto-char beg)
4878 ;; Include headline point is currently on.
4879 (beginning-of-line)
4880 (while (and (< (point) end) (re-search-forward re end t))
4881 (when (member org-archive-tag (org-get-tags))
4882 (org-flag-subtree t)
4883 (org-end-of-subtree t))))))
4885 (declare-function outline-end-of-heading "outline" ())
4886 (declare-function outline-flag-region "outline" (from to flag))
4887 (defun org-flag-subtree (flag)
4888 (save-excursion
4889 (org-back-to-heading t)
4890 (outline-end-of-heading)
4891 (outline-flag-region (point)
4892 (progn (org-end-of-subtree t) (point))
4893 flag)))
4895 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4897 ;; Declare Column View Code
4899 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4900 (declare-function org-columns-compute "org-colview" (property))
4902 ;; Declare ID code
4904 (declare-function org-id-store-link "org-id")
4905 (declare-function org-id-locations-load "org-id")
4906 (declare-function org-id-locations-save "org-id")
4907 (defvar org-id-track-globally)
4909 ;;; Variables for pre-computed regular expressions, all buffer local
4911 (defvar-local org-todo-regexp nil
4912 "Matches any of the TODO state keywords.
4913 Since TODO keywords are case-sensitive, `case-fold-search' is
4914 expected to be bound to nil when matching against this regexp.")
4916 (defvar-local org-not-done-regexp nil
4917 "Matches any of the TODO state keywords except the last one.
4918 Since TODO keywords are case-sensitive, `case-fold-search' is
4919 expected to be bound to nil when matching against this regexp.")
4921 (defvar-local org-not-done-heading-regexp nil
4922 "Matches a TODO headline that is not done.
4923 Since TODO keywords are case-sensitive, `case-fold-search' is
4924 expected to be bound to nil when matching against this regexp.")
4926 (defvar-local org-todo-line-regexp nil
4927 "Matches a headline and puts TODO state into group 2 if present.
4928 Since TODO keywords are case-sensitive, `case-fold-search' is
4929 expected to be bound to nil when matching against this regexp.")
4931 (defvar-local org-complex-heading-regexp nil
4932 "Matches a headline and puts everything into groups:
4934 group 1: Stars
4935 group 2: The TODO keyword, maybe
4936 group 3: Priority cookie
4937 group 4: True headline
4938 group 5: Tags
4940 Since TODO keywords are case-sensitive, `case-fold-search' is
4941 expected to be bound to nil when matching against this regexp.")
4943 (defvar-local org-complex-heading-regexp-format nil
4944 "Printf format to make regexp to match an exact headline.
4945 This regexp will match the headline of any node which has the
4946 exact headline text that is put into the format, but may have any
4947 TODO state, priority and tags.")
4949 (defvar-local org-todo-line-tags-regexp nil
4950 "Matches a headline and puts TODO state into group 2 if present.
4951 Also put tags into group 4 if tags are present.")
4953 (defconst org-plain-time-of-day-regexp
4954 (concat
4955 "\\(\\<[012]?[0-9]"
4956 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4957 "\\(--?"
4958 "\\(\\<[012]?[0-9]"
4959 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4960 "\\)?")
4961 "Regular expression to match a plain time or time range.
4962 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4963 groups carry important information:
4964 0 the full match
4965 1 the first time, range or not
4966 8 the second time, if it is a range.")
4968 (defconst org-plain-time-extension-regexp
4969 (concat
4970 "\\(\\<[012]?[0-9]"
4971 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4972 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4973 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4974 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4975 groups carry important information:
4976 0 the full match
4977 7 hours of duration
4978 9 minutes of duration")
4980 (defconst org-stamp-time-of-day-regexp
4981 (concat
4982 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4983 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4984 "\\(--?"
4985 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4986 "Regular expression to match a timestamp time or time range.
4987 After a match, the following groups carry important information:
4988 0 the full match
4989 1 date plus weekday, for back referencing to make sure both times are on the same day
4990 2 the first time, range or not
4991 4 the second time, if it is a range.")
4993 (defconst org-startup-options
4994 '(("fold" org-startup-folded t)
4995 ("overview" org-startup-folded t)
4996 ("nofold" org-startup-folded nil)
4997 ("showall" org-startup-folded nil)
4998 ("showeverything" org-startup-folded showeverything)
4999 ("content" org-startup-folded content)
5000 ("indent" org-startup-indented t)
5001 ("noindent" org-startup-indented nil)
5002 ("hidestars" org-hide-leading-stars t)
5003 ("showstars" org-hide-leading-stars nil)
5004 ("odd" org-odd-levels-only t)
5005 ("oddeven" org-odd-levels-only nil)
5006 ("align" org-startup-align-all-tables t)
5007 ("noalign" org-startup-align-all-tables nil)
5008 ("inlineimages" org-startup-with-inline-images t)
5009 ("noinlineimages" org-startup-with-inline-images nil)
5010 ("latexpreview" org-startup-with-latex-preview t)
5011 ("nolatexpreview" org-startup-with-latex-preview nil)
5012 ("customtime" org-display-custom-times t)
5013 ("logdone" org-log-done time)
5014 ("lognotedone" org-log-done note)
5015 ("nologdone" org-log-done nil)
5016 ("lognoteclock-out" org-log-note-clock-out t)
5017 ("nolognoteclock-out" org-log-note-clock-out nil)
5018 ("logrepeat" org-log-repeat state)
5019 ("lognoterepeat" org-log-repeat note)
5020 ("logdrawer" org-log-into-drawer t)
5021 ("nologdrawer" org-log-into-drawer nil)
5022 ("logstatesreversed" org-log-states-order-reversed t)
5023 ("nologstatesreversed" org-log-states-order-reversed nil)
5024 ("nologrepeat" org-log-repeat nil)
5025 ("logreschedule" org-log-reschedule time)
5026 ("lognotereschedule" org-log-reschedule note)
5027 ("nologreschedule" org-log-reschedule nil)
5028 ("logredeadline" org-log-redeadline time)
5029 ("lognoteredeadline" org-log-redeadline note)
5030 ("nologredeadline" org-log-redeadline nil)
5031 ("logrefile" org-log-refile time)
5032 ("lognoterefile" org-log-refile note)
5033 ("nologrefile" org-log-refile nil)
5034 ("fninline" org-footnote-define-inline t)
5035 ("nofninline" org-footnote-define-inline nil)
5036 ("fnlocal" org-footnote-section nil)
5037 ("fnauto" org-footnote-auto-label t)
5038 ("fnprompt" org-footnote-auto-label nil)
5039 ("fnconfirm" org-footnote-auto-label confirm)
5040 ("fnplain" org-footnote-auto-label plain)
5041 ("fnadjust" org-footnote-auto-adjust t)
5042 ("nofnadjust" org-footnote-auto-adjust nil)
5043 ("constcgs" constants-unit-system cgs)
5044 ("constSI" constants-unit-system SI)
5045 ("noptag" org-tag-persistent-alist nil)
5046 ("hideblocks" org-hide-block-startup t)
5047 ("nohideblocks" org-hide-block-startup nil)
5048 ("beamer" org-startup-with-beamer-mode t)
5049 ("entitiespretty" org-pretty-entities t)
5050 ("entitiesplain" org-pretty-entities nil))
5051 "Variable associated with STARTUP options for org-mode.
5052 Each element is a list of three items: the startup options (as written
5053 in the #+STARTUP line), the corresponding variable, and the value to set
5054 this variable to if the option is found. An optional forth element PUSH
5055 means to push this value onto the list in the variable.")
5057 (defcustom org-group-tags t
5058 "When non-nil (the default), use group tags.
5059 This can be turned on/off through `org-toggle-tags-groups'."
5060 :group 'org-tags
5061 :group 'org-startup
5062 :type 'boolean)
5064 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5066 (defun org-toggle-tags-groups ()
5067 "Toggle support for group tags.
5068 Support for group tags is controlled by the option
5069 `org-group-tags', which is non-nil by default."
5070 (interactive)
5071 (setq org-group-tags (not org-group-tags))
5072 (cond ((and (derived-mode-p 'org-agenda-mode)
5073 org-group-tags)
5074 (org-agenda-redo))
5075 ((derived-mode-p 'org-mode)
5076 (let ((org-inhibit-startup t)) (org-mode))))
5077 (message "Groups tags support has been turned %s"
5078 (if org-group-tags "on" "off")))
5080 (defun org-set-regexps-and-options (&optional tags-only)
5081 "Precompute regular expressions used in the current buffer.
5082 When optional argument TAGS-ONLY is non-nil, only compute tags
5083 related expressions."
5084 (when (derived-mode-p 'org-mode)
5085 (let ((alist (org--setup-collect-keywords
5086 (org-make-options-regexp
5087 (append '("FILETAGS" "TAGS" "SETUPFILE")
5088 (and (not tags-only)
5089 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5090 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5091 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5092 ;; Startup options. Get this early since it does change
5093 ;; behavior for other options (e.g., tags).
5094 (let ((startup (cdr (assq 'startup alist))))
5095 (dolist (option startup)
5096 (let ((entry (assoc-string option org-startup-options t)))
5097 (when entry
5098 (let ((var (nth 1 entry))
5099 (val (nth 2 entry)))
5100 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5101 (unless (listp (symbol-value var))
5102 (set (make-local-variable var) nil))
5103 (add-to-list var val)))))))
5104 (setq-local org-file-tags
5105 (mapcar #'org-add-prop-inherited
5106 (cdr (assq 'filetags alist))))
5107 (setq org-current-tag-alist
5108 (append org-tag-persistent-alist
5109 (let ((tags (cdr (assq 'tags alist))))
5110 (if tags (org-tag-string-to-alist tags)
5111 org-tag-alist))))
5112 (setq org-tag-groups-alist
5113 (org-tag-alist-to-groups org-current-tag-alist))
5114 (unless tags-only
5115 ;; File properties.
5116 (setq-local org-file-properties (cdr (assq 'property alist)))
5117 ;; Archive location.
5118 (let ((archive (cdr (assq 'archive alist))))
5119 (when archive (setq-local org-archive-location archive)))
5120 ;; Category.
5121 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5122 (when cat
5123 (setq-local org-category (intern cat))
5124 (setq-local org-file-properties
5125 (org--update-property-plist
5126 "CATEGORY" cat org-file-properties))))
5127 ;; Columns.
5128 (let ((column (cdr (assq 'columns alist))))
5129 (when column (setq-local org-columns-default-format column)))
5130 ;; Constants.
5131 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5132 ;; Link abbreviations.
5133 (let ((links (cdr (assq 'link alist))))
5134 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5135 ;; Priorities.
5136 (let ((priorities (cdr (assq 'priorities alist))))
5137 (when priorities
5138 (setq-local org-highest-priority (nth 0 priorities))
5139 (setq-local org-lowest-priority (nth 1 priorities))
5140 (setq-local org-default-priority (nth 2 priorities))))
5141 ;; Scripts.
5142 (let ((scripts (assq 'scripts alist)))
5143 (when scripts
5144 (setq-local org-use-sub-superscripts (cdr scripts))))
5145 ;; TODO keywords.
5146 (setq-local org-todo-kwd-alist nil)
5147 (setq-local org-todo-key-alist nil)
5148 (setq-local org-todo-key-trigger nil)
5149 (setq-local org-todo-keywords-1 nil)
5150 (setq-local org-done-keywords nil)
5151 (setq-local org-todo-heads nil)
5152 (setq-local org-todo-sets nil)
5153 (setq-local org-todo-log-states nil)
5154 (let ((todo-sequences
5155 (or (nreverse (cdr (assq 'todo alist)))
5156 (let ((d (default-value 'org-todo-keywords)))
5157 (if (not (stringp (car d))) d
5158 ;; XXX: Backward compatibility code.
5159 (list (cons org-todo-interpretation d)))))))
5160 (dolist (sequence todo-sequences)
5161 (let* ((sequence (or (run-hook-with-args-until-success
5162 'org-todo-setup-filter-hook sequence)
5163 sequence))
5164 (sequence-type (car sequence))
5165 (keywords (cdr sequence))
5166 (sep (member "|" keywords))
5167 names alist)
5168 (dolist (k (remove "|" keywords))
5169 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5171 (error "Invalid TODO keyword %s" k))
5172 (let ((name (match-string 1 k))
5173 (key (match-string 2 k))
5174 (log (org-extract-log-state-settings k)))
5175 (push name names)
5176 (push (cons name (and key (string-to-char key))) alist)
5177 (when log (push log org-todo-log-states))))
5178 (let* ((names (nreverse names))
5179 (done (if sep (org-remove-keyword-keys (cdr sep))
5180 (last names)))
5181 (head (car names))
5182 (tail (list sequence-type head (car done) (org-last done))))
5183 (add-to-list 'org-todo-heads head 'append)
5184 (push names org-todo-sets)
5185 (setq org-done-keywords (append org-done-keywords done nil))
5186 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5187 (setq org-todo-key-alist
5188 (append org-todo-key-alist
5189 (and alist
5190 (append '((:startgroup))
5191 (nreverse alist)
5192 '((:endgroup))))))
5193 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5194 (setq org-todo-sets (nreverse org-todo-sets)
5195 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5196 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5197 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5198 ;; Compute the regular expressions and other local variables.
5199 ;; Using `org-outline-regexp-bol' would complicate them much,
5200 ;; because of the fixed white space at the end of that string.
5201 (unless org-done-keywords
5202 (setq org-done-keywords
5203 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5204 (setq org-not-done-keywords
5205 (org-delete-all org-done-keywords
5206 (copy-sequence org-todo-keywords-1))
5207 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5208 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5209 org-not-done-heading-regexp
5210 (format org-heading-keyword-regexp-format org-not-done-regexp)
5211 org-todo-line-regexp
5212 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5213 org-complex-heading-regexp
5214 (concat "^\\(\\*+\\)"
5215 "\\(?: +" org-todo-regexp "\\)?"
5216 "\\(?: +\\(\\[#.\\]\\)\\)?"
5217 "\\(?: +\\(.*?\\)\\)??"
5218 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5219 "[ \t]*$")
5220 org-complex-heading-regexp-format
5221 (concat "^\\(\\*+\\)"
5222 "\\(?: +" org-todo-regexp "\\)?"
5223 "\\(?: +\\(\\[#.\\]\\)\\)?"
5224 "\\(?: +"
5225 ;; Stats cookies can be stuck to body.
5226 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5227 "\\(%s\\)"
5228 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5229 "\\)"
5230 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5231 "[ \t]*$")
5232 org-todo-line-tags-regexp
5233 (concat "^\\(\\*+\\)"
5234 "\\(?: +" org-todo-regexp "\\)?"
5235 "\\(?: +\\(.*?\\)\\)??"
5236 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5237 "[ \t]*$"))
5238 (org-compute-latex-and-related-regexp)))))
5240 (defun org--setup-collect-keywords (regexp &optional files alist)
5241 "Return setup keywords values as an alist.
5243 REGEXP matches a subset of setup keywords. FILES is a list of
5244 file names already visited. It is used to avoid circular setup
5245 files. ALIST, when non-nil, is the alist computed so far.
5247 Return value contains the following keys: `archive', `category',
5248 `columns', `constants', `filetags', `link', `priorities',
5249 `property', `scripts', `startup', `tags' and `todo'."
5250 (org-with-wide-buffer
5251 (goto-char (point-min))
5252 (let ((case-fold-search t))
5253 (while (re-search-forward regexp nil t)
5254 (let ((element (org-element-at-point)))
5255 (when (eq (org-element-type element) 'keyword)
5256 (let ((key (org-element-property :key element))
5257 (value (org-element-property :value element)))
5258 (cond
5259 ((equal key "ARCHIVE")
5260 (when (org-string-nw-p value)
5261 (push (cons 'archive value) alist)))
5262 ((equal key "CATEGORY") (push (cons 'category value) alist))
5263 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5264 ((equal key "CONSTANTS")
5265 (let* ((constants (assq 'constants alist))
5266 (store (cdr constants)))
5267 (dolist (pair (org-split-string value))
5268 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5269 pair)
5270 (let* ((name (match-string 1 pair))
5271 (value (match-string 2 pair))
5272 (old (assoc name store)))
5273 (if old (setcdr old value)
5274 (push (cons name value) store)))))
5275 (if constants (setcdr constants store)
5276 (push (cons 'constants store) alist))))
5277 ((equal key "FILETAGS")
5278 (when (org-string-nw-p value)
5279 (let ((old (assq 'filetags alist))
5280 (new (apply #'nconc
5281 (mapcar (lambda (x) (org-split-string x ":"))
5282 (org-split-string value)))))
5283 (if old (setcdr old (append new (cdr old)))
5284 (push (cons 'filetags new) alist)))))
5285 ((equal key "LINK")
5286 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5287 (let ((links (assq 'link alist))
5288 (pair (cons (match-string-no-properties 1 value)
5289 (match-string-no-properties 2 value))))
5290 (if links (push pair (cdr links))
5291 (push (list 'link pair) alist)))))
5292 ((equal key "OPTIONS")
5293 (when (and (org-string-nw-p value)
5294 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5295 (push (cons 'scripts (read (match-string 1 value))) alist)))
5296 ((equal key "PRIORITIES")
5297 (push (cons 'priorities
5298 (let ((prio (org-split-string value)))
5299 (if (< (length prio) 3) '(?A ?C ?B)
5300 (mapcar #'string-to-char prio))))
5301 alist))
5302 ((equal key "PROPERTY")
5303 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5304 (let* ((property (assq 'property alist))
5305 (value (org--update-property-plist
5306 (match-string-no-properties 1 value)
5307 (match-string-no-properties 2 value)
5308 (cdr property))))
5309 (if property (setcdr property value)
5310 (push (cons 'property value) alist)))))
5311 ((equal key "STARTUP")
5312 (let ((startup (assq 'startup alist)))
5313 (if startup
5314 (setcdr startup
5315 (append (cdr startup) (org-split-string value)))
5316 (push (cons 'startup (org-split-string value)) alist))))
5317 ((equal key "TAGS")
5318 (let ((tag-cell (assq 'tags alist)))
5319 (if tag-cell
5320 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5321 (push (cons 'tags value) alist))))
5322 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5323 (let ((todo (assq 'todo alist))
5324 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5325 (org-split-string value))))
5326 (if todo (push value (cdr todo))
5327 (push (list 'todo value) alist))))
5328 ((equal key "SETUPFILE")
5329 (unless buffer-read-only ; Do not check in Gnus messages.
5330 (let ((f (and (org-string-nw-p value)
5331 (expand-file-name
5332 (org-unbracket-string "\"" "\"" value)))))
5333 (when (and f (file-readable-p f) (not (member f files)))
5334 (with-temp-buffer
5335 (setq default-directory (file-name-directory f))
5336 (insert-file-contents f)
5337 (setq alist
5338 ;; Fake Org mode to benefit from cache
5339 ;; without recurring needlessly.
5340 (let ((major-mode 'org-mode))
5341 (org--setup-collect-keywords
5342 regexp (cons f files) alist)))))))))))))))
5343 alist)
5345 (defun org-tag-string-to-alist (s)
5346 "Return tag alist associated to string S.
5347 S is a value for TAGS keyword or produced with
5348 `org-tag-alist-to-string'. Return value is an alist suitable for
5349 `org-tag-alist' or `org-tag-persistent-alist'."
5350 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5351 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5352 "\\|{.+?}\\)" ; regular expression
5353 "\\(?:(\\(.\\))\\)?\\'"))
5354 alist group-flag)
5355 (dolist (tokens lines (cdr (nreverse alist)))
5356 (push '(:newline) alist)
5357 (while tokens
5358 (let ((token (pop tokens)))
5359 (pcase token
5360 ("{"
5361 (push '(:startgroup) alist)
5362 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5363 ("}"
5364 (push '(:endgroup) alist)
5365 (setq group-flag nil))
5366 ("["
5367 (push '(:startgrouptag) alist)
5368 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5369 ("]"
5370 (push '(:endgrouptag) alist)
5371 (setq group-flag nil))
5372 (":"
5373 (push '(:grouptags) alist))
5374 ((guard (string-match tag-re token))
5375 (let ((tag (match-string 1 token))
5376 (key (and (match-beginning 2)
5377 (string-to-char (match-string 2 token)))))
5378 ;; Push all tags in groups, no matter if they already
5379 ;; appear somewhere else in the list.
5380 (when (or group-flag (not (assoc tag alist)))
5381 (push (cons tag key) alist))))))))))
5383 (defun org-tag-alist-to-string (alist &optional skip-key)
5384 "Return tag string associated to ALIST.
5386 ALIST is an alist, as defined in `org-tag-alist' or
5387 `org-tag-persistent-alist', or produced with
5388 `org-tag-string-to-alist'.
5390 Return value is a string suitable as a value for \"TAGS\"
5391 keyword.
5393 When optional argument SKIP-KEY is non-nil, skip selection keys
5394 next to tags."
5395 (mapconcat (lambda (token)
5396 (pcase token
5397 (`(:startgroup) "{")
5398 (`(:endgroup) "}")
5399 (`(:startgrouptag) "[")
5400 (`(:endgrouptag) "]")
5401 (`(:grouptags) ":")
5402 (`(:newline) "\\n")
5403 ((and
5404 (guard (not skip-key))
5405 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5406 (format "%s(%c)" tag key))
5407 (`(,(and tag (pred stringp)) . ,_) tag)
5408 (_ (user-error "Invalid tag token: %S" token))))
5409 alist
5410 " "))
5412 (defun org-tag-alist-to-groups (alist)
5413 "Return group alist from tag ALIST.
5414 ALIST is an alist, as defined in `org-tag-alist' or
5415 `org-tag-persistent-alist', or produced with
5416 `org-tag-string-to-alist'. Return value is an alist following
5417 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5418 a string, summarizing TAGS, as a list of strings."
5419 (let (groups group-status current-group)
5420 (dolist (token alist (nreverse groups))
5421 (pcase token
5422 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5423 (`(,(or :endgroup :endgrouptag))
5424 (when (eq group-status 'append)
5425 (push (nreverse current-group) groups))
5426 (setq group-status nil))
5427 (`(:grouptags) (setq group-status 'append))
5428 ((and `(,tag . ,_) (guard group-status))
5429 (if (eq group-status 'append) (push tag current-group)
5430 (setq current-group (list tag))))
5431 (_ nil)))))
5433 (defun org-file-contents (file &optional noerror)
5434 "Return the contents of FILE, as a string."
5435 (if (and file (file-readable-p file))
5436 (with-temp-buffer
5437 (insert-file-contents file)
5438 (buffer-string))
5439 (funcall (if noerror 'message 'error)
5440 "Cannot read file \"%s\"%s"
5441 file
5442 (let ((from (buffer-file-name (buffer-base-buffer))))
5443 (if from (concat " (referenced in file \"" from "\")") "")))))
5445 (defun org-extract-log-state-settings (x)
5446 "Extract the log state setting from a TODO keyword string.
5447 This will extract info from a string like \"WAIT(w@/!)\"."
5448 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5449 (let ((kw (match-string 1 x))
5450 (log1 (and (match-end 3) (match-string 3 x)))
5451 (log2 (and (match-end 4) (match-string 4 x))))
5452 (and (or log1 log2)
5453 (list kw
5454 (and log1 (if (equal log1 "!") 'time 'note))
5455 (and log2 (if (equal log2 "!") 'time 'note)))))))
5457 (defun org-remove-keyword-keys (list)
5458 "Remove a pair of parenthesis at the end of each string in LIST."
5459 (mapcar (lambda (x)
5460 (if (string-match "(.*)$" x)
5461 (substring x 0 (match-beginning 0))
5463 list))
5465 (defun org-assign-fast-keys (alist)
5466 "Assign fast keys to a keyword-key alist.
5467 Respect keys that are already there."
5468 (let (new e (alt ?0))
5469 (while (setq e (pop alist))
5470 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5471 (cdr e)) ;; Key already assigned.
5472 (push e new)
5473 (let ((clist (string-to-list (downcase (car e))))
5474 (used (append new alist)))
5475 (when (= (car clist) ?@)
5476 (pop clist))
5477 (while (and clist (rassoc (car clist) used))
5478 (pop clist))
5479 (unless clist
5480 (while (rassoc alt used)
5481 (cl-incf alt)))
5482 (push (cons (car e) (or (car clist) alt)) new))))
5483 (nreverse new)))
5485 ;;; Some variables used in various places
5487 (defvar org-window-configuration nil
5488 "Used in various places to store a window configuration.")
5489 (defvar org-selected-window nil
5490 "Used in various places to store a window configuration.")
5491 (defvar org-finish-function nil
5492 "Function to be called when `C-c C-c' is used.
5493 This is for getting out of special buffers like capture.")
5494 (defvar org-last-state)
5496 ;; Defined somewhere in this file, but used before definition.
5497 (defvar org-entities) ;; defined in org-entities.el
5498 (defvar org-struct-menu)
5499 (defvar org-org-menu)
5500 (defvar org-tbl-menu)
5502 ;;;; Define the Org mode
5504 ;; We use a before-change function to check if a table might need
5505 ;; an update.
5506 (defvar org-table-may-need-update t
5507 "Indicates that a table might need an update.
5508 This variable is set by `org-before-change-function'.
5509 `org-table-align' sets it back to nil.")
5510 (defun org-before-change-function (_beg _end)
5511 "Every change indicates that a table might need an update."
5512 (setq org-table-may-need-update t))
5513 (defvar org-mode-map)
5514 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5515 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5516 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5517 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5518 (defvar org-table-buffer-is-an nil)
5520 (defvar bidi-paragraph-direction)
5521 (defvar buffer-face-mode-face)
5523 (require 'outline)
5525 ;; Other stuff we need.
5526 (require 'time-date)
5527 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5528 (require 'easymenu)
5529 (autoload 'easy-menu-add "easymenu")
5530 (require 'overlay)
5532 ;; (require 'org-macs) moved higher up in the file before it is first used
5533 (require 'org-entities)
5534 ;; (require 'org-compat) moved higher up in the file before it is first used
5535 (require 'org-faces)
5536 (require 'org-list)
5537 (require 'org-pcomplete)
5538 (require 'org-src)
5539 (require 'org-footnote)
5540 (require 'org-macro)
5542 ;; babel
5543 (require 'ob)
5545 ;;;###autoload
5546 (define-derived-mode org-mode outline-mode "Org"
5547 "Outline-based notes management and organizer, alias
5548 \"Carsten's outline-mode for keeping track of everything.\"
5550 Org mode develops organizational tasks around a NOTES file which
5551 contains information about projects as plain text. Org mode is
5552 implemented on top of Outline mode, which is ideal to keep the content
5553 of large files well structured. It supports ToDo items, deadlines and
5554 time stamps, which magically appear in the diary listing of the Emacs
5555 calendar. Tables are easily created with a built-in table editor.
5556 Plain text URL-like links connect to websites, emails (VM), Usenet
5557 messages (Gnus), BBDB entries, and any files related to the project.
5558 For printing and sharing of notes, an Org file (or a part of it)
5559 can be exported as a structured ASCII or HTML file.
5561 The following commands are available:
5563 \\{org-mode-map}"
5565 ;; Get rid of Outline menus, they are not needed
5566 ;; Need to do this here because define-derived-mode sets up
5567 ;; the keymap so late. Still, it is a waste to call this each time
5568 ;; we switch another buffer into Org mode.
5569 (define-key org-mode-map [menu-bar headings] 'undefined)
5570 (define-key org-mode-map [menu-bar hide] 'undefined)
5571 (define-key org-mode-map [menu-bar show] 'undefined)
5573 (org-load-modules-maybe)
5574 (org-install-agenda-files-menu)
5575 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5576 (add-to-invisibility-spec '(org-cwidth))
5577 (add-to-invisibility-spec '(org-hide-block . t))
5578 (setq-local outline-regexp org-outline-regexp)
5579 (setq-local outline-level 'org-outline-level)
5580 (setq bidi-paragraph-direction 'left-to-right)
5581 (when (and org-ellipsis
5582 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5583 (fboundp 'make-glyph-code))
5584 (unless org-display-table
5585 (setq org-display-table (make-display-table)))
5586 (set-display-table-slot
5587 org-display-table 4
5588 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5589 (if (stringp org-ellipsis) org-ellipsis "..."))))
5590 (setq buffer-display-table org-display-table))
5591 (org-set-regexps-and-options)
5592 (org-set-font-lock-defaults)
5593 (when (and org-tag-faces (not org-tags-special-faces-re))
5594 ;; tag faces set outside customize.... force initialization.
5595 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5596 ;; Calc embedded
5597 (setq-local calc-embedded-open-mode "# ")
5598 ;; Modify a few syntax entries
5599 (modify-syntax-entry ?@ "w")
5600 (modify-syntax-entry ?\" "\"")
5601 (modify-syntax-entry ?\\ "_")
5602 (modify-syntax-entry ?~ "_")
5603 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5604 ;; Activate before-change-function
5605 (setq-local org-table-may-need-update t)
5606 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5607 ;; Check for running clock before killing a buffer
5608 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5609 ;; Initialize macros templates.
5610 (org-macro-initialize-templates)
5611 ;; Initialize radio targets.
5612 (org-update-radio-target-regexp)
5613 ;; Indentation.
5614 (setq-local indent-line-function 'org-indent-line)
5615 (setq-local indent-region-function 'org-indent-region)
5616 ;; Filling and auto-filling.
5617 (org-setup-filling)
5618 ;; Comments.
5619 (org-setup-comments-handling)
5620 ;; Initialize cache.
5621 (org-element-cache-reset)
5622 ;; Beginning/end of defun
5623 (setq-local beginning-of-defun-function 'org-backward-element)
5624 (setq-local end-of-defun-function
5625 (lambda ()
5626 (if (not (org-at-heading-p))
5627 (org-forward-element)
5628 (org-forward-element)
5629 (forward-char -1))))
5630 ;; Next error for sparse trees
5631 (setq-local next-error-function 'org-occur-next-match)
5632 ;; Make sure dependence stuff works reliably, even for users who set it
5633 ;; too late :-(
5634 (if org-enforce-todo-dependencies
5635 (add-hook 'org-blocker-hook
5636 'org-block-todo-from-children-or-siblings-or-parent)
5637 (remove-hook 'org-blocker-hook
5638 'org-block-todo-from-children-or-siblings-or-parent))
5639 (if org-enforce-todo-checkbox-dependencies
5640 (add-hook 'org-blocker-hook
5641 'org-block-todo-from-checkboxes)
5642 (remove-hook 'org-blocker-hook
5643 'org-block-todo-from-checkboxes))
5645 ;; Align options lines
5646 (setq-local
5647 align-mode-rules-list
5648 '((org-in-buffer-settings
5649 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5650 (modes . '(org-mode)))))
5652 ;; Imenu
5653 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5655 ;; Make isearch reveal context
5656 (setq-local outline-isearch-open-invisible-function
5657 (lambda (&rest _) (org-show-context 'isearch)))
5659 ;; Setup the pcomplete hooks
5660 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5661 (setq-local pcomplete-command-name-function 'org-command-at-point)
5662 (setq-local pcomplete-default-completion-function 'ignore)
5663 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5664 (setq-local pcomplete-termination-string "")
5665 (setq-local buffer-face-mode-face 'org-default)
5667 ;; If empty file that did not turn on Org mode automatically, make
5668 ;; it to.
5669 (when (and org-insert-mode-line-in-empty-file
5670 (called-interactively-p 'any)
5671 (= (point-min) (point-max)))
5672 (insert "# -*- mode: org -*-\n\n"))
5673 (unless org-inhibit-startup
5674 (org-unmodified
5675 (when org-startup-with-beamer-mode (org-beamer-mode))
5676 (when org-startup-align-all-tables
5677 (org-table-map-tables #'org-table-align t))
5678 (when org-startup-with-inline-images (org-display-inline-images))
5679 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5680 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5681 (when org-startup-truncated (setq truncate-lines t))
5682 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5683 (org-refresh-effort-properties)))
5684 ;; Try to set `org-hide' face correctly.
5685 (let ((foreground (org-find-invisible-foreground)))
5686 (when foreground
5687 (set-face-foreground 'org-hide foreground))))
5689 ;; Update `customize-package-emacs-version-alist'
5690 (add-to-list 'customize-package-emacs-version-alist
5691 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5692 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5693 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5694 ("9.0" . "25.2")))
5696 (defvar org-mode-transpose-word-syntax-table
5697 (let ((st (make-syntax-table text-mode-syntax-table)))
5698 (dolist (c org-emphasis-alist st)
5699 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5701 (when (fboundp 'abbrev-table-put)
5702 (abbrev-table-put org-mode-abbrev-table
5703 :parents (list text-mode-abbrev-table)))
5705 (defun org-find-invisible-foreground ()
5706 (let ((candidates (remove
5707 "unspecified-bg"
5708 (nconc
5709 (list (face-background 'default)
5710 (face-background 'org-default))
5711 (mapcar
5712 (lambda (alist)
5713 (when (boundp alist)
5714 (cdr (assq 'background-color (symbol-value alist)))))
5715 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5716 (list (face-foreground 'org-hide))))))
5717 (car (remove nil candidates))))
5719 (defun org-current-time (&optional rounding-minutes past)
5720 "Current time, possibly rounded to ROUNDING-MINUTES.
5721 When ROUNDING-MINUTES is not an integer, fall back on the car of
5722 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5723 the rounding returns a past time."
5724 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5725 (car org-time-stamp-rounding-minutes)))
5726 (time (decode-time)) res)
5727 (if (< r 1)
5728 (current-time)
5729 (setq res
5730 (apply 'encode-time
5731 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5732 (nthcdr 2 time))))
5733 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5734 (seconds-to-time (- (float-time res) (* r 60)))
5735 res))))
5737 (defun org-today ()
5738 "Return today date, considering `org-extend-today-until'."
5739 (time-to-days
5740 (time-subtract (current-time)
5741 (list 0 (* 3600 org-extend-today-until) 0))))
5743 ;;;; Font-Lock stuff, including the activators
5745 (defvar org-mouse-map (make-sparse-keymap))
5746 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5747 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5748 (when org-mouse-1-follows-link
5749 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5750 (when org-tab-follows-link
5751 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5752 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5754 (require 'font-lock)
5756 (defconst org-non-link-chars "]\t\n\r<>")
5757 (defvar org-link-types-re nil
5758 "Matches a link that has a url-like prefix like \"http:\"")
5759 (defvar org-link-re-with-space nil
5760 "Matches a link with spaces, optional angular brackets around it.")
5761 (defvar org-link-re-with-space2 nil
5762 "Matches a link with spaces, optional angular brackets around it.")
5763 (defvar org-link-re-with-space3 nil
5764 "Matches a link with spaces, only for internal part in bracket links.")
5765 (defvar org-angle-link-re nil
5766 "Matches link with angular brackets, spaces are allowed.")
5767 (defvar org-plain-link-re nil
5768 "Matches plain link, without spaces.")
5769 (defvar org-bracket-link-regexp nil
5770 "Matches a link in double brackets.")
5771 (defvar org-bracket-link-analytic-regexp nil
5772 "Regular expression used to analyze links.
5773 Here is what the match groups contain after a match:
5774 1: http:
5775 2: http
5776 3: path
5777 4: [desc]
5778 5: desc")
5779 (defvar org-bracket-link-analytic-regexp++ nil
5780 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5781 (defvar org-any-link-re nil
5782 "Regular expression matching any link.")
5784 (defconst org-match-sexp-depth 3
5785 "Number of stacked braces for sub/superscript matching.")
5787 (defun org-create-multibrace-regexp (left right n)
5788 "Create a regular expression which will match a balanced sexp.
5789 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5790 as single character strings.
5791 The regexp returned will match the entire expression including the
5792 delimiters. It will also define a single group which contains the
5793 match except for the outermost delimiters. The maximum depth of
5794 stacked delimiters is N. Escaping delimiters is not possible."
5795 (let* ((nothing (concat "[^" left right "]*?"))
5796 (or "\\|")
5797 (re nothing)
5798 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5799 (while (> n 1)
5800 (setq n (1- n)
5801 re (concat re or next)
5802 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5803 (concat left "\\(" re "\\)" right)))
5805 (defconst org-match-substring-regexp
5806 (concat
5807 "\\(\\S-\\)\\([_^]\\)\\("
5808 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5809 "\\|"
5810 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5811 "\\|"
5812 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5813 "The regular expression matching a sub- or superscript.")
5815 (defconst org-match-substring-with-braces-regexp
5816 (concat
5817 "\\(\\S-\\)\\([_^]\\)"
5818 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5819 "The regular expression matching a sub- or superscript, forcing braces.")
5821 (defun org-make-link-regexps ()
5822 "Update the link regular expressions.
5823 This should be called after the variable `org-link-parameters' has changed."
5824 (let ((types-re (regexp-opt (org-link-types) t)))
5825 (setq org-link-types-re
5826 (concat "\\`" types-re ":")
5827 org-link-re-with-space
5828 (concat "<?" types-re ":"
5829 "\\([^" org-non-link-chars " ]"
5830 "[^" org-non-link-chars "]*"
5831 "[^" org-non-link-chars " ]\\)>?")
5832 org-link-re-with-space2
5833 (concat "<?" types-re ":"
5834 "\\([^" org-non-link-chars " ]"
5835 "[^\t\n\r]*"
5836 "[^" org-non-link-chars " ]\\)>?")
5837 org-link-re-with-space3
5838 (concat "<?" types-re ":"
5839 "\\([^" org-non-link-chars " ]"
5840 "[^\t\n\r]*\\)")
5841 org-angle-link-re
5842 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5843 types-re)
5844 org-plain-link-re
5845 (concat
5846 "\\<" types-re ":"
5847 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5848 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5849 org-bracket-link-regexp
5850 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5851 org-bracket-link-analytic-regexp
5852 (concat
5853 "\\[\\["
5854 "\\(" types-re ":\\)?"
5855 "\\([^]]+\\)"
5856 "\\]"
5857 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5858 "\\]")
5859 org-bracket-link-analytic-regexp++
5860 (concat
5861 "\\[\\["
5862 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5863 "\\([^]]+\\)"
5864 "\\]"
5865 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5866 "\\]")
5867 org-any-link-re
5868 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5869 org-angle-link-re "\\)\\|\\("
5870 org-plain-link-re "\\)"))))
5872 (org-make-link-regexps)
5874 (defvar org-emph-face nil)
5876 (defun org-do-emphasis-faces (limit)
5877 "Run through the buffer and emphasize strings."
5878 (let (rtn a)
5879 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5880 (let* ((border (char-after (match-beginning 3)))
5881 (bre (regexp-quote (char-to-string border))))
5882 (when (and (not (= border (char-after (match-beginning 4))))
5883 (not (string-match-p (concat bre ".*" bre)
5884 (replace-regexp-in-string
5885 "\n" " "
5886 (substring (match-string 2) 1 -1)))))
5887 (setq rtn t)
5888 (setq a (assoc (match-string 3) org-emphasis-alist))
5889 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5890 'face
5891 (nth 1 a))
5892 (and (nth 2 a)
5893 (org-remove-flyspell-overlays-in
5894 (match-beginning 0) (match-end 0)))
5895 (add-text-properties (match-beginning 2) (match-end 2)
5896 '(font-lock-multiline t org-emphasis t))
5897 (when org-hide-emphasis-markers
5898 (add-text-properties (match-end 4) (match-beginning 5)
5899 '(invisible org-link))
5900 (add-text-properties (match-beginning 3) (match-end 3)
5901 '(invisible org-link)))))
5902 (goto-char (1+ (match-beginning 0))))
5903 rtn))
5905 (defun org-emphasize (&optional char)
5906 "Insert or change an emphasis, i.e. a font like bold or italic.
5907 If there is an active region, change that region to a new emphasis.
5908 If there is no region, just insert the marker characters and position
5909 the cursor between them.
5910 CHAR should be the marker character. If it is a space, it means to
5911 remove the emphasis of the selected region.
5912 If CHAR is not given (for example in an interactive call) it will be
5913 prompted for."
5914 (interactive)
5915 (let ((erc org-emphasis-regexp-components)
5916 (string "") beg end move s)
5917 (if (org-region-active-p)
5918 (setq beg (region-beginning)
5919 end (region-end)
5920 string (buffer-substring beg end))
5921 (setq move t))
5923 (unless char
5924 (message "Emphasis marker or tag: [%s]"
5925 (mapconcat #'car org-emphasis-alist ""))
5926 (setq char (read-char-exclusive)))
5927 (if (equal char ?\s)
5928 (setq s ""
5929 move nil)
5930 (unless (assoc (char-to-string char) org-emphasis-alist)
5931 (user-error "No such emphasis marker: \"%c\"" char))
5932 (setq s (char-to-string char)))
5933 (while (and (> (length string) 1)
5934 (equal (substring string 0 1) (substring string -1))
5935 (assoc (substring string 0 1) org-emphasis-alist))
5936 (setq string (substring string 1 -1)))
5937 (setq string (concat s string s))
5938 (when beg (delete-region beg end))
5939 (unless (or (bolp)
5940 (string-match (concat "[" (nth 0 erc) "\n]")
5941 (char-to-string (char-before (point)))))
5942 (insert " "))
5943 (unless (or (eobp)
5944 (string-match (concat "[" (nth 1 erc) "\n]")
5945 (char-to-string (char-after (point)))))
5946 (insert " ") (backward-char 1))
5947 (insert string)
5948 (and move (backward-char 1))))
5950 (defconst org-nonsticky-props
5951 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5953 (defsubst org-rear-nonsticky-at (pos)
5954 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5956 (defun org-activate-plain-links (limit)
5957 "Add link properties for plain links."
5958 (when (and (re-search-forward org-plain-link-re limit t)
5959 (not (org-in-src-block-p)))
5961 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5962 'face))
5963 (link (match-string-no-properties 0))
5964 (type (match-string-no-properties 1))
5965 (path (match-string-no-properties 2))
5966 (link-start (match-beginning 0))
5967 (link-end (match-end 0))
5968 (link-face (org-link-get-parameter type :face))
5969 (help-echo (org-link-get-parameter type :help-echo))
5970 (htmlize-link (org-link-get-parameter type :htmlize-link))
5971 (activate-func (org-link-get-parameter type :activate-func)))
5972 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5973 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5974 (add-text-properties (match-beginning 0) (match-end 0)
5975 (list
5976 'mouse-face (or (org-link-get-parameter type :mouse-face)
5977 'highlight)
5978 'face (cond
5979 ;; A function that returns a face
5980 ((functionp link-face)
5981 (funcall link-face path))
5982 ;; a face
5983 ((facep link-face)
5984 link-face)
5985 ;; An anonymous face
5986 ((consp link-face)
5987 link-face)
5988 ;; default
5990 'org-link))
5991 'help-echo (cond
5992 ((stringp help-echo)
5993 help-echo)
5994 ((functionp help-echo)
5995 help-echo)
5997 (concat "LINK: "
5998 (save-match-data
5999 (org-link-unescape link)))))
6000 'htmlize-link (cond
6001 ((functionp htmlize-link)
6002 (funcall htmlize-link path))
6004 `(:uri ,link)))
6005 'keymap (or (org-link-get-parameter type :keymap)
6006 org-mouse-map)
6007 'org-link-start (match-beginning 0)))
6008 (org-rear-nonsticky-at (match-end 0))
6009 (when activate-func
6010 (funcall activate-func link-start link-end path nil))
6011 t))))
6013 (defun org-activate-code (limit)
6014 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
6015 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6016 (remove-text-properties (match-beginning 0) (match-end 0)
6017 '(display t invisible t intangible t))
6020 (defcustom org-src-fontify-natively t
6021 "When non-nil, fontify code in code blocks.
6022 See also the `org-block' face."
6023 :type 'boolean
6024 :version "24.4"
6025 :package-version '(Org . "8.3")
6026 :group 'org-appearance
6027 :group 'org-babel)
6029 (defcustom org-allow-promoting-top-level-subtree nil
6030 "When non-nil, allow promoting a top level subtree.
6031 The leading star of the top level headline will be replaced
6032 by a #."
6033 :type 'boolean
6034 :version "24.1"
6035 :group 'org-appearance)
6037 (defun org-fontify-meta-lines-and-blocks (limit)
6038 (condition-case nil
6039 (org-fontify-meta-lines-and-blocks-1 limit)
6040 (error (message "org-mode fontification error in %S at %d"
6041 (current-buffer)
6042 (line-number-at-pos)))))
6044 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6045 "Fontify #+ lines and blocks."
6046 (let ((case-fold-search t))
6047 (when (re-search-forward
6048 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6049 limit t)
6050 (let ((beg (match-beginning 0))
6051 (block-start (match-end 0))
6052 (block-end nil)
6053 (lang (match-string 7))
6054 (beg1 (line-beginning-position 2))
6055 (dc1 (downcase (match-string 2)))
6056 (dc3 (downcase (match-string 3)))
6057 end end1 quoting block-type)
6058 (cond
6059 ((and (match-end 4) (equal dc3 "+begin"))
6060 ;; Truly a block
6061 (setq block-type (downcase (match-string 5))
6062 quoting (member block-type org-protecting-blocks))
6063 (when (re-search-forward
6064 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6065 nil t) ;; on purpose, we look further than LIMIT
6066 (setq end (min (point-max) (match-end 0))
6067 end1 (min (point-max) (1- (match-beginning 0))))
6068 (setq block-end (match-beginning 0))
6069 (when quoting
6070 (org-remove-flyspell-overlays-in beg1 end1)
6071 (remove-text-properties beg end
6072 '(display t invisible t intangible t)))
6073 (add-text-properties
6074 beg end '(font-lock-fontified t font-lock-multiline t))
6075 (add-text-properties beg beg1 '(face org-meta-line))
6076 (org-remove-flyspell-overlays-in beg beg1)
6077 (add-text-properties ; For end_src
6078 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6079 (org-remove-flyspell-overlays-in end1 end)
6080 (cond
6081 ((and lang (not (string= lang "")) org-src-fontify-natively)
6082 (org-src-font-lock-fontify-block lang block-start block-end)
6083 (add-text-properties beg1 block-end '(src-block t)))
6084 (quoting
6085 (add-text-properties beg1 (min (point-max) (1+ end1))
6086 (list 'face
6087 (list :inherit
6088 (let ((face-name
6089 (intern (format "org-block-%s" lang))))
6090 (append (and (facep face-name) (list face-name))
6091 '(org-block))))))) ; end of source block
6092 ((not org-fontify-quote-and-verse-blocks))
6093 ((string= block-type "quote")
6094 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
6095 ((string= block-type "verse")
6096 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
6097 (add-text-properties beg beg1 '(face org-block-begin-line))
6098 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6099 '(face org-block-end-line))
6101 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6102 (org-remove-flyspell-overlays-in
6103 (match-beginning 0)
6104 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6105 (add-text-properties
6106 beg (match-end 3)
6107 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6108 '(font-lock-fontified t invisible t)
6109 '(font-lock-fontified t face org-document-info-keyword)))
6110 (add-text-properties
6111 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6112 (if (string-equal dc1 "+title:")
6113 '(font-lock-fontified t face org-document-title)
6114 '(font-lock-fontified t face org-document-info))))
6115 ((string-prefix-p "+caption" dc1)
6116 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6117 (remove-text-properties (match-beginning 0) (match-end 0)
6118 '(display t invisible t intangible t))
6119 ;; Handle short captions.
6120 (save-excursion
6121 (beginning-of-line)
6122 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6123 (add-text-properties (line-beginning-position) (match-end 1)
6124 '(font-lock-fontified t face org-meta-line))
6125 (add-text-properties (match-end 0) (line-end-position)
6126 '(font-lock-fontified t face org-block))
6128 ((member dc3 '(" " ""))
6129 (org-remove-flyspell-overlays-in beg (match-end 0))
6130 (add-text-properties
6131 beg (match-end 0)
6132 '(font-lock-fontified t face font-lock-comment-face)))
6133 (t ;; just any other in-buffer setting, but not indented
6134 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6135 (remove-text-properties (match-beginning 0) (match-end 0)
6136 '(display t invisible t intangible t))
6137 (add-text-properties beg (match-end 0)
6138 '(font-lock-fontified t face org-meta-line))
6139 t))))))
6141 (defun org-fontify-drawers (limit)
6142 "Fontify drawers."
6143 (when (re-search-forward org-drawer-regexp limit t)
6144 (add-text-properties
6145 (match-beginning 0) (match-end 0)
6146 '(font-lock-fontified t face org-special-keyword))
6147 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6150 (defun org-fontify-macros (limit)
6151 "Fontify macros."
6152 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6153 (add-text-properties
6154 (match-beginning 0) (match-end 0)
6155 '(font-lock-fontified t face org-macro))
6156 (when org-hide-macro-markers
6157 (add-text-properties (match-end 2) (match-beginning 2)
6158 '(invisible t))
6159 (add-text-properties (match-beginning 1) (match-end 1)
6160 '(invisible t)))
6161 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6164 (defun org-activate-angle-links (limit)
6165 "Add text properties for angle links."
6166 (when (and (re-search-forward org-angle-link-re limit t)
6167 (not (org-in-src-block-p)))
6168 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6169 (add-text-properties (match-beginning 0) (match-end 0)
6170 (list 'mouse-face 'highlight
6171 'keymap org-mouse-map
6172 'font-lock-multiline t))
6173 (org-rear-nonsticky-at (match-end 0))
6176 (defun org-activate-footnote-links (limit)
6177 "Add text properties for footnotes."
6178 (let ((fn (org-footnote-next-reference-or-definition limit)))
6179 (when fn
6180 (let* ((beg (nth 1 fn))
6181 (end (nth 2 fn))
6182 (label (car fn))
6183 (referencep (/= (line-beginning-position) beg)))
6184 (when (and referencep (nth 3 fn))
6185 (save-excursion
6186 (goto-char beg)
6187 (search-forward (or label "fn:"))
6188 (org-remove-flyspell-overlays-in beg (match-end 0))))
6189 (add-text-properties beg end
6190 (list 'mouse-face 'highlight
6191 'keymap org-mouse-map
6192 'help-echo
6193 (if referencep "Footnote reference"
6194 "Footnote definition")
6195 'font-lock-fontified t
6196 'font-lock-multiline t
6197 'face 'org-footnote))))))
6199 (defun org-activate-bracket-links (limit)
6200 "Add text properties for bracketed links."
6201 (when (and (re-search-forward org-bracket-link-regexp limit t)
6202 (not (org-in-src-block-p)))
6203 (let* ((hl (save-match-data
6204 (org-link-expand-abbrev (match-string-no-properties 1))))
6205 (type (save-match-data
6206 (and (string-match org-plain-link-re hl)
6207 (match-string-no-properties 1 hl))))
6208 (path (save-match-data
6209 (and (string-match org-plain-link-re hl)
6210 (match-string-no-properties 2 hl))))
6211 (link-start (match-beginning 0))
6212 (link-end (match-end 0))
6213 (bracketp t)
6214 (help-echo (org-link-get-parameter type :help-echo))
6215 (help (cond
6216 ((stringp help-echo)
6217 help-echo)
6218 ((functionp help-echo)
6219 help-echo)
6221 (concat "LINK: "
6222 (save-match-data
6223 (org-link-unescape hl))))))
6224 (link-face (org-link-get-parameter type :face))
6225 (face (cond
6226 ;; A function that returns a face
6227 ((functionp link-face)
6228 (funcall link-face path))
6229 ;; a face
6230 ((facep link-face)
6231 link-face)
6232 ;; An anonymous face
6233 ((consp link-face)
6234 link-face)
6235 ;; default
6237 'org-link)))
6238 (keymap (or (org-link-get-parameter type :keymap)
6239 org-mouse-map))
6240 (mouse-face (or (org-link-get-parameter type :mouse-face)
6241 'highlight))
6242 (htmlize (org-link-get-parameter type :htmlize-link))
6243 (htmlize-link (cond
6244 ((functionp htmlize)
6245 (funcall htmlize))
6247 `(:uri ,(format "%s:%s" type path)))))
6248 (activate-func (org-link-get-parameter type :activate-func))
6249 ;; invisible part
6250 (ip (list 'invisible (or
6251 (org-link-get-parameter type :display)
6252 'org-link)
6253 'face face
6254 'keymap keymap
6255 'mouse-face mouse-face
6256 'font-lock-multiline t
6257 'help-echo help
6258 'htmlize-link htmlize-link))
6259 ;; visible part
6260 (vp (list 'keymap keymap
6261 'face face
6262 'mouse-face mouse-face
6263 'font-lock-multiline t
6264 'help-echo help
6265 'htmlize-link htmlize-link)))
6266 ;; We need to remove the invisible property here. Table narrowing
6267 ;; may have made some of this invisible.
6268 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6269 (remove-text-properties (match-beginning 0) (match-end 0)
6270 '(invisible nil))
6271 (if (match-end 3)
6272 (progn
6273 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6274 (org-rear-nonsticky-at (match-beginning 3))
6275 (add-text-properties (match-beginning 3) (match-end 3) vp)
6276 (org-rear-nonsticky-at (match-end 3))
6277 (add-text-properties (match-end 3) (match-end 0) ip)
6278 (org-rear-nonsticky-at (match-end 0)))
6279 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6280 (org-rear-nonsticky-at (match-beginning 1))
6281 (add-text-properties (match-beginning 1) (match-end 1) vp)
6282 (org-rear-nonsticky-at (match-end 1))
6283 (add-text-properties (match-end 1) (match-end 0) ip)
6284 (org-rear-nonsticky-at (match-end 0)))
6285 (when activate-func
6286 (funcall activate-func link-start link-end path bracketp))
6287 t)))
6289 (defun org-activate-dates (limit)
6290 "Add text properties for dates."
6291 (when (and (re-search-forward org-tsr-regexp-both limit t)
6292 (not (equal (char-before (match-beginning 0)) 91)))
6293 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6294 (add-text-properties (match-beginning 0) (match-end 0)
6295 (list 'mouse-face 'highlight
6296 'keymap org-mouse-map))
6297 (org-rear-nonsticky-at (match-end 0))
6298 (when org-display-custom-times
6299 (if (match-end 3)
6300 (org-display-custom-time (match-beginning 3) (match-end 3))
6301 (org-display-custom-time (match-beginning 1) (match-end 1))))
6304 (defvar-local org-target-link-regexp nil
6305 "Regular expression matching radio targets in plain text.")
6307 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6308 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6309 border border border))
6310 "Regular expression matching a link target.")
6312 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6313 "Regular expression matching a radio target.")
6315 (defconst org-any-target-regexp
6316 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6317 "Regular expression matching any target.")
6319 (defun org-activate-target-links (limit)
6320 "Add text properties for target matches."
6321 (when org-target-link-regexp
6322 (let ((case-fold-search t))
6323 (when (re-search-forward org-target-link-regexp limit t)
6324 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6325 (add-text-properties (match-beginning 1) (match-end 1)
6326 (list 'mouse-face 'highlight
6327 'keymap org-mouse-map
6328 'help-echo "Radio target link"
6329 'org-linked-text t))
6330 (org-rear-nonsticky-at (match-end 1))
6331 t))))
6333 (defun org-update-radio-target-regexp ()
6334 "Find all radio targets in this file and update the regular expression.
6335 Also refresh fontification if needed."
6336 (interactive)
6337 (let ((old-regexp org-target-link-regexp)
6338 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6339 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6340 (targets
6341 (org-with-wide-buffer
6342 (goto-char (point-min))
6343 (let (rtn)
6344 (while (re-search-forward org-radio-target-regexp nil t)
6345 ;; Make sure point is really within the object.
6346 (backward-char)
6347 (let ((obj (org-element-context)))
6348 (when (eq (org-element-type obj) 'radio-target)
6349 (cl-pushnew (org-element-property :value obj) rtn
6350 :test #'equal))))
6351 rtn))))
6352 (setq org-target-link-regexp
6353 (and targets
6354 (concat before-re
6355 (mapconcat
6356 (lambda (x)
6357 (replace-regexp-in-string
6358 " +" "\\s-+" (regexp-quote x) t t))
6359 targets
6360 "\\|")
6361 after-re)))
6362 (unless (equal old-regexp org-target-link-regexp)
6363 ;; Clean-up cache.
6364 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6365 ((not org-target-link-regexp) old-regexp)
6367 (concat before-re
6368 (mapconcat
6369 (lambda (re)
6370 (substring re (length before-re)
6371 (- (length after-re))))
6372 (list old-regexp org-target-link-regexp)
6373 "\\|")
6374 after-re)))))
6375 (org-with-wide-buffer
6376 (goto-char (point-min))
6377 (while (re-search-forward regexp nil t)
6378 (org-element-cache-refresh (match-beginning 1)))))
6379 ;; Re fontify buffer.
6380 (when (memq 'radio org-highlight-links)
6381 (org-restart-font-lock)))))
6383 (defun org-hide-wide-columns (limit)
6384 (let (s e)
6385 (setq s (text-property-any (point) (or limit (point-max))
6386 'org-cwidth t))
6387 (when s
6388 (setq e (next-single-property-change s 'org-cwidth))
6389 (add-text-properties s e '(invisible org-cwidth))
6390 (goto-char e)
6391 t)))
6393 (defvar org-latex-and-related-regexp nil
6394 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6396 (defun org-compute-latex-and-related-regexp ()
6397 "Compute regular expression for LaTeX, entities and sub/superscript.
6398 Result depends on variable `org-highlight-latex-and-related'."
6399 (setq-local
6400 org-latex-and-related-regexp
6401 (let* ((re-sub
6402 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6403 ((eq org-use-sub-superscripts '{})
6404 (list org-match-substring-with-braces-regexp))
6405 (org-use-sub-superscripts (list org-match-substring-regexp))))
6406 (re-latex
6407 (when (memq 'latex org-highlight-latex-and-related)
6408 (let ((matchers (plist-get org-format-latex-options :matchers)))
6409 (delq nil
6410 (mapcar (lambda (x)
6411 (and (member (car x) matchers) (nth 1 x)))
6412 org-latex-regexps)))))
6413 (re-entities
6414 (when (memq 'entities org-highlight-latex-and-related)
6415 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6416 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6418 (defun org-do-latex-and-related (limit)
6419 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6420 LIMIT bounds the search for syntax to highlight. Stop at first
6421 highlighted object, if any. Return t if some highlighting was
6422 done, nil otherwise."
6423 (when (org-string-nw-p org-latex-and-related-regexp)
6424 (catch 'found
6425 (while (re-search-forward org-latex-and-related-regexp limit t)
6426 (unless
6427 (cl-some
6428 (lambda (f)
6429 (memq f '(org-code org-verbatim underline org-special-keyword)))
6430 (save-excursion
6431 (goto-char (1+ (match-beginning 0)))
6432 (face-at-point nil t)))
6433 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6434 '(?_ ?^))
6436 0)))
6437 (font-lock-prepend-text-property
6438 (+ offset (match-beginning 0)) (match-end 0)
6439 'face 'org-latex-and-related)
6440 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6441 '(font-lock-multiline t)))
6442 (throw 'found t)))
6443 nil)))
6445 (defun org-restart-font-lock ()
6446 "Restart `font-lock-mode', to force refontification."
6447 (when (and (boundp 'font-lock-mode) font-lock-mode)
6448 (font-lock-mode -1)
6449 (font-lock-mode 1)))
6451 (defun org-activate-tags (limit)
6452 (when (re-search-forward
6453 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6454 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6455 (add-text-properties (match-beginning 1) (match-end 1)
6456 (list 'mouse-face 'highlight
6457 'keymap org-mouse-map))
6458 (org-rear-nonsticky-at (match-end 1))
6461 (defun org-outline-level ()
6462 "Compute the outline level of the heading at point.
6464 If this is called at a normal headline, the level is the number
6465 of stars. Use `org-reduced-level' to remove the effect of
6466 `org-odd-levels'. Unlike to `org-current-level', this function
6467 takes into consideration inlinetasks."
6468 (org-with-wide-buffer
6469 (end-of-line)
6470 (if (re-search-backward org-outline-regexp-bol nil t)
6471 (1- (- (match-end 0) (match-beginning 0)))
6472 0)))
6474 (defvar org-font-lock-keywords nil)
6476 (defsubst org-re-property (property &optional literal allow-null value)
6477 "Return a regexp matching a PROPERTY line.
6479 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6480 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6481 non-nil, match properties even without a value.
6483 Match group 3 is set to the value when it exists. If there is no
6484 value and ALLOW-NULL is non-nil, it is set to the empty string.
6486 With optional argument VALUE, match only property lines with
6487 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6488 unless LITERAL is non-nil."
6489 (concat
6490 "^\\(?4:[ \t]*\\)"
6491 (format "\\(?1::\\(?2:%s\\):\\)"
6492 (if literal property (regexp-quote property)))
6493 (cond (value
6494 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6495 (if literal value (regexp-quote value))))
6496 (allow-null
6497 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6499 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6501 (defconst org-property-re
6502 (org-re-property "\\S-+" 'literal t)
6503 "Regular expression matching a property line.
6504 There are four matching groups:
6505 1: :PROPKEY: including the leading and trailing colon,
6506 2: PROPKEY without the leading and trailing colon,
6507 3: PROPVAL without leading or trailing spaces,
6508 4: the indentation of the current line,
6509 5: trailing whitespace.")
6511 (defvar org-font-lock-hook nil
6512 "Functions to be called for special font lock stuff.")
6514 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6516 (defvar org-font-lock-set-keywords-hook nil
6517 "Functions that can manipulate `org-font-lock-extra-keywords'.
6518 This is called after `org-font-lock-extra-keywords' is defined, but before
6519 it is installed to be used by font lock. This can be useful if something
6520 needs to be inserted at a specific position in the font-lock sequence.")
6522 (defun org-font-lock-hook (limit)
6523 "Run `org-font-lock-hook' within LIMIT."
6524 (run-hook-with-args 'org-font-lock-hook limit))
6526 (defun org-set-font-lock-defaults ()
6527 "Set font lock defaults for the current buffer."
6528 (let* ((em org-fontify-emphasized-text)
6529 (lk org-highlight-links)
6530 (org-font-lock-extra-keywords
6531 (list
6532 ;; Call the hook
6533 '(org-font-lock-hook)
6534 ;; Headlines
6535 `(,(if org-fontify-whole-heading-line
6536 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6537 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6538 (1 (org-get-level-face 1))
6539 (2 (org-get-level-face 2))
6540 (3 (org-get-level-face 3)))
6541 ;; Table lines
6542 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6543 (1 'org-table t))
6544 ;; Table internals
6545 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6546 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6547 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6548 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6549 ;; Drawers
6550 '(org-fontify-drawers)
6551 ;; Properties
6552 (list org-property-re
6553 '(1 'org-special-keyword t)
6554 '(3 'org-property-value t))
6555 ;; Links
6556 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6557 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6558 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6559 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6560 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6561 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6562 (when (memq 'footnote lk) '(org-activate-footnote-links))
6563 ;; Targets.
6564 (list org-any-target-regexp '(0 'org-target t))
6565 ;; Diary sexps.
6566 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6567 ;; Macro
6568 '(org-fontify-macros)
6569 '(org-hide-wide-columns (0 nil append))
6570 ;; TODO keyword
6571 (list (format org-heading-keyword-regexp-format
6572 org-todo-regexp)
6573 '(2 (org-get-todo-face 2) t))
6574 ;; DONE
6575 (if org-fontify-done-headline
6576 (list (format org-heading-keyword-regexp-format
6577 (concat
6578 "\\(?:"
6579 (mapconcat 'regexp-quote org-done-keywords "\\|")
6580 "\\)"))
6581 '(2 'org-headline-done t))
6582 nil)
6583 ;; Priorities
6584 '(org-font-lock-add-priority-faces)
6585 ;; Tags
6586 '(org-font-lock-add-tag-faces)
6587 ;; Tags groups
6588 (when (and org-group-tags org-tag-groups-alist)
6589 (list (concat org-outline-regexp-bol ".+\\(:"
6590 (regexp-opt (mapcar 'car org-tag-groups-alist))
6591 ":\\).*$")
6592 '(1 'org-tag-group prepend)))
6593 ;; Special keywords
6594 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6595 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6596 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6597 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6598 ;; Emphasis
6599 (when em '(org-do-emphasis-faces))
6600 ;; Checkboxes
6601 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6602 1 'org-checkbox prepend)
6603 (when (cdr (assq 'checkbox org-list-automatic-rules))
6604 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6605 (0 (org-get-checkbox-statistics-face) t)))
6606 ;; Description list items
6607 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6608 1 'org-list-dt prepend)
6609 ;; ARCHIVEd headings
6610 (list (concat
6611 org-outline-regexp-bol
6612 "\\(.*:" org-archive-tag ":.*\\)")
6613 '(1 'org-archived prepend))
6614 ;; Specials
6615 '(org-do-latex-and-related)
6616 '(org-fontify-entities)
6617 '(org-raise-scripts)
6618 ;; Code
6619 '(org-activate-code (1 'org-code t))
6620 ;; COMMENT
6621 (list (format
6622 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6623 org-todo-regexp
6624 org-comment-string)
6625 '(9 'org-special-keyword t))
6626 ;; Blocks and meta lines
6627 '(org-fontify-meta-lines-and-blocks))))
6628 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6629 (run-hooks 'org-font-lock-set-keywords-hook)
6630 ;; Now set the full font-lock-keywords
6631 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6632 (setq-local font-lock-defaults
6633 '(org-font-lock-keywords t nil nil backward-paragraph))
6634 (kill-local-variable 'font-lock-keywords)
6635 nil))
6637 (defun org-toggle-pretty-entities ()
6638 "Toggle the composition display of entities as UTF8 characters."
6639 (interactive)
6640 (setq-local org-pretty-entities (not org-pretty-entities))
6641 (org-restart-font-lock)
6642 (if org-pretty-entities
6643 (message "Entities are now displayed as UTF8 characters")
6644 (save-restriction
6645 (widen)
6646 (decompose-region (point-min) (point-max))
6647 (message "Entities are now displayed as plain text"))))
6649 (defvar-local org-custom-properties-overlays nil
6650 "List of overlays used for custom properties.")
6652 (defun org-toggle-custom-properties-visibility ()
6653 "Display or hide properties in `org-custom-properties'."
6654 (interactive)
6655 (if org-custom-properties-overlays
6656 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6657 (setq org-custom-properties-overlays nil))
6658 (when org-custom-properties
6659 (org-with-wide-buffer
6660 (goto-char (point-min))
6661 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6662 (while (re-search-forward regexp nil t)
6663 (let ((end (cdr (save-match-data (org-get-property-block)))))
6664 (when (and end (< (point) end))
6665 ;; Hide first custom property in current drawer.
6666 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6667 (overlay-put o 'invisible t)
6668 (overlay-put o 'org-custom-property t)
6669 (push o org-custom-properties-overlays))
6670 ;; Hide additional custom properties in the same drawer.
6671 (while (re-search-forward regexp end t)
6672 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6673 (overlay-put o 'invisible t)
6674 (overlay-put o 'org-custom-property t)
6675 (push o org-custom-properties-overlays)))))
6676 ;; Each entry is limited to a single property drawer.
6677 (outline-next-heading)))))))
6679 (defun org-fontify-entities (limit)
6680 "Find an entity to fontify."
6681 (let (ee)
6682 (when org-pretty-entities
6683 (catch 'match
6684 ;; "\_ "-family is left out on purpose. Only the first one,
6685 ;; i.e., "\_ ", could be fontified anyway, and it would be
6686 ;; confusing when adding a second white space character.
6687 (while (re-search-forward
6688 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6689 limit t)
6690 (when (and (not (org-at-comment-p))
6691 (setq ee (org-entity-get (match-string 1)))
6692 (= (length (nth 6 ee)) 1))
6693 (let* ((end (if (equal (match-string 2) "{}")
6694 (match-end 2)
6695 (match-end 1))))
6696 (add-text-properties
6697 (match-beginning 0) end
6698 (list 'font-lock-fontified t))
6699 (compose-region (match-beginning 0) end
6700 (nth 6 ee) nil)
6701 (backward-char 1)
6702 (throw 'match t))))
6703 nil))))
6705 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6706 "Fontify string S like in Org mode."
6707 (with-temp-buffer
6708 (insert s)
6709 (let ((org-odd-levels-only odd-levels))
6710 (org-mode)
6711 (org-font-lock-ensure)
6712 (buffer-string))))
6714 (defvar org-m nil)
6715 (defvar org-l nil)
6716 (defvar org-f nil)
6717 (defun org-get-level-face (n)
6718 "Get the right face for match N in font-lock matching of headlines."
6719 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6720 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6721 (if org-cycle-level-faces
6722 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6723 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6724 (cond
6725 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6726 ((eq n 2) org-f)
6727 (t (unless org-level-color-stars-only org-f))))
6729 (defun org-face-from-face-or-color (context inherit face-or-color)
6730 "Create a face list that inherits INHERIT, but sets the foreground color.
6731 When FACE-OR-COLOR is not a string, just return it."
6732 (if (stringp face-or-color)
6733 (list :inherit inherit
6734 (cdr (assoc context org-faces-easy-properties))
6735 face-or-color)
6736 face-or-color))
6738 (defun org-get-todo-face (kwd)
6739 "Get the right face for a TODO keyword KWD.
6740 If KWD is a number, get the corresponding match group."
6741 (when (numberp kwd) (setq kwd (match-string kwd)))
6742 (or (org-face-from-face-or-color
6743 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6744 (and (member kwd org-done-keywords) 'org-done)
6745 'org-todo))
6747 (defun org-get-priority-face (priority)
6748 "Get the right face for PRIORITY.
6749 PRIORITY is a character."
6750 (or (org-face-from-face-or-color
6751 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6752 'org-priority))
6754 (defun org-get-tag-face (tag)
6755 "Get the right face for TAG.
6756 If TAG is a number, get the corresponding match group."
6757 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6758 (or (org-face-from-face-or-color
6759 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6760 'org-tag)))
6762 (defun org-font-lock-add-priority-faces (limit)
6763 "Add the special priority faces."
6764 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6765 (add-text-properties
6766 (match-beginning 1) (match-end 1)
6767 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6768 'font-lock-fontified t))))
6770 (defun org-font-lock-add-tag-faces (limit)
6771 "Add the special tag faces."
6772 (when (and org-tag-faces org-tags-special-faces-re)
6773 (while (re-search-forward org-tags-special-faces-re limit t)
6774 (add-text-properties (match-beginning 1) (match-end 1)
6775 (list 'face (org-get-tag-face 1)
6776 'font-lock-fontified t))
6777 (backward-char 1))))
6779 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6780 "Remove fontification and activation overlays from links."
6781 (font-lock-default-unfontify-region beg end)
6782 (let* ((buffer-undo-list t)
6783 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6784 (inhibit-modification-hooks t)
6785 deactivate-mark buffer-file-name buffer-file-truename)
6786 (decompose-region beg end)
6787 (remove-text-properties beg end
6788 '(mouse-face t keymap t org-linked-text t
6789 invisible t intangible t
6790 org-emphasis t))
6791 (org-remove-font-lock-display-properties beg end)))
6793 (defconst org-script-display '(((raise -0.3) (height 0.7))
6794 ((raise 0.3) (height 0.7))
6795 ((raise -0.5))
6796 ((raise 0.5)))
6797 "Display properties for showing superscripts and subscripts.")
6799 (defun org-remove-font-lock-display-properties (beg end)
6800 "Remove specific display properties that have been added by font lock.
6801 The will remove the raise properties that are used to show superscripts
6802 and subscripts."
6803 (let (next prop)
6804 (while (< beg end)
6805 (setq next (next-single-property-change beg 'display nil end)
6806 prop (get-text-property beg 'display))
6807 (when (member prop org-script-display)
6808 (put-text-property beg next 'display nil))
6809 (setq beg next))))
6811 (defun org-raise-scripts (limit)
6812 "Add raise properties to sub/superscripts."
6813 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6814 (re-search-forward
6815 (if (eq org-use-sub-superscripts t)
6816 org-match-substring-regexp
6817 org-match-substring-with-braces-regexp)
6818 limit t))
6819 (let* ((pos (point)) table-p comment-p
6820 (mpos (match-beginning 3))
6821 (emph-p (get-text-property mpos 'org-emphasis))
6822 (link-p (get-text-property mpos 'mouse-face))
6823 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6824 (goto-char (point-at-bol))
6825 (setq table-p (looking-at-p org-table-dataline-regexp)
6826 comment-p (looking-at-p "^[ \t]*#[ +]"))
6827 (goto-char pos)
6828 ;; Handle a_b^c
6829 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6830 (unless (or comment-p emph-p link-p keyw-p)
6831 (put-text-property (match-beginning 3) (match-end 0)
6832 'display
6833 (if (equal (char-after (match-beginning 2)) ?^)
6834 (nth (if table-p 3 1) org-script-display)
6835 (nth (if table-p 2 0) org-script-display)))
6836 (add-text-properties (match-beginning 2) (match-end 2)
6837 (list 'invisible t
6838 'org-dwidth t 'org-dwidth-n 1))
6839 (if (and (eq (char-after (match-beginning 3)) ?{)
6840 (eq (char-before (match-end 3)) ?}))
6841 (progn
6842 (add-text-properties
6843 (match-beginning 3) (1+ (match-beginning 3))
6844 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6845 (add-text-properties
6846 (1- (match-end 3)) (match-end 3)
6847 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6848 t)))
6850 ;;;; Visibility cycling, including org-goto and indirect buffer
6852 ;;; Cycling
6854 (defvar-local org-cycle-global-status nil)
6855 (put 'org-cycle-global-status 'org-state t)
6856 (defvar-local org-cycle-subtree-status nil)
6857 (put 'org-cycle-subtree-status 'org-state t)
6859 (defvar org-inlinetask-min-level)
6861 (defun org-unlogged-message (&rest args)
6862 "Display a message, but avoid logging it in the *Messages* buffer."
6863 (let ((message-log-max nil))
6864 (apply 'message args)))
6866 ;;;###autoload
6867 (defun org-cycle (&optional arg)
6868 "TAB-action and visibility cycling for Org mode.
6870 This is the command invoked in Org mode by the `TAB' key. Its main
6871 purpose is outline visibility cycling, but it also invokes other actions
6872 in special contexts.
6874 When this function is called with a `\\[universal-argument]' prefix, rotate \
6875 the entire
6876 buffer through 3 states (global cycling)
6877 1. OVERVIEW: Show only top-level headlines.
6878 2. CONTENTS: Show all headlines of all levels, but no body text.
6879 3. SHOW ALL: Show everything.
6881 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6882 switch to the startup visibility,
6883 determined by the variable `org-startup-folded', and by any VISIBILITY
6884 properties in the buffer.
6886 With a `\\[universal-argument] \\[universal-argument] \
6887 \\[universal-argument]' prefix argument, show the entire buffer, including
6888 any drawers.
6890 When inside a table, re-align the table and move to the next field.
6892 When point is at the beginning of a headline, rotate the subtree started
6893 by this line through 3 different states (local cycling)
6894 1. FOLDED: Only the main headline is shown.
6895 2. CHILDREN: The main headline and the direct children are shown.
6896 From this state, you can move to one of the children
6897 and zoom in further.
6898 3. SUBTREE: Show the entire subtree, including body text.
6899 If there is no subtree, switch directly from CHILDREN to FOLDED.
6901 When point is at the beginning of an empty headline and the variable
6902 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6903 of the headline by demoting and promoting it to likely levels. This
6904 speeds up creation document structure by pressing `TAB' once or several
6905 times right after creating a new headline.
6907 When there is a numeric prefix, go up to a heading with level ARG, do
6908 a `show-subtree' and return to the previous cursor position. If ARG
6909 is negative, go up that many levels.
6911 When point is not at the beginning of a headline, execute the global
6912 binding for `TAB', which is re-indenting the line. See the option
6913 `org-cycle-emulate-tab' for details.
6915 As a special case, if point is at the beginning of the buffer and there is
6916 no headline in line 1, this function will act as if called with prefix arg
6917 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6918 prefix arg, but only
6919 if the variable `org-cycle-global-at-bob' is t."
6920 (interactive "P")
6921 (org-load-modules-maybe)
6922 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6923 (and org-cycle-level-after-item/entry-creation
6924 (or (org-cycle-level)
6925 (org-cycle-item-indentation))))
6926 (let* ((limit-level
6927 (or org-cycle-max-level
6928 (and (boundp 'org-inlinetask-min-level)
6929 org-inlinetask-min-level
6930 (1- org-inlinetask-min-level))))
6931 (nstars (and limit-level
6932 (if org-odd-levels-only
6933 (and limit-level (1- (* limit-level 2)))
6934 limit-level)))
6935 (org-outline-regexp
6936 (if (not (derived-mode-p 'org-mode))
6937 outline-regexp
6938 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6939 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6940 (not (looking-at org-outline-regexp))))
6941 (org-cycle-hook
6942 (if bob-special
6943 (delq 'org-optimize-window-after-visibility-change
6944 (copy-sequence org-cycle-hook))
6945 org-cycle-hook))
6946 (pos (point)))
6948 (cond
6950 ((equal arg '(16))
6951 (setq last-command 'dummy)
6952 (org-set-startup-visibility)
6953 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6955 ((equal arg '(64))
6956 (outline-show-all)
6957 (org-unlogged-message "Entire buffer visible, including drawers"))
6959 ((equal arg '(4)) (org-cycle-internal-global))
6961 ;; Try hiding block at point.
6962 ((org-hide-block-toggle-maybe))
6964 ;; Try cdlatex TAB completion
6965 ((org-try-cdlatex-tab))
6967 ;; Table: enter it or move to the next field.
6968 ((org-at-table-p 'any)
6969 (if (org-at-table.el-p)
6970 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6971 Use `\\[org-edit-special]' to edit table.el tables"))
6972 (if arg (org-table-edit-field t)
6973 (org-table-justify-field-maybe)
6974 (call-interactively 'org-table-next-field))))
6976 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6978 ;; Global cycling: delegate to `org-cycle-internal-global'.
6979 (bob-special (org-cycle-internal-global))
6981 ;; Drawers: delegate to `org-flag-drawer'.
6982 ((save-excursion
6983 (beginning-of-line 1)
6984 (looking-at org-drawer-regexp))
6985 (org-flag-drawer ; toggle block visibility
6986 (not (get-char-property (match-end 0) 'invisible))))
6988 ;; Show-subtree, ARG levels up from here.
6989 ((integerp arg)
6990 (save-excursion
6991 (org-back-to-heading)
6992 (outline-up-heading (if (< arg 0) (- arg)
6993 (- (funcall outline-level) arg)))
6994 (org-show-subtree)))
6996 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6997 ((and (featurep 'org-inlinetask)
6998 (org-inlinetask-at-task-p)
6999 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
7000 (org-inlinetask-toggle-visibility))
7002 ;; At an item/headline: delegate to `org-cycle-internal-local'.
7003 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
7004 (save-excursion (move-beginning-of-line 1)
7005 (looking-at org-outline-regexp)))
7006 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
7007 (org-cycle-internal-local))
7009 ;; From there: TAB emulation and template completion.
7010 (buffer-read-only (org-back-to-heading))
7012 ((run-hook-with-args-until-success
7013 'org-tab-after-check-for-cycling-hook))
7015 ((org-try-structure-completion))
7017 ((run-hook-with-args-until-success
7018 'org-tab-before-tab-emulation-hook))
7020 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
7021 (or (not (bolp))
7022 (not (looking-at org-outline-regexp))))
7023 (call-interactively (global-key-binding "\t")))
7025 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
7026 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
7027 (or (and (eq org-cycle-emulate-tab 'white)
7028 (= (match-end 0) (point-at-eol)))
7029 (and (eq org-cycle-emulate-tab 'whitestart)
7030 (>= (match-end 0) pos))))
7032 (eq org-cycle-emulate-tab t))
7033 (call-interactively (global-key-binding "\t")))
7035 (t (save-excursion
7036 (org-back-to-heading)
7037 (org-cycle)))))))
7039 (defun org-cycle-internal-global ()
7040 "Do the global cycling action."
7041 ;; Hack to avoid display of messages for .org attachments in Gnus
7042 (let ((ga (string-match "\\*fontification" (buffer-name))))
7043 (cond
7044 ((and (eq last-command this-command)
7045 (eq org-cycle-global-status 'overview))
7046 ;; We just created the overview - now do table of contents
7047 ;; This can be slow in very large buffers, so indicate action
7048 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7049 (unless ga (org-unlogged-message "CONTENTS..."))
7050 (org-content)
7051 (unless ga (org-unlogged-message "CONTENTS...done"))
7052 (setq org-cycle-global-status 'contents)
7053 (run-hook-with-args 'org-cycle-hook 'contents))
7055 ((and (eq last-command this-command)
7056 (eq org-cycle-global-status 'contents))
7057 ;; We just showed the table of contents - now show everything
7058 (run-hook-with-args 'org-pre-cycle-hook 'all)
7059 (outline-show-all)
7060 (unless ga (org-unlogged-message "SHOW ALL"))
7061 (setq org-cycle-global-status 'all)
7062 (run-hook-with-args 'org-cycle-hook 'all))
7065 ;; Default action: go to overview
7066 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7067 (org-overview)
7068 (unless ga (org-unlogged-message "OVERVIEW"))
7069 (setq org-cycle-global-status 'overview)
7070 (run-hook-with-args 'org-cycle-hook 'overview)))))
7072 (defvar org-called-with-limited-levels nil
7073 "Non-nil when `org-with-limited-levels' is currently active.")
7075 (defun org-cycle-internal-local ()
7076 "Do the local cycling action."
7077 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7078 ;; First, determine end of headline (EOH), end of subtree or item
7079 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7080 (save-excursion
7081 (if (org-at-item-p)
7082 (progn
7083 (beginning-of-line)
7084 (setq struct (org-list-struct))
7085 (setq eoh (point-at-eol))
7086 (setq eos (org-list-get-item-end-before-blank (point) struct))
7087 (setq has-children (org-list-has-child-p (point) struct)))
7088 (org-back-to-heading)
7089 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7090 (setq eos (save-excursion (org-end-of-subtree t t)
7091 (when (bolp) (backward-char)) (point)))
7092 (setq has-children
7093 (or (save-excursion
7094 (let ((level (funcall outline-level)))
7095 (outline-next-heading)
7096 (and (org-at-heading-p t)
7097 (> (funcall outline-level) level))))
7098 (save-excursion
7099 (org-list-search-forward (org-item-beginning-re) eos t)))))
7100 ;; Determine end invisible part of buffer (EOL)
7101 (beginning-of-line 2)
7102 (while (and (not (eobp)) ;This is like `next-line'.
7103 (get-char-property (1- (point)) 'invisible))
7104 (goto-char (next-single-char-property-change (point) 'invisible))
7105 (and (eolp) (beginning-of-line 2)))
7106 (setq eol (point)))
7107 ;; Find out what to do next and set `this-command'
7108 (cond
7109 ((= eos eoh)
7110 ;; Nothing is hidden behind this heading
7111 (unless (org-before-first-heading-p)
7112 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7113 (org-unlogged-message "EMPTY ENTRY")
7114 (setq org-cycle-subtree-status nil)
7115 (save-excursion
7116 (goto-char eos)
7117 (outline-next-heading)
7118 (when (outline-invisible-p) (org-flag-heading nil))))
7119 ((and (or (>= eol eos)
7120 (not (string-match "\\S-" (buffer-substring eol eos))))
7121 (or has-children
7122 (not (setq children-skipped
7123 org-cycle-skip-children-state-if-no-children))))
7124 ;; Entire subtree is hidden in one line: children view
7125 (unless (org-before-first-heading-p)
7126 (run-hook-with-args 'org-pre-cycle-hook 'children))
7127 (if (org-at-item-p)
7128 (org-list-set-item-visibility (point-at-bol) struct 'children)
7129 (org-show-entry)
7130 (org-with-limited-levels (org-show-children))
7131 ;; FIXME: This slows down the func way too much.
7132 ;; How keep drawers hidden in subtree anyway?
7133 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7134 ;; (org-cycle-hide-drawers 'subtree))
7136 ;; Fold every list in subtree to top-level items.
7137 (when (eq org-cycle-include-plain-lists 'integrate)
7138 (save-excursion
7139 (org-back-to-heading)
7140 (while (org-list-search-forward (org-item-beginning-re) eos t)
7141 (beginning-of-line 1)
7142 (let* ((struct (org-list-struct))
7143 (prevs (org-list-prevs-alist struct))
7144 (end (org-list-get-bottom-point struct)))
7145 (dolist (e (org-list-get-all-items (point) struct prevs))
7146 (org-list-set-item-visibility e struct 'folded))
7147 (goto-char (if (< end eos) end eos)))))))
7148 (org-unlogged-message "CHILDREN")
7149 (save-excursion
7150 (goto-char eos)
7151 (outline-next-heading)
7152 (when (outline-invisible-p) (org-flag-heading nil)))
7153 (setq org-cycle-subtree-status 'children)
7154 (unless (org-before-first-heading-p)
7155 (run-hook-with-args 'org-cycle-hook 'children)))
7156 ((or children-skipped
7157 (and (eq last-command this-command)
7158 (eq org-cycle-subtree-status 'children)))
7159 ;; We just showed the children, or no children are there,
7160 ;; now show everything.
7161 (unless (org-before-first-heading-p)
7162 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7163 (outline-flag-region eoh eos nil)
7164 (org-unlogged-message
7165 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7166 (setq org-cycle-subtree-status 'subtree)
7167 (unless (org-before-first-heading-p)
7168 (run-hook-with-args 'org-cycle-hook 'subtree)))
7170 ;; Default action: hide the subtree.
7171 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7172 (outline-flag-region eoh eos t)
7173 (org-unlogged-message "FOLDED")
7174 (setq org-cycle-subtree-status 'folded)
7175 (unless (org-before-first-heading-p)
7176 (run-hook-with-args 'org-cycle-hook 'folded))))))
7178 ;;;###autoload
7179 (defun org-global-cycle (&optional arg)
7180 "Cycle the global visibility. For details see `org-cycle'.
7181 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7182 With a numeric prefix, show all headlines up to that level."
7183 (interactive "P")
7184 (let ((org-cycle-include-plain-lists
7185 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7186 (cond
7187 ((integerp arg)
7188 (outline-show-all)
7189 (outline-hide-sublevels arg)
7190 (setq org-cycle-global-status 'contents))
7191 ((equal arg '(4))
7192 (org-set-startup-visibility)
7193 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7195 (org-cycle '(4))))))
7197 (defun org-set-startup-visibility ()
7198 "Set the visibility required by startup options and properties."
7199 (cond
7200 ((eq org-startup-folded t)
7201 (org-overview))
7202 ((eq org-startup-folded 'content)
7203 (org-content))
7204 ((or (eq org-startup-folded 'showeverything)
7205 (eq org-startup-folded nil))
7206 (outline-show-all)))
7207 (unless (eq org-startup-folded 'showeverything)
7208 (when org-hide-block-startup (org-hide-block-all))
7209 (org-set-visibility-according-to-property 'no-cleanup)
7210 (org-cycle-hide-archived-subtrees 'all)
7211 (org-cycle-hide-drawers 'all)
7212 (org-cycle-show-empty-lines t)))
7214 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7215 "Switch subtree visibilities according to :VISIBILITY: property."
7216 (interactive)
7217 (org-with-wide-buffer
7218 (goto-char (point-min))
7219 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7220 (if (not (org-at-property-p)) (outline-next-heading)
7221 (let ((state (match-string 3)))
7222 (save-excursion
7223 (org-back-to-heading t)
7224 (outline-hide-subtree)
7225 (org-reveal)
7226 (cond
7227 ((equal state "folded")
7228 (outline-hide-subtree))
7229 ((equal state "children")
7230 (org-show-hidden-entry)
7231 (org-show-children))
7232 ((equal state "content")
7233 (save-excursion
7234 (save-restriction
7235 (org-narrow-to-subtree)
7236 (org-content))))
7237 ((member state '("all" "showall"))
7238 (outline-show-subtree)))))))
7239 (unless no-cleanup
7240 (org-cycle-hide-archived-subtrees 'all)
7241 (org-cycle-hide-drawers 'all)
7242 (org-cycle-show-empty-lines 'all))))
7244 ;; This function uses outline-regexp instead of the more fundamental
7245 ;; org-outline-regexp so that org-cycle-global works outside of Org
7246 ;; buffers, where outline-regexp is needed.
7247 (defun org-overview ()
7248 "Switch to overview mode, showing only top-level headlines.
7249 This shows all headlines with a level equal or greater than the level
7250 of the first headline in the buffer. This is important, because if the
7251 first headline is not level one, then (hide-sublevels 1) gives confusing
7252 results."
7253 (interactive)
7254 (save-excursion
7255 (let ((level
7256 (save-excursion
7257 (goto-char (point-min))
7258 (when (re-search-forward (concat "^" outline-regexp) nil t)
7259 (goto-char (match-beginning 0))
7260 (funcall outline-level)))))
7261 (and level (outline-hide-sublevels level)))))
7263 (defun org-content (&optional arg)
7264 "Show all headlines in the buffer, like a table of contents.
7265 With numerical argument N, show content up to level N."
7266 (interactive "P")
7267 (org-overview)
7268 (save-excursion
7269 ;; Visit all headings and show their offspring
7270 (and (integerp arg) (org-overview))
7271 (goto-char (point-max))
7272 (catch 'exit
7273 (while (and (progn (condition-case nil
7274 (outline-previous-visible-heading 1)
7275 (error (goto-char (point-min))))
7277 (looking-at org-outline-regexp))
7278 (if (integerp arg)
7279 (org-show-children (1- arg))
7280 (outline-show-branches))
7281 (when (bobp) (throw 'exit nil))))))
7283 (defun org-optimize-window-after-visibility-change (state)
7284 "Adjust the window after a change in outline visibility.
7285 This function is the default value of the hook `org-cycle-hook'."
7286 (when (get-buffer-window (current-buffer))
7287 (cond
7288 ((eq state 'content) nil)
7289 ((eq state 'all) nil)
7290 ((eq state 'folded) nil)
7291 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7292 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7294 (defun org-remove-empty-overlays-at (pos)
7295 "Remove outline overlays that do not contain non-white stuff."
7296 (dolist (o (overlays-at pos))
7297 (and (eq 'outline (overlay-get o 'invisible))
7298 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7299 (overlay-end o))))
7300 (delete-overlay o))))
7302 (defun org-clean-visibility-after-subtree-move ()
7303 "Fix visibility issues after moving a subtree."
7304 ;; First, find a reasonable region to look at:
7305 ;; Start two siblings above, end three below
7306 (let* ((beg (save-excursion
7307 (and (org-get-last-sibling)
7308 (org-get-last-sibling))
7309 (point)))
7310 (end (save-excursion
7311 (and (org-get-next-sibling)
7312 (org-get-next-sibling)
7313 (org-get-next-sibling))
7314 (if (org-at-heading-p)
7315 (point-at-eol)
7316 (point))))
7317 (level (looking-at "\\*+"))
7318 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7319 (save-excursion
7320 (save-restriction
7321 (narrow-to-region beg end)
7322 (when re
7323 ;; Properly fold already folded siblings
7324 (goto-char (point-min))
7325 (while (re-search-forward re nil t)
7326 (when (and (not (outline-invisible-p))
7327 (save-excursion
7328 (goto-char (point-at-eol)) (outline-invisible-p)))
7329 (outline-hide-entry))))
7330 (org-cycle-show-empty-lines 'overview)
7331 (org-cycle-hide-drawers 'overview)))))
7333 (defun org-cycle-show-empty-lines (state)
7334 "Show empty lines above all visible headlines.
7335 The region to be covered depends on STATE when called through
7336 `org-cycle-hook'. Lisp program can use t for STATE to get the
7337 entire buffer covered. Note that an empty line is only shown if there
7338 are at least `org-cycle-separator-lines' empty lines before the headline."
7339 (when (/= org-cycle-separator-lines 0)
7340 (save-excursion
7341 (let* ((n (abs org-cycle-separator-lines))
7342 (re (cond
7343 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7344 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7345 (t (let ((ns (number-to-string (- n 2))))
7346 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7347 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7348 beg end)
7349 (cond
7350 ((memq state '(overview contents t))
7351 (setq beg (point-min) end (point-max)))
7352 ((memq state '(children folded))
7353 (setq beg (point)
7354 end (progn (org-end-of-subtree t t)
7355 (line-beginning-position 2)))))
7356 (when beg
7357 (goto-char beg)
7358 (while (re-search-forward re end t)
7359 (unless (get-char-property (match-end 1) 'invisible)
7360 (let ((e (match-end 1))
7361 (b (if (>= org-cycle-separator-lines 0)
7362 (match-beginning 1)
7363 (save-excursion
7364 (goto-char (match-beginning 0))
7365 (skip-chars-backward " \t\n")
7366 (line-end-position)))))
7367 (outline-flag-region b e nil))))))))
7368 ;; Never hide empty lines at the end of the file.
7369 (save-excursion
7370 (goto-char (point-max))
7371 (outline-previous-heading)
7372 (outline-end-of-heading)
7373 (when (and (looking-at "[ \t\n]+")
7374 (= (match-end 0) (point-max)))
7375 (outline-flag-region (point) (match-end 0) nil))))
7377 (defun org-show-empty-lines-in-parent ()
7378 "Move to the parent and re-show empty lines before visible headlines."
7379 (save-excursion
7380 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7381 (org-cycle-show-empty-lines context))))
7383 (defun org-files-list ()
7384 "Return `org-agenda-files' list, plus all open Org files.
7385 This is useful for operations that need to scan all of a user's
7386 open and agenda-wise Org files."
7387 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7388 (dolist (buf (buffer-list))
7389 (with-current-buffer buf
7390 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7391 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7392 files))
7394 (defsubst org-entry-beginning-position ()
7395 "Return the beginning position of the current entry."
7396 (save-excursion (org-back-to-heading t) (point)))
7398 (defsubst org-entry-end-position ()
7399 "Return the end position of the current entry."
7400 (save-excursion (outline-next-heading) (point)))
7402 (defun org-cycle-hide-drawers (state &optional exceptions)
7403 "Re-hide all drawers after a visibility state change.
7404 When non-nil, optional argument EXCEPTIONS is a list of strings
7405 specifying which drawers should not be hidden."
7406 (when (and (derived-mode-p 'org-mode)
7407 (not (memq state '(overview folded contents))))
7408 (save-excursion
7409 (let* ((globalp (memq state '(contents all)))
7410 (beg (if globalp (point-min) (point)))
7411 (end (if globalp (point-max)
7412 (if (eq state 'children)
7413 (save-excursion (outline-next-heading) (point))
7414 (org-end-of-subtree t)))))
7415 (goto-char beg)
7416 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7417 (unless (member-ignore-case (match-string 1) exceptions)
7418 (let ((drawer (org-element-at-point)))
7419 (when (memq (org-element-type drawer) '(drawer property-drawer))
7420 (org-flag-drawer t drawer)
7421 ;; Make sure to skip drawer entirely or we might flag
7422 ;; it another time when matching its ending line with
7423 ;; `org-drawer-regexp'.
7424 (goto-char (org-element-property :end drawer))))))))))
7426 (defun org-flag-drawer (flag &optional element)
7427 "When FLAG is non-nil, hide the drawer we are at.
7428 Otherwise make it visible. When optional argument ELEMENT is
7429 a parsed drawer, as returned by `org-element-at-point', hide or
7430 show that drawer instead."
7431 (let ((drawer (or element
7432 (and (save-excursion
7433 (beginning-of-line)
7434 (looking-at-p org-drawer-regexp))
7435 (org-element-at-point)))))
7436 (when (memq (org-element-type drawer) '(drawer property-drawer))
7437 (let ((post (org-element-property :post-affiliated drawer)))
7438 (save-excursion
7439 (outline-flag-region
7440 (progn (goto-char post) (line-end-position))
7441 (progn (goto-char (org-element-property :end drawer))
7442 (skip-chars-backward " \r\t\n")
7443 (line-end-position))
7444 flag))
7445 ;; When the drawer is hidden away, make sure point lies in
7446 ;; a visible part of the buffer.
7447 (when (and flag (> (line-beginning-position) post))
7448 (goto-char post))))))
7450 (defun org-subtree-end-visible-p ()
7451 "Is the end of the current subtree visible?"
7452 (pos-visible-in-window-p
7453 (save-excursion (org-end-of-subtree t) (point))))
7455 (defun org-first-headline-recenter ()
7456 "Move cursor to the first headline and recenter the headline."
7457 (let ((window (get-buffer-window)))
7458 (when window
7459 (goto-char (point-min))
7460 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7461 (set-window-start window (line-beginning-position))))))
7463 ;;; Saving and restoring visibility
7465 (defun org-outline-overlay-data (&optional use-markers)
7466 "Return a list of the locations of all outline overlays.
7467 These are overlays with the `invisible' property value `outline'.
7468 The return value is a list of cons cells, with start and stop
7469 positions for each overlay.
7470 If USE-MARKERS is set, return the positions as markers."
7471 (let (beg end)
7472 (org-with-wide-buffer
7473 (delq nil
7474 (mapcar (lambda (o)
7475 (when (eq (overlay-get o 'invisible) 'outline)
7476 (setq beg (overlay-start o)
7477 end (overlay-end o))
7478 (and beg end (> end beg)
7479 (if use-markers
7480 (cons (copy-marker beg)
7481 (copy-marker end t))
7482 (cons beg end)))))
7483 (overlays-in (point-min) (point-max)))))))
7485 (defun org-set-outline-overlay-data (data)
7486 "Create visibility overlays for all positions in DATA.
7487 DATA should have been made by `org-outline-overlay-data'."
7488 (org-with-wide-buffer
7489 (outline-show-all)
7490 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7492 ;;; Folding of blocks
7494 (defvar-local org-hide-block-overlays nil
7495 "Overlays hiding blocks.")
7497 (defun org-block-map (function &optional start end)
7498 "Call FUNCTION at the head of all source blocks in the current buffer.
7499 Optional arguments START and END can be used to limit the range."
7500 (let ((start (or start (point-min)))
7501 (end (or end (point-max))))
7502 (save-excursion
7503 (goto-char start)
7504 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7505 (save-excursion
7506 (save-match-data
7507 (goto-char (match-beginning 0))
7508 (funcall function)))))))
7510 (defun org-hide-block-toggle-all ()
7511 "Toggle the visibility of all blocks in the current buffer."
7512 (org-block-map 'org-hide-block-toggle))
7514 (defun org-hide-block-all ()
7515 "Fold all blocks in the current buffer."
7516 (interactive)
7517 (org-show-block-all)
7518 (org-block-map 'org-hide-block-toggle-maybe))
7520 (defun org-show-block-all ()
7521 "Unfold all blocks in the current buffer."
7522 (interactive)
7523 (mapc #'delete-overlay org-hide-block-overlays)
7524 (setq org-hide-block-overlays nil))
7526 (defun org-hide-block-toggle-maybe ()
7527 "Toggle visibility of block at point.
7528 Unlike to `org-hide-block-toggle', this function does not throw
7529 an error. Return a non-nil value when toggling is successful."
7530 (interactive)
7531 (ignore-errors (org-hide-block-toggle)))
7533 (defun org-hide-block-toggle (&optional force)
7534 "Toggle the visibility of the current block.
7535 When optional argument FORCE is `off', make block visible. If it
7536 is non-nil, hide it unconditionally. Throw an error when not at
7537 a block. Return a non-nil value when toggling is successful."
7538 (interactive)
7539 (let ((element (org-element-at-point)))
7540 (unless (memq (org-element-type element)
7541 '(center-block comment-block dynamic-block example-block
7542 export-block quote-block special-block
7543 src-block verse-block))
7544 (user-error "Not at a block"))
7545 (let* ((start (save-excursion
7546 (goto-char (org-element-property :post-affiliated element))
7547 (line-end-position)))
7548 (end (save-excursion
7549 (goto-char (org-element-property :end element))
7550 (skip-chars-backward " \r\t\n")
7551 (line-end-position)))
7552 (overlays (overlays-at start)))
7553 (cond
7554 ;; Do nothing when not before or at the block opening line or
7555 ;; at the block closing line.
7556 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7557 ((and (not (eq force 'off))
7558 (not (memq t (mapcar
7559 (lambda (o)
7560 (eq (overlay-get o 'invisible) 'org-hide-block))
7561 overlays))))
7562 (let ((ov (make-overlay start end)))
7563 (overlay-put ov 'invisible 'org-hide-block)
7564 ;; Make the block accessible to `isearch'.
7565 (overlay-put
7566 ov 'isearch-open-invisible
7567 (lambda (ov)
7568 (when (memq ov org-hide-block-overlays)
7569 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7570 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7571 (delete-overlay ov))))
7572 (push ov org-hide-block-overlays)
7573 ;; When the block is hidden away, make sure point is left in
7574 ;; a visible part of the buffer.
7575 (when (> (line-beginning-position) start)
7576 (goto-char start)
7577 (beginning-of-line))
7578 ;; Signal successful toggling.
7580 ((or (not force) (eq force 'off))
7581 (dolist (ov overlays t)
7582 (when (memq ov org-hide-block-overlays)
7583 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7584 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7585 (delete-overlay ov))))))))
7587 ;; Remove overlays when changing major mode
7588 (add-hook 'org-mode-hook
7589 (lambda () (add-hook 'change-major-mode-hook
7590 'org-show-block-all 'append 'local)))
7592 ;;; Org-goto
7594 (defvar org-goto-window-configuration nil)
7595 (defvar org-goto-marker nil)
7596 (defvar org-goto-map)
7597 (defun org-goto-map ()
7598 "Set the keymap `org-goto'."
7599 (setq org-goto-map
7600 (let ((map (make-sparse-keymap)))
7601 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7602 mouse-drag-region universal-argument org-occur)))
7603 (dolist (cmd cmds)
7604 (substitute-key-definition cmd cmd map global-map)))
7605 (suppress-keymap map)
7606 (org-defkey map "\C-m" 'org-goto-ret)
7607 (org-defkey map [(return)] 'org-goto-ret)
7608 (org-defkey map [(left)] 'org-goto-left)
7609 (org-defkey map [(right)] 'org-goto-right)
7610 (org-defkey map [(control ?g)] 'org-goto-quit)
7611 (org-defkey map "\C-i" 'org-cycle)
7612 (org-defkey map [(tab)] 'org-cycle)
7613 (org-defkey map [(down)] 'outline-next-visible-heading)
7614 (org-defkey map [(up)] 'outline-previous-visible-heading)
7615 (if org-goto-auto-isearch
7616 (if (fboundp 'define-key-after)
7617 (define-key-after map [t] 'org-goto-local-auto-isearch)
7618 nil)
7619 (org-defkey map "q" 'org-goto-quit)
7620 (org-defkey map "n" 'outline-next-visible-heading)
7621 (org-defkey map "p" 'outline-previous-visible-heading)
7622 (org-defkey map "f" 'outline-forward-same-level)
7623 (org-defkey map "b" 'outline-backward-same-level)
7624 (org-defkey map "u" 'outline-up-heading))
7625 (org-defkey map "/" 'org-occur)
7626 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7627 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7628 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7629 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7630 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7631 map)))
7633 (defconst org-goto-help
7634 "Browse buffer copy, to find location or copy text.%s
7635 RET=jump to location C-g=quit and return to previous location
7636 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7638 (defvar org-goto-start-pos) ; dynamically scoped parameter
7640 (defun org-goto (&optional alternative-interface)
7641 "Look up a different location in the current file, keeping current visibility.
7643 When you want look-up or go to a different location in a
7644 document, the fastest way is often to fold the entire buffer and
7645 then dive into the tree. This method has the disadvantage, that
7646 the previous location will be folded, which may not be what you
7647 want.
7649 This command works around this by showing a copy of the current
7650 buffer in an indirect buffer, in overview mode. You can dive
7651 into the tree in that copy, use org-occur and incremental search
7652 to find a location. When pressing RET or `Q', the command
7653 returns to the original buffer in which the visibility is still
7654 unchanged. After RET it will also jump to the location selected
7655 in the indirect buffer and expose the headline hierarchy above.
7657 With a prefix argument, use the alternative interface: e.g., if
7658 `org-goto-interface' is `outline' use `outline-path-completion'."
7659 (interactive "P")
7660 (org-goto-map)
7661 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7662 (org-refile-use-outline-path t)
7663 (org-refile-target-verify-function nil)
7664 (interface
7665 (if (not alternative-interface)
7666 org-goto-interface
7667 (if (eq org-goto-interface 'outline)
7668 'outline-path-completion
7669 'outline)))
7670 (org-goto-start-pos (point))
7671 (selected-point
7672 (if (eq interface 'outline)
7673 (car (org-get-location (current-buffer) org-goto-help))
7674 (let ((pa (org-refile-get-location "Goto")))
7675 (org-refile-check-position pa)
7676 (nth 3 pa)))))
7677 (if selected-point
7678 (progn
7679 (org-mark-ring-push org-goto-start-pos)
7680 (goto-char selected-point)
7681 (when (or (outline-invisible-p) (org-invisible-p2))
7682 (org-show-context 'org-goto)))
7683 (message "Quit"))))
7685 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7686 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7687 (defvar org-goto-local-auto-isearch-map) ; defined below
7689 (defun org-get-location (_buf help)
7690 "Let the user select a location in current buffer.
7691 This function uses a recursive edit. It returns the selected position
7692 or nil."
7693 (org-no-popups
7694 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7695 (isearch-hide-immediately nil)
7696 (isearch-search-fun-function
7697 (lambda () 'org-goto-local-search-headings))
7698 (org-goto-selected-point org-goto-exit-command))
7699 (save-excursion
7700 (save-window-excursion
7701 (delete-other-windows)
7702 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7703 (pop-to-buffer-same-window
7704 (condition-case nil
7705 (make-indirect-buffer (current-buffer) "*org-goto*")
7706 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7707 (with-output-to-temp-buffer "*Org Help*"
7708 (princ (format help (if org-goto-auto-isearch
7709 " Just type for auto-isearch."
7710 " n/p/f/b/u to navigate, q to quit."))))
7711 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7712 (setq buffer-read-only nil)
7713 (let ((org-startup-truncated t)
7714 (org-startup-folded nil)
7715 (org-startup-align-all-tables nil))
7716 (org-mode)
7717 (org-overview))
7718 (setq buffer-read-only t)
7719 (if (and (boundp 'org-goto-start-pos)
7720 (integer-or-marker-p org-goto-start-pos))
7721 (progn (goto-char org-goto-start-pos)
7722 (when (outline-invisible-p)
7723 (org-show-set-visibility 'lineage)))
7724 (goto-char (point-min)))
7725 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7726 (message "Select location and press RET")
7727 (use-local-map org-goto-map)
7728 (recursive-edit)))
7729 (kill-buffer "*org-goto*")
7730 (cons org-goto-selected-point org-goto-exit-command))))
7732 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7733 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7734 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7735 (if (fboundp 'isearch-other-control-char)
7736 (progn
7737 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7738 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7739 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7740 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7741 (define-key org-goto-local-auto-isearch-map [return] nil))
7743 (defun org-goto-local-search-headings (string bound noerror)
7744 "Search and make sure that any matches are in headlines."
7745 (catch 'return
7746 (while (if isearch-forward
7747 (search-forward string bound noerror)
7748 (search-backward string bound noerror))
7749 (when (save-match-data
7750 (and (save-excursion
7751 (beginning-of-line)
7752 (looking-at org-complex-heading-regexp))
7753 (or (not (match-beginning 5))
7754 (< (point) (match-beginning 5)))))
7755 (throw 'return (point))))))
7757 (defun org-goto-local-auto-isearch ()
7758 "Start isearch."
7759 (interactive)
7760 (goto-char (point-min))
7761 (let ((keys (this-command-keys)))
7762 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7763 (isearch-mode t)
7764 (isearch-process-search-char (string-to-char keys)))))
7766 (defun org-goto-ret (&optional _arg)
7767 "Finish `org-goto' by going to the new location."
7768 (interactive "P")
7769 (setq org-goto-selected-point (point))
7770 (setq org-goto-exit-command 'return)
7771 (throw 'exit nil))
7773 (defun org-goto-left ()
7774 "Finish `org-goto' by going to the new location."
7775 (interactive)
7776 (if (org-at-heading-p)
7777 (progn
7778 (beginning-of-line 1)
7779 (setq org-goto-selected-point (point)
7780 org-goto-exit-command 'left)
7781 (throw 'exit nil))
7782 (user-error "Not on a heading")))
7784 (defun org-goto-right ()
7785 "Finish `org-goto' by going to the new location."
7786 (interactive)
7787 (if (org-at-heading-p)
7788 (progn
7789 (setq org-goto-selected-point (point)
7790 org-goto-exit-command 'right)
7791 (throw 'exit nil))
7792 (user-error "Not on a heading")))
7794 (defun org-goto-quit ()
7795 "Finish `org-goto' without cursor motion."
7796 (interactive)
7797 (setq org-goto-selected-point nil)
7798 (setq org-goto-exit-command 'quit)
7799 (throw 'exit nil))
7801 ;;; Indirect buffer display of subtrees
7803 (defvar org-indirect-dedicated-frame nil
7804 "This is the frame being used for indirect tree display.")
7805 (defvar org-last-indirect-buffer nil)
7807 (defun org-tree-to-indirect-buffer (&optional arg)
7808 "Create indirect buffer and narrow it to current subtree.
7810 With a numerical prefix ARG, go up to this level and then take that tree.
7811 If ARG is negative, go up that many levels.
7813 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7814 indirect buffer previously made with this command, to avoid proliferation of
7815 indirect buffers. However, when you call the command with a \
7816 `\\[universal-argument]' prefix, or
7817 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7818 so that you can work with several indirect buffers at the same time. If
7819 `org-indirect-buffer-display' is `dedicated-frame', the \
7820 `\\[universal-argument]' prefix also
7821 requests that a new frame be made for the new buffer, so that the dedicated
7822 frame is not changed."
7823 (interactive "P")
7824 (let ((cbuf (current-buffer))
7825 (cwin (selected-window))
7826 (pos (point))
7827 beg end level heading ibuf)
7828 (save-excursion
7829 (org-back-to-heading t)
7830 (when (numberp arg)
7831 (setq level (org-outline-level))
7832 (when (< arg 0) (setq arg (+ level arg)))
7833 (while (> (setq level (org-outline-level)) arg)
7834 (org-up-heading-safe)))
7835 (setq beg (point)
7836 heading (org-get-heading 'no-tags))
7837 (org-end-of-subtree t t)
7838 (when (org-at-heading-p) (backward-char 1))
7839 (setq end (point)))
7840 (when (and (buffer-live-p org-last-indirect-buffer)
7841 (not (eq org-indirect-buffer-display 'new-frame))
7842 (not arg))
7843 (kill-buffer org-last-indirect-buffer))
7844 (setq ibuf (org-get-indirect-buffer cbuf heading)
7845 org-last-indirect-buffer ibuf)
7846 (cond
7847 ((or (eq org-indirect-buffer-display 'new-frame)
7848 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7849 (select-frame (make-frame))
7850 (delete-other-windows)
7851 (pop-to-buffer-same-window ibuf)
7852 (org-set-frame-title heading))
7853 ((eq org-indirect-buffer-display 'dedicated-frame)
7854 (raise-frame
7855 (select-frame (or (and org-indirect-dedicated-frame
7856 (frame-live-p org-indirect-dedicated-frame)
7857 org-indirect-dedicated-frame)
7858 (setq org-indirect-dedicated-frame (make-frame)))))
7859 (delete-other-windows)
7860 (pop-to-buffer-same-window ibuf)
7861 (org-set-frame-title (concat "Indirect: " heading)))
7862 ((eq org-indirect-buffer-display 'current-window)
7863 (pop-to-buffer-same-window ibuf))
7864 ((eq org-indirect-buffer-display 'other-window)
7865 (pop-to-buffer ibuf))
7866 (t (error "Invalid value")))
7867 (narrow-to-region beg end)
7868 (outline-show-all)
7869 (goto-char pos)
7870 (run-hook-with-args 'org-cycle-hook 'all)
7871 (and (window-live-p cwin) (select-window cwin))))
7873 (defun org-get-indirect-buffer (&optional buffer heading)
7874 (setq buffer (or buffer (current-buffer)))
7875 (let ((n 1) (base (buffer-name buffer)) bname)
7876 (while (buffer-live-p
7877 (get-buffer
7878 (setq bname
7879 (concat base "-"
7880 (if heading (concat heading "-" (number-to-string n))
7881 (number-to-string n))))))
7882 (setq n (1+ n)))
7883 (condition-case nil
7884 (make-indirect-buffer buffer bname 'clone)
7885 (error (make-indirect-buffer buffer bname)))))
7887 (defun org-set-frame-title (title)
7888 "Set the title of the current frame to the string TITLE."
7889 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7891 ;;;; Structure editing
7893 ;;; Inserting headlines
7895 (defun org--line-empty-p (n)
7896 "Is the Nth next line empty?
7898 Counts the current line as N = 1 and the previous line as N = 0;
7899 see `beginning-of-line'."
7900 (save-excursion
7901 (and (not (bobp))
7902 (or (beginning-of-line n) t)
7903 (save-match-data
7904 (looking-at "[ \t]*$")))))
7906 (defun org-previous-line-empty-p ()
7907 "Is the previous line a blank line?
7908 When NEXT is non-nil, check the next line instead."
7909 (org--line-empty-p 0))
7911 (defun org-next-line-empty-p ()
7912 "Is the previous line a blank line?
7913 When NEXT is non-nil, check the next line instead."
7914 (org--line-empty-p 2))
7916 (defun org-insert-heading (&optional arg invisible-ok top)
7917 "Insert a new heading or an item with the same depth at point.
7919 If point is at the beginning of a heading or a list item, insert
7920 a new heading or a new item above the current one. When at the
7921 beginning of a regular line of text, turn it into a heading.
7923 If point is in the middle of a line, split it and create a new
7924 headline/item with the text in the current line after point (see
7925 `org-M-RET-may-split-line' on how to modify this behavior). As
7926 a special case, on a headline, splitting can only happen on the
7927 title itself. E.g., this excludes breaking stars or tags.
7929 With a `\\[universal-argument]' prefix, set \
7930 `org-insert-heading-respect-content' to
7931 a non-nil value for the duration of the command. This forces the
7932 insertion of a heading after the current subtree, independently
7933 on the location of point.
7935 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7936 insert the heading at the end of the tree
7937 above the current heading. For example, if point is within a
7938 2nd-level heading, then it will insert a 2nd-level heading at
7939 the end of the 1st-level parent subtree.
7941 When INVISIBLE-OK is set, stop at invisible headlines when going
7942 back. This is important for non-interactive uses of the
7943 command.
7945 When optional argument TOP is non-nil, insert a level 1 heading,
7946 unconditionally."
7947 (interactive "P")
7948 (let ((itemp (and (not top) (org-in-item-p)))
7949 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7950 (respect-content (or org-insert-heading-respect-content
7951 (equal arg '(4))))
7952 (initial-content ""))
7954 (cond
7956 ((or (= (buffer-size) 0)
7957 (and (not (save-excursion
7958 (and (ignore-errors (org-back-to-heading invisible-ok))
7959 (org-at-heading-p))))
7960 (or arg (not itemp))))
7961 ;; At beginning of buffer or so high up that only a heading
7962 ;; makes sense.
7963 (cond ((and (bolp) (not respect-content)) (insert "* "))
7964 ((not respect-content)
7965 (unless may-split (end-of-line))
7966 (insert "\n* "))
7967 ((re-search-forward org-outline-regexp-bol nil t)
7968 (beginning-of-line)
7969 (insert "* \n")
7970 (backward-char))
7971 (t (goto-char (point-max))
7972 (insert "\n* ")))
7973 (run-hooks 'org-insert-heading-hook))
7975 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7978 ;; Maybe move at the end of the subtree
7979 (when (equal arg '(16))
7980 (org-up-heading-safe)
7981 (org-end-of-subtree t))
7982 ;; Insert a heading
7983 (save-restriction
7984 (widen)
7985 (let* ((level nil)
7986 (on-heading (org-at-heading-p))
7987 (empty-line-p (if on-heading
7988 (org-previous-line-empty-p)
7989 ;; We will decide later
7990 nil))
7991 ;; Get a level string to fall back on.
7992 (fix-level
7993 (if (org-before-first-heading-p) "*"
7994 (save-excursion
7995 (org-back-to-heading t)
7996 (when (org-previous-line-empty-p) (setq empty-line-p t))
7997 (looking-at org-outline-regexp)
7998 (make-string (1- (length (match-string 0))) ?*))))
7999 (stars
8000 (save-excursion
8001 (condition-case nil
8002 (if top "* "
8003 (org-back-to-heading invisible-ok)
8004 (when (and (not on-heading)
8005 (featurep 'org-inlinetask)
8006 (integerp org-inlinetask-min-level)
8007 (>= (length (match-string 0))
8008 org-inlinetask-min-level))
8009 ;; Find a heading level before the inline
8010 ;; task.
8011 (while (and (setq level (org-up-heading-safe))
8012 (>= level org-inlinetask-min-level)))
8013 (if (org-at-heading-p)
8014 (org-back-to-heading invisible-ok)
8015 (error "This should not happen")))
8016 (unless (and (save-excursion
8017 (save-match-data
8018 (org-backward-heading-same-level
8019 1 invisible-ok))
8020 (= (point) (match-beginning 0)))
8021 (not (org-next-line-empty-p)))
8022 (setq empty-line-p (or empty-line-p
8023 (org-previous-line-empty-p))))
8024 (match-string 0))
8025 (error (or fix-level "* ")))))
8026 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
8027 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
8029 ;; If we insert after content, move there and clean up
8030 ;; whitespace.
8031 (when respect-content
8032 (if (not (org-before-first-heading-p))
8033 (org-end-of-subtree nil t)
8034 (re-search-forward org-outline-regexp-bol)
8035 (beginning-of-line 0))
8036 (skip-chars-backward " \r\t\n")
8037 (and (not (looking-back "^\\*+" (line-beginning-position)))
8038 (looking-at "[ \t]+") (replace-match ""))
8039 (unless (eobp) (forward-char 1))
8040 (when (looking-at "^\\*")
8041 (unless (bobp) (backward-char 1))
8042 (insert "\n")))
8044 ;; If we are splitting, grab the text that should be moved
8045 ;; to the new headline.
8046 (when may-split
8047 (if (org-at-heading-p)
8048 ;; This is a heading: split intelligently (keeping
8049 ;; tags).
8050 (let ((pos (point)))
8051 (beginning-of-line)
8052 (let ((case-fold-search nil))
8053 (unless (looking-at org-complex-heading-regexp)
8054 (error "This should not happen")))
8055 (when (and (match-beginning 4)
8056 (> pos (match-beginning 4))
8057 (< pos (match-end 4)))
8058 (setq initial-content (buffer-substring pos (match-end 4)))
8059 (goto-char pos)
8060 (delete-region (point) (match-end 4))
8061 (if (looking-at "[ \t]*$")
8062 (replace-match "")
8063 (insert (make-string (length initial-content) ?\s)))
8064 (setq initial-content (org-trim initial-content)))
8065 (goto-char pos))
8066 ;; A normal line.
8067 (setq initial-content
8068 (org-trim
8069 (delete-and-extract-region (point) (line-end-position))))))
8071 ;; If we are at the beginning of the line, insert before it.
8072 ;; Otherwise, after it.
8073 (cond
8074 ((and (bolp) (looking-at "[ \t]*$")))
8075 ((bolp) (save-excursion (insert "\n")))
8076 (t (end-of-line)
8077 (insert "\n")))
8079 ;; Insert the new heading
8080 (insert stars)
8081 (just-one-space)
8082 (insert initial-content)
8083 (unless (and blank (org-previous-line-empty-p))
8084 (org-N-empty-lines-before-current (if blank 1 0)))
8085 ;; Adjust visibility, which may be messed up if we removed
8086 ;; blank lines while previous entry was hidden.
8087 (let ((bol (line-beginning-position)))
8088 (dolist (o (overlays-at (1- bol)))
8089 (when (and (eq (overlay-get o 'invisible) 'outline)
8090 (eq (overlay-end o) bol))
8091 (move-overlay o (overlay-start o) (1- bol)))))
8092 (run-hooks 'org-insert-heading-hook)))))))
8094 (defun org-N-empty-lines-before-current (N)
8095 "Make the number of empty lines before current exactly N.
8096 So this will delete or add empty lines."
8097 (save-excursion
8098 (beginning-of-line)
8099 (let ((p (point)))
8100 (skip-chars-backward " \r\t\n")
8101 (unless (bolp) (forward-line))
8102 (delete-region (point) p))
8103 (when (> N 0) (insert (make-string N ?\n)))))
8105 (defun org-get-heading (&optional no-tags no-todo)
8106 "Return the heading of the current entry, without the stars.
8107 When NO-TAGS is non-nil, don't include tags.
8108 When NO-TODO is non-nil, don't include TODO keywords."
8109 (save-excursion
8110 (org-back-to-heading t)
8111 (let ((case-fold-search nil))
8112 (cond
8113 ((and no-tags no-todo)
8114 (looking-at org-complex-heading-regexp)
8115 ;; Return value has to be a string, but match group 4 is
8116 ;; optional.
8117 (or (match-string 4) ""))
8118 (no-tags
8119 (looking-at (concat org-outline-regexp
8120 "\\(.*?\\)"
8121 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8122 (match-string 1))
8123 (no-todo
8124 (looking-at org-todo-line-regexp)
8125 (match-string 3))
8126 (t (looking-at org-heading-regexp)
8127 (match-string 2))))))
8129 (defvar orgstruct-mode) ; defined below
8131 (defun org-heading-components ()
8132 "Return the components of the current heading.
8133 This is a list with the following elements:
8134 - the level as an integer
8135 - the reduced level, different if `org-odd-levels-only' is set.
8136 - the TODO keyword, or nil
8137 - the priority character, like ?A, or nil if no priority is given
8138 - the headline text itself, or the tags string if no headline text
8139 - the tags string, or nil."
8140 (save-excursion
8141 (org-back-to-heading t)
8142 (when (let (case-fold-search)
8143 (looking-at
8144 (if orgstruct-mode
8145 org-heading-regexp
8146 org-complex-heading-regexp)))
8147 (if orgstruct-mode
8148 (list (length (match-string 1))
8149 (org-reduced-level (length (match-string 1)))
8152 (match-string 2)
8153 nil)
8154 (list (length (match-string 1))
8155 (org-reduced-level (length (match-string 1)))
8156 (match-string-no-properties 2)
8157 (and (match-end 3) (aref (match-string 3) 2))
8158 (match-string-no-properties 4)
8159 (match-string-no-properties 5))))))
8161 (defun org-get-entry ()
8162 "Get the entry text, after heading, entire subtree."
8163 (save-excursion
8164 (org-back-to-heading t)
8165 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8167 (defun org-edit-headline (&optional heading)
8168 "Edit the current headline.
8169 Set it to HEADING when provided."
8170 (interactive)
8171 (org-with-wide-buffer
8172 (org-back-to-heading t)
8173 (let ((case-fold-search nil))
8174 (when (looking-at org-complex-heading-regexp)
8175 (let* ((old (match-string-no-properties 4))
8176 (new (save-match-data
8177 (org-trim (or heading (read-string "Edit: " old))))))
8178 (unless (equal old new)
8179 (if old (replace-match new t t nil 4)
8180 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8181 (insert " " new))
8182 (org-set-tags nil t)
8183 (when (looking-at "[ \t]*$") (replace-match ""))))))))
8185 (defun org-insert-heading-after-current ()
8186 "Insert a new heading with same level as current, after current subtree."
8187 (interactive)
8188 (org-back-to-heading)
8189 (org-insert-heading)
8190 (org-move-subtree-down)
8191 (end-of-line 1))
8193 (defun org-insert-heading-respect-content (&optional invisible-ok)
8194 "Insert heading with `org-insert-heading-respect-content' set to t."
8195 (interactive)
8196 (org-insert-heading '(4) invisible-ok))
8198 (defun org-insert-todo-heading-respect-content (&optional force-state)
8199 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8200 (interactive)
8201 (org-insert-todo-heading force-state '(4)))
8203 (defun org-insert-todo-heading (arg &optional force-heading)
8204 "Insert a new heading with the same level and TODO state as current heading.
8206 If the heading has no TODO state, or if the state is DONE, use
8207 the first state (TODO by default). Also with one prefix arg,
8208 force first state. With two prefix args, force inserting at the
8209 end of the parent subtree.
8211 When called at a plain list item, insert a new item with an
8212 unchecked check box."
8213 (interactive "P")
8214 (when (or force-heading (not (org-insert-item 'checkbox)))
8215 (org-insert-heading (or (and (equal arg '(16)) '(16))
8216 force-heading))
8217 (save-excursion
8218 (org-back-to-heading)
8219 (outline-previous-heading)
8220 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
8221 (let* ((new-mark-x
8222 (if (or (equal arg '(4))
8223 (not (match-beginning 2))
8224 (member (match-string 2) org-done-keywords))
8225 (car org-todo-keywords-1)
8226 (match-string 2)))
8227 (new-mark
8229 (run-hook-with-args-until-success
8230 'org-todo-get-default-hook new-mark-x nil)
8231 new-mark-x)))
8232 (beginning-of-line 1)
8233 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8234 (if org-treat-insert-todo-heading-as-state-change
8235 (org-todo new-mark)
8236 (insert new-mark " "))))
8237 (when org-provide-todo-statistics
8238 (org-update-parent-todo-statistics))))
8240 (defun org-insert-subheading (arg)
8241 "Insert a new subheading and demote it.
8242 Works for outline headings and for plain lists alike."
8243 (interactive "P")
8244 (org-insert-heading arg)
8245 (cond
8246 ((org-at-heading-p) (org-do-demote))
8247 ((org-at-item-p) (org-indent-item))))
8249 (defun org-insert-todo-subheading (arg)
8250 "Insert a new subheading with TODO keyword or checkbox and demote it.
8251 Works for outline headings and for plain lists alike."
8252 (interactive "P")
8253 (org-insert-todo-heading arg)
8254 (cond
8255 ((org-at-heading-p) (org-do-demote))
8256 ((org-at-item-p) (org-indent-item))))
8258 ;;; Promotion and Demotion
8260 (defvar org-after-demote-entry-hook nil
8261 "Hook run after an entry has been demoted.
8262 The cursor will be at the beginning of the entry.
8263 When a subtree is being demoted, the hook will be called for each node.")
8265 (defvar org-after-promote-entry-hook nil
8266 "Hook run after an entry has been promoted.
8267 The cursor will be at the beginning of the entry.
8268 When a subtree is being promoted, the hook will be called for each node.")
8270 (defun org-promote-subtree ()
8271 "Promote the entire subtree.
8272 See also `org-promote'."
8273 (interactive)
8274 (save-excursion
8275 (org-with-limited-levels (org-map-tree 'org-promote)))
8276 (org-fix-position-after-promote))
8278 (defun org-demote-subtree ()
8279 "Demote the entire subtree.
8280 See `org-demote' and `org-promote'."
8281 (interactive)
8282 (save-excursion
8283 (org-with-limited-levels (org-map-tree 'org-demote)))
8284 (org-fix-position-after-promote))
8286 (defun org-do-promote ()
8287 "Promote the current heading higher up the tree.
8288 If the region is active in `transient-mark-mode', promote all
8289 headings in the region."
8290 (interactive)
8291 (save-excursion
8292 (if (org-region-active-p)
8293 (org-map-region 'org-promote (region-beginning) (region-end))
8294 (org-promote)))
8295 (org-fix-position-after-promote))
8297 (defun org-do-demote ()
8298 "Demote the current heading lower down the tree.
8299 If the region is active in `transient-mark-mode', demote all
8300 headings in the region."
8301 (interactive)
8302 (save-excursion
8303 (if (org-region-active-p)
8304 (org-map-region 'org-demote (region-beginning) (region-end))
8305 (org-demote)))
8306 (org-fix-position-after-promote))
8308 (defun org-fix-position-after-promote ()
8309 "Fix cursor position and indentation after demoting/promoting."
8310 (let ((pos (point)))
8311 (when (save-excursion
8312 (beginning-of-line)
8313 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8314 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8315 (cond ((eobp) (insert " "))
8316 ((eolp) (insert " "))
8317 ((equal (char-after) ?\s) (forward-char 1))))))
8319 (defun org-current-level ()
8320 "Return the level of the current entry, or nil if before the first headline.
8321 The level is the number of stars at the beginning of the
8322 headline. Use `org-reduced-level' to remove the effect of
8323 `org-odd-levels'. Unlike to `org-outline-level', this function
8324 ignores inlinetasks."
8325 (let ((level (org-with-limited-levels (org-outline-level))))
8326 (and (> level 0) level)))
8328 (defun org-get-previous-line-level ()
8329 "Return the outline depth of the last headline before the current line.
8330 Returns 0 for the first headline in the buffer, and nil if before the
8331 first headline."
8332 (and (org-current-level)
8333 (or (and (/= (line-beginning-position) (point-min))
8334 (save-excursion (beginning-of-line 0) (org-current-level)))
8335 0)))
8337 (defun org-reduced-level (l)
8338 "Compute the effective level of a heading.
8339 This takes into account the setting of `org-odd-levels-only'."
8340 (cond
8341 ((zerop l) 0)
8342 (org-odd-levels-only (1+ (floor (/ l 2))))
8343 (t l)))
8345 (defun org-level-increment ()
8346 "Return the number of stars that will be added or removed at a
8347 time to headlines when structure editing, based on the value of
8348 `org-odd-levels-only'."
8349 (if org-odd-levels-only 2 1))
8351 (defun org-get-valid-level (level &optional change)
8352 "Rectify a level change under the influence of `org-odd-levels-only'
8353 LEVEL is a current level, CHANGE is by how much the level should be
8354 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8355 even level numbers will become the next higher odd number."
8356 (if org-odd-levels-only
8357 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8358 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8359 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8360 (max 1 (+ level (or change 0)))))
8362 (defun org-promote ()
8363 "Promote the current heading higher up the tree."
8364 (org-with-wide-buffer
8365 (org-back-to-heading t)
8366 (let* ((after-change-functions (remq 'flyspell-after-change-function
8367 after-change-functions))
8368 (level (save-match-data (funcall outline-level)))
8369 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8370 (diff (abs (- level (length up-head) -1))))
8371 (cond
8372 ((and (= level 1) org-allow-promoting-top-level-subtree)
8373 (replace-match "# " nil t))
8374 ((= level 1)
8375 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8376 (t (replace-match up-head nil t)))
8377 (unless (= level 1)
8378 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8379 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8380 (run-hooks 'org-after-promote-entry-hook))))
8382 (defun org-demote ()
8383 "Demote the current heading lower down the tree."
8384 (org-with-wide-buffer
8385 (org-back-to-heading t)
8386 (let* ((after-change-functions (remq 'flyspell-after-change-function
8387 after-change-functions))
8388 (level (save-match-data (funcall outline-level)))
8389 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8390 (diff (abs (- level (length down-head) -1))))
8391 (replace-match down-head nil t)
8392 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8393 (when org-adapt-indentation (org-fixup-indentation diff))
8394 (run-hooks 'org-after-demote-entry-hook))))
8396 (defun org-cycle-level ()
8397 "Cycle the level of an empty headline through possible states.
8398 This goes first to child, then to parent, level, then up the hierarchy.
8399 After top level, it switches back to sibling level."
8400 (interactive)
8401 (let ((org-adapt-indentation nil))
8402 (when (org-point-at-end-of-empty-headline)
8403 (setq this-command 'org-cycle-level) ; Only needed for caching
8404 (let ((cur-level (org-current-level))
8405 (prev-level (org-get-previous-line-level)))
8406 (cond
8407 ;; If first headline in file, promote to top-level.
8408 ((= prev-level 0)
8409 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8410 do (org-do-promote)))
8411 ;; If same level as prev, demote one.
8412 ((= prev-level cur-level)
8413 (org-do-demote))
8414 ;; If parent is top-level, promote to top level if not already.
8415 ((= prev-level 1)
8416 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8417 do (org-do-promote)))
8418 ;; If top-level, return to prev-level.
8419 ((= cur-level 1)
8420 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8421 do (org-do-demote)))
8422 ;; If less than prev-level, promote one.
8423 ((< cur-level prev-level)
8424 (org-do-promote))
8425 ;; If deeper than prev-level, promote until higher than
8426 ;; prev-level.
8427 ((> cur-level prev-level)
8428 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8429 do (org-do-promote))))
8430 t))))
8432 (defun org-map-tree (fun)
8433 "Call FUN for every heading underneath the current one."
8434 (org-back-to-heading t)
8435 (let ((level (funcall outline-level)))
8436 (save-excursion
8437 (funcall fun)
8438 (while (and (progn
8439 (outline-next-heading)
8440 (> (funcall outline-level) level))
8441 (not (eobp)))
8442 (funcall fun)))))
8444 (defun org-map-region (fun beg end)
8445 "Call FUN for every heading between BEG and END."
8446 (let ((org-ignore-region t))
8447 (save-excursion
8448 (setq end (copy-marker end))
8449 (goto-char beg)
8450 (when (and (re-search-forward org-outline-regexp-bol nil t)
8451 (< (point) end))
8452 (funcall fun))
8453 (while (and (progn
8454 (outline-next-heading)
8455 (< (point) end))
8456 (not (eobp)))
8457 (funcall fun)))))
8459 (defun org-fixup-indentation (diff)
8460 "Change the indentation in the current entry by DIFF.
8462 DIFF is an integer. Indentation is done according to the
8463 following rules:
8465 - Planning information and property drawers are always indented
8466 according to the new level of the headline;
8468 - Footnote definitions and their contents are ignored;
8470 - Inlinetasks' boundaries are not shifted;
8472 - Empty lines are ignored;
8474 - Other lines' indentation are shifted by DIFF columns, unless
8475 it would introduce a structural change in the document, in
8476 which case no shifting is done at all.
8478 Assume point is at a heading or an inlinetask beginning."
8479 (org-with-wide-buffer
8480 (narrow-to-region (line-beginning-position)
8481 (save-excursion
8482 (if (org-with-limited-levels (org-at-heading-p))
8483 (org-with-limited-levels (outline-next-heading))
8484 (org-inlinetask-goto-end))
8485 (point)))
8486 (forward-line)
8487 ;; Indent properly planning info and property drawer.
8488 (when (looking-at-p org-planning-line-re)
8489 (org-indent-line)
8490 (forward-line))
8491 (when (looking-at org-property-drawer-re)
8492 (goto-char (match-end 0))
8493 (forward-line)
8494 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8495 (catch 'no-shift
8496 (when (zerop diff) (throw 'no-shift nil))
8497 ;; If DIFF is negative, first check if a shift is possible at all
8498 ;; (e.g., it doesn't break structure). This can only happen if
8499 ;; some contents are not properly indented.
8500 (let ((case-fold-search t))
8501 (when (< diff 0)
8502 (let ((diff (- diff))
8503 (forbidden-re (concat org-outline-regexp
8504 "\\|"
8505 (substring org-footnote-definition-re 1))))
8506 (save-excursion
8507 (while (not (eobp))
8508 (cond
8509 ((looking-at-p "[ \t]*$") (forward-line))
8510 ((and (looking-at-p org-footnote-definition-re)
8511 (let ((e (org-element-at-point)))
8512 (and (eq (org-element-type e) 'footnote-definition)
8513 (goto-char (org-element-property :end e))))))
8514 ((looking-at-p org-outline-regexp) (forward-line))
8515 ;; Give up if shifting would move before column 0 or
8516 ;; if it would introduce a headline or a footnote
8517 ;; definition.
8519 (skip-chars-forward " \t")
8520 (let ((ind (current-column)))
8521 (when (or (< ind diff)
8522 (and (= ind diff) (looking-at-p forbidden-re)))
8523 (throw 'no-shift nil)))
8524 ;; Ignore contents of example blocks and source
8525 ;; blocks if their indentation is meant to be
8526 ;; preserved. Jump to block's closing line.
8527 (beginning-of-line)
8528 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8529 (let ((e (org-element-at-point)))
8530 (and (memq (org-element-type e)
8531 '(example-block src-block))
8532 (or org-src-preserve-indentation
8533 (org-element-property :preserve-indent e))
8534 (goto-char (org-element-property :end e))
8535 (progn (skip-chars-backward " \r\t\n")
8536 (beginning-of-line)
8537 t))))
8538 (forward-line))))))))
8539 ;; Shift lines but footnote definitions, inlinetasks boundaries
8540 ;; by DIFF. Also skip contents of source or example blocks
8541 ;; when indentation is meant to be preserved.
8542 (while (not (eobp))
8543 (cond
8544 ((and (looking-at-p org-footnote-definition-re)
8545 (let ((e (org-element-at-point)))
8546 (and (eq (org-element-type e) 'footnote-definition)
8547 (goto-char (org-element-property :end e))))))
8548 ((looking-at-p org-outline-regexp) (forward-line))
8549 ((looking-at-p "[ \t]*$") (forward-line))
8551 (indent-line-to (+ (org-get-indentation) diff))
8552 (beginning-of-line)
8553 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8554 (let ((e (org-element-at-point)))
8555 (and (memq (org-element-type e)
8556 '(example-block src-block))
8557 (or org-src-preserve-indentation
8558 (org-element-property :preserve-indent e))
8559 (goto-char (org-element-property :end e))
8560 (progn (skip-chars-backward " \r\t\n")
8561 (beginning-of-line)
8562 t))))
8563 (forward-line)))))))))
8565 (defun org-convert-to-odd-levels ()
8566 "Convert an Org file with all levels allowed to one with odd levels.
8567 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8568 level 5 etc."
8569 (interactive)
8570 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8571 (let ((outline-level 'org-outline-level)
8572 (org-odd-levels-only nil) n)
8573 (save-excursion
8574 (goto-char (point-min))
8575 (while (re-search-forward "^\\*\\*+ " nil t)
8576 (setq n (- (length (match-string 0)) 2))
8577 (while (>= (setq n (1- n)) 0)
8578 (org-demote))
8579 (end-of-line 1))))))
8581 (defun org-convert-to-oddeven-levels ()
8582 "Convert an Org file with only odd levels to one with odd/even levels.
8583 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8584 file contains a section with an even level, conversion would
8585 destroy the structure of the file. An error is signaled in this
8586 case."
8587 (interactive)
8588 (goto-char (point-min))
8589 ;; First check if there are no even levels
8590 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8591 (org-show-set-visibility 'canonical)
8592 (error "Not all levels are odd in this file. Conversion not possible"))
8593 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8594 (let ((outline-regexp org-outline-regexp)
8595 (outline-level 'org-outline-level)
8596 (org-odd-levels-only nil) n)
8597 (save-excursion
8598 (goto-char (point-min))
8599 (while (re-search-forward "^\\*\\*+ " nil t)
8600 (setq n (/ (1- (length (match-string 0))) 2))
8601 (while (>= (setq n (1- n)) 0)
8602 (org-promote))
8603 (end-of-line 1))))))
8605 (defun org-tr-level (n)
8606 "Make N odd if required."
8607 (if org-odd-levels-only (1+ (/ n 2)) n))
8609 ;;; Vertical tree motion, cutting and pasting of subtrees
8611 (defun org-move-subtree-up (&optional arg)
8612 "Move the current subtree up past ARG headlines of the same level."
8613 (interactive "p")
8614 (org-move-subtree-down (- (prefix-numeric-value arg))))
8616 (defun org-move-subtree-down (&optional arg)
8617 "Move the current subtree down past ARG headlines of the same level."
8618 (interactive "p")
8619 (setq arg (prefix-numeric-value arg))
8620 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8621 'org-get-last-sibling))
8622 (ins-point (make-marker))
8623 (cnt (abs arg))
8624 (col (current-column))
8625 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8626 ;; Select the tree
8627 (org-back-to-heading)
8628 (setq beg0 (point))
8629 (save-excursion
8630 (setq ne-beg (org-back-over-empty-lines))
8631 (setq beg (point)))
8632 (save-match-data
8633 (save-excursion (outline-end-of-heading)
8634 (setq folded (outline-invisible-p)))
8635 (progn (org-end-of-subtree nil t)
8636 (unless (eobp) (backward-char))))
8637 (outline-next-heading)
8638 (setq ne-end (org-back-over-empty-lines))
8639 (setq end (point))
8640 (goto-char beg0)
8641 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8642 ;; include less whitespace
8643 (save-excursion
8644 (goto-char beg)
8645 (forward-line (- ne-beg ne-end))
8646 (setq beg (point))))
8647 ;; Find insertion point, with error handling
8648 (while (> cnt 0)
8649 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8650 (progn (goto-char beg0)
8651 (user-error "Cannot move past superior level or buffer limit")))
8652 (setq cnt (1- cnt)))
8653 (when (> arg 0)
8654 ;; Moving forward - still need to move over subtree
8655 (org-end-of-subtree t t)
8656 (save-excursion
8657 (org-back-over-empty-lines)
8658 (or (bolp) (newline))))
8659 (setq ne-ins (org-back-over-empty-lines))
8660 (move-marker ins-point (point))
8661 (setq txt (buffer-substring beg end))
8662 (org-save-markers-in-region beg end)
8663 (delete-region beg end)
8664 (org-remove-empty-overlays-at beg)
8665 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8666 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8667 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8668 (let ((bbb (point)))
8669 (insert-before-markers txt)
8670 (org-reinstall-markers-in-region bbb)
8671 (move-marker ins-point bbb))
8672 (or (bolp) (insert "\n"))
8673 (setq ins-end (point))
8674 (goto-char ins-point)
8675 (org-skip-whitespace)
8676 (when (and (< arg 0)
8677 (org-first-sibling-p)
8678 (> ne-ins ne-beg))
8679 ;; Move whitespace back to beginning
8680 (save-excursion
8681 (goto-char ins-end)
8682 (let ((kill-whole-line t))
8683 (kill-line (- ne-ins ne-beg)) (point)))
8684 (insert (make-string (- ne-ins ne-beg) ?\n)))
8685 (move-marker ins-point nil)
8686 (if folded
8687 (outline-hide-subtree)
8688 (org-show-entry)
8689 (org-show-children)
8690 (org-cycle-hide-drawers 'children))
8691 (org-clean-visibility-after-subtree-move)
8692 ;; move back to the initial column we were at
8693 (move-to-column col)))
8695 (defvar org-subtree-clip ""
8696 "Clipboard for cut and paste of subtrees.
8697 This is actually only a copy of the kill, because we use the normal kill
8698 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8700 (defvar org-subtree-clip-folded nil
8701 "Was the last copied subtree folded?
8702 This is used to fold the tree back after pasting.")
8704 (defun org-cut-subtree (&optional n)
8705 "Cut the current subtree into the clipboard.
8706 With prefix arg N, cut this many sequential subtrees.
8707 This is a short-hand for marking the subtree and then cutting it."
8708 (interactive "p")
8709 (org-copy-subtree n 'cut))
8711 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8712 "Copy the current subtree it in the clipboard.
8713 With prefix arg N, copy this many sequential subtrees.
8714 This is a short-hand for marking the subtree and then copying it.
8715 If CUT is non-nil, actually cut the subtree.
8716 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8717 of some markers in the region, even if CUT is non-nil. This is
8718 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8719 (interactive "p")
8720 (let (beg end folded (beg0 (point)))
8721 (if (called-interactively-p 'any)
8722 (org-back-to-heading nil) ; take what looks like a subtree
8723 (org-back-to-heading t)) ; take what is really there
8724 (setq beg (point))
8725 (skip-chars-forward " \t\r\n")
8726 (save-match-data
8727 (if nosubtrees
8728 (outline-next-heading)
8729 (save-excursion (outline-end-of-heading)
8730 (setq folded (outline-invisible-p)))
8731 (ignore-errors (org-forward-heading-same-level (1- n) t))
8732 (org-end-of-subtree t t)))
8733 ;; Include the end of an inlinetask
8734 (when (and (featurep 'org-inlinetask)
8735 (looking-at-p (concat (org-inlinetask-outline-regexp)
8736 "END[ \t]*$")))
8737 (end-of-line))
8738 (setq end (point))
8739 (goto-char beg0)
8740 (when (> end beg)
8741 (setq org-subtree-clip-folded folded)
8742 (when (or cut force-store-markers)
8743 (org-save-markers-in-region beg end))
8744 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8745 (setq org-subtree-clip (current-kill 0))
8746 (message "%s: Subtree(s) with %d characters"
8747 (if cut "Cut" "Copied")
8748 (length org-subtree-clip)))))
8750 (defun org-paste-subtree (&optional level tree for-yank remove)
8751 "Paste the clipboard as a subtree, with modification of headline level.
8752 The entire subtree is promoted or demoted in order to match a new headline
8753 level.
8755 If the cursor is at the beginning of a headline, the same level as
8756 that headline is used to paste the tree.
8758 If not, the new level is derived from the *visible* headings
8759 before and after the insertion point, and taken to be the inferior headline
8760 level of the two. So if the previous visible heading is level 3 and the
8761 next is level 4 (or vice versa), level 4 will be used for insertion.
8762 This makes sure that the subtree remains an independent subtree and does
8763 not swallow low level entries.
8765 You can also force a different level, either by using a numeric prefix
8766 argument, or by inserting the heading marker by hand. For example, if the
8767 cursor is after \"*****\", then the tree will be shifted to level 5.
8769 If optional TREE is given, use this text instead of the kill ring.
8771 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8772 move back over whitespace before inserting, and move point to the end of
8773 the inserted text when done.
8775 When REMOVE is non-nil, remove the subtree from the clipboard."
8776 (interactive "P")
8777 (setq tree (or tree (and kill-ring (current-kill 0))))
8778 (unless (org-kill-is-subtree-p tree)
8779 (user-error "%s"
8780 (substitute-command-keys
8781 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8782 (org-with-limited-levels
8783 (let* ((visp (not (outline-invisible-p)))
8784 (txt tree)
8785 (^re_ "\\(\\*+\\)[ \t]*")
8786 (old-level (if (string-match org-outline-regexp-bol txt)
8787 (- (match-end 0) (match-beginning 0) 1)
8788 -1))
8789 (force-level (cond (level (prefix-numeric-value level))
8790 ((and (looking-at "[ \t]*$")
8791 (string-match
8792 "^\\*+$" (buffer-substring
8793 (point-at-bol) (point))))
8794 (- (match-end 0) (match-beginning 0)))
8795 ((and (bolp)
8796 (looking-at org-outline-regexp))
8797 (- (match-end 0) (point) 1))))
8798 (previous-level (save-excursion
8799 (condition-case nil
8800 (progn
8801 (outline-previous-visible-heading 1)
8802 (if (looking-at ^re_)
8803 (- (match-end 0) (match-beginning 0) 1)
8805 (error 1))))
8806 (next-level (save-excursion
8807 (condition-case nil
8808 (progn
8809 (or (looking-at org-outline-regexp)
8810 (outline-next-visible-heading 1))
8811 (if (looking-at ^re_)
8812 (- (match-end 0) (match-beginning 0) 1)
8814 (error 1))))
8815 (new-level (or force-level (max previous-level next-level)))
8816 (shift (if (or (= old-level -1)
8817 (= new-level -1)
8818 (= old-level new-level))
8820 (- new-level old-level)))
8821 (delta (if (> shift 0) -1 1))
8822 (func (if (> shift 0) 'org-demote 'org-promote))
8823 (org-odd-levels-only nil)
8824 beg end newend)
8825 ;; Remove the forced level indicator
8826 (when force-level
8827 (delete-region (point-at-bol) (point)))
8828 ;; Paste
8829 (beginning-of-line (if (bolp) 1 2))
8830 (setq beg (point))
8831 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8832 (insert-before-markers txt)
8833 (unless (string-suffix-p "\n" txt) (insert "\n"))
8834 (setq newend (point))
8835 (org-reinstall-markers-in-region beg)
8836 (setq end (point))
8837 (goto-char beg)
8838 (skip-chars-forward " \t\n\r")
8839 (setq beg (point))
8840 (when (and (outline-invisible-p) visp)
8841 (save-excursion (outline-show-heading)))
8842 ;; Shift if necessary
8843 (unless (= shift 0)
8844 (save-restriction
8845 (narrow-to-region beg end)
8846 (while (not (= shift 0))
8847 (org-map-region func (point-min) (point-max))
8848 (setq shift (+ delta shift)))
8849 (goto-char (point-min))
8850 (setq newend (point-max))))
8851 (when (or (called-interactively-p 'interactive) for-yank)
8852 (message "Clipboard pasted as level %d subtree" new-level))
8853 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8854 kill-ring
8855 (eq org-subtree-clip (current-kill 0))
8856 org-subtree-clip-folded)
8857 ;; The tree was folded before it was killed/copied
8858 (outline-hide-subtree))
8859 (and for-yank (goto-char newend))
8860 (and remove (setq kill-ring (cdr kill-ring))))))
8862 (defun org-kill-is-subtree-p (&optional txt)
8863 "Check if the current kill is an outline subtree, or a set of trees.
8864 Returns nil if kill does not start with a headline, or if the first
8865 headline level is not the largest headline level in the tree.
8866 So this will actually accept several entries of equal levels as well,
8867 which is OK for `org-paste-subtree'.
8868 If optional TXT is given, check this string instead of the current kill."
8869 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8870 (re (org-get-limited-outline-regexp))
8871 (^re (concat "^" re))
8872 (start-level (and kill
8873 (string-match
8874 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8875 kill)
8876 (- (match-end 2) (match-beginning 2) 1)))
8877 (start (1+ (or (match-beginning 2) -1))))
8878 (if (not start-level)
8879 (progn
8880 nil) ;; does not even start with a heading
8881 (catch 'exit
8882 (while (setq start (string-match ^re kill (1+ start)))
8883 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8884 (throw 'exit nil)))
8885 t))))
8887 (defvar org-markers-to-move nil
8888 "Markers that should be moved with a cut-and-paste operation.
8889 Those markers are stored together with their positions relative to
8890 the start of the region.")
8892 (defun org-save-markers-in-region (beg end)
8893 "Check markers in region.
8894 If these markers are between BEG and END, record their position relative
8895 to BEG, so that after moving the block of text, we can put the markers back
8896 into place.
8897 This function gets called just before an entry or tree gets cut from the
8898 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8899 called immediately, to move the markers with the entries."
8900 (setq org-markers-to-move nil)
8901 (when (featurep 'org-clock)
8902 (org-clock-save-markers-for-cut-and-paste beg end))
8903 (when (featurep 'org-agenda)
8904 (org-agenda-save-markers-for-cut-and-paste beg end)))
8906 (defun org-check-and-save-marker (marker beg end)
8907 "Check if MARKER is between BEG and END.
8908 If yes, remember the marker and the distance to BEG."
8909 (when (and (marker-buffer marker)
8910 (equal (marker-buffer marker) (current-buffer))
8911 (>= marker beg) (< marker end))
8912 (push (cons marker (- marker beg)) org-markers-to-move)))
8914 (defun org-reinstall-markers-in-region (beg)
8915 "Move all remembered markers to their position relative to BEG."
8916 (dolist (x org-markers-to-move)
8917 (move-marker (car x) (+ beg (cdr x))))
8918 (setq org-markers-to-move nil))
8920 (defun org-narrow-to-subtree ()
8921 "Narrow buffer to the current subtree."
8922 (interactive)
8923 (save-excursion
8924 (save-match-data
8925 (org-with-limited-levels
8926 (narrow-to-region
8927 (progn (org-back-to-heading t) (point))
8928 (progn (org-end-of-subtree t t)
8929 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8930 (point)))))))
8932 (defun org-narrow-to-block ()
8933 "Narrow buffer to the current block."
8934 (interactive)
8935 (let* ((case-fold-search t)
8936 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8937 "^[ \t]*#\\+end_.*")))
8938 (if blockp
8939 (narrow-to-region (car blockp) (cdr blockp))
8940 (user-error "Not in a block"))))
8942 (defun org-clone-subtree-with-time-shift (n &optional shift)
8943 "Clone the task (subtree) at point N times.
8944 The clones will be inserted as siblings.
8946 In interactive use, the user will be prompted for the number of
8947 clones to be produced. If the entry has a timestamp, the user
8948 will also be prompted for a time shift, which may be a repeater
8949 as used in time stamps, for example `+3d'. To disable this,
8950 you can call the function with a universal prefix argument.
8952 When a valid repeater is given and the entry contains any time
8953 stamps, the clones will become a sequence in time, with time
8954 stamps in the subtree shifted for each clone produced. If SHIFT
8955 is nil or the empty string, time stamps will be left alone. The
8956 ID property of the original subtree is removed.
8958 In each clone, all the CLOCK entries will be removed. This
8959 prevents Org from considering that the clocked times overlap.
8961 If the original subtree did contain time stamps with a repeater,
8962 the following will happen:
8963 - the repeater will be removed in each clone
8964 - an additional clone will be produced, with the current, unshifted
8965 date(s) in the entry.
8966 - the original entry will be placed *after* all the clones, with
8967 repeater intact.
8968 - the start days in the repeater in the original entry will be shifted
8969 to past the last clone.
8970 In this way you can spell out a number of instances of a repeating task,
8971 and still retain the repeater to cover future instances of the task.
8973 As described above, N+1 clones are produced when the original
8974 subtree has a repeater. Setting N to 0, then, can be used to
8975 remove the repeater from a subtree and create a shifted clone
8976 with the original repeater."
8977 (interactive "nNumber of clones to produce: ")
8978 (let ((shift
8979 (or shift
8980 (if (and (not (equal current-prefix-arg '(4)))
8981 (save-excursion
8982 (re-search-forward org-ts-regexp-both
8983 (save-excursion
8984 (org-end-of-subtree t)
8985 (point)) t)))
8986 (read-from-minibuffer
8987 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8988 ""))) ;; No time shift
8989 (n-no-remove -1)
8990 (drawer-re org-drawer-regexp)
8991 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8992 beg end template task idprop
8993 shift-n shift-what doshift nmin nmax)
8994 (unless (wholenump n)
8995 (user-error "Invalid number of replications %s" n))
8996 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8997 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8998 shift)))
8999 (user-error "Invalid shift specification %s" shift))
9000 (when doshift
9001 (setq shift-n (string-to-number (match-string 1 shift))
9002 shift-what (cdr (assoc (match-string 2 shift)
9003 '(("d" . day) ("w" . week)
9004 ("m" . month) ("y" . year))))))
9005 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
9006 (setq nmin 1 nmax n)
9007 (org-back-to-heading t)
9008 (setq beg (point))
9009 (setq idprop (org-entry-get nil "ID"))
9010 (org-end-of-subtree t t)
9011 (or (bolp) (insert "\n"))
9012 (setq end (point))
9013 (setq template (buffer-substring beg end))
9014 (when (and doshift
9015 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
9016 (delete-region beg end)
9017 (setq end beg)
9018 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
9019 (goto-char end)
9020 (cl-loop for n from nmin to nmax do
9021 ;; prepare clone
9022 (with-temp-buffer
9023 (insert template)
9024 (org-mode)
9025 (goto-char (point-min))
9026 (org-show-subtree)
9027 (and idprop (if org-clone-delete-id
9028 (org-entry-delete nil "ID")
9029 (org-id-get-create t)))
9030 (unless (= n 0)
9031 (while (re-search-forward org-clock-re nil t)
9032 (kill-whole-line))
9033 (goto-char (point-min))
9034 (while (re-search-forward drawer-re nil t)
9035 (org-remove-empty-drawer-at (point))))
9036 (goto-char (point-min))
9037 (when doshift
9038 (while (re-search-forward org-ts-regexp-both nil t)
9039 (org-timestamp-change (* n shift-n) shift-what))
9040 (unless (= n n-no-remove)
9041 (goto-char (point-min))
9042 (while (re-search-forward org-ts-regexp nil t)
9043 (save-excursion
9044 (goto-char (match-beginning 0))
9045 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
9046 (delete-region (match-beginning 1) (match-end 1)))))))
9047 (setq task (buffer-string)))
9048 (insert task))
9049 (goto-char beg)))
9051 ;;; Outline Sorting
9053 (defun org-sort (with-case)
9054 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
9055 Optional argument WITH-CASE means sort case-sensitively."
9056 (interactive "P")
9057 (cond
9058 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
9059 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
9061 (org-call-with-arg 'org-sort-entries with-case))))
9063 (defun org-sort-remove-invisible (s)
9064 "Remove invisible links from string S."
9065 (remove-text-properties 0 (length s) org-rm-props s)
9066 (while (string-match org-bracket-link-regexp s)
9067 (setq s (replace-match (if (match-end 2)
9068 (match-string 3 s)
9069 (match-string 1 s))
9070 t t s)))
9071 (let ((st (format " %s " s)))
9072 (while (string-match org-emph-re st)
9073 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
9074 (setq s (substring st 1 -1)))
9077 (defvar org-priority-regexp) ; defined later in the file
9079 (defvar org-after-sorting-entries-or-items-hook nil
9080 "Hook that is run after a bunch of entries or items have been sorted.
9081 When children are sorted, the cursor is in the parent line when this
9082 hook gets called. When a region or a plain list is sorted, the cursor
9083 will be in the first entry of the sorted region/list.")
9085 (defun org-sort-entries
9086 (&optional with-case sorting-type getkey-func compare-func property)
9087 "Sort entries on a certain level of an outline tree.
9088 If there is an active region, the entries in the region are sorted.
9089 Else, if the cursor is before the first entry, sort the top-level items.
9090 Else, the children of the entry at point are sorted.
9092 Sorting can be alphabetically, numerically, by date/time as given by
9093 a time stamp, by a property, by priority order, or by a custom function.
9095 The command prompts for the sorting type unless it has been given to the
9096 function through the SORTING-TYPE argument, which needs to be a character,
9097 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9098 the precise meaning of each character:
9100 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9101 c By creation time, which is assumed to be the first inactive time stamp
9102 at the beginning of a line.
9103 d By deadline date/time.
9104 k By clocking time.
9105 n Numerically, by converting the beginning of the entry/item to a number.
9106 o By order of TODO keywords.
9107 p By priority according to the cookie.
9108 r By the value of a property.
9109 s By scheduled date/time.
9110 t By date/time, either the first active time stamp in the entry, or, if
9111 none exist, by the first inactive one.
9113 Capital letters will reverse the sort order.
9115 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9116 called with point at the beginning of the record. It must return either
9117 a string or a number that should serve as the sorting key for that record.
9119 Comparing entries ignores case by default. However, with an optional argument
9120 WITH-CASE, the sorting considers case as well.
9122 Sorting is done against the visible part of the headlines, it ignores hidden
9123 links.
9125 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
9126 (interactive "P")
9127 (let ((case-func (if with-case 'identity 'downcase))
9128 (cmstr
9129 ;; The clock marker is lost when using `sort-subr', let's
9130 ;; store the clocking string.
9131 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9132 (save-excursion
9133 (goto-char org-clock-marker)
9134 (buffer-substring-no-properties (line-beginning-position)
9135 (point)))))
9136 start beg end stars re re2
9137 txt what tmp)
9138 ;; Find beginning and end of region to sort
9139 (cond
9140 ((org-region-active-p)
9141 ;; we will sort the region
9142 (setq end (region-end)
9143 what "region")
9144 (goto-char (region-beginning))
9145 (unless (org-at-heading-p) (outline-next-heading))
9146 (setq start (point)))
9147 ((or (org-at-heading-p)
9148 (ignore-errors (progn (org-back-to-heading) t)))
9149 ;; we will sort the children of the current headline
9150 (org-back-to-heading)
9151 (setq start (point)
9152 end (progn (org-end-of-subtree t t)
9153 (or (bolp) (insert "\n"))
9154 (when (>= (org-back-over-empty-lines) 1)
9155 (forward-line 1))
9156 (point))
9157 what "children")
9158 (goto-char start)
9159 (outline-show-subtree)
9160 (outline-next-heading))
9162 ;; we will sort the top-level entries in this file
9163 (goto-char (point-min))
9164 (or (org-at-heading-p) (outline-next-heading))
9165 (setq start (point))
9166 (goto-char (point-max))
9167 (beginning-of-line 1)
9168 (when (looking-at ".*?\\S-")
9169 ;; File ends in a non-white line
9170 (end-of-line 1)
9171 (insert "\n"))
9172 (setq end (point-max))
9173 (setq what "top-level")
9174 (goto-char start)
9175 (outline-show-all)))
9177 (setq beg (point))
9178 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9180 (looking-at "\\(\\*+\\)")
9181 (setq stars (match-string 1)
9182 re (concat "^" (regexp-quote stars) " +")
9183 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9184 txt (buffer-substring beg end))
9185 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9186 (when (and (not (equal stars "*")) (string-match re2 txt))
9187 (user-error "Region to sort contains a level above the first entry"))
9189 (unless sorting-type
9190 (message
9191 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9192 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9193 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9194 what)
9195 (setq sorting-type (read-char-exclusive))
9197 (unless getkey-func
9198 (and (= (downcase sorting-type) ?f)
9199 (setq getkey-func
9200 (completing-read "Sort using function: "
9201 obarray 'fboundp t nil nil))
9202 (setq getkey-func (intern getkey-func))))
9204 (and (= (downcase sorting-type) ?r)
9205 (not property)
9206 (setq property
9207 (completing-read "Property: "
9208 (mapcar #'list (org-buffer-property-keys t))
9209 nil t))))
9211 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9212 (message "Sorting entries...")
9214 (save-restriction
9215 (narrow-to-region start end)
9216 (let ((dcst (downcase sorting-type))
9217 (case-fold-search nil)
9218 (now (current-time)))
9219 (sort-subr
9220 (/= dcst sorting-type)
9221 ;; This function moves to the beginning character of the "record" to
9222 ;; be sorted.
9223 (lambda nil
9224 (if (re-search-forward re nil t)
9225 (goto-char (match-beginning 0))
9226 (goto-char (point-max))))
9227 ;; This function moves to the last character of the "record" being
9228 ;; sorted.
9229 (lambda nil
9230 (save-match-data
9231 (condition-case nil
9232 (outline-forward-same-level 1)
9233 (error
9234 (goto-char (point-max))))))
9235 ;; This function returns the value that gets sorted against.
9236 (lambda nil
9237 (cond
9238 ((= dcst ?n)
9239 (if (looking-at org-complex-heading-regexp)
9240 (string-to-number (org-sort-remove-invisible (match-string 4)))
9241 nil))
9242 ((= dcst ?a)
9243 (if (looking-at org-complex-heading-regexp)
9244 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9245 nil))
9246 ((= dcst ?k)
9247 (or (get-text-property (point) :org-clock-minutes) 0))
9248 ((= dcst ?t)
9249 (let ((end (save-excursion (outline-next-heading) (point))))
9250 (if (or (re-search-forward org-ts-regexp end t)
9251 (re-search-forward org-ts-regexp-both end t))
9252 (org-time-string-to-seconds (match-string 0))
9253 (float-time now))))
9254 ((= dcst ?c)
9255 (let ((end (save-excursion (outline-next-heading) (point))))
9256 (if (re-search-forward
9257 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9258 end t)
9259 (org-time-string-to-seconds (match-string 0))
9260 (float-time now))))
9261 ((= dcst ?s)
9262 (let ((end (save-excursion (outline-next-heading) (point))))
9263 (if (re-search-forward org-scheduled-time-regexp end t)
9264 (org-time-string-to-seconds (match-string 1))
9265 (float-time now))))
9266 ((= dcst ?d)
9267 (let ((end (save-excursion (outline-next-heading) (point))))
9268 (if (re-search-forward org-deadline-time-regexp end t)
9269 (org-time-string-to-seconds (match-string 1))
9270 (float-time now))))
9271 ((= dcst ?p)
9272 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9273 (string-to-char (match-string 2))
9274 org-default-priority))
9275 ((= dcst ?r)
9276 (or (org-entry-get nil property) ""))
9277 ((= dcst ?o)
9278 (when (looking-at org-complex-heading-regexp)
9279 (let* ((m (match-string 2))
9280 (s (if (member m org-done-keywords) '- '+)))
9281 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9282 ((= dcst ?f)
9283 (if getkey-func
9284 (progn
9285 (setq tmp (funcall getkey-func))
9286 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9287 tmp)
9288 (error "Invalid key function `%s'" getkey-func)))
9289 (t (error "Invalid sorting type `%c'" sorting-type))))
9291 (cond
9292 ((= dcst ?a) 'string<)
9293 ((= dcst ?f) compare-func)
9294 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9295 (run-hooks 'org-after-sorting-entries-or-items-hook)
9296 ;; Reset the clock marker if needed
9297 (when cmstr
9298 (save-excursion
9299 (goto-char start)
9300 (search-forward cmstr nil t)
9301 (move-marker org-clock-marker (point))))
9302 (message "Sorting entries...done")))
9304 ;;; The orgstruct minor mode
9306 ;; Define a minor mode which can be used in other modes in order to
9307 ;; integrate the Org mode structure editing commands.
9309 ;; This is really a hack, because the Org mode structure commands use
9310 ;; keys which normally belong to the major mode. Here is how it
9311 ;; works: The minor mode defines all the keys necessary to operate the
9312 ;; structure commands, but wraps the commands into a function which
9313 ;; tests if the cursor is currently at a headline or a plain list
9314 ;; item. If that is the case, the structure command is used,
9315 ;; temporarily setting many Org mode variables like regular
9316 ;; expressions for filling etc. However, when any of those keys is
9317 ;; used at a different location, function uses `key-binding' to look
9318 ;; up if the key has an associated command in another currently active
9319 ;; keymap (minor modes, major mode, global), and executes that
9320 ;; command. There might be problems if any of the keys is otherwise
9321 ;; used as a prefix key.
9323 (defcustom orgstruct-heading-prefix-regexp ""
9324 "Regexp that matches the custom prefix of Org headlines in
9325 orgstruct(++)-mode."
9326 :group 'org
9327 :version "24.4"
9328 :package-version '(Org . "8.3")
9329 :type 'regexp)
9330 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9332 (defcustom orgstruct-setup-hook nil
9333 "Hook run after orgstruct-mode-map is filled."
9334 :group 'org
9335 :version "24.4"
9336 :package-version '(Org . "8.0")
9337 :type 'hook)
9339 (defvar orgstruct-initialized nil)
9341 (defvar org-local-vars nil
9342 "List of local variables, for use by `orgstruct-mode'.")
9344 ;;;###autoload
9345 (define-minor-mode orgstruct-mode
9346 "Toggle the minor mode `orgstruct-mode'.
9347 This mode is for using Org mode structure commands in other
9348 modes. The following keys behave as if Org mode were active, if
9349 the cursor is on a headline, or on a plain list item (both as
9350 defined by Org mode)."
9351 nil " OrgStruct" (make-sparse-keymap)
9352 (funcall (if orgstruct-mode
9353 'add-to-invisibility-spec
9354 'remove-from-invisibility-spec)
9355 '(outline . t))
9356 (when orgstruct-mode
9357 (org-load-modules-maybe)
9358 (unless orgstruct-initialized
9359 (orgstruct-setup)
9360 (setq orgstruct-initialized t))))
9362 ;;;###autoload
9363 (defun turn-on-orgstruct ()
9364 "Unconditionally turn on `orgstruct-mode'."
9365 (orgstruct-mode 1))
9367 (defvar-local orgstruct-is-++ nil
9368 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9369 (defvar-local org-fb-vars nil)
9370 (defun orgstruct++-mode (&optional arg)
9371 "Toggle `orgstruct-mode', the enhanced version of it.
9372 In addition to setting orgstruct-mode, this also exports all
9373 indentation and autofilling variables from Org mode into the
9374 buffer. It will also recognize item context in multiline items."
9375 (interactive "P")
9376 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9377 (if (< arg 1)
9378 (progn (orgstruct-mode -1)
9379 (dolist (v org-fb-vars)
9380 (set (make-local-variable (car v))
9381 (if (eq (car-safe (cadr v)) 'quote)
9382 (cl-cadadr v)
9383 (nth 1 v)))))
9384 (orgstruct-mode 1)
9385 (setq org-fb-vars nil)
9386 (unless org-local-vars
9387 (setq org-local-vars (org-get-local-variables)))
9388 (let (var val)
9389 (dolist (x org-local-vars)
9390 (when (string-match
9391 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9392 \\|fill-prefix\\|indent-\\)"
9393 (symbol-name (car x)))
9394 (setq var (car x) val (nth 1 x))
9395 (push (list var `(quote ,(eval var))) org-fb-vars)
9396 (set (make-local-variable var)
9397 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9398 (setq-local orgstruct-is-++ t))))
9400 ;;;###autoload
9401 (defun turn-on-orgstruct++ ()
9402 "Unconditionally turn on `orgstruct++-mode'."
9403 (orgstruct++-mode 1))
9405 (defun orgstruct-error ()
9406 "Error when there is no default binding for a structure key."
9407 (interactive)
9408 (funcall (if (fboundp 'user-error)
9409 'user-error
9410 'error)
9411 "This key has no function outside structure elements"))
9413 (defun orgstruct-setup ()
9414 "Setup orgstruct keymap."
9415 (dolist (cell '((org-demote . t)
9416 (org-metaleft . t)
9417 (org-metaright . t)
9418 (org-promote . t)
9419 (org-shiftmetaleft . t)
9420 (org-shiftmetaright . t)
9421 org-backward-element
9422 org-backward-heading-same-level
9423 org-ctrl-c-ret
9424 org-ctrl-c-minus
9425 org-ctrl-c-star
9426 org-cycle
9427 org-force-cycle-archived
9428 org-forward-heading-same-level
9429 org-insert-heading
9430 org-insert-heading-respect-content
9431 org-kill-note-or-show-branches
9432 org-mark-subtree
9433 org-meta-return
9434 org-metadown
9435 org-metaup
9436 org-narrow-to-subtree
9437 org-promote-subtree
9438 org-reveal
9439 org-shiftdown
9440 org-shiftleft
9441 org-shiftmetadown
9442 org-shiftmetaup
9443 org-shiftright
9444 org-shifttab
9445 org-shifttab
9446 org-shiftup
9447 org-show-children
9448 org-show-subtree
9449 org-sort
9450 org-up-element
9451 outline-demote
9452 outline-next-visible-heading
9453 outline-previous-visible-heading
9454 outline-promote
9455 outline-up-heading))
9456 (let ((f (or (car-safe cell) cell))
9457 (disable-when-heading-prefix (cdr-safe cell)))
9458 (when (fboundp f)
9459 (let ((new-bindings))
9460 (dolist (binding (nconc (where-is-internal f org-mode-map)
9461 (where-is-internal f outline-mode-map)))
9462 (push binding new-bindings)
9463 ;; TODO use local-function-key-map
9464 (dolist (rep '(("<tab>" . "TAB")
9465 ("<return>" . "RET")
9466 ("<escape>" . "ESC")
9467 ("<delete>" . "DEL")))
9468 (setq binding (read-kbd-macro
9469 (let ((case-fold-search))
9470 (replace-regexp-in-string
9471 (regexp-quote (cdr rep))
9472 (car rep)
9473 (key-description binding)))))
9474 (cl-pushnew binding new-bindings :test 'equal)))
9475 (dolist (binding new-bindings)
9476 (let ((key (lookup-key orgstruct-mode-map binding)))
9477 (when (or (not key) (numberp key))
9478 (ignore-errors
9479 (org-defkey orgstruct-mode-map
9480 binding
9481 (orgstruct-make-binding
9482 f binding disable-when-heading-prefix))))))))))
9483 (run-hooks 'orgstruct-setup-hook))
9485 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9486 "Create a function for binding in the structure minor mode.
9487 FUN is the command to call inside a table. KEY is the key that
9488 should be checked in for a command to execute outside of tables.
9489 Non-nil `disable-when-heading-prefix' means to disable the command
9490 if `orgstruct-heading-prefix-regexp' is not empty."
9491 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9492 (let ((nname name)
9493 (i 0))
9494 (while (fboundp (intern nname))
9495 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9496 (setq name (intern nname)))
9497 (eval
9498 (let ((bindings '((org-heading-regexp
9499 (concat "^"
9500 orgstruct-heading-prefix-regexp
9501 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9502 (org-outline-regexp
9503 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9504 (org-outline-regexp-bol
9505 (concat "^" org-outline-regexp))
9506 (outline-regexp org-outline-regexp)
9507 (outline-heading-end-regexp "\n")
9508 (outline-level 'org-outline-level)
9509 (outline-heading-alist))))
9510 `(defun ,name (arg)
9511 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9512 "Outside of structure, run the binding of `"
9513 (key-description key) "'."
9514 (when disable-when-heading-prefix
9515 (concat
9516 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9517 "back to the default binding due to limitations of Org's implementation of\n"
9518 "`" (symbol-name fun) "'.")))
9519 (interactive "p")
9520 (let* ((disable
9521 ,(and disable-when-heading-prefix
9522 '(not (string= orgstruct-heading-prefix-regexp ""))))
9523 (fallback
9524 (or disable
9525 (not
9526 (let* ,bindings
9527 (org-context-p 'headline 'item
9528 ,(when (memq fun
9529 '(org-insert-heading
9530 org-insert-heading-respect-content
9531 org-meta-return))
9532 '(when orgstruct-is-++
9533 'item-body))))))))
9534 (if fallback
9535 (let* ((orgstruct-mode)
9536 (binding
9537 (let ((key ,key))
9538 (catch 'exit
9539 (dolist
9540 (rep
9541 '(nil
9542 ("<\\([^>]*\\)tab>" . "\\1TAB")
9543 ("<\\([^>]*\\)return>" . "\\1RET")
9544 ("<\\([^>]*\\)escape>" . "\\1ESC")
9545 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9546 nil)
9547 (when rep
9548 (setq key (read-kbd-macro
9549 (let ((case-fold-search))
9550 (replace-regexp-in-string
9551 (car rep)
9552 (cdr rep)
9553 (key-description key))))))
9554 (when (key-binding key)
9555 (throw 'exit (key-binding key))))))))
9556 (if (keymapp binding)
9557 (org-set-transient-map binding)
9558 (let ((func (or binding
9559 (unless disable
9560 'orgstruct-error))))
9561 (when func
9562 (call-interactively func)))))
9563 (org-run-like-in-org-mode
9564 (lambda ()
9565 (interactive)
9566 (let* ,bindings
9567 (call-interactively ',fun)))))))))
9568 name))
9570 (defun org-contextualize-keys (alist contexts)
9571 "Return valid elements in ALIST depending on CONTEXTS.
9573 `org-agenda-custom-commands' or `org-capture-templates' are the
9574 values used for ALIST, and `org-agenda-custom-commands-contexts'
9575 or `org-capture-templates-contexts' are the associated contexts
9576 definitions."
9577 (let ((contexts
9578 ;; normalize contexts
9579 (mapcar
9580 (lambda(c) (cond ((listp (cadr c))
9581 (list (car c) (car c) (nth 1 c)))
9582 ((string= "" (cadr c))
9583 (list (car c) (car c) (nth 2 c)))
9584 (t c)))
9585 contexts))
9586 (a alist) r s)
9587 ;; loop over all commands or templates
9588 (dolist (c a)
9589 (let (vrules repl)
9590 (cond
9591 ((not (assoc (car c) contexts))
9592 (push c r))
9593 ((and (assoc (car c) contexts)
9594 (setq vrules (org-contextualize-validate-key
9595 (car c) contexts)))
9596 (mapc (lambda (vr)
9597 (unless (equal (car vr) (cadr vr))
9598 (setq repl vr)))
9599 vrules)
9600 (if (not repl) (push c r)
9601 (push (cadr repl) s)
9602 (push
9603 (cons (car c)
9604 (cdr (or (assoc (cadr repl) alist)
9605 (error "Undefined key `%s' as contextual replacement for `%s'"
9606 (cadr repl) (car c)))))
9607 r))))))
9608 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9609 (delq
9611 (delete-dups
9612 (mapcar (lambda (x)
9613 (let ((tpl (car x)))
9614 (unless (delq
9616 (mapcar (lambda (y)
9617 (equal y tpl))
9619 x)))
9620 (reverse r))))))
9622 (defun org-contextualize-validate-key (key contexts)
9623 "Check CONTEXTS for agenda or capture KEY."
9624 (let (res)
9625 (dolist (r contexts)
9626 (dolist (rr (car (last r)))
9627 (when
9628 (and (equal key (car r))
9629 (if (functionp rr) (funcall rr)
9630 (or (and (eq (car rr) 'in-file)
9631 (buffer-file-name)
9632 (string-match (cdr rr) (buffer-file-name)))
9633 (and (eq (car rr) 'in-mode)
9634 (string-match (cdr rr) (symbol-name major-mode)))
9635 (and (eq (car rr) 'in-buffer)
9636 (string-match (cdr rr) (buffer-name)))
9637 (when (and (eq (car rr) 'not-in-file)
9638 (buffer-file-name))
9639 (not (string-match (cdr rr) (buffer-file-name))))
9640 (when (eq (car rr) 'not-in-mode)
9641 (not (string-match (cdr rr) (symbol-name major-mode))))
9642 (when (eq (car rr) 'not-in-buffer)
9643 (not (string-match (cdr rr) (buffer-name)))))))
9644 (push r res))))
9645 (delete-dups (delq nil res))))
9647 (defun org-context-p (&rest contexts)
9648 "Check if local context is any of CONTEXTS.
9649 Possible values in the list of contexts are `table', `headline', and `item'."
9650 (let ((pos (point)))
9651 (goto-char (point-at-bol))
9652 (prog1 (or (and (memq 'table contexts)
9653 (looking-at "[ \t]*|"))
9654 (and (memq 'headline contexts)
9655 (looking-at org-outline-regexp))
9656 (and (memq 'item contexts)
9657 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9658 (and (memq 'item-body contexts)
9659 (org-in-item-p)))
9660 (goto-char pos))))
9662 (defconst org-unique-local-variables
9663 '(org-element--cache
9664 org-element--cache-objects
9665 org-element--cache-sync-keys
9666 org-element--cache-sync-requests
9667 org-element--cache-sync-timer)
9668 "List of local variables that cannot be transferred to another buffer.")
9670 (defun org-get-local-variables ()
9671 "Return a list of all local variables in an Org mode buffer."
9672 (delq nil
9673 (mapcar
9674 (lambda (x)
9675 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9676 (name (car binding)))
9677 (and (not (get name 'org-state))
9678 (not (memq name org-unique-local-variables))
9679 (string-match-p
9680 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9681 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9682 (symbol-name name))
9683 binding)))
9684 (with-temp-buffer
9685 (org-mode)
9686 (buffer-local-variables)))))
9688 (defun org-clone-local-variables (from-buffer &optional regexp)
9689 "Clone local variables from FROM-BUFFER.
9690 Optional argument REGEXP selects variables to clone."
9691 (dolist (pair (buffer-local-variables from-buffer))
9692 (let ((name (car pair)))
9693 (when (and (symbolp name)
9694 (not (memq name org-unique-local-variables))
9695 (or (null regexp) (string-match regexp (symbol-name name))))
9696 (set (make-local-variable name) (cdr pair))))))
9698 ;;;###autoload
9699 (defun org-run-like-in-org-mode (cmd)
9700 "Run a command, pretending that the current buffer is in Org mode.
9701 This will temporarily bind local variables that are typically bound in
9702 Org mode to the values they have in Org mode, and then interactively
9703 call CMD."
9704 (org-load-modules-maybe)
9705 (unless org-local-vars
9706 (setq org-local-vars (org-get-local-variables)))
9707 (let (binds)
9708 (dolist (var org-local-vars)
9709 (when (or (not (boundp (car var)))
9710 (eq (symbol-value (car var))
9711 (default-value (car var))))
9712 (push (list (car var) `(quote ,(cadr var))) binds)))
9713 (eval `(let ,binds
9714 (call-interactively (quote ,cmd))))))
9716 (defun org-get-category (&optional pos force-refresh)
9717 "Get the category applying to position POS."
9718 (save-match-data
9719 (when force-refresh (org-refresh-category-properties))
9720 (let ((pos (or pos (point))))
9721 (or (get-text-property pos 'org-category)
9722 (progn (org-refresh-category-properties)
9723 (get-text-property pos 'org-category))))))
9725 ;;; Refresh properties
9727 (defun org-refresh-properties (dprop tprop)
9728 "Refresh buffer text properties.
9729 DPROP is the drawer property and TPROP is either the
9730 corresponding text property to set, or an alist with each element
9731 being a text property (as a symbol) and a function to apply to
9732 the value of the drawer property."
9733 (let ((case-fold-search t)
9734 (inhibit-read-only t))
9735 (org-with-silent-modifications
9736 (org-with-wide-buffer
9737 (goto-char (point-min))
9738 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9739 (org-refresh-property tprop (match-string-no-properties 1)))))))
9741 (defun org-refresh-property (tprop p)
9742 "Refresh the buffer text property TPROP from the drawer property P.
9743 The refresh happens only for the current tree (not subtree)."
9744 (unless (org-before-first-heading-p)
9745 (save-excursion
9746 (org-back-to-heading t)
9747 (if (symbolp tprop)
9748 ;; TPROP is a text property symbol
9749 (put-text-property
9750 (point) (or (outline-next-heading) (point-max)) tprop p)
9751 ;; TPROP is an alist with (properties . function) elements
9752 (dolist (al tprop)
9753 (save-excursion
9754 (put-text-property
9755 (line-beginning-position) (or (outline-next-heading) (point-max))
9756 (car al)
9757 (funcall (cdr al) p))))))))
9759 (defun org-refresh-category-properties ()
9760 "Refresh category text properties in the buffer."
9761 (let ((case-fold-search t)
9762 (inhibit-read-only t)
9763 (default-category
9764 (cond ((null org-category)
9765 (if buffer-file-name
9766 (file-name-sans-extension
9767 (file-name-nondirectory buffer-file-name))
9768 "???"))
9769 ((symbolp org-category) (symbol-name org-category))
9770 (t org-category))))
9771 (org-with-silent-modifications
9772 (org-with-wide-buffer
9773 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9774 ;; This is the default category for the buffer. If none is
9775 ;; found, fall-back to `org-category' or buffer file name.
9776 (put-text-property
9777 (point-min) (point-max)
9778 'org-category
9779 (catch 'buffer-category
9780 (goto-char (point-max))
9781 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9782 (let ((element (org-element-at-point)))
9783 (when (eq (org-element-type element) 'keyword)
9784 (throw 'buffer-category
9785 (org-element-property :value element)))))
9786 default-category))
9787 ;; Set sub-tree specific categories.
9788 (goto-char (point-min))
9789 (let ((regexp (org-re-property "CATEGORY")))
9790 (while (re-search-forward regexp nil t)
9791 (let ((value (match-string-no-properties 3)))
9792 (when (org-at-property-p)
9793 (put-text-property
9794 (save-excursion (org-back-to-heading t) (point))
9795 (save-excursion (org-end-of-subtree t t) (point))
9796 'org-category
9797 value)))))))))
9799 (defun org-refresh-stats-properties ()
9800 "Refresh stats text properties in the buffer."
9801 (let (stats)
9802 (org-with-silent-modifications
9803 (org-with-wide-buffer
9804 (goto-char (point-min))
9805 (while (re-search-forward
9806 (concat org-outline-regexp-bol ".*"
9807 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9808 nil t)
9809 (setq stats (cond ((equal (match-string 3) "0") 0)
9810 ((match-string 2)
9811 (/ (* (string-to-number (match-string 2)) 100)
9812 (string-to-number (match-string 3))))
9813 (t (string-to-number (match-string 1)))))
9814 (org-back-to-heading t)
9815 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9816 'org-stats stats))))))
9818 (defun org-refresh-effort-properties ()
9819 "Refresh effort properties"
9820 (org-refresh-properties
9821 org-effort-property
9822 '((effort . identity)
9823 (effort-minutes . org-duration-string-to-minutes))))
9825 ;;;; Link Stuff
9827 ;;; Link abbreviations
9829 (defun org-link-expand-abbrev (link)
9830 "Apply replacements as defined in `org-link-abbrev-alist'."
9831 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9832 (let* ((key (match-string 1 link))
9833 (as (or (assoc key org-link-abbrev-alist-local)
9834 (assoc key org-link-abbrev-alist)))
9835 (tag (and (match-end 2) (match-string 3 link)))
9836 rpl)
9837 (if (not as)
9838 link
9839 (setq rpl (cdr as))
9840 (cond
9841 ((symbolp rpl) (funcall rpl tag))
9842 ((string-match "%(\\([^)]+\\))" rpl)
9843 (replace-match
9844 (save-match-data
9845 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9846 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9847 ((string-match "%h" rpl)
9848 (replace-match (url-hexify-string (or tag "")) t t rpl))
9849 (t (concat rpl tag)))))
9850 link))
9852 ;;; Storing and inserting links
9854 (defvar org-insert-link-history nil
9855 "Minibuffer history for links inserted with `org-insert-link'.")
9857 (defvar org-stored-links nil
9858 "Contains the links stored with `org-store-link'.")
9860 (defvar org-store-link-plist nil
9861 "Plist with info about the most recently link created with `org-store-link'.")
9863 (defun org-store-link-functions ()
9864 "Return a list of functions that are called to create and store a link.
9865 The functions defined in the :store property of
9866 `org-link-parameters'.
9868 Each function will be called in turn until one returns a non-nil
9869 value. Each function should check if it is responsible for
9870 creating this link (for example by looking at the major mode).
9871 If not, it must exit and return nil. If yes, it should return
9872 a non-nil value after calling `org-store-link-props' with a list
9873 of properties and values. Special properties are:
9875 :type The link prefix, like \"http\". This must be given.
9876 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9877 This is obligatory as well.
9878 :description Optional default description for the second pair
9879 of brackets in an Org mode link. The user can still change
9880 this when inserting this link into an Org mode buffer.
9882 In addition to these, any additional properties can be specified
9883 and then used in capture templates."
9884 (cl-loop for link in org-link-parameters
9885 with store-func
9886 do (setq store-func (org-link-get-parameter (car link) :store))
9887 if store-func
9888 collect store-func))
9890 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9891 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9893 ;;;###autoload
9894 (defun org-store-link (arg)
9895 "Store an org-link to the current location.
9896 \\<org-mode-map>
9897 This link is added to `org-stored-links' and can later be inserted
9898 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9900 For some link types, a `\\[universal-argument]' prefix ARG is interpreted.
9901 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9902 For file links, ARG negates `org-context-in-file-links'.
9904 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9905 skipping storing functions that are not
9906 part of Org core.
9908 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9909 prefix ARG forces storing a link for each line in the
9910 active region."
9911 (interactive "P")
9912 (org-load-modules-maybe)
9913 (if (and (equal arg '(64)) (org-region-active-p))
9914 (save-excursion
9915 (let ((end (region-end)))
9916 (goto-char (region-beginning))
9917 (set-mark (point))
9918 (while (< (point-at-eol) end)
9919 (move-end-of-line 1) (activate-mark)
9920 (let (current-prefix-arg)
9921 (call-interactively 'org-store-link))
9922 (move-beginning-of-line 2)
9923 (set-mark (point)))))
9924 (setq org-store-link-plist nil)
9925 (let (link cpltxt desc description search
9926 txt custom-id agenda-link sfuns sfunsn)
9927 (cond
9929 ;; Store a link using an external link type
9930 ((and (not (equal arg '(16)))
9931 (setq sfuns
9932 (delq
9933 nil (mapcar (lambda (f)
9934 (let (fs) (if (funcall f) (push f fs))))
9935 (org-store-link-functions)))
9936 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9937 (or (and (cdr sfuns)
9938 (funcall (intern
9939 (completing-read
9940 "Which function for creating the link? "
9941 sfunsn nil t (car sfunsn)))))
9942 (funcall (caar sfuns)))
9943 (setq link (plist-get org-store-link-plist :link)
9944 desc (or (plist-get org-store-link-plist
9945 :description)
9946 link))))
9948 ;; Store a link from a source code buffer.
9949 ((org-src-edit-buffer-p)
9950 (let ((coderef-format (org-src-coderef-format)))
9951 (cond ((save-excursion
9952 (beginning-of-line)
9953 (looking-at (org-src-coderef-regexp coderef-format)))
9954 (setq link (format "(%s)" (match-string-no-properties 3))))
9955 ((called-interactively-p 'any)
9956 (let ((label (read-string "Code line label: ")))
9957 (end-of-line)
9958 (setq link (format coderef-format label))
9959 (let ((gc (- 79 (length link))))
9960 (if (< (current-column) gc)
9961 (org-move-to-column gc t)
9962 (insert " ")))
9963 (insert link)
9964 (setq link (concat "(" label ")"))
9965 (setq desc nil)))
9966 (t (setq link nil)))))
9968 ;; We are in the agenda, link to referenced location
9969 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9970 (let ((m (or (get-text-property (point) 'org-hd-marker)
9971 (get-text-property (point) 'org-marker))))
9972 (when m
9973 (org-with-point-at m
9974 (setq agenda-link
9975 (if (called-interactively-p 'any)
9976 (call-interactively 'org-store-link)
9977 (org-store-link nil)))))))
9979 ((eq major-mode 'calendar-mode)
9980 (let ((cd (calendar-cursor-to-date)))
9981 (setq link
9982 (format-time-string
9983 (car org-time-stamp-formats)
9984 (apply 'encode-time
9985 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9986 nil nil nil))))
9987 (org-store-link-props :type "calendar" :date cd)))
9989 ((eq major-mode 'help-mode)
9990 (setq link (concat "help:" (save-excursion
9991 (goto-char (point-min))
9992 (looking-at "^[^ ]+")
9993 (match-string 0))))
9994 (org-store-link-props :type "help"))
9996 ((eq major-mode 'w3-mode)
9997 (setq cpltxt (if (and (buffer-name)
9998 (not (string-match "Untitled" (buffer-name))))
9999 (buffer-name)
10000 (url-view-url t))
10001 link (url-view-url t))
10002 (org-store-link-props :type "w3" :url (url-view-url t)))
10004 ((eq major-mode 'image-mode)
10005 (setq cpltxt (concat "file:"
10006 (abbreviate-file-name buffer-file-name))
10007 link cpltxt)
10008 (org-store-link-props :type "image" :file buffer-file-name))
10010 ;; In dired, store a link to the file of the current line
10011 ((derived-mode-p 'dired-mode)
10012 (let ((file (dired-get-filename nil t)))
10013 (setq file (if file
10014 (abbreviate-file-name
10015 (expand-file-name (dired-get-filename nil t)))
10016 ;; otherwise, no file so use current directory.
10017 default-directory))
10018 (setq cpltxt (concat "file:" file)
10019 link cpltxt)))
10021 ((setq search (run-hook-with-args-until-success
10022 'org-create-file-search-functions))
10023 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10024 "::" search))
10025 (setq cpltxt (or description link)))
10027 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
10028 (org-with-limited-levels
10029 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
10030 (cond
10031 ;; Store a link using the target at point
10032 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
10033 (setq cpltxt
10034 (concat "file:"
10035 (abbreviate-file-name
10036 (buffer-file-name (buffer-base-buffer)))
10037 "::" (match-string 1))
10038 link cpltxt))
10039 ((and (featurep 'org-id)
10040 (or (eq org-id-link-to-org-use-id t)
10041 (and (called-interactively-p 'any)
10042 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
10043 (and (eq org-id-link-to-org-use-id
10044 'create-if-interactive-and-no-custom-id)
10045 (not custom-id))))
10046 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
10047 ;; Store a link using the ID at point
10048 (setq link (condition-case nil
10049 (prog1 (org-id-store-link)
10050 (setq desc (or (plist-get org-store-link-plist
10051 :description)
10052 "")))
10053 (error
10054 ;; Probably before first headline, link only to file
10055 (concat "file:"
10056 (abbreviate-file-name
10057 (buffer-file-name (buffer-base-buffer))))))))
10059 ;; Just link to current headline
10060 (setq cpltxt (concat "file:"
10061 (abbreviate-file-name
10062 (buffer-file-name (buffer-base-buffer)))))
10063 ;; Add a context search string
10064 (when (org-xor org-context-in-file-links arg)
10065 (let* ((element (org-element-at-point))
10066 (name (org-element-property :name element)))
10067 (setq txt (cond
10068 ((org-at-heading-p) nil)
10069 (name)
10070 ((org-region-active-p)
10071 (buffer-substring (region-beginning) (region-end)))))
10072 (when (or (null txt) (string-match "\\S-" txt))
10073 (setq cpltxt
10074 (concat cpltxt "::"
10075 (condition-case nil
10076 (org-make-org-heading-search-string txt)
10077 (error "")))
10078 desc (or name
10079 (nth 4 (ignore-errors (org-heading-components)))
10080 "NONE")))))
10081 (when (string-match "::\\'" cpltxt)
10082 (setq cpltxt (substring cpltxt 0 -2)))
10083 (setq link cpltxt)))))
10085 ((buffer-file-name (buffer-base-buffer))
10086 ;; Just link to this file here.
10087 (setq cpltxt (concat "file:"
10088 (abbreviate-file-name
10089 (buffer-file-name (buffer-base-buffer)))))
10090 ;; Add a context string.
10091 (when (org-xor org-context-in-file-links arg)
10092 (setq txt (if (org-region-active-p)
10093 (buffer-substring (region-beginning) (region-end))
10094 (buffer-substring (point-at-bol) (point-at-eol))))
10095 ;; Only use search option if there is some text.
10096 (when (string-match "\\S-" txt)
10097 (setq cpltxt
10098 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10099 desc "NONE")))
10100 (setq link cpltxt))
10102 ((called-interactively-p 'interactive)
10103 (user-error "No method for storing a link from this buffer"))
10105 (t (setq link nil)))
10107 ;; We're done setting link and desc, clean up
10108 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10109 (setq link (or link cpltxt)
10110 desc (or desc cpltxt))
10111 (cond ((not desc))
10112 ((equal desc "NONE") (setq desc nil))
10113 (t (setq desc
10114 (replace-regexp-in-string
10115 org-bracket-link-analytic-regexp
10116 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10117 desc))))
10118 ;; Return the link
10119 (if (not (and (or (called-interactively-p 'any)
10120 executing-kbd-macro)
10121 link))
10122 (or agenda-link (and link (org-make-link-string link desc)))
10123 (push (list link desc) org-stored-links)
10124 (message "Stored: %s" (or desc link))
10125 (when custom-id
10126 (setq link (concat "file:" (abbreviate-file-name
10127 (buffer-file-name)) "::#" custom-id))
10128 (push (list link desc) org-stored-links))
10129 (car org-stored-links)))))
10131 (defun org-store-link-props (&rest plist)
10132 "Store link properties, extract names, addresses and dates."
10133 (let ((x (plist-get plist :from)))
10134 (when x
10135 (let ((adr (mail-extract-address-components x)))
10136 (setq plist (plist-put plist :fromname (car adr)))
10137 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10138 (let ((x (plist-get plist :to)))
10139 (when x
10140 (let ((adr (mail-extract-address-components x)))
10141 (setq plist (plist-put plist :toname (car adr)))
10142 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10143 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10144 (when x
10145 (setq plist (plist-put plist :date-timestamp
10146 (format-time-string
10147 (org-time-stamp-format t) x)))
10148 (setq plist (plist-put plist :date-timestamp-inactive
10149 (format-time-string
10150 (org-time-stamp-format t t) x)))))
10151 (let ((from (plist-get plist :from))
10152 (to (plist-get plist :to)))
10153 (when (and from to org-from-is-user-regexp)
10154 (setq plist
10155 (plist-put plist :fromto
10156 (if (string-match org-from-is-user-regexp from)
10157 (concat "to %t")
10158 (concat "from %f"))))))
10159 (setq org-store-link-plist plist))
10161 (defun org-add-link-props (&rest plist)
10162 "Add these properties to the link property list."
10163 (let (key value)
10164 (while plist
10165 (setq key (pop plist) value (pop plist))
10166 (setq org-store-link-plist
10167 (plist-put org-store-link-plist key value)))))
10169 (defun org-email-link-description (&optional fmt)
10170 "Return the description part of an email link.
10171 This takes information from `org-store-link-plist' and formats it
10172 according to FMT (default from `org-email-link-description-format')."
10173 (setq fmt (or fmt org-email-link-description-format))
10174 (let* ((p org-store-link-plist)
10175 (to (plist-get p :toaddress))
10176 (from (plist-get p :fromaddress))
10177 (table
10178 (list
10179 (cons "%c" (plist-get p :fromto))
10180 (cons "%F" (plist-get p :from))
10181 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10182 (cons "%T" (plist-get p :to))
10183 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10184 (cons "%s" (plist-get p :subject))
10185 (cons "%d" (plist-get p :date))
10186 (cons "%m" (plist-get p :message-id)))))
10187 (when (string-match "%c" fmt)
10188 ;; Check if the user wrote this message
10189 (if (and org-from-is-user-regexp from to
10190 (save-match-data (string-match org-from-is-user-regexp from)))
10191 (setq fmt (replace-match "to %t" t t fmt))
10192 (setq fmt (replace-match "from %f" t t fmt))))
10193 (org-replace-escapes fmt table)))
10195 (defun org-make-org-heading-search-string (&optional string)
10196 "Make search string for the current headline or STRING."
10197 (let ((s (or string
10198 (and (derived-mode-p 'org-mode)
10199 (save-excursion
10200 (org-back-to-heading t)
10201 (org-element-property :raw-value (org-element-at-point))))))
10202 (lines org-context-in-file-links))
10203 (or string (setq s (concat "*" s))) ; Add * for headlines
10204 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10205 (when (and string (integerp lines) (> lines 0))
10206 (let ((slines (org-split-string s "\n")))
10207 (when (< lines (length slines))
10208 (setq s (mapconcat
10209 'identity
10210 (reverse (nthcdr (- (length slines) lines)
10211 (reverse slines))) "\n")))))
10212 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10214 (defun org-make-link-string (link &optional description)
10215 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10216 (unless (org-string-nw-p link) (error "Empty link"))
10217 (let ((uri (cond ((string-match org-link-types-re link)
10218 (concat (match-string 1 link)
10219 (org-link-escape (substring link (match-end 1)))))
10220 ;; For readability, url-encode internal links only
10221 ;; when absolutely needed (i.e, when they contain
10222 ;; square brackets). File links however, are
10223 ;; encoded since, e.g., spaces are significant.
10224 ((or (file-name-absolute-p link)
10225 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10226 (org-link-escape link))
10227 (t link)))
10228 (description
10229 (and (org-string-nw-p description)
10230 ;; Remove brackets from description, as they are fatal.
10231 (replace-regexp-in-string
10232 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10233 (org-trim description)))))
10234 (format "[[%s]%s]"
10236 (if description (format "[%s]" description) ""))))
10238 (defconst org-link-escape-chars
10239 ;;%20 %5B %5D %25
10240 '(?\s ?\[ ?\] ?%)
10241 "List of characters that should be escaped in a link when stored to Org.
10242 This is the list that is used for internal purposes.")
10244 (defun org-link-escape (text &optional table merge)
10245 "Return percent escaped representation of TEXT.
10246 TEXT is a string with the text to escape.
10247 Optional argument TABLE is a list with characters that should be
10248 escaped. When nil, `org-link-escape-chars' is used.
10249 If optional argument MERGE is set, merge TABLE into
10250 `org-link-escape-chars'."
10251 (let ((characters-to-encode
10252 (cond ((null table) org-link-escape-chars)
10253 (merge (append org-link-escape-chars table))
10254 (t table))))
10255 (mapconcat
10256 (lambda (c)
10257 (if (or (memq c characters-to-encode)
10258 (and org-url-hexify-p (or (< c 32) (> c 126))))
10259 (mapconcat (lambda (e) (format "%%%.2X" e))
10260 (or (encode-coding-char c 'utf-8)
10261 (error "Unable to percent escape character: %c" c))
10263 (char-to-string c)))
10264 text "")))
10266 (defun org-link-unescape (str)
10267 "Unhex hexified Unicode parts in string STR.
10268 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10269 reciprocal of `org-link-escape', which see."
10270 (if (org-string-nw-p str)
10271 (replace-regexp-in-string
10272 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10273 str))
10275 (defun org-link-unescape-compound (hex)
10276 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10277 Note: this function also decodes single byte encodings like
10278 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10279 (save-match-data
10280 (let* ((bytes (cdr (split-string hex "%")))
10281 (ret "")
10282 (eat 0)
10283 (sum 0))
10284 (while bytes
10285 (let* ((val (string-to-number (pop bytes) 16))
10286 (shift-xor
10287 (if (= 0 eat)
10288 (cond
10289 ((>= val 252) (cons 6 252))
10290 ((>= val 248) (cons 5 248))
10291 ((>= val 240) (cons 4 240))
10292 ((>= val 224) (cons 3 224))
10293 ((>= val 192) (cons 2 192))
10294 (t (cons 0 0)))
10295 (cons 6 128))))
10296 (when (>= val 192) (setq eat (car shift-xor)))
10297 (setq val (logxor val (cdr shift-xor)))
10298 (setq sum (+ (lsh sum (car shift-xor)) val))
10299 (when (> eat 0) (setq eat (- eat 1)))
10300 (cond
10301 ((= 0 eat) ;multi byte
10302 (setq ret (concat ret (char-to-string sum)))
10303 (setq sum 0))
10304 ((not bytes) ; single byte(s)
10305 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10306 ret)))
10308 (defun org-link-unescape-single-byte-sequence (hex)
10309 "Unhexify hex-encoded single byte character sequences."
10310 (mapconcat (lambda (byte)
10311 (char-to-string (string-to-number byte 16)))
10312 (cdr (split-string hex "%")) ""))
10314 (defun org-xor (a b)
10315 "Exclusive or."
10316 (if a (not b) b))
10318 (defun org-fixup-message-id-for-http (s)
10319 "Replace special characters in a message id, so it can be used in an http query."
10320 (when (string-match "%" s)
10321 (setq s (mapconcat (lambda (c)
10322 (if (eq c ?%)
10323 "%25"
10324 (char-to-string c)))
10325 s "")))
10326 (while (string-match "<" s)
10327 (setq s (replace-match "%3C" t t s)))
10328 (while (string-match ">" s)
10329 (setq s (replace-match "%3E" t t s)))
10330 (while (string-match "@" s)
10331 (setq s (replace-match "%40" t t s)))
10334 (defun org-link-prettify (link)
10335 "Return a human-readable representation of LINK.
10336 The car of LINK must be a raw link.
10337 The cdr of LINK must be either a link description or nil."
10338 (let ((desc (or (cadr link) "<no description>")))
10339 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10340 "<" (car link) ">")))
10342 ;;;###autoload
10343 (defun org-insert-link-global ()
10344 "Insert a link like Org mode does.
10345 This command can be called in any mode to insert a link in Org syntax."
10346 (interactive)
10347 (org-load-modules-maybe)
10348 (org-run-like-in-org-mode 'org-insert-link))
10350 (defun org-insert-all-links (arg &optional pre post)
10351 "Insert all links in `org-stored-links'.
10352 When a universal prefix, do not delete the links from `org-stored-links'.
10353 When `ARG' is a number, insert the last N link(s).
10354 `PRE' and `POST' are optional arguments to define a string to
10355 prepend or to append."
10356 (interactive "P")
10357 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10358 (links (copy-sequence org-stored-links))
10359 (pr (or pre "- "))
10360 (po (or post "\n"))
10361 (cnt 1) l)
10362 (if (null org-stored-links)
10363 (message "No link to insert")
10364 (while (and (or (listp arg) (>= arg cnt))
10365 (setq l (if (listp arg)
10366 (pop links)
10367 (pop org-stored-links))))
10368 (setq cnt (1+ cnt))
10369 (insert pr)
10370 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10371 (insert po)))))
10373 (defun org-insert-last-stored-link (arg)
10374 "Insert the last link stored in `org-stored-links'."
10375 (interactive "p")
10376 (org-insert-all-links arg "" "\n"))
10378 (defun org-link-fontify-links-to-this-file ()
10379 "Fontify links to the current file in `org-stored-links'."
10380 (let ((f (buffer-file-name)) a b)
10381 (setq a (mapcar (lambda(l)
10382 (let ((ll (car l)))
10383 (when (and (string-match "^file:\\(.+\\)::" ll)
10384 (equal f (expand-file-name (match-string 1 ll))))
10385 ll)))
10386 org-stored-links))
10387 (when (featurep 'org-id)
10388 (setq b (mapcar (lambda(l)
10389 (let ((ll (car l)))
10390 (when (and (string-match "^id:\\(.+\\)$" ll)
10391 (equal f (expand-file-name
10392 (or (org-id-find-id-file
10393 (match-string 1 ll)) ""))))
10394 ll)))
10395 org-stored-links)))
10396 (mapcar (lambda(l)
10397 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10398 (delq nil (append a b)))))
10400 (defvar org--links-history nil)
10401 (defun org-insert-link (&optional complete-file link-location default-description)
10402 "Insert a link. At the prompt, enter the link.
10404 Completion can be used to insert any of the link protocol prefixes in use.
10406 The history can be used to select a link previously stored with
10407 `org-store-link'. When the empty string is entered (i.e. if you just
10408 press `RET' at the prompt), the link defaults to the most recently
10409 stored link. As `SPC' triggers completion in the minibuffer, you need to
10410 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10412 You will also be prompted for a description, and if one is given, it will
10413 be displayed in the buffer instead of the link.
10415 If there is already a link at point, this command will allow you to edit
10416 link and description parts.
10418 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10419 file name can be
10420 selected using completion. The path to the file will be relative to the
10421 current directory if the file is in the current directory or a subdirectory.
10422 Otherwise, the link will be the absolute path as completed in the minibuffer
10423 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10424 option `org-link-file-path-type'.
10426 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10427 absolute path even if the file is in
10428 the current directory or below.
10430 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10431 prefix negates `org-keep-stored-link-after-insertion'.
10433 If `org-make-link-description-function' is non-nil, this function will be
10434 called with the link target, and the result will be the default
10435 link description.
10437 If the LINK-LOCATION parameter is non-nil, this value will be used as
10438 the link location instead of reading one interactively.
10440 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10441 as the default description."
10442 (interactive "P")
10443 (let* ((wcf (current-window-configuration))
10444 (origbuf (current-buffer))
10445 (region (when (org-region-active-p)
10446 (buffer-substring (region-beginning) (region-end))))
10447 (remove (and region (list (region-beginning) (region-end))))
10448 (desc region)
10449 (link link-location)
10450 (abbrevs org-link-abbrev-alist-local)
10451 entry all-prefixes auto-desc)
10452 (cond
10453 (link-location) ; specified by arg, just use it.
10454 ((org-in-regexp org-bracket-link-regexp 1)
10455 ;; We do have a link at point, and we are going to edit it.
10456 (setq remove (list (match-beginning 0) (match-end 0)))
10457 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10458 (setq link (read-string "Link: "
10459 (org-link-unescape
10460 (match-string-no-properties 1)))))
10461 ((or (org-in-regexp org-angle-link-re)
10462 (org-in-regexp org-plain-link-re))
10463 ;; Convert to bracket link
10464 (setq remove (list (match-beginning 0) (match-end 0))
10465 link (read-string "Link: "
10466 (org-unbracket-string "<" ">" (match-string 0)))))
10467 ((member complete-file '((4) (16)))
10468 ;; Completing read for file names.
10469 (setq link (org-file-complete-link complete-file)))
10471 ;; Read link, with completion for stored links.
10472 (org-link-fontify-links-to-this-file)
10473 (org-switch-to-buffer-other-window "*Org Links*")
10474 (with-current-buffer "*Org Links*"
10475 (erase-buffer)
10476 (insert "Insert a link.
10477 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10478 (when org-stored-links
10479 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10480 (insert (mapconcat 'org-link-prettify
10481 (reverse org-stored-links) "\n")))
10482 (goto-char (point-min)))
10483 (let ((cw (selected-window)))
10484 (select-window (get-buffer-window "*Org Links*" 'visible))
10485 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10486 (unless (pos-visible-in-window-p (point-max))
10487 (org-fit-window-to-buffer))
10488 (and (window-live-p cw) (select-window cw)))
10489 (setq all-prefixes (append (mapcar 'car abbrevs)
10490 (mapcar 'car org-link-abbrev-alist)
10491 (org-link-types)))
10492 (unwind-protect
10493 ;; Fake a link history, containing the stored links.
10494 (let ((org--links-history
10495 (append (mapcar #'car org-stored-links)
10496 org-insert-link-history)))
10497 (setq link
10498 (org-completing-read
10499 "Link: "
10500 (append
10501 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10502 (mapcar #'car org-stored-links))
10503 nil nil nil
10504 'org--links-history
10505 (caar org-stored-links)))
10506 (unless (org-string-nw-p link) (user-error "No link selected"))
10507 (dolist (l org-stored-links)
10508 (when (equal link (cadr l))
10509 (setq link (car l))
10510 (setq auto-desc t)))
10511 (when (or (member link all-prefixes)
10512 (and (equal ":" (substring link -1))
10513 (member (substring link 0 -1) all-prefixes)
10514 (setq link (substring link 0 -1))))
10515 (setq link (with-current-buffer origbuf
10516 (org-link-try-special-completion link)))))
10517 (set-window-configuration wcf)
10518 (kill-buffer "*Org Links*"))
10519 (setq entry (assoc link org-stored-links))
10520 (or entry (push link org-insert-link-history))
10521 (setq desc (or desc (nth 1 entry)))))
10523 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10524 (not org-keep-stored-link-after-insertion))
10525 (setq org-stored-links (delq (assoc link org-stored-links)
10526 org-stored-links)))
10528 (when (and (string-match org-plain-link-re link)
10529 (not (string-match org-ts-regexp link)))
10530 ;; URL-like link, normalize the use of angular brackets.
10531 (setq link (org-unbracket-string "<" ">" link)))
10533 ;; Check if we are linking to the current file with a search
10534 ;; option If yes, simplify the link by using only the search
10535 ;; option.
10536 (when (and buffer-file-name
10537 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10538 (let* ((path (match-string 1 link))
10539 (case-fold-search nil)
10540 (search (match-string 2 link)))
10541 (save-match-data
10542 (when (equal (file-truename buffer-file-name) (file-truename path))
10543 ;; We are linking to this same file, with a search option
10544 (setq link search)))))
10546 ;; Check if we can/should use a relative path. If yes, simplify the link
10547 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10548 (let* ((type (match-string 1 link))
10549 (path (match-string 2 link))
10550 (origpath path)
10551 (case-fold-search nil))
10552 (cond
10553 ((or (eq org-link-file-path-type 'absolute)
10554 (equal complete-file '(16)))
10555 (setq path (abbreviate-file-name (expand-file-name path))))
10556 ((eq org-link-file-path-type 'noabbrev)
10557 (setq path (expand-file-name path)))
10558 ((eq org-link-file-path-type 'relative)
10559 (setq path (file-relative-name path)))
10561 (save-match-data
10562 (if (string-match (concat "^" (regexp-quote
10563 (expand-file-name
10564 (file-name-as-directory
10565 default-directory))))
10566 (expand-file-name path))
10567 ;; We are linking a file with relative path name.
10568 (setq path (substring (expand-file-name path)
10569 (match-end 0)))
10570 (setq path (abbreviate-file-name (expand-file-name path)))))))
10571 (setq link (concat type path))
10572 (when (equal desc origpath)
10573 (setq desc path))))
10575 (if org-make-link-description-function
10576 (setq desc
10577 (or (condition-case nil
10578 (funcall org-make-link-description-function link desc)
10579 (error (progn (message "Can't get link description from `%s'"
10580 (symbol-name org-make-link-description-function))
10581 (sit-for 2) nil)))
10582 (read-string "Description: " default-description)))
10583 (if default-description (setq desc default-description)
10584 (setq desc (or (and auto-desc desc)
10585 (read-string "Description: " desc)))))
10587 (unless (string-match "\\S-" desc) (setq desc nil))
10588 (when remove (apply 'delete-region remove))
10589 (insert (org-make-link-string link desc))
10590 ;; Redisplay so as the new link has proper invisible characters.
10591 (sit-for 0)))
10593 (defun org-link-try-special-completion (type)
10594 "If there is completion support for link type TYPE, offer it."
10595 (let ((fun (org-link-get-parameter type :complete)))
10596 (if (functionp fun)
10597 (funcall fun)
10598 (read-string "Link (no completion support): " (concat type ":")))))
10600 (defun org-file-complete-link (&optional arg)
10601 "Create a file link using completion."
10602 (let ((file (read-file-name "File: "))
10603 (pwd (file-name-as-directory (expand-file-name ".")))
10604 (pwd1 (file-name-as-directory (abbreviate-file-name
10605 (expand-file-name ".")))))
10606 (cond ((equal arg '(16))
10607 (concat "file:"
10608 (abbreviate-file-name (expand-file-name file))))
10609 ((string-match
10610 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10611 (concat "file:" (match-string 1 file)))
10612 ((string-match
10613 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10614 (expand-file-name file))
10615 (concat "file:"
10616 (match-string 1 (expand-file-name file))))
10617 (t (concat "file:" file)))))
10619 (defun org-completing-read (&rest args)
10620 "Completing-read with SPACE being a normal character."
10621 (let ((enable-recursive-minibuffers t)
10622 (minibuffer-local-completion-map
10623 (copy-keymap minibuffer-local-completion-map)))
10624 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10625 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10626 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10627 'org-time-stamp-inactive)
10628 (apply #'completing-read args)))
10630 ;;; Opening/following a link
10632 (defvar org-link-search-failed nil)
10634 (defvar org-open-link-functions nil
10635 "Hook for functions finding a plain text link.
10636 These functions must take a single argument, the link content.
10637 They will be called for links that look like [[link text][description]]
10638 when LINK TEXT does not have a protocol like \"http:\" and does not look
10639 like a filename (e.g. \"./blue.png\").
10641 These functions will be called *before* Org attempts to resolve the
10642 link by doing text searches in the current buffer - so if you want a
10643 link \"[[target]]\" to still find \"<<target>>\", your function should
10644 handle this as a special case.
10646 When the function does handle the link, it must return a non-nil value.
10647 If it decides that it is not responsible for this link, it must return
10648 nil to indicate that that Org can continue with other options like
10649 exact and fuzzy text search.")
10651 (defun org-next-link (&optional search-backward)
10652 "Move forward to the next link.
10653 If the link is in hidden text, expose it."
10654 (interactive "P")
10655 (when (and org-link-search-failed (eq this-command last-command))
10656 (goto-char (point-min))
10657 (message "Link search wrapped back to beginning of buffer"))
10658 (setq org-link-search-failed nil)
10659 (let* ((pos (point))
10660 (ct (org-context))
10661 (a (assq :link ct))
10662 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10663 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10664 ((looking-at org-any-link-re)
10665 ;; Don't stay stuck at link without an org-link face
10666 (forward-char (if search-backward -1 1))))
10667 (if (funcall srch-fun org-any-link-re nil t)
10668 (progn
10669 (goto-char (match-beginning 0))
10670 (when (outline-invisible-p) (org-show-context)))
10671 (goto-char pos)
10672 (setq org-link-search-failed t)
10673 (message "No further link found"))))
10675 (defun org-previous-link ()
10676 "Move backward to the previous link.
10677 If the link is in hidden text, expose it."
10678 (interactive)
10679 (funcall 'org-next-link t))
10681 (defun org-translate-link (s)
10682 "Translate a link string if a translation function has been defined."
10683 (with-temp-buffer
10684 (insert (org-trim s))
10685 (org-trim (org-element-interpret-data (org-element-context)))))
10687 (defun org-translate-link-from-planner (type path)
10688 "Translate a link from Emacs Planner syntax so that Org can follow it.
10689 This is still an experimental function, your mileage may vary."
10690 (cond
10691 ((member type '("http" "https" "news" "ftp"))
10692 ;; standard Internet links are the same.
10693 nil)
10694 ((and (equal type "irc") (string-match "^//" path))
10695 ;; Planner has two / at the beginning of an irc link, we have 1.
10696 ;; We should have zero, actually....
10697 (setq path (substring path 1)))
10698 ((and (equal type "lisp") (string-match "^/" path))
10699 ;; Planner has a slash, we do not.
10700 (setq type "elisp" path (substring path 1)))
10701 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10702 ;; A typical message link. Planner has the id after the final slash,
10703 ;; we separate it with a hash mark
10704 (setq path (concat (match-string 1 path) "#"
10705 (org-unbracket-string "<" ">" (match-string 2 path))))))
10706 (cons type path))
10708 (defun org-find-file-at-mouse (ev)
10709 "Open file link or URL at mouse."
10710 (interactive "e")
10711 (mouse-set-point ev)
10712 (org-open-at-point 'in-emacs))
10714 (defun org-open-at-mouse (ev)
10715 "Open file link or URL at mouse.
10716 See the docstring of `org-open-file' for details."
10717 (interactive "e")
10718 (mouse-set-point ev)
10719 (when (eq major-mode 'org-agenda-mode)
10720 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10721 (org-open-at-point))
10723 (defvar org-window-config-before-follow-link nil
10724 "The window configuration before following a link.
10725 This is saved in case the need arises to restore it.")
10727 ;;;###autoload
10728 (defun org-open-at-point-global ()
10729 "Follow a link or time-stamp like Org mode does.
10730 This command can be called in any mode to follow an external link
10731 or a time-stamp that has Org mode syntax. Its behavior is
10732 undefined when called on internal links (e.g., fuzzy links).
10733 Raise an error when there is nothing to follow. "
10734 (interactive)
10735 (cond ((org-in-regexp org-any-link-re)
10736 (org-open-link-from-string (match-string-no-properties 0)))
10737 ((or (org-in-regexp org-ts-regexp-both nil t)
10738 (org-in-regexp org-tsr-regexp-both nil t))
10739 (org-follow-timestamp-link))
10740 (t (user-error "No link found"))))
10742 ;;;###autoload
10743 (defun org-open-link-from-string (s &optional arg reference-buffer)
10744 "Open a link in the string S, as if it was in Org mode."
10745 (interactive "sLink: \nP")
10746 (let ((reference-buffer (or reference-buffer (current-buffer))))
10747 (with-temp-buffer
10748 (let ((org-inhibit-startup (not reference-buffer)))
10749 (org-mode)
10750 (insert s)
10751 (goto-char (point-min))
10752 (when reference-buffer
10753 (setq org-link-abbrev-alist-local
10754 (with-current-buffer reference-buffer
10755 org-link-abbrev-alist-local)))
10756 (org-open-at-point arg reference-buffer)))))
10758 (defvar org-open-at-point-functions nil
10759 "Hook that is run when following a link at point.
10761 Functions in this hook must return t if they identify and follow
10762 a link at point. If they don't find anything interesting at point,
10763 they must return nil.")
10765 (defvar org-link-search-inhibit-query nil)
10766 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10767 (defun org--open-doi-link (path)
10768 "Open a \"doi\" type link.
10769 PATH is a the path to search for, as a string."
10770 (browse-url (url-encode-url (concat org-doi-server-url path))))
10772 (defun org--open-elisp-link (path)
10773 "Open a \"elisp\" type link.
10774 PATH is the sexp to evaluate, as a string."
10775 (let ((cmd path))
10776 (if (or (and (org-string-nw-p
10777 org-confirm-elisp-link-not-regexp)
10778 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10779 (not org-confirm-elisp-link-function)
10780 (funcall org-confirm-elisp-link-function
10781 (format "Execute \"%s\" as elisp? "
10782 (org-add-props cmd nil 'face 'org-warning))))
10783 (message "%s => %s" cmd
10784 (if (eq (string-to-char cmd) ?\()
10785 (eval (read cmd))
10786 (call-interactively (read cmd))))
10787 (user-error "Abort"))))
10789 (defun org--open-help-link (path)
10790 "Open a \"help\" type link.
10791 PATH is a symbol name, as a string."
10792 (pcase (intern path)
10793 ((and (pred fboundp) variable) (describe-function variable))
10794 ((and (pred boundp) function) (describe-variable function))
10795 (name (user-error "Unknown function or variable: %s" name))))
10797 (defun org--open-shell-link (path)
10798 "Open a \"shell\" type link.
10799 PATH is the command to execute, as a string."
10800 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10801 (cmd path))
10802 (if (or (and (org-string-nw-p
10803 org-confirm-shell-link-not-regexp)
10804 (string-match
10805 org-confirm-shell-link-not-regexp cmd))
10806 (not org-confirm-shell-link-function)
10807 (funcall org-confirm-shell-link-function
10808 (format "Execute \"%s\" in shell? "
10809 (org-add-props cmd nil
10810 'face 'org-warning))))
10811 (progn
10812 (message "Executing %s" cmd)
10813 (shell-command cmd buf)
10814 (when (featurep 'midnight)
10815 (setq clean-buffer-list-kill-buffer-names
10816 (cons (buffer-name buf)
10817 clean-buffer-list-kill-buffer-names))))
10818 (user-error "Abort"))))
10820 (defun org-open-at-point (&optional arg reference-buffer)
10821 "Open link, timestamp, footnote or tags at point.
10823 When point is on a link, follow it. Normally, files will be
10824 opened by an appropriate application. If the optional prefix
10825 argument ARG is non-nil, Emacs will visit the file. With
10826 a double prefix argument, try to open outside of Emacs, in the
10827 application the system uses for this file type.
10829 When point is on a timestamp, open the agenda at the day
10830 specified.
10832 When point is a footnote definition, move to the first reference
10833 found. If it is on a reference, move to the associated
10834 definition.
10836 When point is on a headline, display a list of every link in the
10837 entry, so it is possible to pick one, or all, of them. If point
10838 is on a tag, call `org-tags-view' instead.
10840 When optional argument REFERENCE-BUFFER is non-nil, it should
10841 specify a buffer from where the link search should happen. This
10842 is used internally by `org-open-link-from-string'.
10844 On top of syntactically correct links, this function will open
10845 the link at point in comments or comment blocks and the first
10846 link in a property drawer line."
10847 (interactive "P")
10848 ;; On a code block, open block's results.
10849 (unless (call-interactively 'org-babel-open-src-block-result)
10850 (org-load-modules-maybe)
10851 (setq org-window-config-before-follow-link (current-window-configuration))
10852 (org-remove-occur-highlights nil nil t)
10853 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10854 (let* ((context
10855 ;; Only consider supported types, even if they are not
10856 ;; the closest one.
10857 (org-element-lineage
10858 (org-element-context)
10859 '(clock comment comment-block footnote-definition
10860 footnote-reference headline inlinetask keyword link
10861 node-property timestamp)
10863 (type (org-element-type context))
10864 (value (org-element-property :value context)))
10865 (cond
10866 ((not context) (user-error "No link found"))
10867 ;; Exception: open timestamps and links in properties
10868 ;; drawers, keywords and comments.
10869 ((memq type '(comment comment-block keyword node-property))
10870 (call-interactively #'org-open-at-point-global))
10871 ;; On a headline or an inlinetask, but not on a timestamp,
10872 ;; a link, a footnote reference or on tags.
10873 ((and (memq type '(headline inlinetask))
10874 ;; Not on tags.
10875 (let ((case-fold-search nil))
10876 (save-excursion
10877 (beginning-of-line)
10878 (looking-at org-complex-heading-regexp))
10879 (or (not (match-beginning 5))
10880 (< (point) (match-beginning 5)))))
10881 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10882 (links (car data))
10883 (links-end (cdr data)))
10884 (if links
10885 (dolist (link (if (stringp links) (list links) links))
10886 (search-forward link nil links-end)
10887 (goto-char (match-beginning 0))
10888 (org-open-at-point))
10889 (require 'org-attach)
10890 (org-attach-reveal 'if-exists))))
10891 ;; On a clock line, make sure point is on the timestamp
10892 ;; before opening it.
10893 ((and (eq type 'clock)
10894 value
10895 (>= (point) (org-element-property :begin value))
10896 (<= (point) (org-element-property :end value)))
10897 (org-follow-timestamp-link))
10898 ;; Do nothing on white spaces after an object.
10899 ((>= (point)
10900 (save-excursion
10901 (goto-char (org-element-property :end context))
10902 (skip-chars-backward " \t")
10903 (point)))
10904 (user-error "No link found"))
10905 ((eq type 'timestamp) (org-follow-timestamp-link))
10906 ;; On tags within a headline or an inlinetask.
10907 ((and (memq type '(headline inlinetask))
10908 (let ((case-fold-search nil))
10909 (save-excursion (beginning-of-line)
10910 (looking-at org-complex-heading-regexp))
10911 (and (match-beginning 5)
10912 (>= (point) (match-beginning 5)))))
10913 (org-tags-view arg (substring (match-string 5) 0 -1)))
10914 ((eq type 'link)
10915 ;; When link is located within the description of another
10916 ;; link (e.g., an inline image), always open the parent
10917 ;; link.
10918 (let* ((link (let ((up (org-element-property :parent context)))
10919 (if (eq (org-element-type up) 'link) up context)))
10920 (type (org-element-property :type link))
10921 (path (org-link-unescape (org-element-property :path link))))
10922 ;; Switch back to REFERENCE-BUFFER needed when called in
10923 ;; a temporary buffer through `org-open-link-from-string'.
10924 (with-current-buffer (or reference-buffer (current-buffer))
10925 (cond
10926 ((equal type "file")
10927 (if (string-match "[*?{]" (file-name-nondirectory path))
10928 (dired path)
10929 ;; Look into `org-link-parameters' in order to find
10930 ;; a DEDICATED-FUNCTION to open file. The function
10931 ;; will be applied on raw link instead of parsed
10932 ;; link due to the limitation in `org-add-link-type'
10933 ;; ("open" function called with a single argument).
10934 ;; If no such function is found, fallback to
10935 ;; `org-open-file'.
10936 (let* ((option (org-element-property :search-option link))
10937 (app (org-element-property :application link))
10938 (dedicated-function
10939 (org-link-get-parameter
10940 (if app (concat type "+" app) type)
10941 :follow)))
10942 (if dedicated-function
10943 (funcall dedicated-function
10944 (concat path
10945 (and option (concat "::" option))))
10946 (apply #'org-open-file
10947 path
10948 (cond (arg)
10949 ((equal app "emacs") 'emacs)
10950 ((equal app "sys") 'system))
10951 (cond ((not option) nil)
10952 ((string-match-p "\\`[0-9]+\\'" option)
10953 (list (string-to-number option)))
10954 (t (list nil
10955 (org-link-unescape option)))))))))
10956 ((functionp (org-link-get-parameter type :follow))
10957 (funcall (org-link-get-parameter type :follow) path))
10958 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10959 (unless (run-hook-with-args-until-success
10960 'org-open-link-functions path)
10961 (if (not arg) (org-mark-ring-push)
10962 (switch-to-buffer-other-window
10963 (org-get-buffer-for-internal-link (current-buffer))))
10964 (let ((destination
10965 (org-with-wide-buffer
10966 (if (equal type "radio")
10967 (org-search-radio-target
10968 (org-element-property :path link))
10969 (org-link-search
10970 (if (member type '("custom-id" "coderef"))
10971 (org-element-property :raw-link link)
10972 path)
10973 ;; Prevent fuzzy links from matching
10974 ;; themselves.
10975 (and (equal type "fuzzy")
10976 (+ 2 (org-element-property :begin link)))))
10977 (point))))
10978 (unless (and (<= (point-min) destination)
10979 (>= (point-max) destination))
10980 (widen))
10981 (goto-char destination))))
10982 (t (browse-url-at-point))))))
10983 ;; On a footnote reference or at a footnote definition's label.
10984 ((or (eq type 'footnote-reference)
10985 (and (eq type 'footnote-definition)
10986 (save-excursion
10987 ;; Do not validate action when point is on the
10988 ;; spaces right after the footnote label, in
10989 ;; order to be on par with behaviour on links.
10990 (skip-chars-forward " \t")
10991 (let ((begin
10992 (org-element-property :contents-begin context)))
10993 (if begin (< (point) begin)
10994 (= (org-element-property :post-affiliated context)
10995 (line-beginning-position)))))))
10996 (org-footnote-action))
10997 (t (user-error "No link found")))))
10998 (run-hook-with-args 'org-follow-link-hook)))
11000 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
11001 "Offer links in the current entry and return the selected link.
11002 If there is only one link, return it.
11003 If NTH is an integer, return the NTH link found.
11004 If ZERO is a string, check also this string for a link, and if
11005 there is one, return it."
11006 (with-current-buffer buffer
11007 (org-with-wide-buffer
11008 (goto-char marker)
11009 (let ((cnt ?0)
11010 have-zero end links link c)
11011 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
11012 (push (match-string 0 zero) links)
11013 (setq cnt (1- cnt) have-zero t))
11014 (save-excursion
11015 (org-back-to-heading t)
11016 (setq end (save-excursion (outline-next-heading) (point)))
11017 (while (re-search-forward org-any-link-re end t)
11018 (push (match-string 0) links))
11019 (setq links (org-uniquify (reverse links))))
11020 (cond
11021 ((null links)
11022 (message "No links"))
11023 ((equal (length links) 1)
11024 (setq link (car links)))
11025 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
11026 (setq link (nth (if have-zero nth (1- nth)) links)))
11027 (t ; we have to select a link
11028 (save-excursion
11029 (save-window-excursion
11030 (delete-other-windows)
11031 (with-output-to-temp-buffer "*Select Link*"
11032 (dolist (l links)
11033 (cond
11034 ((not (string-match org-bracket-link-regexp l))
11035 (princ (format "[%c] %s\n" (cl-incf cnt)
11036 (org-unbracket-string "<" ">" l))))
11037 ((match-end 3)
11038 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
11039 (match-string 3 l) (match-string 1 l))))
11040 (t (princ (format "[%c] %s\n" (cl-incf cnt)
11041 (match-string 1 l)))))))
11042 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
11043 (message "Select link to open, RET to open all:")
11044 (setq c (read-char-exclusive))
11045 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
11046 (when (equal c ?q) (user-error "Abort"))
11047 (if (equal c ?\C-m)
11048 (setq link links)
11049 (setq nth (- c ?0))
11050 (when have-zero (setq nth (1+ nth)))
11051 (unless (and (integerp nth) (>= (length links) nth))
11052 (user-error "Invalid link selection"))
11053 (setq link (nth (1- nth) links)))))
11054 (cons link end)))))
11056 ;; TODO: These functions are deprecated since `org-open-at-point'
11057 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
11058 (defun org-open-file-with-system (path)
11059 "Open file at PATH using the system way of opening it."
11060 (org-open-file path 'system))
11061 (defun org-open-file-with-emacs (path)
11062 "Open file at PATH in Emacs."
11063 (org-open-file path 'emacs))
11066 ;;; File search
11068 (defvar org-create-file-search-functions nil
11069 "List of functions to construct the right search string for a file link.
11070 These functions are called in turn with point at the location to
11071 which the link should point.
11073 A function in the hook should first test if it would like to
11074 handle this file type, for example by checking the `major-mode'
11075 or the file extension. If it decides not to handle this file, it
11076 should just return nil to give other functions a chance. If it
11077 does handle the file, it must return the search string to be used
11078 when following the link. The search string will be part of the
11079 file link, given after a double colon, and `org-open-at-point'
11080 will automatically search for it. If special measures must be
11081 taken to make the search successful, another function should be
11082 added to the companion hook `org-execute-file-search-functions',
11083 which see.
11085 A function in this hook may also use `setq' to set the variable
11086 `description' to provide a suggestion for the descriptive text to
11087 be used for this link when it gets inserted into an Org buffer
11088 with \\[org-insert-link].")
11090 (defvar org-execute-file-search-functions nil
11091 "List of functions to execute a file search triggered by a link.
11093 Functions added to this hook must accept a single argument, the
11094 search string that was part of the file link, the part after the
11095 double colon. The function must first check if it would like to
11096 handle this search, for example by checking the `major-mode' or
11097 the file extension. If it decides not to handle this search, it
11098 should just return nil to give other functions a chance. If it
11099 does handle the search, it must return a non-nil value to keep
11100 other functions from trying.
11102 Each function can access the current prefix argument through the
11103 variable `current-prefix-arg'. Note that a single prefix is used
11104 to force opening a link in Emacs, so it may be good to only use a
11105 numeric or double prefix to guide the search function.
11107 In case this is needed, a function in this hook can also restore
11108 the window configuration before `org-open-at-point' was called using:
11110 (set-window-configuration org-window-config-before-follow-link)")
11112 (defun org-search-radio-target (target)
11113 "Search a radio target matching TARGET in current buffer.
11114 White spaces are not significant."
11115 (let ((re (format "<<<%s>>>"
11116 (mapconcat #'regexp-quote
11117 (org-split-string target "[ \t\n]+")
11118 "[ \t]+\\(?:\n[ \t]*\\)?")))
11119 (origin (point)))
11120 (goto-char (point-min))
11121 (catch :radio-match
11122 (while (re-search-forward re nil t)
11123 (backward-char)
11124 (let ((object (org-element-context)))
11125 (when (eq (org-element-type object) 'radio-target)
11126 (goto-char (org-element-property :begin object))
11127 (org-show-context 'link-search)
11128 (throw :radio-match nil))))
11129 (goto-char origin)
11130 (user-error "No match for radio target: %s" target))))
11132 (defun org-link-search (s &optional avoid-pos stealth)
11133 "Search for a search string S.
11135 If S starts with \"#\", it triggers a custom ID search.
11137 If S is enclosed within parenthesis, it initiates a coderef
11138 search.
11140 If S is surrounded by forward slashes, it is interpreted as
11141 a regular expression. In Org mode files, this will create an
11142 `org-occur' sparse tree. In ordinary files, `occur' will be used
11143 to list matches. If the current buffer is in `dired-mode', grep
11144 will be used to search in all files.
11146 When AVOID-POS is given, ignore matches near that position.
11148 When optional argument STEALTH is non-nil, do not modify
11149 visibility around point, thus ignoring `org-show-context-detail'
11150 variable.
11152 Search is case-insensitive and ignores white spaces. Return type
11153 of matched result, which is either `dedicated' or `fuzzy'."
11154 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11155 (let* ((case-fold-search t)
11156 (origin (point))
11157 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11158 (words (org-split-string s "[ \t\n]+"))
11159 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11160 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11161 type)
11162 (cond
11163 ;; Check if there are any special search functions.
11164 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11165 ((eq (string-to-char s) ?#)
11166 ;; Look for a custom ID S if S starts with "#".
11167 (let* ((id (substring normalized 1))
11168 (match (org-find-property "CUSTOM_ID" id)))
11169 (if match (progn (goto-char match) (setf type 'dedicated))
11170 (error "No match for custom ID: %s" id))))
11171 ((string-match "\\`(\\(.*\\))\\'" normalized)
11172 ;; Look for coderef targets if S is enclosed within parenthesis.
11173 (let ((coderef (match-string-no-properties 1 normalized))
11174 (re (substring s-single-re 1 -1)))
11175 (goto-char (point-min))
11176 (catch :coderef-match
11177 (while (re-search-forward re nil t)
11178 (let ((element (org-element-at-point)))
11179 (when (and (memq (org-element-type element)
11180 '(example-block src-block))
11181 ;; Build proper regexp according to current
11182 ;; block's label format.
11183 (let ((label-fmt
11184 (regexp-quote
11185 (or (org-element-property :label-fmt element)
11186 org-coderef-label-format))))
11187 (save-excursion
11188 (beginning-of-line)
11189 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11190 (format label-fmt coderef))))))
11191 (setq type 'dedicated)
11192 (goto-char (match-beginning 1))
11193 (throw :coderef-match nil))))
11194 (goto-char origin)
11195 (error "No match for coderef: %s" coderef))))
11196 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11197 ;; Look for a regular expression.
11198 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11199 (match-string 1 s)))
11200 ;; Fuzzy links.
11202 (let ((starred (eq (string-to-char normalized) ?*)))
11203 (cond
11204 ;; Look for targets, only if not in a headline search.
11205 ((and (not starred)
11206 (let ((target (format "<<%s>>" s-multi-re)))
11207 (catch :target-match
11208 (goto-char (point-min))
11209 (while (re-search-forward target nil t)
11210 (backward-char)
11211 (let ((context (org-element-context)))
11212 (when (eq (org-element-type context) 'target)
11213 (setq type 'dedicated)
11214 (goto-char (org-element-property :begin context))
11215 (throw :target-match t))))
11216 nil))))
11217 ;; Look for elements named after S, only if not in a headline
11218 ;; search.
11219 ((and (not starred)
11220 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11221 (catch :name-match
11222 (goto-char (point-min))
11223 (while (re-search-forward name nil t)
11224 (let ((element (org-element-at-point)))
11225 (when (equal (org-split-string
11226 (org-element-property :name element)
11227 "[ \t]+")
11228 words)
11229 (setq type 'dedicated)
11230 (beginning-of-line)
11231 (throw :name-match t))))
11232 nil))))
11233 ;; Regular text search. Prefer headlines in Org mode
11234 ;; buffers.
11235 ((and (derived-mode-p 'org-mode)
11236 (let* ((wspace "[ \t]")
11237 (wspaceopt (concat wspace "*"))
11238 (cookie (concat "\\(?:"
11239 wspaceopt
11240 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11241 wspaceopt
11242 "\\)"))
11243 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11244 (title
11245 (format "\\(?:%s[ \t]+\\)?%s?%s%s?"
11246 org-comment-string
11248 (let ((re (mapconcat #'regexp-quote words sep)))
11249 (if starred (substring re 1) re))
11250 sep))
11251 (exact-title (format "\\`%s\\'" title))
11252 (re (concat org-outline-regexp-bol "+.*" title)))
11253 (goto-char (point-min))
11254 (catch :found
11255 (while (re-search-forward re nil t)
11256 (when (string-match-p exact-title (org-get-heading t t))
11257 (throw :found t)))
11258 nil)))
11259 (beginning-of-line)
11260 (setq type 'dedicated))
11261 ;; Offer to create non-existent headline depending on
11262 ;; `org-link-search-must-match-exact-headline'.
11263 ((and (derived-mode-p 'org-mode)
11264 (not org-link-search-inhibit-query)
11265 (eq org-link-search-must-match-exact-headline 'query-to-create)
11266 (yes-or-no-p "No match - create this as a new heading? "))
11267 (goto-char (point-max))
11268 (unless (bolp) (newline))
11269 (org-insert-heading nil t t)
11270 (insert s "\n")
11271 (beginning-of-line 0))
11272 ;; Only headlines are looked after. No need to process
11273 ;; further: throw an error.
11274 ((and (derived-mode-p 'org-mode)
11275 (or starred org-link-search-must-match-exact-headline))
11276 (goto-char origin)
11277 (error "No match for fuzzy expression: %s" normalized))
11278 ;; Regular text search.
11279 ((catch :fuzzy-match
11280 (goto-char (point-min))
11281 (while (re-search-forward s-multi-re nil t)
11282 ;; Skip match if it contains AVOID-POS or it is included
11283 ;; in a link with a description but outside the
11284 ;; description.
11285 (unless (or (and avoid-pos
11286 (<= (match-beginning 0) avoid-pos)
11287 (> (match-end 0) avoid-pos))
11288 (and (save-match-data
11289 (org-in-regexp org-bracket-link-regexp))
11290 (match-beginning 3)
11291 (or (> (match-beginning 3) (point))
11292 (<= (match-end 3) (point)))
11293 (org-element-lineage
11294 (save-match-data (org-element-context))
11295 '(link) t)))
11296 (goto-char (match-beginning 0))
11297 (setq type 'fuzzy)
11298 (throw :fuzzy-match t)))
11299 nil))
11300 ;; All failed. Throw an error.
11301 (t (goto-char origin)
11302 (error "No match for fuzzy expression: %s" normalized))))))
11303 ;; Disclose surroundings of match, if appropriate.
11304 (when (and (derived-mode-p 'org-mode) (not stealth))
11305 (org-show-context 'link-search))
11306 type))
11308 (defun org-get-buffer-for-internal-link (buffer)
11309 "Return a buffer to be used for displaying the link target of internal links."
11310 (cond
11311 ((not org-display-internal-link-with-indirect-buffer)
11312 buffer)
11313 ((string-suffix-p "(Clone)" (buffer-name buffer))
11314 (message "Buffer is already a clone, not making another one")
11315 ;; we also do not modify visibility in this case
11316 buffer)
11317 (t ; make a new indirect buffer for displaying the link
11318 (let* ((bn (buffer-name buffer))
11319 (ibn (concat bn "(Clone)"))
11320 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11321 (with-current-buffer ib (org-overview))
11322 ib))))
11324 (defun org-do-occur (regexp &optional cleanup)
11325 "Call the Emacs command `occur'.
11326 If CLEANUP is non-nil, remove the printout of the regular expression
11327 in the *Occur* buffer. This is useful if the regex is long and not useful
11328 to read."
11329 (occur regexp)
11330 (when cleanup
11331 (let ((cwin (selected-window)) win beg end)
11332 (when (setq win (get-buffer-window "*Occur*"))
11333 (select-window win))
11334 (goto-char (point-min))
11335 (when (re-search-forward "match[a-z]+" nil t)
11336 (setq beg (match-end 0))
11337 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11338 (setq end (1- (match-beginning 0)))))
11339 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11340 (goto-char (point-min))
11341 (select-window cwin))))
11343 ;;; The mark ring for links jumps
11345 (defvar org-mark-ring nil
11346 "Mark ring for positions before jumps in Org mode.")
11347 (defvar org-mark-ring-last-goto nil
11348 "Last position in the mark ring used to go back.")
11349 ;; Fill and close the ring
11350 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11351 (dotimes (_ org-mark-ring-length)
11352 (push (make-marker) org-mark-ring))
11353 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11354 org-mark-ring)
11356 (defun org-mark-ring-push (&optional pos buffer)
11357 "Put the current position or POS into the mark ring and rotate it."
11358 (interactive)
11359 (setq pos (or pos (point)))
11360 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11361 (move-marker (car org-mark-ring)
11362 (or pos (point))
11363 (or buffer (current-buffer)))
11364 (message "%s"
11365 (substitute-command-keys
11366 "Position saved to mark ring, go back with \
11367 `\\[org-mark-ring-goto]'.")))
11369 (defun org-mark-ring-goto (&optional n)
11370 "Jump to the previous position in the mark ring.
11371 With prefix arg N, jump back that many stored positions. When
11372 called several times in succession, walk through the entire ring.
11373 Org mode commands jumping to a different position in the current file,
11374 or to another Org file, automatically push the old position onto the ring."
11375 (interactive "p")
11376 (let (p m)
11377 (if (eq last-command this-command)
11378 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11379 (setq p org-mark-ring))
11380 (setq org-mark-ring-last-goto p)
11381 (setq m (car p))
11382 (pop-to-buffer-same-window (marker-buffer m))
11383 (goto-char m)
11384 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11386 (defun org-add-angle-brackets (s)
11387 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11388 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11391 ;;; Following specific links
11393 (defvar org-agenda-buffer-tmp-name)
11394 (defvar org-agenda-start-on-weekday)
11395 (defun org-follow-timestamp-link ()
11396 "Open an agenda view for the time-stamp date/range at point."
11397 (cond
11398 ((org-at-date-range-p t)
11399 (let ((org-agenda-start-on-weekday)
11400 (t1 (match-string 1))
11401 (t2 (match-string 2)) tt1 tt2)
11402 (setq tt1 (time-to-days (org-time-string-to-time t1))
11403 tt2 (time-to-days (org-time-string-to-time t2)))
11404 (let ((org-agenda-buffer-tmp-name
11405 (format "*Org Agenda(a:%s)"
11406 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11407 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11408 ((org-at-timestamp-p t)
11409 (let ((org-agenda-buffer-tmp-name
11410 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11411 (org-agenda-list nil (time-to-days (org-time-string-to-time
11412 (substring (match-string 1) 0 10)))
11413 1)))
11414 (t (error "This should not happen"))))
11417 ;;; Following file links
11418 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11419 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11420 (declare-function mailcap-mime-info
11421 "mailcap" (string &optional request no-decode))
11422 (defvar org-wait nil)
11423 (defun org-open-file (path &optional in-emacs line search)
11424 "Open the file at PATH.
11425 First, this expands any special file name abbreviations. Then the
11426 configuration variable `org-file-apps' is checked if it contains an
11427 entry for this file type, and if yes, the corresponding command is launched.
11429 If no application is found, Emacs simply visits the file.
11431 With optional prefix argument IN-EMACS, Emacs will visit the file.
11432 With a double \\[universal-argument] \\[universal-argument] \
11433 prefix arg, Org tries to avoid opening in Emacs
11434 and to use an external application to visit the file.
11436 Optional LINE specifies a line to go to, optional SEARCH a string
11437 to search for. If LINE or SEARCH is given, the file will be
11438 opened in Emacs, unless an entry from org-file-apps that makes
11439 use of groups in a regexp matches.
11441 If you want to change the way frames are used when following a
11442 link, please customize `org-link-frame-setup'.
11444 If the file does not exist, an error is thrown."
11445 (let* ((file (if (equal path "")
11446 buffer-file-name
11447 (substitute-in-file-name (expand-file-name path))))
11448 (file-apps (append org-file-apps (org-default-apps)))
11449 (apps (cl-remove-if
11450 'org-file-apps-entry-match-against-dlink-p file-apps))
11451 (apps-dlink (cl-remove-if-not
11452 'org-file-apps-entry-match-against-dlink-p file-apps))
11453 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11454 (dirp (unless remp (file-directory-p file)))
11455 (file (if (and dirp org-open-directory-means-index-dot-org)
11456 (concat (file-name-as-directory file) "index.org")
11457 file))
11458 (a-m-a-p (assq 'auto-mode apps))
11459 (dfile (downcase file))
11460 ;; Reconstruct the original link from the PATH, LINE and
11461 ;; SEARCH args.
11462 (link (cond (line (concat file "::" (number-to-string line)))
11463 (search (concat file "::" search))
11464 (t file)))
11465 (dlink (downcase link))
11466 (old-buffer (current-buffer))
11467 (old-pos (point))
11468 (old-mode major-mode)
11469 (ext
11470 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11471 (match-string 1 dfile)))
11472 cmd link-match-data)
11473 (cond
11474 ((member in-emacs '((16) system))
11475 (setq cmd (cdr (assq 'system apps))))
11476 (in-emacs (setq cmd 'emacs))
11478 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11479 (and dirp (cdr (assq 'directory apps)))
11480 ;; First, try matching against apps-dlink if we
11481 ;; get a match here, store the match data for
11482 ;; later.
11483 (let ((match (assoc-default dlink apps-dlink
11484 'string-match)))
11485 (if match
11486 (progn (setq link-match-data (match-data))
11487 match)
11488 (progn (setq in-emacs (or in-emacs line search))
11489 nil))) ; if we have no match in apps-dlink,
11490 ; always open the file in emacs if line or search
11491 ; is given (for backwards compatibility)
11492 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11493 'string-match)
11494 (cdr (assoc ext apps))
11495 (cdr (assq t apps))))))
11496 (when (eq cmd 'system)
11497 (setq cmd (cdr (assq 'system apps))))
11498 (when (eq cmd 'default)
11499 (setq cmd (cdr (assoc t apps))))
11500 (when (eq cmd 'mailcap)
11501 (require 'mailcap)
11502 (mailcap-parse-mailcaps)
11503 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11504 (command (mailcap-mime-info mime-type)))
11505 (if (stringp command)
11506 (setq cmd command)
11507 (setq cmd 'emacs))))
11508 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11509 (not (file-exists-p file))
11510 (not org-open-non-existing-files))
11511 (user-error "No such file: %s" file))
11512 (cond
11513 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11514 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11515 (while (string-match "['\"]%s['\"]" cmd)
11516 (setq cmd (replace-match "%s" t t cmd)))
11517 (setq cmd (replace-regexp-in-string
11518 "%s"
11519 (shell-quote-argument (convert-standard-filename file))
11521 nil t))
11523 ;; Replace "%1", "%2" etc. in command with group matches from regex
11524 (save-match-data
11525 (let ((match-index 1)
11526 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11527 (set-match-data link-match-data)
11528 (while (<= match-index number-of-groups)
11529 (let ((regex (concat "%" (number-to-string match-index)))
11530 (replace-with (match-string match-index dlink)))
11531 (while (string-match regex cmd)
11532 (setq cmd (replace-match replace-with t t cmd))))
11533 (setq match-index (+ match-index 1)))))
11535 (save-window-excursion
11536 (message "Running %s...done" cmd)
11537 (start-process-shell-command cmd nil cmd)
11538 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11539 ((or (stringp cmd)
11540 (eq cmd 'emacs))
11541 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11542 (widen)
11543 (cond (line (org-goto-line line)
11544 (when (derived-mode-p 'org-mode) (org-reveal)))
11545 (search (org-link-search search))))
11546 ((functionp cmd)
11547 (save-match-data
11548 (set-match-data link-match-data)
11549 (condition-case nil
11550 (funcall cmd file link)
11551 ;; FIXME: Remove this check when most default installations
11552 ;; of Emacs have at least Org 9.0.
11553 ((debug wrong-number-of-arguments wrong-type-argument
11554 invalid-function)
11555 (user-error "Please see Org News for version 9.0 about \
11556 `org-file-apps'--Lisp error: %S" cmd)))))
11557 ((consp cmd)
11558 ;; FIXME: Remove this check when most default installations of
11559 ;; Emacs have at least Org 9.0.
11560 ;; Heads-up instead of silently fall back to
11561 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11562 ;; with sexp instead of a function for `cmd'.
11563 (user-error "Please see Org News for version 9.0 about \
11564 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11565 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11566 (and (derived-mode-p 'org-mode)
11567 (eq old-mode 'org-mode)
11568 (or (not (eq old-buffer (current-buffer)))
11569 (not (eq old-pos (point))))
11570 (org-mark-ring-push old-pos old-buffer))))
11572 (defun org-file-apps-entry-match-against-dlink-p (entry)
11573 "This function returns non-nil if `entry' uses a regular
11574 expression which should be matched against the whole link by
11575 org-open-file.
11577 It assumes that is the case when the entry uses a regular
11578 expression which has at least one grouping construct and the
11579 action is either a lisp form or a command string containing
11580 `%1', i.e. using at least one subexpression match as a
11581 parameter."
11582 (let ((selector (car entry))
11583 (action (cdr entry)))
11584 (if (stringp selector)
11585 (and (> (regexp-opt-depth selector) 0)
11586 (or (and (stringp action)
11587 (string-match "%[0-9]" action))
11588 (consp action)))
11589 nil)))
11591 (defun org-default-apps ()
11592 "Return the default applications for this operating system."
11593 (cond
11594 ((eq system-type 'darwin)
11595 org-file-apps-defaults-macosx)
11596 ((eq system-type 'windows-nt)
11597 org-file-apps-defaults-windowsnt)
11598 (t org-file-apps-defaults-gnu)))
11600 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11601 "Convert extensions to regular expressions in the cars of LIST.
11602 Also, weed out any non-string entries, because the return value is used
11603 only for regexp matching.
11604 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11605 point to the symbol `emacs', indicating that the file should
11606 be opened in Emacs."
11607 (append
11608 (delq nil
11609 (mapcar (lambda (x)
11610 (unless (not (stringp (car x)))
11611 (if (string-match "\\W" (car x))
11613 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11614 list))
11615 (when add-auto-mode
11616 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11618 (defvar ange-ftp-name-format)
11619 (defun org-file-remote-p (file)
11620 "Test whether FILE specifies a location on a remote system.
11621 Return non-nil if the location is indeed remote.
11623 For example, the filename \"/user@host:/foo\" specifies a location
11624 on the system \"/user@host:\"."
11625 (cond ((fboundp 'file-remote-p)
11626 (file-remote-p file))
11627 ((fboundp 'tramp-handle-file-remote-p)
11628 (tramp-handle-file-remote-p file))
11629 ((and (boundp 'ange-ftp-name-format)
11630 (string-match (car ange-ftp-name-format) file))
11631 t)))
11634 ;;;; Refiling
11636 (defun org-get-org-file ()
11637 "Read a filename, with default directory `org-directory'."
11638 (let ((default (or org-default-notes-file remember-data-file)))
11639 (read-file-name (format "File name [%s]: " default)
11640 (file-name-as-directory org-directory)
11641 default)))
11643 (defun org-notes-order-reversed-p ()
11644 "Check if the current file should receive notes in reversed order."
11645 (cond
11646 ((not org-reverse-note-order) nil)
11647 ((eq t org-reverse-note-order) t)
11648 ((not (listp org-reverse-note-order)) nil)
11649 (t (catch 'exit
11650 (dolist (entry org-reverse-note-order)
11651 (when (string-match (car entry) buffer-file-name)
11652 (throw 'exit (cdr entry))))))))
11654 (defvar org-refile-target-table nil
11655 "The list of refile targets, created by `org-refile'.")
11657 (defvar org-agenda-new-buffers nil
11658 "Buffers created to visit agenda files.")
11660 (defvar org-refile-cache nil
11661 "Cache for refile targets.")
11663 (defvar org-refile-markers nil
11664 "All the markers used for caching refile locations.")
11666 (defun org-refile-marker (pos)
11667 "Get a new refile marker, but only if caching is in use."
11668 (if (not org-refile-use-cache)
11670 (let ((m (make-marker)))
11671 (move-marker m pos)
11672 (push m org-refile-markers)
11673 m)))
11675 (defun org-refile-cache-clear ()
11676 "Clear the refile cache and disable all the markers."
11677 (dolist (m org-refile-markers) (move-marker m nil))
11678 (setq org-refile-markers nil)
11679 (setq org-refile-cache nil)
11680 (message "Refile cache has been cleared"))
11682 (defun org-refile-cache-check-set (set)
11683 "Check if all the markers in the cache still have live buffers."
11684 (let (marker)
11685 (catch 'exit
11686 (while (and set (setq marker (nth 3 (pop set))))
11687 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11688 (when (and marker (null (marker-buffer marker)))
11689 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11690 (sit-for 3)
11691 (throw 'exit nil)))
11692 t)))
11694 (defun org-refile-cache-put (set &rest identifiers)
11695 "Push the refile targets SET into the cache, under IDENTIFIERS."
11696 (let* ((key (sha1 (prin1-to-string identifiers)))
11697 (entry (assoc key org-refile-cache)))
11698 (if entry
11699 (setcdr entry set)
11700 (push (cons key set) org-refile-cache))))
11702 (defun org-refile-cache-get (&rest identifiers)
11703 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11704 (cond
11705 ((not org-refile-cache) nil)
11706 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11708 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11709 org-refile-cache))))
11710 (and set (org-refile-cache-check-set set) set)))))
11712 (defvar org-outline-path-cache nil
11713 "Alist between buffer positions and outline paths.
11714 It value is an alist (POSITION . PATH) where POSITION is the
11715 buffer position at the beginning of an entry and PATH is a list
11716 of strings describing the outline path for that entry, in reverse
11717 order.")
11719 (defun org-refile-get-targets (&optional default-buffer)
11720 "Produce a table with refile targets."
11721 (let ((case-fold-search nil)
11722 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11723 (entries (or org-refile-targets '((nil . (:level . 1)))))
11724 targets tgs files desc descre)
11725 (message "Getting targets...")
11726 (with-current-buffer (or default-buffer (current-buffer))
11727 (dolist (entry entries)
11728 (setq files (car entry) desc (cdr entry))
11729 (cond
11730 ((null files) (setq files (list (current-buffer))))
11731 ((eq files 'org-agenda-files)
11732 (setq files (org-agenda-files 'unrestricted)))
11733 ((and (symbolp files) (fboundp files))
11734 (setq files (funcall files)))
11735 ((and (symbolp files) (boundp files))
11736 (setq files (symbol-value files))))
11737 (when (stringp files) (setq files (list files)))
11738 (cond
11739 ((eq (car desc) :tag)
11740 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11741 ((eq (car desc) :todo)
11742 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11743 ((eq (car desc) :regexp)
11744 (setq descre (cdr desc)))
11745 ((eq (car desc) :level)
11746 (setq descre (concat "^\\*\\{" (number-to-string
11747 (if org-odd-levels-only
11748 (1- (* 2 (cdr desc)))
11749 (cdr desc)))
11750 "\\}[ \t]")))
11751 ((eq (car desc) :maxlevel)
11752 (setq descre (concat "^\\*\\{1," (number-to-string
11753 (if org-odd-levels-only
11754 (1- (* 2 (cdr desc)))
11755 (cdr desc)))
11756 "\\}[ \t]")))
11757 (t (error "Bad refiling target description %s" desc)))
11758 (dolist (f files)
11759 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11761 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11762 (progn
11763 (when (bufferp f)
11764 (setq f (buffer-file-name (buffer-base-buffer f))))
11765 (setq f (and f (expand-file-name f)))
11766 (when (eq org-refile-use-outline-path 'file)
11767 (push (list (file-name-nondirectory f) f nil nil) tgs))
11768 (org-with-wide-buffer
11769 (goto-char (point-min))
11770 (setq org-outline-path-cache nil)
11771 (while (re-search-forward descre nil t)
11772 (beginning-of-line)
11773 (let ((case-fold-search nil))
11774 (looking-at org-complex-heading-regexp))
11775 (let ((begin (point))
11776 (heading (match-string-no-properties 4)))
11777 (unless (or (and
11778 org-refile-target-verify-function
11779 (not
11780 (funcall org-refile-target-verify-function)))
11781 (not heading))
11782 (let ((re (format org-complex-heading-regexp-format
11783 (regexp-quote heading)))
11784 (target
11785 (if (not org-refile-use-outline-path) heading
11786 (mapconcat
11787 #'org-protect-slash
11788 (append
11789 (pcase org-refile-use-outline-path
11790 (`file (list (file-name-nondirectory
11791 (buffer-file-name
11792 (buffer-base-buffer)))))
11793 (`full-file-path
11794 (list (buffer-file-name
11795 (buffer-base-buffer))))
11796 (_ nil))
11797 (org-get-outline-path t t))
11798 "/"))))
11799 (push (list target f re (org-refile-marker (point)))
11800 tgs)))
11801 (when (= (point) begin)
11802 ;; Verification function has not moved point.
11803 (end-of-line)))))))
11804 (when org-refile-use-cache
11805 (org-refile-cache-put tgs (buffer-file-name) descre))
11806 (setq targets (append tgs targets))))))
11807 (message "Getting targets...done")
11808 (nreverse targets)))
11810 (defun org-protect-slash (s)
11811 (replace-regexp-in-string "/" "\\/" s nil t))
11813 (defun org--get-outline-path-1 (&optional use-cache)
11814 "Return outline path to current headline.
11816 Outline path is a list of strings, in reverse order. When
11817 optional argument USE-CACHE is non-nil, make use of a cache. See
11818 `org-get-outline-path' for details.
11820 Assume buffer is widened and point is on a headline."
11821 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11822 (let ((p (point))
11823 (heading (let ((case-fold-search nil))
11824 (looking-at org-complex-heading-regexp)
11825 (if (not (match-end 4)) ""
11826 ;; Remove statistics cookies.
11827 (org-trim
11828 (org-link-display-format
11829 (replace-regexp-in-string
11830 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11831 (match-string-no-properties 4))))))))
11832 (if (org-up-heading-safe)
11833 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11834 (when use-cache
11835 (push (cons p path) org-outline-path-cache))
11836 path)
11837 ;; This is a new root node. Since we assume we are moving
11838 ;; forward, we can drop previous cache so as to limit number
11839 ;; of associations there.
11840 (let ((path (list heading)))
11841 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11842 path)))))
11844 (defun org-get-outline-path (&optional with-self use-cache)
11845 "Return the outline path to the current entry.
11847 An outline path is a list of ancestors for current headline, as
11848 a list of strings. Statistics cookies are removed and links are
11849 replaced with their description, if any, or their path otherwise.
11851 When optional argument WITH-SELF is non-nil, the path also
11852 includes the current headline.
11854 When optional argument USE-CACHE is non-nil, cache outline paths
11855 between calls to this function so as to avoid backtracking. This
11856 argument is useful when planning to find more than one outline
11857 path in the same document. In that case, there are two
11858 conditions to satisfy:
11859 - `org-outline-path-cache' is set to nil before starting the
11860 process;
11861 - outline paths are computed by increasing buffer positions."
11862 (org-with-wide-buffer
11863 (and (or (and with-self (org-back-to-heading t))
11864 (org-up-heading-safe))
11865 (reverse (org--get-outline-path-1 use-cache)))))
11867 (defun org-format-outline-path (path &optional width prefix separator)
11868 "Format the outline path PATH for display.
11869 WIDTH is the maximum number of characters that is available.
11870 PREFIX is a prefix to be included in the returned string,
11871 such as the file name.
11872 SEPARATOR is inserted between the different parts of the path,
11873 the default is \"/\"."
11874 (setq width (or width 79))
11875 (setq path (delq nil path))
11876 (unless (> width 0)
11877 (user-error "Argument `width' must be positive"))
11878 (setq separator (or separator "/"))
11879 (let* ((org-odd-levels-only nil)
11880 (fpath (concat
11881 prefix (and prefix path separator)
11882 (mapconcat
11883 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11884 (cl-loop for head in path
11885 for n from 0
11886 collect (org-add-props
11887 head nil 'face
11888 (nth (% n org-n-level-faces) org-level-faces)))
11889 separator))))
11890 (when (> (length fpath) width)
11891 (if (< width 7)
11892 ;; It's unlikely that `width' will be this small, but don't
11893 ;; waste characters by adding ".." if it is.
11894 (setq fpath (substring fpath 0 width))
11895 (setf (substring fpath (- width 2)) "..")))
11896 fpath))
11898 (defun org-display-outline-path (&optional file current separator just-return-string)
11899 "Display the current outline path in the echo area.
11901 If FILE is non-nil, prepend the output with the file name.
11902 If CURRENT is non-nil, append the current heading to the output.
11903 SEPARATOR is passed through to `org-format-outline-path'. It separates
11904 the different parts of the path and defaults to \"/\".
11905 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11906 (interactive "P")
11907 (let* (case-fold-search
11908 (bfn (buffer-file-name (buffer-base-buffer)))
11909 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11910 res)
11911 (when current (setq path (append path
11912 (save-excursion
11913 (org-back-to-heading t)
11914 (when (looking-at org-complex-heading-regexp)
11915 (list (match-string 4)))))))
11916 (setq res
11917 (org-format-outline-path
11918 path
11919 (1- (frame-width))
11920 (and file bfn (concat (file-name-nondirectory bfn) separator))
11921 separator))
11922 (if just-return-string
11923 (org-no-properties res)
11924 (org-unlogged-message "%s" res))))
11926 (defvar org-refile-history nil
11927 "History for refiling operations.")
11929 (defvar org-after-refile-insert-hook nil
11930 "Hook run after `org-refile' has inserted its stuff at the new location.
11931 Note that this is still *before* the stuff will be removed from
11932 the *old* location.")
11934 (defvar org-capture-last-stored-marker)
11935 (defvar org-refile-keep nil
11936 "Non-nil means `org-refile' will copy instead of refile.")
11938 (defun org-copy ()
11939 "Like `org-refile', but copy."
11940 (interactive)
11941 (let ((org-refile-keep t))
11942 (funcall 'org-refile nil nil nil "Copy")))
11944 (defun org-refile (&optional arg default-buffer rfloc msg)
11945 "Move the entry or entries at point to another heading.
11947 The list of target headings is compiled using the information in
11948 `org-refile-targets', which see.
11950 At the target location, the entry is filed as a subitem of the
11951 target heading. Depending on `org-reverse-note-order', the new
11952 subitem will either be the first or the last subitem.
11954 If there is an active region, all entries in that region will be
11955 refiled. However, the region must fulfill the requirement that
11956 the first heading sets the top-level of the moved text.
11958 With a `\\[universal-argument]' ARG, the command will only visit the target \
11959 location
11960 and not actually move anything.
11962 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11963 location where the last
11964 refiling operation has put the subtree.
11966 With a numeric prefix argument of `2', refile to the running clock.
11968 With a numeric prefix argument of `3', emulate `org-refile-keep'
11969 being set to t and copy to the target location, don't move it.
11970 Beware that keeping refiled entries may result in duplicated ID
11971 properties.
11973 RFLOC can be a refile location obtained in a different way.
11975 MSG is a string to replace \"Refile\" in the default prompt with
11976 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11978 See also `org-refile-use-outline-path'.
11980 If you are using target caching (see `org-refile-use-cache'), you
11981 have to clear the target cache in order to find new targets.
11982 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11983 prefix argument (`C-u C-u C-u C-c C-w')."
11984 (interactive "P")
11985 (if (member arg '(0 (64)))
11986 (org-refile-cache-clear)
11987 (let* ((actionmsg (cond (msg msg)
11988 ((equal arg 3) "Refile (and keep)")
11989 (t "Refile")))
11990 (regionp (org-region-active-p))
11991 (region-start (and regionp (region-beginning)))
11992 (region-end (and regionp (region-end)))
11993 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11994 pos it nbuf file level reversed)
11995 (setq last-command nil)
11996 (when regionp
11997 (goto-char region-start)
11998 (or (bolp) (goto-char (point-at-bol)))
11999 (setq region-start (point))
12000 (unless (or (org-kill-is-subtree-p
12001 (buffer-substring region-start region-end))
12002 (prog1 org-refile-active-region-within-subtree
12003 (let ((s (point-at-eol)))
12004 (org-toggle-heading)
12005 (setq region-end (+ (- (point-at-eol) s) region-end)))))
12006 (user-error "The region is not a (sequence of) subtree(s)")))
12007 (if (equal arg '(16))
12008 (org-refile-goto-last-stored)
12009 (when (or
12010 (and (equal arg 2)
12011 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
12012 (prog1
12013 (setq it (list (or org-clock-heading "running clock")
12014 (buffer-file-name
12015 (marker-buffer org-clock-hd-marker))
12017 (marker-position org-clock-hd-marker)))
12018 (setq arg nil)))
12019 (setq it
12020 (or rfloc
12021 (let (heading-text)
12022 (save-excursion
12023 (unless (and arg (listp arg))
12024 (org-back-to-heading t)
12025 (setq heading-text
12026 (replace-regexp-in-string
12027 org-bracket-link-regexp
12028 "\\3"
12029 (or (nth 4 (org-heading-components))
12030 ""))))
12031 (org-refile-get-location
12032 (cond ((and arg (listp arg)) "Goto")
12033 (regionp (concat actionmsg " region to"))
12034 (t (concat actionmsg " subtree \""
12035 heading-text "\" to")))
12036 default-buffer
12037 (and (not (equal '(4) arg))
12038 org-refile-allow-creating-parent-nodes)))))))
12039 (setq file (nth 1 it)
12040 pos (nth 3 it))
12041 (when (and (not arg)
12043 (equal (buffer-file-name) file)
12044 (if regionp
12045 (and (>= pos region-start)
12046 (<= pos region-end))
12047 (and (>= pos (point))
12048 (< pos (save-excursion
12049 (org-end-of-subtree t t))))))
12050 (error "Cannot refile to position inside the tree or region"))
12051 (setq nbuf (or (find-buffer-visiting file)
12052 (find-file-noselect file)))
12053 (if (and arg (not (equal arg 3)))
12054 (progn
12055 (pop-to-buffer-same-window nbuf)
12056 (goto-char pos)
12057 (org-show-context 'org-goto))
12058 (if regionp
12059 (progn
12060 (org-kill-new (buffer-substring region-start region-end))
12061 (org-save-markers-in-region region-start region-end))
12062 (org-copy-subtree 1 nil t))
12063 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
12064 (find-file-noselect file)))
12065 (setq reversed (org-notes-order-reversed-p))
12066 (org-with-wide-buffer
12067 (if pos
12068 (progn
12069 (goto-char pos)
12070 (looking-at org-outline-regexp)
12071 (setq level (org-get-valid-level (funcall outline-level) 1))
12072 (goto-char
12073 (if reversed
12074 (or (outline-next-heading) (point-max))
12075 (or (save-excursion (org-get-next-sibling))
12076 (org-end-of-subtree t t)
12077 (point-max)))))
12078 (setq level 1)
12079 (if (not reversed)
12080 (goto-char (point-max))
12081 (goto-char (point-min))
12082 (or (outline-next-heading) (goto-char (point-max)))))
12083 (unless (bolp) (newline))
12084 (org-paste-subtree level nil nil t)
12085 (when org-log-refile
12086 (org-add-log-setup 'refile nil nil org-log-refile)
12087 (unless (eq org-log-refile 'note)
12088 (save-excursion (org-add-log-note))))
12089 (and org-auto-align-tags
12090 (let ((org-loop-over-headlines-in-active-region nil))
12091 (org-set-tags nil t)))
12092 (let ((bookmark-name (plist-get org-bookmark-names-plist
12093 :last-refile)))
12094 (when bookmark-name
12095 (with-demoted-errors
12096 (bookmark-set bookmark-name))))
12097 ;; If we are refiling for capture, make sure that the
12098 ;; last-capture pointers point here
12099 (when (bound-and-true-p org-capture-is-refiling)
12100 (let ((bookmark-name (plist-get org-bookmark-names-plist
12101 :last-capture-marker)))
12102 (when bookmark-name
12103 (with-demoted-errors
12104 (bookmark-set bookmark-name))))
12105 (move-marker org-capture-last-stored-marker (point)))
12106 (when (fboundp 'deactivate-mark) (deactivate-mark))
12107 (run-hooks 'org-after-refile-insert-hook)))
12108 (unless org-refile-keep
12109 (if regionp
12110 (delete-region (point) (+ (point) (- region-end region-start)))
12111 (delete-region
12112 (and (org-back-to-heading t) (point))
12113 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12114 (when (featurep 'org-inlinetask)
12115 (org-inlinetask-remove-END-maybe))
12116 (setq org-markers-to-move nil)
12117 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12119 (defun org-refile-goto-last-stored ()
12120 "Go to the location where the last refile was stored."
12121 (interactive)
12122 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12123 (message "This is the location of the last refile"))
12125 (defun org-refile--get-location (refloc tbl)
12126 "When user refile to REFLOC, find the associated target in TBL.
12127 Also check `org-refile-target-table'."
12128 (car (delq
12130 (mapcar
12131 (lambda (r) (or (assoc r tbl)
12132 (assoc r org-refile-target-table)))
12133 (list (replace-regexp-in-string "/$" "" refloc)
12134 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12136 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12137 "Prompt the user for a refile location, using PROMPT.
12138 PROMPT should not be suffixed with a colon and a space, because
12139 this function appends the default value from
12140 `org-refile-history' automatically, if that is not empty."
12141 (let ((org-refile-targets org-refile-targets)
12142 (org-refile-use-outline-path org-refile-use-outline-path))
12143 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12144 (unless org-refile-target-table
12145 (user-error "No refile targets"))
12146 (let* ((cbuf (current-buffer))
12147 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12148 (cfunc (if (and org-refile-use-outline-path
12149 org-outline-path-complete-in-steps)
12150 #'org-olpath-completing-read
12151 #'completing-read))
12152 (extra (if org-refile-use-outline-path "/" ""))
12153 (cbnex (concat (buffer-name) extra))
12154 (filename (and cfn (expand-file-name cfn)))
12155 (tbl (mapcar
12156 (lambda (x)
12157 (if (and (not (member org-refile-use-outline-path
12158 '(file full-file-path)))
12159 (not (equal filename (nth 1 x))))
12160 (cons (concat (car x) extra " ("
12161 (file-name-nondirectory (nth 1 x)) ")")
12162 (cdr x))
12163 (cons (concat (car x) extra) (cdr x))))
12164 org-refile-target-table))
12165 (completion-ignore-case t)
12166 cdef
12167 (prompt (concat prompt
12168 (or (and (car org-refile-history)
12169 (concat " (default " (car org-refile-history) ")"))
12170 (and (assoc cbnex tbl) (setq cdef cbnex)
12171 (concat " (default " cbnex ")"))) ": "))
12172 pa answ parent-target child parent old-hist)
12173 (setq old-hist org-refile-history)
12174 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12175 nil 'org-refile-history (or cdef (car org-refile-history))))
12176 (if (setq pa (org-refile--get-location answ tbl))
12177 (progn
12178 (org-refile-check-position pa)
12179 (when (or (not org-refile-history)
12180 (not (eq old-hist org-refile-history))
12181 (not (equal (car pa) (car org-refile-history))))
12182 (setq org-refile-history
12183 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12184 org-refile-history
12185 (cdr org-refile-history))))
12186 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12187 (pop org-refile-history)))
12189 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12190 (progn
12191 (setq parent (match-string 1 answ)
12192 child (match-string 2 answ))
12193 (setq parent-target (org-refile--get-location parent tbl))
12194 (when (and parent-target
12195 (or (eq new-nodes t)
12196 (and (eq new-nodes 'confirm)
12197 (y-or-n-p (format "Create new node \"%s\"? "
12198 child)))))
12199 (org-refile-new-child parent-target child)))
12200 (user-error "Invalid target location")))))
12202 (declare-function org-string-nw-p "org-macs" (s))
12203 (defun org-refile-check-position (refile-pointer)
12204 "Check if the refile pointer matches the headline to which it points."
12205 (let* ((file (nth 1 refile-pointer))
12206 (re (nth 2 refile-pointer))
12207 (pos (nth 3 refile-pointer))
12208 buffer)
12209 (if (and (not (markerp pos)) (not file))
12210 (user-error "Please indicate a target file in the refile path")
12211 (when (org-string-nw-p re)
12212 (setq buffer (if (markerp pos)
12213 (marker-buffer pos)
12214 (or (find-buffer-visiting file)
12215 (find-file-noselect file))))
12216 (with-current-buffer buffer
12217 (org-with-wide-buffer
12218 (goto-char pos)
12219 (beginning-of-line 1)
12220 (unless (looking-at-p re)
12221 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12223 (defun org-refile-new-child (parent-target child)
12224 "Use refile target PARENT-TARGET to add new CHILD below it."
12225 (unless parent-target
12226 (error "Cannot find parent for new node"))
12227 (let ((file (nth 1 parent-target))
12228 (pos (nth 3 parent-target))
12229 level)
12230 (with-current-buffer (or (find-buffer-visiting file)
12231 (find-file-noselect file))
12232 (org-with-wide-buffer
12233 (if pos
12234 (goto-char pos)
12235 (goto-char (point-max))
12236 (unless (bolp) (newline)))
12237 (when (looking-at org-outline-regexp)
12238 (setq level (funcall outline-level))
12239 (org-end-of-subtree t t))
12240 (org-back-over-empty-lines)
12241 (insert "\n" (make-string
12242 (if pos (org-get-valid-level level 1) 1) ?*)
12243 " " child "\n")
12244 (beginning-of-line 0)
12245 (list (concat (car parent-target) "/" child) file "" (point))))))
12247 (defun org-olpath-completing-read (prompt collection &rest args)
12248 "Read an outline path like a file name."
12249 (let ((thetable collection))
12250 (apply #'completing-read
12251 prompt
12252 (lambda (string predicate &optional flag)
12253 (cond
12254 ((eq flag nil) (try-completion string thetable))
12255 ((eq flag t)
12256 (let ((l (length string)))
12257 (mapcar (lambda (x)
12258 (let ((r (substring x l))
12259 (f (if (string-match " ([^)]*)$" x)
12260 (match-string 0 x)
12261 "")))
12262 (if (string-match "/" r)
12263 (concat string (substring r 0 (match-end 0)) f)
12264 x)))
12265 (all-completions string thetable predicate))))
12266 ;; Exact match?
12267 ((eq flag 'lambda) (assoc string thetable))))
12268 args)))
12270 ;;;; Dynamic blocks
12272 (defun org-find-dblock (name)
12273 "Find the first dynamic block with name NAME in the buffer.
12274 If not found, stay at current position and return nil."
12275 (let ((case-fold-search t) pos)
12276 (save-excursion
12277 (goto-char (point-min))
12278 (setq pos (and (re-search-forward
12279 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12280 (match-beginning 0))))
12281 (when pos (goto-char pos))
12282 pos))
12284 (defun org-create-dblock (plist)
12285 "Create a dynamic block section, with parameters taken from PLIST.
12286 PLIST must contain a :name entry which is used as the name of the block."
12287 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12288 (end-of-line 1)
12289 (newline))
12290 (let ((col (current-column))
12291 (name (plist-get plist :name)))
12292 (insert "#+BEGIN: " name)
12293 (while plist
12294 (if (eq (car plist) :name)
12295 (setq plist (cddr plist))
12296 (insert " " (prin1-to-string (pop plist)))))
12297 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12298 (beginning-of-line -2)))
12300 (defun org-prepare-dblock ()
12301 "Prepare dynamic block for refresh.
12302 This empties the block, puts the cursor at the insert position and returns
12303 the property list including an extra property :name with the block name."
12304 (unless (looking-at org-dblock-start-re)
12305 (user-error "Not at a dynamic block"))
12306 (let* ((begdel (1+ (match-end 0)))
12307 (name (org-no-properties (match-string 1)))
12308 (params (append (list :name name)
12309 (read (concat "(" (match-string 3) ")")))))
12310 (save-excursion
12311 (beginning-of-line 1)
12312 (skip-chars-forward " \t")
12313 (setq params (plist-put params :indentation-column (current-column))))
12314 (unless (re-search-forward org-dblock-end-re nil t)
12315 (error "Dynamic block not terminated"))
12316 (setq params
12317 (append params
12318 (list :content (buffer-substring
12319 begdel (match-beginning 0)))))
12320 (delete-region begdel (match-beginning 0))
12321 (goto-char begdel)
12322 (open-line 1)
12323 params))
12325 (defun org-map-dblocks (&optional command)
12326 "Apply COMMAND to all dynamic blocks in the current buffer.
12327 If COMMAND is not given, use `org-update-dblock'."
12328 (let ((cmd (or command 'org-update-dblock)))
12329 (save-excursion
12330 (goto-char (point-min))
12331 (while (re-search-forward org-dblock-start-re nil t)
12332 (goto-char (match-beginning 0))
12333 (save-excursion
12334 (condition-case nil
12335 (funcall cmd)
12336 (error (message "Error during update of dynamic block"))))
12337 (unless (re-search-forward org-dblock-end-re nil t)
12338 (error "Dynamic block not terminated"))))))
12340 (defun org-dblock-update (&optional arg)
12341 "User command for updating dynamic blocks.
12342 Update the dynamic block at point. With prefix ARG, update all dynamic
12343 blocks in the buffer."
12344 (interactive "P")
12345 (if arg
12346 (org-update-all-dblocks)
12347 (or (looking-at org-dblock-start-re)
12348 (org-beginning-of-dblock))
12349 (org-update-dblock)))
12351 (defun org-update-dblock ()
12352 "Update the dynamic block at point.
12353 This means to empty the block, parse for parameters and then call
12354 the correct writing function."
12355 (interactive)
12356 (save-excursion
12357 (let* ((win (selected-window))
12358 (pos (point))
12359 (line (org-current-line))
12360 (params (org-prepare-dblock))
12361 (name (plist-get params :name))
12362 (indent (plist-get params :indentation-column))
12363 (cmd (intern (concat "org-dblock-write:" name))))
12364 (message "Updating dynamic block `%s' at line %d..." name line)
12365 (funcall cmd params)
12366 (message "Updating dynamic block `%s' at line %d...done" name line)
12367 (goto-char pos)
12368 (when (and indent (> indent 0))
12369 (setq indent (make-string indent ?\ ))
12370 (save-excursion
12371 (select-window win)
12372 (org-beginning-of-dblock)
12373 (forward-line 1)
12374 (while (not (looking-at org-dblock-end-re))
12375 (insert indent)
12376 (beginning-of-line 2))
12377 (when (looking-at org-dblock-end-re)
12378 (and (looking-at "[ \t]+")
12379 (replace-match ""))
12380 (insert indent)))))))
12382 (defun org-beginning-of-dblock ()
12383 "Find the beginning of the dynamic block at point.
12384 Error if there is no such block at point."
12385 (let ((pos (point))
12386 beg)
12387 (end-of-line 1)
12388 (if (and (re-search-backward org-dblock-start-re nil t)
12389 (setq beg (match-beginning 0))
12390 (re-search-forward org-dblock-end-re nil t)
12391 (> (match-end 0) pos))
12392 (goto-char beg)
12393 (goto-char pos)
12394 (error "Not in a dynamic block"))))
12396 (defun org-update-all-dblocks ()
12397 "Update all dynamic blocks in the buffer.
12398 This function can be used in a hook."
12399 (interactive)
12400 (when (derived-mode-p 'org-mode)
12401 (org-map-dblocks 'org-update-dblock)))
12404 ;;;; Completion
12406 (declare-function org-export-backend-options "ox" (cl-x) t)
12407 (defun org-get-export-keywords ()
12408 "Return a list of all currently understood export keywords.
12409 Export keywords include options, block names, attributes and
12410 keywords relative to each registered export back-end."
12411 (let (keywords)
12412 (dolist (backend
12413 (bound-and-true-p org-export-registered-backends)
12414 (delq nil keywords))
12415 ;; Back-end name (for keywords, like #+LATEX:)
12416 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12417 (dolist (option-entry (org-export-backend-options backend))
12418 ;; Back-end options.
12419 (push (nth 1 option-entry) keywords)))))
12421 (defconst org-options-keywords
12422 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12423 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12424 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12425 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12426 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12428 (defcustom org-structure-template-alist
12429 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12430 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12431 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12432 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12433 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12434 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12435 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12436 ("L" "#+LaTeX: ")
12437 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12438 ("H" "#+HTML: ")
12439 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12440 ("A" "#+ASCII: ")
12441 ("i" "#+INDEX: ?")
12442 ("I" "#+INCLUDE: %file ?"))
12443 "Structure completion elements.
12444 This is a list of abbreviation keys and values. The value gets inserted
12445 if you type `<' followed by the key and then press the completion key,
12446 usually `TAB'. %file will be replaced by a file name after prompting
12447 for the file using completion. The cursor will be placed at the position
12448 of the `?' in the template.
12449 There are two templates for each key, the first uses the original Org syntax,
12450 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12451 the default when the /org-mtags.el/ module has been loaded. See also the
12452 variable `org-mtags-prefer-muse-templates'."
12453 :group 'org-completion
12454 :type '(repeat
12455 (list
12456 (string :tag "Key")
12457 (string :tag "Template")))
12458 :version "25.2"
12459 :package-version '(Org . "8.3"))
12461 (defun org-try-structure-completion ()
12462 "Try to complete a structure template before point.
12463 This looks for strings like \"<e\" on an otherwise empty line and
12464 expands them."
12465 (let ((l (buffer-substring (point-at-bol) (point)))
12467 (when (and (looking-at "[ \t]*$")
12468 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12469 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12470 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12471 (match-beginning 1)) a)
12472 t)))
12474 (defun org-complete-expand-structure-template (start cell)
12475 "Expand a structure template."
12476 (let ((rpl (nth 1 cell))
12477 (ind ""))
12478 (delete-region start (point))
12479 (when (string-match "\\`[ \t]*#\\+" rpl)
12480 (cond
12481 ((bolp))
12482 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12483 (setq ind (buffer-substring (point-at-bol) (point))))
12484 (t (newline))))
12485 (setq start (point))
12486 (when (string-match "%file" rpl)
12487 (setq rpl (replace-match
12488 (concat
12489 "\""
12490 (save-match-data
12491 (abbreviate-file-name (read-file-name "Include file: ")))
12492 "\"")
12493 t t rpl)))
12494 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12495 (concat "\n" ind)))
12496 (insert rpl)
12497 (when (re-search-backward "\\?" start t) (delete-char 1))))
12499 ;;;; TODO, DEADLINE, Comments
12501 (defun org-toggle-comment ()
12502 "Change the COMMENT state of an entry."
12503 (interactive)
12504 (save-excursion
12505 (org-back-to-heading)
12506 (let ((case-fold-search nil))
12507 (looking-at org-complex-heading-regexp))
12508 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12509 (skip-chars-forward " \t")
12510 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12511 (if (org-in-commented-heading-p t)
12512 (delete-region (point)
12513 (progn (search-forward " " (line-end-position) 'move)
12514 (skip-chars-forward " \t")
12515 (point)))
12516 (insert org-comment-string)
12517 (unless (eolp) (insert " ")))))
12519 (defvar org-last-todo-state-is-todo nil
12520 "This is non-nil when the last TODO state change led to a TODO state.
12521 If the last change removed the TODO tag or switched to DONE, then
12522 this is nil.")
12524 (defvar org-setting-tags nil) ; dynamically skipped
12526 (defvar org-todo-setup-filter-hook nil
12527 "Hook for functions that pre-filter todo specs.
12528 Each function takes a todo spec and returns either nil or the spec
12529 transformed into canonical form." )
12531 (defvar org-todo-get-default-hook nil
12532 "Hook for functions that get a default item for todo.
12533 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12534 nil or a string to be used for the todo mark." )
12536 (defvar org-agenda-headline-snapshot-before-repeat)
12538 (defun org-current-effective-time ()
12539 "Return current time adjusted for `org-extend-today-until' variable."
12540 (let* ((ct (org-current-time))
12541 (dct (decode-time ct))
12542 (ct1
12543 (cond
12544 (org-use-last-clock-out-time-as-effective-time
12545 (or (org-clock-get-last-clock-out-time) ct))
12546 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12547 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12548 (t ct))))
12549 ct1))
12551 (defun org-todo-yesterday (&optional arg)
12552 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12553 (interactive "P")
12554 (if (eq major-mode 'org-agenda-mode)
12555 (apply 'org-agenda-todo-yesterday arg)
12556 (let* ((org-use-effective-time t)
12557 (hour (nth 2 (decode-time (org-current-time))))
12558 (org-extend-today-until (1+ hour)))
12559 (org-todo arg))))
12561 (defvar org-block-entry-blocking ""
12562 "First entry preventing the TODO state change.")
12564 (defun org-cancel-repeater ()
12565 "Cancel a repeater by setting its numeric value to zero."
12566 (interactive)
12567 (save-excursion
12568 (org-back-to-heading t)
12569 (let ((bound1 (point))
12570 (bound0 (save-excursion (outline-next-heading) (point))))
12571 (when (and (re-search-forward
12572 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12573 org-deadline-time-regexp "\\)\\|\\("
12574 org-ts-regexp "\\)")
12575 bound0 t)
12576 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12577 bound1 t))
12578 (replace-match "0" t nil nil 1)))))
12580 (defvar org-state) ;; dynamically scoped into this function
12581 (defun org-todo (&optional arg)
12582 "Change the TODO state of an item.
12584 The state of an item is given by a keyword at the start of the heading,
12585 like
12586 *** TODO Write paper
12587 *** DONE Call mom
12589 The different keywords are specified in the variable `org-todo-keywords'.
12590 By default the available states are \"TODO\" and \"DONE\". So, for this
12591 example: when the item starts with TODO, it is changed to DONE.
12592 When it starts with DONE, the DONE is removed. And when neither TODO nor
12593 DONE are present, add TODO at the beginning of the heading.
12595 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12596 state.
12597 With numeric prefix ARG, switch to that state.
12598 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12599 next set of TODO \
12600 keywords (nextset).
12601 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12602 prefix, circumvent any state blocking.
12603 With a numeric prefix arg of 0, inhibit note taking for the change.
12604 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12606 When called through ELisp, arg is also interpreted in the following way:
12607 `none' -> empty state
12608 \"\" -> switch to empty state
12609 `done' -> switch to DONE
12610 `nextset' -> switch to the next set of keywords
12611 `previousset' -> switch to the previous set of keywords
12612 \"WAITING\" -> switch to the specified keyword, but only if it
12613 really is a member of `org-todo-keywords'."
12614 (interactive "P")
12615 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12616 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12617 'region-start-level 'region))
12618 org-loop-over-headlines-in-active-region)
12619 (org-map-entries
12620 `(org-todo ,arg)
12621 org-loop-over-headlines-in-active-region
12622 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12623 (when (equal arg '(16)) (setq arg 'nextset))
12624 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12625 (let ((org-blocker-hook org-blocker-hook)
12626 commentp
12627 case-fold-search)
12628 (when (equal arg '(64))
12629 (setq arg nil org-blocker-hook nil))
12630 (when (and org-blocker-hook
12631 (or org-inhibit-blocking
12632 (org-entry-get nil "NOBLOCKING")))
12633 (setq org-blocker-hook nil))
12634 (save-excursion
12635 (catch 'exit
12636 (org-back-to-heading t)
12637 (when (org-in-commented-heading-p t)
12638 (org-toggle-comment)
12639 (setq commentp t))
12640 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12641 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12642 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12643 (let* ((match-data (match-data))
12644 (startpos (point-at-bol))
12645 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12646 (org-log-done org-log-done)
12647 (org-log-repeat org-log-repeat)
12648 (org-todo-log-states org-todo-log-states)
12649 (org-inhibit-logging
12650 (if (equal arg 0)
12651 (progn (setq arg nil) 'note) org-inhibit-logging))
12652 (this (match-string 1))
12653 (hl-pos (match-beginning 0))
12654 (head (org-get-todo-sequence-head this))
12655 (ass (assoc head org-todo-kwd-alist))
12656 (interpret (nth 1 ass))
12657 (done-word (nth 3 ass))
12658 (final-done-word (nth 4 ass))
12659 (org-last-state (or this ""))
12660 (completion-ignore-case t)
12661 (member (member this org-todo-keywords-1))
12662 (tail (cdr member))
12663 (org-state (cond
12664 ((and org-todo-key-trigger
12665 (or (and (equal arg '(4))
12666 (eq org-use-fast-todo-selection 'prefix))
12667 (and (not arg) org-use-fast-todo-selection
12668 (not (eq org-use-fast-todo-selection
12669 'prefix)))))
12670 ;; Use fast selection
12671 (org-fast-todo-selection))
12672 ((and (equal arg '(4))
12673 (or (not org-use-fast-todo-selection)
12674 (not org-todo-key-trigger)))
12675 ;; Read a state with completion
12676 (completing-read
12677 "State: " (mapcar #'list org-todo-keywords-1)
12678 nil t))
12679 ((eq arg 'right)
12680 (if this
12681 (if tail (car tail) nil)
12682 (car org-todo-keywords-1)))
12683 ((eq arg 'left)
12684 (unless (equal member org-todo-keywords-1)
12685 (if this
12686 (nth (- (length org-todo-keywords-1)
12687 (length tail) 2)
12688 org-todo-keywords-1)
12689 (org-last org-todo-keywords-1))))
12690 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12691 (setq arg nil))) ; hack to fall back to cycling
12692 (arg
12693 ;; user or caller requests a specific state
12694 (cond
12695 ((equal arg "") nil)
12696 ((eq arg 'none) nil)
12697 ((eq arg 'done) (or done-word (car org-done-keywords)))
12698 ((eq arg 'nextset)
12699 (or (car (cdr (member head org-todo-heads)))
12700 (car org-todo-heads)))
12701 ((eq arg 'previousset)
12702 (let ((org-todo-heads (reverse org-todo-heads)))
12703 (or (car (cdr (member head org-todo-heads)))
12704 (car org-todo-heads))))
12705 ((car (member arg org-todo-keywords-1)))
12706 ((stringp arg)
12707 (user-error "State `%s' not valid in this file" arg))
12708 ((nth (1- (prefix-numeric-value arg))
12709 org-todo-keywords-1))))
12710 ((null member) (or head (car org-todo-keywords-1)))
12711 ((equal this final-done-word) nil) ;; -> make empty
12712 ((null tail) nil) ;; -> first entry
12713 ((memq interpret '(type priority))
12714 (if (eq this-command last-command)
12715 (car tail)
12716 (if (> (length tail) 0)
12717 (or done-word (car org-done-keywords))
12718 nil)))
12720 (car tail))))
12721 (org-state (or
12722 (run-hook-with-args-until-success
12723 'org-todo-get-default-hook org-state org-last-state)
12724 org-state))
12725 (next (if org-state (concat " " org-state " ") " "))
12726 (change-plist (list :type 'todo-state-change :from this :to org-state
12727 :position startpos))
12728 dolog now-done-p)
12729 (when org-blocker-hook
12730 (setq org-last-todo-state-is-todo
12731 (not (member this org-done-keywords)))
12732 (unless (save-excursion
12733 (save-match-data
12734 (org-with-wide-buffer
12735 (run-hook-with-args-until-failure
12736 'org-blocker-hook change-plist))))
12737 (if (called-interactively-p 'interactive)
12738 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12739 this org-state org-block-entry-blocking)
12740 ;; fail silently
12741 (message "TODO state change from %s to %s blocked (by \"%s\")"
12742 this org-state org-block-entry-blocking)
12743 (throw 'exit nil))))
12744 (store-match-data match-data)
12745 (replace-match next t t)
12746 (cond ((equal this org-state)
12747 (message "TODO state was already %s" (org-trim next)))
12748 ((pos-visible-in-window-p hl-pos)
12749 (message "TODO state changed to %s" (org-trim next))))
12750 (unless head
12751 (setq head (org-get-todo-sequence-head org-state)
12752 ass (assoc head org-todo-kwd-alist)
12753 interpret (nth 1 ass)
12754 done-word (nth 3 ass)
12755 final-done-word (nth 4 ass)))
12756 (when (memq arg '(nextset previousset))
12757 (message "Keyword-Set %d/%d: %s"
12758 (- (length org-todo-sets) -1
12759 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12760 (length org-todo-sets)
12761 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12762 (setq org-last-todo-state-is-todo
12763 (not (member org-state org-done-keywords)))
12764 (setq now-done-p (and (member org-state org-done-keywords)
12765 (not (member this org-done-keywords))))
12766 (and logging (org-local-logging logging))
12767 (when (and (or org-todo-log-states org-log-done)
12768 (not (eq org-inhibit-logging t))
12769 (not (memq arg '(nextset previousset))))
12770 ;; we need to look at recording a time and note
12771 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12772 (nth 2 (assoc this org-todo-log-states))))
12773 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12774 (setq dolog 'time))
12775 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12776 (and org-state
12777 (member org-state org-not-done-keywords)
12778 (not (member this org-not-done-keywords))))
12779 ;; This is now a todo state and was not one before
12780 ;; If there was a CLOSED time stamp, get rid of it.
12781 (org-add-planning-info nil nil 'closed))
12782 (when (and now-done-p org-log-done)
12783 ;; It is now done, and it was not done before
12784 (org-add-planning-info 'closed (org-current-effective-time))
12785 (when (and (not dolog) (eq 'note org-log-done))
12786 (org-add-log-setup 'done org-state this 'note)))
12787 (when (and org-state dolog)
12788 ;; This is a non-nil state, and we need to log it
12789 (org-add-log-setup 'state org-state this dolog)))
12790 ;; Fixup tag positioning
12791 (org-todo-trigger-tag-changes org-state)
12792 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12793 (when org-provide-todo-statistics
12794 (org-update-parent-todo-statistics))
12795 (run-hooks 'org-after-todo-state-change-hook)
12796 (when (and arg (not (member org-state org-done-keywords)))
12797 (setq head (org-get-todo-sequence-head org-state)))
12798 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12799 ;; Do we need to trigger a repeat?
12800 (when now-done-p
12801 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12802 ;; This is for the agenda, take a snapshot of the headline.
12803 (save-match-data
12804 (setq org-agenda-headline-snapshot-before-repeat
12805 (org-get-heading))))
12806 (org-auto-repeat-maybe org-state))
12807 ;; Fixup cursor location if close to the keyword
12808 (when (and (outline-on-heading-p)
12809 (not (bolp))
12810 (save-excursion (beginning-of-line 1)
12811 (looking-at org-todo-line-regexp))
12812 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12813 (goto-char (or (match-end 2) (match-end 1)))
12814 (and (looking-at " ") (just-one-space)))
12815 (when org-trigger-hook
12816 (save-excursion
12817 (run-hook-with-args 'org-trigger-hook change-plist)))
12818 (when commentp (org-toggle-comment))))))))
12820 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12821 "Block turning an entry into a TODO, using the hierarchy.
12822 This checks whether the current task should be blocked from state
12823 changes. Such blocking occurs when:
12825 1. The task has children which are not all in a completed state.
12827 2. A task has a parent with the property :ORDERED:, and there
12828 are siblings prior to the current task with incomplete
12829 status.
12831 3. The parent of the task is blocked because it has siblings that should
12832 be done first, or is child of a block grandparent TODO entry."
12834 (if (not org-enforce-todo-dependencies)
12835 t ; if locally turned off don't block
12836 (catch 'dont-block
12837 ;; If this is not a todo state change, or if this entry is already DONE,
12838 ;; do not block
12839 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12840 (member (plist-get change-plist :from)
12841 (cons 'done org-done-keywords))
12842 (member (plist-get change-plist :to)
12843 (cons 'todo org-not-done-keywords))
12844 (not (plist-get change-plist :to)))
12845 (throw 'dont-block t))
12846 ;; If this task has children, and any are undone, it's blocked
12847 (save-excursion
12848 (org-back-to-heading t)
12849 (let ((this-level (funcall outline-level)))
12850 (outline-next-heading)
12851 (let ((child-level (funcall outline-level)))
12852 (while (and (not (eobp))
12853 (> child-level this-level))
12854 ;; this todo has children, check whether they are all
12855 ;; completed
12856 (when (and (not (org-entry-is-done-p))
12857 (org-entry-is-todo-p))
12858 (setq org-block-entry-blocking (org-get-heading))
12859 (throw 'dont-block nil))
12860 (outline-next-heading)
12861 (setq child-level (funcall outline-level))))))
12862 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12863 ;; any previous siblings are undone, it's blocked
12864 (save-excursion
12865 (org-back-to-heading t)
12866 (let* ((pos (point))
12867 (parent-pos (and (org-up-heading-safe) (point)))
12868 (case-fold-search nil))
12869 (unless parent-pos (throw 'dont-block t)) ; no parent
12870 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12871 (forward-line 1)
12872 (re-search-forward org-not-done-heading-regexp pos t))
12873 (setq org-block-entry-blocking (match-string 0))
12874 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12875 ;; Search further up the hierarchy, to see if an ancestor is blocked
12876 (while t
12877 (goto-char parent-pos)
12878 (unless (looking-at org-not-done-heading-regexp)
12879 (throw 'dont-block t)) ; do not block, parent is not a TODO
12880 (setq pos (point))
12881 (setq parent-pos (and (org-up-heading-safe) (point)))
12882 (unless parent-pos (throw 'dont-block t)) ; no parent
12883 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12884 (forward-line 1)
12885 (re-search-forward org-not-done-heading-regexp pos t)
12886 (setq org-block-entry-blocking (org-get-heading)))
12887 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12889 (defcustom org-track-ordered-property-with-tag nil
12890 "Should the ORDERED property also be shown as a tag?
12891 The ORDERED property decides if an entry should require subtasks to be
12892 completed in sequence. Since a property is not very visible, setting
12893 this option means that toggling the ORDERED property with the command
12894 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12895 not relevant for the behavior, but it makes things more visible.
12897 Note that toggling the tag with tags commands will not change the property
12898 and therefore not influence behavior!
12900 This can be t, meaning the tag ORDERED should be used, It can also be a
12901 string to select a different tag for this task."
12902 :group 'org-todo
12903 :type '(choice
12904 (const :tag "No tracking" nil)
12905 (const :tag "Track with ORDERED tag" t)
12906 (string :tag "Use other tag")))
12908 (defun org-toggle-ordered-property ()
12909 "Toggle the ORDERED property of the current entry.
12910 For better visibility, you can track the value of this property with a tag.
12911 See variable `org-track-ordered-property-with-tag'."
12912 (interactive)
12913 (let* ((t1 org-track-ordered-property-with-tag)
12914 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12915 (save-excursion
12916 (org-back-to-heading)
12917 (if (org-entry-get nil "ORDERED")
12918 (progn
12919 (org-delete-property "ORDERED")
12920 (and tag (org-toggle-tag tag 'off))
12921 (message "Subtasks can be completed in arbitrary order"))
12922 (org-entry-put nil "ORDERED" "t")
12923 (and tag (org-toggle-tag tag 'on))
12924 (message "Subtasks must be completed in sequence")))))
12926 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12927 (defun org-block-todo-from-checkboxes (change-plist)
12928 "Block turning an entry into a TODO, using checkboxes.
12929 This checks whether the current task should be blocked from state
12930 changes because there are unchecked boxes in this entry."
12931 (if (not org-enforce-todo-checkbox-dependencies)
12932 t ; if locally turned off don't block
12933 (catch 'dont-block
12934 ;; If this is not a todo state change, or if this entry is already DONE,
12935 ;; do not block
12936 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12937 (member (plist-get change-plist :from)
12938 (cons 'done org-done-keywords))
12939 (member (plist-get change-plist :to)
12940 (cons 'todo org-not-done-keywords))
12941 (not (plist-get change-plist :to)))
12942 (throw 'dont-block t))
12943 ;; If this task has checkboxes that are not checked, it's blocked
12944 (save-excursion
12945 (org-back-to-heading t)
12946 (let ((beg (point)) end)
12947 (outline-next-heading)
12948 (setq end (point))
12949 (goto-char beg)
12950 (when (org-list-search-forward
12951 (concat (org-item-beginning-re)
12952 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12953 "\\[[- ]\\]")
12954 end t)
12955 (when (boundp 'org-blocked-by-checkboxes)
12956 (setq org-blocked-by-checkboxes t))
12957 (throw 'dont-block nil))))
12958 t))) ; do not block
12960 (defun org-entry-blocked-p ()
12961 "Non-nil if entry at point is blocked."
12962 (and (not (org-entry-get nil "NOBLOCKING"))
12963 (member (org-entry-get nil "TODO") org-not-done-keywords)
12964 (not (run-hook-with-args-until-failure
12965 'org-blocker-hook
12966 (list :type 'todo-state-change
12967 :position (point)
12968 :from 'todo
12969 :to 'done)))))
12971 (defun org-update-statistics-cookies (all)
12972 "Update the statistics cookie, either from TODO or from checkboxes.
12973 This should be called with the cursor in a line with a statistics
12974 cookie. When called with a \\[universal-argument] prefix, update
12975 all statistics cookies in the buffer."
12976 (interactive "P")
12977 (if all
12978 (progn
12979 (org-update-checkbox-count 'all)
12980 (org-map-entries 'org-update-parent-todo-statistics))
12981 (if (not (org-at-heading-p))
12982 (org-update-checkbox-count)
12983 (let ((pos (point-marker))
12984 end l1 l2)
12985 (ignore-errors (org-back-to-heading t))
12986 (if (not (org-at-heading-p))
12987 (org-update-checkbox-count)
12988 (setq l1 (org-outline-level))
12989 (setq end (save-excursion
12990 (outline-next-heading)
12991 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12992 (point)))
12993 (if (and (save-excursion
12994 (re-search-forward
12995 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12996 (not (save-excursion (re-search-forward
12997 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12998 (org-update-checkbox-count)
12999 (if (and l2 (> l2 l1))
13000 (progn
13001 (goto-char end)
13002 (org-update-parent-todo-statistics))
13003 (goto-char pos)
13004 (beginning-of-line 1)
13005 (while (re-search-forward
13006 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
13007 (point-at-eol) t)
13008 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
13009 (goto-char pos)
13010 (move-marker pos nil)))))
13012 (defvar org-entry-property-inherited-from) ;; defined below
13013 (defun org-update-parent-todo-statistics ()
13014 "Update any statistics cookie in the parent of the current headline.
13015 When `org-hierarchical-todo-statistics' is nil, statistics will cover
13016 the entire subtree and this will travel up the hierarchy and update
13017 statistics everywhere."
13018 (let* ((prop (save-excursion (org-up-heading-safe)
13019 (org-entry-get nil "COOKIE_DATA" 'inherit)))
13020 (recursive (or (not org-hierarchical-todo-statistics)
13021 (and prop (string-match "\\<recursive\\>" prop))))
13022 (lim (or (and prop (marker-position org-entry-property-inherited-from))
13024 (first t)
13025 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
13026 level ltoggle l1 new ndel
13027 (cnt-all 0) (cnt-done 0) is-percent kwd
13028 checkbox-beg cookie-present)
13029 (catch 'exit
13030 (save-excursion
13031 (beginning-of-line 1)
13032 (setq ltoggle (funcall outline-level))
13033 ;; Three situations are to consider:
13035 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
13036 ;; to the top-level ancestor on the headline;
13038 ;; 2. If parent has "recursive" property, repeat up to the
13039 ;; headline setting that property, taking inheritance into
13040 ;; account;
13042 ;; 3. Else, move up to direct parent and proceed only once.
13043 (while (and (setq level (org-up-heading-safe))
13044 (or recursive first)
13045 (>= (point) lim))
13046 (setq first nil cookie-present nil)
13047 (unless (and level
13048 (not (string-match
13049 "\\<checkbox\\>"
13050 (downcase (or (org-entry-get nil "COOKIE_DATA")
13051 "")))))
13052 (throw 'exit nil))
13053 (while (re-search-forward box-re (point-at-eol) t)
13054 (setq cnt-all 0 cnt-done 0 cookie-present t)
13055 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
13056 (save-match-data
13057 (unless (outline-next-heading) (throw 'exit nil))
13058 (while (and (looking-at org-complex-heading-regexp)
13059 (> (setq l1 (length (match-string 1))) level))
13060 (setq kwd (and (or recursive (= l1 ltoggle))
13061 (match-string 2)))
13062 (if (or (eq org-provide-todo-statistics 'all-headlines)
13063 (and (eq org-provide-todo-statistics t)
13064 (or (member kwd org-done-keywords)))
13065 (and (listp org-provide-todo-statistics)
13066 (stringp (car org-provide-todo-statistics))
13067 (or (member kwd org-provide-todo-statistics)
13068 (member kwd org-done-keywords)))
13069 (and (listp org-provide-todo-statistics)
13070 (listp (car org-provide-todo-statistics))
13071 (or (member kwd (car org-provide-todo-statistics))
13072 (and (member kwd org-done-keywords)
13073 (member kwd (cadr org-provide-todo-statistics))))))
13074 (setq cnt-all (1+ cnt-all))
13075 (and (eq org-provide-todo-statistics t)
13077 (setq cnt-all (1+ cnt-all))))
13078 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13079 (member kwd org-done-keywords))
13080 (and (listp org-provide-todo-statistics)
13081 (listp (car org-provide-todo-statistics))
13082 (member kwd org-done-keywords)
13083 (member kwd (cadr org-provide-todo-statistics)))
13084 (and (listp org-provide-todo-statistics)
13085 (stringp (car org-provide-todo-statistics))
13086 (member kwd org-done-keywords)))
13087 (setq cnt-done (1+ cnt-done)))
13088 (outline-next-heading)))
13089 (setq new
13090 (if is-percent
13091 (format "[%d%%]" (floor (* 100.0 cnt-done)
13092 (max 1 cnt-all)))
13093 (format "[%d/%d]" cnt-done cnt-all))
13094 ndel (- (match-end 0) checkbox-beg))
13095 (goto-char checkbox-beg)
13096 (insert new)
13097 (delete-region (point) (+ (point) ndel))
13098 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13099 (when cookie-present
13100 (run-hook-with-args 'org-after-todo-statistics-hook
13101 cnt-done (- cnt-all cnt-done))))))
13102 (run-hooks 'org-todo-statistics-hook)))
13104 (defvar org-after-todo-statistics-hook nil
13105 "Hook that is called after a TODO statistics cookie has been updated.
13106 Each function is called with two arguments: the number of not-done entries
13107 and the number of done entries.
13109 For example, the following function, when added to this hook, will switch
13110 an entry to DONE when all children are done, and back to TODO when new
13111 entries are set to a TODO status. Note that this hook is only called
13112 when there is a statistics cookie in the headline!
13114 (defun org-summary-todo (n-done n-not-done)
13115 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13116 (let (org-log-done org-log-states) ; turn off logging
13117 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13120 (defvar org-todo-statistics-hook nil
13121 "Hook that is run whenever Org thinks TODO statistics should be updated.
13122 This hook runs even if there is no statistics cookie present, in which case
13123 `org-after-todo-statistics-hook' would not run.")
13125 (defun org-todo-trigger-tag-changes (state)
13126 "Apply the changes defined in `org-todo-state-tags-triggers'."
13127 (let ((l org-todo-state-tags-triggers)
13128 changes)
13129 (when (or (not state) (equal state ""))
13130 (setq changes (append changes (cdr (assoc "" l)))))
13131 (when (and (stringp state) (> (length state) 0))
13132 (setq changes (append changes (cdr (assoc state l)))))
13133 (when (member state org-not-done-keywords)
13134 (setq changes (append changes (cdr (assq 'todo l)))))
13135 (when (member state org-done-keywords)
13136 (setq changes (append changes (cdr (assq 'done l)))))
13137 (dolist (c changes)
13138 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13140 (defun org-local-logging (value)
13141 "Get logging settings from a property VALUE."
13142 ;; Directly set the variables, they are already local.
13143 (setq org-log-done nil
13144 org-log-repeat nil
13145 org-todo-log-states nil)
13146 (dolist (w (org-split-string value))
13147 (let (a)
13148 (cond
13149 ((setq a (assoc w org-startup-options))
13150 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13151 (set (nth 1 a) (nth 2 a))))
13152 ((setq a (org-extract-log-state-settings w))
13153 (and (member (car a) org-todo-keywords-1)
13154 (push a org-todo-log-states)))))))
13156 (defun org-get-todo-sequence-head (kwd)
13157 "Return the head of the TODO sequence to which KWD belongs.
13158 If KWD is not set, check if there is a text property remembering the
13159 right sequence."
13160 (let (p)
13161 (cond
13162 ((not kwd)
13163 (or (get-text-property (point-at-bol) 'org-todo-head)
13164 (progn
13165 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13166 nil (point-at-eol)))
13167 (get-text-property p 'org-todo-head))))
13168 ((not (member kwd org-todo-keywords-1))
13169 (car org-todo-keywords-1))
13170 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13172 (defun org-fast-todo-selection ()
13173 "Fast TODO keyword selection with single keys.
13174 Returns the new TODO keyword, or nil if no state change should occur."
13175 (let* ((fulltable org-todo-key-alist)
13176 (done-keywords org-done-keywords) ;; needed for the faces.
13177 (maxlen (apply 'max (mapcar
13178 (lambda (x)
13179 (if (stringp (car x)) (string-width (car x)) 0))
13180 fulltable)))
13181 (expert nil)
13182 (fwidth (+ maxlen 3 1 3))
13183 (ncol (/ (- (window-width) 4) fwidth))
13184 tg cnt e c tbl
13185 groups ingroup)
13186 (save-excursion
13187 (save-window-excursion
13188 (if expert
13189 (set-buffer (get-buffer-create " *Org todo*"))
13190 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13191 (erase-buffer)
13192 (setq-local org-done-keywords done-keywords)
13193 (setq tbl fulltable cnt 0)
13194 (while (setq e (pop tbl))
13195 (cond
13196 ((equal e '(:startgroup))
13197 (push '() groups) (setq ingroup t)
13198 (unless (= cnt 0)
13199 (setq cnt 0)
13200 (insert "\n"))
13201 (insert "{ "))
13202 ((equal e '(:endgroup))
13203 (setq ingroup nil cnt 0)
13204 (insert "}\n"))
13205 ((equal e '(:newline))
13206 (unless (= cnt 0)
13207 (setq cnt 0)
13208 (insert "\n")
13209 (setq e (car tbl))
13210 (while (equal (car tbl) '(:newline))
13211 (insert "\n")
13212 (setq tbl (cdr tbl)))))
13214 (setq tg (car e) c (cdr e))
13215 (when ingroup (push tg (car groups)))
13216 (setq tg (org-add-props tg nil 'face
13217 (org-get-todo-face tg)))
13218 (when (and (= cnt 0) (not ingroup)) (insert " "))
13219 (insert "[" c "] " tg (make-string
13220 (- fwidth 4 (length tg)) ?\ ))
13221 (when (= (setq cnt (1+ cnt)) ncol)
13222 (insert "\n")
13223 (when ingroup (insert " "))
13224 (setq cnt 0)))))
13225 (insert "\n")
13226 (goto-char (point-min))
13227 (unless expert (org-fit-window-to-buffer))
13228 (message "[a-z..]:Set [SPC]:clear")
13229 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13230 (cond
13231 ((or (= c ?\C-g)
13232 (and (= c ?q) (not (rassoc c fulltable))))
13233 (setq quit-flag t))
13234 ((= c ?\ ) nil)
13235 ((setq e (rassoc c fulltable) tg (car e))
13237 (t (setq quit-flag t)))))))
13239 (defun org-entry-is-todo-p ()
13240 (member (org-get-todo-state) org-not-done-keywords))
13242 (defun org-entry-is-done-p ()
13243 (member (org-get-todo-state) org-done-keywords))
13245 (defun org-get-todo-state ()
13246 "Return the TODO keyword of the current subtree."
13247 (save-excursion
13248 (org-back-to-heading t)
13249 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13250 (match-end 2)
13251 (match-string 2))))
13253 (defun org-at-date-range-p (&optional inactive-ok)
13254 "Non-nil if point is inside a date range.
13256 When optional argument INACTIVE-OK is non-nil, also consider
13257 inactive time ranges.
13259 When this function returns a non-nil value, match data is set
13260 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13261 on INACTIVE-OK."
13262 (interactive)
13263 (save-excursion
13264 (catch 'exit
13265 (let ((pos (point)))
13266 (skip-chars-backward "^[<\r\n")
13267 (skip-chars-backward "<[")
13268 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13269 (>= (match-end 0) pos)
13270 (throw 'exit t))
13271 (skip-chars-backward "^<[\r\n")
13272 (skip-chars-backward "<[")
13273 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13274 (>= (match-end 0) pos)
13275 (throw 'exit t)))
13276 nil)))
13278 (defun org-get-repeat (&optional tagline)
13279 "Check if there is a deadline/schedule with repeater in this entry."
13280 (save-match-data
13281 (save-excursion
13282 (org-back-to-heading t)
13283 (and (re-search-forward (if tagline
13284 (concat tagline "\\s-*" org-repeat-re)
13285 org-repeat-re)
13286 (org-entry-end-position) t)
13287 (match-string-no-properties 1)))))
13289 (defvar org-last-changed-timestamp)
13290 (defvar org-last-inserted-timestamp)
13291 (defvar org-log-post-message)
13292 (defvar org-log-note-purpose)
13293 (defvar org-log-note-how nil)
13294 (defvar org-log-note-extra)
13295 (defun org-auto-repeat-maybe (done-word)
13296 "Check if the current headline contains a repeated time-stamp.
13298 If yes, set TODO state back to what it was and change the base date
13299 of repeating deadline/scheduled time stamps to new date.
13301 This function is run automatically after each state change to a DONE state."
13302 (let* ((repeat (org-get-repeat))
13303 (aa (assoc org-last-state org-todo-kwd-alist))
13304 (interpret (nth 1 aa))
13305 (head (nth 2 aa))
13306 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13307 (msg "Entry repeats: ")
13308 (org-log-done nil)
13309 (org-todo-log-states nil))
13310 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13311 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13312 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13313 org-todo-repeat-to-state)))
13314 (unless (and to-state (member to-state org-todo-keywords-1))
13315 (setq to-state (if (eq interpret 'type) org-last-state head)))
13316 (org-todo to-state))
13317 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13318 (org-entry-put nil "LAST_REPEAT" (format-time-string
13319 (org-time-stamp-format t t))))
13320 (when org-log-repeat
13321 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13322 (memq 'org-add-log-note post-command-hook))
13323 ;; We are already setup for some record.
13324 (when (eq org-log-repeat 'note)
13325 ;; Make sure we take a note, not only a time stamp.
13326 (setq org-log-note-how 'note))
13327 ;; Set up for taking a record.
13328 (org-add-log-setup 'state
13329 (or done-word (car org-done-keywords))
13330 org-last-state
13331 org-log-repeat)))
13332 (org-back-to-heading t)
13333 (org-add-planning-info nil nil 'closed)
13334 (let ((end (save-excursion (outline-next-heading) (point))))
13335 (while (re-search-forward org-ts-regexp end t)
13336 (when (save-match-data
13337 (or (org-at-planning-p)
13338 (org-at-property-p)
13339 (eq (org-element-type (save-excursion
13340 (backward-char)
13341 (org-element-context)))
13342 'timestamp)))
13343 (let ((type (cond ((match-end 1) org-scheduled-string)
13344 ((match-end 3) org-deadline-string)
13345 (t "Plain:")))
13346 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13347 (cond
13348 ((not
13349 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13350 ;; Time-stamps without a repeater are usually skipped.
13351 ;; However, a SCHEDULED time-stamp without one is
13352 ;; removed, as it is considered as no longer relevant.
13353 (when (equal type org-scheduled-string)
13354 (org-remove-timestamp-with-keyword type)))
13356 (let ((n (string-to-number (match-string 2 ts)))
13357 (what (match-string 3 ts)))
13358 (when (equal what "w") (setq n (* n 7) what "d"))
13359 (when (and (equal what "h")
13360 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13361 ts)))
13362 (user-error
13363 "Cannot repeat in Repeat in %d hour(s) because no hour \
13364 has been set"
13366 ;; Preparation, see if we need to modify the start
13367 ;; date for the change.
13368 (when (match-end 1)
13369 (let ((time (save-match-data (org-time-string-to-time ts))))
13370 (cond
13371 ((equal (match-string 1 ts) ".")
13372 ;; Shift starting date to today
13373 (org-timestamp-change
13374 (- (org-today) (time-to-days time))
13375 'day))
13376 ((equal (match-string 1 ts) "+")
13377 (let ((nshiftmax 10)
13378 (nshift 0))
13379 (while (or (= nshift 0)
13380 (not (time-less-p (current-time) time)))
13381 (when (= (cl-incf nshift) nshiftmax)
13382 (or (y-or-n-p
13383 (format "%d repeater intervals were not \
13384 enough to shift date past today. Continue? "
13385 nshift))
13386 (user-error "Abort")))
13387 (org-timestamp-change n (cdr (assoc what whata)))
13388 (org-at-timestamp-p t)
13389 (setq ts (match-string 1))
13390 (setq time
13391 (save-match-data
13392 (org-time-string-to-time ts)))))
13393 (org-timestamp-change (- n) (cdr (assoc what whata)))
13394 ;; Rematch, so that we have everything in
13395 ;; place for the real shift.
13396 (org-at-timestamp-p t)
13397 (setq ts (match-string 1))
13398 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13399 ts)))))
13400 (save-excursion
13401 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13402 (setq msg
13403 (concat
13404 msg type " " org-last-changed-timestamp " ")))))))))
13405 (setq org-log-post-message msg)
13406 (message "%s" msg))))
13408 (defun org-show-todo-tree (arg)
13409 "Make a compact tree which shows all headlines marked with TODO.
13410 The tree will show the lines where the regexp matches, and all higher
13411 headlines above the match.
13412 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13413 With a numeric prefix N, construct a sparse tree for the Nth element
13414 of `org-todo-keywords-1'."
13415 (interactive "P")
13416 (let ((case-fold-search nil)
13417 (kwd-re
13418 (cond ((null arg) org-not-done-regexp)
13419 ((equal arg '(4))
13420 (let ((kwd
13421 (completing-read "Keyword (or KWD1|KWD2|...): "
13422 (mapcar #'list org-todo-keywords-1))))
13423 (concat "\\("
13424 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13425 "\\)\\>")))
13426 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13427 (regexp-quote (nth (1- (prefix-numeric-value arg))
13428 org-todo-keywords-1)))
13429 (t (user-error "Invalid prefix argument: %s" arg)))))
13430 (message "%d TODO entries found"
13431 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13433 (defun org-deadline (arg &optional time)
13434 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13435 With one universal prefix argument, remove any deadline from the item.
13436 With two universal prefix arguments, prompt for a warning delay.
13437 With argument TIME, set the deadline at the corresponding date. TIME
13438 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13439 (interactive "P")
13440 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13441 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13442 'region-start-level 'region))
13443 org-loop-over-headlines-in-active-region)
13444 (org-map-entries
13445 `(org-deadline ',arg ,time)
13446 org-loop-over-headlines-in-active-region
13447 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13448 (let* ((old-date (org-entry-get nil "DEADLINE"))
13449 (old-date-time (when old-date (org-time-string-to-time old-date)))
13450 (repeater (and old-date
13451 (string-match
13452 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13453 old-date)
13454 (match-string 1 old-date))))
13455 (cond
13456 ((equal arg '(4))
13457 (when (and old-date org-log-redeadline)
13458 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13459 (org-remove-timestamp-with-keyword org-deadline-string)
13460 (message "Item no longer has a deadline."))
13461 ((equal arg '(16))
13462 (save-excursion
13463 (org-back-to-heading t)
13464 (if (re-search-forward
13465 org-deadline-time-regexp
13466 (save-excursion (outline-next-heading) (point)) t)
13467 (let* ((rpl0 (match-string 1))
13468 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13469 (replace-match
13470 (concat org-deadline-string
13471 " <" rpl
13472 (format " -%dd"
13473 (abs
13474 (- (time-to-days
13475 (save-match-data
13476 (org-read-date nil t nil "Warn starting from" old-date-time)))
13477 (time-to-days old-date-time))))
13478 ">") t t))
13479 (user-error "No deadline information to update"))))
13481 (org-add-planning-info 'deadline time 'closed)
13482 (when (and old-date
13483 org-log-redeadline
13484 (not (equal old-date org-last-inserted-timestamp)))
13485 (org-add-log-setup
13486 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13487 (when repeater
13488 (save-excursion
13489 (org-back-to-heading t)
13490 (when (re-search-forward (concat org-deadline-string " "
13491 org-last-inserted-timestamp)
13492 (save-excursion
13493 (outline-next-heading) (point)) t)
13494 (goto-char (1- (match-end 0)))
13495 (insert " " repeater)
13496 (setq org-last-inserted-timestamp
13497 (concat (substring org-last-inserted-timestamp 0 -1)
13498 " " repeater
13499 (substring org-last-inserted-timestamp -1))))))
13500 (message "Deadline on %s" org-last-inserted-timestamp))))))
13502 (defun org-schedule (arg &optional time)
13503 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13504 With one universal prefix argument, remove any scheduling date from the item.
13505 With two universal prefix arguments, prompt for a delay cookie.
13506 With argument TIME, scheduled at the corresponding date. TIME can
13507 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13508 (interactive "P")
13509 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13510 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13511 'region-start-level 'region))
13512 org-loop-over-headlines-in-active-region)
13513 (org-map-entries
13514 `(org-schedule ',arg ,time)
13515 org-loop-over-headlines-in-active-region
13516 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13517 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13518 (old-date-time (when old-date (org-time-string-to-time old-date)))
13519 (repeater (and old-date
13520 (string-match
13521 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13522 old-date)
13523 (match-string 1 old-date))))
13524 (cond
13525 ((equal arg '(4))
13526 (progn
13527 (when (and old-date org-log-reschedule)
13528 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13529 (org-remove-timestamp-with-keyword org-scheduled-string)
13530 (message "Item is no longer scheduled.")))
13531 ((equal arg '(16))
13532 (save-excursion
13533 (org-back-to-heading t)
13534 (if (re-search-forward
13535 org-scheduled-time-regexp
13536 (save-excursion (outline-next-heading) (point)) t)
13537 (let* ((rpl0 (match-string 1))
13538 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13539 (replace-match
13540 (concat org-scheduled-string
13541 " <" rpl
13542 (format " -%dd"
13543 (abs
13544 (- (time-to-days
13545 (save-match-data
13546 (org-read-date nil t nil "Delay until" old-date-time)))
13547 (time-to-days old-date-time))))
13548 ">") t t))
13549 (user-error "No scheduled information to update"))))
13551 (org-add-planning-info 'scheduled time 'closed)
13552 (when (and old-date
13553 org-log-reschedule
13554 (not (equal old-date org-last-inserted-timestamp)))
13555 (org-add-log-setup
13556 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13557 (when repeater
13558 (save-excursion
13559 (org-back-to-heading t)
13560 (when (re-search-forward (concat org-scheduled-string " "
13561 org-last-inserted-timestamp)
13562 (save-excursion
13563 (outline-next-heading) (point)) t)
13564 (goto-char (1- (match-end 0)))
13565 (insert " " repeater)
13566 (setq org-last-inserted-timestamp
13567 (concat (substring org-last-inserted-timestamp 0 -1)
13568 " " repeater
13569 (substring org-last-inserted-timestamp -1))))))
13570 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13572 (defun org-get-scheduled-time (pom &optional inherit)
13573 "Get the scheduled time as a time tuple, of a format suitable
13574 for calling org-schedule with, or if there is no scheduling,
13575 returns nil."
13576 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13577 (when time
13578 (apply 'encode-time (org-parse-time-string time)))))
13580 (defun org-get-deadline-time (pom &optional inherit)
13581 "Get the deadline as a time tuple, of a format suitable for
13582 calling org-deadline with, or if there is no scheduling, returns
13583 nil."
13584 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13585 (when time
13586 (apply 'encode-time (org-parse-time-string time)))))
13588 (defun org-remove-timestamp-with-keyword (keyword)
13589 "Remove all time stamps with KEYWORD in the current entry."
13590 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13591 beg)
13592 (save-excursion
13593 (org-back-to-heading t)
13594 (setq beg (point))
13595 (outline-next-heading)
13596 (while (re-search-backward re beg t)
13597 (replace-match "")
13598 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13599 (equal (char-before) ?\ ))
13600 (backward-delete-char 1)
13601 (when (string-match "^[ \t]*$" (buffer-substring
13602 (point-at-bol) (point-at-eol)))
13603 (delete-region (point-at-bol)
13604 (min (point-max) (1+ (point-at-eol))))))))))
13606 (defvar org-time-was-given) ; dynamically scoped parameter
13607 (defvar org-end-time-was-given) ; dynamically scoped parameter
13609 (defun org-at-planning-p ()
13610 "Non-nil when point is on a planning info line."
13611 ;; This is as accurate and faster than `org-element-at-point' since
13612 ;; planning info location is fixed in the section.
13613 (org-with-wide-buffer
13614 (beginning-of-line)
13615 (and (looking-at-p org-planning-line-re)
13616 (eq (point)
13617 (ignore-errors
13618 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13619 (org-back-to-heading t)
13620 (org-with-limited-levels (org-back-to-heading t)))
13621 (line-beginning-position 2))))))
13623 (defun org-add-planning-info (what &optional time &rest remove)
13624 "Insert new timestamp with keyword in the planning line.
13625 WHAT indicates what kind of time stamp to add. It is a symbol
13626 among `closed', `deadline', `scheduled' and nil. TIME indicates
13627 the time to use. If none is given, the user is prompted for
13628 a date. REMOVE indicates what kind of entries to remove. An old
13629 WHAT entry will also be removed."
13630 (let (org-time-was-given org-end-time-was-given default-time default-input)
13631 (catch 'exit
13632 (when (and (memq what '(scheduled deadline))
13633 (or (not time)
13634 (and (stringp time)
13635 (string-match "^[-+]+[0-9]" time))))
13636 ;; Try to get a default date/time from existing timestamp
13637 (save-excursion
13638 (org-back-to-heading t)
13639 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13640 (when (re-search-forward (if (eq what 'scheduled)
13641 org-scheduled-time-regexp
13642 org-deadline-time-regexp)
13643 end t)
13644 (setq ts (match-string 1)
13645 default-time (apply 'encode-time (org-parse-time-string ts))
13646 default-input (and ts (org-get-compact-tod ts)))))))
13647 (when what
13648 (setq time
13649 (if (stringp time)
13650 ;; This is a string (relative or absolute), set
13651 ;; proper date.
13652 (apply #'encode-time
13653 (org-read-date-analyze
13654 time default-time (decode-time default-time)))
13655 ;; If necessary, get the time from the user
13656 (or time (org-read-date nil 'to-time nil nil
13657 default-time default-input)))))
13659 (org-with-wide-buffer
13660 (org-back-to-heading t)
13661 (forward-line)
13662 (unless (bolp) (insert "\n"))
13663 (cond ((looking-at-p org-planning-line-re)
13664 ;; Move to current indentation.
13665 (skip-chars-forward " \t")
13666 ;; Check if we have to remove something.
13667 (dolist (type (if what (cons what remove) remove))
13668 (save-excursion
13669 (when (re-search-forward
13670 (cl-case type
13671 (closed org-closed-time-regexp)
13672 (deadline org-deadline-time-regexp)
13673 (scheduled org-scheduled-time-regexp)
13674 (otherwise
13675 (error "Invalid planning type: %s" type)))
13676 (line-end-position) t)
13677 ;; Delete until next keyword or end of line.
13678 (delete-region
13679 (match-beginning 0)
13680 (if (re-search-forward org-keyword-time-not-clock-regexp
13681 (line-end-position)
13683 (match-beginning 0)
13684 (line-end-position))))))
13685 ;; If there is nothing more to add and no more keyword
13686 ;; is left, remove the line completely.
13687 (if (and (looking-at-p "[ \t]*$") (not what))
13688 (delete-region (line-beginning-position)
13689 (line-beginning-position 2))
13690 ;; If we removed last keyword, do not leave trailing
13691 ;; white space at the end of line.
13692 (let ((p (point)))
13693 (save-excursion
13694 (end-of-line)
13695 (unless (= (skip-chars-backward " \t" p) 0)
13696 (delete-region (point) (line-end-position)))))))
13697 ((not what) (throw 'exit nil)) ; Nothing to do.
13698 (t (insert-before-markers "\n")
13699 (backward-char 1)
13700 (when org-adapt-indentation
13701 (indent-to-column (1+ (org-outline-level))))))
13702 (when what
13703 ;; Insert planning keyword.
13704 (insert (cl-case what
13705 (closed org-closed-string)
13706 (deadline org-deadline-string)
13707 (scheduled org-scheduled-string)
13708 (otherwise (error "Invalid planning type: %s" what)))
13709 " ")
13710 ;; Insert associated timestamp.
13711 (let ((ts (org-insert-time-stamp
13712 time
13713 (or org-time-was-given
13714 (and (eq what 'closed) org-log-done-with-time))
13715 (eq what 'closed)
13716 nil nil (list org-end-time-was-given))))
13717 (unless (eolp) (insert " "))
13718 ts))))))
13720 (defvar org-log-note-marker (make-marker)
13721 "Marker pointing at the entry where the note is to be inserted.")
13722 (defvar org-log-note-purpose nil)
13723 (defvar org-log-note-state nil)
13724 (defvar org-log-note-previous-state nil)
13725 (defvar org-log-note-extra nil)
13726 (defvar org-log-note-window-configuration nil)
13727 (defvar org-log-note-return-to (make-marker))
13728 (defvar org-log-note-effective-time nil
13729 "Remembered current time so that dynamically scoped
13730 `org-extend-today-until' affects timestamps in state change log")
13732 (defvar org-log-post-message nil
13733 "Message to be displayed after a log note has been stored.
13734 The auto-repeater uses this.")
13736 (defun org-add-note ()
13737 "Add a note to the current entry.
13738 This is done in the same way as adding a state change note."
13739 (interactive)
13740 (org-add-log-setup 'note))
13742 (defun org-log-beginning (&optional create)
13743 "Return expected start of log notes in current entry.
13744 When optional argument CREATE is non-nil, the function creates
13745 a drawer to store notes, if necessary. Returned position ignores
13746 narrowing."
13747 (org-with-wide-buffer
13748 (let ((drawer (org-log-into-drawer)))
13749 (cond
13750 (drawer
13751 (org-end-of-meta-data)
13752 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13753 (end (if (org-at-heading-p) (point)
13754 (save-excursion (outline-next-heading) (point))))
13755 (case-fold-search t))
13756 (catch 'exit
13757 ;; Try to find existing drawer.
13758 (while (re-search-forward regexp end t)
13759 (let ((element (org-element-at-point)))
13760 (when (eq (org-element-type element) 'drawer)
13761 (let ((cend (org-element-property :contents-end element)))
13762 (when (and (not org-log-states-order-reversed) cend)
13763 (goto-char cend)))
13764 (throw 'exit nil))))
13765 ;; No drawer found. Create one, if permitted.
13766 (when create
13767 (unless (bolp) (insert "\n"))
13768 (let ((beg (point)))
13769 (insert ":" drawer ":\n:END:\n")
13770 (org-indent-region beg (point)))
13771 (end-of-line -1)))))
13773 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13774 (skip-chars-forward " \t\n")
13775 (beginning-of-line)
13776 (unless org-log-states-order-reversed
13777 (org-skip-over-state-notes)
13778 (skip-chars-backward " \t\n")
13779 (forward-line)))))
13780 (if (bolp) (point) (line-beginning-position 2))))
13782 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13783 "Set up the post command hook to take a note.
13784 If this is about to TODO state change, the new state is expected in STATE.
13785 HOW is an indicator what kind of note should be created.
13786 EXTRA is additional text that will be inserted into the notes buffer."
13787 (move-marker org-log-note-marker (point))
13788 (setq org-log-note-purpose purpose
13789 org-log-note-state state
13790 org-log-note-previous-state prev-state
13791 org-log-note-how how
13792 org-log-note-extra extra
13793 org-log-note-effective-time (org-current-effective-time))
13794 (add-hook 'post-command-hook 'org-add-log-note 'append))
13796 (defun org-skip-over-state-notes ()
13797 "Skip past the list of State notes in an entry."
13798 (when (ignore-errors (goto-char (org-in-item-p)))
13799 (let* ((struct (org-list-struct))
13800 (prevs (org-list-prevs-alist struct))
13801 (regexp
13802 (concat "[ \t]*- +"
13803 (replace-regexp-in-string
13804 " +" " +"
13805 (org-replace-escapes
13806 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13807 `(("%d" . ,org-ts-regexp-inactive)
13808 ("%D" . ,org-ts-regexp)
13809 ("%s" . "\"\\S-+\"")
13810 ("%S" . "\"\\S-+\"")
13811 ("%t" . ,org-ts-regexp-inactive)
13812 ("%T" . ,org-ts-regexp)
13813 ("%u" . ".*?")
13814 ("%U" . ".*?")))))))
13815 (while (looking-at-p regexp)
13816 (goto-char (or (org-list-get-next-item (point) struct prevs)
13817 (org-list-get-item-end (point) struct)))))))
13819 (defun org-add-log-note (&optional _purpose)
13820 "Pop up a window for taking a note, and add this note later."
13821 (remove-hook 'post-command-hook 'org-add-log-note)
13822 (setq org-log-note-window-configuration (current-window-configuration))
13823 (delete-other-windows)
13824 (move-marker org-log-note-return-to (point))
13825 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13826 (goto-char org-log-note-marker)
13827 (org-switch-to-buffer-other-window "*Org Note*")
13828 (erase-buffer)
13829 (if (memq org-log-note-how '(time state))
13830 (let (current-prefix-arg) (org-store-log-note))
13831 (let ((org-inhibit-startup t)) (org-mode))
13832 (insert (format "# Insert note for %s.
13833 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13834 (cond
13835 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13836 ((eq org-log-note-purpose 'done) "closed todo item")
13837 ((eq org-log-note-purpose 'state)
13838 (format "state change from \"%s\" to \"%s\""
13839 (or org-log-note-previous-state "")
13840 (or org-log-note-state "")))
13841 ((eq org-log-note-purpose 'reschedule)
13842 "rescheduling")
13843 ((eq org-log-note-purpose 'delschedule)
13844 "no longer scheduled")
13845 ((eq org-log-note-purpose 'redeadline)
13846 "changing deadline")
13847 ((eq org-log-note-purpose 'deldeadline)
13848 "removing deadline")
13849 ((eq org-log-note-purpose 'refile)
13850 "refiling")
13851 ((eq org-log-note-purpose 'note)
13852 "this entry")
13853 (t (error "This should not happen")))))
13854 (when org-log-note-extra (insert org-log-note-extra))
13855 (setq-local org-finish-function 'org-store-log-note)
13856 (run-hooks 'org-log-buffer-setup-hook)))
13858 (defvar org-note-abort nil) ; dynamically scoped
13859 (defun org-store-log-note ()
13860 "Finish taking a log note, and insert it to where it belongs."
13861 (let ((txt (prog1 (buffer-string)
13862 (kill-buffer)))
13863 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13864 lines)
13865 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13866 (setq txt (replace-match "" t t txt)))
13867 (when (string-match "\\s-+\\'" txt)
13868 (setq txt (replace-match "" t t txt)))
13869 (setq lines (org-split-string txt "\n"))
13870 (when (org-string-nw-p note)
13871 (setq note
13872 (org-replace-escapes
13873 note
13874 (list (cons "%u" (user-login-name))
13875 (cons "%U" user-full-name)
13876 (cons "%t" (format-time-string
13877 (org-time-stamp-format 'long 'inactive)
13878 org-log-note-effective-time))
13879 (cons "%T" (format-time-string
13880 (org-time-stamp-format 'long nil)
13881 org-log-note-effective-time))
13882 (cons "%d" (format-time-string
13883 (org-time-stamp-format nil 'inactive)
13884 org-log-note-effective-time))
13885 (cons "%D" (format-time-string
13886 (org-time-stamp-format nil nil)
13887 org-log-note-effective-time))
13888 (cons "%s" (cond
13889 ((not org-log-note-state) "")
13890 ((string-match-p org-ts-regexp
13891 org-log-note-state)
13892 (format "\"[%s]\""
13893 (substring org-log-note-state 1 -1)))
13894 (t (format "\"%s\"" org-log-note-state))))
13895 (cons "%S"
13896 (cond
13897 ((not org-log-note-previous-state) "")
13898 ((string-match-p org-ts-regexp
13899 org-log-note-previous-state)
13900 (format "\"[%s]\""
13901 (substring
13902 org-log-note-previous-state 1 -1)))
13903 (t (format "\"%s\""
13904 org-log-note-previous-state)))))))
13905 (when lines (setq note (concat note " \\\\")))
13906 (push note lines))
13907 (when (and lines (not (or current-prefix-arg org-note-abort)))
13908 (with-current-buffer (marker-buffer org-log-note-marker)
13909 (org-with-wide-buffer
13910 ;; Find location for the new note.
13911 (goto-char org-log-note-marker)
13912 (set-marker org-log-note-marker nil)
13913 (goto-char (org-log-beginning t))
13914 ;; Make sure point is at the beginning of an empty line.
13915 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13916 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13917 ;; In an existing list, add a new item at the top level.
13918 ;; Otherwise, indent line like a regular one.
13919 (let ((itemp (org-in-item-p)))
13920 (if itemp
13921 (indent-line-to
13922 (let ((struct (save-excursion
13923 (goto-char itemp) (org-list-struct))))
13924 (org-list-get-ind (org-list-get-top-point struct) struct)))
13925 (org-indent-line)))
13926 (insert (org-list-bullet-string "-") (pop lines))
13927 (let ((ind (org-list-item-body-column (line-beginning-position))))
13928 (dolist (line lines)
13929 (insert "\n")
13930 (indent-line-to ind)
13931 (insert line)))
13932 (message "Note stored")
13933 (org-back-to-heading t)
13934 (org-cycle-hide-drawers 'children))
13935 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13936 ;; from within `org-add-log-note' because `buffer-undo-list'
13937 ;; is then modified outside of `org-with-remote-undo'.
13938 (when (eq this-command 'org-agenda-todo)
13939 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13940 ;; Don't add undo information when called from `org-agenda-todo'.
13941 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13942 (set-window-configuration org-log-note-window-configuration)
13943 (with-current-buffer (marker-buffer org-log-note-return-to)
13944 (goto-char org-log-note-return-to))
13945 (move-marker org-log-note-return-to nil)
13946 (when org-log-post-message (message "%s" org-log-post-message))))
13948 (defun org-remove-empty-drawer-at (pos)
13949 "Remove an empty drawer at position POS.
13950 POS may also be a marker."
13951 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13952 (org-with-wide-buffer
13953 (goto-char pos)
13954 (let ((drawer (org-element-at-point)))
13955 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13956 (not (org-element-property :contents-begin drawer)))
13957 (delete-region (org-element-property :begin drawer)
13958 (progn (goto-char (org-element-property :end drawer))
13959 (skip-chars-backward " \r\t\n")
13960 (forward-line)
13961 (point))))))))
13963 (defvar org-ts-type nil)
13964 (defun org-sparse-tree (&optional arg type)
13965 "Create a sparse tree, prompt for the details.
13966 This command can create sparse trees. You first need to select the type
13967 of match used to create the tree:
13969 t Show all TODO entries.
13970 T Show entries with a specific TODO keyword.
13971 m Show entries selected by a tags/property match.
13972 p Enter a property name and its value (both with completion on existing
13973 names/values) and show entries with that property.
13974 r Show entries matching a regular expression (`/' can be used as well).
13975 b Show deadlines and scheduled items before a date.
13976 a Show deadlines and scheduled items after a date.
13977 d Show deadlines due within `org-deadline-warning-days'.
13978 D Show deadlines and scheduled items between a date range."
13979 (interactive "P")
13980 (setq type (or type org-sparse-tree-default-date-type))
13981 (setq org-ts-type type)
13982 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13983 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13984 \[c]ycle through date types: %s"
13985 (cl-case type
13986 (all "all timestamps")
13987 (scheduled "only scheduled")
13988 (deadline "only deadline")
13989 (active "only active timestamps")
13990 (inactive "only inactive timestamps")
13991 (closed "with a closed time-stamp")
13992 (otherwise "scheduled/deadline")))
13993 (let ((answer (read-char-exclusive)))
13994 (cl-case answer
13996 (org-sparse-tree
13998 (cadr
13999 (memq type '(nil all scheduled deadline active inactive closed)))))
14000 (?d (call-interactively 'org-check-deadlines))
14001 (?b (call-interactively 'org-check-before-date))
14002 (?a (call-interactively 'org-check-after-date))
14003 (?D (call-interactively 'org-check-dates-range))
14004 (?t (call-interactively 'org-show-todo-tree))
14005 (?T (org-show-todo-tree '(4)))
14006 (?m (call-interactively 'org-match-sparse-tree))
14007 ((?p ?P)
14008 (let* ((kwd (completing-read
14009 "Property: " (mapcar #'list (org-buffer-property-keys))))
14010 (value (completing-read
14011 "Value: " (mapcar #'list (org-property-values kwd)))))
14012 (unless (string-match "\\`{.*}\\'" value)
14013 (setq value (concat "\"" value "\"")))
14014 (org-match-sparse-tree arg (concat kwd "=" value))))
14015 ((?r ?R ?/) (call-interactively 'org-occur))
14016 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
14018 (defvar-local org-occur-highlights nil
14019 "List of overlays used for occur matches.")
14020 (defvar-local org-occur-parameters nil
14021 "Parameters of the active org-occur calls.
14022 This is a list, each call to org-occur pushes as cons cell,
14023 containing the regular expression and the callback, onto the list.
14024 The list can contain several entries if `org-occur' has been called
14025 several time with the KEEP-PREVIOUS argument. Otherwise, this list
14026 will only contain one set of parameters. When the highlights are
14027 removed (for example with `C-c C-c', or with the next edit (depending
14028 on `org-remove-highlights-with-change'), this variable is emptied
14029 as well.")
14031 (defun org-occur (regexp &optional keep-previous callback)
14032 "Make a compact tree which shows all matches of REGEXP.
14034 The tree will show the lines where the regexp matches, and any other context
14035 defined in `org-show-context-detail', which see.
14037 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
14038 done by a previous call to `org-occur' will be kept, to allow stacking of
14039 calls to this command.
14041 Optional argument CALLBACK can be a function of no argument. In this case,
14042 it is called with point at the end of the match, match data being set
14043 accordingly. Current match is shown only if the return value is non-nil.
14044 The function must neither move point nor alter narrowing."
14045 (interactive "sRegexp: \nP")
14046 (when (equal regexp "")
14047 (user-error "Regexp cannot be empty"))
14048 (unless keep-previous
14049 (org-remove-occur-highlights nil nil t))
14050 (push (cons regexp callback) org-occur-parameters)
14051 (let ((cnt 0))
14052 (save-excursion
14053 (goto-char (point-min))
14054 (when (or (not keep-previous) ; do not want to keep
14055 (not org-occur-highlights)) ; no previous matches
14056 ;; hide everything
14057 (org-overview))
14058 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
14059 (isearch-no-upper-case-p regexp t)
14060 org-occur-case-fold-search)))
14061 (while (re-search-forward regexp nil t)
14062 (when (or (not callback)
14063 (save-match-data (funcall callback)))
14064 (setq cnt (1+ cnt))
14065 (when org-highlight-sparse-tree-matches
14066 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14067 (org-show-context 'occur-tree)))))
14068 (when org-remove-highlights-with-change
14069 (add-hook 'before-change-functions 'org-remove-occur-highlights
14070 nil 'local))
14071 (unless org-sparse-tree-open-archived-trees
14072 (org-hide-archived-subtrees (point-min) (point-max)))
14073 (run-hooks 'org-occur-hook)
14074 (when (called-interactively-p 'interactive)
14075 (message "%d match(es) for regexp %s" cnt regexp))
14076 cnt))
14078 (defun org-occur-next-match (&optional n _reset)
14079 "Function for `next-error-function' to find sparse tree matches.
14080 N is the number of matches to move, when negative move backwards.
14081 This function always goes back to the starting point when no
14082 match is found."
14083 (let* ((limit (if (< n 0) (point-min) (point-max)))
14084 (search-func (if (< n 0)
14085 'previous-single-char-property-change
14086 'next-single-char-property-change))
14087 (n (abs n))
14088 (pos (point))
14090 (catch 'exit
14091 (while (setq p1 (funcall search-func (point) 'org-type))
14092 (when (equal p1 limit)
14093 (goto-char pos)
14094 (user-error "No more matches"))
14095 (when (equal (get-char-property p1 'org-type) 'org-occur)
14096 (setq n (1- n))
14097 (when (= n 0)
14098 (goto-char p1)
14099 (throw 'exit (point))))
14100 (goto-char p1))
14101 (goto-char p1)
14102 (user-error "No more matches"))))
14104 (defun org-show-context (&optional key)
14105 "Make sure point and context are visible.
14106 Optional argument KEY, when non-nil, is a symbol. See
14107 `org-show-context-detail' for allowed values and how much is to
14108 be shown."
14109 (org-show-set-visibility
14110 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14111 ((cdr (assq key org-show-context-detail)))
14112 (t (cdr (assq 'default org-show-context-detail))))))
14114 (defun org-show-set-visibility (detail)
14115 "Set visibility around point according to DETAIL.
14116 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14117 `tree', `canonical' or t. See `org-show-context-detail' for more
14118 information."
14119 ;; Show current heading and possibly its entry, following headline
14120 ;; or all children.
14121 (if (and (org-at-heading-p) (not (eq detail 'local)))
14122 (org-flag-heading nil)
14123 (org-show-entry)
14124 ;; If point is hidden within a drawer or a block, make sure to
14125 ;; expose it.
14126 (dolist (o (overlays-at (point)))
14127 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14128 (delete-overlay o)))
14129 (unless (org-before-first-heading-p)
14130 (org-with-limited-levels
14131 (cl-case detail
14132 ((tree canonical t) (org-show-children))
14133 ((nil minimal ancestors))
14134 (t (save-excursion
14135 (outline-next-heading)
14136 (org-flag-heading nil)))))))
14137 ;; Show all siblings.
14138 (when (eq detail 'lineage) (org-show-siblings))
14139 ;; Show ancestors, possibly with their children.
14140 (when (memq detail '(ancestors lineage tree canonical t))
14141 (save-excursion
14142 (while (org-up-heading-safe)
14143 (org-flag-heading nil)
14144 (when (memq detail '(canonical t)) (org-show-entry))
14145 (when (memq detail '(tree canonical t)) (org-show-children))))))
14147 (defvar org-reveal-start-hook nil
14148 "Hook run before revealing a location.")
14150 (defun org-reveal (&optional siblings)
14151 "Show current entry, hierarchy above it, and the following headline.
14153 This can be used to show a consistent set of context around
14154 locations exposed with `org-show-context'.
14156 With optional argument SIBLINGS, on each level of the hierarchy all
14157 siblings are shown. This repairs the tree structure to what it would
14158 look like when opened with hierarchical calls to `org-cycle'.
14160 With a \\[universal-argument] \\[universal-argument] prefix, \
14161 go to the parent and show the entire tree."
14162 (interactive "P")
14163 (run-hooks 'org-reveal-start-hook)
14164 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14165 ((equal siblings '(16))
14166 (save-excursion
14167 (when (org-up-heading-safe)
14168 (org-show-subtree)
14169 (run-hook-with-args 'org-cycle-hook 'subtree))))
14170 (t (org-show-set-visibility 'lineage))))
14172 (defun org-highlight-new-match (beg end)
14173 "Highlight from BEG to END and mark the highlight is an occur headline."
14174 (let ((ov (make-overlay beg end)))
14175 (overlay-put ov 'face 'secondary-selection)
14176 (overlay-put ov 'org-type 'org-occur)
14177 (push ov org-occur-highlights)))
14179 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14180 "Remove the occur highlights from the buffer.
14181 BEG and END are ignored. If NOREMOVE is nil, remove this function
14182 from the `before-change-functions' in the current buffer."
14183 (interactive)
14184 (unless org-inhibit-highlight-removal
14185 (mapc #'delete-overlay org-occur-highlights)
14186 (setq org-occur-highlights nil)
14187 (setq org-occur-parameters nil)
14188 (unless noremove
14189 (remove-hook 'before-change-functions
14190 'org-remove-occur-highlights 'local))))
14192 ;;;; Priorities
14194 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14195 "Regular expression matching the priority indicator.")
14197 (defvar org-remove-priority-next-time nil)
14199 (defun org-priority-up ()
14200 "Increase the priority of the current item."
14201 (interactive)
14202 (org-priority 'up))
14204 (defun org-priority-down ()
14205 "Decrease the priority of the current item."
14206 (interactive)
14207 (org-priority 'down))
14209 (defun org-priority (&optional action _show)
14210 "Change the priority of an item.
14211 ACTION can be `set', `up', `down', or a character."
14212 (interactive "P")
14213 (if (equal action '(4))
14214 (org-show-priority)
14215 (unless org-enable-priority-commands
14216 (user-error "Priority commands are disabled"))
14217 (setq action (or action 'set))
14218 (let (current new news have remove)
14219 (save-excursion
14220 (org-back-to-heading t)
14221 (when (looking-at org-priority-regexp)
14222 (setq current (string-to-char (match-string 2))
14223 have t))
14224 (cond
14225 ((eq action 'remove)
14226 (setq remove t new ?\ ))
14227 ((or (eq action 'set)
14228 (integerp action))
14229 (if (not (eq action 'set))
14230 (setq new action)
14231 (message "Priority %c-%c, SPC to remove: "
14232 org-highest-priority org-lowest-priority)
14233 (save-match-data
14234 (setq new (read-char-exclusive))))
14235 (when (and (= (upcase org-highest-priority) org-highest-priority)
14236 (= (upcase org-lowest-priority) org-lowest-priority))
14237 (setq new (upcase new)))
14238 (cond ((equal new ?\ ) (setq remove t))
14239 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14240 (user-error "Priority must be between `%c' and `%c'"
14241 org-highest-priority org-lowest-priority))))
14242 ((eq action 'up)
14243 (setq new (if have
14244 (1- current) ; normal cycling
14245 ;; last priority was empty
14246 (if (eq last-command this-command)
14247 org-lowest-priority ; wrap around empty to lowest
14248 ;; default
14249 (if org-priority-start-cycle-with-default
14250 org-default-priority
14251 (1- org-default-priority))))))
14252 ((eq action 'down)
14253 (setq new (if have
14254 (1+ current) ; normal cycling
14255 ;; last priority was empty
14256 (if (eq last-command this-command)
14257 org-highest-priority ; wrap around empty to highest
14258 ;; default
14259 (if org-priority-start-cycle-with-default
14260 org-default-priority
14261 (1+ org-default-priority))))))
14262 (t (user-error "Invalid action")))
14263 (when (or (< (upcase new) org-highest-priority)
14264 (> (upcase new) org-lowest-priority))
14265 (if (and (memq action '(up down))
14266 (not have) (not (eq last-command this-command)))
14267 ;; `new' is from default priority
14268 (error
14269 "The default can not be set, see `org-default-priority' why")
14270 ;; normal cycling: `new' is beyond highest/lowest priority
14271 ;; and is wrapped around to the empty priority
14272 (setq remove t)))
14273 (setq news (format "%c" new))
14274 (if have
14275 (if remove
14276 (replace-match "" t t nil 1)
14277 (replace-match news t t nil 2))
14278 (if remove
14279 (user-error "No priority cookie found in line")
14280 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14281 (if (match-end 2)
14282 (progn
14283 (goto-char (match-end 2))
14284 (insert " [#" news "]"))
14285 (goto-char (match-beginning 3))
14286 (insert "[#" news "] "))))
14287 (org-set-tags nil 'align))
14288 (if remove
14289 (message "Priority removed")
14290 (message "Priority of current item set to %s" news)))))
14292 (defun org-show-priority ()
14293 "Show the priority of the current item.
14294 This priority is composed of the main priority given with the [#A] cookies,
14295 and by additional input from the age of a schedules or deadline entry."
14296 (interactive)
14297 (let ((pri (if (eq major-mode 'org-agenda-mode)
14298 (org-get-at-bol 'priority)
14299 (save-excursion
14300 (save-match-data
14301 (beginning-of-line)
14302 (and (looking-at org-heading-regexp)
14303 (org-get-priority (match-string 0))))))))
14304 (message "Priority is %d" (if pri pri -1000))))
14306 (defun org-get-priority (s)
14307 "Find priority cookie and return priority."
14308 (save-match-data
14309 (if (functionp org-get-priority-function)
14310 (funcall org-get-priority-function)
14311 (if (not (string-match org-priority-regexp s))
14312 (* 1000 (- org-lowest-priority org-default-priority))
14313 (* 1000 (- org-lowest-priority
14314 (string-to-char (match-string 2 s))))))))
14316 ;;;; Tags
14318 (defvar org-agenda-archives-mode)
14319 (defvar org-map-continue-from nil
14320 "Position from where mapping should continue.
14321 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14323 (defvar org-scanner-tags nil
14324 "The current tag list while the tags scanner is running.")
14326 (defvar org-trust-scanner-tags nil
14327 "Should `org-get-tags-at' use the tags for the scanner.
14328 This is for internal dynamical scoping only.
14329 When this is non-nil, the function `org-get-tags-at' will return the value
14330 of `org-scanner-tags' instead of building the list by itself. This
14331 can lead to large speed-ups when the tags scanner is used in a file with
14332 many entries, and when the list of tags is retrieved, for example to
14333 obtain a list of properties. Building the tags list for each entry in such
14334 a file becomes an N^2 operation - but with this variable set, it scales
14335 as N.")
14337 (defvar org--matcher-tags-todo-only nil)
14339 (defun org-scan-tags (action matcher todo-only &optional start-level)
14340 "Scan headline tags with inheritance and produce output ACTION.
14342 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14343 or `agenda' to produce an entry list for an agenda view. It can also be
14344 a Lisp form or a function that should be called at each matched headline, in
14345 this case the return value is a list of all return values from these calls.
14347 MATCHER is a function accepting three arguments, returning
14348 a non-nil value whenever a given set of tags qualifies a headline
14349 for inclusion. See `org-make-tags-matcher' for more information.
14350 As a special case, it can also be set to t (respectively nil) in
14351 order to match all (respectively none) headline.
14353 When TODO-ONLY is non-nil, only lines with a not-done TODO
14354 keyword are included in the output.
14356 START-LEVEL can be a string with asterisks, reducing the scope to
14357 headlines matching this string."
14358 (require 'org-agenda)
14359 (let* ((re (concat "^"
14360 (if start-level
14361 ;; Get the correct level to match
14362 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14363 org-outline-regexp)
14364 " *\\(\\<\\("
14365 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14366 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14367 (props (list 'face 'default
14368 'done-face 'org-agenda-done
14369 'undone-face 'default
14370 'mouse-face 'highlight
14371 'org-not-done-regexp org-not-done-regexp
14372 'org-todo-regexp org-todo-regexp
14373 'org-complex-heading-regexp org-complex-heading-regexp
14374 'help-echo
14375 (format "mouse-2 or RET jump to org file %s"
14376 (abbreviate-file-name
14377 (or (buffer-file-name (buffer-base-buffer))
14378 (buffer-name (buffer-base-buffer)))))))
14379 (org-map-continue-from nil)
14380 lspos tags tags-list
14381 (tags-alist (list (cons 0 org-file-tags)))
14382 (llast 0) rtn rtn1 level category i txt
14383 todo marker entry priority
14384 ts-date ts-date-type ts-date-pair)
14385 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14386 (setq action (list 'lambda nil action)))
14387 (save-excursion
14388 (goto-char (point-min))
14389 (when (eq action 'sparse-tree)
14390 (org-overview)
14391 (org-remove-occur-highlights))
14392 (while (let (case-fold-search)
14393 (re-search-forward re nil t))
14394 (setq org-map-continue-from nil)
14395 (catch :skip
14396 (setq todo
14397 ;; TODO: is the 1-2 difference a bug?
14398 (when (match-end 1) (match-string-no-properties 2))
14399 tags (when (match-end 4) (match-string-no-properties 4)))
14400 (goto-char (setq lspos (match-beginning 0)))
14401 (setq level (org-reduced-level (org-outline-level))
14402 category (org-get-category))
14403 (when (eq action 'agenda)
14404 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14405 ts-date (car ts-date-pair)
14406 ts-date-type (cdr ts-date-pair)))
14407 (setq i llast llast level)
14408 ;; remove tag lists from same and sublevels
14409 (while (>= i level)
14410 (when (setq entry (assoc i tags-alist))
14411 (setq tags-alist (delete entry tags-alist)))
14412 (setq i (1- i)))
14413 ;; add the next tags
14414 (when tags
14415 (setq tags (org-split-string tags ":")
14416 tags-alist
14417 (cons (cons level tags) tags-alist)))
14418 ;; compile tags for current headline
14419 (setq tags-list
14420 (if org-use-tag-inheritance
14421 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14422 tags)
14423 org-scanner-tags tags-list)
14424 (when org-use-tag-inheritance
14425 (setcdr (car tags-alist)
14426 (mapcar (lambda (x)
14427 (setq x (copy-sequence x))
14428 (org-add-prop-inherited x))
14429 (cdar tags-alist))))
14430 (when (and tags org-use-tag-inheritance
14431 (or (not (eq t org-use-tag-inheritance))
14432 org-tags-exclude-from-inheritance))
14433 ;; Selective inheritance, remove uninherited ones.
14434 (setcdr (car tags-alist)
14435 (org-remove-uninherited-tags (cdar tags-alist))))
14436 (when (and
14438 ;; eval matcher only when the todo condition is OK
14439 (and (or (not todo-only) (member todo org-not-done-keywords))
14440 (if (functionp matcher)
14441 (let ((case-fold-search t) (org-trust-scanner-tags t))
14442 (funcall matcher todo tags-list level))
14443 matcher))
14445 ;; Call the skipper, but return t if it does not
14446 ;; skip, so that the `and' form continues evaluating.
14447 (progn
14448 (unless (eq action 'sparse-tree) (org-agenda-skip))
14451 ;; Check if timestamps are deselecting this entry
14452 (or (not todo-only)
14453 (and (member todo org-not-done-keywords)
14454 (or (not org-agenda-tags-todo-honor-ignore-options)
14455 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14457 ;; select this headline
14458 (cond
14459 ((eq action 'sparse-tree)
14460 (and org-highlight-sparse-tree-matches
14461 (org-get-heading) (match-end 0)
14462 (org-highlight-new-match
14463 (match-beginning 1) (match-end 1)))
14464 (org-show-context 'tags-tree))
14465 ((eq action 'agenda)
14466 (setq txt (org-agenda-format-item
14468 (concat
14469 (if (eq org-tags-match-list-sublevels 'indented)
14470 (make-string (1- level) ?.) "")
14471 (org-get-heading))
14472 (make-string level ?\s)
14473 category
14474 tags-list)
14475 priority (org-get-priority txt))
14476 (goto-char lspos)
14477 (setq marker (org-agenda-new-marker))
14478 (org-add-props txt props
14479 'org-marker marker 'org-hd-marker marker 'org-category category
14480 'todo-state todo
14481 'ts-date ts-date
14482 'priority priority
14483 'type (concat "tagsmatch" ts-date-type))
14484 (push txt rtn))
14485 ((functionp action)
14486 (setq org-map-continue-from nil)
14487 (save-excursion
14488 (setq rtn1 (funcall action))
14489 (push rtn1 rtn)))
14490 (t (user-error "Invalid action")))
14492 ;; if we are to skip sublevels, jump to end of subtree
14493 (unless org-tags-match-list-sublevels
14494 (org-end-of-subtree t)
14495 (backward-char 1))))
14496 ;; Get the correct position from where to continue
14497 (if org-map-continue-from
14498 (goto-char org-map-continue-from)
14499 (and (= (point) lspos) (end-of-line 1)))))
14500 (when (and (eq action 'sparse-tree)
14501 (not org-sparse-tree-open-archived-trees))
14502 (org-hide-archived-subtrees (point-min) (point-max)))
14503 (nreverse rtn)))
14505 (defun org-remove-uninherited-tags (tags)
14506 "Remove all tags that are not inherited from the list TAGS."
14507 (cond
14508 ((eq org-use-tag-inheritance t)
14509 (if org-tags-exclude-from-inheritance
14510 (org-delete-all org-tags-exclude-from-inheritance tags)
14511 tags))
14512 ((not org-use-tag-inheritance) nil)
14513 ((stringp org-use-tag-inheritance)
14514 (delq nil (mapcar
14515 (lambda (x)
14516 (if (and (string-match org-use-tag-inheritance x)
14517 (not (member x org-tags-exclude-from-inheritance)))
14518 x nil))
14519 tags)))
14520 ((listp org-use-tag-inheritance)
14521 (delq nil (mapcar
14522 (lambda (x)
14523 (if (member x org-use-tag-inheritance) x nil))
14524 tags)))))
14526 (defun org-match-sparse-tree (&optional todo-only match)
14527 "Create a sparse tree according to tags string MATCH.
14529 MATCH is a string with match syntax. It can contain a selection
14530 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14531 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14532 those. See the manual for details.
14534 If optional argument TODO-ONLY is non-nil, only select lines that
14535 are also TODO tasks."
14536 (interactive "P")
14537 (org-agenda-prepare-buffers (list (current-buffer)))
14538 (let ((org--matcher-tags-todo-only todo-only))
14539 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14540 org--matcher-tags-todo-only)))
14542 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14544 (defvar org-cached-props nil)
14545 (defun org-cached-entry-get (pom property)
14546 (if (or (eq t org-use-property-inheritance)
14547 (and (stringp org-use-property-inheritance)
14548 (let ((case-fold-search t))
14549 (string-match-p org-use-property-inheritance property)))
14550 (and (listp org-use-property-inheritance)
14551 (member-ignore-case property org-use-property-inheritance)))
14552 ;; Caching is not possible, check it directly.
14553 (org-entry-get pom property 'inherit)
14554 ;; Get all properties, so we can do complicated checks easily.
14555 (cdr (assoc-string property
14556 (or org-cached-props
14557 (setq org-cached-props (org-entry-properties pom)))
14558 t))))
14560 (defun org-global-tags-completion-table (&optional files)
14561 "Return the list of all tags in all agenda buffer/files.
14562 Optional FILES argument is a list of files which can be used
14563 instead of the agenda files."
14564 (save-excursion
14565 (org-uniquify
14566 (delq nil
14567 (apply #'append
14568 (mapcar
14569 (lambda (file)
14570 (set-buffer (find-file-noselect file))
14571 (mapcar (lambda (x)
14572 (and (stringp (car-safe x))
14573 (list (car-safe x))))
14574 (or org-current-tag-alist (org-get-buffer-tags))))
14575 (if (car-safe files) files
14576 (org-agenda-files))))))))
14578 (defun org-make-tags-matcher (match)
14579 "Create the TAGS/TODO matcher form for the selection string MATCH.
14581 Returns a cons of the selection string MATCH and a function
14582 implementing the matcher.
14584 The matcher is to be called at an Org entry, with point on the
14585 headline, and returns non-nil if the entry matches the selection
14586 string MATCH. It must be called with three arguments: the TODO
14587 keyword at the entry (or nil if none), the list of all tags at
14588 the entry including inherited ones and the reduced level of the
14589 headline. Additionally, the category of the entry, if any, must
14590 be specified as the text property `org-category' on the headline.
14592 This function sets the variable `org--matcher-tags-todo-only' to
14593 a non-nil value if the matcher restricts matching to TODO
14594 entries, otherwise it is not touched.
14596 See also `org-scan-tags'."
14597 (unless match
14598 ;; Get a new match request, with completion against the global
14599 ;; tags table and the local tags in current buffer.
14600 (let ((org-last-tags-completion-table
14601 (org-uniquify
14602 (delq nil (append (org-get-buffer-tags)
14603 (org-global-tags-completion-table))))))
14604 (setq match
14605 (completing-read
14606 "Match: "
14607 'org-tags-completion-function nil nil nil 'org-tags-history))))
14609 (let ((match0 match)
14610 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14611 (start 0)
14612 tagsmatch todomatch tagsmatcher todomatcher)
14614 ;; Expand group tags.
14615 (setq match (org-tags-expand match))
14617 ;; Check if there is a TODO part of this match, which would be the
14618 ;; part after a "/". To make sure that this slash is not part of
14619 ;; a property value to be matched against, we also check that
14620 ;; there is no / after that slash. First, find the last slash.
14621 (let ((s 0))
14622 (while (string-match "/+" match s)
14623 (setq start (match-beginning 0))
14624 (setq s (match-end 0))))
14625 (if (and (string-match "/+" match start)
14626 (not (string-match-p "\"" match start)))
14627 ;; Match contains also a TODO-matching request.
14628 (progn
14629 (setq tagsmatch (substring match 0 (match-beginning 0)))
14630 (setq todomatch (substring match (match-end 0)))
14631 (when (string-prefix-p "!" todomatch)
14632 (setq org--matcher-tags-todo-only t)
14633 (setq todomatch (substring todomatch 1)))
14634 (when (string-match "\\`\\s-*\\'" todomatch)
14635 (setq todomatch nil)))
14636 ;; Only matching tags.
14637 (setq tagsmatch match)
14638 (setq todomatch nil))
14640 ;; Make the tags matcher.
14641 (when (org-string-nw-p tagsmatch)
14642 (let ((orlist nil)
14643 (orterms (org-split-string tagsmatch "|"))
14644 term)
14645 (while (setq term (pop orterms))
14646 (while (and (equal (substring term -1) "\\") orterms)
14647 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14648 (while (string-match re term)
14649 (let* ((rest (substring term (match-end 0)))
14650 (minus (and (match-end 1)
14651 (equal (match-string 1 term) "-")))
14652 (tag (save-match-data
14653 (replace-regexp-in-string
14654 "\\\\-" "-" (match-string 2 term))))
14655 (regexp (eq (string-to-char tag) ?{))
14656 (levelp (match-end 4))
14657 (propp (match-end 5))
14659 (cond
14660 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14661 (levelp
14662 `(,(org-op-to-function (match-string 3 term))
14663 level
14664 ,(string-to-number (match-string 4 term))))
14665 (propp
14666 (let* ((gv (pcase (upcase (match-string 5 term))
14667 ("CATEGORY"
14668 '(get-text-property (point) 'org-category))
14669 ("TODO" 'todo)
14670 (p `(org-cached-entry-get nil ,p))))
14671 (pv (match-string 7 term))
14672 (regexp (eq (string-to-char pv) ?{))
14673 (strp (eq (string-to-char pv) ?\"))
14674 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14675 (po (org-op-to-function (match-string 6 term)
14676 (if timep 'time strp))))
14677 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14678 (when timep (setq pv (org-matcher-time pv)))
14679 (cond ((and regexp (eq po 'org<>))
14680 `(not (string-match ,pv (or ,gv ""))))
14681 (regexp `(string-match ,pv (or ,gv "")))
14682 (strp `(,po (or ,gv "") ,pv))
14684 `(,po
14685 (string-to-number (or ,gv ""))
14686 ,(string-to-number pv))))))
14687 (t `(member ,tag tags-list)))))
14688 (push (if minus `(not ,mm) mm) tagsmatcher)
14689 (setq term rest)))
14690 (push `(and ,@tagsmatcher) orlist)
14691 (setq tagsmatcher nil))
14692 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14694 ;; Make the TODO matcher.
14695 (when (org-string-nw-p todomatch)
14696 (let ((orlist nil))
14697 (dolist (term (org-split-string todomatch "|"))
14698 (while (string-match re term)
14699 (let* ((minus (and (match-end 1)
14700 (equal (match-string 1 term) "-")))
14701 (kwd (match-string 2 term))
14702 (regexp (eq (string-to-char kwd) ?{))
14703 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14704 `(equal todo ,kwd))))
14705 (push (if minus `(not ,mm) mm) todomatcher))
14706 (setq term (substring term (match-end 0))))
14707 (push (if (> (length todomatcher) 1)
14708 (cons 'and todomatcher)
14709 (car todomatcher))
14710 orlist)
14711 (setq todomatcher nil))
14712 (setq todomatcher (cons 'or orlist))))
14714 ;; Return the string and function of the matcher. If no
14715 ;; tags-specific or todo-specific matcher exists, match
14716 ;; everything.
14717 (let ((matcher (if (and tagsmatcher todomatcher)
14718 `(and ,tagsmatcher ,todomatcher)
14719 (or tagsmatcher todomatcher t))))
14720 (when org--matcher-tags-todo-only
14721 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14722 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14724 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14725 "Expand group tags in MATCH.
14727 This replaces every group tag in MATCH with a regexp tag search.
14728 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14729 will be replaced like this:
14731 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14732 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14733 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14735 Replacing by a regexp preserves the structure of the match.
14736 E.g., this expansion
14738 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14740 will match anything tagged with \"Lab\" and \"Home\", or tagged
14741 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14743 A group tag in MATCH can contain regular expressions of its own.
14744 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14745 will be replaced like this:
14747 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14749 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14750 assumed to be a single group tag, and the function will return
14751 the list of tags in this group.
14753 When DOWNCASE is non-nil, expand downcased TAGS."
14754 (if org-group-tags
14755 (let* ((case-fold-search t)
14756 (stable org-mode-syntax-table)
14757 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14758 (taggroups (if downcased
14759 (mapcar (lambda (tg) (mapcar #'downcase tg))
14760 taggroups)
14761 taggroups))
14762 (taggroups-keys (mapcar #'car taggroups))
14763 (return-match (if downcased (downcase match) match))
14764 (count 0)
14765 (work-already-expanded tags-already-expanded)
14766 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14767 ;; @ and _ are allowed as word-components in tags.
14768 (modify-syntax-entry ?@ "w" stable)
14769 (modify-syntax-entry ?_ "w" stable)
14770 ;; Temporarily replace regexp-expressions in the match-expression.
14771 (while (string-match "{.+?}" return-match)
14772 (cl-incf count)
14773 (push (match-string 0 return-match) regexps-in-match)
14774 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14775 (while (and taggroups-keys
14776 (with-syntax-table stable
14777 (string-match
14778 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14779 (regexp-opt taggroups-keys) "\\>\\)")
14780 return-match)))
14781 (let* ((dir (match-string 1 return-match))
14782 (tag (match-string 2 return-match))
14783 (tag (if downcased (downcase tag) tag)))
14784 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14785 (member tag work-already-expanded))
14786 (setq tags-in-group (assoc tag taggroups))
14787 (push tag work-already-expanded)
14788 ;; Recursively expand each tag in the group, if the tag hasn't
14789 ;; already been expanded. Restore the match-data after all recursive calls.
14790 (save-match-data
14791 (let (tags-expanded)
14792 (dolist (x (cdr tags-in-group))
14793 (if (and (member x taggroups-keys)
14794 (not (member x work-already-expanded)))
14795 (setq tags-expanded
14796 (delete-dups
14797 (append
14798 (org-tags-expand x t downcased
14799 work-already-expanded)
14800 tags-expanded)))
14801 (setq tags-expanded
14802 (append (list x) tags-expanded)))
14803 (setq work-already-expanded
14804 (delete-dups
14805 (append tags-expanded
14806 work-already-expanded))))
14807 (setq tags-in-group
14808 (delete-dups (cons (car tags-in-group)
14809 tags-expanded)))))
14810 ;; Filter tag-regexps from tags.
14811 (setq regexp-in-group-escaped
14812 (delq nil (mapcar (lambda (x)
14813 (if (stringp x)
14814 (and (equal "{" (substring x 0 1))
14815 (equal "}" (substring x -1))
14818 tags-in-group))
14819 regexp-in-group
14820 (mapcar (lambda (x)
14821 (substring x 1 -1))
14822 regexp-in-group-escaped)
14823 tags-in-group
14824 (delq nil (mapcar (lambda (x)
14825 (if (stringp x)
14826 (and (not (equal "{" (substring x 0 1)))
14827 (not (equal "}" (substring x -1)))
14830 tags-in-group)))
14831 ;; If single-as-list, do no more in the while-loop.
14832 (if (not single-as-list)
14833 (progn
14834 (when regexp-in-group
14835 (setq regexp-in-group
14836 (concat "\\|"
14837 (mapconcat 'identity regexp-in-group
14838 "\\|"))))
14839 (setq tags-in-group
14840 (concat dir
14841 "{\\<"
14842 (regexp-opt tags-in-group)
14843 "\\>"
14844 regexp-in-group
14845 "}"))
14846 (when (stringp tags-in-group)
14847 (org-add-props tags-in-group '(grouptag t)))
14848 (setq return-match
14849 (replace-match tags-in-group t t return-match)))
14850 (setq tags-in-group
14851 (append regexp-in-group-escaped tags-in-group))))
14852 (setq taggroups-keys (delete tag taggroups-keys))))
14853 ;; Add the regular expressions back into the match-expression again.
14854 (while regexps-in-match
14855 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14856 (pop regexps-in-match)
14857 return-match t t))
14858 (cl-decf count))
14859 (if single-as-list
14860 (if tags-in-group tags-in-group (list return-match))
14861 return-match))
14862 (if single-as-list
14863 (list (if downcased (downcase match) match))
14864 match)))
14866 (defun org-op-to-function (op &optional stringp)
14867 "Turn an operator into the appropriate function."
14868 (setq op
14869 (cond
14870 ((equal op "<" ) '(< string< org-time<))
14871 ((equal op ">" ) '(> org-string> org-time>))
14872 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14873 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14874 ((member op '("=" "==")) '(= string= org-time=))
14875 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14876 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14878 (defun org<> (a b) (not (= a b)))
14879 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14880 (defun org-string>= (a b) (not (string< a b)))
14881 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14882 (defun org-string<> (a b) (not (string= a b)))
14883 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14884 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14885 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14886 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14887 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14888 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14889 (defun org-2ft (s)
14890 "Convert S to a floating point time.
14891 If S is already a number, just return it. If it is a string, parse
14892 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14893 (cond
14894 ((numberp s) s)
14895 ((stringp s)
14896 (condition-case nil
14897 (float-time (apply 'encode-time (org-parse-time-string s)))
14898 (error 0.)))
14899 (t 0.)))
14901 (defun org-time-today ()
14902 "Time in seconds today at 0:00.
14903 Returns the float number of seconds since the beginning of the
14904 epoch to the beginning of today (00:00)."
14905 (float-time (apply 'encode-time
14906 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14908 (defun org-matcher-time (s)
14909 "Interpret a time comparison value."
14910 (save-match-data
14911 (cond
14912 ((string= s "<now>") (float-time))
14913 ((string= s "<today>") (org-time-today))
14914 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14915 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14916 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14917 (+ (org-time-today)
14918 (* (string-to-number (match-string 1 s))
14919 (cdr (assoc (match-string 2 s)
14920 '(("d" . 86400.0) ("w" . 604800.0)
14921 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14922 (t (org-2ft s)))))
14924 (defun org-match-any-p (re list)
14925 "Does re match any element of list?"
14926 (setq list (mapcar (lambda (x) (string-match re x)) list))
14927 (delq nil list))
14929 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14930 (defvar org-tags-overlay (make-overlay 1 1))
14931 (delete-overlay org-tags-overlay)
14933 (defun org-get-local-tags-at (&optional pos)
14934 "Get a list of tags defined in the current headline."
14935 (org-get-tags-at pos 'local))
14937 (defun org-get-local-tags ()
14938 "Get a list of tags defined in the current headline."
14939 (org-get-tags-at nil 'local))
14941 (defun org-get-tags-at (&optional pos local)
14942 "Get a list of all headline tags applicable at POS.
14943 POS defaults to point. If tags are inherited, the list contains
14944 the targets in the same sequence as the headlines appear, i.e.
14945 the tags of the current headline come last.
14946 When LOCAL is non-nil, only return tags from the current headline,
14947 ignore inherited ones."
14948 (interactive)
14949 (if (and org-trust-scanner-tags
14950 (or (not pos) (equal pos (point)))
14951 (not local))
14952 org-scanner-tags
14953 (let (tags ltags lastpos parent)
14954 (save-excursion
14955 (save-restriction
14956 (widen)
14957 (goto-char (or pos (point)))
14958 (save-match-data
14959 (catch 'done
14960 (condition-case nil
14961 (progn
14962 (org-back-to-heading t)
14963 (while (not (equal lastpos (point)))
14964 (setq lastpos (point))
14965 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14966 (setq ltags (org-split-string
14967 (match-string-no-properties 1) ":"))
14968 (when parent
14969 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14970 (setq tags (append
14971 (if parent
14972 (org-remove-uninherited-tags ltags)
14973 ltags)
14974 tags)))
14975 (or org-use-tag-inheritance (throw 'done t))
14976 (when local (throw 'done t))
14977 (or (org-up-heading-safe) (error nil))
14978 (setq parent t)))
14979 (error nil)))))
14980 (if local
14981 tags
14982 (reverse (delete-dups
14983 (reverse (append
14984 (org-remove-uninherited-tags
14985 org-file-tags)
14986 tags)))))))))
14988 (defun org-add-prop-inherited (s)
14989 (add-text-properties 0 (length s) '(inherited t) s)
14992 (defun org-toggle-tag (tag &optional onoff)
14993 "Toggle the tag TAG for the current line.
14994 If ONOFF is `on' or `off', don't toggle but set to this state."
14995 (let (res current)
14996 (save-excursion
14997 (org-back-to-heading t)
14998 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14999 (point-at-eol) t)
15000 (progn
15001 (setq current (match-string 1))
15002 (replace-match ""))
15003 (setq current ""))
15004 (setq current (nreverse (org-split-string current ":")))
15005 (cond
15006 ((eq onoff 'on)
15007 (setq res t)
15008 (or (member tag current) (push tag current)))
15009 ((eq onoff 'off)
15010 (or (not (member tag current)) (setq current (delete tag current))))
15011 (t (if (member tag current)
15012 (setq current (delete tag current))
15013 (setq res t)
15014 (push tag current))))
15015 (end-of-line 1)
15016 (if current
15017 (progn
15018 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
15019 (org-set-tags nil t))
15020 (delete-horizontal-space))
15021 (run-hooks 'org-after-tags-change-hook))
15022 res))
15024 (defun org--align-tags-here (to-col)
15025 "Align tags on the current headline to TO-COL.
15026 Assume point is on a headline."
15027 (let ((pos (point)))
15028 (beginning-of-line)
15029 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15030 (>= pos (match-beginning 2)))
15031 ;; No tags or point within tags: do not align.
15032 (goto-char pos)
15033 (goto-char (match-beginning 1))
15034 (let ((shift (max (- (if (>= to-col 0) to-col
15035 (- (abs to-col) (string-width (match-string 2))))
15036 (current-column))
15037 1)))
15038 (replace-match (make-string shift ?\s) nil nil nil 1)
15039 ;; Preserve initial position, if possible. In any case, stop
15040 ;; before tags.
15041 (when (< pos (point)) (goto-char pos))))))
15043 (defun org-set-tags-command (&optional arg just-align)
15044 "Call the set-tags command for the current entry."
15045 (interactive "P")
15046 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
15047 (org-set-tags arg just-align)
15048 (save-excursion
15049 (unless (and (org-region-active-p)
15050 org-loop-over-headlines-in-active-region)
15051 (org-back-to-heading t))
15052 (org-set-tags arg just-align))))
15054 (defun org-set-tags-to (data)
15055 "Set the tags of the current entry to DATA, replacing the current tags.
15056 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
15057 If DATA is nil or the empty string, any tags will be removed."
15058 (interactive "sTags: ")
15059 (setq data
15060 (cond
15061 ((eq data nil) "")
15062 ((equal data "") "")
15063 ((stringp data)
15064 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
15065 ":"))
15066 ((listp data)
15067 (concat ":" (mapconcat 'identity data ":") ":"))))
15068 (when data
15069 (save-excursion
15070 (org-back-to-heading t)
15071 (when (let ((case-fold-search nil))
15072 (looking-at org-complex-heading-regexp))
15073 (if (match-end 5)
15074 (progn
15075 (goto-char (match-beginning 5))
15076 (insert data)
15077 (delete-region (point) (point-at-eol))
15078 (org-set-tags nil 'align))
15079 (goto-char (point-at-eol))
15080 (insert " " data)
15081 (org-set-tags nil 'align)))
15082 (beginning-of-line 1)
15083 (when (looking-at ".*?\\([ \t]+\\)$")
15084 (delete-region (match-beginning 1) (match-end 1))))))
15086 (defun org-align-all-tags ()
15087 "Align the tags in all headings."
15088 (interactive)
15089 (save-excursion
15090 (or (ignore-errors (org-back-to-heading t))
15091 (outline-next-heading))
15092 (if (org-at-heading-p)
15093 (org-set-tags t)
15094 (message "No headings"))))
15096 (defvar org-indent-indentation-per-level)
15097 (defun org-set-tags (&optional arg just-align)
15098 "Set the tags for the current headline.
15099 With prefix ARG, realign all tags in headings in the current buffer.
15100 When JUST-ALIGN is non-nil, only align tags."
15101 (interactive "P")
15102 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15103 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15104 'region-start-level
15105 'region))
15106 org-loop-over-headlines-in-active-region)
15107 (org-map-entries
15108 ;; We don't use ARG and JUST-ALIGN here because these args
15109 ;; are not useful when looping over headlines.
15110 #'org-set-tags
15111 org-loop-over-headlines-in-active-region
15113 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15114 (let ((org-setting-tags t))
15115 (if arg
15116 (save-excursion
15117 (goto-char (point-min))
15118 (while (re-search-forward org-outline-regexp-bol nil t)
15119 (org-set-tags nil t)
15120 (end-of-line))
15121 (message "All tags realigned to column %d" org-tags-column))
15122 (let* ((current (org-get-tags-string))
15123 (tags
15124 (if just-align current
15125 ;; Get a new set of tags from the user.
15126 (save-excursion
15127 (let* ((seen)
15128 (table
15129 (setq
15130 org-last-tags-completion-table
15131 ;; Uniquify tags in alists, yet preserve
15132 ;; structure (i.e., keywords).
15133 (delq nil
15134 (mapcar
15135 (lambda (pair)
15136 (let ((head (car pair)))
15137 (cond ((symbolp head) pair)
15138 ((member head seen) nil)
15139 (t (push head seen)
15140 pair))))
15141 (append
15142 (or org-current-tag-alist
15143 (org-get-buffer-tags))
15144 (and
15145 org-complete-tags-always-offer-all-agenda-tags
15146 (org-global-tags-completion-table
15147 (org-agenda-files))))))))
15148 (current-tags (org-split-string current ":"))
15149 (inherited-tags
15150 (nreverse (nthcdr (length current-tags)
15151 (nreverse (org-get-tags-at))))))
15152 (replace-regexp-in-string
15153 "\\([-+&]+\\|,\\)"
15155 (if (or (eq t org-use-fast-tag-selection)
15156 (and org-use-fast-tag-selection
15157 (delq nil (mapcar #'cdr table))))
15158 (org-fast-tag-selection
15159 current-tags inherited-tags table
15160 (and org-fast-tag-selection-include-todo
15161 org-todo-key-alist))
15162 (let ((org-add-colon-after-tag-completion
15163 (< 1 (length table))))
15164 (org-trim
15165 (completing-read
15166 "Tags: "
15167 #'org-tags-completion-function
15168 nil nil current 'org-tags-history))))))))))
15170 (when org-tags-sort-function
15171 (setq tags
15172 (mapconcat
15173 #'identity
15174 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15175 org-tags-sort-function)
15176 ":")))
15178 (if (not (org-string-nw-p tags)) (setq tags "")
15179 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15180 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15182 ;; Insert new tags at the correct column.
15183 (unless (equal current tags)
15184 (save-excursion
15185 (beginning-of-line)
15186 (let ((case-fold-search nil))
15187 (looking-at org-complex-heading-regexp))
15188 ;; Remove current tags, if any.
15189 (when (match-end 5) (replace-match "" nil nil nil 5))
15190 ;; Insert new tags, if any. Otherwise, remove trailing
15191 ;; white spaces.
15192 (end-of-line)
15193 (if (not (equal tags ""))
15194 (insert " " tags)
15195 (skip-chars-backward " \t")
15196 (delete-region (point) (line-end-position)))))
15197 ;; Align tags, if any. Fix tags column if `org-indent-mode'
15198 ;; is on.
15199 (unless (equal tags "")
15200 (let* ((level (save-excursion
15201 (beginning-of-line)
15202 (skip-chars-forward "\\*")))
15203 (offset (if (bound-and-true-p org-indent-mode)
15204 (* (1- org-indent-indentation-per-level)
15205 (1- level))
15207 (tags-column
15208 (+ org-tags-column
15209 (if (> org-tags-column 0) (- offset) offset))))
15210 (org--align-tags-here tags-column))))
15211 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15213 (defun org-change-tag-in-region (beg end tag off)
15214 "Add or remove TAG for each entry in the region.
15215 This works in the agenda, and also in an Org buffer."
15216 (interactive
15217 (list (region-beginning) (region-end)
15218 (let ((org-last-tags-completion-table
15219 (if (derived-mode-p 'org-mode)
15220 (org-uniquify
15221 (delq nil (append (org-get-buffer-tags)
15222 (org-global-tags-completion-table))))
15223 (org-global-tags-completion-table))))
15224 (completing-read
15225 "Tag: " 'org-tags-completion-function nil nil nil
15226 'org-tags-history))
15227 (progn
15228 (message "[s]et or [r]emove? ")
15229 (equal (read-char-exclusive) ?r))))
15230 (when (fboundp 'deactivate-mark) (deactivate-mark))
15231 (let ((agendap (equal major-mode 'org-agenda-mode))
15232 l1 l2 m buf pos newhead (cnt 0))
15233 (goto-char end)
15234 (setq l2 (1- (org-current-line)))
15235 (goto-char beg)
15236 (setq l1 (org-current-line))
15237 (cl-loop for l from l1 to l2 do
15238 (org-goto-line l)
15239 (setq m (get-text-property (point) 'org-hd-marker))
15240 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15241 (and agendap m))
15242 (setq buf (if agendap (marker-buffer m) (current-buffer))
15243 pos (if agendap m (point)))
15244 (with-current-buffer buf
15245 (save-excursion
15246 (save-restriction
15247 (goto-char pos)
15248 (setq cnt (1+ cnt))
15249 (org-toggle-tag tag (if off 'off 'on))
15250 (setq newhead (org-get-heading)))))
15251 (and agendap (org-agenda-change-all-lines newhead m))))
15252 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15254 (defun org-tags-completion-function (string _predicate &optional flag)
15255 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15256 (confirm (lambda (x) (stringp (car x)))))
15257 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15258 (setq s1 (match-string 1 string)
15259 s2 (match-string 2 string))
15260 (setq s1 "" s2 string))
15261 (cond
15262 ((eq flag nil)
15263 ;; try completion
15264 (setq rtn (try-completion s2 ctable confirm))
15265 (when (stringp rtn)
15266 (setq rtn
15267 (concat s1 s2 (substring rtn (length s2))
15268 (if (and org-add-colon-after-tag-completion
15269 (assoc rtn ctable))
15270 ":" ""))))
15271 rtn)
15272 ((eq flag t)
15273 ;; all-completions
15274 (all-completions s2 ctable confirm))
15275 ((eq flag 'lambda)
15276 ;; exact match?
15277 (assoc s2 ctable)))))
15279 (defun org-fast-tag-insert (kwd tags face &optional end)
15280 "Insert KDW, and the TAGS, the latter with face FACE.
15281 Also insert END."
15282 (insert (format "%-12s" (concat kwd ":"))
15283 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15284 (or end "")))
15286 (defun org-fast-tag-show-exit (flag)
15287 (save-excursion
15288 (org-goto-line 3)
15289 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15290 (replace-match ""))
15291 (when flag
15292 (end-of-line 1)
15293 (org-move-to-column (- (window-width) 19) t)
15294 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15296 (defun org-set-current-tags-overlay (current prefix)
15297 "Add an overlay to CURRENT tag with PREFIX."
15298 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15299 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15300 (org-overlay-display org-tags-overlay (concat prefix s))))
15302 (defvar org-last-tag-selection-key nil)
15303 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15304 "Fast tag selection with single keys.
15305 CURRENT is the current list of tags in the headline, INHERITED is the
15306 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15307 possibly with grouping information. TODO-TABLE is a similar table with
15308 TODO keywords, should these have keys assigned to them.
15309 If the keys are nil, a-z are automatically assigned.
15310 Returns the new tags string, or nil to not change the current settings."
15311 (let* ((fulltable (append table todo-table))
15312 (maxlen (apply 'max (mapcar
15313 (lambda (x)
15314 (if (stringp (car x)) (string-width (car x)) 0))
15315 fulltable)))
15316 (buf (current-buffer))
15317 (expert (eq org-fast-tag-selection-single-key 'expert))
15318 (buffer-tags nil)
15319 (fwidth (+ maxlen 3 1 3))
15320 (ncol (/ (- (window-width) 4) fwidth))
15321 (i-face 'org-done)
15322 (c-face 'org-todo)
15323 tg cnt e c char c1 c2 ntable tbl rtn
15324 ov-start ov-end ov-prefix
15325 (exit-after-next org-fast-tag-selection-single-key)
15326 (done-keywords org-done-keywords)
15327 groups ingroup intaggroup)
15328 (save-excursion
15329 (beginning-of-line 1)
15330 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15331 (setq ov-start (match-beginning 1)
15332 ov-end (match-end 1)
15333 ov-prefix "")
15334 (setq ov-start (1- (point-at-eol))
15335 ov-end (1+ ov-start))
15336 (skip-chars-forward "^\n\r")
15337 (setq ov-prefix
15338 (concat
15339 (buffer-substring (1- (point)) (point))
15340 (if (> (current-column) org-tags-column)
15342 (make-string (- org-tags-column (current-column)) ?\ ))))))
15343 (move-overlay org-tags-overlay ov-start ov-end)
15344 (save-window-excursion
15345 (if expert
15346 (set-buffer (get-buffer-create " *Org tags*"))
15347 (delete-other-windows)
15348 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15349 (org-switch-to-buffer-other-window " *Org tags*"))
15350 (erase-buffer)
15351 (setq-local org-done-keywords done-keywords)
15352 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15353 (org-fast-tag-insert "Current" current c-face "\n\n")
15354 (org-fast-tag-show-exit exit-after-next)
15355 (org-set-current-tags-overlay current ov-prefix)
15356 (setq tbl fulltable char ?a cnt 0)
15357 (while (setq e (pop tbl))
15358 (cond
15359 ((eq (car e) :startgroup)
15360 (push '() groups) (setq ingroup t)
15361 (unless (zerop cnt)
15362 (setq cnt 0)
15363 (insert "\n"))
15364 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15365 ((eq (car e) :endgroup)
15366 (setq ingroup nil cnt 0)
15367 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15368 ((eq (car e) :startgrouptag)
15369 (setq intaggroup t)
15370 (unless (zerop cnt)
15371 (setq cnt 0)
15372 (insert "\n"))
15373 (insert "[ "))
15374 ((eq (car e) :endgrouptag)
15375 (setq intaggroup nil cnt 0)
15376 (insert "]\n"))
15377 ((equal e '(:newline))
15378 (unless (zerop cnt)
15379 (setq cnt 0)
15380 (insert "\n")
15381 (setq e (car tbl))
15382 (while (equal (car tbl) '(:newline))
15383 (insert "\n")
15384 (setq tbl (cdr tbl)))))
15385 ((equal e '(:grouptags)) (insert " : "))
15387 (setq tg (copy-sequence (car e)) c2 nil)
15388 (if (cdr e)
15389 (setq c (cdr e))
15390 ;; automatically assign a character.
15391 (setq c1 (string-to-char
15392 (downcase (substring
15393 tg (if (= (string-to-char tg) ?@) 1 0)))))
15394 (if (or (rassoc c1 ntable) (rassoc c1 table))
15395 (while (or (rassoc char ntable) (rassoc char table))
15396 (setq char (1+ char)))
15397 (setq c2 c1))
15398 (setq c (or c2 char)))
15399 (when ingroup (push tg (car groups)))
15400 (setq tg (org-add-props tg nil 'face
15401 (cond
15402 ((not (assoc tg table))
15403 (org-get-todo-face tg))
15404 ((member tg current) c-face)
15405 ((member tg inherited) i-face))))
15406 (when (equal (caar tbl) :grouptags)
15407 (org-add-props tg nil 'face 'org-tag-group))
15408 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15409 (insert "[" c "] " tg (make-string
15410 (- fwidth 4 (length tg)) ?\ ))
15411 (push (cons tg c) ntable)
15412 (when (= (cl-incf cnt) ncol)
15413 (insert "\n")
15414 (when (or ingroup intaggroup) (insert " "))
15415 (setq cnt 0)))))
15416 (setq ntable (nreverse ntable))
15417 (insert "\n")
15418 (goto-char (point-min))
15419 (unless expert (org-fit-window-to-buffer))
15420 (setq rtn
15421 (catch 'exit
15422 (while t
15423 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15424 (if (not groups) "no " "")
15425 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15426 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15427 (setq org-last-tag-selection-key c)
15428 (cond
15429 ((= c ?\r) (throw 'exit t))
15430 ((= c ?!)
15431 (setq groups (not groups))
15432 (goto-char (point-min))
15433 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15434 ((= c ?\C-c)
15435 (if (not expert)
15436 (org-fast-tag-show-exit
15437 (setq exit-after-next (not exit-after-next)))
15438 (setq expert nil)
15439 (delete-other-windows)
15440 (set-window-buffer (split-window-vertically) " *Org tags*")
15441 (org-switch-to-buffer-other-window " *Org tags*")
15442 (org-fit-window-to-buffer)))
15443 ((or (= c ?\C-g)
15444 (and (= c ?q) (not (rassoc c ntable))))
15445 (delete-overlay org-tags-overlay)
15446 (setq quit-flag t))
15447 ((= c ?\ )
15448 (setq current nil)
15449 (when exit-after-next (setq exit-after-next 'now)))
15450 ((= c ?\t)
15451 (condition-case nil
15452 (setq tg (completing-read
15453 "Tag: "
15454 (or buffer-tags
15455 (with-current-buffer buf
15456 (setq buffer-tags
15457 (org-get-buffer-tags))))))
15458 (quit (setq tg "")))
15459 (when (string-match "\\S-" tg)
15460 (cl-pushnew (list tg) buffer-tags :test #'equal)
15461 (if (member tg current)
15462 (setq current (delete tg current))
15463 (push tg current)))
15464 (when exit-after-next (setq exit-after-next 'now)))
15465 ((setq e (rassoc c todo-table) tg (car e))
15466 (with-current-buffer buf
15467 (save-excursion (org-todo tg)))
15468 (when exit-after-next (setq exit-after-next 'now)))
15469 ((setq e (rassoc c ntable) tg (car e))
15470 (if (member tg current)
15471 (setq current (delete tg current))
15472 (cl-loop for g in groups do
15473 (when (member tg g)
15474 (dolist (x g) (setq current (delete x current)))))
15475 (push tg current))
15476 (when exit-after-next (setq exit-after-next 'now))))
15478 ;; Create a sorted list
15479 (setq current
15480 (sort current
15481 (lambda (a b)
15482 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15483 (when (eq exit-after-next 'now) (throw 'exit t))
15484 (goto-char (point-min))
15485 (beginning-of-line 2)
15486 (delete-region (point) (point-at-eol))
15487 (org-fast-tag-insert "Current" current c-face)
15488 (org-set-current-tags-overlay current ov-prefix)
15489 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15490 (setq tg (match-string 1))
15491 (add-text-properties
15492 (match-beginning 1) (match-end 1)
15493 (list 'face
15494 (cond
15495 ((member tg current) c-face)
15496 ((member tg inherited) i-face)
15497 (t (get-text-property (match-beginning 1) 'face))))))
15498 (goto-char (point-min)))))
15499 (delete-overlay org-tags-overlay)
15500 (if rtn
15501 (mapconcat 'identity current ":")
15502 nil))))
15504 (defun org-get-tags-string ()
15505 "Get the TAGS string in the current headline."
15506 (unless (org-at-heading-p t)
15507 (user-error "Not on a heading"))
15508 (save-excursion
15509 (beginning-of-line 1)
15510 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15511 (match-string-no-properties 1)
15512 "")))
15514 (defun org-get-tags ()
15515 "Get the list of tags specified in the current headline."
15516 (org-split-string (org-get-tags-string) ":"))
15518 (defun org-get-buffer-tags ()
15519 "Get a table of all tags used in the buffer, for completion."
15520 (org-with-wide-buffer
15521 (goto-char (point-min))
15522 (let ((tag-re (concat org-outline-regexp-bol
15523 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15524 tags)
15525 (while (re-search-forward tag-re nil t)
15526 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15527 (push tag tags)))
15528 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15530 ;;;; The mapping API
15532 (defvar org-agenda-skip-comment-trees)
15533 (defvar org-agenda-skip-function)
15534 (defun org-map-entries (func &optional match scope &rest skip)
15535 "Call FUNC at each headline selected by MATCH in SCOPE.
15537 FUNC is a function or a lisp form. The function will be called without
15538 arguments, with the cursor positioned at the beginning of the headline.
15539 The return values of all calls to the function will be collected and
15540 returned as a list.
15542 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15543 does not need to preserve point. After evaluation, the cursor will be
15544 moved to the end of the line (presumably of the headline of the
15545 processed entry) and search continues from there. Under some
15546 circumstances, this may not produce the wanted results. For example,
15547 if you have removed (e.g. archived) the current (sub)tree it could
15548 mean that the next entry will be skipped entirely. In such cases, you
15549 can specify the position from where search should continue by making
15550 FUNC set the variable `org-map-continue-from' to the desired buffer
15551 position.
15553 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15554 Only headlines that are matched by this query will be considered during
15555 the iteration. When MATCH is nil or t, all headlines will be
15556 visited by the iteration.
15558 SCOPE determines the scope of this command. It can be any of:
15560 nil The current buffer, respecting the restriction if any
15561 tree The subtree started with the entry at point
15562 region The entries within the active region, if any
15563 region-start-level
15564 The entries within the active region, but only those at
15565 the same level than the first one.
15566 file The current buffer, without restriction
15567 file-with-archives
15568 The current buffer, and any archives associated with it
15569 agenda All agenda files
15570 agenda-with-archives
15571 All agenda files with any archive files associated with them
15572 \(file1 file2 ...)
15573 If this is a list, all files in the list will be scanned
15575 The remaining args are treated as settings for the skipping facilities of
15576 the scanner. The following items can be given here:
15578 archive skip trees with the archive tag
15579 comment skip trees with the COMMENT keyword
15580 function or Emacs Lisp form:
15581 will be used as value for `org-agenda-skip-function', so
15582 whenever the function returns a position, FUNC will not be
15583 called for that entry and search will continue from the
15584 position returned
15586 If your function needs to retrieve the tags including inherited tags
15587 at the *current* entry, you can use the value of the variable
15588 `org-scanner-tags' which will be much faster than getting the value
15589 with `org-get-tags-at'. If your function gets properties with
15590 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15591 to t around the call to `org-entry-properties' to get the same speedup.
15592 Note that if your function moves around to retrieve tags and properties at
15593 a *different* entry, you cannot use these techniques."
15594 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15595 (not (org-region-active-p)))
15596 (let* ((org-agenda-archives-mode nil) ; just to make sure
15597 (org-agenda-skip-archived-trees (memq 'archive skip))
15598 (org-agenda-skip-comment-trees (memq 'comment skip))
15599 (org-agenda-skip-function
15600 (car (org-delete-all '(comment archive) skip)))
15601 (org-tags-match-list-sublevels t)
15602 (start-level (eq scope 'region-start-level))
15603 matcher res
15604 org-todo-keywords-for-agenda
15605 org-done-keywords-for-agenda
15606 org-todo-keyword-alist-for-agenda
15607 org-tag-alist-for-agenda
15608 org--matcher-tags-todo-only)
15610 (cond
15611 ((eq match t) (setq matcher t))
15612 ((eq match nil) (setq matcher t))
15613 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15615 (save-excursion
15616 (save-restriction
15617 (cond ((eq scope 'tree)
15618 (org-back-to-heading t)
15619 (org-narrow-to-subtree)
15620 (setq scope nil))
15621 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15622 (org-region-active-p))
15623 ;; If needed, set start-level to a string like "2"
15624 (when start-level
15625 (save-excursion
15626 (goto-char (region-beginning))
15627 (unless (org-at-heading-p) (outline-next-heading))
15628 (setq start-level (org-current-level))))
15629 (narrow-to-region (region-beginning)
15630 (save-excursion
15631 (goto-char (region-end))
15632 (unless (and (bolp) (org-at-heading-p))
15633 (outline-next-heading))
15634 (point)))
15635 (setq scope nil)))
15637 (if (not scope)
15638 (progn
15639 (org-agenda-prepare-buffers
15640 (and buffer-file-name (list buffer-file-name)))
15641 (setq res
15642 (org-scan-tags
15643 func matcher org--matcher-tags-todo-only start-level)))
15644 ;; Get the right scope
15645 (cond
15646 ((and scope (listp scope) (symbolp (car scope)))
15647 (setq scope (eval scope)))
15648 ((eq scope 'agenda)
15649 (setq scope (org-agenda-files t)))
15650 ((eq scope 'agenda-with-archives)
15651 (setq scope (org-agenda-files t))
15652 (setq scope (org-add-archive-files scope)))
15653 ((eq scope 'file)
15654 (setq scope (and buffer-file-name (list buffer-file-name))))
15655 ((eq scope 'file-with-archives)
15656 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15657 (org-agenda-prepare-buffers scope)
15658 (dolist (file scope)
15659 (with-current-buffer (org-find-base-buffer-visiting file)
15660 (org-with-wide-buffer
15661 (goto-char (point-min))
15662 (setq res
15663 (append
15665 (org-scan-tags
15666 func matcher org--matcher-tags-todo-only)))))))))
15667 res)))
15669 ;;; Properties API
15671 (defconst org-special-properties
15672 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15673 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15674 "The special properties valid in Org mode.
15675 These are properties that are not defined in the property drawer,
15676 but in some other way.")
15678 (defconst org-default-properties
15679 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15680 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15681 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15682 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15683 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15684 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15685 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15686 "Some properties that are used by Org mode for various purposes.
15687 Being in this list makes sure that they are offered for completion.")
15689 (defun org--valid-property-p (property)
15690 "Non nil when string PROPERTY is a valid property name."
15691 (not
15692 (or (equal property "")
15693 (string-match-p "\\s-" property))))
15695 (defun org--update-property-plist (key val props)
15696 "Associate KEY to VAL in alist PROPS.
15697 Modifications are made by side-effect. Return new alist."
15698 (let* ((appending (string= (substring key -1) "+"))
15699 (key (if appending (substring key 0 -1) key))
15700 (old (assoc-string key props t)))
15701 (if (not old) (cons (cons key val) props)
15702 (setcdr old (if appending (concat (cdr old) " " val) val))
15703 props)))
15705 (defun org-get-property-block (&optional beg force)
15706 "Return the (beg . end) range of the body of the property drawer.
15707 BEG is the beginning of the current subtree, or of the part
15708 before the first headline. If it is not given, it will be found.
15709 If the drawer does not exist, create it if FORCE is non-nil, or
15710 return nil."
15711 (org-with-wide-buffer
15712 (when beg (goto-char beg))
15713 (unless (org-before-first-heading-p)
15714 (let ((beg (cond (beg)
15715 ((or (not (featurep 'org-inlinetask))
15716 (org-inlinetask-in-task-p))
15717 (org-back-to-heading t))
15718 (t (org-with-limited-levels (org-back-to-heading t))))))
15719 (forward-line)
15720 (when (looking-at-p org-planning-line-re) (forward-line))
15721 (cond ((looking-at org-property-drawer-re)
15722 (forward-line)
15723 (cons (point) (progn (goto-char (match-end 0))
15724 (line-beginning-position))))
15725 (force
15726 (goto-char beg)
15727 (org-insert-property-drawer)
15728 (let ((pos (save-excursion (search-forward ":END:")
15729 (line-beginning-position))))
15730 (cons pos pos))))))))
15732 (defun org-at-property-p ()
15733 "Non-nil when point is inside a property drawer.
15734 See `org-property-re' for match data, if applicable."
15735 (save-excursion
15736 (beginning-of-line)
15737 (and (looking-at org-property-re)
15738 (let ((property-drawer (save-match-data (org-get-property-block))))
15739 (and property-drawer
15740 (>= (point) (car property-drawer))
15741 (< (point) (cdr property-drawer)))))))
15743 (defun org-property-action ()
15744 "Do an action on properties."
15745 (interactive)
15746 (unless (org-at-property-p) (user-error "Not at a property"))
15747 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15748 (let ((c (read-char-exclusive)))
15749 (cl-case c
15750 (?s (call-interactively #'org-set-property))
15751 (?d (call-interactively #'org-delete-property))
15752 (?D (call-interactively #'org-delete-property-globally))
15753 (?c (call-interactively #'org-compute-property-at-point))
15754 (otherwise (user-error "No such property action %c" c)))))
15756 (defun org-inc-effort ()
15757 "Increment the value of the effort property in the current entry."
15758 (interactive)
15759 (org-set-effort nil t))
15761 (defvar org-clock-effort) ; Defined in org-clock.el.
15762 (defvar org-clock-current-task) ; Defined in org-clock.el.
15763 (defun org-set-effort (&optional value increment)
15764 "Set the effort property of the current entry.
15765 With numerical prefix arg, use the nth allowed value, 0 stands for the
15766 10th allowed value.
15768 When INCREMENT is non-nil, set the property to the next allowed value."
15769 (interactive "P")
15770 (when (equal value 0) (setq value 10))
15771 (let* ((completion-ignore-case t)
15772 (prop org-effort-property)
15773 (cur (org-entry-get nil prop))
15774 (allowed (org-property-get-allowed-values nil prop 'table))
15775 (existing (mapcar 'list (org-property-values prop)))
15776 (heading (nth 4 (org-heading-components)))
15778 (val (cond
15779 ((stringp value) value)
15780 ((and allowed (integerp value))
15781 (or (car (nth (1- value) allowed))
15782 (car (org-last allowed))))
15783 ((and allowed increment)
15784 (or (cl-caadr (member (list cur) allowed))
15785 (user-error "Allowed effort values are not set")))
15786 (allowed
15787 (message "Select 1-9,0, [RET%s]: %s"
15788 (if cur (concat "=" cur) "")
15789 (mapconcat 'car allowed " "))
15790 (setq rpl (read-char-exclusive))
15791 (if (equal rpl ?\r)
15793 (setq rpl (- rpl ?0))
15794 (when (equal rpl 0) (setq rpl 10))
15795 (if (and (> rpl 0) (<= rpl (length allowed)))
15796 (car (nth (1- rpl) allowed))
15797 (org-completing-read "Effort: " allowed nil))))
15799 (org-completing-read
15800 (concat "Effort" (and cur (string-match "\\S-" cur)
15801 (concat " [" cur "]"))
15802 ": ")
15803 existing nil nil "" nil cur)))))
15804 (unless (equal (org-entry-get nil prop) val)
15805 (org-entry-put nil prop val))
15806 (org-refresh-property
15807 '((effort . identity)
15808 (effort-minutes . org-duration-string-to-minutes))
15809 val)
15810 (when (equal heading (bound-and-true-p org-clock-current-task))
15811 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15812 (org-clock-update-mode-line))
15813 (message "%s is now %s" prop val)))
15815 (defun org-entry-properties (&optional pom which)
15816 "Get all properties of the current entry.
15818 When POM is a buffer position, get all properties from the entry
15819 there instead.
15821 This includes the TODO keyword, the tags, time strings for
15822 deadline, scheduled, and clocking, and any additional properties
15823 defined in the entry.
15825 If WHICH is nil or `all', get all properties. If WHICH is
15826 `special' or `standard', only get that subclass. If WHICH is
15827 a string, only get that property.
15829 Return value is an alist. Keys are properties, as upcased
15830 strings."
15831 (org-with-point-at pom
15832 (when (and (derived-mode-p 'org-mode)
15833 (ignore-errors (org-back-to-heading t)))
15834 (catch 'exit
15835 (let* ((beg (point))
15836 (specific (and (stringp which) (upcase which)))
15837 (which (cond ((not specific) which)
15838 ((member specific org-special-properties) 'special)
15839 (t 'standard)))
15840 props)
15841 ;; Get the special properties, like TODO and TAGS.
15842 (when (memq which '(nil all special))
15843 (when (or (not specific) (string= specific "CLOCKSUM"))
15844 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15845 (when clocksum
15846 (push (cons "CLOCKSUM"
15847 (org-minutes-to-clocksum-string clocksum))
15848 props)))
15849 (when specific (throw 'exit props)))
15850 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15851 (let ((clocksumt (get-text-property (point)
15852 :org-clock-minutes-today)))
15853 (when clocksumt
15854 (push (cons "CLOCKSUM_T"
15855 (org-minutes-to-clocksum-string clocksumt))
15856 props)))
15857 (when specific (throw 'exit props)))
15858 (when (or (not specific) (string= specific "ITEM"))
15859 (let ((case-fold-search nil))
15860 (when (looking-at org-complex-heading-regexp)
15861 (push (cons "ITEM"
15862 (let ((title (match-string-no-properties 4)))
15863 (if (org-string-nw-p title)
15864 (org-remove-tabs title)
15865 "")))
15866 props)))
15867 (when specific (throw 'exit props)))
15868 (when (or (not specific) (string= specific "TODO"))
15869 (let ((case-fold-search nil))
15870 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15871 (push (cons "TODO" (match-string-no-properties 2)) props)))
15872 (when specific (throw 'exit props)))
15873 (when (or (not specific) (string= specific "PRIORITY"))
15874 (push (cons "PRIORITY"
15875 (if (looking-at org-priority-regexp)
15876 (match-string-no-properties 2)
15877 (char-to-string org-default-priority)))
15878 props)
15879 (when specific (throw 'exit props)))
15880 (when (or (not specific) (string= specific "FILE"))
15881 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15882 props)
15883 (when specific (throw 'exit props)))
15884 (when (or (not specific) (string= specific "TAGS"))
15885 (let ((value (org-string-nw-p (org-get-tags-string))))
15886 (when value (push (cons "TAGS" value) props)))
15887 (when specific (throw 'exit props)))
15888 (when (or (not specific) (string= specific "ALLTAGS"))
15889 (let ((value (org-get-tags-at)))
15890 (when value
15891 (push (cons "ALLTAGS"
15892 (format ":%s:" (mapconcat #'identity value ":")))
15893 props)))
15894 (when specific (throw 'exit props)))
15895 (when (or (not specific) (string= specific "BLOCKED"))
15896 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15897 (when specific (throw 'exit props)))
15898 (when (or (not specific)
15899 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15900 (forward-line)
15901 (when (looking-at-p org-planning-line-re)
15902 (end-of-line)
15903 (let ((bol (line-beginning-position))
15904 ;; Backward compatibility: time keywords used to
15905 ;; be configurable (before 8.3). Make sure we
15906 ;; get the correct keyword.
15907 (key-assoc `(("CLOSED" . ,org-closed-string)
15908 ("DEADLINE" . ,org-deadline-string)
15909 ("SCHEDULED" . ,org-scheduled-string))))
15910 (dolist (pair (if specific (list (assoc specific key-assoc))
15911 key-assoc))
15912 (save-excursion
15913 (when (search-backward (cdr pair) bol t)
15914 (goto-char (match-end 0))
15915 (skip-chars-forward " \t")
15916 (and (looking-at org-ts-regexp-both)
15917 (push (cons (car pair)
15918 (match-string-no-properties 0))
15919 props)))))))
15920 (when specific (throw 'exit props)))
15921 (when (or (not specific)
15922 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15923 (let ((find-ts
15924 (lambda (end ts)
15925 ;; Fix next time-stamp before END. TS is the
15926 ;; list of time-stamps found so far.
15927 (let ((ts ts)
15928 (regexp (cond
15929 ((string= specific "TIMESTAMP")
15930 org-ts-regexp)
15931 ((string= specific "TIMESTAMP_IA")
15932 org-ts-regexp-inactive)
15933 ((assoc "TIMESTAMP_IA" ts)
15934 org-ts-regexp)
15935 ((assoc "TIMESTAMP" ts)
15936 org-ts-regexp-inactive)
15937 (t org-ts-regexp-both))))
15938 (catch 'next
15939 (while (re-search-forward regexp end t)
15940 (backward-char)
15941 (let ((object (org-element-context)))
15942 ;; Accept to match timestamps in node
15943 ;; properties, too.
15944 (when (memq (org-element-type object)
15945 '(node-property timestamp))
15946 (let ((type
15947 (org-element-property :type object)))
15948 (cond
15949 ((and (memq type '(active active-range))
15950 (not (equal specific "TIMESTAMP_IA")))
15951 (unless (assoc "TIMESTAMP" ts)
15952 (push (cons "TIMESTAMP"
15953 (org-element-property
15954 :raw-value object))
15956 (when specific (throw 'exit ts))))
15957 ((and (memq type '(inactive inactive-range))
15958 (not (string= specific "TIMESTAMP")))
15959 (unless (assoc "TIMESTAMP_IA" ts)
15960 (push (cons "TIMESTAMP_IA"
15961 (org-element-property
15962 :raw-value object))
15964 (when specific (throw 'exit ts))))))
15965 ;; Both timestamp types are found,
15966 ;; move to next part.
15967 (when (= (length ts) 2) (throw 'next ts)))))
15968 ts)))))
15969 (goto-char beg)
15970 ;; First look for timestamps within headline.
15971 (let ((ts (funcall find-ts (line-end-position) nil)))
15972 (if (= (length ts) 2) (setq props (nconc ts props))
15973 (forward-line)
15974 ;; Then find timestamps in the section, skipping
15975 ;; planning line.
15976 (when (looking-at-p org-planning-line-re)
15977 (forward-line))
15978 (let ((end (save-excursion (outline-next-heading))))
15979 (setq props (nconc (funcall find-ts end ts) props))))))))
15980 ;; Get the standard properties, like :PROP:.
15981 (when (memq which '(nil all standard))
15982 ;; If we are looking after a specific property, delegate
15983 ;; to `org-entry-get', which is faster. However, make an
15984 ;; exception for "CATEGORY", since it can be also set
15985 ;; through keywords (i.e. #+CATEGORY).
15986 (if (and specific (not (equal specific "CATEGORY")))
15987 (let ((value (org-entry-get beg specific nil t)))
15988 (throw 'exit (and value (list (cons specific value)))))
15989 (let ((range (org-get-property-block beg)))
15990 (when range
15991 (let ((end (cdr range)) seen-base)
15992 (goto-char (car range))
15993 ;; Unlike to `org--update-property-plist', we
15994 ;; handle the case where base values is found
15995 ;; after its extension. We also forbid standard
15996 ;; properties to be named as special properties.
15997 (while (re-search-forward org-property-re end t)
15998 (let* ((key (upcase (match-string-no-properties 2)))
15999 (extendp (string-match-p "\\+\\'" key))
16000 (key-base (if extendp (substring key 0 -1) key))
16001 (value (match-string-no-properties 3)))
16002 (cond
16003 ((member-ignore-case key-base org-special-properties))
16004 (extendp
16005 (setq props
16006 (org--update-property-plist key value props)))
16007 ((member key seen-base))
16008 (t (push key seen-base)
16009 (let ((p (assoc-string key props t)))
16010 (if p (setcdr p (concat value " " (cdr p)))
16011 (push (cons key value) props))))))))))))
16012 (unless (assoc "CATEGORY" props)
16013 (push (cons "CATEGORY" (org-get-category beg)) props)
16014 (when (string= specific "CATEGORY") (throw 'exit props)))
16015 ;; Return value.
16016 props)))))
16018 (defun org-property--local-values (property literal-nil)
16019 "Return value for PROPERTY in current entry.
16020 Value is a list whose car is the base value for PROPERTY and cdr
16021 a list of accumulated values. Return nil if neither is found in
16022 the entry. Also return nil when PROPERTY is set to \"nil\",
16023 unless LITERAL-NIL is non-nil."
16024 (let ((range (org-get-property-block)))
16025 (when range
16026 (goto-char (car range))
16027 (let* ((case-fold-search t)
16028 (end (cdr range))
16029 (value
16030 ;; Base value.
16031 (save-excursion
16032 (let ((v (and (re-search-forward
16033 (org-re-property property nil t) end t)
16034 (match-string-no-properties 3))))
16035 (list (if literal-nil v (org-not-nil v)))))))
16036 ;; Find additional values.
16037 (let* ((property+ (org-re-property (concat property "+") nil t)))
16038 (while (re-search-forward property+ end t)
16039 (push (match-string-no-properties 3) value)))
16040 ;; Return final values.
16041 (and (not (equal value '(nil))) (nreverse value))))))
16043 (defun org-entry-get (pom property &optional inherit literal-nil)
16044 "Get value of PROPERTY for entry or content at point-or-marker POM.
16046 If INHERIT is non-nil and the entry does not have the property,
16047 then also check higher levels of the hierarchy. If INHERIT is
16048 the symbol `selective', use inheritance only if the setting in
16049 `org-use-property-inheritance' selects PROPERTY for inheritance.
16051 If the property is present but empty, the return value is the
16052 empty string. If the property is not present at all, nil is
16053 returned. In any other case, return the value as a string.
16054 Search is case-insensitive.
16056 If LITERAL-NIL is set, return the string value \"nil\" as
16057 a string, do not interpret it as the list atom nil. This is used
16058 for inheritance when a \"nil\" value can supersede a non-nil
16059 value higher up the hierarchy."
16060 (org-with-point-at pom
16061 (cond
16062 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
16063 ;; We need a special property. Use `org-entry-properties' to
16064 ;; retrieve it, but specify the wanted property.
16065 (cdr (assoc-string property (org-entry-properties nil property))))
16066 ((and inherit
16067 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
16068 (org-entry-get-with-inheritance property literal-nil))
16070 (let* ((local (org-property--local-values property literal-nil))
16071 (value (and local (mapconcat #'identity (delq nil local) " "))))
16072 (if literal-nil value (org-not-nil value)))))))
16074 (defun org-property-or-variable-value (var &optional inherit)
16075 "Check if there is a property fixing the value of VAR.
16076 If yes, return this value. If not, return the current value of the variable."
16077 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16078 (if (and prop (stringp prop) (string-match "\\S-" prop))
16079 (read prop)
16080 (symbol-value var))))
16082 (defun org-entry-delete (pom property)
16083 "Delete PROPERTY from entry at point-or-marker POM.
16084 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16085 non-nil when a property was removed."
16086 (unless (member property org-special-properties)
16087 (org-with-point-at pom
16088 (let ((range (org-get-property-block)))
16089 (when range
16090 (let* ((begin (car range))
16091 (origin (cdr range))
16092 (end (copy-marker origin))
16093 (re (org-re-property
16094 (concat (regexp-quote property) "\\+?") t t)))
16095 (goto-char begin)
16096 (while (re-search-forward re end t)
16097 (delete-region (match-beginning 0) (line-beginning-position 2)))
16098 ;; If drawer is empty, remove it altogether.
16099 (when (= begin end)
16100 (delete-region (line-beginning-position 0)
16101 (line-beginning-position 2)))
16102 ;; Return non-nil if some property was removed.
16103 (prog1 (/= end origin) (set-marker end nil))))))))
16105 ;; Multi-values properties are properties that contain multiple values
16106 ;; These values are assumed to be single words, separated by whitespace.
16107 (defun org-entry-add-to-multivalued-property (pom property value)
16108 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16109 (let* ((old (org-entry-get pom property))
16110 (values (and old (org-split-string old "[ \t]"))))
16111 (setq value (org-entry-protect-space value))
16112 (unless (member value values)
16113 (setq values (append values (list value)))
16114 (org-entry-put pom property
16115 (mapconcat 'identity values " ")))))
16117 (defun org-entry-remove-from-multivalued-property (pom property value)
16118 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16119 (let* ((old (org-entry-get pom property))
16120 (values (and old (org-split-string old "[ \t]"))))
16121 (setq value (org-entry-protect-space value))
16122 (when (member value values)
16123 (setq values (delete value values))
16124 (org-entry-put pom property
16125 (mapconcat 'identity values " ")))))
16127 (defun org-entry-member-in-multivalued-property (pom property value)
16128 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16129 (let* ((old (org-entry-get pom property))
16130 (values (and old (org-split-string old "[ \t]"))))
16131 (setq value (org-entry-protect-space value))
16132 (member value values)))
16134 (defun org-entry-get-multivalued-property (pom property)
16135 "Return a list of values in a multivalued property."
16136 (let* ((value (org-entry-get pom property))
16137 (values (and value (org-split-string value "[ \t]"))))
16138 (mapcar 'org-entry-restore-space values)))
16140 (defun org-entry-put-multivalued-property (pom property &rest values)
16141 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16142 VALUES should be a list of strings. Spaces will be protected."
16143 (org-entry-put pom property
16144 (mapconcat 'org-entry-protect-space values " "))
16145 (let* ((value (org-entry-get pom property))
16146 (values (and value (org-split-string value "[ \t]"))))
16147 (mapcar 'org-entry-restore-space values)))
16149 (defun org-entry-protect-space (s)
16150 "Protect spaces and newline in string S."
16151 (while (string-match " " s)
16152 (setq s (replace-match "%20" t t s)))
16153 (while (string-match "\n" s)
16154 (setq s (replace-match "%0A" t t s)))
16157 (defun org-entry-restore-space (s)
16158 "Restore spaces and newline in string S."
16159 (while (string-match "%20" s)
16160 (setq s (replace-match " " t t s)))
16161 (while (string-match "%0A" s)
16162 (setq s (replace-match "\n" t t s)))
16165 (defvar org-entry-property-inherited-from (make-marker)
16166 "Marker pointing to the entry from where a property was inherited.
16167 Each call to `org-entry-get-with-inheritance' will set this marker to the
16168 location of the entry where the inheritance search matched. If there was
16169 no match, the marker will point nowhere.
16170 Note that also `org-entry-get' calls this function, if the INHERIT flag
16171 is set.")
16173 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16174 "Get PROPERTY of entry or content at point, search higher levels if needed.
16175 The search will stop at the first ancestor which has the property defined.
16176 If the value found is \"nil\", return nil to show that the property
16177 should be considered as undefined (this is the meaning of nil here).
16178 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16179 (move-marker org-entry-property-inherited-from nil)
16180 (org-with-wide-buffer
16181 (let (value)
16182 (catch 'exit
16183 (while t
16184 (let ((v (org-property--local-values property literal-nil)))
16185 (when v
16186 (setq value
16187 (concat (mapconcat #'identity (delq nil v) " ")
16188 (and value " ")
16189 value)))
16190 (cond
16191 ((car v)
16192 (org-back-to-heading t)
16193 (move-marker org-entry-property-inherited-from (point))
16194 (throw 'exit nil))
16195 ((org-up-heading-safe))
16197 (let ((global
16198 (cdr (or (assoc-string property org-file-properties t)
16199 (assoc-string property org-global-properties t)
16200 (assoc-string property org-global-properties-fixed t)))))
16201 (cond ((not global))
16202 (value (setq value (concat global " " value)))
16203 (t (setq value global))))
16204 (throw 'exit nil))))))
16205 (if literal-nil value (org-not-nil value)))))
16207 (defvar org-property-changed-functions nil
16208 "Hook called when the value of a property has changed.
16209 Each hook function should accept two arguments, the name of the property
16210 and the new value.")
16212 (defun org-entry-put (pom property value)
16213 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16215 If the value is nil, it is converted to the empty string. If it
16216 is not a string, an error is raised. Also raise an error on
16217 invalid property names.
16219 PROPERTY can be any regular property (see
16220 `org-special-properties'). It can also be \"TODO\",
16221 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16223 For the last two properties, VALUE may have any of the special
16224 values \"earlier\" and \"later\". The function then increases or
16225 decreases scheduled or deadline date by one day."
16226 (cond ((null value) (setq value ""))
16227 ((not (stringp value)) (error "Properties values should be strings"))
16228 ((not (org--valid-property-p property))
16229 (user-error "Invalid property name: \"%s\"" property)))
16230 (org-with-point-at pom
16231 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16232 (org-back-to-heading t)
16233 (org-with-limited-levels (org-back-to-heading t)))
16234 (let ((beg (point)))
16235 (cond
16236 ((equal property "TODO")
16237 (cond ((not (org-string-nw-p value)) (setq value 'none))
16238 ((not (member value org-todo-keywords-1))
16239 (user-error "\"%s\" is not a valid TODO state" value)))
16240 (org-todo value)
16241 (org-set-tags nil 'align))
16242 ((equal property "PRIORITY")
16243 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16244 (org-set-tags nil 'align))
16245 ((equal property "SCHEDULED")
16246 (forward-line)
16247 (if (and (looking-at-p org-planning-line-re)
16248 (re-search-forward
16249 org-scheduled-time-regexp (line-end-position) t))
16250 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16251 ((string= value "later") (org-timestamp-change 1 'day))
16252 ((string= value "") (org-schedule '(4)))
16253 (t (org-schedule nil value)))
16254 (if (member value '("earlier" "later" ""))
16255 (call-interactively #'org-schedule)
16256 (org-schedule nil value))))
16257 ((equal property "DEADLINE")
16258 (forward-line)
16259 (if (and (looking-at-p org-planning-line-re)
16260 (re-search-forward
16261 org-deadline-time-regexp (line-end-position) t))
16262 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16263 ((string= value "later") (org-timestamp-change 1 'day))
16264 ((string= value "") (org-deadline '(4)))
16265 (t (org-deadline nil value)))
16266 (if (member value '("earlier" "later" ""))
16267 (call-interactively #'org-deadline)
16268 (org-deadline nil value))))
16269 ((member property org-special-properties)
16270 (error "The %s property cannot be set with `org-entry-put'" property))
16272 (let* ((range (org-get-property-block beg 'force))
16273 (end (cdr range))
16274 (case-fold-search t))
16275 (goto-char (car range))
16276 (if (re-search-forward (org-re-property property nil t) end t)
16277 (progn (delete-region (match-beginning 0) (match-end 0))
16278 (goto-char (match-beginning 0)))
16279 (goto-char end)
16280 (insert "\n")
16281 (backward-char))
16282 (insert ":" property ":")
16283 (when value (insert " " value))
16284 (org-indent-line)))))
16285 (run-hook-with-args 'org-property-changed-functions property value)))
16287 (defun org-buffer-property-keys
16288 (&optional specials defaults columns ignore-malformed)
16289 "Get all property keys in the current buffer.
16291 When SPECIALS is non-nil, also list the special properties that
16292 reflect things like tags and TODO state.
16294 When DEFAULTS is non-nil, also include properties that has
16295 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16296 DESCRIPTION, LOCATION, and LOGGING and others.
16298 When COLUMNS in non-nil, also include property names given in
16299 COLUMN formats in the current buffer.
16301 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16302 automatically performed, such drawers will be silently ignored."
16303 (let ((case-fold-search t)
16304 (props (append
16305 (and specials org-special-properties)
16306 (and defaults (cons org-effort-property org-default-properties))
16307 nil)))
16308 (org-with-wide-buffer
16309 (goto-char (point-min))
16310 (while (re-search-forward org-property-start-re nil t)
16311 (let ((range (org-get-property-block)))
16312 (catch 'skip
16313 (unless range
16314 (when (and (not ignore-malformed)
16315 (not (org-before-first-heading-p))
16316 (y-or-n-p (format "Malformed drawer at %d, repair?"
16317 (line-beginning-position))))
16318 (org-get-property-block nil t))
16319 (throw 'skip nil))
16320 (goto-char (car range))
16321 (let ((begin (car range))
16322 (end (cdr range)))
16323 ;; Make sure that found property block is not located
16324 ;; before current point, as it would generate an infloop.
16325 ;; It can happen, for example, in the following
16326 ;; situation:
16328 ;; * Headline
16329 ;; :PROPERTIES:
16330 ;; ...
16331 ;; :END:
16332 ;; *************** Inlinetask
16333 ;; #+BEGIN_EXAMPLE
16334 ;; :PROPERTIES:
16335 ;; #+END_EXAMPLE
16337 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16338 (while (< (point) end)
16339 (let ((p (progn (looking-at org-property-re)
16340 (match-string-no-properties 2))))
16341 ;; Only add true property name, not extension symbol.
16342 (push (if (not (string-match-p "\\+\\'" p)) p
16343 (substring p 0 -1))
16344 props))
16345 (forward-line))))
16346 (outline-next-heading)))
16347 (when columns
16348 (goto-char (point-min))
16349 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16350 (let ((element (org-element-at-point)))
16351 (when (memq (org-element-type element) '(keyword node-property))
16352 (let ((value (org-element-property :value element))
16353 (start 0))
16354 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16355 (setq start (match-end 0))
16356 (let ((p (match-string-no-properties 1 value)))
16357 (unless (member-ignore-case p org-special-properties)
16358 (push p props))))))))))
16359 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16361 (defun org-property-values (key)
16362 "List all non-nil values of property KEY in current buffer."
16363 (org-with-wide-buffer
16364 (goto-char (point-min))
16365 (let ((case-fold-search t)
16366 (re (org-re-property key))
16367 values)
16368 (while (re-search-forward re nil t)
16369 (push (org-entry-get (point) key) values))
16370 (delete-dups values))))
16372 (defun org-insert-property-drawer ()
16373 "Insert a property drawer into the current entry."
16374 (org-with-wide-buffer
16375 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16376 (org-back-to-heading t)
16377 (org-with-limited-levels (org-back-to-heading t)))
16378 (forward-line)
16379 (when (looking-at-p org-planning-line-re) (forward-line))
16380 (unless (looking-at-p org-property-drawer-re)
16381 ;; Make sure we start editing a line from current entry, not from
16382 ;; next one. It prevents extending text properties or overlays
16383 ;; belonging to the latter.
16384 (when (bolp) (backward-char))
16385 (let ((begin (1+ (point)))
16386 (inhibit-read-only t))
16387 (insert "\n:PROPERTIES:\n:END:")
16388 (when (eobp) (insert "\n"))
16389 (org-indent-region begin (point))))))
16391 (defun org-insert-drawer (&optional arg drawer)
16392 "Insert a drawer at point.
16394 When optional argument ARG is non-nil, insert a property drawer.
16396 Optional argument DRAWER, when non-nil, is a string representing
16397 drawer's name. Otherwise, the user is prompted for a name.
16399 If a region is active, insert the drawer around that region
16400 instead.
16402 Point is left between drawer's boundaries."
16403 (interactive "P")
16404 (let* ((drawer (if arg "PROPERTIES"
16405 (or drawer (read-from-minibuffer "Drawer: ")))))
16406 (cond
16407 ;; With C-u, fall back on `org-insert-property-drawer'
16408 (arg (org-insert-property-drawer))
16409 ;; Check validity of suggested drawer's name.
16410 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16411 (user-error "Invalid drawer name"))
16412 ;; With an active region, insert a drawer at point.
16413 ((not (org-region-active-p))
16414 (progn
16415 (unless (bolp) (insert "\n"))
16416 (insert (format ":%s:\n\n:END:\n" drawer))
16417 (forward-line -2)))
16418 ;; Otherwise, insert the drawer at point
16420 (let ((rbeg (region-beginning))
16421 (rend (copy-marker (region-end))))
16422 (unwind-protect
16423 (progn
16424 (goto-char rbeg)
16425 (beginning-of-line)
16426 (when (save-excursion
16427 (re-search-forward org-outline-regexp-bol rend t))
16428 (user-error "Drawers cannot contain headlines"))
16429 ;; Position point at the beginning of the first
16430 ;; non-blank line in region. Insert drawer's opening
16431 ;; there, then indent it.
16432 (org-skip-whitespace)
16433 (beginning-of-line)
16434 (insert ":" drawer ":\n")
16435 (forward-line -1)
16436 (indent-for-tab-command)
16437 ;; Move point to the beginning of the first blank line
16438 ;; after the last non-blank line in region. Insert
16439 ;; drawer's closing, then indent it.
16440 (goto-char rend)
16441 (skip-chars-backward " \r\t\n")
16442 (insert "\n:END:")
16443 (deactivate-mark t)
16444 (indent-for-tab-command)
16445 (unless (eolp) (insert "\n")))
16446 ;; Clear marker, whatever the outcome of insertion is.
16447 (set-marker rend nil)))))))
16449 (defvar org-property-set-functions-alist nil
16450 "Property set function alist.
16451 Each entry should have the following format:
16453 (PROPERTY . READ-FUNCTION)
16455 The read function will be called with the same argument as
16456 `org-completing-read'.")
16458 (defun org-set-property-function (property)
16459 "Get the function that should be used to set PROPERTY.
16460 This is computed according to `org-property-set-functions-alist'."
16461 (or (cdr (assoc property org-property-set-functions-alist))
16462 'org-completing-read))
16464 (defun org-read-property-value (property)
16465 "Read PROPERTY value from user."
16466 (let* ((completion-ignore-case t)
16467 (allowed (org-property-get-allowed-values nil property 'table))
16468 (cur (org-entry-get nil property))
16469 (prompt (concat property " value"
16470 (if (and cur (string-match "\\S-" cur))
16471 (concat " [" cur "]") "") ": "))
16472 (set-function (org-set-property-function property))
16473 (val (if allowed
16474 (funcall set-function prompt allowed nil
16475 (not (get-text-property 0 'org-unrestricted
16476 (caar allowed))))
16477 (funcall set-function prompt
16478 (mapcar 'list (org-property-values property))
16479 nil nil "" nil cur))))
16480 (org-trim val)))
16482 (defvar org-last-set-property nil)
16483 (defvar org-last-set-property-value nil)
16484 (defun org-read-property-name ()
16485 "Read a property name."
16486 (let ((completion-ignore-case t)
16487 (default-prop (or (and (org-at-property-p)
16488 (match-string-no-properties 2))
16489 org-last-set-property)))
16490 (org-completing-read
16491 (concat "Property"
16492 (if default-prop (concat " [" default-prop "]") "")
16493 ": ")
16494 (mapcar #'list (org-buffer-property-keys nil t t))
16495 nil nil nil nil default-prop)))
16497 (defun org-set-property-and-value (use-last)
16498 "Allow to set [PROPERTY]: [value] direction from prompt.
16499 When use-default, don't even ask, just use the last
16500 \"[PROPERTY]: [value]\" string from the history."
16501 (interactive "P")
16502 (let* ((completion-ignore-case t)
16503 (pv (or (and use-last org-last-set-property-value)
16504 (org-completing-read
16505 "Enter a \"[Property]: [value]\" pair: "
16506 nil nil nil nil nil
16507 org-last-set-property-value)))
16508 prop val)
16509 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16510 (setq prop (match-string 1 pv)
16511 val (match-string 2 pv))
16512 (org-set-property prop val))))
16514 (defun org-set-property (property value)
16515 "In the current entry, set PROPERTY to VALUE.
16517 When called interactively, this will prompt for a property name, offering
16518 completion on existing and default properties. And then it will prompt
16519 for a value, offering completion either on allowed values (via an inherited
16520 xxx_ALL property) or on existing values in other instances of this property
16521 in the current file.
16523 Throw an error when trying to set a property with an invalid name."
16524 (interactive (list nil nil))
16525 (let ((property (or property (org-read-property-name))))
16526 ;; `org-entry-put' also makes the following check, but this one
16527 ;; avoids polluting `org-last-set-property' and
16528 ;; `org-last-set-property-value' needlessly.
16529 (unless (org--valid-property-p property)
16530 (user-error "Invalid property name: \"%s\"" property))
16531 (let ((value (or value (org-read-property-value property)))
16532 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16533 (setq org-last-set-property property)
16534 (setq org-last-set-property-value (concat property ": " value))
16535 ;; Possibly postprocess the inserted value:
16536 (when fn (setq value (funcall fn value)))
16537 (unless (equal (org-entry-get nil property) value)
16538 (org-entry-put nil property value)))))
16540 (defun org-find-property (property &optional value)
16541 "Find first entry in buffer that sets PROPERTY.
16543 When optional argument VALUE is non-nil, only consider an entry
16544 if it contains PROPERTY set to this value. If PROPERTY should be
16545 explicitly set to nil, use string \"nil\" for VALUE.
16547 Return position where the entry begins, or nil if there is no
16548 such entry. If narrowing is in effect, only search the visible
16549 part of the buffer."
16550 (save-excursion
16551 (goto-char (point-min))
16552 (let ((case-fold-search t)
16553 (re (org-re-property property nil (not value) value)))
16554 (catch 'exit
16555 (while (re-search-forward re nil t)
16556 (when (if value (org-at-property-p)
16557 (org-entry-get (point) property nil t))
16558 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16560 (defun org-delete-property (property)
16561 "In the current entry, delete PROPERTY."
16562 (interactive
16563 (let* ((completion-ignore-case t)
16564 (cat (org-entry-get (point) "CATEGORY"))
16565 (props0 (org-entry-properties nil 'standard))
16566 (props (if cat props0
16567 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16568 (prop (if (< 1 (length props))
16569 (completing-read "Property: " props nil t)
16570 (caar props))))
16571 (list prop)))
16572 (if (not property)
16573 (message "No property to delete in this entry")
16574 (org-entry-delete nil property)
16575 (message "Property \"%s\" deleted" property)))
16577 (defun org-delete-property-globally (property)
16578 "Remove PROPERTY globally, from all entries.
16579 This function ignores narrowing, if any."
16580 (interactive
16581 (let* ((completion-ignore-case t)
16582 (prop (completing-read
16583 "Globally remove property: "
16584 (mapcar #'list (org-buffer-property-keys)))))
16585 (list prop)))
16586 (org-with-wide-buffer
16587 (goto-char (point-min))
16588 (let ((count 0)
16589 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16590 (while (re-search-forward re nil t)
16591 (when (org-entry-delete (point) property) (cl-incf count)))
16592 (message "Property \"%s\" removed from %d entries" property count))))
16594 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16596 (defun org-compute-property-at-point ()
16597 "Compute the property at point.
16598 This looks for an enclosing column format, extracts the operator and
16599 then applies it to the property in the column format's scope."
16600 (interactive)
16601 (unless (org-at-property-p)
16602 (user-error "Not at a property"))
16603 (let ((prop (match-string-no-properties 2)))
16604 (org-columns-get-format-and-top-level)
16605 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16606 (user-error "No operator defined for property %s" prop))
16607 (org-columns-compute prop)))
16609 (defvar org-property-allowed-value-functions nil
16610 "Hook for functions supplying allowed values for a specific property.
16611 The functions must take a single argument, the name of the property, and
16612 return a flat list of allowed values. If \":ETC\" is one of
16613 the values, this means that these values are intended as defaults for
16614 completion, but that other values should be allowed too.
16615 The functions must return nil if they are not responsible for this
16616 property.")
16618 (defun org-property-get-allowed-values (pom property &optional table)
16619 "Get allowed values for the property PROPERTY.
16620 When TABLE is non-nil, return an alist that can directly be used for
16621 completion."
16622 (let (vals)
16623 (cond
16624 ((equal property "TODO")
16625 (setq vals (org-with-point-at pom
16626 (append org-todo-keywords-1 '("")))))
16627 ((equal property "PRIORITY")
16628 (let ((n org-lowest-priority))
16629 (while (>= n org-highest-priority)
16630 (push (char-to-string n) vals)
16631 (setq n (1- n)))))
16632 ((equal property "CATEGORY"))
16633 ((member property org-special-properties))
16634 ((setq vals (run-hook-with-args-until-success
16635 'org-property-allowed-value-functions property)))
16637 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16638 (when (and vals (string-match "\\S-" vals))
16639 (setq vals (car (read-from-string (concat "(" vals ")"))))
16640 (setq vals (mapcar (lambda (x)
16641 (cond ((stringp x) x)
16642 ((numberp x) (number-to-string x))
16643 ((symbolp x) (symbol-name x))
16644 (t "???")))
16645 vals)))))
16646 (when (member ":ETC" vals)
16647 (setq vals (remove ":ETC" vals))
16648 (org-add-props (car vals) '(org-unrestricted t)))
16649 (if table (mapcar 'list vals) vals)))
16651 (defun org-property-previous-allowed-value (&optional _previous)
16652 "Switch to the next allowed value for this property."
16653 (interactive)
16654 (org-property-next-allowed-value t))
16656 (defun org-property-next-allowed-value (&optional previous)
16657 "Switch to the next allowed value for this property."
16658 (interactive)
16659 (unless (org-at-property-p)
16660 (user-error "Not at a property"))
16661 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16662 (key (match-string 2))
16663 (value (match-string 3))
16664 (allowed (or (org-property-get-allowed-values (point) key)
16665 (and (member value '("[ ]" "[-]" "[X]"))
16666 '("[ ]" "[X]"))))
16667 (heading (save-match-data (nth 4 (org-heading-components))))
16668 nval)
16669 (unless allowed
16670 (user-error "Allowed values for this property have not been defined"))
16671 (when previous (setq allowed (reverse allowed)))
16672 (when (member value allowed)
16673 (setq nval (car (cdr (member value allowed)))))
16674 (setq nval (or nval (car allowed)))
16675 (when (equal nval value)
16676 (user-error "Only one allowed value for this property"))
16677 (org-at-property-p)
16678 (replace-match (concat " :" key ": " nval) t t)
16679 (org-indent-line)
16680 (beginning-of-line 1)
16681 (skip-chars-forward " \t")
16682 (when (equal prop org-effort-property)
16683 (org-refresh-property
16684 '((effort . identity)
16685 (effort-minutes . org-duration-string-to-minutes))
16686 nval)
16687 (when (string= org-clock-current-task heading)
16688 (setq org-clock-effort nval)
16689 (org-clock-update-mode-line)))
16690 (run-hook-with-args 'org-property-changed-functions key nval)))
16692 (defun org-find-olp (path &optional this-buffer)
16693 "Return a marker pointing to the entry at outline path OLP.
16694 If anything goes wrong, throw an error.
16695 You can wrap this call to catch the error like this:
16697 (condition-case msg
16698 (org-mobile-locate-entry (match-string 4))
16699 (error (nth 1 msg)))
16701 The return value will then be either a string with the error message,
16702 or a marker if everything is OK.
16704 If THIS-BUFFER is set, the outline path does not contain a file,
16705 only headings."
16706 (let* ((file (if this-buffer buffer-file-name (pop path)))
16707 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16708 (level 1)
16709 (lmin 1)
16710 (lmax 1)
16711 end found flevel)
16712 (unless buffer (error "File not found :%s" file))
16713 (with-current-buffer buffer
16714 (org-with-wide-buffer
16715 (goto-char (point-min))
16716 (dolist (heading path)
16717 (let ((re (format org-complex-heading-regexp-format
16718 (regexp-quote heading)))
16719 (cnt 0))
16720 (while (re-search-forward re end t)
16721 (setq level (- (match-end 1) (match-beginning 1)))
16722 (when (and (>= level lmin) (<= level lmax))
16723 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16724 (when (= cnt 0)
16725 (error "Heading not found on level %d: %s" lmax heading))
16726 (when (> cnt 1)
16727 (error "Heading not unique on level %d: %s" lmax heading))
16728 (goto-char found)
16729 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16730 (setq end (save-excursion (org-end-of-subtree t t)))))
16731 (when (org-at-heading-p)
16732 (point-marker))))))
16734 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16735 "Find node HEADING in BUFFER.
16736 Return a marker to the heading if it was found, or nil if not.
16737 If POS-ONLY is set, return just the position instead of a marker.
16739 The heading text must match exact, but it may have a TODO keyword,
16740 a priority cookie and tags in the standard locations."
16741 (with-current-buffer (or buffer (current-buffer))
16742 (org-with-wide-buffer
16743 (goto-char (point-min))
16744 (let (case-fold-search)
16745 (when (re-search-forward
16746 (format org-complex-heading-regexp-format
16747 (regexp-quote heading)) nil t)
16748 (if pos-only
16749 (match-beginning 0)
16750 (move-marker (make-marker) (match-beginning 0))))))))
16752 (defun org-find-exact-heading-in-directory (heading &optional dir)
16753 "Find Org node headline HEADING in all .org files in directory DIR.
16754 When the target headline is found, return a marker to this location."
16755 (let ((files (directory-files (or dir default-directory)
16756 t "\\`[^.#].*\\.org\\'"))
16757 visiting m buffer)
16758 (catch 'found
16759 (dolist (file files)
16760 (message "trying %s" file)
16761 (setq visiting (org-find-base-buffer-visiting file))
16762 (setq buffer (or visiting (find-file-noselect file)))
16763 (setq m (org-find-exact-headline-in-buffer
16764 heading buffer))
16765 (when (and (not m) (not visiting)) (kill-buffer buffer))
16766 (and m (throw 'found m))))))
16768 (defun org-find-entry-with-id (ident)
16769 "Locate the entry that contains the ID property with exact value IDENT.
16770 IDENT can be a string, a symbol or a number, this function will search for
16771 the string representation of it.
16772 Return the position where this entry starts, or nil if there is no such entry."
16773 (interactive "sID: ")
16774 (let ((id (cond
16775 ((stringp ident) ident)
16776 ((symbolp ident) (symbol-name ident))
16777 ((numberp ident) (number-to-string ident))
16778 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16779 (org-with-wide-buffer (org-find-property "ID" id))))
16781 ;;;; Timestamps
16783 (defvar org-last-changed-timestamp nil)
16784 (defvar org-last-inserted-timestamp nil
16785 "The last time stamp inserted with `org-insert-time-stamp'.")
16786 (defvar org-ts-what) ; dynamically scoped parameter
16788 (defun org-time-stamp (arg &optional inactive)
16789 "Prompt for a date/time and insert a time stamp.
16791 If the user specifies a time like HH:MM or if this command is
16792 called with at least one prefix argument, the time stamp contains
16793 the date and the time. Otherwise, only the date is included.
16795 All parts of a date not specified by the user are filled in from
16796 the timestamp at point, if any, or the current date/time
16797 otherwise.
16799 If there is already a timestamp at the cursor, it is replaced.
16801 With two universal prefix arguments, insert an active timestamp
16802 with the current time without prompting the user.
16804 When called from lisp, the timestamp is inactive if INACTIVE is
16805 non-nil."
16806 (interactive "P")
16807 (let* ((ts (cond
16808 ((org-at-date-range-p t)
16809 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16810 ((org-at-timestamp-p t) (match-string 0))))
16811 ;; Default time is either the timestamp at point or today.
16812 ;; When entering a range, only the range start is considered.
16813 (default-time (if (not ts) (current-time)
16814 (apply #'encode-time (org-parse-time-string ts))))
16815 (default-input (and ts (org-get-compact-tod ts)))
16816 (repeater (and ts
16817 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16818 (match-string 0 ts)))
16819 org-time-was-given
16820 org-end-time-was-given
16821 (time
16822 (and (if (equal arg '(16)) (current-time)
16823 ;; Preserve `this-command' and `last-command'.
16824 (let ((this-command this-command)
16825 (last-command last-command))
16826 (org-read-date
16827 arg 'totime nil nil default-time default-input
16828 inactive))))))
16829 (cond
16830 ((and ts
16831 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16832 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16833 (insert "--")
16834 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16836 ;; Make sure we're on a timestamp. When in the middle of a date
16837 ;; range, move arbitrarily to range end.
16838 (unless (org-at-timestamp-p t)
16839 (skip-chars-forward "-")
16840 (org-at-timestamp-p t))
16841 (replace-match "")
16842 (setq org-last-changed-timestamp
16843 (org-insert-time-stamp
16844 time (or org-time-was-given arg)
16845 inactive nil nil (list org-end-time-was-given)))
16846 (when repeater
16847 (backward-char)
16848 (insert " " repeater)
16849 (setq org-last-changed-timestamp
16850 (concat (substring org-last-inserted-timestamp 0 -1)
16851 " " repeater ">")))
16852 (message "Timestamp updated"))
16853 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16854 (t (org-insert-time-stamp
16855 time (or org-time-was-given arg) inactive nil nil
16856 (list org-end-time-was-given))))))
16858 ;; FIXME: can we use this for something else, like computing time differences?
16859 (defun org-get-compact-tod (s)
16860 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16861 (let* ((t1 (match-string 1 s))
16862 (h1 (string-to-number (match-string 2 s)))
16863 (m1 (string-to-number (match-string 3 s)))
16864 (t2 (and (match-end 4) (match-string 5 s)))
16865 (h2 (and t2 (string-to-number (match-string 6 s))))
16866 (m2 (and t2 (string-to-number (match-string 7 s))))
16867 dh dm)
16868 (if (not t2)
16870 (setq dh (- h2 h1) dm (- m2 m1))
16871 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16872 (concat t1 "+" (number-to-string dh)
16873 (and (/= 0 dm) (format ":%02d" dm)))))))
16875 (defun org-time-stamp-inactive (&optional arg)
16876 "Insert an inactive time stamp.
16877 An inactive time stamp is enclosed in square brackets instead of angle
16878 brackets. It is inactive in the sense that it does not trigger agenda entries,
16879 does not link to the calendar and cannot be changed with the S-cursor keys.
16880 So these are more for recording a certain time/date."
16881 (interactive "P")
16882 (org-time-stamp arg 'inactive))
16884 (defvar org-date-ovl (make-overlay 1 1))
16885 (overlay-put org-date-ovl 'face 'org-date-selected)
16886 (delete-overlay org-date-ovl)
16888 (defvar org-ans1) ; dynamically scoped parameter
16889 (defvar org-ans2) ; dynamically scoped parameter
16891 (defvar org-plain-time-of-day-regexp) ; defined below
16893 (defvar org-overriding-default-time nil) ; dynamically scoped
16894 (defvar org-read-date-overlay nil)
16895 (defvar org-dcst nil) ; dynamically scoped
16896 (defvar org-read-date-history nil)
16897 (defvar org-read-date-final-answer nil)
16898 (defvar org-read-date-analyze-futurep nil)
16899 (defvar org-read-date-analyze-forced-year nil)
16900 (defvar org-read-date-inactive)
16902 (defvar org-read-date-minibuffer-local-map
16903 (let* ((map (make-sparse-keymap)))
16904 (set-keymap-parent map minibuffer-local-map)
16905 (org-defkey map (kbd ".")
16906 (lambda () (interactive)
16907 ;; Are we at the beginning of the prompt?
16908 (if (looking-back "^[^:]+: "
16909 (let ((inhibit-field-text-motion t))
16910 (line-beginning-position)))
16911 (org-eval-in-calendar '(calendar-goto-today))
16912 (insert "."))))
16913 (org-defkey map (kbd "C-.")
16914 (lambda () (interactive)
16915 (org-eval-in-calendar '(calendar-goto-today))))
16916 (org-defkey map [(meta shift left)]
16917 (lambda () (interactive)
16918 (org-eval-in-calendar '(calendar-backward-month 1))))
16919 (org-defkey map [(meta shift right)]
16920 (lambda () (interactive)
16921 (org-eval-in-calendar '(calendar-forward-month 1))))
16922 (org-defkey map [(meta shift up)]
16923 (lambda () (interactive)
16924 (org-eval-in-calendar '(calendar-backward-year 1))))
16925 (org-defkey map [(meta shift down)]
16926 (lambda () (interactive)
16927 (org-eval-in-calendar '(calendar-forward-year 1))))
16928 (org-defkey map [?\e (shift left)]
16929 (lambda () (interactive)
16930 (org-eval-in-calendar '(calendar-backward-month 1))))
16931 (org-defkey map [?\e (shift right)]
16932 (lambda () (interactive)
16933 (org-eval-in-calendar '(calendar-forward-month 1))))
16934 (org-defkey map [?\e (shift up)]
16935 (lambda () (interactive)
16936 (org-eval-in-calendar '(calendar-backward-year 1))))
16937 (org-defkey map [?\e (shift down)]
16938 (lambda () (interactive)
16939 (org-eval-in-calendar '(calendar-forward-year 1))))
16940 (org-defkey map [(shift up)]
16941 (lambda () (interactive)
16942 (org-eval-in-calendar '(calendar-backward-week 1))))
16943 (org-defkey map [(shift down)]
16944 (lambda () (interactive)
16945 (org-eval-in-calendar '(calendar-forward-week 1))))
16946 (org-defkey map [(shift left)]
16947 (lambda () (interactive)
16948 (org-eval-in-calendar '(calendar-backward-day 1))))
16949 (org-defkey map [(shift right)]
16950 (lambda () (interactive)
16951 (org-eval-in-calendar '(calendar-forward-day 1))))
16952 (org-defkey map "!"
16953 (lambda () (interactive)
16954 (org-eval-in-calendar '(diary-view-entries))
16955 (message "")))
16956 (org-defkey map ">"
16957 (lambda () (interactive)
16958 (org-eval-in-calendar '(calendar-scroll-left 1))))
16959 (org-defkey map "<"
16960 (lambda () (interactive)
16961 (org-eval-in-calendar '(calendar-scroll-right 1))))
16962 (org-defkey map "\C-v"
16963 (lambda () (interactive)
16964 (org-eval-in-calendar
16965 '(calendar-scroll-left-three-months 1))))
16966 (org-defkey map "\M-v"
16967 (lambda () (interactive)
16968 (org-eval-in-calendar
16969 '(calendar-scroll-right-three-months 1))))
16970 map)
16971 "Keymap for minibuffer commands when using `org-read-date'.")
16973 (defvar org-def)
16974 (defvar org-defdecode)
16975 (defvar org-with-time)
16977 (defvar calendar-setup) ; Dynamically scoped.
16978 (defun org-read-date (&optional with-time to-time from-string prompt
16979 default-time default-input inactive)
16980 "Read a date, possibly a time, and make things smooth for the user.
16981 The prompt will suggest to enter an ISO date, but you can also enter anything
16982 which will at least partially be understood by `parse-time-string'.
16983 Unrecognized parts of the date will default to the current day, month, year,
16984 hour and minute. If this command is called to replace a timestamp at point,
16985 or to enter the second timestamp of a range, the default time is taken
16986 from the existing stamp. Furthermore, the command prefers the future,
16987 so if you are giving a date where the year is not given, and the day-month
16988 combination is already past in the current year, it will assume you
16989 mean next year. For details, see the manual. A few examples:
16991 3-2-5 --> 2003-02-05
16992 feb 15 --> currentyear-02-15
16993 2/15 --> currentyear-02-15
16994 sep 12 9 --> 2009-09-12
16995 12:45 --> today 12:45
16996 22 sept 0:34 --> currentyear-09-22 0:34
16997 12 --> currentyear-currentmonth-12
16998 Fri --> nearest Friday after today
16999 -Tue --> last Tuesday
17000 etc.
17002 Furthermore you can specify a relative date by giving, as the *first* thing
17003 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
17004 change in days weeks, months, years.
17005 With a single plus or minus, the date is relative to today. With a double
17006 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17007 +4d --> four days from today
17008 +4 --> same as above
17009 +2w --> two weeks from today
17010 ++5 --> five days from default date
17012 The function understands only English month and weekday abbreviations.
17014 While prompting, a calendar is popped up - you can also select the
17015 date with the mouse (button 1). The calendar shows a period of three
17016 months. To scroll it to other months, use the keys `>' and `<'.
17017 If you don't like the calendar, turn it off with
17018 (setq org-read-date-popup-calendar nil)
17020 With optional argument TO-TIME, the date will immediately be converted
17021 to an internal time.
17022 With an optional argument WITH-TIME, the prompt will suggest to
17023 also insert a time. Note that when WITH-TIME is not set, you can
17024 still enter a time, and this function will inform the calling routine
17025 about this change. The calling routine may then choose to change the
17026 format used to insert the time stamp into the buffer to include the time.
17027 With optional argument FROM-STRING, read from this string instead from
17028 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17029 the time/date that is used for everything that is not specified by the
17030 user."
17031 (require 'parse-time)
17032 (let* ((org-with-time with-time)
17033 (org-time-stamp-rounding-minutes
17034 (if (equal org-with-time '(16))
17035 '(0 0)
17036 org-time-stamp-rounding-minutes))
17037 (org-dcst org-display-custom-times)
17038 (ct (org-current-time))
17039 (org-def (or org-overriding-default-time default-time ct))
17040 (org-defdecode (decode-time org-def))
17041 (cur-frame (selected-frame))
17042 (mouse-autoselect-window nil) ; Don't let the mouse jump
17043 (calendar-setup
17044 (and (eq calendar-setup 'calendar-only) 'calendar-only))
17045 (calendar-move-hook nil)
17046 (calendar-view-diary-initially-flag nil)
17047 (calendar-view-holidays-initially-flag nil)
17048 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
17049 ;; Rationalize `org-def' and `org-defdecode', if required.
17050 (when (< (nth 2 org-defdecode) org-extend-today-until)
17051 (setf (nth 2 org-defdecode) -1)
17052 (setf (nth 1 org-defdecode) 59)
17053 (setq org-def (apply #'encode-time org-defdecode))
17054 (setq org-defdecode (decode-time org-def)))
17055 (let* ((timestr (format-time-string
17056 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
17057 org-def))
17058 (prompt (concat (if prompt (concat prompt " ") "")
17059 (format "Date+time [%s]: " timestr))))
17060 (cond
17061 (from-string (setq ans from-string))
17062 (org-read-date-popup-calendar
17063 (save-excursion
17064 (save-window-excursion
17065 (calendar)
17066 (when (eq calendar-setup 'calendar-only)
17067 (setq cal-frame
17068 (window-frame (get-buffer-window "*Calendar*" 'visible)))
17069 (select-frame cal-frame))
17070 (org-eval-in-calendar '(setq cursor-type nil) t)
17071 (unwind-protect
17072 (progn
17073 (calendar-forward-day (- (time-to-days org-def)
17074 (calendar-absolute-from-gregorian
17075 (calendar-current-date))))
17076 (org-eval-in-calendar nil t)
17077 (let* ((old-map (current-local-map))
17078 (map (copy-keymap calendar-mode-map))
17079 (minibuffer-local-map
17080 (copy-keymap org-read-date-minibuffer-local-map)))
17081 (org-defkey map (kbd "RET") 'org-calendar-select)
17082 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17083 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17084 (unwind-protect
17085 (progn
17086 (use-local-map map)
17087 (setq org-read-date-inactive inactive)
17088 (add-hook 'post-command-hook 'org-read-date-display)
17089 (setq org-ans0
17090 (read-string prompt
17091 default-input
17092 'org-read-date-history
17093 nil))
17094 ;; org-ans0: from prompt
17095 ;; org-ans1: from mouse click
17096 ;; org-ans2: from calendar motion
17097 (setq ans
17098 (concat org-ans0 " " (or org-ans1 org-ans2))))
17099 (remove-hook 'post-command-hook 'org-read-date-display)
17100 (use-local-map old-map)
17101 (when org-read-date-overlay
17102 (delete-overlay org-read-date-overlay)
17103 (setq org-read-date-overlay nil)))))
17104 (bury-buffer "*Calendar*")
17105 (when cal-frame
17106 (delete-frame cal-frame)
17107 (select-frame-set-input-focus cur-frame))))))
17109 (t ; Naked prompt only
17110 (unwind-protect
17111 (setq ans (read-string prompt default-input
17112 'org-read-date-history timestr))
17113 (when org-read-date-overlay
17114 (delete-overlay org-read-date-overlay)
17115 (setq org-read-date-overlay nil))))))
17117 (setq final (org-read-date-analyze ans org-def org-defdecode))
17119 (when org-read-date-analyze-forced-year
17120 (message "Year was forced into %s"
17121 (if org-read-date-force-compatible-dates
17122 "compatible range (1970-2037)"
17123 "range representable on this machine"))
17124 (ding))
17126 ;; One round trip to get rid of 34th of August and stuff like that....
17127 (setq final (decode-time (apply 'encode-time final)))
17129 (setq org-read-date-final-answer ans)
17131 (if to-time
17132 (apply 'encode-time final)
17133 (if (and (boundp 'org-time-was-given) org-time-was-given)
17134 (format "%04d-%02d-%02d %02d:%02d"
17135 (nth 5 final) (nth 4 final) (nth 3 final)
17136 (nth 2 final) (nth 1 final))
17137 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17139 (defun org-read-date-display ()
17140 "Display the current date prompt interpretation in the minibuffer."
17141 (when org-read-date-display-live
17142 (when org-read-date-overlay
17143 (delete-overlay org-read-date-overlay))
17144 (when (minibufferp (current-buffer))
17145 (save-excursion
17146 (end-of-line 1)
17147 (while (not (equal (buffer-substring
17148 (max (point-min) (- (point) 4)) (point))
17149 " "))
17150 (insert " ")))
17151 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17152 " " (or org-ans1 org-ans2)))
17153 (org-end-time-was-given nil)
17154 (f (org-read-date-analyze ans org-def org-defdecode))
17155 (fmts (if org-dcst
17156 org-time-stamp-custom-formats
17157 org-time-stamp-formats))
17158 (fmt (if (or org-with-time
17159 (and (boundp 'org-time-was-given) org-time-was-given))
17160 (cdr fmts)
17161 (car fmts)))
17162 (txt (format-time-string fmt (apply 'encode-time f)))
17163 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17164 (txt (concat "=> " txt)))
17165 (when (and org-end-time-was-given
17166 (string-match org-plain-time-of-day-regexp txt))
17167 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17168 org-end-time-was-given
17169 (substring txt (match-end 0)))))
17170 (when org-read-date-analyze-futurep
17171 (setq txt (concat txt " (=>F)")))
17172 (setq org-read-date-overlay
17173 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17174 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17176 (defun org-read-date-analyze (ans def defdecode)
17177 "Analyze the combined answer of the date prompt."
17178 ;; FIXME: cleanup and comment
17179 ;; Pass `current-time' result to `decode-time' (instead of calling
17180 ;; without arguments) so that only `current-time' has to be
17181 ;; overriden in tests.
17182 (let ((org-def def)
17183 (org-defdecode defdecode)
17184 (nowdecode (decode-time (current-time)))
17185 delta deltan deltaw deltadef year month day
17186 hour minute second wday pm h2 m2 tl wday1
17187 iso-year iso-weekday iso-week iso-date futurep kill-year)
17188 (setq org-read-date-analyze-futurep nil
17189 org-read-date-analyze-forced-year nil)
17190 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17191 (setq ans "+0"))
17193 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17194 (setq ans (replace-match "" t t ans)
17195 deltan (car delta)
17196 deltaw (nth 1 delta)
17197 deltadef (nth 2 delta)))
17199 ;; Check if there is an iso week date in there. If yes, store the
17200 ;; info and postpone interpreting it until the rest of the parsing
17201 ;; is done.
17202 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17203 (setq iso-year (when (match-end 1)
17204 (org-small-year-to-year
17205 (string-to-number (match-string 1 ans))))
17206 iso-weekday (when (match-end 3)
17207 (string-to-number (match-string 3 ans)))
17208 iso-week (string-to-number (match-string 2 ans)))
17209 (setq ans (replace-match "" t t ans)))
17211 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17212 (when (string-match
17213 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17214 (setq year (if (match-end 2)
17215 (string-to-number (match-string 2 ans))
17216 (progn (setq kill-year t)
17217 (string-to-number (format-time-string "%Y"))))
17218 month (string-to-number (match-string 3 ans))
17219 day (string-to-number (match-string 4 ans)))
17220 (setq year (org-small-year-to-year year))
17221 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17222 t nil ans)))
17224 ;; Help matching dotted european dates
17225 (when (string-match
17226 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17227 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17228 (setq kill-year t)
17229 (string-to-number (format-time-string "%Y")))
17230 day (string-to-number (match-string 1 ans))
17231 month (string-to-number (match-string 2 ans))
17232 ans (replace-match (format "%04d-%02d-%02d" year month day)
17233 t nil ans)))
17235 ;; Help matching american dates, like 5/30 or 5/30/7
17236 (when (string-match
17237 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17238 (setq year (if (match-end 4)
17239 (string-to-number (match-string 4 ans))
17240 (progn (setq kill-year t)
17241 (string-to-number (format-time-string "%Y"))))
17242 month (string-to-number (match-string 1 ans))
17243 day (string-to-number (match-string 2 ans)))
17244 (setq year (org-small-year-to-year year))
17245 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17246 t nil ans)))
17247 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17248 ;; If there is a time with am/pm, and *no* time without it, we convert
17249 ;; so that matching will be successful.
17250 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17251 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17252 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17253 (setq hour (string-to-number (match-string 1 ans))
17254 minute (if (match-end 3)
17255 (string-to-number (match-string 3 ans))
17257 pm (equal ?p
17258 (string-to-char (downcase (match-string 4 ans)))))
17259 (if (and (= hour 12) (not pm))
17260 (setq hour 0)
17261 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17262 (setq ans (replace-match (format "%02d:%02d" hour minute)
17263 t t ans))))
17265 ;; Check if a time range is given as a duration
17266 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17267 (setq hour (string-to-number (match-string 1 ans))
17268 h2 (+ hour (string-to-number (match-string 3 ans)))
17269 minute (string-to-number (match-string 2 ans))
17270 m2 (+ minute (if (match-end 5) (string-to-number
17271 (match-string 5 ans))0)))
17272 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17273 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17274 t t ans)))
17276 ;; Check if there is a time range
17277 (when (boundp 'org-end-time-was-given)
17278 (setq org-time-was-given nil)
17279 (when (and (string-match org-plain-time-of-day-regexp ans)
17280 (match-end 8))
17281 (setq org-end-time-was-given (match-string 8 ans))
17282 (setq ans (concat (substring ans 0 (match-beginning 7))
17283 (substring ans (match-end 7))))))
17285 (setq tl (parse-time-string ans)
17286 day (or (nth 3 tl) (nth 3 org-defdecode))
17287 month
17288 (cond ((nth 4 tl))
17289 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17290 ;; Day was specified. Make sure DAY+MONTH
17291 ;; combination happens in the future.
17292 ((nth 3 tl)
17293 (setq futurep t)
17294 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17295 (nth 4 nowdecode)))
17296 (t (nth 4 org-defdecode)))
17297 year
17298 (cond ((and (not kill-year) (nth 5 tl)))
17299 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17300 ;; Month was guessed in the future and is at least
17301 ;; equal to NOWDECODE's. Fix year accordingly.
17302 (futurep
17303 (if (or (> month (nth 4 nowdecode))
17304 (>= day (nth 3 nowdecode)))
17305 (nth 5 nowdecode)
17306 (1+ (nth 5 nowdecode))))
17307 ;; Month was specified. Make sure MONTH+YEAR
17308 ;; combination happens in the future.
17309 ((nth 4 tl)
17310 (setq futurep t)
17311 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17312 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17313 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17314 (t (nth 5 nowdecode))))
17315 (t (nth 5 org-defdecode)))
17316 hour (or (nth 2 tl) (nth 2 org-defdecode))
17317 minute (or (nth 1 tl) (nth 1 org-defdecode))
17318 second (or (nth 0 tl) 0)
17319 wday (nth 6 tl))
17321 (when (and (eq org-read-date-prefer-future 'time)
17322 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17323 (equal day (nth 3 nowdecode))
17324 (equal month (nth 4 nowdecode))
17325 (equal year (nth 5 nowdecode))
17326 (nth 2 tl)
17327 (or (< (nth 2 tl) (nth 2 nowdecode))
17328 (and (= (nth 2 tl) (nth 2 nowdecode))
17329 (nth 1 tl)
17330 (< (nth 1 tl) (nth 1 nowdecode)))))
17331 (setq day (1+ day)
17332 futurep t))
17334 ;; Special date definitions below
17335 (cond
17336 (iso-week
17337 ;; There was an iso week
17338 (require 'cal-iso)
17339 (setq futurep nil)
17340 (setq year (or iso-year year)
17341 day (or iso-weekday wday 1)
17342 wday nil ; to make sure that the trigger below does not match
17343 iso-date (calendar-gregorian-from-absolute
17344 (calendar-iso-to-absolute
17345 (list iso-week day year))))
17346 ; FIXME: Should we also push ISO weeks into the future?
17347 ; (when (and org-read-date-prefer-future
17348 ; (not iso-year)
17349 ; (< (calendar-absolute-from-gregorian iso-date)
17350 ; (time-to-days (current-time))))
17351 ; (setq year (1+ year)
17352 ; iso-date (calendar-gregorian-from-absolute
17353 ; (calendar-iso-to-absolute
17354 ; (list iso-week day year)))))
17355 (setq month (car iso-date)
17356 year (nth 2 iso-date)
17357 day (nth 1 iso-date)))
17358 (deltan
17359 (setq futurep nil)
17360 (unless deltadef
17361 ;; Pass `current-time' result to `decode-time' (instead of
17362 ;; calling without arguments) so that only `current-time' has
17363 ;; to be overriden in tests.
17364 (let ((now (decode-time (current-time))))
17365 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17366 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17367 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17368 ((equal deltaw "m") (setq month (+ month deltan)))
17369 ((equal deltaw "y") (setq year (+ year deltan)))))
17370 ((and wday (not (nth 3 tl)))
17371 ;; Weekday was given, but no day, so pick that day in the week
17372 ;; on or after the derived date.
17373 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17374 (unless (equal wday wday1)
17375 (setq day (+ day (% (- wday wday1 -7) 7))))))
17376 (when (and (boundp 'org-time-was-given)
17377 (nth 2 tl))
17378 (setq org-time-was-given t))
17379 (when (< year 100) (setq year (+ 2000 year)))
17380 ;; Check of the date is representable
17381 (if org-read-date-force-compatible-dates
17382 (progn
17383 (when (< year 1970)
17384 (setq year 1970 org-read-date-analyze-forced-year t))
17385 (when (> year 2037)
17386 (setq year 2037 org-read-date-analyze-forced-year t)))
17387 (condition-case nil
17388 (ignore (encode-time second minute hour day month year))
17389 (error
17390 (setq year (nth 5 org-defdecode))
17391 (setq org-read-date-analyze-forced-year t))))
17392 (setq org-read-date-analyze-futurep futurep)
17393 (list second minute hour day month year)))
17395 (defvar parse-time-weekdays)
17396 (defun org-read-date-get-relative (s today default)
17397 "Check string S for special relative date string.
17398 TODAY and DEFAULT are internal times, for today and for a default.
17399 Return shift list (N what def-flag)
17400 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17401 N is the number of WHATs to shift.
17402 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17403 the DEFAULT date rather than TODAY."
17404 (require 'parse-time)
17405 (when (and
17406 (string-match
17407 (concat
17408 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17409 "\\([0-9]+\\)?"
17410 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17411 "\\([ \t]\\|$\\)") s)
17412 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17413 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17414 (string-to-char (substring (match-string 1 s) -1))
17415 ?+))
17416 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17417 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17418 (what (if (match-end 3) (match-string 3 s) "d"))
17419 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17420 (date (if rel default today))
17421 (wday (nth 6 (decode-time date)))
17422 delta)
17423 (if wday1
17424 (progn
17425 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17426 (when (= delta 0) (setq delta 7))
17427 (when (= dir ?-)
17428 (setq delta (- delta 7))
17429 (when (= delta 0) (setq delta -7)))
17430 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17431 (list delta "d" rel))
17432 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17434 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17435 "Turn a user-specified date into the internal representation.
17436 The internal representation needed by the calendar is (month day year).
17437 This is a wrapper to handle the brain-dead convention in calendar that
17438 user function argument order change dependent on argument order."
17439 (pcase calendar-date-style
17440 (`american (list arg1 arg2 arg3))
17441 (`european (list arg2 arg1 arg3))
17442 (`iso (list arg2 arg3 arg1))))
17444 (defun org-eval-in-calendar (form &optional keepdate)
17445 "Eval FORM in the calendar window and return to current window.
17446 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17447 (let ((sf (selected-frame))
17448 (sw (selected-window)))
17449 (select-window (get-buffer-window "*Calendar*" t))
17450 (eval form)
17451 (when (and (not keepdate) (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-ans2 (format-time-string "%Y-%m-%d" time))))
17455 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17456 (select-window sw)
17457 (select-frame-set-input-focus sf)))
17459 (defun org-calendar-select ()
17460 "Return to `org-read-date' with the date currently selected.
17461 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17462 (interactive)
17463 (when (calendar-cursor-to-date)
17464 (let* ((date (calendar-cursor-to-date))
17465 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17466 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17467 (when (active-minibuffer-window) (exit-minibuffer))))
17469 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17470 "Insert a date stamp for the date given by the internal TIME.
17471 See `format-time-string' for the format of TIME.
17472 WITH-HM means use the stamp format that includes the time of the day.
17473 INACTIVE means use square brackets instead of angular ones, so that the
17474 stamp will not contribute to the agenda.
17475 PRE and POST are optional strings to be inserted before and after the
17476 stamp.
17477 The command returns the inserted time stamp."
17478 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17479 stamp)
17480 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17481 (insert-before-markers (or pre ""))
17482 (when (listp extra)
17483 (setq extra (car extra))
17484 (if (and (stringp extra)
17485 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17486 (setq extra (format "-%02d:%02d"
17487 (string-to-number (match-string 1 extra))
17488 (string-to-number (match-string 2 extra))))
17489 (setq extra nil)))
17490 (when extra
17491 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17492 (insert-before-markers (setq stamp (format-time-string fmt time)))
17493 (insert-before-markers (or post ""))
17494 (setq org-last-inserted-timestamp stamp)))
17496 (defun org-toggle-time-stamp-overlays ()
17497 "Toggle the use of custom time stamp formats."
17498 (interactive)
17499 (setq org-display-custom-times (not org-display-custom-times))
17500 (unless org-display-custom-times
17501 (let ((p (point-min)) (bmp (buffer-modified-p)))
17502 (while (setq p (next-single-property-change p 'display))
17503 (when (and (get-text-property p 'display)
17504 (eq (get-text-property p 'face) 'org-date))
17505 (remove-text-properties
17506 p (setq p (next-single-property-change p 'display))
17507 '(display t))))
17508 (set-buffer-modified-p bmp)))
17509 (org-restart-font-lock)
17510 (setq org-table-may-need-update t)
17511 (if org-display-custom-times
17512 (message "Time stamps are overlaid with custom format")
17513 (message "Time stamp overlays removed")))
17515 (defun org-display-custom-time (beg end)
17516 "Overlay modified time stamp format over timestamp between BEG and END."
17517 (let* ((ts (buffer-substring beg end))
17518 t1 w1 with-hm tf time str w2 (off 0))
17519 (save-match-data
17520 (setq t1 (org-parse-time-string ts t))
17521 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17522 (setq off (- (match-end 0) (match-beginning 0)))))
17523 (setq end (- end off))
17524 (setq w1 (- end beg)
17525 with-hm (and (nth 1 t1) (nth 2 t1))
17526 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17527 time (org-fix-decoded-time t1)
17528 str (org-add-props
17529 (format-time-string
17530 (substring tf 1 -1) (apply 'encode-time time))
17531 nil 'mouse-face 'highlight)
17532 w2 (length str))
17533 (unless (= w2 w1)
17534 (add-text-properties (1+ beg) (+ 2 beg)
17535 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17536 (put-text-property beg end 'display str)))
17538 (defun org-fix-decoded-time (time)
17539 "Set 0 instead of nil for the first 6 elements of time.
17540 Don't touch the rest."
17541 (let ((n 0))
17542 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17544 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17545 "Difference between TIMESTAMP-STRING and now in days.
17546 If SECONDS is non-nil, return the difference in seconds."
17547 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17548 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17549 (funcall fdiff (current-time)))))
17551 (defun org-deadline-close-p (timestamp-string &optional ndays)
17552 "Is the time in TIMESTAMP-STRING close to the current date?"
17553 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17554 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17555 (not (org-entry-is-done-p))))
17557 (defun org-get-wdays (ts &optional delay zero-delay)
17558 "Get the deadline lead time appropriate for timestring TS.
17559 When DELAY is non-nil, get the delay time for scheduled items
17560 instead of the deadline lead time. When ZERO-DELAY is non-nil
17561 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17562 don't try to find the delay cookie in the scheduled timestamp."
17563 (let ((tv (if delay org-scheduled-delay-days
17564 org-deadline-warning-days)))
17565 (cond
17566 ((or (and delay (< tv 0))
17567 (and delay zero-delay (<= tv 0))
17568 (and (not delay) (<= tv 0)))
17569 ;; Enforce this value no matter what
17570 (- tv))
17571 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17572 ;; lead time is specified.
17573 (floor (* (string-to-number (match-string 1 ts))
17574 (cdr (assoc (match-string 2 ts)
17575 '(("d" . 1) ("w" . 7)
17576 ("m" . 30.4) ("y" . 365.25)
17577 ("h" . 0.041667)))))))
17578 ;; go for the default.
17579 (t tv))))
17581 (defun org-calendar-select-mouse (ev)
17582 "Return to `org-read-date' with the date currently selected.
17583 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17584 (interactive "e")
17585 (mouse-set-point ev)
17586 (when (calendar-cursor-to-date)
17587 (let* ((date (calendar-cursor-to-date))
17588 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17589 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17590 (when (active-minibuffer-window) (exit-minibuffer))))
17592 (defun org-check-deadlines (ndays)
17593 "Check if there are any deadlines due or past due.
17594 A deadline is considered due if it happens within `org-deadline-warning-days'
17595 days from today's date. If the deadline appears in an entry marked DONE,
17596 it is not shown. A numeric prefix argument NDAYS can be used to test that
17597 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17598 are shown."
17599 (interactive "P")
17600 (let* ((org-warn-days
17601 (cond
17602 ((equal ndays '(4)) 100000)
17603 (ndays (prefix-numeric-value ndays))
17604 (t (abs org-deadline-warning-days))))
17605 (case-fold-search nil)
17606 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17607 (callback
17608 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17609 (message "%d deadlines past-due or due within %d days"
17610 (org-occur regexp nil callback)
17611 org-warn-days)))
17613 (defsubst org-re-timestamp (type)
17614 "Return a regexp for timestamp TYPE.
17615 Allowed values for TYPE are:
17617 all: all timestamps
17618 active: only active timestamps (<...>)
17619 inactive: only inactive timestamps ([...])
17620 scheduled: only scheduled timestamps
17621 deadline: only deadline timestamps
17622 closed: only closed time-stamps
17624 When TYPE is nil, fall back on returning a regexp that matches
17625 both scheduled and deadline timestamps."
17626 (cl-case type
17627 (all org-ts-regexp-both)
17628 (active org-ts-regexp)
17629 (inactive org-ts-regexp-inactive)
17630 (scheduled org-scheduled-time-regexp)
17631 (deadline org-deadline-time-regexp)
17632 (closed org-closed-time-regexp)
17633 (otherwise
17634 (concat "\\<"
17635 (regexp-opt (list org-deadline-string org-scheduled-string))
17636 " *<\\([^>]+\\)>"))))
17638 (defun org-check-before-date (d)
17639 "Check if there are deadlines or scheduled entries before date D."
17640 (interactive (list (org-read-date)))
17641 (let* ((case-fold-search nil)
17642 (regexp (org-re-timestamp org-ts-type))
17643 (ts-type org-ts-type)
17644 (callback
17645 (lambda ()
17646 (let ((match (match-string 1)))
17647 (and (if (memq ts-type '(active inactive all))
17648 (eq (org-element-type (save-excursion
17649 (backward-char)
17650 (org-element-context)))
17651 'timestamp)
17652 (org-at-planning-p))
17653 (time-less-p
17654 (org-time-string-to-time match)
17655 (org-time-string-to-time d)))))))
17656 (message "%d entries before %s"
17657 (org-occur regexp nil callback)
17658 d)))
17660 (defun org-check-after-date (d)
17661 "Check if there are deadlines or scheduled entries after date D."
17662 (interactive (list (org-read-date)))
17663 (let* ((case-fold-search nil)
17664 (regexp (org-re-timestamp org-ts-type))
17665 (ts-type org-ts-type)
17666 (callback
17667 (lambda ()
17668 (let ((match (match-string 1)))
17669 (and (if (memq ts-type '(active inactive all))
17670 (eq (org-element-type (save-excursion
17671 (backward-char)
17672 (org-element-context)))
17673 'timestamp)
17674 (org-at-planning-p))
17675 (not (time-less-p
17676 (org-time-string-to-time match)
17677 (org-time-string-to-time d))))))))
17678 (message "%d entries after %s"
17679 (org-occur regexp nil callback)
17680 d)))
17682 (defun org-check-dates-range (start-date end-date)
17683 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17684 (interactive (list (org-read-date nil nil nil "Range starts")
17685 (org-read-date nil nil nil "Range end")))
17686 (let ((case-fold-search nil)
17687 (regexp (org-re-timestamp org-ts-type))
17688 (callback
17689 (let ((type org-ts-type))
17690 (lambda ()
17691 (let ((match (match-string 1)))
17692 (and
17693 (if (memq type '(active inactive all))
17694 (eq (org-element-type (save-excursion
17695 (backward-char)
17696 (org-element-context)))
17697 'timestamp)
17698 (org-at-planning-p))
17699 (not (time-less-p
17700 (org-time-string-to-time match)
17701 (org-time-string-to-time start-date)))
17702 (time-less-p
17703 (org-time-string-to-time match)
17704 (org-time-string-to-time end-date))))))))
17705 (message "%d entries between %s and %s"
17706 (org-occur regexp nil callback) start-date end-date)))
17708 (defun org-evaluate-time-range (&optional to-buffer)
17709 "Evaluate a time range by computing the difference between start and end.
17710 Normally the result is just printed in the echo area, but with prefix arg
17711 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17712 If the time range is actually in a table, the result is inserted into the
17713 next column.
17714 For time difference computation, a year is assumed to be exactly 365
17715 days in order to avoid rounding problems."
17716 (interactive "P")
17718 (org-clock-update-time-maybe)
17719 (save-excursion
17720 (unless (org-at-date-range-p t)
17721 (goto-char (point-at-bol))
17722 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17723 (unless (org-at-date-range-p t)
17724 (user-error "Not at a time-stamp range, and none found in current line")))
17725 (let* ((ts1 (match-string 1))
17726 (ts2 (match-string 2))
17727 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17728 (match-end (match-end 0))
17729 (time1 (org-time-string-to-time ts1))
17730 (time2 (org-time-string-to-time ts2))
17731 (t1 (float-time time1))
17732 (t2 (float-time time2))
17733 (diff (abs (- t2 t1)))
17734 (negative (< (- t2 t1) 0))
17735 ;; (ys (floor (* 365 24 60 60)))
17736 (ds (* 24 60 60))
17737 (hs (* 60 60))
17738 (fy "%dy %dd %02d:%02d")
17739 (fy1 "%dy %dd")
17740 (fd "%dd %02d:%02d")
17741 (fd1 "%dd")
17742 (fh "%02d:%02d")
17743 y d h m align)
17744 (if havetime
17745 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17747 d (floor (/ diff ds)) diff (mod diff ds)
17748 h (floor (/ diff hs)) diff (mod diff hs)
17749 m (floor (/ diff 60)))
17750 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17752 d (floor (+ (/ diff ds) 0.5))
17753 h 0 m 0))
17754 (if (not to-buffer)
17755 (message "%s" (org-make-tdiff-string y d h m))
17756 (if (org-at-table-p)
17757 (progn
17758 (goto-char match-end)
17759 (setq align t)
17760 (and (looking-at " *|") (goto-char (match-end 0))))
17761 (goto-char match-end))
17762 (when (looking-at
17763 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17764 (replace-match ""))
17765 (when negative (insert " -"))
17766 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17767 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17768 (insert " " (format fh h m))))
17769 (when align (org-table-align))
17770 (message "Time difference inserted")))))
17772 (defun org-make-tdiff-string (y d h m)
17773 (let ((fmt "")
17774 (l nil))
17775 (when (> y 0)
17776 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17777 (push y l))
17778 (when (> d 0)
17779 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17780 (push d l))
17781 (when (> h 0)
17782 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17783 (push h l))
17784 (when (> m 0)
17785 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17786 (push m l))
17787 (apply 'format fmt (nreverse l))))
17789 (defun org-time-string-to-time (s &optional buffer pos)
17790 "Convert a timestamp string into internal time."
17791 (condition-case errdata
17792 (apply 'encode-time (org-parse-time-string s))
17793 (error (error "Bad timestamp `%s'%s\nError was: %s"
17794 s (if (not (and buffer pos))
17796 (format-message " at %d in buffer `%s'" pos buffer))
17797 (cdr errdata)))))
17799 (defun org-time-string-to-seconds (s)
17800 "Convert a timestamp string to a number of seconds."
17801 (float-time (org-time-string-to-time s)))
17803 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17805 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17806 "Convert time stamp S to an absolute day number.
17808 If DAYNR in non-nil, and there is a specifier for a cyclic time
17809 stamp, get the closest date to DAYNR. If PREFER is
17810 `past' (respectively `future') return a date past (respectively
17811 after) or equal to DAYNR.
17813 POS is the location of time stamp S, as a buffer position in
17814 BUFFER.
17816 Diary sexp timestamps are matched against DAYNR, when non-nil.
17817 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17818 signalled."
17819 (cond
17820 ((string-match "\\`%%\\((.*)\\)" s)
17821 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17822 ;; only able to match individual dates. If it fails, raise an
17823 ;; error.
17824 (if (and daynr
17825 (org-diary-sexp-entry
17826 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17827 daynr
17828 (signal 'org-diary-sexp-no-match (list s))))
17829 ((and daynr show-all) (org-closest-date s daynr prefer))
17830 (t (time-to-days
17831 (condition-case errdata
17832 (apply #'encode-time (org-parse-time-string s))
17833 (error (error "Bad timestamp `%s'%s\nError was: %s"
17835 (if (not (and buffer pos)) ""
17836 (format-message " at %d in buffer `%s'" pos buffer))
17837 (cdr errdata))))))))
17839 (defun org-days-to-iso-week (days)
17840 "Return the iso week number."
17841 (require 'cal-iso)
17842 (car (calendar-iso-from-absolute days)))
17844 (defun org-small-year-to-year (year)
17845 "Convert 2-digit years into 4-digit years.
17846 YEAR is expanded into one of the 30 next years, if possible, or
17847 into a past one. Any year larger than 99 is returned unchanged."
17848 (if (>= year 100) year
17849 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17850 (century (/ current 100))
17851 (offset (- year (% current 100))))
17852 (cond ((> offset 30) (+ (* (1- century) 100) year))
17853 ((> offset -70) (+ (* century 100) year))
17854 (t (+ (* (1+ century) 100) year))))))
17856 (defun org-time-from-absolute (d)
17857 "Return the time corresponding to date D.
17858 D may be an absolute day number, or a calendar-type list (month day year)."
17859 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17860 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17862 (defvar org-agenda-current-date)
17863 (defun org-calendar-holiday ()
17864 "List of holidays, for Diary display in Org mode."
17865 (require 'holidays)
17866 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17867 (and hl (mapconcat #'identity hl "; "))))
17869 (defun org-diary-sexp-entry (sexp entry d)
17870 "Process a SEXP diary ENTRY for date D."
17871 (require 'diary-lib)
17872 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17873 ;; dynamically.
17874 (let* ((sexp `(let ((entry ,entry)
17875 (date ',d))
17876 ,(car (read-from-string sexp))))
17877 (result (if calendar-debug-sexp (eval sexp)
17878 (condition-case nil
17879 (eval sexp)
17880 (error
17881 (beep)
17882 (message "Bad sexp at line %d in %s: %s"
17883 (org-current-line)
17884 (buffer-file-name) sexp)
17885 (sleep-for 2))))))
17886 (cond ((stringp result) (split-string result "; "))
17887 ((and (consp result)
17888 (not (consp (cdr result)))
17889 (stringp (cdr result))) (cdr result))
17890 ((and (consp result)
17891 (stringp (car result))) result)
17892 (result entry))))
17894 (defun org-diary-to-ical-string (frombuf)
17895 "Get iCalendar entries from diary entries in buffer FROMBUF.
17896 This uses the icalendar.el library."
17897 (let* ((tmpdir temporary-file-directory)
17898 (tmpfile (make-temp-name
17899 (expand-file-name "orgics" tmpdir)))
17900 buf rtn b e)
17901 (with-current-buffer frombuf
17902 (icalendar-export-region (point-min) (point-max) tmpfile)
17903 (setq buf (find-buffer-visiting tmpfile))
17904 (set-buffer buf)
17905 (goto-char (point-min))
17906 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17907 (setq b (match-beginning 0)))
17908 (goto-char (point-max))
17909 (when (re-search-backward "^END:VEVENT" nil t)
17910 (setq e (match-end 0)))
17911 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17912 (kill-buffer buf)
17913 (delete-file tmpfile)
17914 rtn))
17916 (defun org-closest-date (start current prefer)
17917 "Return closest date to CURRENT starting from START.
17919 CURRENT and START are both time stamps.
17921 When PREFER is `past', return a date that is either CURRENT or
17922 past. When PREFER is `future', return a date that is either
17923 CURRENT or future.
17925 Only time stamps with a repeater are modified. Any other time
17926 stamp stay unchanged. In any case, return value is an absolute
17927 day number."
17928 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17929 ;; No repeater. Do not shift time stamp.
17930 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17931 (let ((value (string-to-number (match-string 1 start)))
17932 (type (match-string 2 start)))
17933 (if (= 0 value)
17934 ;; Repeater with a 0-value is considered as void.
17935 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17936 (let* ((base (org-date-to-gregorian start))
17937 (target (org-date-to-gregorian current))
17938 (sday (calendar-absolute-from-gregorian base))
17939 (cday (calendar-absolute-from-gregorian target))
17940 n1 n2)
17941 ;; If START is already past CURRENT, just return START.
17942 (if (<= cday sday) sday
17943 ;; Compute closest date before (N1) and closest date past
17944 ;; (N2) CURRENT.
17945 (pcase type
17946 ("h"
17947 (let ((missing-hours
17948 (mod (+ (- (* 24 (- cday sday))
17949 (nth 2 (org-parse-time-string start)))
17950 org-extend-today-until)
17951 value)))
17952 (setf n1 (if (= missing-hours 0) cday
17953 (- cday (1+ (/ missing-hours 24)))))
17954 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17955 ((or "d" "w")
17956 (let ((value (if (equal type "w") (* 7 value) value)))
17957 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17958 (setf n2 (+ n1 value))))
17959 ("m"
17960 (let* ((add-months
17961 (lambda (d n)
17962 ;; Add N months to gregorian date D, i.e.,
17963 ;; a list (MONTH DAY YEAR). Return a valid
17964 ;; gregorian date.
17965 (let ((m (+ (nth 0 d) n)))
17966 (list (mod m 12)
17967 (nth 1 d)
17968 (+ (/ m 12) (nth 2 d))))))
17969 (months ; Complete months to TARGET.
17970 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17971 (- (nth 0 target) (nth 0 base))
17972 ;; If START's day is greater than
17973 ;; TARGET's, remove incomplete month.
17974 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17975 value)
17976 value))
17977 (before (funcall add-months base months)))
17978 (setf n1 (calendar-absolute-from-gregorian before))
17979 (setf n2
17980 (calendar-absolute-from-gregorian
17981 (funcall add-months before value)))))
17983 (let* ((d (nth 1 base))
17984 (m (nth 0 base))
17985 (y (nth 2 base))
17986 (years ; Complete years to TARGET.
17987 (* (/ (- (nth 2 target)
17989 ;; If START's month and day are
17990 ;; greater than TARGET's, remove
17991 ;; incomplete year.
17992 (if (or (> (nth 0 target) m)
17993 (and (= (nth 0 target) m)
17994 (> (nth 1 target) d)))
17997 value)
17998 value))
17999 (before (list m d (+ y years))))
18000 (setf n1 (calendar-absolute-from-gregorian before))
18001 (setf n2 (calendar-absolute-from-gregorian
18002 (list m d (+ (nth 2 before) value)))))))
18003 ;; Handle PREFER parameter, if any.
18004 (cond
18005 ((eq prefer 'past) (if (= cday n2) n2 n1))
18006 ((eq prefer 'future) (if (= cday n1) n1 n2))
18007 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
18009 (defun org-date-to-gregorian (d)
18010 "Turn any specification of date D into a Gregorian date for the calendar."
18011 (cond ((integerp d) (calendar-gregorian-from-absolute d))
18012 ((and (listp d) (= (length d) 3)) d)
18013 ((stringp d)
18014 (let ((d (org-parse-time-string d)))
18015 (list (nth 4 d) (nth 3 d) (nth 5 d))))
18016 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
18018 (defun org-parse-time-string (s &optional nodefault)
18019 "Parse the standard Org time string.
18020 This should be a lot faster than the normal `parse-time-string'.
18021 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18022 hour and minute fields will be nil if not given."
18023 (cond ((string-match org-ts-regexp0 s)
18024 (list 0
18025 (when (or (match-beginning 8) (not nodefault))
18026 (string-to-number (or (match-string 8 s) "0")))
18027 (when (or (match-beginning 7) (not nodefault))
18028 (string-to-number (or (match-string 7 s) "0")))
18029 (string-to-number (match-string 4 s))
18030 (string-to-number (match-string 3 s))
18031 (string-to-number (match-string 2 s))
18032 nil nil nil))
18033 ((string-match "^<[^>]+>$" s)
18034 (decode-time (seconds-to-time (org-matcher-time s))))
18035 (t (error "Not a standard Org time string: %s" s))))
18037 (defun org-timestamp-up (&optional arg)
18038 "Increase the date item at the cursor by one.
18039 If the cursor is on the year, change the year. If it is on the month,
18040 the day or the time, change that.
18041 With prefix ARG, change by that many units."
18042 (interactive "p")
18043 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
18045 (defun org-timestamp-down (&optional arg)
18046 "Decrease the date item at the cursor by one.
18047 If the cursor is on the year, change the year. If it is on the month,
18048 the day or the time, change that.
18049 With prefix ARG, change by that many units."
18050 (interactive "p")
18051 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
18053 (defun org-timestamp-up-day (&optional arg)
18054 "Increase the date in the time stamp by one day.
18055 With prefix ARG, change that many days."
18056 (interactive "p")
18057 (if (and (not (org-at-timestamp-p t))
18058 (org-at-heading-p))
18059 (org-todo 'up)
18060 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
18062 (defun org-timestamp-down-day (&optional arg)
18063 "Decrease the date in the time stamp by one day.
18064 With prefix ARG, change that many days."
18065 (interactive "p")
18066 (if (and (not (org-at-timestamp-p t))
18067 (org-at-heading-p))
18068 (org-todo 'down)
18069 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
18071 (defun org-at-timestamp-p (&optional inactive-ok)
18072 "Non-nil if point is inside a timestamp.
18074 When optional argument INACTIVE-OK is non-nil, also consider
18075 inactive timestamps.
18077 When this function returns a non-nil value, match data is set
18078 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18079 INACTIVE-OK."
18080 (interactive)
18081 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18082 (pos (point))
18083 (ans (or (looking-at tsr)
18084 (save-excursion
18085 (skip-chars-backward "^[<\n\r\t")
18086 (when (> (point) (point-min)) (backward-char 1))
18087 (and (looking-at tsr)
18088 (> (- (match-end 0) pos) -1))))))
18089 (and ans
18090 (boundp 'org-ts-what)
18091 (setq org-ts-what
18092 (cond
18093 ((= pos (match-beginning 0)) 'bracket)
18094 ;; Point is considered to be "on the bracket" whether
18095 ;; it's really on it or right after it.
18096 ((= pos (1- (match-end 0))) 'bracket)
18097 ((= pos (match-end 0)) 'after)
18098 ((org-pos-in-match-range pos 2) 'year)
18099 ((org-pos-in-match-range pos 3) 'month)
18100 ((org-pos-in-match-range pos 7) 'hour)
18101 ((org-pos-in-match-range pos 8) 'minute)
18102 ((or (org-pos-in-match-range pos 4)
18103 (org-pos-in-match-range pos 5)) 'day)
18104 ((and (> pos (or (match-end 8) (match-end 5)))
18105 (< pos (match-end 0)))
18106 (- pos (or (match-end 8) (match-end 5))))
18107 (t 'day))))
18108 ans))
18110 (defun org-toggle-timestamp-type ()
18111 "Toggle the type (<active> or [inactive]) of a time stamp."
18112 (interactive)
18113 (when (org-at-timestamp-p t)
18114 (let ((beg (match-beginning 0)) (end (match-end 0))
18115 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18116 (save-excursion
18117 (goto-char beg)
18118 (while (re-search-forward "[][<>]" end t)
18119 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18120 t t)))
18121 (message "Timestamp is now %sactive"
18122 (if (equal (char-after beg) ?<) "" "in")))))
18124 (defun org-at-clock-log-p nil
18125 "Is the cursor on the clock log line?"
18126 (save-excursion
18127 (move-beginning-of-line 1)
18128 (looking-at org-clock-line-re)))
18130 (defvar org-clock-history) ; defined in org-clock.el
18131 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18132 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18133 "Change the date in the time stamp at point.
18134 The date will be changed by N times WHAT. WHAT can be `day', `month',
18135 `year', `minute', `second'. If WHAT is not given, the cursor position
18136 in the timestamp determines what will be changed.
18137 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18138 (let ((origin (point)) origin-cat
18139 with-hm inactive
18140 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18141 org-ts-what
18142 extra rem
18143 ts time time0 fixnext clrgx)
18144 (unless (org-at-timestamp-p t)
18145 (user-error "Not at a timestamp"))
18146 (if (and (not what) (eq org-ts-what 'bracket))
18147 (org-toggle-timestamp-type)
18148 ;; Point isn't on brackets. Remember the part of the time-stamp
18149 ;; the point was in. Indeed, size of time-stamps may change,
18150 ;; but point must be kept in the same category nonetheless.
18151 (setq origin-cat org-ts-what)
18152 (when (and (not what) (not (eq org-ts-what 'day))
18153 org-display-custom-times
18154 (get-text-property (point) 'display)
18155 (not (get-text-property (1- (point)) 'display)))
18156 (setq org-ts-what 'day))
18157 (setq org-ts-what (or what org-ts-what)
18158 inactive (= (char-after (match-beginning 0)) ?\[)
18159 ts (match-string 0))
18160 (replace-match "")
18161 (when (string-match
18162 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18164 (setq extra (match-string 1 ts))
18165 (when suppress-tmp-delay
18166 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18167 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18168 (setq with-hm t))
18169 (setq time0 (org-parse-time-string ts))
18170 (when (and updown
18171 (eq org-ts-what 'minute)
18172 (not current-prefix-arg))
18173 ;; This looks like s-up and s-down. Change by one rounding step.
18174 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18175 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18176 (setcar (cdr time0) (+ (nth 1 time0)
18177 (if (> n 0) (- rem) (- dm rem))))))
18178 (setq time
18179 (apply #'encode-time
18180 (or (car time0) 0)
18181 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18182 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18183 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18184 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18185 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18186 (nthcdr 6 time0)))
18187 (when (and (member org-ts-what '(hour minute))
18188 extra
18189 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18190 (setq extra (org-modify-ts-extra
18191 extra
18192 (if (eq org-ts-what 'hour) 2 5)
18193 n dm)))
18194 (when (integerp org-ts-what)
18195 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18196 (when (eq what 'calendar)
18197 (let ((cal-date (org-get-date-from-calendar)))
18198 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18199 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18200 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18201 (setcar time0 (or (car time0) 0))
18202 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18203 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18204 (setq time (apply 'encode-time time0))))
18205 ;; Insert the new time-stamp, and ensure point stays in the same
18206 ;; category as before (i.e. not after the last position in that
18207 ;; category).
18208 (let ((pos (point)))
18209 ;; Stay before inserted string. `save-excursion' is of no use.
18210 (setq org-last-changed-timestamp
18211 (org-insert-time-stamp time with-hm inactive nil nil extra))
18212 (goto-char pos))
18213 (save-match-data
18214 (looking-at org-ts-regexp3)
18215 (goto-char
18216 (pcase origin-cat
18217 ;; `day' category ends before `hour' if any, or at the end
18218 ;; of the day name.
18219 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18220 (`hour (min (match-end 7) origin))
18221 (`minute (min (1- (match-end 8)) origin))
18222 ((pred integerp) (min (1- (match-end 0)) origin))
18223 ;; Point was right after the time-stamp. However, the
18224 ;; time-stamp length might have changed, so refer to
18225 ;; (match-end 0) instead.
18226 (`after (match-end 0))
18227 ;; `year' and `month' have both fixed size: point couldn't
18228 ;; have moved into another part.
18229 (_ origin))))
18230 ;; Update clock if on a CLOCK line.
18231 (org-clock-update-time-maybe)
18232 ;; Maybe adjust the closest clock in `org-clock-history'
18233 (when org-clock-adjust-closest
18234 (if (not (and (org-at-clock-log-p)
18235 (< 1 (length (delq nil (mapcar 'marker-position
18236 org-clock-history))))))
18237 (message "No clock to adjust")
18238 (cond ((save-excursion ; fix previous clock?
18239 (re-search-backward org-ts-regexp0 nil t)
18240 (looking-back (concat org-clock-string " \\[")
18241 (line-beginning-position)))
18242 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18243 ((save-excursion ; fix next clock?
18244 (re-search-backward org-ts-regexp0 nil t)
18245 (looking-at (concat org-ts-regexp0 "\\] =>")))
18246 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18247 (save-window-excursion
18248 ;; Find closest clock to point, adjust the previous/next one in history
18249 (let* ((p (save-excursion (org-back-to-heading t)))
18250 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18251 (clfixnth
18252 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18253 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18254 (if (not clfixpos)
18255 (message "No clock to adjust")
18256 (save-excursion
18257 (org-goto-marker-or-bmk clfixpos)
18258 (org-show-subtree)
18259 (when (re-search-forward clrgx nil t)
18260 (goto-char (match-beginning 1))
18261 (let (org-clock-adjust-closest)
18262 (org-timestamp-change n org-ts-what updown))
18263 (message "Clock adjusted in %s for heading: %s"
18264 (file-name-nondirectory (buffer-file-name))
18265 (org-get-heading t t)))))))))
18266 ;; Try to recenter the calendar window, if any.
18267 (when (and org-calendar-follow-timestamp-change
18268 (get-buffer-window "*Calendar*" t)
18269 (memq org-ts-what '(day month year)))
18270 (org-recenter-calendar (time-to-days time))))))
18272 (defun org-modify-ts-extra (s pos n dm)
18273 "Change the different parts of the lead-time and repeat fields in timestamp."
18274 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18275 ng h m new rem)
18276 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18277 (cond
18278 ((or (org-pos-in-match-range pos 2)
18279 (org-pos-in-match-range pos 3))
18280 (setq m (string-to-number (match-string 3 s))
18281 h (string-to-number (match-string 2 s)))
18282 (if (org-pos-in-match-range pos 2)
18283 (setq h (+ h n))
18284 (setq n (* dm (with-no-warnings (signum n))))
18285 (unless (= 0 (setq rem (% m dm)))
18286 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18287 (setq m (+ m n)))
18288 (when (< m 0) (setq m (+ m 60) h (1- h)))
18289 (when (> m 59) (setq m (- m 60) h (1+ h)))
18290 (setq h (mod h 24))
18291 (setq ng 1 new (format "-%02d:%02d" h m)))
18292 ((org-pos-in-match-range pos 6)
18293 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18294 ((org-pos-in-match-range pos 5)
18295 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18297 ((org-pos-in-match-range pos 9)
18298 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18299 ((org-pos-in-match-range pos 8)
18300 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18302 (when ng
18303 (setq s (concat
18304 (substring s 0 (match-beginning ng))
18306 (substring s (match-end ng))))))
18309 (defun org-recenter-calendar (d)
18310 "If the calendar is visible, recenter it to date D."
18311 (let ((cwin (get-buffer-window "*Calendar*" t)))
18312 (when cwin
18313 (let ((calendar-move-hook nil))
18314 (with-selected-window cwin
18315 (calendar-goto-date
18316 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18318 (defun org-goto-calendar (&optional arg)
18319 "Go to the Emacs calendar at the current date.
18320 If there is a time stamp in the current line, go to that date.
18321 A prefix ARG can be used to force the current date."
18322 (interactive "P")
18323 (let ((tsr org-ts-regexp) diff
18324 (calendar-move-hook nil)
18325 (calendar-view-holidays-initially-flag nil)
18326 (calendar-view-diary-initially-flag nil))
18327 (when (or (org-at-timestamp-p)
18328 (save-excursion
18329 (beginning-of-line 1)
18330 (looking-at (concat ".*" tsr))))
18331 (let ((d1 (time-to-days (current-time)))
18332 (d2 (time-to-days
18333 (org-time-string-to-time (match-string 1)))))
18334 (setq diff (- d2 d1))))
18335 (calendar)
18336 (calendar-goto-today)
18337 (when (and diff (not arg)) (calendar-forward-day diff))))
18339 (defun org-get-date-from-calendar ()
18340 "Return a list (month day year) of date at point in calendar."
18341 (with-current-buffer "*Calendar*"
18342 (save-match-data
18343 (calendar-cursor-to-date))))
18345 (defun org-date-from-calendar ()
18346 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18347 If there is already a time stamp at the cursor position, update it."
18348 (interactive)
18349 (if (org-at-timestamp-p t)
18350 (org-timestamp-change 0 'calendar)
18351 (let ((cal-date (org-get-date-from-calendar)))
18352 (org-insert-time-stamp
18353 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18355 (defcustom org-effort-durations
18356 `(("min" . 1)
18357 ("h" . 60)
18358 ("d" . ,(* 60 8))
18359 ("w" . ,(* 60 8 5))
18360 ("m" . ,(* 60 8 5 4))
18361 ("y" . ,(* 60 8 5 40)))
18362 "Conversion factor to minutes for an effort modifier.
18364 Each entry has the form (MODIFIER . MINUTES).
18366 In an effort string, a number followed by MODIFIER is multiplied
18367 by the specified number of MINUTES to obtain an effort in
18368 minutes.
18370 For example, if the value of this variable is ((\"hours\" . 60)), then an
18371 effort string \"2hours\" is equivalent to 120 minutes."
18372 :group 'org-agenda
18373 :version "25.2"
18374 :package-version '(Org . "8.3")
18375 :type '(alist :key-type (string :tag "Modifier")
18376 :value-type (number :tag "Minutes")))
18378 (defun org-minutes-to-clocksum-string (m)
18379 "Format number of minutes as a clocksum string.
18380 The format is determined by `org-time-clocksum-format',
18381 `org-time-clocksum-use-fractional' and
18382 `org-time-clocksum-fractional-format' and
18383 `org-time-clocksum-use-effort-durations'."
18384 (let ((clocksum "")
18385 (m (round m)) ; Don't allow fractions of minutes
18386 h d w mo y fmt n)
18387 (setq h (if org-time-clocksum-use-effort-durations
18388 (cdr (assoc "h" org-effort-durations)) 60)
18389 d (if org-time-clocksum-use-effort-durations
18390 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18391 w (if org-time-clocksum-use-effort-durations
18392 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18393 mo (if org-time-clocksum-use-effort-durations
18394 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18395 y (if org-time-clocksum-use-effort-durations
18396 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18397 ;; fractional format
18398 (if org-time-clocksum-use-fractional
18399 (cond
18400 ;; single format string
18401 ((stringp org-time-clocksum-fractional-format)
18402 (format org-time-clocksum-fractional-format (/ m (float h))))
18403 ;; choice of fractional formats for different time units
18404 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18405 (> (/ (truncate m) (* y d h)) 0))
18406 (format fmt (/ m (* y d (float h)))))
18407 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18408 (> (/ (truncate m) (* mo d h)) 0))
18409 (format fmt (/ m (* mo d (float h)))))
18410 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18411 (> (/ (truncate m) (* w d h)) 0))
18412 (format fmt (/ m (* w d (float h)))))
18413 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18414 (> (/ (truncate m) (* d h)) 0))
18415 (format fmt (/ m (* d (float h)))))
18416 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18417 (> (/ (truncate m) h) 0))
18418 (format fmt (/ m (float h))))
18419 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18420 (format fmt m))
18421 ;; fall back to smallest time unit with a format
18422 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18423 (format fmt (/ m (float h))))
18424 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18425 (format fmt (/ m (* d (float h)))))
18426 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18427 (format fmt (/ m (* w d (float h)))))
18428 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18429 (format fmt (/ m (* mo d (float h)))))
18430 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18431 (format fmt (/ m (* y d (float h))))))
18432 ;; standard (non-fractional) format, with single format string
18433 (if (stringp org-time-clocksum-format)
18434 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18435 ;; separate formats components
18436 (and (setq fmt (plist-get org-time-clocksum-format :years))
18437 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18438 (plist-get org-time-clocksum-format :require-years))
18439 (setq clocksum (concat clocksum (format fmt n))
18440 m (- m (* n y d h))))
18441 (and (setq fmt (plist-get org-time-clocksum-format :months))
18442 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18443 (plist-get org-time-clocksum-format :require-months))
18444 (setq clocksum (concat clocksum (format fmt n))
18445 m (- m (* n mo d h))))
18446 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18447 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18448 (plist-get org-time-clocksum-format :require-weeks))
18449 (setq clocksum (concat clocksum (format fmt n))
18450 m (- m (* n w d h))))
18451 (and (setq fmt (plist-get org-time-clocksum-format :days))
18452 (or (> (setq n (/ (truncate m) (* d h))) 0)
18453 (plist-get org-time-clocksum-format :require-days))
18454 (setq clocksum (concat clocksum (format fmt n))
18455 m (- m (* n d h))))
18456 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18457 (or (> (setq n (/ (truncate m) h)) 0)
18458 (plist-get org-time-clocksum-format :require-hours))
18459 (setq clocksum (concat clocksum (format fmt n))
18460 m (- m (* n h))))
18461 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18462 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18463 (setq clocksum (concat clocksum (format fmt m))))
18464 ;; return formatted time duration
18465 clocksum))))
18467 (defun org-hours-to-clocksum-string (n)
18468 (org-minutes-to-clocksum-string (* n 60)))
18470 (defun org-hh:mm-string-to-minutes (s)
18471 "Convert a string H:MM to a number of minutes.
18472 If the string is just a number, interpret it as minutes.
18473 In fact, the first hh:mm or number in the string will be taken,
18474 there can be extra stuff in the string.
18475 If no number is found, the return value is 0."
18476 (cond
18477 ((integerp s) s)
18478 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18479 (+ (* (string-to-number (match-string 1 s)) 60)
18480 (string-to-number (match-string 2 s))))
18481 ((string-match "\\([0-9]+\\)" s)
18482 (string-to-number (match-string 1 s)))
18483 (t 0)))
18485 (defcustom org-image-actual-width t
18486 "Should we use the actual width of images when inlining them?
18488 When set to t, always use the image width.
18490 When set to a number, use imagemagick (when available) to set
18491 the image's width to this value.
18493 When set to a number in a list, try to get the width from any
18494 #+ATTR.* keyword if it matches a width specification like
18496 #+ATTR_HTML: :width 300px
18498 and fall back on that number if none is found.
18500 When set to nil, try to get the width from an #+ATTR.* keyword
18501 and fall back on the original width if none is found.
18503 This requires Emacs >= 24.1, build with imagemagick support."
18504 :group 'org-appearance
18505 :version "24.4"
18506 :package-version '(Org . "8.0")
18507 :type '(choice
18508 (const :tag "Use the image width" t)
18509 (integer :tag "Use a number of pixels")
18510 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18511 (const :tag "Use #+ATTR* or don't resize" nil)))
18513 (defcustom org-agenda-inhibit-startup nil
18514 "Inhibit startup when preparing agenda buffers.
18515 When this variable is t, the initialization of the Org agenda
18516 buffers is inhibited: e.g. the visibility state is not set, the
18517 tables are not re-aligned, etc."
18518 :type 'boolean
18519 :version "24.3"
18520 :group 'org-agenda)
18522 (defcustom org-agenda-ignore-properties nil
18523 "Avoid updating text properties when building the agenda.
18524 Properties are used to prepare buffers for effort estimates,
18525 appointments, statistics and subtree-local categories.
18526 If you don't use these in the agenda, you can add them to this
18527 list and agenda building will be a bit faster.
18528 The value is a list, with zero or more of the symbols `effort', `appt',
18529 `stats' or `category'."
18530 :type '(set :greedy t
18531 (const effort)
18532 (const appt)
18533 (const stats)
18534 (const category))
18535 :version "25.2"
18536 :package-version '(Org . "8.3")
18537 :group 'org-agenda)
18539 (defun org-duration-string-to-minutes (s &optional output-to-string)
18540 "Convert a duration string S to minutes.
18542 A bare number is interpreted as minutes, modifiers can be set by
18543 customizing `org-effort-durations' (which see).
18545 Entries containing a colon are interpreted as H:MM by
18546 `org-hh:mm-string-to-minutes'."
18547 (let ((result 0)
18548 (re (concat "\\([0-9.]+\\) *\\("
18549 (regexp-opt (mapcar 'car org-effort-durations))
18550 "\\)")))
18551 (while (string-match re s)
18552 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18553 (string-to-number (match-string 1 s))))
18554 (setq s (replace-match "" nil t s)))
18555 (setq result (floor result))
18556 (cl-incf result (org-hh:mm-string-to-minutes s))
18557 (if output-to-string (number-to-string result) result)))
18559 ;;;; Files
18561 (defun org-save-all-org-buffers ()
18562 "Save all Org buffers without user confirmation."
18563 (interactive)
18564 (message "Saving all Org buffers...")
18565 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18566 (when (featurep 'org-id) (org-id-locations-save))
18567 (message "Saving all Org buffers... done"))
18569 (defun org-revert-all-org-buffers ()
18570 "Revert all Org buffers.
18571 Prompt for confirmation when there are unsaved changes.
18572 Be sure you know what you are doing before letting this function
18573 overwrite your changes.
18575 This function is useful in a setup where one tracks org files
18576 with a version control system, to revert on one machine after pulling
18577 changes from another. I believe the procedure must be like this:
18579 1. M-x org-save-all-org-buffers
18580 2. Pull changes from the other machine, resolve conflicts
18581 3. M-x org-revert-all-org-buffers"
18582 (interactive)
18583 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18584 (user-error "Abort"))
18585 (save-excursion
18586 (save-window-excursion
18587 (dolist (b (buffer-list))
18588 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18589 (with-current-buffer b buffer-file-name))
18590 (pop-to-buffer-same-window b)
18591 (revert-buffer t 'no-confirm)))
18592 (when (and (featurep 'org-id) org-id-track-globally)
18593 (org-id-locations-load)))))
18595 ;;;; Agenda files
18597 ;;;###autoload
18598 (defun org-switchb (&optional arg)
18599 "Switch between Org buffers.
18601 With `\\[universal-argument]' prefix, restrict available buffers to files.
18603 With `\\[universal-argument] \\[universal-argument]' \
18604 prefix, restrict available buffers to agenda files."
18605 (interactive "P")
18606 (let ((blist (org-buffer-list
18607 (cond ((equal arg '(4)) 'files)
18608 ((equal arg '(16)) 'agenda)))))
18609 (pop-to-buffer-same-window
18610 (completing-read "Org buffer: "
18611 (mapcar #'list (mapcar #'buffer-name blist))
18612 nil t))))
18614 (defun org-buffer-list (&optional predicate exclude-tmp)
18615 "Return a list of Org buffers.
18616 PREDICATE can be `export', `files' or `agenda'.
18618 export restrict the list to Export buffers.
18619 files restrict the list to buffers visiting Org files.
18620 agenda restrict the list to buffers visiting agenda files.
18622 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18623 (let* ((bfn nil)
18624 (agenda-files (and (eq predicate 'agenda)
18625 (mapcar 'file-truename (org-agenda-files t))))
18626 (filter
18627 (cond
18628 ((eq predicate 'files)
18629 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18630 ((eq predicate 'export)
18631 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18632 ((eq predicate 'agenda)
18633 (lambda (b)
18634 (with-current-buffer b
18635 (and (derived-mode-p 'org-mode)
18636 (setq bfn (buffer-file-name b))
18637 (member (file-truename bfn) agenda-files)))))
18638 (t (lambda (b) (with-current-buffer b
18639 (or (derived-mode-p 'org-mode)
18640 (string-match "\\*Org .*Export"
18641 (buffer-name b)))))))))
18642 (delq nil
18643 (mapcar
18644 (lambda(b)
18645 (if (and (funcall filter b)
18646 (or (not exclude-tmp)
18647 (not (string-match "tmp" (buffer-name b)))))
18649 nil))
18650 (buffer-list)))))
18652 (defun org-agenda-files (&optional unrestricted archives)
18653 "Get the list of agenda files.
18654 Optional UNRESTRICTED means return the full list even if a restriction
18655 is currently in place.
18656 When ARCHIVES is t, include all archive files that are really being
18657 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18658 `org-agenda-archives-mode' is t."
18659 (let ((files
18660 (cond
18661 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18662 ((stringp org-agenda-files) (org-read-agenda-file-list))
18663 ((listp org-agenda-files) org-agenda-files)
18664 (t (error "Invalid value of `org-agenda-files'")))))
18665 (setq files (apply 'append
18666 (mapcar (lambda (f)
18667 (if (file-directory-p f)
18668 (directory-files
18669 f t org-agenda-file-regexp)
18670 (list f)))
18671 files)))
18672 (when org-agenda-skip-unavailable-files
18673 (setq files (delq nil
18674 (mapcar (function
18675 (lambda (file)
18676 (and (file-readable-p file) file)))
18677 files))))
18678 (when (or (eq archives t)
18679 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18680 (setq files (org-add-archive-files files)))
18681 files))
18683 (defun org-agenda-file-p (&optional file)
18684 "Return non-nil, if FILE is an agenda file.
18685 If FILE is omitted, use the file associated with the current
18686 buffer."
18687 (let ((fname (or file (buffer-file-name))))
18688 (and fname
18689 (member (file-truename fname)
18690 (mapcar #'file-truename (org-agenda-files t))))))
18692 (defun org-edit-agenda-file-list ()
18693 "Edit the list of agenda files.
18694 Depending on setup, this either uses customize to edit the variable
18695 `org-agenda-files', or it visits the file that is holding the list. In the
18696 latter case, the buffer is set up in a way that saving it automatically kills
18697 the buffer and restores the previous window configuration."
18698 (interactive)
18699 (if (stringp org-agenda-files)
18700 (let ((cw (current-window-configuration)))
18701 (find-file org-agenda-files)
18702 (setq-local org-window-configuration cw)
18703 (add-hook 'after-save-hook
18704 (lambda ()
18705 (set-window-configuration
18706 (prog1 org-window-configuration
18707 (kill-buffer (current-buffer))))
18708 (org-install-agenda-files-menu)
18709 (message "New agenda file list installed"))
18710 nil 'local)
18711 (message "%s" (substitute-command-keys
18712 "Edit list and finish with \\[save-buffer]")))
18713 (customize-variable 'org-agenda-files)))
18715 (defun org-store-new-agenda-file-list (list)
18716 "Set new value for the agenda file list and save it correctly."
18717 (if (stringp org-agenda-files)
18718 (let ((fe (org-read-agenda-file-list t)) b u)
18719 (while (setq b (find-buffer-visiting org-agenda-files))
18720 (kill-buffer b))
18721 (with-temp-file org-agenda-files
18722 (insert
18723 (mapconcat
18724 (lambda (f) ;; Keep un-expanded entries.
18725 (if (setq u (assoc f fe))
18726 (cdr u)
18728 list "\n")
18729 "\n")))
18730 (let ((org-mode-hook nil) (org-inhibit-startup t)
18731 (org-insert-mode-line-in-empty-file nil))
18732 (setq org-agenda-files list)
18733 (customize-save-variable 'org-agenda-files org-agenda-files))))
18735 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18736 "Read the list of agenda files from a file.
18737 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18738 filenames, used by `org-store-new-agenda-file-list' to write back
18739 un-expanded file names."
18740 (when (file-directory-p org-agenda-files)
18741 (error "`org-agenda-files' cannot be a single directory"))
18742 (when (stringp org-agenda-files)
18743 (with-temp-buffer
18744 (insert-file-contents org-agenda-files)
18745 (mapcar
18746 (lambda (f)
18747 (let ((e (expand-file-name (substitute-in-file-name f)
18748 org-directory)))
18749 (if pair-with-expansion
18750 (cons e f)
18751 e)))
18752 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18754 ;;;###autoload
18755 (defun org-cycle-agenda-files ()
18756 "Cycle through the files in `org-agenda-files'.
18757 If the current buffer visits an agenda file, find the next one in the list.
18758 If the current buffer does not, find the first agenda file."
18759 (interactive)
18760 (let* ((fs (or (org-agenda-files t)
18761 (user-error "No agenda files")))
18762 (files (copy-sequence fs))
18763 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18764 file)
18765 (when tcf
18766 (while (and (setq file (pop files))
18767 (not (equal (file-truename file) tcf)))))
18768 (find-file (car (or files fs)))
18769 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18771 (defun org-agenda-file-to-front (&optional to-end)
18772 "Move/add the current file to the top of the agenda file list.
18773 If the file is not present in the list, it is added to the front. If it is
18774 present, it is moved there. With optional argument TO-END, add/move to the
18775 end of the list."
18776 (interactive "P")
18777 (let ((org-agenda-skip-unavailable-files nil)
18778 (file-alist (mapcar (lambda (x)
18779 (cons (file-truename x) x))
18780 (org-agenda-files t)))
18781 (ctf (file-truename
18782 (or buffer-file-name
18783 (user-error "Please save the current buffer to a file"))))
18784 x had)
18785 (setq x (assoc ctf file-alist) had x)
18787 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18788 (if to-end
18789 (setq file-alist (append (delq x file-alist) (list x)))
18790 (setq file-alist (cons x (delq x file-alist))))
18791 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18792 (org-install-agenda-files-menu)
18793 (message "File %s to %s of agenda file list"
18794 (if had "moved" "added") (if to-end "end" "front"))))
18796 (defun org-remove-file (&optional file)
18797 "Remove current file from the list of files in variable `org-agenda-files'.
18798 These are the files which are being checked for agenda entries.
18799 Optional argument FILE means use this file instead of the current."
18800 (interactive)
18801 (let* ((org-agenda-skip-unavailable-files nil)
18802 (file (or file buffer-file-name
18803 (user-error "Current buffer does not visit a file")))
18804 (true-file (file-truename file))
18805 (afile (abbreviate-file-name file))
18806 (files (delq nil (mapcar
18807 (lambda (x)
18808 (unless (equal true-file
18809 (file-truename x))
18811 (org-agenda-files t)))))
18812 (if (not (= (length files) (length (org-agenda-files t))))
18813 (progn
18814 (org-store-new-agenda-file-list files)
18815 (org-install-agenda-files-menu)
18816 (message "Removed from Org Agenda list: %s" afile))
18817 (message "File was not in list: %s (not removed)" afile))))
18819 (defun org-file-menu-entry (file)
18820 (vector file (list 'find-file file) t))
18822 (defun org-check-agenda-file (file)
18823 "Make sure FILE exists. If not, ask user what to do."
18824 (unless (file-exists-p file)
18825 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18826 (abbreviate-file-name file))
18827 (let ((r (downcase (read-char-exclusive))))
18828 (cond
18829 ((equal r ?r)
18830 (org-remove-file file)
18831 (throw 'nextfile t))
18832 (t (user-error "Abort"))))))
18834 (defun org-get-agenda-file-buffer (file)
18835 "Get an agenda buffer visiting FILE.
18836 If the buffer needs to be created, add it to the list of buffers
18837 which might be released later."
18838 (let ((buf (org-find-base-buffer-visiting file)))
18839 (if buf
18840 buf ; just return it
18841 ;; Make a new buffer and remember it
18842 (setq buf (find-file-noselect file))
18843 (when buf (push buf org-agenda-new-buffers))
18844 buf)))
18846 (defun org-release-buffers (blist)
18847 "Release all buffers in list, asking the user for confirmation when needed.
18848 When a buffer is unmodified, it is just killed. When modified, it is saved
18849 \(if the user agrees) and then killed."
18850 (let (file)
18851 (dolist (buf blist)
18852 (setq file (buffer-file-name buf))
18853 (when (and (buffer-modified-p buf)
18854 file
18855 (y-or-n-p (format "Save file %s? " file)))
18856 (with-current-buffer buf (save-buffer)))
18857 (kill-buffer buf))))
18859 (defun org-agenda-prepare-buffers (files)
18860 "Create buffers for all agenda files, protect archived trees and comments."
18861 (interactive)
18862 (let ((pa '(:org-archived t))
18863 (pc '(:org-comment t))
18864 (pall '(:org-archived t :org-comment t))
18865 (inhibit-read-only t)
18866 (org-inhibit-startup org-agenda-inhibit-startup)
18867 (rea (concat ":" org-archive-tag ":"))
18868 re pos)
18869 (setq org-tag-alist-for-agenda nil
18870 org-tag-groups-alist-for-agenda nil)
18871 (save-excursion
18872 (save-restriction
18873 (dolist (file files)
18874 (catch 'nextfile
18875 (if (bufferp file)
18876 (set-buffer file)
18877 (org-check-agenda-file file)
18878 (set-buffer (org-get-agenda-file-buffer file)))
18879 (widen)
18880 (org-set-regexps-and-options 'tags-only)
18881 (setq pos (point))
18882 (or (memq 'category org-agenda-ignore-properties)
18883 (org-refresh-category-properties))
18884 (or (memq 'stats org-agenda-ignore-properties)
18885 (org-refresh-stats-properties))
18886 (or (memq 'effort org-agenda-ignore-properties)
18887 (org-refresh-effort-properties))
18888 (or (memq 'appt org-agenda-ignore-properties)
18889 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18890 (setq org-todo-keywords-for-agenda
18891 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18892 (setq org-done-keywords-for-agenda
18893 (append org-done-keywords-for-agenda org-done-keywords))
18894 (setq org-todo-keyword-alist-for-agenda
18895 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18896 (setq org-tag-alist-for-agenda
18897 (org-uniquify
18898 (append org-tag-alist-for-agenda
18899 org-current-tag-alist)))
18900 ;; Merge current file's tag groups into global
18901 ;; `org-tag-groups-alist-for-agenda'.
18902 (when org-group-tags
18903 (dolist (alist org-tag-groups-alist)
18904 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18905 (if old
18906 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18907 (push alist org-tag-groups-alist-for-agenda)))))
18908 (org-with-silent-modifications
18909 (save-excursion
18910 (remove-text-properties (point-min) (point-max) pall)
18911 (when org-agenda-skip-archived-trees
18912 (goto-char (point-min))
18913 (while (re-search-forward rea nil t)
18914 (when (org-at-heading-p t)
18915 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18916 (goto-char (point-min))
18917 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18918 (while (re-search-forward re nil t)
18919 (when (save-match-data (org-in-commented-heading-p t))
18920 (add-text-properties
18921 (match-beginning 0) (org-end-of-subtree t) pc)))))
18922 (goto-char pos)))))
18923 (setq org-todo-keywords-for-agenda
18924 (org-uniquify org-todo-keywords-for-agenda))
18925 (setq org-todo-keyword-alist-for-agenda
18926 (org-uniquify org-todo-keyword-alist-for-agenda))))
18929 ;;;; CDLaTeX minor mode
18931 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18932 "Keymap for the minor `org-cdlatex-mode'.")
18934 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18935 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18936 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18937 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18938 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18940 (defvar org-cdlatex-texmathp-advice-is-done nil
18941 "Flag remembering if we have applied the advice to texmathp already.")
18943 (define-minor-mode org-cdlatex-mode
18944 "Toggle the minor `org-cdlatex-mode'.
18945 This mode supports entering LaTeX environment and math in LaTeX fragments
18946 in Org mode.
18947 \\{org-cdlatex-mode-map}"
18948 nil " OCDL" nil
18949 (when org-cdlatex-mode
18950 (require 'cdlatex)
18951 (run-hooks 'cdlatex-mode-hook)
18952 (cdlatex-compute-tables))
18953 (unless org-cdlatex-texmathp-advice-is-done
18954 (setq org-cdlatex-texmathp-advice-is-done t)
18955 (defadvice texmathp (around org-math-always-on activate)
18956 "Always return t in Org buffers.
18957 This is because we want to insert math symbols without dollars even outside
18958 the LaTeX math segments. If Org mode thinks that point is actually inside
18959 an embedded LaTeX fragment, let `texmathp' do its job.
18960 `\\[org-cdlatex-mode-map]'"
18961 (interactive)
18962 (let (p)
18963 (cond
18964 ((not (derived-mode-p 'org-mode)) ad-do-it)
18965 ((eq this-command 'cdlatex-math-symbol)
18966 (setq ad-return-value t
18967 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18969 (let ((p (org-inside-LaTeX-fragment-p)))
18970 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18971 (setq ad-return-value t
18972 texmathp-why '("Org mode embedded math" . 0))
18973 (when p ad-do-it)))))))))
18975 (defun turn-on-org-cdlatex ()
18976 "Unconditionally turn on `org-cdlatex-mode'."
18977 (org-cdlatex-mode 1))
18979 (defun org-try-cdlatex-tab ()
18980 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18981 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18982 - inside a LaTeX fragment, or
18983 - after the first word in a line, where an abbreviation expansion could
18984 insert a LaTeX environment."
18985 (when org-cdlatex-mode
18986 (cond
18987 ;; Before any word on the line: No expansion possible.
18988 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18989 ;; Just after first word on the line: Expand it. Make sure it
18990 ;; cannot happen on headlines, though.
18991 ((save-excursion
18992 (skip-chars-backward "a-zA-Z0-9*")
18993 (skip-chars-backward " \t")
18994 (and (bolp) (not (org-at-heading-p))))
18995 (cdlatex-tab) t)
18996 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18998 (defun org-cdlatex-underscore-caret (&optional _arg)
18999 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
19000 Revert to the normal definition outside of these fragments."
19001 (interactive "P")
19002 (if (org-inside-LaTeX-fragment-p)
19003 (call-interactively 'cdlatex-sub-superscript)
19004 (let (org-cdlatex-mode)
19005 (call-interactively (key-binding (vector last-input-event))))))
19007 (defun org-cdlatex-math-modify (&optional _arg)
19008 "Execute `cdlatex-math-modify' in LaTeX fragments.
19009 Revert to the normal definition outside of these fragments."
19010 (interactive "P")
19011 (if (org-inside-LaTeX-fragment-p)
19012 (call-interactively 'cdlatex-math-modify)
19013 (let (org-cdlatex-mode)
19014 (call-interactively (key-binding (vector last-input-event))))))
19016 (defun org-cdlatex-environment-indent (&optional environment item)
19017 "Execute `cdlatex-environment' and indent the inserted environment.
19019 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
19021 The inserted environment is indented to current indentation
19022 unless point is at the beginning of the line, in which the
19023 environment remains unintended."
19024 (interactive)
19025 ;; cdlatex-environment always return nil. Therefore, capture output
19026 ;; first and determine if an environment was selected.
19027 (let* ((beg (point-marker))
19028 (end (copy-marker (point) t))
19029 (inserted (progn
19030 (ignore-errors (cdlatex-environment environment item))
19031 (< beg end)))
19032 ;; Figure out how many lines to move forward after the
19033 ;; environment has been inserted.
19034 (lines (when inserted
19035 (save-excursion
19036 (- (cl-loop while (< beg (point))
19037 with x = 0
19038 do (forward-line -1)
19039 (cl-incf x)
19040 finally return x)
19041 (if (progn (goto-char beg)
19042 (and (progn (skip-chars-forward " \t") (eolp))
19043 (progn (skip-chars-backward " \t") (bolp))))
19044 1 0)))))
19045 (env (org-trim (delete-and-extract-region beg end))))
19046 (when inserted
19047 ;; Get indentation of next line unless at column 0.
19048 (let ((ind (if (bolp) 0
19049 (save-excursion
19050 (org-return-indent)
19051 (prog1 (org-get-indentation)
19052 (when (progn (skip-chars-forward " \t") (eolp))
19053 (delete-region beg (point)))))))
19054 (bol (progn (skip-chars-backward " \t") (bolp))))
19055 ;; Insert a newline before environment unless at column zero
19056 ;; to "escape" the current line. Insert a newline if
19057 ;; something is one the same line as \end{ENVIRONMENT}.
19058 (insert
19059 (concat (unless bol "\n") env
19060 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
19061 (unless (zerop ind)
19062 (save-excursion
19063 (goto-char beg)
19064 (while (< (point) end)
19065 (unless (eolp) (indent-line-to ind))
19066 (forward-line))))
19067 (goto-char beg)
19068 (forward-line lines)
19069 (indent-line-to ind)))
19070 (set-marker beg nil)
19071 (set-marker end nil)))
19074 ;;;; LaTeX fragments
19076 (defun org-inside-LaTeX-fragment-p ()
19077 "Test if point is inside a LaTeX fragment.
19078 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19079 sequence appearing also before point.
19080 Even though the matchers for math are configurable, this function assumes
19081 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19082 delimiters are skipped when they have been removed by customization.
19083 The return value is nil, or a cons cell with the delimiter and the
19084 position of this delimiter.
19086 This function does a reasonably good job, but can locally be fooled by
19087 for example currency specifications. For example it will assume being in
19088 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19089 fragments that are properly closed, but during editing, we have to live
19090 with the uncertainty caused by missing closing delimiters. This function
19091 looks only before point, not after."
19092 (catch 'exit
19093 (let ((pos (point))
19094 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19095 (lim (progn
19096 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19097 (point)))
19098 dd-on str (start 0) m re)
19099 (goto-char pos)
19100 (when dodollar
19101 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19102 re (nth 1 (assoc "$" org-latex-regexps)))
19103 (while (string-match re str start)
19104 (cond
19105 ((= (match-end 0) (length str))
19106 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19107 ((= (match-end 0) (- (length str) 5))
19108 (throw 'exit nil))
19109 (t (setq start (match-end 0))))))
19110 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19111 (goto-char pos)
19112 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19113 (and (match-beginning 2) (throw 'exit nil))
19114 ;; count $$
19115 (while (re-search-backward "\\$\\$" lim t)
19116 (setq dd-on (not dd-on)))
19117 (goto-char pos)
19118 (when dd-on (cons "$$" m))))))
19120 (defun org-inside-latex-macro-p ()
19121 "Is point inside a LaTeX macro or its arguments?"
19122 (save-match-data
19123 (org-in-regexp
19124 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19126 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19127 "Build an overlay between BEG and END using IMAGE file.
19128 Argument IMAGETYPE is the extension of the displayed image,
19129 as a string. It defaults to \"png\"."
19130 (let ((ov (make-overlay beg end))
19131 (imagetype (or (intern imagetype) 'png)))
19132 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19133 (overlay-put ov 'evaporate t)
19134 (overlay-put ov
19135 'modification-hooks
19136 (list (lambda (o _flag _beg _end &optional _l)
19137 (delete-overlay o))))
19138 (overlay-put ov
19139 'display
19140 (list 'image :type imagetype :file image :ascent 'center))))
19142 (defun org--list-latex-overlays (&optional beg end)
19143 "List all Org LaTeX overlays in current buffer.
19144 Limit to overlays between BEG and END when those are provided."
19145 (cl-remove-if-not
19146 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19147 (overlays-in (or beg (point-min)) (or end (point-max)))))
19149 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19150 "Remove all overlays with LaTeX fragment images in current buffer.
19151 When optional arguments BEG and END are non-nil, remove all
19152 overlays between them instead. Return a non-nil value when some
19153 overlays were removed, nil otherwise."
19154 (let ((overlays (org--list-latex-overlays beg end)))
19155 (mapc #'delete-overlay overlays)
19156 overlays))
19158 (defun org-toggle-latex-fragment (&optional arg)
19159 "Preview the LaTeX fragment at point, or all locally or globally.
19161 If the cursor is on a LaTeX fragment, create the image and overlay
19162 it over the source code, if there is none. Remove it otherwise.
19163 If there is no fragment at point, display all fragments in the
19164 current section.
19166 With prefix ARG, preview or clear image for all fragments in the
19167 current subtree or in the whole buffer when used before the first
19168 headline. With a prefix ARG `\\[universal-argument] \
19169 \\[universal-argument]' preview or clear images
19170 for all fragments in the buffer."
19171 (interactive "P")
19172 (when (display-graphic-p)
19173 (catch 'exit
19174 (save-excursion
19175 (let (beg end msg)
19176 (cond
19177 ((or (equal arg '(16))
19178 (and (equal arg '(4))
19179 (org-with-limited-levels (org-before-first-heading-p))))
19180 (if (org-remove-latex-fragment-image-overlays)
19181 (progn (message "LaTeX fragments images removed from buffer")
19182 (throw 'exit nil))
19183 (setq msg "Creating images for buffer...")))
19184 ((equal arg '(4))
19185 (org-with-limited-levels (org-back-to-heading t))
19186 (setq beg (point))
19187 (setq end (progn (org-end-of-subtree t) (point)))
19188 (if (org-remove-latex-fragment-image-overlays beg end)
19189 (progn
19190 (message "LaTeX fragment images removed from subtree")
19191 (throw 'exit nil))
19192 (setq msg "Creating images for subtree...")))
19193 ((let ((datum (org-element-context)))
19194 (when (memq (org-element-type datum)
19195 '(latex-environment latex-fragment))
19196 (setq beg (org-element-property :begin datum))
19197 (setq end (org-element-property :end datum))
19198 (if (org-remove-latex-fragment-image-overlays beg end)
19199 (progn (message "LaTeX fragment image removed")
19200 (throw 'exit nil))
19201 (setq msg "Creating image...")))))
19203 (org-with-limited-levels
19204 (setq beg (if (org-at-heading-p) (line-beginning-position)
19205 (outline-previous-heading)
19206 (point)))
19207 (setq end (progn (outline-next-heading) (point)))
19208 (if (org-remove-latex-fragment-image-overlays beg end)
19209 (progn
19210 (message "LaTeX fragment images removed from section")
19211 (throw 'exit nil))
19212 (setq msg "Creating images for section...")))))
19213 (let ((file (buffer-file-name (buffer-base-buffer))))
19214 (org-format-latex
19215 (concat org-preview-latex-image-directory "org-ltximg")
19216 beg end
19217 ;; Emacs cannot overlay images from remote hosts. Create
19218 ;; it in `temporary-file-directory' instead.
19219 (if (or (not file) (file-remote-p file))
19220 temporary-file-directory
19221 default-directory)
19222 'overlays msg 'forbuffer org-preview-latex-default-process))
19223 (message (concat msg "done")))))))
19225 (defun org-format-latex
19226 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19227 "Replace LaTeX fragments with links to an image.
19229 The function takes care of creating the replacement image.
19231 Only consider fragments between BEG and END when those are
19232 provided.
19234 When optional argument OVERLAYS is non-nil, display the image on
19235 top of the fragment instead of replacing it.
19237 PROCESSING-TYPE is the conversion method to use, as a symbol.
19239 Some of the options can be changed using the variable
19240 `org-format-latex-options', which see."
19241 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19242 (unless (eq processing-type 'verbatim)
19243 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19244 (cnt 0)
19245 checkdir-flag)
19246 (goto-char (or beg (point-min)))
19247 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19248 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19249 (overlay-recenter (or end (point-max))))
19250 (while (re-search-forward math-regexp end t)
19251 (unless (and overlays
19252 (eq (get-char-property (point) 'org-overlay-type)
19253 'org-latex-overlay))
19254 (let* ((context (org-element-context))
19255 (type (org-element-type context)))
19256 (when (memq type '(latex-environment latex-fragment))
19257 (let ((block-type (eq type 'latex-environment))
19258 (value (org-element-property :value context))
19259 (beg (org-element-property :begin context))
19260 (end (save-excursion
19261 (goto-char (org-element-property :end context))
19262 (skip-chars-backward " \r\t\n")
19263 (point))))
19264 (cond
19265 ((eq processing-type 'mathjax)
19266 ;; Prepare for MathJax processing.
19267 (if (not (string-match "\\`\\$\\$?" value))
19268 (goto-char end)
19269 (delete-region beg end)
19270 (if (string= (match-string 0 value) "$$")
19271 (insert "\\[" (substring value 2 -2) "\\]")
19272 (insert "\\(" (substring value 1 -1) "\\)"))))
19273 ((assq processing-type org-preview-latex-process-alist)
19274 ;; Process to an image.
19275 (cl-incf cnt)
19276 (goto-char beg)
19277 (let* ((processing-info
19278 (cdr (assq processing-type org-preview-latex-process-alist)))
19279 (face (face-at-point))
19280 ;; Get the colors from the face at point.
19282 (let ((color (plist-get org-format-latex-options
19283 :foreground)))
19284 (if (and forbuffer (eq color 'auto))
19285 (face-attribute face :foreground nil 'default)
19286 color)))
19288 (let ((color (plist-get org-format-latex-options
19289 :background)))
19290 (if (and forbuffer (eq color 'auto))
19291 (face-attribute face :background nil 'default)
19292 color)))
19293 (hash (sha1 (prin1-to-string
19294 (list org-format-latex-header
19295 org-latex-default-packages-alist
19296 org-latex-packages-alist
19297 org-format-latex-options
19298 forbuffer value fg bg))))
19299 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19300 (absprefix (expand-file-name prefix dir))
19301 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19302 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19303 (sep (and block-type "\n\n"))
19304 (link (concat sep "[[file:" linkfile "]]" sep))
19305 (options
19306 (org-combine-plists
19307 org-format-latex-options
19308 `(:foreground ,fg :background ,bg))))
19309 (when msg (message msg cnt))
19310 (unless checkdir-flag ; Ensure the directory exists.
19311 (setq checkdir-flag t)
19312 (let ((todir (file-name-directory absprefix)))
19313 (unless (file-directory-p todir)
19314 (make-directory todir t))))
19315 (unless (file-exists-p movefile)
19316 (org-create-formula-image
19317 value movefile options forbuffer processing-type))
19318 (if overlays
19319 (progn
19320 (dolist (o (overlays-in beg end))
19321 (when (eq (overlay-get o 'org-overlay-type)
19322 'org-latex-overlay)
19323 (delete-overlay o)))
19324 (org--format-latex-make-overlay beg end movefile imagetype)
19325 (goto-char end))
19326 (delete-region beg end)
19327 (insert
19328 (org-add-props link
19329 (list 'org-latex-src
19330 (replace-regexp-in-string "\"" "" value)
19331 'org-latex-src-embed-type
19332 (if block-type 'paragraph 'character)))))))
19333 ((eq processing-type 'mathml)
19334 ;; Process to MathML.
19335 (unless (org-format-latex-mathml-available-p)
19336 (user-error "LaTeX to MathML converter not configured"))
19337 (cl-incf cnt)
19338 (when msg (message msg cnt))
19339 (goto-char beg)
19340 (delete-region beg end)
19341 (insert (org-format-latex-as-mathml
19342 value block-type prefix dir)))
19344 (error "Unknown conversion process %s for LaTeX fragments"
19345 processing-type)))))))))))
19347 (defun org-create-math-formula (latex-frag &optional mathml-file)
19348 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19349 Use `org-latex-to-mathml-convert-command'. If the conversion is
19350 sucessful, return the portion between \"<math...> </math>\"
19351 elements otherwise return nil. When MATHML-FILE is specified,
19352 write the results in to that file. When invoked as an
19353 interactive command, prompt for LATEX-FRAG, with initial value
19354 set to the current active region and echo the results for user
19355 inspection."
19356 (interactive (list (let ((frag (when (org-region-active-p)
19357 (buffer-substring-no-properties
19358 (region-beginning) (region-end)))))
19359 (read-string "LaTeX Fragment: " frag nil frag))))
19360 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19361 (let* ((tmp-in-file
19362 (let ((file (file-relative-name
19363 (make-temp-name (expand-file-name "ltxmathml-in")))))
19364 (write-region latex-frag nil file)
19365 file))
19366 (tmp-out-file (file-relative-name
19367 (make-temp-name (expand-file-name "ltxmathml-out"))))
19368 (cmd (format-spec
19369 org-latex-to-mathml-convert-command
19370 `((?j . ,(and org-latex-to-mathml-jar-file
19371 (shell-quote-argument
19372 (expand-file-name
19373 org-latex-to-mathml-jar-file))))
19374 (?I . ,(shell-quote-argument tmp-in-file))
19375 (?i . ,latex-frag)
19376 (?o . ,(shell-quote-argument tmp-out-file)))))
19377 mathml shell-command-output)
19378 (when (called-interactively-p 'any)
19379 (unless (org-format-latex-mathml-available-p)
19380 (user-error "LaTeX to MathML converter not configured")))
19381 (message "Running %s" cmd)
19382 (setq shell-command-output (shell-command-to-string cmd))
19383 (setq mathml
19384 (when (file-readable-p tmp-out-file)
19385 (with-current-buffer (find-file-noselect tmp-out-file t)
19386 (goto-char (point-min))
19387 (when (re-search-forward
19388 (concat
19389 (regexp-quote
19390 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19391 "[^>]*?>"
19392 "\\(.\\|\n\\)*"
19393 "</math>")
19394 nil t)
19395 (prog1 (match-string 0) (kill-buffer))))))
19396 (cond
19397 (mathml
19398 (setq mathml
19399 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19400 (when mathml-file
19401 (write-region mathml nil mathml-file))
19402 (when (called-interactively-p 'any)
19403 (message mathml)))
19404 ((message "LaTeX to MathML conversion failed")
19405 (message shell-command-output)))
19406 (delete-file tmp-in-file)
19407 (when (file-exists-p tmp-out-file)
19408 (delete-file tmp-out-file))
19409 mathml))
19411 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19412 prefix &optional dir)
19413 "Use `org-create-math-formula' but check local cache first."
19414 (let* ((absprefix (expand-file-name prefix dir))
19415 (print-length nil) (print-level nil)
19416 (formula-id (concat
19417 "formula-"
19418 (sha1
19419 (prin1-to-string
19420 (list latex-frag
19421 org-latex-to-mathml-convert-command)))))
19422 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19423 (formula-cache-dir (file-name-directory formula-cache)))
19425 (unless (file-directory-p formula-cache-dir)
19426 (make-directory formula-cache-dir t))
19428 (unless (file-exists-p formula-cache)
19429 (org-create-math-formula latex-frag formula-cache))
19431 (if (file-exists-p formula-cache)
19432 ;; Successful conversion. Return the link to MathML file.
19433 (org-add-props
19434 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19435 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19436 'org-latex-src-embed-type (if latex-frag-type
19437 'paragraph 'character)))
19438 ;; Failed conversion. Return the LaTeX fragment verbatim
19439 latex-frag)))
19441 (declare-function org-export-get-backend "ox" (name))
19442 (declare-function org-export--get-global-options "ox" (&optional backend))
19443 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19444 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19445 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19446 (defun org-create-formula--latex-header ()
19447 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19448 (let ((info (org-combine-plists (org-export--get-global-options
19449 (org-export-get-backend 'latex))
19450 (org-export--get-inbuffer-options
19451 (org-export-get-backend 'latex)))))
19452 (org-latex-guess-babel-language
19453 (org-latex-guess-inputenc
19454 (org-splice-latex-header
19455 org-format-latex-header
19456 org-latex-default-packages-alist
19457 org-latex-packages-alist t
19458 (plist-get info :latex-header)))
19459 info)))
19461 (defun org--get-display-dpi ()
19462 "Get the DPI of the display.
19464 Assumes that the display has the same pixel width in the
19465 horizontal and vertical directions."
19466 (if (display-graphic-p)
19467 (round (/ (display-pixel-height)
19468 (/ (display-mm-height) 25.4)))
19469 (error "Attempt to calculate the dpi of a non-graphic display")))
19471 (defun org-create-formula-image
19472 (string tofile options buffer &optional processing-type)
19473 "Create an image from LaTeX source using external processes.
19475 The LaTeX STRING is saved to a temporary LaTeX file, then
19476 converted to an image file by process PROCESSING-TYPE defined in
19477 `org-preview-latex-process-alist'. A nil value defaults to
19478 `org-preview-latex-default-process'.
19480 The generated image file is eventually moved to TOFILE.
19482 The OPTIONS argument controls the size, foreground color and
19483 background color of the generated image.
19485 When BUFFER non-nil, this function is used for LaTeX previewing.
19486 Otherwise, it is used to deal with LaTeX snippets showed in
19487 a HTML file."
19488 (let* ((processing-type (or processing-type
19489 org-preview-latex-default-process))
19490 (processing-info
19491 (cdr (assq processing-type org-preview-latex-process-alist)))
19492 (programs (plist-get processing-info :programs))
19493 (error-message (or (plist-get processing-info :message) ""))
19494 (use-xcolor (plist-get processing-info :use-xcolor))
19495 (image-input-type (plist-get processing-info :image-input-type))
19496 (image-output-type (plist-get processing-info :image-output-type))
19497 (post-clean (or (plist-get processing-info :post-clean)
19498 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19499 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19500 (latex-header (or (plist-get processing-info :latex-header)
19501 (org-create-formula--latex-header)))
19502 (latex-compiler (plist-get processing-info :latex-compiler))
19503 (image-converter (plist-get processing-info :image-converter))
19504 (tmpdir temporary-file-directory)
19505 (texfilebase (make-temp-name
19506 (expand-file-name "orgtex" tmpdir)))
19507 (texfile (concat texfilebase ".tex"))
19508 (font-height (face-attribute 'default :height nil))
19509 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19510 '(1.0 . 1.0)))
19511 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19512 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19513 (dpi (* scale (floor (if buffer font-height 140.0))))
19514 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19515 "Black"))
19516 (bg (or (plist-get options (if buffer :background :html-background))
19517 "Transparent"))
19518 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19519 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19520 (dolist (program programs)
19521 (org-check-external-command program error-message))
19522 (if use-xcolor
19523 (progn (if (eq fg 'default)
19524 (setq fg (org-latex-color :foreground))
19525 (setq fg (org-latex-color-format fg)))
19526 (if (eq bg 'default)
19527 (setq bg (org-latex-color :background))
19528 (setq bg (org-latex-color-format
19529 (if (string= bg "Transparent") "white" bg))))
19530 (with-temp-file texfile
19531 (insert latex-header)
19532 (insert "\n\\begin{document}\n"
19533 "\\definecolor{fg}{rgb}{" fg "}\n"
19534 "\\definecolor{bg}{rgb}{" bg "}\n"
19535 "\n\\pagecolor{bg}\n"
19536 "\n{\\color{fg}\n"
19537 string
19538 "\n}\n"
19539 "\n\\end{document}\n")))
19540 (if (eq fg 'default)
19541 (setq fg (org-dvipng-color :foreground))
19542 (unless (string= fg "Transparent")
19543 (setq fg (org-dvipng-color-format fg))))
19544 (if (eq bg 'default)
19545 (setq bg (org-dvipng-color :background))
19546 (unless (string= bg "Transparent")
19547 (setq bg (org-dvipng-color-format bg))))
19548 (with-temp-file texfile
19549 (insert latex-header)
19550 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19552 (let* ((err-msg (format "Please adjust '%s' part of \
19553 `org-preview-latex-process-alist'."
19554 processing-type))
19555 (image-input-file
19556 (org-compile-file
19557 texfile latex-compiler image-input-type err-msg log-buf))
19558 (image-output-file
19559 (org-compile-file
19560 image-input-file image-converter image-output-type err-msg log-buf
19561 `((?F . ,(shell-quote-argument fg))
19562 (?B . ,(shell-quote-argument bg))
19563 (?D . ,(shell-quote-argument (format "%s" dpi)))
19564 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19565 (copy-file image-output-file tofile 'replace)
19566 (dolist (e post-clean)
19567 (when (file-exists-p (concat texfilebase e))
19568 (delete-file (concat texfilebase e))))
19569 image-output-file)))
19571 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19572 "Fill a LaTeX header template TPL.
19573 In the template, the following place holders will be recognized:
19575 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19576 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19577 [PACKAGES] \\usepackage statements for PKG
19578 [NO-PACKAGES] do not include PKG
19579 [EXTRA] the string EXTRA
19580 [NO-EXTRA] do not include EXTRA
19582 For backward compatibility, if both the positive and the negative place
19583 holder is missing, the positive one (without the \"NO-\") will be
19584 assumed to be present at the end of the template.
19585 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19586 EXTRA is a string.
19587 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19588 (let (rpl (end ""))
19589 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19590 (setq rpl (if (or (match-end 1) (not def-pkg))
19591 "" (org-latex-packages-to-string def-pkg snippets-p t))
19592 tpl (replace-match rpl t t tpl))
19593 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19595 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19596 (setq rpl (if (or (match-end 1) (not pkg))
19597 "" (org-latex-packages-to-string pkg snippets-p t))
19598 tpl (replace-match rpl t t tpl))
19599 (when pkg (setq end
19600 (concat end "\n"
19601 (org-latex-packages-to-string pkg snippets-p)))))
19603 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19604 (setq rpl (if (or (match-end 1) (not extra))
19605 "" (concat extra "\n"))
19606 tpl (replace-match rpl t t tpl))
19607 (when (and extra (string-match "\\S-" extra))
19608 (setq end (concat end "\n" extra))))
19610 (if (string-match "\\S-" end)
19611 (concat tpl "\n" end)
19612 tpl)))
19614 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19615 "Turn an alist of packages into a string with the \\usepackage macros."
19616 (setq pkg (mapconcat (lambda(p)
19617 (cond
19618 ((stringp p) p)
19619 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19620 (format "%% Package %s omitted" (cadr p)))
19621 ((equal "" (car p))
19622 (format "\\usepackage{%s}" (cadr p)))
19624 (format "\\usepackage[%s]{%s}"
19625 (car p) (cadr p)))))
19627 "\n"))
19628 (if newline (concat pkg "\n") pkg))
19630 (defun org-dvipng-color (attr)
19631 "Return a RGB color specification for dvipng."
19632 (org-dvipng-color-format (face-attribute 'default attr nil)))
19634 (defun org-dvipng-color-format (color-name)
19635 "Convert COLOR-NAME to a RGB color value for dvipng."
19636 (apply #'format "rgb %s %s %s"
19637 (mapcar 'org-normalize-color
19638 (color-values color-name))))
19640 (defun org-latex-color (attr)
19641 "Return a RGB color for the LaTeX color package."
19642 (org-latex-color-format (face-attribute 'default attr nil)))
19644 (defun org-latex-color-format (color-name)
19645 "Convert COLOR-NAME to a RGB color value."
19646 (apply #'format "%s,%s,%s"
19647 (mapcar 'org-normalize-color
19648 (color-values color-name))))
19650 (defun org-normalize-color (value)
19651 "Return string to be used as color value for an RGB component."
19652 (format "%g" (/ value 65535.0)))
19656 ;; Image display
19658 (defvar-local org-inline-image-overlays nil)
19660 (defun org-toggle-inline-images (&optional include-linked)
19661 "Toggle the display of inline images.
19662 INCLUDE-LINKED is passed to `org-display-inline-images'."
19663 (interactive "P")
19664 (if org-inline-image-overlays
19665 (progn
19666 (org-remove-inline-images)
19667 (when (called-interactively-p 'interactive)
19668 (message "Inline image display turned off")))
19669 (org-display-inline-images include-linked)
19670 (when (called-interactively-p 'interactive)
19671 (message (if org-inline-image-overlays
19672 (format "%d images displayed inline"
19673 (length org-inline-image-overlays))
19674 "No images to display inline")))))
19676 (defun org-redisplay-inline-images ()
19677 "Refresh the display of inline images."
19678 (interactive)
19679 (if (not org-inline-image-overlays)
19680 (org-toggle-inline-images)
19681 (org-toggle-inline-images)
19682 (org-toggle-inline-images)))
19684 (defun org-display-inline-images (&optional include-linked refresh beg end)
19685 "Display inline images.
19687 An inline image is a link which follows either of these
19688 conventions:
19690 1. Its path is a file with an extension matching return value
19691 from `image-file-name-regexp' and it has no contents.
19693 2. Its description consists in a single link of the previous
19694 type.
19696 When optional argument INCLUDE-LINKED is non-nil, also links with
19697 a text description part will be inlined. This can be nice for
19698 a quick look at those images, but it does not reflect what
19699 exported files will look like.
19701 When optional argument REFRESH is non-nil, refresh existing
19702 images between BEG and END. This will create new image displays
19703 only if necessary. BEG and END default to the buffer
19704 boundaries."
19705 (interactive "P")
19706 (when (display-graphic-p)
19707 (unless refresh
19708 (org-remove-inline-images)
19709 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19710 (org-with-wide-buffer
19711 (goto-char (or beg (point-min)))
19712 (let ((case-fold-search t)
19713 (file-extension-re (image-file-name-regexp)))
19714 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19715 (let ((link (save-match-data (org-element-context))))
19716 ;; Check if we're at an inline image.
19717 (when (and (equal (org-element-property :type link) "file")
19718 (or include-linked
19719 (not (org-element-property :contents-begin link)))
19720 (let ((parent (org-element-property :parent link)))
19721 (or (not (eq (org-element-type parent) 'link))
19722 (not (cdr (org-element-contents parent)))))
19723 (string-match-p file-extension-re
19724 (org-element-property :path link)))
19725 (let ((file (expand-file-name
19726 (org-link-unescape
19727 (org-element-property :path link)))))
19728 (when (file-exists-p file)
19729 (let ((width
19730 ;; Apply `org-image-actual-width' specifications.
19731 (cond
19732 ((not (image-type-available-p 'imagemagick)) nil)
19733 ((eq org-image-actual-width t) nil)
19734 ((listp org-image-actual-width)
19736 ;; First try to find a width among
19737 ;; attributes associated to the paragraph
19738 ;; containing link.
19739 (let ((paragraph
19740 (let ((e link))
19741 (while (and (setq e (org-element-property
19742 :parent e))
19743 (not (eq (org-element-type e)
19744 'paragraph))))
19745 e)))
19746 (when paragraph
19747 (save-excursion
19748 (goto-char (org-element-property :begin paragraph))
19749 (when
19750 (re-search-forward
19751 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19752 (org-element-property
19753 :post-affiliated paragraph)
19755 (string-to-number (match-string 1))))))
19756 ;; Otherwise, fall-back to provided number.
19757 (car org-image-actual-width)))
19758 ((numberp org-image-actual-width)
19759 org-image-actual-width)))
19760 (old (get-char-property-and-overlay
19761 (org-element-property :begin link)
19762 'org-image-overlay)))
19763 (if (and (car-safe old) refresh)
19764 (image-refresh (overlay-get (cdr old) 'display))
19765 (let ((image (create-image file
19766 (and width 'imagemagick)
19768 :width width)))
19769 (when image
19770 (let* ((link
19771 ;; If inline image is the description
19772 ;; of another link, be sure to
19773 ;; consider the latter as the one to
19774 ;; apply the overlay on.
19775 (let ((parent
19776 (org-element-property :parent link)))
19777 (if (eq (org-element-type parent) 'link)
19778 parent
19779 link)))
19780 (ov (make-overlay
19781 (org-element-property :begin link)
19782 (progn
19783 (goto-char
19784 (org-element-property :end link))
19785 (skip-chars-backward " \t")
19786 (point)))))
19787 (overlay-put ov 'display image)
19788 (overlay-put ov 'face 'default)
19789 (overlay-put ov 'org-image-overlay t)
19790 (overlay-put
19791 ov 'modification-hooks
19792 (list 'org-display-inline-remove-overlay))
19793 (push ov org-inline-image-overlays)))))))))))))))
19795 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19796 "Remove inline-display overlay if a corresponding region is modified."
19797 (let ((inhibit-modification-hooks t))
19798 (when (and ov after)
19799 (delete ov org-inline-image-overlays)
19800 (delete-overlay ov))))
19802 (defun org-remove-inline-images ()
19803 "Remove inline display of images."
19804 (interactive)
19805 (mapc #'delete-overlay org-inline-image-overlays)
19806 (setq org-inline-image-overlays nil))
19808 ;;;; Key bindings
19810 ;; Outline functions from `outline-mode-prefix-map'
19811 ;; that can be remapped in Org:
19812 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19813 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19814 (define-key org-mode-map [remap outline-forward-same-level]
19815 'org-forward-heading-same-level)
19816 (define-key org-mode-map [remap outline-backward-same-level]
19817 'org-backward-heading-same-level)
19818 (define-key org-mode-map [remap outline-show-branches]
19819 'org-kill-note-or-show-branches)
19820 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19821 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19822 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19823 (define-key org-mode-map [remap outline-next-visible-heading]
19824 'org-next-visible-heading)
19825 (define-key org-mode-map [remap outline-previous-visible-heading]
19826 'org-previous-visible-heading)
19827 (define-key org-mode-map [remap show-children] 'org-show-children)
19829 ;; Outline functions from `outline-mode-prefix-map' that can not
19830 ;; be remapped in Org:
19832 ;; - the column "key binding" shows whether the Outline function is still
19833 ;; available in Org mode on the same key that it has been bound to in
19834 ;; Outline mode:
19835 ;; - "overridden": key used for a different functionality in Org mode
19836 ;; - else: key still bound to the same Outline function in Org mode
19838 ;; | Outline function | key binding | Org replacement |
19839 ;; |------------------------------------+-------------+--------------------------|
19840 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19841 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19842 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19843 ;; | `show-entry' | overridden | no replacement |
19844 ;; | `show-branches' | `C-c C-k' | still same function |
19845 ;; | `show-subtree' | overridden | visibility cycling |
19846 ;; | `show-all' | overridden | no replacement |
19847 ;; | `hide-subtree' | overridden | visibility cycling |
19848 ;; | `hide-body' | overridden | no replacement |
19849 ;; | `hide-entry' | overridden | visibility cycling |
19850 ;; | `hide-leaves' | overridden | no replacement |
19851 ;; | `hide-sublevels' | overridden | no replacement |
19852 ;; | `hide-other' | overridden | no replacement |
19854 ;; Make `C-c C-x' a prefix key
19855 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19857 ;; TAB key with modifiers
19858 (org-defkey org-mode-map "\C-i" 'org-cycle)
19859 (org-defkey org-mode-map [(tab)] 'org-cycle)
19860 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19861 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19862 ;; The following line is necessary under Suse GNU/Linux
19863 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19864 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19865 (define-key org-mode-map [backtab] 'org-shifttab)
19867 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19868 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19869 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19871 ;; Cursor keys with modifiers
19872 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19873 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19874 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19875 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19877 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19878 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19879 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19880 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19881 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19882 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19884 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19885 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19886 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19887 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19889 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19890 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19891 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19892 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19894 ;; Babel keys
19895 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19896 (dolist (pair org-babel-key-bindings)
19897 (define-key org-babel-map (car pair) (cdr pair)))
19899 ;;; Extra keys for tty access.
19900 ;; We only set them when really needed because otherwise the
19901 ;; menus don't show the simple keys
19903 (when (or org-use-extra-keys (not window-system))
19904 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19905 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19906 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19907 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19908 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19909 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19910 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19911 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19912 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19913 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19914 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19915 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19916 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19917 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19918 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19919 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19920 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19921 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19922 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19923 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19924 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19925 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19926 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19927 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19928 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19929 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19930 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19931 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19933 ;; All the other keys
19935 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19936 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19937 (if (boundp 'narrow-map)
19938 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19939 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19940 (if (boundp 'narrow-map)
19941 (org-defkey narrow-map "b" 'org-narrow-to-block)
19942 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19943 (if (boundp 'narrow-map)
19944 (org-defkey narrow-map "e" 'org-narrow-to-element)
19945 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19946 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19947 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19948 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19949 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19950 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19951 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19952 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19953 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19954 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19955 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19956 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19957 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19958 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19959 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19960 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19961 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19962 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19963 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19964 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19965 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19966 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19967 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19968 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19969 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19970 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19971 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19972 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19973 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19974 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19975 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19976 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19977 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19978 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19979 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19980 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19981 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19982 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19983 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19984 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19985 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19986 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19987 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19988 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19989 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19990 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19991 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19992 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19993 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19994 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19995 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19996 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19997 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19998 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19999 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20000 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
20001 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
20002 (org-defkey org-mode-map "\C-c^" 'org-sort)
20003 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
20004 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
20005 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
20006 (org-defkey org-mode-map [remap open-line] 'org-open-line)
20007 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
20008 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
20009 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
20010 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
20011 (org-defkey org-mode-map "\C-m" 'org-return)
20012 (org-defkey org-mode-map "\C-j" 'org-return-indent)
20013 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
20014 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
20015 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
20016 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
20017 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
20018 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
20019 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
20020 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
20021 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
20022 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
20023 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
20024 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
20025 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
20026 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
20027 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
20028 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
20029 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
20030 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
20031 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
20032 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
20033 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
20034 (org-defkey org-mode-map "\M-h" 'org-mark-element)
20035 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
20036 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
20038 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
20039 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
20040 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
20042 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
20043 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
20044 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
20045 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
20046 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
20047 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
20048 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
20049 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
20050 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
20051 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
20052 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
20053 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
20054 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
20055 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
20056 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
20057 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
20058 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
20059 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
20060 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
20061 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
20062 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
20063 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
20065 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
20066 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
20067 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
20068 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
20069 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
20071 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20073 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20075 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20076 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20078 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20081 (defconst org-speed-commands-default
20083 ("Outline Navigation")
20084 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20085 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20086 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20087 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20088 ("F" . org-next-block)
20089 ("B" . org-previous-block)
20090 ("u" . (org-speed-move-safe 'outline-up-heading))
20091 ("j" . org-goto)
20092 ("g" . (org-refile t))
20093 ("Outline Visibility")
20094 ("c" . org-cycle)
20095 ("C" . org-shifttab)
20096 (" " . org-display-outline-path)
20097 ("s" . org-narrow-to-subtree)
20098 ("=" . org-columns)
20099 ("Outline Structure Editing")
20100 ("U" . org-metaup)
20101 ("D" . org-metadown)
20102 ("r" . org-metaright)
20103 ("l" . org-metaleft)
20104 ("R" . org-shiftmetaright)
20105 ("L" . org-shiftmetaleft)
20106 ("i" . (progn (forward-char 1) (call-interactively
20107 'org-insert-heading-respect-content)))
20108 ("^" . org-sort)
20109 ("w" . org-refile)
20110 ("a" . org-archive-subtree-default-with-confirmation)
20111 ("@" . org-mark-subtree)
20112 ("#" . org-toggle-comment)
20113 ("Clock Commands")
20114 ("I" . org-clock-in)
20115 ("O" . org-clock-out)
20116 ("Meta Data Editing")
20117 ("t" . org-todo)
20118 ("," . (org-priority))
20119 ("0" . (org-priority ?\ ))
20120 ("1" . (org-priority ?A))
20121 ("2" . (org-priority ?B))
20122 ("3" . (org-priority ?C))
20123 (":" . org-set-tags-command)
20124 ("e" . org-set-effort)
20125 ("E" . org-inc-effort)
20126 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20127 (org-entry-put (point) "APPT_WARNTIME" m)))
20128 ("Agenda Views etc")
20129 ("v" . org-agenda)
20130 ("/" . org-sparse-tree)
20131 ("Misc")
20132 ("o" . org-open-at-point)
20133 ("?" . org-speed-command-help)
20134 ("<" . (org-agenda-set-restriction-lock 'subtree))
20135 (">" . (org-agenda-remove-restriction-lock))
20137 "The default speed commands.")
20139 (defun org-print-speed-command (e)
20140 (if (> (length (car e)) 1)
20141 (progn
20142 (princ "\n")
20143 (princ (car e))
20144 (princ "\n")
20145 (princ (make-string (length (car e)) ?-))
20146 (princ "\n"))
20147 (princ (car e))
20148 (princ " ")
20149 (if (symbolp (cdr e))
20150 (princ (symbol-name (cdr e)))
20151 (prin1 (cdr e)))
20152 (princ "\n")))
20154 (defun org-speed-command-help ()
20155 "Show the available speed commands."
20156 (interactive)
20157 (if (not org-use-speed-commands)
20158 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20159 (with-output-to-temp-buffer "*Help*"
20160 (princ "User-defined Speed commands\n===========================\n")
20161 (mapc #'org-print-speed-command org-speed-commands-user)
20162 (princ "\n")
20163 (princ "Built-in Speed commands\n=======================\n")
20164 (mapc #'org-print-speed-command org-speed-commands-default))
20165 (with-current-buffer "*Help*"
20166 (setq truncate-lines t))))
20168 (defun org-speed-move-safe (cmd)
20169 "Execute CMD, but make sure that the cursor always ends up in a headline.
20170 If not, return to the original position and throw an error."
20171 (interactive)
20172 (let ((pos (point)))
20173 (call-interactively cmd)
20174 (unless (and (bolp) (org-at-heading-p))
20175 (goto-char pos)
20176 (error "Boundary reached while executing %s" cmd))))
20178 (defvar org-self-insert-command-undo-counter 0)
20180 (defvar org-table-auto-blank-field) ; defined in org-table.el
20181 (defvar org-speed-command nil)
20183 (defun org-speed-command-activate (keys)
20184 "Hook for activating single-letter speed commands.
20185 `org-speed-commands-default' specifies a minimal command set.
20186 Use `org-speed-commands-user' for further customization."
20187 (when (or (and (bolp) (looking-at org-outline-regexp))
20188 (and (functionp org-use-speed-commands)
20189 (funcall org-use-speed-commands)))
20190 (cdr (assoc keys (append org-speed-commands-user
20191 org-speed-commands-default)))))
20193 (defun org-babel-speed-command-activate (keys)
20194 "Hook for activating single-letter code block commands."
20195 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20196 (cdr (assoc keys org-babel-key-bindings))))
20198 (defcustom org-speed-command-hook
20199 '(org-speed-command-default-hook org-babel-speed-command-hook)
20200 "Hook for activating speed commands at strategic locations.
20201 Hook functions are called in sequence until a valid handler is
20202 found.
20204 Each hook takes a single argument, a user-pressed command key
20205 which is also a `self-insert-command' from the global map.
20207 Within the hook, examine the cursor position and the command key
20208 and return nil or a valid handler as appropriate. Handler could
20209 be one of an interactive command, a function, or a form.
20211 Set `org-use-speed-commands' to non-nil value to enable this
20212 hook. The default setting is `org-speed-command-activate'."
20213 :group 'org-structure
20214 :version "24.1"
20215 :type 'hook)
20217 (defun org-self-insert-command (N)
20218 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20219 If the cursor is in a table looking at whitespace, the whitespace is
20220 overwritten, and the table is not marked as requiring realignment."
20221 (interactive "p")
20222 (org-check-before-invisible-edit 'insert)
20223 (cond
20224 ((and org-use-speed-commands
20225 (let ((kv (this-command-keys-vector)))
20226 (setq org-speed-command
20227 (run-hook-with-args-until-success
20228 'org-speed-command-hook
20229 (make-string 1 (aref kv (1- (length kv))))))))
20230 (cond
20231 ((commandp org-speed-command)
20232 (setq this-command org-speed-command)
20233 (call-interactively org-speed-command))
20234 ((functionp org-speed-command)
20235 (funcall org-speed-command))
20236 ((and org-speed-command (listp org-speed-command))
20237 (eval org-speed-command))
20238 (t (let (org-use-speed-commands)
20239 (call-interactively 'org-self-insert-command)))))
20240 ((and
20241 (org-at-table-p)
20242 (progn
20243 ;; Check if we blank the field, and if that triggers align.
20244 (and (featurep 'org-table) org-table-auto-blank-field
20245 (memq last-command
20246 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20247 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20248 ;; Got extra space, this field does not determine
20249 ;; column width.
20250 (let (org-table-may-need-update) (org-table-blank-field))
20251 ;; No extra space, this field may determine column
20252 ;; width.
20253 (org-table-blank-field)))
20255 (eq N 1)
20256 (looking-at "[^|\n]* \\( \\)|"))
20257 ;; There is room for insertion without re-aligning the table.
20258 (delete-region (match-beginning 1) (match-end 1))
20259 (self-insert-command N))
20261 (setq org-table-may-need-update t)
20262 (self-insert-command N)
20263 (org-fix-tags-on-the-fly)
20264 (when org-self-insert-cluster-for-undo
20265 (if (not (eq last-command 'org-self-insert-command))
20266 (setq org-self-insert-command-undo-counter 1)
20267 (if (>= org-self-insert-command-undo-counter 20)
20268 (setq org-self-insert-command-undo-counter 1)
20269 (and (> org-self-insert-command-undo-counter 0)
20270 buffer-undo-list (listp buffer-undo-list)
20271 (not (cadr buffer-undo-list)) ; remove nil entry
20272 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20273 (setq org-self-insert-command-undo-counter
20274 (1+ org-self-insert-command-undo-counter))))))))
20276 (defun org-check-before-invisible-edit (kind)
20277 "Check is editing if kind KIND would be dangerous with invisible text around.
20278 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20279 ;; First, try to get out of here as quickly as possible, to reduce overhead
20280 (when (and org-catch-invisible-edits
20281 (or (not (boundp 'visible-mode)) (not visible-mode))
20282 (or (get-char-property (point) 'invisible)
20283 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20284 ;; OK, we need to take a closer look
20285 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20286 (invisible-before-point (unless (bobp) (get-char-property
20287 (1- (point)) 'invisible)))
20288 (border-and-ok-direction
20290 ;; Check if we are acting predictably before invisible text
20291 (and invisible-at-point (not invisible-before-point)
20292 (memq kind '(insert delete-backward)))
20293 ;; Check if we are acting predictably after invisible text
20294 ;; This works not well, and I have turned it off. It seems
20295 ;; better to always show and stop after invisible text.
20296 ;; (and (not invisible-at-point) invisible-before-point
20297 ;; (memq kind '(insert delete)))
20299 (when (or (memq invisible-at-point '(outline org-hide-block t))
20300 (memq invisible-before-point '(outline org-hide-block t)))
20301 (when (eq org-catch-invisible-edits 'error)
20302 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20303 (if (and org-custom-properties-overlays
20304 (y-or-n-p "Display invisible properties in this buffer? "))
20305 (org-toggle-custom-properties-visibility)
20306 ;; Make the area visible
20307 (save-excursion
20308 (when invisible-before-point
20309 (goto-char (previous-single-char-property-change
20310 (point) 'invisible)))
20311 (outline-show-subtree))
20312 (cond
20313 ((eq org-catch-invisible-edits 'show)
20314 ;; That's it, we do the edit after showing
20315 (message
20316 "Unfolding invisible region around point before editing")
20317 (sit-for 1))
20318 ((and (eq org-catch-invisible-edits 'smart)
20319 border-and-ok-direction)
20320 (message "Unfolding invisible region around point before editing"))
20322 ;; Don't do the edit, make the user repeat it in full visibility
20323 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20325 (defun org-fix-tags-on-the-fly ()
20326 "Align tags in headline at point.
20327 Unlike to `org-set-tags', it ignores region and sorting."
20328 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20329 (org-at-heading-p))
20330 (let ((org-ignore-region t)
20331 (org-tags-sort-function nil))
20332 (org-set-tags nil t))))
20334 (defun org-delete-backward-char (N)
20335 "Like `delete-backward-char', insert whitespace at field end in tables.
20336 When deleting backwards, in tables this function will insert whitespace in
20337 front of the next \"|\" separator, to keep the table aligned. The table will
20338 still be marked for re-alignment if the field did fill the entire column,
20339 because, in this case the deletion might narrow the column."
20340 (interactive "p")
20341 (save-match-data
20342 (org-check-before-invisible-edit 'delete-backward)
20343 (if (and (org-at-table-p)
20344 (eq N 1)
20345 (string-match "|" (buffer-substring (point-at-bol) (point)))
20346 (looking-at ".*?|"))
20347 (let ((pos (point))
20348 (noalign (looking-at "[^|\n\r]* |"))
20349 (c org-table-may-need-update))
20350 (backward-delete-char N)
20351 (unless overwrite-mode
20352 (skip-chars-forward "^|")
20353 (insert " ")
20354 (goto-char (1- pos)))
20355 ;; noalign: if there were two spaces at the end, this field
20356 ;; does not determine the width of the column.
20357 (when noalign (setq org-table-may-need-update c)))
20358 (backward-delete-char N)
20359 (org-fix-tags-on-the-fly))))
20361 (defun org-delete-char (N)
20362 "Like `delete-char', but insert whitespace at field end in tables.
20363 When deleting characters, in tables this function will insert whitespace in
20364 front of the next \"|\" separator, to keep the table aligned. The table will
20365 still be marked for re-alignment if the field did fill the entire column,
20366 because, in this case the deletion might narrow the column."
20367 (interactive "p")
20368 (save-match-data
20369 (org-check-before-invisible-edit 'delete)
20370 (if (and (org-at-table-p)
20371 (not (bolp))
20372 (not (= (char-after) ?|))
20373 (eq N 1))
20374 (if (looking-at ".*?|")
20375 (let ((pos (point))
20376 (noalign (looking-at "[^|\n\r]* |"))
20377 (c org-table-may-need-update))
20378 (replace-match
20379 (concat (substring (match-string 0) 1 -1) " |") nil t)
20380 (goto-char pos)
20381 ;; noalign: if there were two spaces at the end, this field
20382 ;; does not determine the width of the column.
20383 (when noalign (setq org-table-may-need-update c)))
20384 (delete-char N))
20385 (delete-char N)
20386 (org-fix-tags-on-the-fly))))
20388 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20389 (put 'org-self-insert-command 'delete-selection
20390 (lambda ()
20391 (not (run-hook-with-args-until-success
20392 'self-insert-uses-region-functions))))
20393 (put 'orgtbl-self-insert-command 'delete-selection
20394 (lambda ()
20395 (not (run-hook-with-args-until-success
20396 'self-insert-uses-region-functions))))
20397 (put 'org-delete-char 'delete-selection 'supersede)
20398 (put 'org-delete-backward-char 'delete-selection 'supersede)
20399 (put 'org-yank 'delete-selection 'yank)
20401 ;; Make `flyspell-mode' delay after some commands
20402 (put 'org-self-insert-command 'flyspell-delayed t)
20403 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20404 (put 'org-delete-char 'flyspell-delayed t)
20405 (put 'org-delete-backward-char 'flyspell-delayed t)
20407 ;; Make pabbrev-mode expand after Org mode commands
20408 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20409 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20411 (defun org-remap (map &rest commands)
20412 "In MAP, remap the functions given in COMMANDS.
20413 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20414 (let (new old)
20415 (while commands
20416 (setq old (pop commands) new (pop commands))
20417 (org-defkey map (vector 'remap old) new))))
20419 (defun org-transpose-words ()
20420 "Transpose words for Org.
20421 This uses the `org-mode-transpose-word-syntax-table' syntax
20422 table, which interprets characters in `org-emphasis-alist' as
20423 word constituents."
20424 (interactive)
20425 (with-syntax-table org-mode-transpose-word-syntax-table
20426 (call-interactively 'transpose-words)))
20427 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20429 (when (eq org-enable-table-editor 'optimized)
20430 ;; If the user wants maximum table support, we need to hijack
20431 ;; some standard editing functions
20432 (org-remap org-mode-map
20433 'self-insert-command 'org-self-insert-command
20434 'delete-char 'org-delete-char
20435 'delete-backward-char 'org-delete-backward-char)
20436 (org-defkey org-mode-map "|" 'org-force-self-insert))
20438 (defvar org-ctrl-c-ctrl-c-hook nil
20439 "Hook for functions attaching themselves to `C-c C-c'.
20441 This can be used to add additional functionality to the C-c C-c
20442 key which executes context-dependent commands. This hook is run
20443 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20444 run after the last test.
20446 Each function will be called with no arguments. The function
20447 must check if the context is appropriate for it to act. If yes,
20448 it should do its thing and then return a non-nil value. If the
20449 context is wrong, just do nothing and return nil.")
20451 (defvar org-ctrl-c-ctrl-c-final-hook nil
20452 "Hook for functions attaching themselves to `C-c C-c'.
20454 This can be used to add additional functionality to the C-c C-c
20455 key which executes context-dependent commands. This hook is run
20456 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20457 before the first test.
20459 Each function will be called with no arguments. The function
20460 must check if the context is appropriate for it to act. If yes,
20461 it should do its thing and then return a non-nil value. If the
20462 context is wrong, just do nothing and return nil.")
20464 (defvar org-tab-first-hook nil
20465 "Hook for functions to attach themselves to TAB.
20466 See `org-ctrl-c-ctrl-c-hook' for more information.
20467 This hook runs as the first action when TAB is pressed, even before
20468 `org-cycle' messes around with the `outline-regexp' to cater for
20469 inline tasks and plain list item folding.
20470 If any function in this hook returns t, any other actions that
20471 would have been caused by TAB (such as table field motion or visibility
20472 cycling) will not occur.")
20474 (defvar org-tab-after-check-for-table-hook nil
20475 "Hook for functions to attach themselves to TAB.
20476 See `org-ctrl-c-ctrl-c-hook' for more information.
20477 This hook runs after it has been established that the cursor is not in a
20478 table, but before checking if the cursor is in a headline or if global cycling
20479 should be done.
20480 If any function in this hook returns t, not other actions like visibility
20481 cycling will be done.")
20483 (defvar org-tab-after-check-for-cycling-hook nil
20484 "Hook for functions to attach themselves to TAB.
20485 See `org-ctrl-c-ctrl-c-hook' for more information.
20486 This hook runs after it has been established that not table field motion and
20487 not visibility should be done because of current context. This is probably
20488 the place where a package like yasnippets can hook in.")
20490 (defvar org-tab-before-tab-emulation-hook nil
20491 "Hook for functions to attach themselves to TAB.
20492 See `org-ctrl-c-ctrl-c-hook' for more information.
20493 This hook runs after every other options for TAB have been exhausted, but
20494 before indentation and \t insertion takes place.")
20496 (defvar org-metaleft-hook nil
20497 "Hook for functions attaching themselves to `M-left'.
20498 See `org-ctrl-c-ctrl-c-hook' for more information.")
20499 (defvar org-metaright-hook nil
20500 "Hook for functions attaching themselves to `M-right'.
20501 See `org-ctrl-c-ctrl-c-hook' for more information.")
20502 (defvar org-metaup-hook nil
20503 "Hook for functions attaching themselves to `M-up'.
20504 See `org-ctrl-c-ctrl-c-hook' for more information.")
20505 (defvar org-metadown-hook nil
20506 "Hook for functions attaching themselves to `M-down'.
20507 See `org-ctrl-c-ctrl-c-hook' for more information.")
20508 (defvar org-shiftmetaleft-hook nil
20509 "Hook for functions attaching themselves to `M-S-left'.
20510 See `org-ctrl-c-ctrl-c-hook' for more information.")
20511 (defvar org-shiftmetaright-hook nil
20512 "Hook for functions attaching themselves to `M-S-right'.
20513 See `org-ctrl-c-ctrl-c-hook' for more information.")
20514 (defvar org-shiftmetaup-hook nil
20515 "Hook for functions attaching themselves to `M-S-up'.
20516 See `org-ctrl-c-ctrl-c-hook' for more information.")
20517 (defvar org-shiftmetadown-hook nil
20518 "Hook for functions attaching themselves to `M-S-down'.
20519 See `org-ctrl-c-ctrl-c-hook' for more information.")
20520 (defvar org-metareturn-hook nil
20521 "Hook for functions attaching themselves to `M-RET'.
20522 See `org-ctrl-c-ctrl-c-hook' for more information.")
20523 (defvar org-shiftup-hook nil
20524 "Hook for functions attaching themselves to `S-up'.
20525 See `org-ctrl-c-ctrl-c-hook' for more information.")
20526 (defvar org-shiftup-final-hook nil
20527 "Hook for functions attaching themselves to `S-up'.
20528 This one runs after all other options except shift-select have been excluded.
20529 See `org-ctrl-c-ctrl-c-hook' for more information.")
20530 (defvar org-shiftdown-hook nil
20531 "Hook for functions attaching themselves to `S-down'.
20532 See `org-ctrl-c-ctrl-c-hook' for more information.")
20533 (defvar org-shiftdown-final-hook nil
20534 "Hook for functions attaching themselves to `S-down'.
20535 This one runs after all other options except shift-select have been excluded.
20536 See `org-ctrl-c-ctrl-c-hook' for more information.")
20537 (defvar org-shiftleft-hook nil
20538 "Hook for functions attaching themselves to `S-left'.
20539 See `org-ctrl-c-ctrl-c-hook' for more information.")
20540 (defvar org-shiftleft-final-hook nil
20541 "Hook for functions attaching themselves to `S-left'.
20542 This one runs after all other options except shift-select have been excluded.
20543 See `org-ctrl-c-ctrl-c-hook' for more information.")
20544 (defvar org-shiftright-hook nil
20545 "Hook for functions attaching themselves to `S-right'.
20546 See `org-ctrl-c-ctrl-c-hook' for more information.")
20547 (defvar org-shiftright-final-hook nil
20548 "Hook for functions attaching themselves to `S-right'.
20549 This one runs after all other options except shift-select have been excluded.
20550 See `org-ctrl-c-ctrl-c-hook' for more information.")
20552 (defun org-modifier-cursor-error ()
20553 "Throw an error, a modified cursor command was applied in wrong context."
20554 (user-error "This command is active in special context like tables, headlines or items"))
20556 (defun org-shiftselect-error ()
20557 "Throw an error because Shift-Cursor command was applied in wrong context."
20558 (if (and (boundp 'shift-select-mode) shift-select-mode)
20559 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20560 (user-error "This command works only in special context like headlines or timestamps")))
20562 (defun org-call-for-shift-select (cmd)
20563 (let ((this-command-keys-shift-translated t))
20564 (call-interactively cmd)))
20566 (defun org-shifttab (&optional arg)
20567 "Global visibility cycling or move to previous table field.
20568 Call `org-table-previous-field' within a table.
20569 When ARG is nil, cycle globally through visibility states.
20570 When ARG is a numeric prefix, show contents of this level."
20571 (interactive "P")
20572 (cond
20573 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20574 ((integerp arg)
20575 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20576 (message "Content view to level: %d" arg)
20577 (org-content (prefix-numeric-value arg2))
20578 (org-cycle-show-empty-lines t)
20579 (setq org-cycle-global-status 'overview)))
20580 (t (call-interactively 'org-global-cycle))))
20582 (defun org-shiftmetaleft ()
20583 "Promote subtree or delete table column.
20584 Calls `org-promote-subtree', `org-outdent-item-tree', or
20585 `org-table-delete-column', depending on context. See the
20586 individual commands for more information."
20587 (interactive)
20588 (cond
20589 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20590 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20591 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20592 ((if (not (org-region-active-p)) (org-at-item-p)
20593 (save-excursion (goto-char (region-beginning))
20594 (org-at-item-p)))
20595 (call-interactively 'org-outdent-item-tree))
20596 (t (org-modifier-cursor-error))))
20598 (defun org-shiftmetaright ()
20599 "Demote subtree or insert table column.
20600 Calls `org-demote-subtree', `org-indent-item-tree', or
20601 `org-table-insert-column', depending on context. See the
20602 individual commands for more information."
20603 (interactive)
20604 (cond
20605 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20606 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20607 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20608 ((if (not (org-region-active-p)) (org-at-item-p)
20609 (save-excursion (goto-char (region-beginning))
20610 (org-at-item-p)))
20611 (call-interactively 'org-indent-item-tree))
20612 (t (org-modifier-cursor-error))))
20614 (defun org-shiftmetaup (&optional _arg)
20615 "Drag the line at point up.
20616 In a table, kill the current row.
20617 On a clock timestamp, update the value of the timestamp like `S-<up>'
20618 but also adjust the previous clocked item in the clock history.
20619 Everywhere else, drag the line at point up."
20620 (interactive "P")
20621 (cond
20622 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20623 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20624 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20625 (call-interactively 'org-timestamp-up)))
20626 (t (call-interactively 'org-drag-line-backward))))
20628 (defun org-shiftmetadown (&optional _arg)
20629 "Drag the line at point down.
20630 In a table, insert an empty row at the current line.
20631 On a clock timestamp, update the value of the timestamp like `S-<down>'
20632 but also adjust the previous clocked item in the clock history.
20633 Everywhere else, drag the line at point down."
20634 (interactive "P")
20635 (cond
20636 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20637 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20638 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20639 (call-interactively 'org-timestamp-down)))
20640 (t (call-interactively 'org-drag-line-forward))))
20642 (defsubst org-hidden-tree-error ()
20643 (user-error
20644 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20646 (defun org-metaleft (&optional _arg)
20647 "Promote heading, list item at point or move table column left.
20649 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20650 depending on context. With no specific context, calls the Emacs
20651 default `backward-word'. See the individual commands for more
20652 information.
20654 This function runs the hook `org-metaleft-hook' as a first step,
20655 and returns at first non-nil value."
20656 (interactive "P")
20657 (cond
20658 ((run-hook-with-args-until-success 'org-metaleft-hook))
20659 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20660 ((org-with-limited-levels
20661 (or (org-at-heading-p)
20662 (and (org-region-active-p)
20663 (save-excursion
20664 (goto-char (region-beginning))
20665 (org-at-heading-p)))))
20666 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20667 (call-interactively 'org-do-promote))
20668 ;; At an inline task.
20669 ((org-at-heading-p)
20670 (call-interactively 'org-inlinetask-promote))
20671 ((or (org-at-item-p)
20672 (and (org-region-active-p)
20673 (save-excursion
20674 (goto-char (region-beginning))
20675 (org-at-item-p))))
20676 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20677 (call-interactively 'org-outdent-item))
20678 (t (call-interactively 'backward-word))))
20680 (defun org-metaright (&optional _arg)
20681 "Demote heading, list item at point or move table column right.
20683 In front of a drawer or a block keyword, indent it correctly.
20685 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20686 `org-indent-drawer' or `org-indent-block' depending on context.
20687 With no specific context, calls the Emacs default `forward-word'.
20688 See the individual commands for more information.
20690 This function runs the hook `org-metaright-hook' as a first step,
20691 and returns at first non-nil value."
20692 (interactive "P")
20693 (cond
20694 ((run-hook-with-args-until-success 'org-metaright-hook))
20695 ((org-at-table-p) (call-interactively 'org-table-move-column))
20696 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20697 ((org-at-block-p) (call-interactively 'org-indent-block))
20698 ((org-with-limited-levels
20699 (or (org-at-heading-p)
20700 (and (org-region-active-p)
20701 (save-excursion
20702 (goto-char (region-beginning))
20703 (org-at-heading-p)))))
20704 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20705 (call-interactively 'org-do-demote))
20706 ;; At an inline task.
20707 ((org-at-heading-p)
20708 (call-interactively 'org-inlinetask-demote))
20709 ((or (org-at-item-p)
20710 (and (org-region-active-p)
20711 (save-excursion
20712 (goto-char (region-beginning))
20713 (org-at-item-p))))
20714 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20715 (call-interactively 'org-indent-item))
20716 (t (call-interactively 'forward-word))))
20718 (defun org-check-for-hidden (what)
20719 "Check if there are hidden headlines/items in the current visual line.
20720 WHAT can be either `headlines' or `items'. If the current line is
20721 an outline or item heading and it has a folded subtree below it,
20722 this function returns t, nil otherwise."
20723 (let ((re (cond
20724 ((eq what 'headlines) org-outline-regexp-bol)
20725 ((eq what 'items) (org-item-beginning-re))
20726 (t (error "This should not happen"))))
20727 beg end)
20728 (save-excursion
20729 (catch 'exit
20730 (unless (org-region-active-p)
20731 (setq beg (point-at-bol))
20732 (beginning-of-line 2)
20733 (while (and (not (eobp)) ;; this is like `next-line'
20734 (get-char-property (1- (point)) 'invisible))
20735 (beginning-of-line 2))
20736 (setq end (point))
20737 (goto-char beg)
20738 (goto-char (point-at-eol))
20739 (setq end (max end (point)))
20740 (while (re-search-forward re end t)
20741 (when (get-char-property (match-beginning 0) 'invisible)
20742 (throw 'exit t))))
20743 nil))))
20745 (defun org-metaup (&optional _arg)
20746 "Move subtree up or move table row up.
20747 Calls `org-move-subtree-up' or `org-table-move-row' or
20748 `org-move-item-up', depending on context. See the individual commands
20749 for more information."
20750 (interactive "P")
20751 (cond
20752 ((run-hook-with-args-until-success 'org-metaup-hook))
20753 ((org-region-active-p)
20754 (let* ((a (min (region-beginning) (region-end)))
20755 (b (1- (max (region-beginning) (region-end))))
20756 (c (save-excursion (goto-char a)
20757 (move-beginning-of-line 0)))
20758 (d (save-excursion (goto-char a)
20759 (move-end-of-line 0) (point))))
20760 (transpose-regions a b c d)
20761 (goto-char c)))
20762 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20763 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20764 ((org-at-item-p) (call-interactively 'org-move-item-up))
20765 (t (org-drag-element-backward))))
20767 (defun org-metadown (&optional _arg)
20768 "Move subtree down or move table row down.
20769 Calls `org-move-subtree-down' or `org-table-move-row' or
20770 `org-move-item-down', depending on context. See the individual
20771 commands for more information."
20772 (interactive "P")
20773 (cond
20774 ((run-hook-with-args-until-success 'org-metadown-hook))
20775 ((org-region-active-p)
20776 (let* ((a (min (region-beginning) (region-end)))
20777 (b (max (region-beginning) (region-end)))
20778 (c (save-excursion (goto-char b)
20779 (move-beginning-of-line 1)))
20780 (d (save-excursion (goto-char b)
20781 (move-end-of-line 1) (1+ (point)))))
20782 (transpose-regions a b c d)
20783 (goto-char d)))
20784 ((org-at-table-p) (call-interactively 'org-table-move-row))
20785 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20786 ((org-at-item-p) (call-interactively 'org-move-item-down))
20787 (t (org-drag-element-forward))))
20789 (defun org-shiftup (&optional arg)
20790 "Increase item in timestamp or increase priority of current headline.
20791 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20792 depending on context. See the individual commands for more information."
20793 (interactive "P")
20794 (cond
20795 ((run-hook-with-args-until-success 'org-shiftup-hook))
20796 ((and org-support-shift-select (org-region-active-p))
20797 (org-call-for-shift-select 'previous-line))
20798 ((org-at-timestamp-p t)
20799 (call-interactively (if org-edit-timestamp-down-means-later
20800 'org-timestamp-down 'org-timestamp-up)))
20801 ((and (not (eq org-support-shift-select 'always))
20802 org-enable-priority-commands
20803 (org-at-heading-p))
20804 (call-interactively 'org-priority-up))
20805 ((and (not org-support-shift-select) (org-at-item-p))
20806 (call-interactively 'org-previous-item))
20807 ((org-clocktable-try-shift 'up arg))
20808 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20809 (org-support-shift-select
20810 (org-call-for-shift-select 'previous-line))
20811 (t (org-shiftselect-error))))
20813 (defun org-shiftdown (&optional arg)
20814 "Decrease item in timestamp or decrease priority of current headline.
20815 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20816 depending on context. See the individual commands for more information."
20817 (interactive "P")
20818 (cond
20819 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20820 ((and org-support-shift-select (org-region-active-p))
20821 (org-call-for-shift-select 'next-line))
20822 ((org-at-timestamp-p t)
20823 (call-interactively (if org-edit-timestamp-down-means-later
20824 'org-timestamp-up 'org-timestamp-down)))
20825 ((and (not (eq org-support-shift-select 'always))
20826 org-enable-priority-commands
20827 (org-at-heading-p))
20828 (call-interactively 'org-priority-down))
20829 ((and (not org-support-shift-select) (org-at-item-p))
20830 (call-interactively 'org-next-item))
20831 ((org-clocktable-try-shift 'down arg))
20832 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20833 (org-support-shift-select
20834 (org-call-for-shift-select 'next-line))
20835 (t (org-shiftselect-error))))
20837 (defun org-shiftright (&optional arg)
20838 "Cycle the thing at point or in the current line, depending on context.
20839 Depending on context, this does one of the following:
20841 - switch a timestamp at point one day into the future
20842 - on a headline, switch to the next TODO keyword.
20843 - on an item, switch entire list to the next bullet type
20844 - on a property line, switch to the next allowed value
20845 - on a clocktable definition line, move time block into the future"
20846 (interactive "P")
20847 (cond
20848 ((run-hook-with-args-until-success 'org-shiftright-hook))
20849 ((and org-support-shift-select (org-region-active-p))
20850 (org-call-for-shift-select 'forward-char))
20851 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20852 ((and (not (eq org-support-shift-select 'always))
20853 (org-at-heading-p))
20854 (let ((org-inhibit-logging
20855 (not org-treat-S-cursor-todo-selection-as-state-change))
20856 (org-inhibit-blocking
20857 (not org-treat-S-cursor-todo-selection-as-state-change)))
20858 (org-call-with-arg 'org-todo 'right)))
20859 ((or (and org-support-shift-select
20860 (not (eq org-support-shift-select 'always))
20861 (org-at-item-bullet-p))
20862 (and (not org-support-shift-select) (org-at-item-p)))
20863 (org-call-with-arg 'org-cycle-list-bullet nil))
20864 ((and (not (eq org-support-shift-select 'always))
20865 (org-at-property-p))
20866 (call-interactively 'org-property-next-allowed-value))
20867 ((org-clocktable-try-shift 'right arg))
20868 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20869 (org-support-shift-select
20870 (org-call-for-shift-select 'forward-char))
20871 (t (org-shiftselect-error))))
20873 (defun org-shiftleft (&optional arg)
20874 "Cycle the thing at point or in the current line, depending on context.
20875 Depending on context, this does one of the following:
20877 - switch a timestamp at point one day into the past
20878 - on a headline, switch to the previous TODO keyword.
20879 - on an item, switch entire list to the previous bullet type
20880 - on a property line, switch to the previous allowed value
20881 - on a clocktable definition line, move time block into the past"
20882 (interactive "P")
20883 (cond
20884 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20885 ((and org-support-shift-select (org-region-active-p))
20886 (org-call-for-shift-select 'backward-char))
20887 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20888 ((and (not (eq org-support-shift-select 'always))
20889 (org-at-heading-p))
20890 (let ((org-inhibit-logging
20891 (not org-treat-S-cursor-todo-selection-as-state-change))
20892 (org-inhibit-blocking
20893 (not org-treat-S-cursor-todo-selection-as-state-change)))
20894 (org-call-with-arg 'org-todo 'left)))
20895 ((or (and org-support-shift-select
20896 (not (eq org-support-shift-select 'always))
20897 (org-at-item-bullet-p))
20898 (and (not org-support-shift-select) (org-at-item-p)))
20899 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20900 ((and (not (eq org-support-shift-select 'always))
20901 (org-at-property-p))
20902 (call-interactively 'org-property-previous-allowed-value))
20903 ((org-clocktable-try-shift 'left arg))
20904 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20905 (org-support-shift-select
20906 (org-call-for-shift-select 'backward-char))
20907 (t (org-shiftselect-error))))
20909 (defun org-shiftcontrolright ()
20910 "Switch to next TODO set."
20911 (interactive)
20912 (cond
20913 ((and org-support-shift-select (org-region-active-p))
20914 (org-call-for-shift-select 'forward-word))
20915 ((and (not (eq org-support-shift-select 'always))
20916 (org-at-heading-p))
20917 (org-call-with-arg 'org-todo 'nextset))
20918 (org-support-shift-select
20919 (org-call-for-shift-select 'forward-word))
20920 (t (org-shiftselect-error))))
20922 (defun org-shiftcontrolleft ()
20923 "Switch to previous TODO set."
20924 (interactive)
20925 (cond
20926 ((and org-support-shift-select (org-region-active-p))
20927 (org-call-for-shift-select 'backward-word))
20928 ((and (not (eq org-support-shift-select 'always))
20929 (org-at-heading-p))
20930 (org-call-with-arg 'org-todo 'previousset))
20931 (org-support-shift-select
20932 (org-call-for-shift-select 'backward-word))
20933 (t (org-shiftselect-error))))
20935 (defun org-shiftcontrolup (&optional n)
20936 "Change timestamps synchronously up in CLOCK log lines.
20937 Optional argument N tells to change by that many units."
20938 (interactive "P")
20939 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20940 (let (org-support-shift-select)
20941 (org-clock-timestamps-up n))
20942 (user-error "Not at a clock log")))
20944 (defun org-shiftcontroldown (&optional n)
20945 "Change timestamps synchronously down in CLOCK log lines.
20946 Optional argument N tells to change by that many units."
20947 (interactive "P")
20948 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20949 (let (org-support-shift-select)
20950 (org-clock-timestamps-down n))
20951 (user-error "Not at a clock log")))
20953 (defun org-increase-number-at-point (&optional inc)
20954 "Increment the number at point.
20955 With an optional prefix numeric argument INC, increment using
20956 this numeric value."
20957 (interactive "p")
20958 (if (not (number-at-point))
20959 (user-error "Not on a number")
20960 (unless inc (setq inc 1))
20961 (let ((pos (point))
20962 (beg (skip-chars-backward "-+^/*0-9eE."))
20963 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20964 (setq nap (buffer-substring-no-properties
20965 (+ pos beg) (+ pos beg end)))
20966 (delete-region (+ pos beg) (+ pos beg end))
20967 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20968 (when (org-at-table-p)
20969 (org-table-align)
20970 (org-table-end-of-field 1))))
20972 (defun org-decrease-number-at-point (&optional inc)
20973 "Decrement the number at point.
20974 With an optional prefix numeric argument INC, decrement using
20975 this numeric value."
20976 (interactive "p")
20977 (org-increase-number-at-point (- (or inc 1))))
20979 (defun org-ctrl-c-ret ()
20980 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20981 (interactive)
20982 (cond
20983 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20984 (t (call-interactively 'org-insert-heading))))
20986 (defun org-find-visible ()
20987 (let ((s (point)))
20988 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20989 (get-char-property s 'invisible)))
20991 (defun org-find-invisible ()
20992 (let ((s (point)))
20993 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20994 (not (get-char-property s 'invisible))))
20997 (defun org-copy-visible (beg end)
20998 "Copy the visible parts of the region."
20999 (interactive "r")
21000 (let (snippets s)
21001 (save-excursion
21002 (save-restriction
21003 (narrow-to-region beg end)
21004 (setq s (goto-char (point-min)))
21005 (while (not (= (point) (point-max)))
21006 (goto-char (org-find-invisible))
21007 (push (buffer-substring s (point)) snippets)
21008 (setq s (goto-char (org-find-visible))))))
21009 (kill-new (apply 'concat (nreverse snippets)))))
21011 (defun org-copy-special ()
21012 "Copy region in table or copy current subtree.
21013 Calls `org-table-copy-region' or `org-copy-subtree', depending on
21014 context. See the individual commands for more information."
21015 (interactive)
21016 (call-interactively
21017 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
21019 (defun org-cut-special ()
21020 "Cut region in table or cut current subtree.
21021 Calls `org-table-cut-region' or `org-cut-subtree', depending on
21022 context. See the individual commands for more information."
21023 (interactive)
21024 (call-interactively
21025 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
21027 (defun org-paste-special (arg)
21028 "Paste rectangular region into table, or past subtree relative to level.
21029 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
21030 See the individual commands for more information."
21031 (interactive "P")
21032 (if (org-at-table-p)
21033 (org-table-paste-rectangle)
21034 (org-paste-subtree arg)))
21036 (defun org-edit-special (&optional arg)
21037 "Call a special editor for the element at point.
21038 When at a table, call the formula editor with `org-table-edit-formulas'.
21039 When in a source code block, call `org-edit-src-code'.
21040 When in a fixed-width region, call `org-edit-fixed-width-region'.
21041 When in an export block, call `org-edit-export-block'.
21042 When at an #+INCLUDE keyword, visit the included file.
21043 When at a footnote reference, call `org-edit-footnote-reference'
21044 On a link, call `ffap' to visit the link at point.
21045 Otherwise, return a user error."
21046 (interactive "P")
21047 (let ((element (org-element-at-point)))
21048 (barf-if-buffer-read-only)
21049 (pcase (org-element-type element)
21050 (`src-block
21051 (if (not arg) (org-edit-src-code)
21052 (let* ((info (org-babel-get-src-block-info))
21053 (lang (nth 0 info))
21054 (params (nth 2 info))
21055 (session (cdr (assq :session params))))
21056 (if (not session) (org-edit-src-code)
21057 ;; At a src-block with a session and function called with
21058 ;; an ARG: switch to the buffer related to the inferior
21059 ;; process.
21060 (switch-to-buffer
21061 (funcall (intern (concat "org-babel-prep-session:" lang))
21062 session params))))))
21063 (`keyword
21064 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21065 (org-open-link-from-string
21066 (format "[[%s]]"
21067 (expand-file-name
21068 (let ((value (org-element-property :value element)))
21069 (cond ((not (org-string-nw-p value))
21070 (user-error "No file to edit"))
21071 ((string-match "\\`\"\\(.*?\\)\"" value)
21072 (match-string 1 value))
21073 ((string-match "\\`[^ \t\"]\\S-*" value)
21074 (match-string 0 value))
21075 (t (user-error "No valid file specified")))))))
21076 (user-error "No special environment to edit here")))
21077 (`table
21078 (if (eq (org-element-property :type element) 'table.el)
21079 (org-edit-table.el)
21080 (call-interactively 'org-table-edit-formulas)))
21081 ;; Only Org tables contain `table-row' type elements.
21082 (`table-row (call-interactively 'org-table-edit-formulas))
21083 (`example-block (org-edit-src-code))
21084 (`export-block (org-edit-export-block))
21085 (`fixed-width (org-edit-fixed-width-region))
21087 ;; No notable element at point. Though, we may be at a link or
21088 ;; a footnote reference, which are objects. Thus, scan deeper.
21089 (let ((context (org-element-context element)))
21090 (pcase (org-element-type context)
21091 (`footnote-reference (org-edit-footnote-reference))
21092 (`inline-src-block (org-edit-inline-src-code))
21093 (`link (call-interactively #'ffap))
21094 (_ (user-error "No special environment to edit here"))))))))
21096 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21097 (defun org-ctrl-c-ctrl-c (&optional arg)
21098 "Set tags in headline, or update according to changed information at point.
21100 This command does many different things, depending on context:
21102 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21103 this is what we do.
21105 - If the cursor is on a statistics cookie, update it.
21107 - If the cursor is in a headline, prompt for tags and insert them
21108 into the current line, aligned to `org-tags-column'. When called
21109 with prefix arg, realign all tags in the current buffer.
21111 - If the cursor is in one of the special #+KEYWORD lines, this
21112 triggers scanning the buffer for these lines and updating the
21113 information.
21115 - If the cursor is inside a table, realign the table. This command
21116 works even if the automatic table editor has been turned off.
21118 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21119 the entire table.
21121 - If the cursor is at a footnote reference or definition, jump to
21122 the corresponding definition or references, respectively.
21124 - If the cursor is a the beginning of a dynamic block, update it.
21126 - If the current buffer is a capture buffer, close note and file it.
21128 - If the cursor is on a <<<target>>>, update radio targets and
21129 corresponding links in this buffer.
21131 - If the cursor is on a numbered item in a plain list, renumber the
21132 ordered list.
21134 - If the cursor is on a checkbox, toggle it.
21136 - If the cursor is on a code block, evaluate it. The variable
21137 `org-confirm-babel-evaluate' can be used to control prompting
21138 before code block evaluation, by default every code block
21139 evaluation requires confirmation. Code block evaluation can be
21140 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21141 (interactive "P")
21142 (cond
21143 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
21144 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21145 (org-remove-occur-highlights)
21146 (message "Temporary highlights/overlays removed from current buffer"))
21147 ((and (local-variable-p 'org-finish-function)
21148 (fboundp org-finish-function))
21149 (funcall org-finish-function))
21150 ((org-babel-hash-at-point))
21151 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21152 ((save-excursion (beginning-of-line) (looking-at-p "[ \t]*$"))
21153 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21154 (user-error
21155 (substitute-command-keys
21156 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
21158 (let* ((context
21159 (org-element-lineage
21160 (org-element-context)
21161 ;; Limit to supported contexts.
21162 '(babel-call clock dynamic-block footnote-definition
21163 footnote-reference inline-babel-call inline-src-block
21164 item keyword node-property paragraph plain-list
21165 property-drawer radio-target src-block
21166 statistics-cookie table table-cell table-row
21167 timestamp)
21169 (type (org-element-type context)))
21170 ;; For convenience: at the first line of a paragraph on the same
21171 ;; line as an item, apply function on that item instead.
21172 (when (eq type 'paragraph)
21173 (let ((parent (org-element-property :parent context)))
21174 (when (and (eq (org-element-type parent) 'item)
21175 (= (line-beginning-position)
21176 (org-element-property :begin parent)))
21177 (setq context parent)
21178 (setq type 'item))))
21179 ;; Act according to type of element or object at point.
21180 (pcase type
21181 ((or `babel-call `inline-babel-call)
21182 (let ((info (org-babel-lob-get-info context)))
21183 (when info (org-babel-execute-src-block nil info))))
21184 (`clock (org-clock-update-time-maybe))
21185 (`dynamic-block
21186 (save-excursion
21187 (goto-char (org-element-property :post-affiliated context))
21188 (org-update-dblock)))
21189 (`footnote-definition
21190 (goto-char (org-element-property :post-affiliated context))
21191 (call-interactively 'org-footnote-action))
21192 (`footnote-reference (call-interactively #'org-footnote-action))
21193 ((or `headline `inlinetask)
21194 (save-excursion (goto-char (org-element-property :begin context))
21195 (call-interactively #'org-set-tags)))
21196 ((or `inline-src-block `src-block)
21197 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
21198 (org-babel-eval-wipe-error-buffer)
21199 (org-babel-execute-src-block
21200 current-prefix-arg (org-babel-get-src-block-info nil context))))
21201 (`item
21202 ;; At an item: `C-u C-u' sets checkbox to "[-]"
21203 ;; unconditionally, whereas `C-u' will toggle its presence.
21204 ;; Without a universal argument, if the item has a checkbox,
21205 ;; toggle it. Otherwise repair the list.
21206 (let* ((box (org-element-property :checkbox context))
21207 (struct (org-element-property :structure context))
21208 (old-struct (copy-tree struct))
21209 (parents (org-list-parents-alist struct))
21210 (prevs (org-list-prevs-alist struct))
21211 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21212 (org-list-set-checkbox
21213 (org-element-property :begin context) struct
21214 (cond ((equal arg '(16)) "[-]")
21215 ((and (not box) (equal arg '(4))) "[ ]")
21216 ((or (not box) (equal arg '(4))) nil)
21217 ((eq box 'on) "[ ]")
21218 (t "[X]")))
21219 ;; Mimic `org-list-write-struct' but with grabbing a return
21220 ;; value from `org-list-struct-fix-box'.
21221 (org-list-struct-fix-ind struct parents 2)
21222 (org-list-struct-fix-item-end struct)
21223 (org-list-struct-fix-bul struct prevs)
21224 (org-list-struct-fix-ind struct parents)
21225 (let ((block-item
21226 (org-list-struct-fix-box struct parents prevs orderedp)))
21227 (if (and box (equal struct old-struct))
21228 (if (equal arg '(16))
21229 (message "Checkboxes already reset")
21230 (user-error "Cannot toggle this checkbox: %s"
21231 (if (eq box 'on)
21232 "all subitems checked"
21233 "unchecked subitems")))
21234 (org-list-struct-apply-struct struct old-struct)
21235 (org-update-checkbox-count-maybe))
21236 (when block-item
21237 (message "Checkboxes were removed due to empty box at line %d"
21238 (org-current-line block-item))))))
21239 (`keyword
21240 (let ((org-inhibit-startup-visibility-stuff t)
21241 (org-startup-align-all-tables nil))
21242 (when (boundp 'org-table-coordinate-overlays)
21243 (mapc #'delete-overlay org-table-coordinate-overlays)
21244 (setq org-table-coordinate-overlays nil))
21245 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21246 (message "Local setup has been refreshed"))
21247 (`plain-list
21248 ;; At a plain list, with a double C-u argument, set
21249 ;; checkboxes of each item to "[-]", whereas a single one
21250 ;; will toggle their presence according to the state of the
21251 ;; first item in the list. Without an argument, repair the
21252 ;; list.
21253 (let* ((begin (org-element-property :contents-begin context))
21254 (beginm (move-marker (make-marker) begin))
21255 (struct (org-element-property :structure context))
21256 (old-struct (copy-tree struct))
21257 (first-box (save-excursion
21258 (goto-char begin)
21259 (looking-at org-list-full-item-re)
21260 (match-string-no-properties 3)))
21261 (new-box (cond ((equal arg '(16)) "[-]")
21262 ((equal arg '(4)) (unless first-box "[ ]"))
21263 ((equal first-box "[X]") "[ ]")
21264 (t "[X]"))))
21265 (cond
21266 (arg
21267 (dolist (pos
21268 (org-list-get-all-items
21269 begin struct (org-list-prevs-alist struct)))
21270 (org-list-set-checkbox pos struct new-box)))
21271 ((and first-box (eq (point) begin))
21272 ;; For convenience, when point is at bol on the first
21273 ;; item of the list and no argument is provided, simply
21274 ;; toggle checkbox of that item, if any.
21275 (org-list-set-checkbox begin struct new-box)))
21276 (org-list-write-struct
21277 struct (org-list-parents-alist struct) old-struct)
21278 (org-update-checkbox-count-maybe)
21279 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21280 ((or `property-drawer `node-property)
21281 (call-interactively #'org-property-action))
21282 (`radio-target
21283 (call-interactively #'org-update-radio-target-regexp))
21284 (`statistics-cookie
21285 (call-interactively #'org-update-statistics-cookies))
21286 ((or `table `table-cell `table-row)
21287 ;; At a table, recalculate every field and align it. Also
21288 ;; send the table if necessary. If the table has
21289 ;; a `table.el' type, just give up. At a table row or cell,
21290 ;; maybe recalculate line but always align table.
21291 (if (eq (org-element-property :type context) 'table.el)
21292 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21293 Use `\\[org-edit-special]' to edit table.el tables"))
21294 (let ((org-enable-table-editor t))
21295 (if (or (eq type 'table)
21296 ;; Check if point is at a TBLFM line.
21297 (and (eq type 'table-row)
21298 (= (point) (org-element-property :end context))))
21299 (save-excursion
21300 (if (org-at-TBLFM-p)
21301 (progn (require 'org-table)
21302 (org-table-calc-current-TBLFM))
21303 (goto-char (org-element-property :contents-begin context))
21304 (org-call-with-arg 'org-table-recalculate (or arg t))
21305 (orgtbl-send-table 'maybe)))
21306 (org-table-maybe-eval-formula)
21307 (cond (arg (call-interactively #'org-table-recalculate))
21308 ((org-table-maybe-recalculate-line))
21309 (t (org-table-align)))))))
21310 (`timestamp (org-timestamp-change 0 'day))
21311 ((and `nil (guard (org-at-heading-p)))
21312 ;; When point is on an unsupported object type, we can miss
21313 ;; the fact that it also is at a heading. Handle it here.
21314 (call-interactively #'org-set-tags))
21315 ((guard
21316 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21318 (user-error
21319 (substitute-command-keys
21320 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21322 (defun org-mode-restart ()
21323 (interactive)
21324 (let ((indent-status (bound-and-true-p org-indent-mode)))
21325 (funcall major-mode)
21326 (hack-local-variables)
21327 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21328 (org-indent-mode -1)))
21329 (message "%s restarted" major-mode))
21331 (defun org-kill-note-or-show-branches ()
21332 "Abort storing current note, or call `outline-show-branches'."
21333 (interactive)
21334 (if (not org-finish-function)
21335 (progn
21336 (outline-hide-subtree)
21337 (call-interactively 'outline-show-branches))
21338 (let ((org-note-abort t))
21339 (funcall org-finish-function))))
21341 (defun org-delete-indentation (&optional arg)
21342 "Join current line to previous and fix whitespace at join.
21344 If previous line is a headline add to headline title. Otherwise
21345 the function calls `delete-indentation'.
21347 With a non-nil optional argument, join it to the following one."
21348 (interactive "*P")
21349 (if (save-excursion
21350 (beginning-of-line (if arg 1 0))
21351 (let ((case-fold-search nil))
21352 (looking-at org-complex-heading-regexp)))
21353 ;; At headline.
21354 (let ((tags-column (when (match-beginning 5)
21355 (save-excursion (goto-char (match-beginning 5))
21356 (current-column))))
21357 (string (concat " " (progn (when arg (forward-line 1))
21358 (org-trim (delete-and-extract-region
21359 (line-beginning-position)
21360 (line-end-position)))))))
21361 (unless (bobp) (delete-region (point) (1- (point))))
21362 (goto-char (or (match-end 4)
21363 (match-beginning 5)
21364 (match-end 0)))
21365 (skip-chars-backward " \t")
21366 (save-excursion (insert string))
21367 ;; Adjust alignment of tags.
21368 (cond
21369 ((not tags-column)) ;no tags
21370 (org-auto-align-tags (org-set-tags nil t))
21371 (t (org--align-tags-here tags-column)))) ;preserve tags column
21372 (delete-indentation arg)))
21374 (defun org-open-line (n)
21375 "Insert a new row in tables, call `open-line' elsewhere.
21376 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21377 As a special case, when a document starts with a table, allow to
21378 call `open-line' on the very first character."
21379 (interactive "*p")
21380 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21381 (org-table-insert-row)
21382 (open-line n)))
21384 (defun org-return (&optional indent)
21385 "Goto next table row or insert a newline.
21387 Calls `org-table-next-row' or `newline', depending on context.
21389 When optional INDENT argument is non-nil, call
21390 `newline-and-indent' instead of `newline'.
21392 When `org-return-follows-link' is non-nil and point is on
21393 a timestamp or a link, call `org-open-at-point'. However, it
21394 will not happen if point is in a table or on a \"dead\"
21395 object (e.g., within a comment). In these case, you need to use
21396 `org-open-at-point' directly."
21397 (interactive)
21398 (let ((context (if org-return-follows-link (org-element-context)
21399 (org-element-at-point))))
21400 (cond
21401 ;; In a table, call `org-table-next-row'.
21402 ((or (and (eq (org-element-type context) 'table)
21403 (>= (point) (org-element-property :contents-begin context))
21404 (< (point) (org-element-property :contents-end context)))
21405 (org-element-lineage context '(table-row table-cell) t))
21406 (org-table-justify-field-maybe)
21407 (call-interactively #'org-table-next-row))
21408 ;; On a link or a timestamp, call `org-open-at-point' if
21409 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21410 ;; locations, e.g., in a comment, as `org-open-at-point'.
21411 ((and org-return-follows-link
21412 (or (org-in-regexp org-ts-regexp-both nil t)
21413 (org-in-regexp org-tsr-regexp-both nil t)
21414 (org-in-regexp org-any-link-re nil t)))
21415 (call-interactively #'org-open-at-point))
21416 ;; Insert newline in heading, but preserve tags.
21417 ((and (not (bolp))
21418 (save-excursion (beginning-of-line)
21419 (let ((case-fold-search nil))
21420 (looking-at org-complex-heading-regexp))))
21421 ;; At headline. Split line. However, if point is on keyword,
21422 ;; priority cookie or tags, do not break any of them: add
21423 ;; a newline after the headline instead.
21424 (let ((tags-column (and (match-beginning 5)
21425 (save-excursion (goto-char (match-beginning 5))
21426 (current-column))))
21427 (string
21428 (when (and (match-end 4) (org-point-in-group (point) 4))
21429 (delete-and-extract-region (point) (match-end 4)))))
21430 ;; Adjust tag alignment.
21431 (cond
21432 ((not (and tags-column string)))
21433 (org-auto-align-tags (org-set-tags nil t))
21434 (t (org--align-tags-here tags-column))) ;preserve tags column
21435 (end-of-line)
21436 (org-show-entry)
21437 (if indent (newline-and-indent) (newline))
21438 (when string (save-excursion (insert (org-trim string))))))
21439 ;; In a list, make sure indenting keeps trailing text within.
21440 ((and indent
21441 (not (eolp))
21442 (org-element-lineage context '(item)))
21443 (let ((trailing-data
21444 (delete-and-extract-region (point) (line-end-position))))
21445 (newline-and-indent)
21446 (save-excursion (insert trailing-data))))
21447 (t (if indent (newline-and-indent) (newline))))))
21449 (defun org-return-indent ()
21450 "Goto next table row or insert a newline and indent.
21451 Calls `org-table-next-row' or `newline-and-indent', depending on
21452 context. See the individual commands for more information."
21453 (interactive)
21454 (org-return t))
21456 (defun org-ctrl-c-star ()
21457 "Compute table, or change heading status of lines.
21458 Calls `org-table-recalculate' or `org-toggle-heading',
21459 depending on context."
21460 (interactive)
21461 (cond
21462 ((org-at-table-p)
21463 (call-interactively 'org-table-recalculate))
21465 ;; Convert all lines in region to list items
21466 (call-interactively 'org-toggle-heading))))
21468 (defun org-ctrl-c-minus ()
21469 "Insert separator line in table or modify bullet status of line.
21470 Also turns a plain line or a region of lines into list items.
21471 Calls `org-table-insert-hline', `org-toggle-item', or
21472 `org-cycle-list-bullet', depending on context."
21473 (interactive)
21474 (cond
21475 ((org-at-table-p)
21476 (call-interactively 'org-table-insert-hline))
21477 ((org-region-active-p)
21478 (call-interactively 'org-toggle-item))
21479 ((org-in-item-p)
21480 (call-interactively 'org-cycle-list-bullet))
21482 (call-interactively 'org-toggle-item))))
21484 (defun org-toggle-heading (&optional nstars)
21485 "Convert headings to normal text, or items or text to headings.
21486 If there is no active region, only convert the current line.
21488 With a `\\[universal-argument]' prefix, convert the whole list at
21489 point into heading.
21491 In a region:
21493 - If the first non blank line is a headline, remove the stars
21494 from all headlines in the region.
21496 - If it is a normal line, turn each and every normal line (i.e.,
21497 not an heading or an item) in the region into headings. If you
21498 want to convert only the first line of this region, use one
21499 universal prefix argument.
21501 - If it is a plain list item, turn all plain list items into headings.
21503 When converting a line into a heading, the number of stars is chosen
21504 such that the lines become children of the current entry. However,
21505 when a numeric prefix argument is given, its value determines the
21506 number of stars to add."
21507 (interactive "P")
21508 (let ((skip-blanks
21509 (function
21510 ;; Return beginning of first non-blank line, starting from
21511 ;; line at POS.
21512 (lambda (pos)
21513 (save-excursion
21514 (goto-char pos)
21515 (while (org-at-comment-p) (forward-line))
21516 (skip-chars-forward " \r\t\n")
21517 (point-at-bol)))))
21518 beg end toggled)
21519 ;; Determine boundaries of changes. If a universal prefix has
21520 ;; been given, put the list in a region. If region ends at a bol,
21521 ;; do not consider the last line to be in the region.
21523 (when (and current-prefix-arg (org-at-item-p))
21524 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21525 (org-mark-element))
21527 (if (org-region-active-p)
21528 (setq beg (funcall skip-blanks (region-beginning))
21529 end (copy-marker (save-excursion
21530 (goto-char (region-end))
21531 (if (bolp) (point) (point-at-eol)))))
21532 (setq beg (funcall skip-blanks (point-at-bol))
21533 end (copy-marker (point-at-eol))))
21534 ;; Ensure inline tasks don't count as headings.
21535 (org-with-limited-levels
21536 (save-excursion
21537 (goto-char beg)
21538 (cond
21539 ;; Case 1. Started at an heading: de-star headings.
21540 ((org-at-heading-p)
21541 (while (< (point) end)
21542 (when (org-at-heading-p t)
21543 (looking-at org-outline-regexp) (replace-match "")
21544 (setq toggled t))
21545 (forward-line)))
21546 ;; Case 2. Started at an item: change items into headlines.
21547 ;; One star will be added by `org-list-to-subtree'.
21548 ((org-at-item-p)
21549 (while (< (point) end)
21550 (when (org-at-item-p)
21551 ;; Pay attention to cases when region ends before list.
21552 (let* ((struct (org-list-struct))
21553 (list-end
21554 (min (org-list-get-bottom-point struct) (1+ end))))
21555 (save-restriction
21556 (narrow-to-region (point) list-end)
21557 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21558 (setq toggled t))
21559 (forward-line)))
21560 ;; Case 3. Started at normal text: make every line an heading,
21561 ;; skipping headlines and items.
21562 (t (let* ((stars
21563 (make-string
21564 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21565 (add-stars
21566 (cond (nstars "") ; stars from prefix only
21567 ((equal stars "") "*") ; before first heading
21568 (org-odd-levels-only "**") ; inside heading, odd
21569 (t "*"))) ; inside heading, oddeven
21570 (rpl (concat stars add-stars " "))
21571 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21572 (while (< (point) (if (equal nstars '(4)) lend end))
21573 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21574 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21575 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21576 (forward-line)))))))
21577 (unless toggled (message "Cannot toggle heading from here"))))
21579 (defun org-meta-return (&optional _arg)
21580 "Insert a new heading or wrap a region in a table.
21581 Calls `org-insert-heading' or `org-table-wrap-region', depending
21582 on context. See the individual commands for more information."
21583 (interactive)
21584 (org-check-before-invisible-edit 'insert)
21585 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21586 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21587 #'org-insert-heading))))
21589 ;;; Menu entries
21591 (defsubst org-in-subtree-not-table-p ()
21592 "Are we in a subtree and not in a table?"
21593 (and (not (org-before-first-heading-p))
21594 (not (org-at-table-p))))
21596 ;; Define the Org mode menus
21597 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21598 '("Tbl"
21599 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21600 ["Next Field" org-cycle (org-at-table-p)]
21601 ["Previous Field" org-shifttab (org-at-table-p)]
21602 ["Next Row" org-return (org-at-table-p)]
21603 "--"
21604 ["Blank Field" org-table-blank-field (org-at-table-p)]
21605 ["Edit Field" org-table-edit-field (org-at-table-p)]
21606 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21607 "--"
21608 ("Column"
21609 ["Move Column Left" org-metaleft (org-at-table-p)]
21610 ["Move Column Right" org-metaright (org-at-table-p)]
21611 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21612 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21613 ("Row"
21614 ["Move Row Up" org-metaup (org-at-table-p)]
21615 ["Move Row Down" org-metadown (org-at-table-p)]
21616 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21617 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21618 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21619 "--"
21620 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21621 ("Rectangle"
21622 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21623 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21624 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21625 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21626 "--"
21627 ("Calculate"
21628 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21629 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21630 ["Edit Formulas" org-edit-special (org-at-table-p)]
21631 "--"
21632 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21633 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21634 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21635 "--"
21636 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21637 "--"
21638 ["Sum Column/Rectangle" org-table-sum
21639 (or (org-at-table-p) (org-region-active-p))]
21640 ["Which Column?" org-table-current-column (org-at-table-p)])
21641 ["Debug Formulas"
21642 org-table-toggle-formula-debugger
21643 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21644 ["Show Col/Row Numbers"
21645 org-table-toggle-coordinate-overlays
21646 :style toggle
21647 :selected (bound-and-true-p org-table-overlay-coordinates)]
21648 "--"
21649 ["Create" org-table-create (and (not (org-at-table-p))
21650 org-enable-table-editor)]
21651 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21652 ["Import from File" org-table-import (not (org-at-table-p))]
21653 ["Export to File" org-table-export (org-at-table-p)]
21654 "--"
21655 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21656 "--"
21657 ("Plot"
21658 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21659 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21661 (easy-menu-define org-org-menu org-mode-map "Org menu"
21662 '("Org"
21663 ("Show/Hide"
21664 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21665 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21666 ["Sparse Tree..." org-sparse-tree t]
21667 ["Reveal Context" org-reveal t]
21668 ["Show All" outline-show-all t]
21669 "--"
21670 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21671 "--"
21672 ["New Heading" org-insert-heading t]
21673 ("Navigate Headings"
21674 ["Up" outline-up-heading t]
21675 ["Next" outline-next-visible-heading t]
21676 ["Previous" outline-previous-visible-heading t]
21677 ["Next Same Level" outline-forward-same-level t]
21678 ["Previous Same Level" outline-backward-same-level t]
21679 "--"
21680 ["Jump" org-goto t])
21681 ("Edit Structure"
21682 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21683 "--"
21684 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21685 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21686 "--"
21687 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21688 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21689 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21690 "--"
21691 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21692 "--"
21693 ["Copy visible text" org-copy-visible t]
21694 "--"
21695 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21696 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21697 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21698 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21699 "--"
21700 ["Sort Region/Children" org-sort t]
21701 "--"
21702 ["Convert to odd levels" org-convert-to-odd-levels t]
21703 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21704 ("Editing"
21705 ["Emphasis..." org-emphasize t]
21706 ["Edit Source Example" org-edit-special t]
21707 "--"
21708 ["Footnote new/jump" org-footnote-action t]
21709 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21710 ("Archive"
21711 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21712 "--"
21713 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21714 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21715 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21717 "--"
21718 ("Hyperlinks"
21719 ["Store Link (Global)" org-store-link t]
21720 ["Find existing link to here" org-occur-link-in-agenda-files t]
21721 ["Insert Link" org-insert-link t]
21722 ["Follow Link" org-open-at-point t]
21723 "--"
21724 ["Next link" org-next-link t]
21725 ["Previous link" org-previous-link t]
21726 "--"
21727 ["Descriptive Links"
21728 org-toggle-link-display
21729 :style radio
21730 :selected org-descriptive-links
21732 ["Literal Links"
21733 org-toggle-link-display
21734 :style radio
21735 :selected (not org-descriptive-links)])
21736 "--"
21737 ("TODO Lists"
21738 ["TODO/DONE/-" org-todo t]
21739 ("Select keyword"
21740 ["Next keyword" org-shiftright (org-at-heading-p)]
21741 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21742 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21743 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21744 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21745 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21746 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21747 "--"
21748 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21749 :selected org-enforce-todo-dependencies :style toggle :active t]
21750 "Settings for tree at point"
21751 ["Do Children sequentially" org-toggle-ordered-property :style radio
21752 :selected (org-entry-get nil "ORDERED")
21753 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21754 ["Do Children parallel" org-toggle-ordered-property :style radio
21755 :selected (not (org-entry-get nil "ORDERED"))
21756 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21757 "--"
21758 ["Set Priority" org-priority t]
21759 ["Priority Up" org-shiftup t]
21760 ["Priority Down" org-shiftdown t]
21761 "--"
21762 ["Get news from all feeds" org-feed-update-all t]
21763 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21764 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21765 ("TAGS and Properties"
21766 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21767 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21768 "--"
21769 ["Set property" org-set-property (not (org-before-first-heading-p))]
21770 ["Column view of properties" org-columns t]
21771 ["Insert Column View DBlock" org-columns-insert-dblock t])
21772 ("Dates and Scheduling"
21773 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21774 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21775 ("Change Date"
21776 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21777 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21778 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21779 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21780 ["Compute Time Range" org-evaluate-time-range t]
21781 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21782 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21783 "--"
21784 ["Custom time format" org-toggle-time-stamp-overlays
21785 :style radio :selected org-display-custom-times]
21786 "--"
21787 ["Goto Calendar" org-goto-calendar t]
21788 ["Date from Calendar" org-date-from-calendar t]
21789 "--"
21790 ["Start/Restart Timer" org-timer-start t]
21791 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21792 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21793 ["Insert Timer String" org-timer t]
21794 ["Insert Timer Item" org-timer-item t])
21795 ("Logging work"
21796 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21797 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21798 ["Clock out" org-clock-out t]
21799 ["Clock cancel" org-clock-cancel t]
21800 "--"
21801 ["Mark as default task" org-clock-mark-default-task t]
21802 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21803 ["Goto running clock" org-clock-goto t]
21804 "--"
21805 ["Display times" org-clock-display t]
21806 ["Create clock table" org-clock-report t]
21807 "--"
21808 ["Record DONE time"
21809 (progn (setq org-log-done (not org-log-done))
21810 (message "Switching to %s will %s record a timestamp"
21811 (car org-done-keywords)
21812 (if org-log-done "automatically" "not")))
21813 :style toggle :selected org-log-done])
21814 "--"
21815 ["Agenda Command..." org-agenda t]
21816 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21817 ("File List for Agenda")
21818 ("Special views current file"
21819 ["TODO Tree" org-show-todo-tree t]
21820 ["Check Deadlines" org-check-deadlines t]
21821 ["Timeline" org-timeline t]
21822 ["Tags/Property tree" org-match-sparse-tree t])
21823 "--"
21824 ["Export/Publish..." org-export-dispatch t]
21825 ("LaTeX"
21826 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21827 :selected org-cdlatex-mode]
21828 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21829 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21830 ["Modify math symbol" org-cdlatex-math-modify
21831 (org-inside-LaTeX-fragment-p)]
21832 ["Insert citation" org-reftex-citation t])
21833 "--"
21834 ("MobileOrg"
21835 ["Push Files and Views" org-mobile-push t]
21836 ["Get Captured and Flagged" org-mobile-pull t]
21837 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21838 "--"
21839 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21840 "--"
21841 ("Documentation"
21842 ["Show Version" org-version t]
21843 ["Info Documentation" org-info t])
21844 ("Customize"
21845 ["Browse Org Group" org-customize t]
21846 "--"
21847 ["Expand This Menu" org-create-customize-menu
21848 (fboundp 'customize-menu-create)])
21849 ["Send bug report" org-submit-bug-report t]
21850 "--"
21851 ("Refresh/Reload"
21852 ["Refresh setup current buffer" org-mode-restart t]
21853 ["Reload Org (after update)" org-reload t]
21854 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21857 (defun org-info (&optional node)
21858 "Read documentation for Org in the info system.
21859 With optional NODE, go directly to that node."
21860 (interactive)
21861 (info (format "(org)%s" (or node ""))))
21863 ;;;###autoload
21864 (defun org-submit-bug-report ()
21865 "Submit a bug report on Org via mail.
21867 Don't hesitate to report any problems or inaccurate documentation.
21869 If you don't have setup sending mail from (X)Emacs, please copy the
21870 output buffer into your mail program, as it gives us important
21871 information about your Org version and configuration."
21872 (interactive)
21873 (require 'reporter)
21874 (defvar reporter-prompt-for-summary-p)
21875 (org-load-modules-maybe)
21876 (org-require-autoloaded-modules)
21877 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21878 (reporter-submit-bug-report
21879 "emacs-orgmode@gnu.org"
21880 (org-version nil 'full)
21881 (let (list)
21882 (save-window-excursion
21883 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21884 (delete-other-windows)
21885 (erase-buffer)
21886 (insert "You are about to submit a bug report to the Org mailing list.
21888 We would like to add your full Org and Outline configuration to the
21889 bug report. This greatly simplifies the work of the maintainer and
21890 other experts on the mailing list.
21892 HOWEVER, some variables you have customized may contain private
21893 information. The names of customers, colleagues, or friends, might
21894 appear in the form of file names, tags, todo states, or search strings.
21895 If you answer yes to the prompt, you might want to check and remove
21896 such private information before sending the email.")
21897 (add-text-properties (point-min) (point-max) '(face org-warning))
21898 (when (yes-or-no-p "Include your Org configuration ")
21899 (mapatoms
21900 (lambda (v)
21901 (and (boundp v)
21902 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21903 (or (and (symbol-value v)
21904 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21905 (and
21906 (get v 'custom-type) (get v 'standard-value)
21907 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21908 (push v list)))))
21909 (kill-buffer (get-buffer "*Warn about privacy*"))
21910 list))
21911 nil nil
21912 "Remember to cover the basics, that is, what you expected to happen and
21913 what in fact did happen. You don't know how to make a good report? See
21915 http://orgmode.org/manual/Feedback.html#Feedback
21917 Your bug report will be posted to the Org mailing list.
21918 ------------------------------------------------------------------------")
21919 (save-excursion
21920 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21921 (replace-match "\\1Bug: \\3 [\\2]")))))
21924 (defun org-install-agenda-files-menu ()
21925 (let ((bl (buffer-list)))
21926 (save-excursion
21927 (while bl
21928 (set-buffer (pop bl))
21929 (when (derived-mode-p 'org-mode) (setq bl nil)))
21930 (when (derived-mode-p 'org-mode)
21931 (easy-menu-change
21932 '("Org") "File List for Agenda"
21933 (append
21934 (list
21935 ["Edit File List" (org-edit-agenda-file-list) t]
21936 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21937 ["Remove Current File from List" org-remove-file t]
21938 ["Cycle through agenda files" org-cycle-agenda-files t]
21939 ["Occur in all agenda files" org-occur-in-agenda-files t]
21940 "--")
21941 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21943 ;;;; Documentation
21945 (defun org-require-autoloaded-modules ()
21946 (interactive)
21947 (mapc #'require
21948 '(org-agenda org-archive org-attach org-clock org-colview org-id
21949 org-table org-timer)))
21951 ;;;###autoload
21952 (defun org-reload (&optional uncompiled)
21953 "Reload all org lisp files.
21954 With prefix arg UNCOMPILED, load the uncompiled versions."
21955 (interactive "P")
21956 (require 'loadhist)
21957 (let* ((org-dir (org-find-library-dir "org"))
21958 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21959 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21960 (remove-re (format "\\`%s\\'"
21961 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21962 (feats (delete-dups
21963 (mapcar 'file-name-sans-extension
21964 (mapcar 'file-name-nondirectory
21965 (delq nil
21966 (mapcar 'feature-file
21967 features))))))
21968 (lfeat (append
21969 (sort
21970 (setq feats
21971 (delq nil (mapcar
21972 (lambda (f)
21973 (if (and (string-match feature-re f)
21974 (not (string-match remove-re f)))
21975 f nil))
21976 feats)))
21977 'string-lessp)
21978 (list "org-version" "org")))
21979 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21980 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21981 load-uncore load-misses)
21982 (setq load-misses
21983 (delq 't
21984 (mapcar (lambda (f)
21985 (or (org-load-noerror-mustsuffix (concat org-dir f))
21986 (and (string= org-dir contrib-dir)
21987 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21988 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21989 (add-to-list 'load-uncore f 'append)
21992 lfeat)))
21993 (when load-uncore
21994 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21995 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21996 (if load-misses
21997 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21998 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21999 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22001 ;;;###autoload
22002 (defun org-customize ()
22003 "Call the customize function with org as argument."
22004 (interactive)
22005 (org-load-modules-maybe)
22006 (org-require-autoloaded-modules)
22007 (customize-browse 'org))
22009 (defun org-create-customize-menu ()
22010 "Create a full customization menu for Org mode, insert it into the menu."
22011 (interactive)
22012 (org-load-modules-maybe)
22013 (org-require-autoloaded-modules)
22014 (if (fboundp 'customize-menu-create)
22015 (progn
22016 (easy-menu-change
22017 '("Org") "Customize"
22018 `(["Browse Org group" org-customize t]
22019 "--"
22020 ,(customize-menu-create 'org)
22021 ["Set" Custom-set t]
22022 ["Save" Custom-save t]
22023 ["Reset to Current" Custom-reset-current t]
22024 ["Reset to Saved" Custom-reset-saved t]
22025 ["Reset to Standard Settings" Custom-reset-standard t]))
22026 (message "\"Org\"-menu now contains full customization menu"))
22027 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22029 ;;;; Miscellaneous stuff
22031 ;;; Generally useful functions
22033 (defun org-get-at-eol (property n)
22034 "Get text property PROPERTY at the end of line less N characters."
22035 (get-text-property (- (point-at-eol) n) property))
22037 (defun org-find-text-property-in-string (prop s)
22038 "Return the first non-nil value of property PROP in string S."
22039 (or (get-text-property 0 prop s)
22040 (get-text-property (or (next-single-property-change 0 prop s) 0)
22041 prop s)))
22043 (defun org-display-warning (message)
22044 "Display the given MESSAGE as a warning."
22045 (display-warning 'org message :warning))
22047 (defun org-eval (form)
22048 "Eval FORM and return result."
22049 (condition-case error
22050 (eval form)
22051 (error (format "%%![Error: %s]" error))))
22053 (defun org-in-clocktable-p ()
22054 "Check if the cursor is in a clocktable."
22055 (let ((pos (point)) start)
22056 (save-excursion
22057 (end-of-line 1)
22058 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22059 (setq start (match-beginning 0))
22060 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22061 (>= (match-end 0) pos)
22062 start))))
22064 (defun org-in-verbatim-emphasis ()
22065 (save-match-data
22066 (and (org-in-regexp org-emph-re 2)
22067 (>= (point) (match-beginning 3))
22068 (<= (point) (match-end 4))
22069 (member (match-string 3) '("=" "~")))))
22071 (defun org-overlay-display (ovl text &optional face evap)
22072 "Make overlay OVL display TEXT with face FACE."
22073 (overlay-put ovl 'display text)
22074 (if face (overlay-put ovl 'face face))
22075 (if evap (overlay-put ovl 'evaporate t)))
22077 (defun org-overlay-before-string (ovl text &optional face evap)
22078 "Make overlay OVL display TEXT with face FACE."
22079 (if face (org-add-props text nil 'face face))
22080 (overlay-put ovl 'before-string text)
22081 (if evap (overlay-put ovl 'evaporate t)))
22083 (defun org-find-overlays (prop &optional pos delete)
22084 "Find all overlays specifying PROP at POS or point.
22085 If DELETE is non-nil, delete all those overlays."
22086 (let (found)
22087 (dolist (ov (overlays-at (or pos (point))) found)
22088 (cond ((not (overlay-get ov prop)))
22089 (delete (delete-overlay ov))
22090 (t (push ov found))))))
22092 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22093 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22094 (if (and marker (marker-buffer marker)
22095 (buffer-live-p (marker-buffer marker)))
22096 (progn
22097 (pop-to-buffer-same-window (marker-buffer marker))
22098 (when (or (> marker (point-max)) (< marker (point-min)))
22099 (widen))
22100 (goto-char marker)
22101 (org-show-context 'org-goto))
22102 (if bookmark
22103 (bookmark-jump bookmark)
22104 (error "Cannot find location"))))
22106 (defun org-quote-csv-field (s)
22107 "Quote field for inclusion in CSV material."
22108 (if (string-match "[\",]" s)
22109 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22112 (defun org-force-self-insert (N)
22113 "Needed to enforce self-insert under remapping."
22114 (interactive "p")
22115 (self-insert-command N))
22117 (defun org-string-width (s)
22118 "Compute width of string, ignoring invisible characters.
22119 This ignores character with invisibility property `org-link', and also
22120 characters with property `org-cwidth', because these will become invisible
22121 upon the next fontification round."
22122 (let (b l)
22123 (when (or (eq t buffer-invisibility-spec)
22124 (assq 'org-link buffer-invisibility-spec))
22125 (while (setq b (text-property-any 0 (length s)
22126 'invisible 'org-link s))
22127 (setq s (concat (substring s 0 b)
22128 (substring s (or (next-single-property-change
22129 b 'invisible s)
22130 (length s)))))))
22131 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22132 (setq s (concat (substring s 0 b)
22133 (substring s (or (next-single-property-change
22134 b 'org-cwidth s)
22135 (length s))))))
22136 (setq l (string-width s) b -1)
22137 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22138 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22141 (defun org-shorten-string (s maxlength)
22142 "Shorten string S so that it is no longer than MAXLENGTH characters.
22143 If the string is shorter or has length MAXLENGTH, just return the
22144 original string. If it is longer, the functions finds a space in the
22145 string, breaks this string off at that locations and adds three dots
22146 as ellipsis. Including the ellipsis, the string will not be longer
22147 than MAXLENGTH. If finding a good breaking point in the string does
22148 not work, the string is just chopped off in the middle of a word
22149 if necessary."
22150 (if (<= (length s) maxlength)
22152 (let* ((n (max (- maxlength 4) 1))
22153 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22154 (if (string-match re s)
22155 (concat (match-string 1 s) "...")
22156 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22158 (defun org-get-indentation (&optional line)
22159 "Get the indentation of the current line, interpreting tabs.
22160 When LINE is given, assume it represents a line and compute its indentation."
22161 (if line
22162 (when (string-match "^ *" (org-remove-tabs line))
22163 (match-end 0))
22164 (save-excursion
22165 (beginning-of-line 1)
22166 (skip-chars-forward " \t")
22167 (current-column))))
22169 (defun org-get-string-indentation (s)
22170 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22171 (let ((n -1) (i 0) (w tab-width) c)
22172 (catch 'exit
22173 (while (< (setq n (1+ n)) (length s))
22174 (setq c (aref s n))
22175 (cond ((= c ?\ ) (setq i (1+ i)))
22176 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22177 (t (throw 'exit t)))))
22180 (defun org-remove-tabs (s &optional width)
22181 "Replace tabulators in S with spaces.
22182 Assumes that s is a single line, starting in column 0."
22183 (setq width (or width tab-width))
22184 (while (string-match "\t" s)
22185 (setq s (replace-match
22186 (make-string
22187 (- (* width (/ (+ (match-beginning 0) width) width))
22188 (match-beginning 0)) ?\ )
22189 t t s)))
22192 (defun org-fix-indentation (line ind)
22193 "Fix indentation in LINE.
22194 IND is a cons cell with target and minimum indentation.
22195 If the current indentation in LINE is smaller than the minimum,
22196 leave it alone. If it is larger than ind, set it to the target."
22197 (let* ((l (org-remove-tabs line))
22198 (i (org-get-indentation l))
22199 (i1 (car ind)) (i2 (cdr ind)))
22200 (when (>= i i2) (setq l (substring line i2)))
22201 (if (> i1 0)
22202 (concat (make-string i1 ?\ ) l)
22203 l)))
22205 (defun org-remove-indentation (code &optional n)
22206 "Remove maximum common indentation in string CODE and return it.
22207 N may optionally be the number of columns to remove. Return CODE
22208 as-is if removal failed."
22209 (with-temp-buffer
22210 (insert code)
22211 (if (org-do-remove-indentation n) (buffer-string) code)))
22213 (defun org-do-remove-indentation (&optional n)
22214 "Remove the maximum common indentation from the buffer.
22215 When optional argument N is a positive integer, remove exactly
22216 that much characters from indentation, if possible. Return nil
22217 if it fails."
22218 (catch :exit
22219 (goto-char (point-min))
22220 ;; Find maximum common indentation, if not specified.
22221 (let ((n (or n
22222 (let ((min-ind (point-max)))
22223 (save-excursion
22224 (while (re-search-forward "^[ \t]*\\S-" nil t)
22225 (let ((ind (1- (current-column))))
22226 (if (zerop ind) (throw :exit nil)
22227 (setq min-ind (min min-ind ind))))))
22228 min-ind))))
22229 (if (zerop n) (throw :exit nil)
22230 ;; Remove exactly N indentation, but give up if not possible.
22231 (while (not (eobp))
22232 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22233 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22234 ((< ind n) (throw :exit nil))
22235 (t (indent-line-to (- ind n))))
22236 (forward-line)))
22237 ;; Signal success.
22238 t))))
22240 (defun org-fill-template (template alist)
22241 "Find each %key of ALIST in TEMPLATE and replace it."
22242 (let ((case-fold-search nil))
22243 (dolist (entry (sort (copy-sequence alist)
22244 (lambda (a b) (< (length (car a)) (length (car b))))))
22245 (setq template
22246 (replace-regexp-in-string
22247 (concat "%" (regexp-quote (car entry)))
22248 (or (cdr entry) "") template t t)))
22249 template))
22251 (defun org-base-buffer (buffer)
22252 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22253 (if (not buffer)
22254 buffer
22255 (or (buffer-base-buffer buffer)
22256 buffer)))
22258 (defun org-wrap (string &optional width lines)
22259 "Wrap string to either a number of lines, or a width in characters.
22260 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22261 that costs. If there is a word longer than WIDTH, the text is actually
22262 wrapped to the length of that word.
22263 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22264 many lines, whatever width that takes.
22265 The return value is a list of lines, without newlines at the end."
22266 (let* ((words (org-split-string string "[ \t\n]+"))
22267 (maxword (apply 'max (mapcar 'org-string-width words)))
22268 w ll)
22269 (cond (width
22270 (org-do-wrap words (max maxword width)))
22271 (lines
22272 (setq w maxword)
22273 (setq ll (org-do-wrap words maxword))
22274 (if (<= (length ll) lines)
22276 (setq ll words)
22277 (while (> (length ll) lines)
22278 (setq w (1+ w))
22279 (setq ll (org-do-wrap words w)))
22280 ll))
22281 (t (error "Cannot wrap this")))))
22283 (defun org-do-wrap (words width)
22284 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22285 (let (lines line)
22286 (while words
22287 (setq line (pop words))
22288 (while (and words (< (+ (length line) (length (car words))) width))
22289 (setq line (concat line " " (pop words))))
22290 (setq lines (push line lines)))
22291 (nreverse lines)))
22293 (defun org-split-string (string &optional separators)
22294 "Splits STRING into substrings at SEPARATORS.
22295 SEPARATORS is a regular expression.
22296 No empty strings are returned if there are matches at the beginning
22297 and end of string."
22298 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22299 (let ((start 0) notfirst list)
22300 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22301 (if (and notfirst
22302 (= start (match-beginning 0))
22303 (< start (length string)))
22304 (1+ start) start))
22305 (< (match-beginning 0) (length string)))
22306 (setq notfirst t)
22307 (or (eq (match-beginning 0) 0)
22308 (and (eq (match-beginning 0) (match-end 0))
22309 (eq (match-beginning 0) start))
22310 (push (substring string start (match-beginning 0)) list))
22311 (setq start (match-end 0)))
22312 (or (eq start (length string))
22313 (push (substring string start) list))
22314 (nreverse list)))
22316 (defun org-quote-vert (s)
22317 "Replace \"|\" with \"\\vert\"."
22318 (while (string-match "|" s)
22319 (setq s (replace-match "\\vert" t t s)))
22322 (defun org-uuidgen-p (s)
22323 "Is S an ID created by UUIDGEN?"
22324 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22326 (defun org-in-src-block-p (&optional inside)
22327 "Whether point is in a code source block.
22328 When INSIDE is non-nil, don't consider we are within a src block
22329 when point is at #+BEGIN_SRC or #+END_SRC."
22330 (let ((case-fold-search t))
22331 (or (and (eq (get-char-property (point) 'src-block) t))
22332 (and (not inside)
22333 (save-match-data
22334 (save-excursion
22335 (beginning-of-line)
22336 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22338 (defun org-context ()
22339 "Return a list of contexts of the current cursor position.
22340 If several contexts apply, all are returned.
22341 Each context entry is a list with a symbol naming the context, and
22342 two positions indicating start and end of the context. Possible
22343 contexts are:
22345 :headline anywhere in a headline
22346 :headline-stars on the leading stars in a headline
22347 :todo-keyword on a TODO keyword (including DONE) in a headline
22348 :tags on the TAGS in a headline
22349 :priority on the priority cookie in a headline
22350 :item on the first line of a plain list item
22351 :item-bullet on the bullet/number of a plain list item
22352 :checkbox on the checkbox in a plain list item
22353 :table in an Org table
22354 :table-special on a special filed in a table
22355 :table-table in a table.el table
22356 :clocktable in a clocktable
22357 :src-block in a source block
22358 :link on a hyperlink
22359 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22360 :target on a <<target>>
22361 :radio-target on a <<<radio-target>>>
22362 :latex-fragment on a LaTeX fragment
22363 :latex-preview on a LaTeX fragment with overlaid preview image
22365 This function expects the position to be visible because it uses font-lock
22366 faces as a help to recognize the following contexts: :table-special, :link,
22367 and :keyword."
22368 (let* ((f (get-text-property (point) 'face))
22369 (faces (if (listp f) f (list f)))
22370 (case-fold-search t)
22371 (p (point)) clist o)
22372 ;; First the large context
22373 (cond
22374 ((org-at-heading-p t)
22375 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22376 (when (progn
22377 (beginning-of-line 1)
22378 (looking-at org-todo-line-tags-regexp))
22379 (push (org-point-in-group p 1 :headline-stars) clist)
22380 (push (org-point-in-group p 2 :todo-keyword) clist)
22381 (push (org-point-in-group p 4 :tags) clist))
22382 (goto-char p)
22383 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22384 (when (looking-at "\\[#[A-Z0-9]\\]")
22385 (push (org-point-in-group p 0 :priority) clist)))
22387 ((org-at-item-p)
22388 (push (org-point-in-group p 2 :item-bullet) clist)
22389 (push (list :item (point-at-bol)
22390 (save-excursion (org-end-of-item) (point)))
22391 clist)
22392 (and (org-at-item-checkbox-p)
22393 (push (org-point-in-group p 0 :checkbox) clist)))
22395 ((org-at-table-p)
22396 (push (list :table (org-table-begin) (org-table-end)) clist)
22397 (when (memq 'org-formula faces)
22398 (push (list :table-special
22399 (previous-single-property-change p 'face)
22400 (next-single-property-change p 'face)) clist)))
22401 ((org-at-table-p 'any)
22402 (push (list :table-table) clist)))
22403 (goto-char p)
22405 (let ((case-fold-search t))
22406 ;; New the "medium" contexts: clocktables, source blocks
22407 (cond ((org-in-clocktable-p)
22408 (push (list :clocktable
22409 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22410 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22411 (match-beginning 1))
22412 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22413 (match-end 0))) clist))
22414 ((org-in-src-block-p)
22415 (push (list :src-block
22416 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22417 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22418 (match-beginning 1))
22419 (and (search-forward "#+END_SRC" nil t)
22420 (match-beginning 0))) clist))))
22421 (goto-char p)
22423 ;; Now the small context
22424 (cond
22425 ((org-at-timestamp-p)
22426 (push (org-point-in-group p 0 :timestamp) clist))
22427 ((memq 'org-link faces)
22428 (push (list :link
22429 (previous-single-property-change p 'face)
22430 (next-single-property-change p 'face)) clist))
22431 ((memq 'org-special-keyword faces)
22432 (push (list :keyword
22433 (previous-single-property-change p 'face)
22434 (next-single-property-change p 'face)) clist))
22435 ((org-at-target-p)
22436 (push (org-point-in-group p 0 :target) clist)
22437 (goto-char (1- (match-beginning 0)))
22438 (when (looking-at org-radio-target-regexp)
22439 (push (org-point-in-group p 0 :radio-target) clist))
22440 (goto-char p))
22441 ((setq o (cl-some
22442 (lambda (o)
22443 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22445 (overlays-at (point))))
22446 (push (list :latex-fragment
22447 (overlay-start o) (overlay-end o)) clist)
22448 (push (list :latex-preview
22449 (overlay-start o) (overlay-end o)) clist))
22450 ((org-inside-LaTeX-fragment-p)
22451 ;; FIXME: positions wrong.
22452 (push (list :latex-fragment (point) (point)) clist)))
22454 (setq clist (nreverse (delq nil clist)))
22455 clist))
22457 (defun org-in-regexp (regexp &optional nlines visually)
22458 "Check if point is inside a match of REGEXP.
22460 Normally only the current line is checked, but you can include
22461 NLINES extra lines around point into the search. If VISUALLY is
22462 set, require that the cursor is not after the match but really
22463 on, so that the block visually is on the match.
22465 Return nil or a cons cell (BEG . END) where BEG and END are,
22466 respectively, the positions at the beginning and the end of the
22467 match."
22468 (catch :exit
22469 (let ((pos (point))
22470 (eol (line-end-position (if nlines (1+ nlines) 1))))
22471 (save-excursion
22472 (beginning-of-line (- 1 (or nlines 0)))
22473 (while (and (re-search-forward regexp eol t)
22474 (<= (match-beginning 0) pos))
22475 (let ((end (match-end 0)))
22476 (when (or (> end pos) (and (= end pos) (not visually)))
22477 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22479 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22480 "Non-nil when point is between matches of START-RE and END-RE.
22482 Also return a non-nil value when point is on one of the matches.
22484 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22485 buffer positions. Default values are the positions of headlines
22486 surrounding the point.
22488 The functions returns a cons cell whose car (resp. cdr) is the
22489 position before START-RE (resp. after END-RE)."
22490 (save-match-data
22491 (let ((pos (point))
22492 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22493 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22494 beg end)
22495 (save-excursion
22496 ;; Point is on a block when on START-RE or if START-RE can be
22497 ;; found before it...
22498 (and (or (org-in-regexp start-re)
22499 (re-search-backward start-re limit-up t))
22500 (setq beg (match-beginning 0))
22501 ;; ... and END-RE after it...
22502 (goto-char (match-end 0))
22503 (re-search-forward end-re limit-down t)
22504 (> (setq end (match-end 0)) pos)
22505 ;; ... without another START-RE in-between.
22506 (goto-char (match-beginning 0))
22507 (not (re-search-backward start-re (1+ beg) t))
22508 ;; Return value.
22509 (cons beg end))))))
22511 (defun org-in-block-p (names)
22512 "Non-nil when point belongs to a block whose name belongs to NAMES.
22514 NAMES is a list of strings containing names of blocks.
22516 Return first block name matched, or nil. Beware that in case of
22517 nested blocks, the returned name may not belong to the closest
22518 block from point."
22519 (save-match-data
22520 (catch 'exit
22521 (let ((case-fold-search t)
22522 (lim-up (save-excursion (outline-previous-heading)))
22523 (lim-down (save-excursion (outline-next-heading))))
22524 (dolist (name names)
22525 (let ((n (regexp-quote name)))
22526 (when (org-between-regexps-p
22527 (concat "^[ \t]*#\\+begin_" n)
22528 (concat "^[ \t]*#\\+end_" n)
22529 lim-up lim-down)
22530 (throw 'exit n)))))
22531 nil)))
22533 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22534 "Call `multi-occur' with buffers for all agenda files."
22535 (interactive "sOrg-files matching: ")
22536 (let* ((files (org-agenda-files))
22537 (tnames (mapcar #'file-truename files))
22538 (extra org-agenda-text-search-extra-files))
22539 (when (eq (car extra) 'agenda-archives)
22540 (setq extra (cdr extra))
22541 (setq files (org-add-archive-files files)))
22542 (dolist (f extra)
22543 (unless (member (file-truename f) tnames)
22544 (unless (member f files) (setq files (append files (list f))))
22545 (setq tnames (append tnames (list (file-truename f))))))
22546 (multi-occur
22547 (mapcar (lambda (x)
22548 (with-current-buffer
22549 ;; FIXME: Why not just (find-file-noselect x)?
22550 ;; Is it to avoid the "revert buffer" prompt?
22551 (or (get-file-buffer x) (find-file-noselect x))
22552 (widen)
22553 (current-buffer)))
22554 files)
22555 regexp)))
22557 (add-hook 'occur-mode-find-occurrence-hook
22558 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22560 (defun org-occur-link-in-agenda-files ()
22561 "Create a link and search for it in the agendas.
22562 The link is not stored in `org-stored-links', it is just created
22563 for the search purpose."
22564 (interactive)
22565 (let ((link (condition-case nil
22566 (org-store-link nil)
22567 (error "Unable to create a link to here"))))
22568 (org-occur-in-agenda-files (regexp-quote link))))
22570 (defun org-reverse-string (string)
22571 "Return the reverse of STRING."
22572 (apply 'string (reverse (string-to-list string))))
22574 ;; defsubst org-uniquify must be defined before first use
22576 (defun org-uniquify-alist (alist)
22577 "Merge elements of ALIST with the same key.
22579 For example, in this alist:
22581 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22582 => \\='((a 1 3) (b 2))
22584 merge (a 1) and (a 3) into (a 1 3).
22586 The function returns the new ALIST."
22587 (let (rtn)
22588 (dolist (e alist rtn)
22589 (let (n)
22590 (if (not (assoc (car e) rtn))
22591 (push e rtn)
22592 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22593 (setq rtn (assq-delete-all (car e) rtn))
22594 (push n rtn))))))
22596 (defun org-delete-all (elts list)
22597 "Remove all elements in ELTS from LIST.
22598 Comparison is done with `equal'. It is a destructive operation
22599 that may remove elements by altering the list structure."
22600 (while elts
22601 (setq list (delete (pop elts) list)))
22602 list)
22604 (defun org-back-over-empty-lines ()
22605 "Move backwards over whitespace, to the beginning of the first empty line.
22606 Returns the number of empty lines passed."
22607 (let ((pos (point)))
22608 (if (cdr (assq 'heading org-blank-before-new-entry))
22609 (skip-chars-backward " \t\n\r")
22610 (unless (eobp)
22611 (forward-line -1)))
22612 (beginning-of-line 2)
22613 (goto-char (min (point) pos))
22614 (count-lines (point) pos)))
22616 (defun org-skip-whitespace ()
22617 (skip-chars-forward " \t\n\r"))
22619 (defun org-point-in-group (point group &optional context)
22620 "Check if POINT is in match-group GROUP.
22621 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22622 match. If the match group does not exist or point is not inside it,
22623 return nil."
22624 (and (match-beginning group)
22625 (>= point (match-beginning group))
22626 (<= point (match-end group))
22627 (if context
22628 (list context (match-beginning group) (match-end group))
22629 t)))
22631 (defun org-switch-to-buffer-other-window (&rest args)
22632 "Switch to buffer in a second window on the current frame.
22633 In particular, do not allow pop-up frames.
22634 Returns the newly created buffer."
22635 (org-no-popups
22636 (apply 'switch-to-buffer-other-window args)))
22638 (defun org-combine-plists (&rest plists)
22639 "Create a single property list from all plists in PLISTS.
22640 The process starts by copying the first list, and then setting properties
22641 from the other lists. Settings in the last list are the most significant
22642 ones and overrule settings in the other lists."
22643 (let ((rtn (copy-sequence (pop plists)))
22644 p v ls)
22645 (while plists
22646 (setq ls (pop plists))
22647 (while ls
22648 (setq p (pop ls) v (pop ls))
22649 (setq rtn (plist-put rtn p v))))
22650 rtn))
22652 (defun org-replace-escapes (string table)
22653 "Replace %-escapes in STRING with values in TABLE.
22654 TABLE is an association list with keys like \"%a\" and string values.
22655 The sequences in STRING may contain normal field width and padding information,
22656 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22657 so values can contain further %-escapes if they are define later in TABLE."
22658 (let ((tbl (copy-alist table))
22659 (case-fold-search nil)
22660 (pchg 0)
22661 re rpl)
22662 (dolist (e tbl)
22663 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22664 (when (and (cdr e) (string-match re (cdr e)))
22665 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22666 (safe "SREF"))
22667 (add-text-properties 0 3 (list 'sref sref) safe)
22668 (setcdr e (replace-match safe t t (cdr e)))))
22669 (while (string-match re string)
22670 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22671 (cdr e)))
22672 (setq string (replace-match rpl t t string))))
22673 (while (setq pchg (next-property-change pchg string))
22674 (let ((sref (get-text-property pchg 'sref string)))
22675 (when (and sref (string-match "SREF" string pchg))
22676 (setq string (replace-match sref t t string)))))
22677 string))
22679 (defun org-find-base-buffer-visiting (file)
22680 "Like `find-buffer-visiting' but always return the base buffer and
22681 not an indirect buffer."
22682 (let ((buf (or (get-file-buffer file)
22683 (find-buffer-visiting file))))
22684 (if buf
22685 (or (buffer-base-buffer buf) buf)
22686 nil)))
22688 ;;; TODO: Only called once, from ox-odt which should probably use
22689 ;;; org-export-inline-image-p or something.
22690 (defun org-file-image-p (file)
22691 "Return non-nil if FILE is an image."
22692 (save-match-data
22693 (string-match (image-file-name-regexp) file)))
22695 (defun org-get-cursor-date (&optional with-time)
22696 "Return the date at cursor in as a time.
22697 This works in the calendar and in the agenda, anywhere else it just
22698 returns the current time.
22699 If WITH-TIME is non-nil, returns the time of the event at point (in
22700 the agenda) or the current time of the day."
22701 (let (date day defd tp hod mod)
22702 (when with-time
22703 (setq tp (get-text-property (point) 'time))
22704 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22705 (setq hod (string-to-number (match-string 1 tp))
22706 mod (string-to-number (match-string 2 tp))))
22707 (or tp (let ((now (decode-time)))
22708 (setq hod (nth 2 now)
22709 mod (nth 1 now)))))
22710 (cond
22711 ((eq major-mode 'calendar-mode)
22712 (setq date (calendar-cursor-to-date)
22713 defd (encode-time 0 (or mod 0) (or hod 0)
22714 (nth 1 date) (nth 0 date) (nth 2 date))))
22715 ((eq major-mode 'org-agenda-mode)
22716 (setq day (get-text-property (point) 'day))
22717 (when day
22718 (setq date (calendar-gregorian-from-absolute day)
22719 defd (encode-time 0 (or mod 0) (or hod 0)
22720 (nth 1 date) (nth 0 date) (nth 2 date))))))
22721 (or defd (current-time))))
22723 (defun org-mark-subtree (&optional up)
22724 "Mark the current subtree.
22725 This puts point at the start of the current subtree, and mark at
22726 the end. If a numeric prefix UP is given, move up into the
22727 hierarchy of headlines by UP levels before marking the subtree."
22728 (interactive "P")
22729 (org-with-limited-levels
22730 (cond ((org-at-heading-p) (beginning-of-line))
22731 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22732 (t (outline-previous-visible-heading 1))))
22733 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22734 (if (called-interactively-p 'any)
22735 (call-interactively 'org-mark-element)
22736 (org-mark-element)))
22738 (defun org-file-newer-than-p (file time)
22739 "Non-nil if FILE is newer than TIME.
22740 FILE is a filename, as a string, TIME is a list of integers, as
22741 returned by, e.g., `current-time'."
22742 (and (file-exists-p file)
22743 ;; Only compare times up to whole seconds as some file-systems
22744 ;; (e.g. HFS+) do not retain any finer granularity. As
22745 ;; a consequence, make sure we return non-nil when the two
22746 ;; times are equal.
22747 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22748 (cl-subseq time 0 2)))))
22750 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22751 "Compile a SOURCE file using PROCESS.
22753 PROCESS is either a function or a list of shell commands, as
22754 strings. EXT is a file extension, without the leading dot, as
22755 a string. It is used to check if the process actually succeeded.
22757 PROCESS must create a file with the same base name and directory
22758 as SOURCE, but ending with EXT. The function then returns its
22759 filename. Otherwise, it raises an error. The error message can
22760 then be refined by providing string ERR-MSG, which is appended to
22761 the standard message.
22763 If PROCESS is a function, it is called with a single argument:
22764 the SOURCE file.
22766 If it is a list of commands, each of them is called using
22767 `shell-command'. By default, in each command, %b, %f, %F and %o
22768 are replaced with, respectively, SOURCE base name, name, full
22769 name and directory. It is possible, however, to use more
22770 place-holders by specifying them in optional argument SPEC, as an
22771 alist following the pattern (CHARACTER . REPLACEMENT-STRING).
22773 When PROCESS is a list of commands, optional argument LOG-BUF can
22774 be set to a buffer or a buffer name. `shell-command' then uses
22775 it for output."
22776 (let* ((base-name (file-name-base source))
22777 (full-name (file-truename source))
22778 (out-dir (file-name-directory source))
22779 (time (current-time))
22780 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22781 (save-window-excursion
22782 (pcase process
22783 ((pred functionp) (funcall process (shell-quote-argument source)))
22784 ((pred consp)
22785 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22786 (spec (append spec
22787 `((?b . ,(shell-quote-argument base-name))
22788 (?f . ,(shell-quote-argument source))
22789 (?F . ,(shell-quote-argument full-name))
22790 (?o . ,(shell-quote-argument out-dir))))))
22791 (dolist (command process)
22792 (shell-command (format-spec command spec) log-buf))))
22793 (_ (error "No valid command to process %S%s" source err-msg))))
22794 ;; Check for process failure. Output file is expected to be
22795 ;; located in the same directory as SOURCE.
22796 (let ((output (expand-file-name (concat base-name "." ext) out-dir)))
22797 (unless (org-file-newer-than-p output time)
22798 (error (format "File %S wasn't produced%s" output err-msg)))
22799 output)))
22801 ;;; Indentation
22803 (defun org--get-expected-indentation (element contentsp)
22804 "Expected indentation column for current line, according to ELEMENT.
22805 ELEMENT is an element containing point. CONTENTSP is non-nil
22806 when indentation is to be computed according to contents of
22807 ELEMENT."
22808 (let ((type (org-element-type element))
22809 (start (org-element-property :begin element))
22810 (post-affiliated (org-element-property :post-affiliated element)))
22811 (org-with-wide-buffer
22812 (cond
22813 (contentsp
22814 (cl-case type
22815 ((diary-sexp footnote-definition) 0)
22816 ((headline inlinetask nil)
22817 (if (not org-adapt-indentation) 0
22818 (let ((level (org-current-level)))
22819 (if level (1+ level) 0))))
22820 ((item plain-list) (org-list-item-body-column post-affiliated))
22822 (goto-char start)
22823 (org-get-indentation))))
22824 ((memq type '(headline inlinetask nil))
22825 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22826 (org--get-expected-indentation element t)
22828 ((memq type '(diary-sexp footnote-definition)) 0)
22829 ;; First paragraph of a footnote definition or an item.
22830 ;; Indent like parent.
22831 ((< (line-beginning-position) start)
22832 (org--get-expected-indentation
22833 (org-element-property :parent element) t))
22834 ;; At first line: indent according to previous sibling, if any,
22835 ;; ignoring footnote definitions and inline tasks, or parent's
22836 ;; contents.
22837 ((= (line-beginning-position) start)
22838 (catch 'exit
22839 (while t
22840 (if (= (point-min) start) (throw 'exit 0)
22841 (goto-char (1- start))
22842 (let* ((previous (org-element-at-point))
22843 (parent previous))
22844 (while (and parent (<= (org-element-property :end parent) start))
22845 (setq previous parent
22846 parent (org-element-property :parent parent)))
22847 (cond
22848 ((not previous) (throw 'exit 0))
22849 ((> (org-element-property :end previous) start)
22850 (throw 'exit (org--get-expected-indentation previous t)))
22851 ((memq (org-element-type previous)
22852 '(footnote-definition inlinetask))
22853 (setq start (org-element-property :begin previous)))
22854 (t (goto-char (org-element-property :begin previous))
22855 (throw 'exit
22856 (if (bolp) (org-get-indentation)
22857 ;; At first paragraph in an item or
22858 ;; a footnote definition.
22859 (org--get-expected-indentation
22860 (org-element-property :parent previous) t))))))))))
22861 ;; Otherwise, move to the first non-blank line above.
22863 (beginning-of-line)
22864 (let ((pos (point)))
22865 (skip-chars-backward " \r\t\n")
22866 (cond
22867 ;; Two blank lines end a footnote definition or a plain
22868 ;; list. When we indent an empty line after them, the
22869 ;; containing list or footnote definition is over, so it
22870 ;; qualifies as a previous sibling. Therefore, we indent
22871 ;; like its first line.
22872 ((and (memq type '(footnote-definition plain-list))
22873 (> (count-lines (point) pos) 2))
22874 (goto-char start)
22875 (org-get-indentation))
22876 ;; Line above is the first one of a paragraph at the
22877 ;; beginning of an item or a footnote definition. Indent
22878 ;; like parent.
22879 ((< (line-beginning-position) start)
22880 (org--get-expected-indentation
22881 (org-element-property :parent element) t))
22882 ;; Line above is the beginning of an element, i.e., point
22883 ;; was originally on the blank lines between element's start
22884 ;; and contents.
22885 ((= (line-beginning-position) post-affiliated)
22886 (org--get-expected-indentation element t))
22887 ;; POS is after contents in a greater element. Indent like
22888 ;; the beginning of the element.
22890 ;; As a special case, if point is at the end of a footnote
22891 ;; definition or an item, indent like the very last element
22892 ;; within. If that last element is an item, indent like its
22893 ;; contents.
22894 ((and (not (eq type 'paragraph))
22895 (let ((cend (org-element-property :contents-end element)))
22896 (and cend (<= cend pos))))
22897 (if (memq type '(footnote-definition item plain-list))
22898 (let ((last (org-element-at-point)))
22899 (org--get-expected-indentation
22900 last (eq (org-element-type last) 'item)))
22901 (goto-char start)
22902 (org-get-indentation)))
22903 ;; In any other case, indent like the current line.
22904 (t (org-get-indentation)))))))))
22906 (defun org--align-node-property ()
22907 "Align node property at point.
22908 Alignment is done according to `org-property-format', which see."
22909 (when (save-excursion
22910 (beginning-of-line)
22911 (looking-at org-property-re))
22912 (replace-match
22913 (concat (match-string 4)
22914 (org-trim
22915 (format org-property-format (match-string 1) (match-string 3))))
22916 t t)))
22918 (defun org-indent-line ()
22919 "Indent line depending on context.
22921 Indentation is done according to the following rules:
22923 - Footnote definitions, diary sexps, headlines and inline tasks
22924 have to start at column 0.
22926 - On the very first line of an element, consider, in order, the
22927 next rules until one matches:
22929 1. If there's a sibling element before, ignoring footnote
22930 definitions and inline tasks, indent like its first line.
22932 2. If element has a parent, indent like its contents. More
22933 precisely, if parent is an item, indent after the
22934 description part, if any, or the bullet (see
22935 `org-list-description-max-indent'). Else, indent like
22936 parent's first line.
22938 3. Otherwise, indent relatively to current level, if
22939 `org-adapt-indentation' is non-nil, or to left margin.
22941 - On a blank line at the end of an element, indent according to
22942 the type of the element. More precisely
22944 1. If element is a plain list, an item, or a footnote
22945 definition, indent like the very last element within.
22947 2. If element is a paragraph, indent like its last non blank
22948 line.
22950 3. Otherwise, indent like its very first line.
22952 - In the code part of a source block, use language major mode
22953 to indent current line if `org-src-tab-acts-natively' is
22954 non-nil. If it is nil, do nothing.
22956 - Otherwise, indent like the first non-blank line above.
22958 The function doesn't indent an item as it could break the whole
22959 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22960 `\\[org-shiftmetaright]'.
22962 Also align node properties according to `org-property-format'."
22963 (interactive)
22964 (cond
22965 (orgstruct-is-++
22966 (let ((indent-line-function
22967 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22968 (indent-according-to-mode)))
22969 ((org-at-heading-p) 'noindent)
22971 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22972 (type (org-element-type element)))
22973 (cond ((and (memq type '(plain-list item))
22974 (= (line-beginning-position)
22975 (org-element-property :post-affiliated element)))
22976 'noindent)
22977 ((and (eq type 'src-block)
22978 org-src-tab-acts-natively
22979 (> (line-beginning-position)
22980 (org-element-property :post-affiliated element))
22981 (< (line-beginning-position)
22982 (org-with-wide-buffer
22983 (goto-char (org-element-property :end element))
22984 (skip-chars-backward " \r\t\n")
22985 (line-beginning-position))))
22986 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22988 (let ((column (org--get-expected-indentation element nil)))
22989 ;; Preserve current column.
22990 (if (<= (current-column) (current-indentation))
22991 (indent-line-to column)
22992 (save-excursion (indent-line-to column))))
22993 ;; Align node property. Also preserve current column.
22994 (when (eq type 'node-property)
22995 (let ((column (current-column)))
22996 (org--align-node-property)
22997 (org-move-to-column column)))))))))
22999 (defun org-indent-region (start end)
23000 "Indent each non-blank line in the region.
23001 Called from a program, START and END specify the region to
23002 indent. The function will not indent contents of example blocks,
23003 verse blocks and export blocks as leading white spaces are
23004 assumed to be significant there."
23005 (interactive "r")
23006 (save-excursion
23007 (goto-char start)
23008 (skip-chars-forward " \r\t\n")
23009 (unless (eobp) (beginning-of-line))
23010 (let ((indent-to
23011 (lambda (ind pos)
23012 ;; Set IND as indentation for all lines between point and
23013 ;; POS. Blank lines are ignored. Leave point after POS
23014 ;; once done.
23015 (let ((limit (copy-marker pos)))
23016 (while (< (point) limit)
23017 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
23018 (forward-line))
23019 (set-marker limit nil))))
23020 (end (copy-marker end)))
23021 (while (< (point) end)
23022 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23023 (let* ((element (org-element-at-point))
23024 (type (org-element-type element))
23025 (element-end (copy-marker (org-element-property :end element)))
23026 (ind (org--get-expected-indentation element nil)))
23027 (cond
23028 ((or (memq type '(paragraph table table-row))
23029 (not (or (org-element-property :contents-begin element)
23030 (memq type
23031 '(example-block export-block src-block)))))
23032 ;; Elements here are indented as a single block. Also
23033 ;; align node properties.
23034 (when (eq type 'node-property)
23035 (org--align-node-property)
23036 (beginning-of-line))
23037 (funcall indent-to ind (min element-end end)))
23039 ;; Elements in this category consist of three parts:
23040 ;; before the contents, the contents, and after the
23041 ;; contents. The contents are treated specially,
23042 ;; according to the element type, or not indented at
23043 ;; all. Other parts are indented as a single block.
23044 (let* ((post (copy-marker
23045 (org-element-property :post-affiliated element)))
23046 (cbeg
23047 (copy-marker
23048 (cond
23049 ((not (org-element-property :contents-begin element))
23050 ;; Fake contents for source blocks.
23051 (org-with-wide-buffer
23052 (goto-char post)
23053 (forward-line)
23054 (point)))
23055 ((memq type '(footnote-definition item plain-list))
23056 ;; Contents in these elements could start on
23057 ;; the same line as the beginning of the
23058 ;; element. Make sure we start indenting
23059 ;; from the second line.
23060 (org-with-wide-buffer
23061 (goto-char post)
23062 (end-of-line)
23063 (skip-chars-forward " \r\t\n")
23064 (if (eobp) (point) (line-beginning-position))))
23065 (t (org-element-property :contents-begin element)))))
23066 (cend (copy-marker
23067 (or (org-element-property :contents-end element)
23068 ;; Fake contents for source blocks.
23069 (org-with-wide-buffer
23070 (goto-char element-end)
23071 (skip-chars-backward " \r\t\n")
23072 (line-beginning-position)))
23073 t)))
23074 ;; Do not change items indentation individually as it
23075 ;; might break the list as a whole. On the other
23076 ;; hand, when at a plain list, indent it as a whole.
23077 (cond ((eq type 'plain-list)
23078 (let ((offset (- ind (org-get-indentation))))
23079 (unless (zerop offset)
23080 (indent-rigidly (org-element-property :begin element)
23081 (org-element-property :end element)
23082 offset))
23083 (goto-char cbeg)))
23084 ((eq type 'item) (goto-char cbeg))
23085 (t (funcall indent-to ind (min cbeg end))))
23086 (when (< (point) end)
23087 (cl-case type
23088 ((example-block export-block verse-block))
23089 (src-block
23090 ;; In a source block, indent source code
23091 ;; according to language major mode, but only if
23092 ;; `org-src-tab-acts-natively' is non-nil.
23093 (when (and (< (point) end) org-src-tab-acts-natively)
23094 (ignore-errors
23095 (org-babel-do-in-edit-buffer
23096 (indent-region (point-min) (point-max))))))
23097 (t (org-indent-region (point) (min cend end))))
23098 (goto-char (min cend end))
23099 (when (< (point) end)
23100 (funcall indent-to ind (min element-end end))))
23101 (set-marker post nil)
23102 (set-marker cbeg nil)
23103 (set-marker cend nil))))
23104 (set-marker element-end nil))))
23105 (set-marker end nil))))
23107 (defun org-indent-drawer ()
23108 "Indent the drawer at point."
23109 (interactive)
23110 (unless (save-excursion
23111 (beginning-of-line)
23112 (looking-at-p org-drawer-regexp))
23113 (user-error "Not at a drawer"))
23114 (let ((element (org-element-at-point)))
23115 (unless (memq (org-element-type element) '(drawer property-drawer))
23116 (user-error "Not at a drawer"))
23117 (org-with-wide-buffer
23118 (org-indent-region (org-element-property :begin element)
23119 (org-element-property :end element))))
23120 (message "Drawer at point indented"))
23122 (defun org-indent-block ()
23123 "Indent the block at point."
23124 (interactive)
23125 (unless (save-excursion
23126 (beginning-of-line)
23127 (let ((case-fold-search t))
23128 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23129 (user-error "Not at a block"))
23130 (let ((element (org-element-at-point)))
23131 (unless (memq (org-element-type element)
23132 '(comment-block center-block dynamic-block example-block
23133 export-block quote-block special-block
23134 src-block verse-block))
23135 (user-error "Not at a block"))
23136 (org-with-wide-buffer
23137 (org-indent-region (org-element-property :begin element)
23138 (org-element-property :end element))))
23139 (message "Block at point indented"))
23142 ;;; Filling
23144 ;; We use our own fill-paragraph and auto-fill functions.
23146 ;; `org-fill-paragraph' relies on adaptive filling and context
23147 ;; checking. Appropriate `fill-prefix' is computed with
23148 ;; `org-adaptive-fill-function'.
23150 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23151 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23152 ;; `org-adaptive-fill-function' value. Internally,
23153 ;; `org-comment-line-break-function' breaks the line.
23155 ;; `org-setup-filling' installs filling and auto-filling related
23156 ;; variables during `org-mode' initialization.
23158 (defvar org-element-paragraph-separate) ; org-element.el
23159 (defun org-setup-filling ()
23160 (require 'org-element)
23161 ;; Prevent auto-fill from inserting unwanted new items.
23162 (when (boundp 'fill-nobreak-predicate)
23163 (setq-local
23164 fill-nobreak-predicate
23165 (org-uniquify
23166 (append fill-nobreak-predicate
23167 '(org-fill-line-break-nobreak-p
23168 org-fill-paragraph-with-timestamp-nobreak-p)))))
23169 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23170 (setq-local paragraph-start paragraph-ending)
23171 (setq-local paragraph-separate paragraph-ending))
23172 (setq-local fill-paragraph-function 'org-fill-paragraph)
23173 (setq-local auto-fill-inhibit-regexp nil)
23174 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23175 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23176 (setq-local comment-line-break-function 'org-comment-line-break-function))
23178 (defun org-fill-line-break-nobreak-p ()
23179 "Non-nil when a new line at point would create an Org line break."
23180 (save-excursion
23181 (skip-chars-backward "[ \t]")
23182 (skip-chars-backward "\\\\")
23183 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23185 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23186 "Non-nil when a new line at point would split a timestamp."
23187 (and (org-at-timestamp-p t)
23188 (not (looking-at org-ts-regexp-both))))
23190 (declare-function message-in-body-p "message" ())
23191 (defvar orgtbl-line-start-regexp) ; From org-table.el
23192 (defun org-adaptive-fill-function ()
23193 "Compute a fill prefix for the current line.
23194 Return fill prefix, as a string, or nil if current line isn't
23195 meant to be filled. For convenience, if `adaptive-fill-regexp'
23196 matches in paragraphs or comments, use it."
23197 (catch 'exit
23198 (when (derived-mode-p 'message-mode)
23199 (save-excursion
23200 (beginning-of-line)
23201 (cond ((not (message-in-body-p)) (throw 'exit nil))
23202 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23203 ((looking-at message-cite-prefix-regexp)
23204 (throw 'exit (match-string-no-properties 0)))
23205 ((looking-at org-outline-regexp)
23206 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23207 (org-with-wide-buffer
23208 (unless (org-at-heading-p)
23209 (let* ((p (line-beginning-position))
23210 (element (save-excursion
23211 (beginning-of-line)
23212 (org-element-at-point)))
23213 (type (org-element-type element))
23214 (post-affiliated (org-element-property :post-affiliated element)))
23215 (unless (< p post-affiliated)
23216 (cl-case type
23217 (comment
23218 (save-excursion
23219 (beginning-of-line)
23220 (looking-at "[ \t]*")
23221 (concat (match-string 0) "# ")))
23222 (footnote-definition "")
23223 ((item plain-list)
23224 (make-string (org-list-item-body-column post-affiliated) ?\s))
23225 (paragraph
23226 ;; Fill prefix is usually the same as the current line,
23227 ;; unless the paragraph is at the beginning of an item.
23228 (let ((parent (org-element-property :parent element)))
23229 (save-excursion
23230 (beginning-of-line)
23231 (cond ((eq (org-element-type parent) 'item)
23232 (make-string (org-list-item-body-column
23233 (org-element-property :begin parent))
23234 ?\s))
23235 ((and adaptive-fill-regexp
23236 ;; Locally disable
23237 ;; `adaptive-fill-function' to let
23238 ;; `fill-context-prefix' handle
23239 ;; `adaptive-fill-regexp' variable.
23240 (let (adaptive-fill-function)
23241 (fill-context-prefix
23242 post-affiliated
23243 (org-element-property :end element)))))
23244 ((looking-at "[ \t]+") (match-string 0))
23245 (t "")))))
23246 (comment-block
23247 ;; Only fill contents if P is within block boundaries.
23248 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23249 (forward-line)
23250 (point)))
23251 (cend (save-excursion
23252 (goto-char (org-element-property :end element))
23253 (skip-chars-backward " \r\t\n")
23254 (line-beginning-position))))
23255 (when (and (>= p cbeg) (< p cend))
23256 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23257 (match-string 0)
23258 "")))))))))))
23260 (declare-function message-goto-body "message" ())
23261 (defvar message-cite-prefix-regexp) ; From message.el
23262 (defun org-fill-paragraph (&optional justify)
23263 "Fill element at point, when applicable.
23265 This function only applies to comment blocks, comments, example
23266 blocks and paragraphs. Also, as a special case, re-align table
23267 when point is at one.
23269 If JUSTIFY is non-nil (interactively, with prefix argument),
23270 justify as well. If `sentence-end-double-space' is non-nil, then
23271 period followed by one space does not end a sentence, so don't
23272 break a line there. The variable `fill-column' controls the
23273 width for filling.
23275 For convenience, when point is at a plain list, an item or
23276 a footnote definition, try to fill the first paragraph within."
23277 (interactive)
23278 (if (and (derived-mode-p 'message-mode)
23279 (or (not (message-in-body-p))
23280 (save-excursion (move-beginning-of-line 1)
23281 (looking-at message-cite-prefix-regexp))))
23282 ;; First ensure filling is correct in message-mode.
23283 (let ((fill-paragraph-function
23284 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23285 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23286 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23287 (paragraph-separate
23288 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23289 (fill-paragraph nil))
23290 (with-syntax-table org-mode-transpose-word-syntax-table
23291 ;; Move to end of line in order to get the first paragraph
23292 ;; within a plain list or a footnote definition.
23293 (let ((element (save-excursion
23294 (end-of-line)
23295 (or (ignore-errors (org-element-at-point))
23296 (user-error "An element cannot be parsed line %d"
23297 (line-number-at-pos (point)))))))
23298 ;; First check if point is in a blank line at the beginning of
23299 ;; the buffer. In that case, ignore filling.
23300 (cl-case (org-element-type element)
23301 ;; Use major mode filling function is src blocks.
23302 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23303 ;; Align Org tables, leave table.el tables as-is.
23304 (table-row (org-table-align) t)
23305 (table
23306 (when (eq (org-element-property :type element) 'org)
23307 (save-excursion
23308 (goto-char (org-element-property :post-affiliated element))
23309 (org-table-align)))
23311 (paragraph
23312 ;; Paragraphs may contain `line-break' type objects.
23313 (let ((beg (max (point-min)
23314 (org-element-property :contents-begin element)))
23315 (end (min (point-max)
23316 (org-element-property :contents-end element))))
23317 ;; Do nothing if point is at an affiliated keyword.
23318 (if (< (line-end-position) beg) t
23319 (when (derived-mode-p 'message-mode)
23320 ;; In `message-mode', do not fill following citation
23321 ;; in current paragraph nor text before message body.
23322 (let ((body-start (save-excursion (message-goto-body))))
23323 (when body-start (setq beg (max body-start beg))))
23324 (when (save-excursion
23325 (re-search-forward
23326 (concat "^" message-cite-prefix-regexp) end t))
23327 (setq end (match-beginning 0))))
23328 ;; Fill paragraph, taking line breaks into account.
23329 (save-excursion
23330 (goto-char beg)
23331 (let ((cuts (list beg)))
23332 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23333 (when (eq 'line-break
23334 (org-element-type
23335 (save-excursion (backward-char)
23336 (org-element-context))))
23337 (push (point) cuts)))
23338 (dolist (c (delq end cuts))
23339 (fill-region-as-paragraph c end justify)
23340 (setq end c))))
23341 t)))
23342 ;; Contents of `comment-block' type elements should be
23343 ;; filled as plain text, but only if point is within block
23344 ;; markers.
23345 (comment-block
23346 (let* ((case-fold-search t)
23347 (beg (save-excursion
23348 (goto-char (org-element-property :begin element))
23349 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23350 (forward-line)
23351 (point)))
23352 (end (save-excursion
23353 (goto-char (org-element-property :end element))
23354 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23355 (line-beginning-position))))
23356 (if (or (< (point) beg) (> (point) end)) t
23357 (fill-region-as-paragraph
23358 (save-excursion (end-of-line)
23359 (re-search-backward "^[ \t]*$" beg 'move)
23360 (line-beginning-position))
23361 (save-excursion (beginning-of-line)
23362 (re-search-forward "^[ \t]*$" end 'move)
23363 (line-beginning-position))
23364 justify))))
23365 ;; Fill comments.
23366 (comment
23367 (let ((begin (org-element-property :post-affiliated element))
23368 (end (org-element-property :end element)))
23369 (when (and (>= (point) begin) (<= (point) end))
23370 (let ((begin (save-excursion
23371 (end-of-line)
23372 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23373 (progn (forward-line) (point))
23374 begin)))
23375 (end (save-excursion
23376 (end-of-line)
23377 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23378 (1- (line-beginning-position))
23379 (skip-chars-backward " \r\t\n")
23380 (line-end-position)))))
23381 ;; Do not fill comments when at a blank line.
23382 (when (> end begin)
23383 (let ((fill-prefix
23384 (save-excursion
23385 (beginning-of-line)
23386 (looking-at "[ \t]*#")
23387 (let ((comment-prefix (match-string 0)))
23388 (goto-char (match-end 0))
23389 (if (looking-at adaptive-fill-regexp)
23390 (concat comment-prefix (match-string 0))
23391 (concat comment-prefix " "))))))
23392 (save-excursion
23393 (fill-region-as-paragraph begin end justify))))))
23395 ;; Ignore every other element.
23396 (otherwise t))))))
23398 (defun org-auto-fill-function ()
23399 "Auto-fill function."
23400 ;; Check if auto-filling is meaningful.
23401 (let ((fc (current-fill-column)))
23402 (when (and fc (> (current-column) fc))
23403 (let* ((fill-prefix (org-adaptive-fill-function))
23404 ;; Enforce empty fill prefix, if required. Otherwise, it
23405 ;; will be computed again.
23406 (adaptive-fill-mode (not (equal fill-prefix ""))))
23407 (when fill-prefix (do-auto-fill))))))
23409 (defun org-comment-line-break-function (&optional soft)
23410 "Break line at point and indent, continuing comment if within one.
23411 The inserted newline is marked hard if variable
23412 `use-hard-newlines' is true, unless optional argument SOFT is
23413 non-nil."
23414 (if soft (insert-and-inherit ?\n) (newline 1))
23415 (save-excursion (forward-char -1) (delete-horizontal-space))
23416 (delete-horizontal-space)
23417 (indent-to-left-margin)
23418 (insert-before-markers-and-inherit fill-prefix))
23421 ;;; Fixed Width Areas
23423 (defun org-toggle-fixed-width ()
23424 "Toggle fixed-width markup.
23426 Add or remove fixed-width markup on current line, whenever it
23427 makes sense. Return an error otherwise.
23429 If a region is active and if it contains only fixed-width areas
23430 or blank lines, remove all fixed-width markup in it. If the
23431 region contains anything else, convert all non-fixed-width lines
23432 to fixed-width ones.
23434 Blank lines at the end of the region are ignored unless the
23435 region only contains such lines."
23436 (interactive)
23437 (if (not (org-region-active-p))
23438 ;; No region:
23440 ;; Remove fixed width marker only in a fixed-with element.
23442 ;; Add fixed width maker in paragraphs, in blank lines after
23443 ;; elements or at the beginning of a headline or an inlinetask,
23444 ;; and before any one-line elements (e.g., a clock).
23445 (progn
23446 (beginning-of-line)
23447 (let* ((element (org-element-at-point))
23448 (type (org-element-type element)))
23449 (cond
23450 ((and (eq type 'fixed-width)
23451 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23452 (replace-match
23453 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23454 ((and (memq type '(babel-call clock comment diary-sexp headline
23455 horizontal-rule keyword paragraph
23456 planning))
23457 (<= (org-element-property :post-affiliated element) (point)))
23458 (skip-chars-forward " \t")
23459 (insert ": "))
23460 ((and (looking-at-p "[ \t]*$")
23461 (or (eq type 'inlinetask)
23462 (save-excursion
23463 (skip-chars-forward " \r\t\n")
23464 (<= (org-element-property :end element) (point)))))
23465 (delete-region (point) (line-end-position))
23466 (org-indent-line)
23467 (insert ": "))
23468 (t (user-error "Cannot insert a fixed-width line here")))))
23469 ;; Region active.
23470 (let* ((begin (save-excursion
23471 (goto-char (region-beginning))
23472 (line-beginning-position)))
23473 (end (copy-marker
23474 (save-excursion
23475 (goto-char (region-end))
23476 (unless (eolp) (beginning-of-line))
23477 (if (save-excursion (re-search-backward "\\S-" begin t))
23478 (progn (skip-chars-backward " \r\t\n") (point))
23479 (point)))))
23480 (all-fixed-width-p
23481 (catch 'not-all-p
23482 (save-excursion
23483 (goto-char begin)
23484 (skip-chars-forward " \r\t\n")
23485 (when (eobp) (throw 'not-all-p nil))
23486 (while (< (point) end)
23487 (let ((element (org-element-at-point)))
23488 (if (eq (org-element-type element) 'fixed-width)
23489 (goto-char (org-element-property :end element))
23490 (throw 'not-all-p nil))))
23491 t))))
23492 (if all-fixed-width-p
23493 (save-excursion
23494 (goto-char begin)
23495 (while (< (point) end)
23496 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23497 (replace-match
23498 "" nil nil nil
23499 (if (= (line-end-position) (match-end 0)) 0 1)))
23500 (forward-line)))
23501 (let ((min-ind (point-max)))
23502 ;; Find minimum indentation across all lines.
23503 (save-excursion
23504 (goto-char begin)
23505 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23506 (setq min-ind 0)
23507 (catch 'zerop
23508 (while (< (point) end)
23509 (unless (looking-at-p "[ \t]*$")
23510 (let ((ind (org-get-indentation)))
23511 (setq min-ind (min min-ind ind))
23512 (when (zerop ind) (throw 'zerop t))))
23513 (forward-line)))))
23514 ;; Loop over all lines and add fixed-width markup everywhere
23515 ;; but in fixed-width lines.
23516 (save-excursion
23517 (goto-char begin)
23518 (while (< (point) end)
23519 (cond
23520 ((org-at-heading-p)
23521 (insert ": ")
23522 (forward-line)
23523 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23524 (insert ":")
23525 (forward-line)))
23526 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23527 (let* ((element (org-element-at-point))
23528 (element-end (org-element-property :end element)))
23529 (if (eq (org-element-type element) 'fixed-width)
23530 (progn (goto-char element-end)
23531 (skip-chars-backward " \r\t\n")
23532 (forward-line))
23533 (let ((limit (min end element-end)))
23534 (while (< (point) limit)
23535 (org-move-to-column min-ind t)
23536 (insert ": ")
23537 (forward-line))))))
23539 (org-move-to-column min-ind t)
23540 (insert ": ")
23541 (forward-line)))))))
23542 (set-marker end nil))))
23545 ;;; Comments
23547 ;; Org comments syntax is quite complex. It requires the entire line
23548 ;; to be just a comment. Also, even with the right syntax at the
23549 ;; beginning of line, some some elements (i.e. verse-block or
23550 ;; example-block) don't accept comments. Usual Emacs comment commands
23551 ;; cannot cope with those requirements. Therefore, Org replaces them.
23553 ;; Org still relies on `comment-dwim', but cannot trust
23554 ;; `comment-only-p'. So, `comment-region-function' and
23555 ;; `uncomment-region-function' both point
23556 ;; to`org-comment-or-uncomment-region'. Eventually,
23557 ;; `org-insert-comment' takes care of insertion of comments at the
23558 ;; beginning of line.
23560 ;; `org-setup-comments-handling' install comments related variables
23561 ;; during `org-mode' initialization.
23563 (defun org-setup-comments-handling ()
23564 (interactive)
23565 (setq-local comment-use-syntax nil)
23566 (setq-local comment-start "# ")
23567 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23568 (setq-local comment-insert-comment-function 'org-insert-comment)
23569 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23570 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23572 (defun org-insert-comment ()
23573 "Insert an empty comment above current line.
23574 If the line is empty, insert comment at its beginning. When
23575 point is within a source block, comment according to the related
23576 major mode."
23577 (if (let ((element (org-element-at-point)))
23578 (and (eq (org-element-type element) 'src-block)
23579 (< (save-excursion
23580 (goto-char (org-element-property :post-affiliated element))
23581 (line-end-position))
23582 (point))
23583 (> (save-excursion
23584 (goto-char (org-element-property :end element))
23585 (skip-chars-backward " \r\t\n")
23586 (line-beginning-position))
23587 (point))))
23588 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23589 (beginning-of-line)
23590 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23591 (open-line 1))
23592 (org-indent-line)
23593 (insert "# ")))
23595 (defvar comment-empty-lines) ; From newcomment.el.
23596 (defun org-comment-or-uncomment-region (beg end &rest _)
23597 "Comment or uncomment each non-blank line in the region.
23598 Uncomment each non-blank line between BEG and END if it only
23599 contains commented lines. Otherwise, comment them. If region is
23600 strictly within a source block, use appropriate comment syntax."
23601 (if (let ((element (org-element-at-point)))
23602 (and (eq (org-element-type element) 'src-block)
23603 (< (save-excursion
23604 (goto-char (org-element-property :post-affiliated element))
23605 (line-end-position))
23606 beg)
23607 (>= (save-excursion
23608 (goto-char (org-element-property :end element))
23609 (skip-chars-backward " \r\t\n")
23610 (line-beginning-position))
23611 end)))
23612 ;; Translate region boundaries for the Org buffer to the source
23613 ;; buffer.
23614 (let ((offset (- end beg)))
23615 (save-excursion
23616 (goto-char beg)
23617 (org-babel-do-in-edit-buffer
23618 (comment-or-uncomment-region (point) (+ offset (point))))))
23619 (save-restriction
23620 ;; Restrict region
23621 (narrow-to-region (save-excursion (goto-char beg)
23622 (skip-chars-forward " \r\t\n" end)
23623 (line-beginning-position))
23624 (save-excursion (goto-char end)
23625 (skip-chars-backward " \r\t\n" beg)
23626 (line-end-position)))
23627 (let ((uncommentp
23628 ;; UNCOMMENTP is non-nil when every non blank line between
23629 ;; BEG and END is a comment.
23630 (save-excursion
23631 (goto-char (point-min))
23632 (while (and (not (eobp))
23633 (let ((element (org-element-at-point)))
23634 (and (eq (org-element-type element) 'comment)
23635 (goto-char (min (point-max)
23636 (org-element-property
23637 :end element)))))))
23638 (eobp))))
23639 (if uncommentp
23640 ;; Only blank lines and comments in region: uncomment it.
23641 (save-excursion
23642 (goto-char (point-min))
23643 (while (not (eobp))
23644 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23645 (replace-match "" nil nil nil 1))
23646 (forward-line)))
23647 ;; Comment each line in region.
23648 (let ((min-indent (point-max)))
23649 ;; First find the minimum indentation across all lines.
23650 (save-excursion
23651 (goto-char (point-min))
23652 (while (and (not (eobp)) (not (zerop min-indent)))
23653 (unless (looking-at "[ \t]*$")
23654 (setq min-indent (min min-indent (current-indentation))))
23655 (forward-line)))
23656 ;; Then loop over all lines.
23657 (save-excursion
23658 (goto-char (point-min))
23659 (while (not (eobp))
23660 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23661 ;; Don't get fooled by invisible text (e.g. link path)
23662 ;; when moving to column MIN-INDENT.
23663 (let ((buffer-invisibility-spec nil))
23664 (org-move-to-column min-indent t))
23665 (insert comment-start))
23666 (forward-line)))))))))
23668 (defun org-comment-dwim (_arg)
23669 "Call `comment-dwim' within a source edit buffer if needed."
23670 (interactive "*P")
23671 (if (org-in-src-block-p)
23672 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23673 (call-interactively 'comment-dwim)))
23676 ;;; Timestamps API
23678 ;; This section contains tools to operate on timestamp objects, as
23679 ;; returned by, e.g. `org-element-context'.
23681 (defun org-timestamp--to-internal-time (timestamp &optional end)
23682 "Encode TIMESTAMP object into Emacs internal time.
23683 Use end of date range or time range when END is non-nil."
23684 (apply #'encode-time
23685 (cons 0
23686 (mapcar
23687 (lambda (prop) (or (org-element-property prop timestamp) 0))
23688 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23689 '(:minute-start :hour-start :day-start :month-start
23690 :year-start))))))
23692 (defun org-timestamp-has-time-p (timestamp)
23693 "Non-nil when TIMESTAMP has a time specified."
23694 (org-element-property :hour-start timestamp))
23696 (defun org-timestamp-format (timestamp format &optional end utc)
23697 "Format a TIMESTAMP object into a string.
23699 FORMAT is a format specifier to be passed to
23700 `format-time-string'.
23702 When optional argument END is non-nil, use end of date-range or
23703 time-range, if possible.
23705 When optional argument UTC is non-nil, time will be expressed as
23706 Universal Time."
23707 (format-time-string
23708 format (org-timestamp--to-internal-time timestamp end)
23709 (and utc t)))
23711 (defun org-timestamp-split-range (timestamp &optional end)
23712 "Extract a TIMESTAMP object from a date or time range.
23714 END, when non-nil, means extract the end of the range.
23715 Otherwise, extract its start.
23717 Return a new timestamp object."
23718 (let ((type (org-element-property :type timestamp)))
23719 (if (memq type '(active inactive diary)) timestamp
23720 (let ((split-ts (org-element-copy timestamp)))
23721 ;; Set new type.
23722 (org-element-put-property
23723 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23724 ;; Copy start properties over end properties if END is
23725 ;; non-nil. Otherwise, copy end properties over `start' ones.
23726 (let ((p-alist '((:minute-start . :minute-end)
23727 (:hour-start . :hour-end)
23728 (:day-start . :day-end)
23729 (:month-start . :month-end)
23730 (:year-start . :year-end))))
23731 (dolist (p-cell p-alist)
23732 (org-element-put-property
23733 split-ts
23734 (funcall (if end #'car #'cdr) p-cell)
23735 (org-element-property
23736 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23737 ;; Eventually refresh `:raw-value'.
23738 (org-element-put-property split-ts :raw-value nil)
23739 (org-element-put-property
23740 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23742 (defun org-timestamp-translate (timestamp &optional boundary)
23743 "Translate TIMESTAMP object to custom format.
23745 Format string is defined in `org-time-stamp-custom-formats',
23746 which see.
23748 When optional argument BOUNDARY is non-nil, it is either the
23749 symbol `start' or `end'. In this case, only translate the
23750 starting or ending part of TIMESTAMP if it is a date or time
23751 range. Otherwise, translate both parts.
23753 Return timestamp as-is if `org-display-custom-times' is nil or if
23754 it has a `diary' type."
23755 (let ((type (org-element-property :type timestamp)))
23756 (if (or (not org-display-custom-times) (eq type 'diary))
23757 (org-element-interpret-data timestamp)
23758 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23759 org-time-stamp-custom-formats)))
23760 (if (and (not boundary) (memq type '(active-range inactive-range)))
23761 (concat (org-timestamp-format timestamp fmt)
23762 "--"
23763 (org-timestamp-format timestamp fmt t))
23764 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23768 ;;; Other stuff.
23770 (defvar reftex-docstruct-symbol)
23771 (defvar org--rds)
23773 (defun org-reftex-citation ()
23774 "Use reftex-citation to insert a citation into the buffer.
23775 This looks for a line like
23777 #+BIBLIOGRAPHY: foo plain option:-d
23779 and derives from it that foo.bib is the bibliography file relevant
23780 for this document. It then installs the necessary environment for RefTeX
23781 to work in this buffer and calls `reftex-citation' to insert a citation
23782 into the buffer.
23784 Export of such citations to both LaTeX and HTML is handled by the contributed
23785 package ox-bibtex by Taru Karttunen."
23786 (interactive)
23787 (let ((reftex-docstruct-symbol 'org--rds)
23788 org--rds bib)
23789 (org-with-wide-buffer
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 n)
23803 "Go to the beginning of the current visible line.
23805 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23806 tags on the first attempt, and only move to after the tags when
23807 the cursor is already beyond the end of the headline.
23809 With argument N not nil or 1, move forward N - 1 lines first."
23810 (interactive "^p")
23811 (let ((origin (point))
23812 (special (pcase org-special-ctrl-a/e
23813 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23814 deactivate-mark)
23815 ;; First move to a visible line.
23816 (if (bound-and-true-p visual-line-mode)
23817 (beginning-of-visual-line n)
23818 (move-beginning-of-line n)
23819 ;; `move-beginning-of-line' may leave point after invisible
23820 ;; characters if line starts with such of these (e.g., with
23821 ;; a link at column 0). Really move to the beginning of the
23822 ;; current visible line.
23823 (beginning-of-line))
23824 (cond
23825 ;; No special behavior. Point is already at the beginning of
23826 ;; a line, logical or visual.
23827 ((not special))
23828 ;; `beginning-of-visual-line' left point before logical beginning
23829 ;; of line: point is at the beginning of a visual line. Bail
23830 ;; out.
23831 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23832 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23833 ;; At a headline, special position is before the title, but
23834 ;; after any TODO keyword or priority cookie.
23835 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23836 (line-end-position)))
23837 (bol (point)))
23838 (if (eq special 'reversed)
23839 (when (and (= origin bol) (eq last-command this-command))
23840 (goto-char refpos))
23841 (when (or (> origin refpos) (= origin bol))
23842 (goto-char refpos)))))
23843 ((and (looking-at org-list-full-item-re)
23844 (memq (org-element-type (save-match-data (org-element-at-point)))
23845 '(item plain-list)))
23846 ;; Set special position at first white space character after
23847 ;; bullet, and check-box, if any.
23848 (let ((after-bullet
23849 (let ((box (match-end 3)))
23850 (cond ((not box) (match-end 1))
23851 ((eq (char-after box) ?\s) (1+ box))
23852 (t box)))))
23853 (if (eq special 'reversed)
23854 (when (and (= (point) origin) (eq last-command this-command))
23855 (goto-char after-bullet))
23856 (when (or (> origin after-bullet) (= (point) origin))
23857 (goto-char after-bullet)))))
23858 ;; No special context. Point is already at beginning of line.
23859 (t nil))))
23861 (defun org-end-of-line (&optional n)
23862 "Go to the end of the line, but before ellipsis, if any.
23864 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23865 tags on the first attempt, and only move to after the tags when
23866 the cursor is already beyond the end of the headline.
23868 With argument N not nil or 1, move forward N - 1 lines first."
23869 (interactive "^p")
23870 (let ((origin (point))
23871 (special (pcase org-special-ctrl-a/e
23872 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23873 deactivate-mark)
23874 ;; First move to a visible line.
23875 (if (bound-and-true-p visual-line-mode)
23876 (beginning-of-visual-line n)
23877 (move-beginning-of-line n))
23878 (cond
23879 ;; At a headline, with tags.
23880 ((and special
23881 (save-excursion
23882 (beginning-of-line)
23883 (let ((case-fold-search nil))
23884 (looking-at org-complex-heading-regexp)))
23885 (match-end 5))
23886 (let ((tags (save-excursion
23887 (goto-char (match-beginning 5))
23888 (skip-chars-backward " \t")
23889 (point)))
23890 (visual-end (and (bound-and-true-p visual-line-mode)
23891 (save-excursion
23892 (end-of-visual-line)
23893 (point)))))
23894 ;; If `end-of-visual-line' brings us before end of line or
23895 ;; even tags, i.e., the headline spans over multiple visual
23896 ;; lines, move there.
23897 (cond ((and visual-end
23898 (< visual-end tags)
23899 (<= origin visual-end))
23900 (goto-char visual-end))
23901 ((eq special 'reversed)
23902 (if (and (= origin (line-end-position))
23903 (eq this-command last-command))
23904 (goto-char tags)
23905 (end-of-line)))
23907 (if (or (< origin tags) (= origin (line-end-position)))
23908 (goto-char tags)
23909 (end-of-line))))))
23910 ((bound-and-true-p visual-line-mode)
23911 (let ((bol (line-beginning-position)))
23912 (end-of-visual-line)
23913 ;; If `end-of-visual-line' gets us past the ellipsis at the
23914 ;; end of a line, backtrack and use `end-of-line' instead.
23915 (when (/= bol (line-beginning-position))
23916 (goto-char bol)
23917 (end-of-line))))
23918 (t (end-of-line)))))
23920 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23921 (define-key org-mode-map "\C-e" 'org-end-of-line)
23923 (defun org-backward-sentence (&optional _arg)
23924 "Go to beginning of sentence, or beginning of table field.
23925 This will call `backward-sentence' or `org-table-beginning-of-field',
23926 depending on context."
23927 (interactive)
23928 (let* ((element (org-element-at-point))
23929 (contents-begin (org-element-property :contents-begin element))
23930 (table (org-element-lineage element '(table) t)))
23931 (if (and table
23932 (> (point) contents-begin)
23933 (<= (point) (org-element-property :contents-end table)))
23934 (call-interactively #'org-table-beginning-of-field)
23935 (save-restriction
23936 (when (and contents-begin
23937 (< (point-min) contents-begin)
23938 (> (point) contents-begin))
23939 (narrow-to-region contents-begin
23940 (org-element-property :contents-end element)))
23941 (call-interactively #'backward-sentence)))))
23943 (defun org-forward-sentence (&optional _arg)
23944 "Go to end of sentence, or end of table field.
23945 This will call `forward-sentence' or `org-table-end-of-field',
23946 depending on context."
23947 (interactive)
23948 (let* ((element (org-element-at-point))
23949 (contents-end (org-element-property :contents-end element))
23950 (table (org-element-lineage element '(table) t)))
23951 (if (and table
23952 (>= (point) (org-element-property :contents-begin table))
23953 (< (point) contents-end))
23954 (call-interactively #'org-table-end-of-field)
23955 (save-restriction
23956 (when (and contents-end
23957 (> (point-max) contents-end)
23958 ;; Skip blank lines between elements.
23959 (< (org-element-property :end element)
23960 (save-excursion (goto-char contents-end)
23961 (skip-chars-forward " \r\t\n"))))
23962 (narrow-to-region (org-element-property :contents-begin element)
23963 contents-end))
23964 (call-interactively #'forward-sentence)))))
23966 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23967 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23969 (defun org-kill-line (&optional _arg)
23970 "Kill line, to tags or end of line."
23971 (interactive)
23972 (cond
23973 ((or (not org-special-ctrl-k)
23974 (bolp)
23975 (not (org-at-heading-p)))
23976 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23977 org-ctrl-k-protect-subtree
23978 (or (eq org-ctrl-k-protect-subtree 'error)
23979 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23980 (user-error "C-k aborted as it would kill a hidden subtree"))
23981 (call-interactively
23982 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23983 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23984 (kill-region (point) (match-beginning 1))
23985 (org-set-tags nil t))
23986 (t (kill-region (point) (point-at-eol)))))
23988 (define-key org-mode-map "\C-k" 'org-kill-line)
23990 (defun org-yank (&optional arg)
23991 "Yank. If the kill is a subtree, treat it specially.
23992 This command will look at the current kill and check if is a single
23993 subtree, or a series of subtrees[1]. If it passes the test, and if the
23994 cursor is at the beginning of a line or after the stars of a currently
23995 empty headline, then the yank is handled specially. How exactly depends
23996 on the value of the following variables.
23998 `org-yank-folded-subtrees'
23999 By default, this variable is non-nil, which results in
24000 subtree(s) being folded after insertion, except if doing so
24001 would swallow text after the yanked text.
24003 `org-yank-adjusted-subtrees'
24004 When non-nil (the default value is nil), the subtree will be
24005 promoted or demoted in order to fit into the local outline tree
24006 structure, which means that the level will be adjusted so that it
24007 becomes the smaller one of the two *visible* surrounding headings.
24009 Any prefix to this command will cause `yank' to be called directly with
24010 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
24011 will just
24012 plainly yank the text as it is.
24014 \[1] The test checks if the first non-white line is a heading
24015 and if there are no other headings with fewer stars."
24016 (interactive "P")
24017 (org-yank-generic 'yank arg))
24019 (defun org-yank-generic (command arg)
24020 "Perform some yank-like command.
24022 This function implements the behavior described in the `org-yank'
24023 documentation. However, it has been generalized to work for any
24024 interactive command with similar behavior."
24026 ;; pretend to be command COMMAND
24027 (setq this-command command)
24029 (if arg
24030 (call-interactively command)
24032 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24033 (and (org-kill-is-subtree-p)
24034 (or (bolp)
24035 (and (looking-at "[ \t]*$")
24036 (string-match
24037 "\\`\\*+\\'"
24038 (buffer-substring (point-at-bol) (point)))))))
24039 swallowp)
24040 (cond
24041 ((and subtreep org-yank-folded-subtrees)
24042 (let ((beg (point))
24043 end)
24044 (if (and subtreep org-yank-adjusted-subtrees)
24045 (org-paste-subtree nil nil 'for-yank)
24046 (call-interactively command))
24048 (setq end (point))
24049 (goto-char beg)
24050 (when (and (bolp) subtreep
24051 (not (setq swallowp
24052 (org-yank-folding-would-swallow-text beg end))))
24053 (org-with-limited-levels
24054 (or (looking-at org-outline-regexp)
24055 (re-search-forward org-outline-regexp-bol end t))
24056 (while (and (< (point) end) (looking-at org-outline-regexp))
24057 (outline-hide-subtree)
24058 (org-cycle-show-empty-lines 'folded)
24059 (condition-case nil
24060 (outline-forward-same-level 1)
24061 (error (goto-char end))))))
24062 (when swallowp
24063 (message
24064 "Inserted text not folded because that would swallow text"))
24066 (goto-char end)
24067 (skip-chars-forward " \t\n\r")
24068 (beginning-of-line 1)
24069 (push-mark beg 'nomsg)))
24070 ((and subtreep org-yank-adjusted-subtrees)
24071 (let ((beg (point-at-bol)))
24072 (org-paste-subtree nil nil 'for-yank)
24073 (push-mark beg 'nomsg)))
24075 (call-interactively command))))))
24077 (defun org-yank-folding-would-swallow-text (beg end)
24078 "Would hide-subtree at BEG swallow any text after END?"
24079 (let (level)
24080 (org-with-limited-levels
24081 (save-excursion
24082 (goto-char beg)
24083 (when (or (looking-at org-outline-regexp)
24084 (re-search-forward org-outline-regexp-bol end t))
24085 (setq level (org-outline-level)))
24086 (goto-char end)
24087 (skip-chars-forward " \t\r\n\v\f")
24088 (not (or (eobp)
24089 (and (bolp) (looking-at-p org-outline-regexp)
24090 (<= (org-outline-level) level))))))))
24092 (define-key org-mode-map "\C-y" 'org-yank)
24094 (defun org-truely-invisible-p ()
24095 "Check if point is at a character currently not visible.
24096 This version does not only check the character property, but also
24097 `visible-mode'."
24098 ;; Early versions of noutline don't have `outline-invisible-p'.
24099 (unless (bound-and-true-p visible-mode)
24100 (outline-invisible-p)))
24102 (defun org-invisible-p2 ()
24103 "Check if point is at a character currently not visible."
24104 (save-excursion
24105 (when (and (eolp) (not (bobp))) (backward-char 1))
24106 ;; Early versions of noutline don't have `outline-invisible-p'.
24107 (outline-invisible-p)))
24109 (defun org-back-to-heading (&optional invisible-ok)
24110 "Call `outline-back-to-heading', but provide a better error message."
24111 (condition-case nil
24112 (outline-back-to-heading invisible-ok)
24113 (error (error "Before first headline at position %d in buffer %s"
24114 (point) (current-buffer)))))
24116 (defun org-before-first-heading-p ()
24117 "Before first heading?"
24118 (save-excursion
24119 (end-of-line)
24120 (null (re-search-backward org-outline-regexp-bol nil t))))
24122 (defun org-at-heading-p (&optional ignored)
24123 (outline-on-heading-p t))
24125 (defun org-in-commented-heading-p (&optional no-inheritance)
24126 "Non-nil if point is under a commented heading.
24127 This function also checks ancestors of the current headline,
24128 unless optional argument NO-INHERITANCE is non-nil."
24129 (cond
24130 ((org-before-first-heading-p) nil)
24131 ((let ((headline (nth 4 (org-heading-components))))
24132 (and headline
24133 (let ((case-fold-search nil))
24134 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24135 headline)))))
24136 (no-inheritance nil)
24138 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24140 (defun org-at-comment-p nil
24141 "Is cursor in a commented line?"
24142 (save-excursion
24143 (save-match-data
24144 (beginning-of-line)
24145 (looking-at "^[ \t]*# "))))
24147 (defun org-at-drawer-p nil
24148 "Is cursor at a drawer keyword?"
24149 (save-excursion
24150 (move-beginning-of-line 1)
24151 (looking-at org-drawer-regexp)))
24153 (defun org-at-block-p nil
24154 "Is cursor at a block keyword?"
24155 (save-excursion
24156 (move-beginning-of-line 1)
24157 (looking-at org-block-regexp)))
24159 (defun org-point-at-end-of-empty-headline ()
24160 "If point is at the end of an empty headline, return t, else nil.
24161 If the heading only contains a TODO keyword, it is still still considered
24162 empty."
24163 (let ((case-fold-search nil))
24164 (and (looking-at "[ \t]*$")
24165 org-todo-line-regexp
24166 (save-excursion
24167 (beginning-of-line)
24168 (looking-at org-todo-line-regexp)
24169 (string= (match-string 3) "")))))
24171 (defun org-at-heading-or-item-p ()
24172 (or (org-at-heading-p) (org-at-item-p)))
24174 (defun org-at-target-p ()
24175 (or (org-in-regexp org-radio-target-regexp)
24176 (org-in-regexp org-target-regexp)))
24177 ;; Compatibility alias with Org versions < 7.8.03
24178 (defalias 'org-on-target-p 'org-at-target-p)
24180 (defun org-up-heading-all (arg)
24181 "Move to the heading line of which the present line is a subheading.
24182 This function considers both visible and invisible heading lines.
24183 With argument, move up ARG levels."
24184 (outline-up-heading arg t))
24186 (defun org-up-heading-safe ()
24187 "Move to the heading line of which the present line is a subheading.
24188 This version will not throw an error. It will return the level of the
24189 headline found, or nil if no higher level is found.
24191 Also, this function will be a lot faster than `outline-up-heading',
24192 because it relies on stars being the outline starters. This can really
24193 make a significant difference in outlines with very many siblings."
24194 (when (ignore-errors (org-back-to-heading t))
24195 (let ((level-up (1- (funcall outline-level))))
24196 (and (> level-up 0)
24197 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24198 (funcall outline-level)))))
24200 (defun org-first-sibling-p ()
24201 "Is this heading the first child of its parents?"
24202 (interactive)
24203 (let ((re org-outline-regexp-bol)
24204 level l)
24205 (unless (org-at-heading-p t)
24206 (user-error "Not at a heading"))
24207 (setq level (funcall outline-level))
24208 (save-excursion
24209 (if (not (re-search-backward re nil t))
24211 (setq l (funcall outline-level))
24212 (< l level)))))
24214 (defun org-goto-sibling (&optional previous)
24215 "Goto the next sibling, even if it is invisible.
24216 When PREVIOUS is set, go to the previous sibling instead. Returns t
24217 when a sibling was found. When none is found, return nil and don't
24218 move point."
24219 (let ((fun (if previous 're-search-backward 're-search-forward))
24220 (pos (point))
24221 (re org-outline-regexp-bol)
24222 level l)
24223 (when (ignore-errors (org-back-to-heading t))
24224 (setq level (funcall outline-level))
24225 (catch 'exit
24226 (or previous (forward-char 1))
24227 (while (funcall fun re nil t)
24228 (setq l (funcall outline-level))
24229 (when (< l level) (goto-char pos) (throw 'exit nil))
24230 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24231 (goto-char pos)
24232 nil))))
24234 (defun org-show-siblings ()
24235 "Show all siblings of the current headline."
24236 (save-excursion
24237 (while (org-goto-sibling) (org-flag-heading nil)))
24238 (save-excursion
24239 (while (org-goto-sibling 'previous)
24240 (org-flag-heading nil))))
24242 (defun org-goto-first-child ()
24243 "Goto the first child, even if it is invisible.
24244 Return t when a child was found. Otherwise don't move point and
24245 return nil."
24246 (let (level (pos (point)) (re org-outline-regexp-bol))
24247 (when (ignore-errors (org-back-to-heading t))
24248 (setq level (outline-level))
24249 (forward-char 1)
24250 (if (and (re-search-forward re nil t) (> (outline-level) level))
24251 (progn (goto-char (match-beginning 0)) t)
24252 (goto-char pos) nil))))
24254 (defun org-show-hidden-entry ()
24255 "Show an entry where even the heading is hidden."
24256 (save-excursion
24257 (org-show-entry)))
24259 (defun org-flag-heading (flag &optional entry)
24260 "Flag the current heading. FLAG non-nil means make invisible.
24261 When ENTRY is non-nil, show the entire entry."
24262 (save-excursion
24263 (org-back-to-heading t)
24264 ;; Check if we should show the entire entry
24265 (if entry
24266 (progn
24267 (org-show-entry)
24268 (save-excursion
24269 (and (outline-next-heading)
24270 (org-flag-heading nil))))
24271 (outline-flag-region (max (point-min) (1- (point)))
24272 (save-excursion (outline-end-of-heading) (point))
24273 flag))))
24275 (defun org-get-next-sibling ()
24276 "Move to next heading of the same level, and return point.
24277 If there is no such heading, return nil.
24278 This is like outline-next-sibling, but invisible headings are ok."
24279 (let ((level (funcall outline-level)))
24280 (outline-next-heading)
24281 (while (and (not (eobp)) (> (funcall outline-level) level))
24282 (outline-next-heading))
24283 (unless (or (eobp) (< (funcall outline-level) level))
24284 (point))))
24286 (defun org-get-last-sibling ()
24287 "Move to previous heading of the same level, and return point.
24288 If there is no such heading, return nil."
24289 (let ((opoint (point))
24290 (level (funcall outline-level)))
24291 (outline-previous-heading)
24292 (when (and (/= (point) opoint) (outline-on-heading-p t))
24293 (while (and (> (funcall outline-level) level)
24294 (not (bobp)))
24295 (outline-previous-heading))
24296 (unless (< (funcall outline-level) level)
24297 (point)))))
24299 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24300 "Goto to the end of a subtree."
24301 ;; This contains an exact copy of the original function, but it uses
24302 ;; `org-back-to-heading', to make it work also in invisible
24303 ;; trees. And is uses an invisible-ok argument.
24304 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24305 ;; Furthermore, when used inside Org, finding the end of a large subtree
24306 ;; with many children and grandchildren etc, this can be much faster
24307 ;; than the outline version.
24308 (org-back-to-heading invisible-ok)
24309 (let ((first t)
24310 (level (funcall outline-level)))
24311 (if (and (derived-mode-p 'org-mode) (< level 1000))
24312 ;; A true heading (not a plain list item), in Org
24313 ;; This means we can easily find the end by looking
24314 ;; only for the right number of stars. Using a regexp to do
24315 ;; this is so much faster than using a Lisp loop.
24316 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24317 (forward-char 1)
24318 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24319 ;; something else, do it the slow way
24320 (while (and (not (eobp))
24321 (or first (> (funcall outline-level) level)))
24322 (setq first nil)
24323 (outline-next-heading)))
24324 (unless to-heading
24325 (when (memq (preceding-char) '(?\n ?\^M))
24326 ;; Go to end of line before heading
24327 (forward-char -1)
24328 (when (memq (preceding-char) '(?\n ?\^M))
24329 ;; leave blank line before heading
24330 (forward-char -1)))))
24331 (point))
24333 (defun org-end-of-meta-data (&optional full)
24334 "Skip planning line and properties drawer in current entry.
24335 When optional argument FULL is non-nil, also skip empty lines,
24336 clocking lines and regular drawers at the beginning of the
24337 entry."
24338 (org-back-to-heading t)
24339 (forward-line)
24340 (when (looking-at-p org-planning-line-re) (forward-line))
24341 (when (looking-at org-property-drawer-re)
24342 (goto-char (match-end 0))
24343 (forward-line))
24344 (when (and full (not (org-at-heading-p)))
24345 (catch 'exit
24346 (let ((end (save-excursion (outline-next-heading) (point)))
24347 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24348 (while (not (eobp))
24349 (cond ((looking-at-p org-drawer-regexp)
24350 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24351 (forward-line)
24352 (throw 'exit t)))
24353 ((looking-at-p re) (forward-line))
24354 (t (throw 'exit t))))))))
24356 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24357 "Move forward to the ARG'th subheading at same level as this one.
24358 Stop at the first and last subheadings of a superior heading.
24359 Normally this only looks at visible headings, but when INVISIBLE-OK is
24360 non-nil it will also look at invisible ones."
24361 (interactive "p")
24362 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24363 (if (and arg (< arg 0))
24364 (goto-char (point-min))
24365 (outline-next-heading))
24366 (org-at-heading-p)
24367 (let ((level (- (match-end 0) (match-beginning 0) 1))
24368 (f (if (and arg (< arg 0))
24369 're-search-backward
24370 're-search-forward))
24371 (count (if arg (abs arg) 1))
24372 (result (point)))
24373 (while (and (prog1 (> count 0)
24374 (forward-char (if (and arg (< arg 0)) -1 1)))
24375 (funcall f org-outline-regexp-bol nil 'move))
24376 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24377 (cond ((< l level) (setq count 0))
24378 ((and (= l level)
24379 (or invisible-ok
24380 (progn
24381 (goto-char (line-beginning-position))
24382 (not (outline-invisible-p)))))
24383 (setq count (1- count))
24384 (when (eq l level)
24385 (setq result (point)))))))
24386 (goto-char result))
24387 (beginning-of-line 1)))
24389 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24390 "Move backward to the ARG'th subheading at same level as this one.
24391 Stop at the first and last subheadings of a superior heading."
24392 (interactive "p")
24393 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24395 (defun org-next-visible-heading (arg)
24396 "Move to the next visible heading.
24398 This function wraps `outline-next-visible-heading' with
24399 `org-with-limited-levels' in order to skip over inline tasks and
24400 respect customization of `org-odd-levels-only'."
24401 (interactive "p")
24402 (org-with-limited-levels
24403 (outline-next-visible-heading arg)))
24405 (defun org-previous-visible-heading (arg)
24406 "Move to the previous visible heading.
24408 This function wraps `outline-previous-visible-heading' with
24409 `org-with-limited-levels' in order to skip over inline tasks and
24410 respect customization of `org-odd-levels-only'."
24411 (interactive "p")
24412 (org-with-limited-levels
24413 (outline-previous-visible-heading arg)))
24415 (defun org-next-block (arg &optional backward block-regexp)
24416 "Jump to the next block.
24418 With a prefix argument ARG, jump forward ARG many blocks.
24420 When BACKWARD is non-nil, jump to the previous block.
24422 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24423 Match data is set according to this regexp when the function
24424 returns.
24426 Return point at beginning of the opening line of found block.
24427 Throw an error if no block is found."
24428 (interactive "p")
24429 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24430 (case-fold-search t)
24431 (search-fn (if backward #'re-search-backward #'re-search-forward))
24432 (count (or arg 1))
24433 (origin (point))
24434 last-element)
24435 (if backward (beginning-of-line) (end-of-line))
24436 (while (and (> count 0) (funcall search-fn re nil t))
24437 (let ((element (save-excursion
24438 (goto-char (match-beginning 0))
24439 (save-match-data (org-element-at-point)))))
24440 (when (and (memq (org-element-type element)
24441 '(center-block comment-block dynamic-block
24442 example-block export-block quote-block
24443 special-block src-block verse-block))
24444 (<= (match-beginning 0)
24445 (org-element-property :post-affiliated element)))
24446 (setq last-element element)
24447 (cl-decf count))))
24448 (if (= count 0)
24449 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24450 (save-match-data (org-show-context)))
24451 (goto-char origin)
24452 (user-error "No %s code blocks" (if backward "previous" "further")))))
24454 (defun org-previous-block (arg &optional block-regexp)
24455 "Jump to the previous block.
24456 With a prefix argument ARG, jump backward ARG many source blocks.
24457 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24458 (interactive "p")
24459 (org-next-block arg t block-regexp))
24461 (defun org-forward-paragraph ()
24462 "Move forward to beginning of next paragraph or equivalent.
24464 The function moves point to the beginning of the next visible
24465 structural element, which can be a paragraph, a table, a list
24466 item, etc. It also provides some special moves for convenience:
24468 - On an affiliated keyword, jump to the beginning of the
24469 relative element.
24470 - On an item or a footnote definition, move to the second
24471 element inside, if any.
24472 - On a table or a property drawer, jump after it.
24473 - On a verse or source block, stop after blank lines."
24474 (interactive)
24475 (when (eobp) (user-error "Cannot move further down"))
24476 (let* ((deactivate-mark nil)
24477 (element (org-element-at-point))
24478 (type (org-element-type element))
24479 (post-affiliated (org-element-property :post-affiliated element))
24480 (contents-begin (org-element-property :contents-begin element))
24481 (contents-end (org-element-property :contents-end element))
24482 (end (let ((end (org-element-property :end element)) (parent element))
24483 (while (and (setq parent (org-element-property :parent parent))
24484 (= (org-element-property :contents-end parent) end))
24485 (setq end (org-element-property :end parent)))
24486 end)))
24487 (cond ((not element)
24488 (skip-chars-forward " \r\t\n")
24489 (or (eobp) (beginning-of-line)))
24490 ;; On affiliated keywords, move to element's beginning.
24491 ((< (point) post-affiliated)
24492 (goto-char post-affiliated))
24493 ;; At a table row, move to the end of the table. Similarly,
24494 ;; at a node property, move to the end of the property
24495 ;; drawer.
24496 ((memq type '(node-property table-row))
24497 (goto-char (org-element-property
24498 :end (org-element-property :parent element))))
24499 ((memq type '(property-drawer table)) (goto-char end))
24500 ;; Consider blank lines as separators in verse and source
24501 ;; blocks to ease editing.
24502 ((memq type '(src-block verse-block))
24503 (when (eq type 'src-block)
24504 (setq contents-end
24505 (save-excursion (goto-char end)
24506 (skip-chars-backward " \r\t\n")
24507 (line-beginning-position))))
24508 (beginning-of-line)
24509 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24510 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24511 (goto-char end)
24512 (skip-chars-forward " \r\t\n")
24513 (if (= (point) contents-end) (goto-char end)
24514 (beginning-of-line))))
24515 ;; With no contents, just skip element.
24516 ((not contents-begin) (goto-char end))
24517 ;; If contents are invisible, skip the element altogether.
24518 ((outline-invisible-p (line-end-position))
24519 (cl-case type
24520 (headline
24521 (org-with-limited-levels (outline-next-visible-heading 1)))
24522 ;; At a plain list, make sure we move to the next item
24523 ;; instead of skipping the whole list.
24524 (plain-list (forward-char)
24525 (org-forward-paragraph))
24526 (otherwise (goto-char end))))
24527 ((>= (point) contents-end) (goto-char end))
24528 ((>= (point) contents-begin)
24529 ;; This can only happen on paragraphs and plain lists.
24530 (cl-case type
24531 (paragraph (goto-char end))
24532 ;; At a plain list, try to move to second element in
24533 ;; first item, if possible.
24534 (plain-list (end-of-line)
24535 (org-forward-paragraph))))
24536 ;; When contents start on the middle of a line (e.g. in
24537 ;; items and footnote definitions), try to reach first
24538 ;; element starting after current line.
24539 ((> (line-end-position) contents-begin)
24540 (end-of-line)
24541 (org-forward-paragraph))
24542 (t (goto-char contents-begin)))))
24544 (defun org-backward-paragraph ()
24545 "Move backward to start of previous paragraph or equivalent.
24547 The function moves point to the beginning of the current
24548 structural element, which can be a paragraph, a table, a list
24549 item, etc., or to the beginning of the previous visible one if
24550 point is already there. It also provides some special moves for
24551 convenience:
24553 - On an affiliated keyword, jump to the first one.
24554 - On a table or a property drawer, move to its beginning.
24555 - On a verse or source block, stop before blank lines."
24556 (interactive)
24557 (when (bobp) (user-error "Cannot move further up"))
24558 (let* ((deactivate-mark nil)
24559 (element (org-element-at-point))
24560 (type (org-element-type element))
24561 (contents-begin (org-element-property :contents-begin element))
24562 (contents-end (org-element-property :contents-end element))
24563 (post-affiliated (org-element-property :post-affiliated element))
24564 (begin (org-element-property :begin element)))
24565 (cond
24566 ((not element) (goto-char (point-min)))
24567 ((= (point) begin)
24568 (backward-char)
24569 (org-backward-paragraph))
24570 ((<= (point) post-affiliated) (goto-char begin))
24571 ((memq type '(node-property table-row))
24572 (goto-char (org-element-property
24573 :post-affiliated (org-element-property :parent element))))
24574 ((memq type '(property-drawer table)) (goto-char begin))
24575 ((memq type '(src-block verse-block))
24576 (when (eq type 'src-block)
24577 (setq contents-begin
24578 (save-excursion (goto-char begin) (forward-line) (point))))
24579 (if (= (point) contents-begin) (goto-char post-affiliated)
24580 ;; Inside a verse block, see blank lines as paragraph
24581 ;; separators.
24582 (let ((origin (point)))
24583 (skip-chars-backward " \r\t\n" contents-begin)
24584 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24585 (skip-chars-forward " \r\t\n" origin)
24586 (if (= (point) origin) (goto-char contents-begin)
24587 (beginning-of-line))))))
24588 ((not contents-begin) (goto-char (or post-affiliated begin)))
24589 ((eq type 'paragraph)
24590 (goto-char contents-begin)
24591 ;; When at first paragraph in an item or a footnote definition,
24592 ;; move directly to beginning of line.
24593 (let ((parent-contents
24594 (org-element-property
24595 :contents-begin (org-element-property :parent element))))
24596 (when (and parent-contents (= parent-contents contents-begin))
24597 (beginning-of-line))))
24598 ;; At the end of a greater element, move to the beginning of the
24599 ;; last element within.
24600 ((>= (point) contents-end)
24601 (goto-char (1- contents-end))
24602 (org-backward-paragraph))
24603 (t (goto-char (or post-affiliated begin))))
24604 ;; Ensure we never leave point invisible.
24605 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24607 (defun org-forward-element ()
24608 "Move forward by one element.
24609 Move to the next element at the same level, when possible."
24610 (interactive)
24611 (cond ((eobp) (user-error "Cannot move further down"))
24612 ((org-with-limited-levels (org-at-heading-p))
24613 (let ((origin (point)))
24614 (goto-char (org-end-of-subtree nil t))
24615 (unless (org-with-limited-levels (org-at-heading-p))
24616 (goto-char origin)
24617 (user-error "Cannot move further down"))))
24619 (let* ((elem (org-element-at-point))
24620 (end (org-element-property :end elem))
24621 (parent (org-element-property :parent elem)))
24622 (cond ((and parent (= (org-element-property :contents-end parent) end))
24623 (goto-char (org-element-property :end parent)))
24624 ((integer-or-marker-p end) (goto-char end))
24625 (t (message "No element at point")))))))
24627 (defun org-backward-element ()
24628 "Move backward by one element.
24629 Move to the previous element at the same level, when possible."
24630 (interactive)
24631 (cond ((bobp) (user-error "Cannot move further up"))
24632 ((org-with-limited-levels (org-at-heading-p))
24633 ;; At a headline, move to the previous one, if any, or stay
24634 ;; here.
24635 (let ((origin (point)))
24636 (org-with-limited-levels (org-backward-heading-same-level 1))
24637 ;; When current headline has no sibling above, move to its
24638 ;; parent.
24639 (when (= (point) origin)
24640 (or (org-with-limited-levels (org-up-heading-safe))
24641 (progn (goto-char origin)
24642 (user-error "Cannot move further up"))))))
24644 (let* ((elem (org-element-at-point))
24645 (beg (org-element-property :begin elem)))
24646 (cond
24647 ;; Move to beginning of current element if point isn't
24648 ;; there already.
24649 ((null beg) (message "No element at point"))
24650 ((/= (point) beg) (goto-char beg))
24651 (t (goto-char beg)
24652 (skip-chars-backward " \r\t\n")
24653 (unless (bobp)
24654 (let ((prev (org-element-at-point)))
24655 (goto-char (org-element-property :begin prev))
24656 (while (and (setq prev (org-element-property :parent prev))
24657 (<= (org-element-property :end prev) beg))
24658 (goto-char (org-element-property :begin prev)))))))))))
24660 (defun org-up-element ()
24661 "Move to upper element."
24662 (interactive)
24663 (if (org-with-limited-levels (org-at-heading-p))
24664 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24665 (let* ((elem (org-element-at-point))
24666 (parent (org-element-property :parent elem)))
24667 (if parent (goto-char (org-element-property :begin parent))
24668 (if (org-with-limited-levels (org-before-first-heading-p))
24669 (user-error "No surrounding element")
24670 (org-with-limited-levels (org-back-to-heading)))))))
24672 (defvar org-element-greater-elements)
24673 (defun org-down-element ()
24674 "Move to inner element."
24675 (interactive)
24676 (let ((element (org-element-at-point)))
24677 (cond
24678 ((memq (org-element-type element) '(plain-list table))
24679 (goto-char (org-element-property :contents-begin element))
24680 (forward-char))
24681 ((memq (org-element-type element) org-element-greater-elements)
24682 ;; If contents are hidden, first disclose them.
24683 (when (outline-invisible-p (line-end-position)) (org-cycle))
24684 (goto-char (or (org-element-property :contents-begin element)
24685 (user-error "No content for this element"))))
24686 (t (user-error "No inner element")))))
24688 (defun org-drag-element-backward ()
24689 "Move backward element at point."
24690 (interactive)
24691 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24692 (let* ((elem (org-element-at-point))
24693 (prev-elem
24694 (save-excursion
24695 (goto-char (org-element-property :begin elem))
24696 (skip-chars-backward " \r\t\n")
24697 (unless (bobp)
24698 (let* ((beg (org-element-property :begin elem))
24699 (prev (org-element-at-point))
24700 (up prev))
24701 (while (and (setq up (org-element-property :parent up))
24702 (<= (org-element-property :end up) beg))
24703 (setq prev up))
24704 prev)))))
24705 ;; Error out if no previous element or previous element is
24706 ;; a parent of the current one.
24707 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24708 (user-error "Cannot drag element backward")
24709 (let ((pos (point)))
24710 (org-element-swap-A-B prev-elem elem)
24711 (goto-char (+ (org-element-property :begin prev-elem)
24712 (- pos (org-element-property :begin elem)))))))))
24714 (defun org-drag-element-forward ()
24715 "Move forward element at point."
24716 (interactive)
24717 (let* ((pos (point))
24718 (elem (org-element-at-point)))
24719 (when (= (point-max) (org-element-property :end elem))
24720 (user-error "Cannot drag element forward"))
24721 (goto-char (org-element-property :end elem))
24722 (let ((next-elem (org-element-at-point)))
24723 (when (or (org-element-nested-p elem next-elem)
24724 (and (eq (org-element-type next-elem) 'headline)
24725 (not (eq (org-element-type elem) 'headline))))
24726 (goto-char pos)
24727 (user-error "Cannot drag element forward"))
24728 ;; Compute new position of point: it's shifted by NEXT-ELEM
24729 ;; body's length (without final blanks) and by the length of
24730 ;; blanks between ELEM and NEXT-ELEM.
24731 (let ((size-next (- (save-excursion
24732 (goto-char (org-element-property :end next-elem))
24733 (skip-chars-backward " \r\t\n")
24734 (forward-line)
24735 ;; Small correction if buffer doesn't end
24736 ;; with a newline character.
24737 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24738 (org-element-property :begin next-elem)))
24739 (size-blank (- (org-element-property :end elem)
24740 (save-excursion
24741 (goto-char (org-element-property :end elem))
24742 (skip-chars-backward " \r\t\n")
24743 (forward-line)
24744 (point)))))
24745 (org-element-swap-A-B elem next-elem)
24746 (goto-char (+ pos size-next size-blank))))))
24748 (defun org-drag-line-forward (arg)
24749 "Drag the line at point ARG lines forward."
24750 (interactive "p")
24751 (dotimes (_ (abs arg))
24752 (let ((c (current-column)))
24753 (if (< 0 arg)
24754 (progn
24755 (beginning-of-line 2)
24756 (transpose-lines 1)
24757 (beginning-of-line 0))
24758 (transpose-lines 1)
24759 (beginning-of-line -1))
24760 (org-move-to-column c))))
24762 (defun org-drag-line-backward (arg)
24763 "Drag the line at point ARG lines backward."
24764 (interactive "p")
24765 (org-drag-line-forward (- arg)))
24767 (defun org-mark-element ()
24768 "Put point at beginning of this element, mark at end.
24770 Interactively, if this command is repeated or (in Transient Mark
24771 mode) if the mark is active, it marks the next element after the
24772 ones already marked."
24773 (interactive)
24774 (let (deactivate-mark)
24775 (if (and (called-interactively-p 'any)
24776 (or (and (eq last-command this-command) (mark t))
24777 (and transient-mark-mode mark-active)))
24778 (set-mark
24779 (save-excursion
24780 (goto-char (mark))
24781 (goto-char (org-element-property :end (org-element-at-point)))))
24782 (let ((element (org-element-at-point)))
24783 (end-of-line)
24784 (push-mark (org-element-property :end element) t t)
24785 (goto-char (org-element-property :begin element))))))
24787 (defun org-narrow-to-element ()
24788 "Narrow buffer to current element."
24789 (interactive)
24790 (let ((elem (org-element-at-point)))
24791 (cond
24792 ((eq (car elem) 'headline)
24793 (narrow-to-region
24794 (org-element-property :begin elem)
24795 (org-element-property :end elem)))
24796 ((memq (car elem) org-element-greater-elements)
24797 (narrow-to-region
24798 (org-element-property :contents-begin elem)
24799 (org-element-property :contents-end elem)))
24801 (narrow-to-region
24802 (org-element-property :begin elem)
24803 (org-element-property :end elem))))))
24805 (defun org-transpose-element ()
24806 "Transpose current and previous elements, keeping blank lines between.
24807 Point is moved after both elements."
24808 (interactive)
24809 (org-skip-whitespace)
24810 (let ((end (org-element-property :end (org-element-at-point))))
24811 (org-drag-element-backward)
24812 (goto-char end)))
24814 (defun org-unindent-buffer ()
24815 "Un-indent the visible part of the buffer.
24816 Relative indentation (between items, inside blocks, etc.) isn't
24817 modified."
24818 (interactive)
24819 (unless (eq major-mode 'org-mode)
24820 (user-error "Cannot un-indent a buffer not in Org mode"))
24821 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24822 (unindent-tree
24823 (lambda (contents)
24824 (dolist (element (reverse contents))
24825 (if (memq (org-element-type element) '(headline section))
24826 (funcall unindent-tree (org-element-contents element))
24827 (save-excursion
24828 (save-restriction
24829 (narrow-to-region
24830 (org-element-property :begin element)
24831 (org-element-property :end element))
24832 (org-do-remove-indentation))))))))
24833 (funcall unindent-tree (org-element-contents parse-tree))))
24835 (defun org-show-children (&optional level)
24836 "Show all direct subheadings of this heading.
24837 Prefix arg LEVEL is how many levels below the current level
24838 should be shown. Default is enough to cause the following
24839 heading to appear."
24840 (interactive "p")
24841 ;; If `orgstruct-mode' is active, use the slower version.
24842 (if orgstruct-mode (call-interactively #'outline-show-children)
24843 (save-excursion
24844 (org-back-to-heading t)
24845 (let* ((current-level (funcall outline-level))
24846 (max-level (org-get-valid-level
24847 current-level
24848 (if level (prefix-numeric-value level) 1)))
24849 (end (save-excursion (org-end-of-subtree t t)))
24850 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24851 (past-first-child nil)
24852 ;; Make sure to skip inlinetasks.
24853 (re (format regexp-fmt
24854 current-level
24855 (cond
24856 ((not (featurep 'org-inlinetask)) "")
24857 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24859 (t (1- org-inlinetask-min-level))))))
24860 ;; Display parent heading.
24861 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24862 (forward-line)
24863 ;; Display children. First child may be deeper than expected
24864 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24865 ;; MAX-LEVEL accordingly.
24866 (while (re-search-forward re end t)
24867 (unless past-first-child
24868 (setq re (format regexp-fmt
24869 current-level
24870 (max (funcall outline-level) max-level)))
24871 (setq past-first-child t))
24872 (outline-flag-region
24873 (line-end-position 0) (line-end-position) nil))))))
24875 (defun org-show-subtree ()
24876 "Show everything after this heading at deeper levels."
24877 (interactive)
24878 (outline-flag-region
24879 (point)
24880 (save-excursion
24881 (org-end-of-subtree t t))
24882 nil))
24884 (defun org-show-entry ()
24885 "Show the body directly following this heading.
24886 Show the heading too, if it is currently invisible."
24887 (interactive)
24888 (save-excursion
24889 (ignore-errors
24890 (org-back-to-heading t)
24891 (outline-flag-region
24892 (max (point-min) (1- (point)))
24893 (save-excursion
24894 (if (re-search-forward
24895 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24896 (match-beginning 1)
24897 (point-max)))
24898 nil)
24899 (org-cycle-hide-drawers 'children))))
24901 (defun org-make-options-regexp (kwds &optional extra)
24902 "Make a regular expression for keyword lines.
24903 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24904 when non-nil, is a regexp matching keywords names."
24905 (concat "^[ \t]*#\\+\\("
24906 (regexp-opt kwds)
24907 (and extra (concat (and kwds "\\|") extra))
24908 "\\):[ \t]*\\(.*\\)"))
24910 ;;;; Integration with and fixes for other packages
24912 ;;; Imenu support
24914 (defvar-local org-imenu-markers nil
24915 "All markers currently used by Imenu.")
24917 (defun org-imenu-new-marker (&optional pos)
24918 "Return a new marker for use by Imenu, and remember the marker."
24919 (let ((m (make-marker)))
24920 (move-marker m (or pos (point)))
24921 (push m org-imenu-markers)
24924 (defun org-imenu-get-tree ()
24925 "Produce the index for Imenu."
24926 (dolist (x org-imenu-markers) (move-marker x nil))
24927 (setq org-imenu-markers nil)
24928 (let* ((case-fold-search nil)
24929 (n org-imenu-depth)
24930 (re (concat "^" (org-get-limited-outline-regexp)))
24931 (subs (make-vector (1+ n) nil))
24932 (last-level 0)
24933 m level head0 head)
24934 (org-with-wide-buffer
24935 (goto-char (point-max))
24936 (while (re-search-backward re nil t)
24937 (setq level (org-reduced-level (funcall outline-level)))
24938 (when (and (<= level n)
24939 (looking-at org-complex-heading-regexp)
24940 (setq head0 (match-string-no-properties 4)))
24941 (setq head (org-link-display-format head0)
24942 m (org-imenu-new-marker))
24943 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24944 (if (>= level last-level)
24945 (push (cons head m) (aref subs level))
24946 (push (cons head (aref subs (1+ level))) (aref subs level))
24947 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24948 (setq last-level level))))
24949 (aref subs 1)))
24951 (eval-after-load "imenu"
24952 '(progn
24953 (add-hook 'imenu-after-jump-hook
24954 (lambda ()
24955 (when (derived-mode-p 'org-mode)
24956 (org-show-context 'org-goto))))))
24958 (defun org-link-display-format (s)
24959 "Replace links in string S with their description.
24960 If there is no description, use the link target."
24961 (save-match-data
24962 (replace-regexp-in-string
24963 org-bracket-link-analytic-regexp
24964 (lambda (m)
24965 (if (match-end 5) (match-string 5 m)
24966 (concat (match-string 1 m) (match-string 3 m))))
24967 s nil t)))
24969 (defun org-toggle-link-display ()
24970 "Toggle the literal or descriptive display of links."
24971 (interactive)
24972 (if org-descriptive-links
24973 (progn (org-remove-from-invisibility-spec '(org-link))
24974 (org-restart-font-lock)
24975 (setq org-descriptive-links nil))
24976 (progn (add-to-invisibility-spec '(org-link))
24977 (org-restart-font-lock)
24978 (setq org-descriptive-links t))))
24980 ;; Speedbar support
24982 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24983 "Overlay marking the agenda restriction line in speedbar.")
24984 (overlay-put org-speedbar-restriction-lock-overlay
24985 'face 'org-agenda-restriction-lock)
24986 (overlay-put org-speedbar-restriction-lock-overlay
24987 'help-echo "Agendas are currently limited to this item.")
24988 (delete-overlay org-speedbar-restriction-lock-overlay)
24990 (defun org-speedbar-set-agenda-restriction ()
24991 "Restrict future agenda commands to the location at point in speedbar.
24992 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24993 (interactive)
24994 (require 'org-agenda)
24995 (let (p m tp np dir txt)
24996 (cond
24997 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24998 'org-imenu t))
24999 (setq m (get-text-property p 'org-imenu-marker))
25000 (with-current-buffer (marker-buffer m)
25001 (goto-char m)
25002 (org-agenda-set-restriction-lock 'subtree)))
25003 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25004 'speedbar-function 'speedbar-find-file))
25005 (setq tp (previous-single-property-change
25006 (1+ p) 'speedbar-function)
25007 np (next-single-property-change
25008 tp 'speedbar-function)
25009 dir (speedbar-line-directory)
25010 txt (buffer-substring-no-properties (or tp (point-min))
25011 (or np (point-max))))
25012 (with-current-buffer (find-file-noselect
25013 (let ((default-directory dir))
25014 (expand-file-name txt)))
25015 (unless (derived-mode-p 'org-mode)
25016 (user-error "Cannot restrict to non-Org mode file"))
25017 (org-agenda-set-restriction-lock 'file)))
25018 (t (user-error "Don't know how to restrict Org mode agenda")))
25019 (move-overlay org-speedbar-restriction-lock-overlay
25020 (point-at-bol) (point-at-eol))
25021 (setq current-prefix-arg nil)
25022 (org-agenda-maybe-redo)))
25024 (defvar speedbar-file-key-map)
25025 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25026 (eval-after-load "speedbar"
25027 '(progn
25028 (speedbar-add-supported-extension ".org")
25029 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25030 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25031 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25032 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25033 (add-hook 'speedbar-visiting-tag-hook
25034 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25036 ;;; Fixes and Hacks for problems with other packages
25038 (defun org--flyspell-object-check-p (element)
25039 "Non-nil when Flyspell can check object at point.
25040 ELEMENT is the element at point."
25041 (let ((object (save-excursion
25042 (when (looking-at-p "\\>") (backward-char))
25043 (org-element-context element))))
25044 (cl-case (org-element-type object)
25045 ;; Prevent checks in links due to keybinding conflict with
25046 ;; Flyspell.
25047 ((code entity export-snippet inline-babel-call
25048 inline-src-block line-break latex-fragment link macro
25049 statistics-cookie target timestamp verbatim)
25050 nil)
25051 (footnote-reference
25052 ;; Only in inline footnotes, within the definition.
25053 (and (eq (org-element-property :type object) 'inline)
25054 (< (save-excursion
25055 (goto-char (org-element-property :begin object))
25056 (search-forward ":" nil t 2))
25057 (point))))
25058 (otherwise t))))
25060 (defun org-mode-flyspell-verify ()
25061 "Function used for `flyspell-generic-check-word-predicate'."
25062 (if (org-at-heading-p)
25063 ;; At a headline or an inlinetask, check title only. This is
25064 ;; faster than relying on `org-element-at-point'.
25065 (and (save-excursion (beginning-of-line)
25066 (and (let ((case-fold-search t))
25067 (not (looking-at-p "\\*+ END[ \t]*$")))
25068 (let ((case-fold-search nil))
25069 (looking-at org-complex-heading-regexp))))
25070 (match-beginning 4)
25071 (>= (point) (match-beginning 4))
25072 (or (not (match-beginning 5))
25073 (< (point) (match-beginning 5))))
25074 (let* ((element (org-element-at-point))
25075 (post-affiliated (org-element-property :post-affiliated element)))
25076 (cond
25077 ;; Ignore checks in all affiliated keywords but captions.
25078 ((< (point) post-affiliated)
25079 (and (save-excursion
25080 (beginning-of-line)
25081 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25082 (> (point) (match-end 0))
25083 (org--flyspell-object-check-p element)))
25084 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25085 ((let ((log (org-log-into-drawer)))
25086 (and log
25087 (let ((drawer (org-element-lineage element '(drawer))))
25088 (and drawer
25089 (eq (compare-strings
25090 log nil nil
25091 (org-element-property :drawer-name drawer) nil nil t)
25092 t)))))
25093 nil)
25095 (cl-case (org-element-type element)
25096 ((comment quote-section) t)
25097 (comment-block
25098 ;; Allow checks between block markers, not on them.
25099 (and (> (line-beginning-position) post-affiliated)
25100 (save-excursion
25101 (end-of-line)
25102 (skip-chars-forward " \r\t\n")
25103 (< (point) (org-element-property :end element)))))
25104 ;; Arbitrary list of keywords where checks are meaningful.
25105 ;; Make sure point is on the value part of the element.
25106 (keyword
25107 (and (member (org-element-property :key element)
25108 '("DESCRIPTION" "TITLE"))
25109 (save-excursion
25110 (search-backward ":" (line-beginning-position) t))))
25111 ;; Check is globally allowed in paragraphs verse blocks and
25112 ;; table rows (after affiliated keywords) but some objects
25113 ;; must not be affected.
25114 ((paragraph table-row verse-block)
25115 (let ((cbeg (org-element-property :contents-begin element))
25116 (cend (org-element-property :contents-end element)))
25117 (and cbeg (>= (point) cbeg) (< (point) cend)
25118 (org--flyspell-object-check-p element))))))))))
25119 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25121 (defun org-remove-flyspell-overlays-in (beg end)
25122 "Remove flyspell overlays in region."
25123 (and (bound-and-true-p flyspell-mode)
25124 (fboundp 'flyspell-delete-region-overlays)
25125 (flyspell-delete-region-overlays beg end)))
25127 (defvar flyspell-delayed-commands)
25128 (eval-after-load "flyspell"
25129 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25131 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25132 (eval-after-load "bookmark"
25133 '(if (boundp 'bookmark-after-jump-hook)
25134 ;; We can use the hook
25135 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25136 ;; Hook not available, use advice
25137 (defadvice bookmark-jump (after org-make-visible activate)
25138 "Make the position visible."
25139 (org-bookmark-jump-unhide))))
25141 ;; Make sure saveplace shows the location if it was hidden
25142 (eval-after-load "saveplace"
25143 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25144 "Make the position visible."
25145 (org-bookmark-jump-unhide)))
25147 ;; Make sure ecb shows the location if it was hidden
25148 (eval-after-load "ecb"
25149 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25150 "Make hierarchy visible when jumping into location from ECB tree buffer."
25151 (when (derived-mode-p 'org-mode)
25152 (org-show-context))))
25154 (defun org-bookmark-jump-unhide ()
25155 "Unhide the current position, to show the bookmark location."
25156 (and (derived-mode-p 'org-mode)
25157 (or (outline-invisible-p)
25158 (save-excursion (goto-char (max (point-min) (1- (point))))
25159 (outline-invisible-p)))
25160 (org-show-context 'bookmark-jump)))
25162 (defun org-mark-jump-unhide ()
25163 "Make the point visible with `org-show-context' after jumping to the mark."
25164 (when (and (derived-mode-p 'org-mode)
25165 (outline-invisible-p))
25166 (org-show-context 'mark-goto)))
25168 (eval-after-load "simple"
25169 '(defadvice pop-to-mark-command (after org-make-visible activate)
25170 "Make the point visible with `org-show-context'."
25171 (org-mark-jump-unhide)))
25173 (eval-after-load "simple"
25174 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25175 "Make the point visible with `org-show-context'."
25176 (org-mark-jump-unhide)))
25178 (eval-after-load "simple"
25179 '(defadvice pop-global-mark (after org-make-visible activate)
25180 "Make the point visible with `org-show-context'."
25181 (org-mark-jump-unhide)))
25183 ;; Make session.el ignore our circular variable
25184 (defvar session-globals-exclude)
25185 (eval-after-load "session"
25186 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25188 ;;;; Finish up
25190 (provide 'org)
25192 (run-hooks 'org-load-hook)
25194 ;;; org.el ends here