Fix: Prevent spurious newlines when inserting a new heading
[org-mode.git] / lisp / org.el
blob3290a2b961d4ef0def2d39837ac54021f13cdbe9
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocktable-shift "org-clock" (dir n))
132 (declare-function org-element-at-point "org-element" ())
133 (declare-function org-element-cache-refresh "org-element" (pos))
134 (declare-function org-element-cache-reset "org-element" (&optional all))
135 (declare-function org-element-contents "org-element" (element))
136 (declare-function org-element-context "org-element" (&optional element))
137 (declare-function org-element-copy "org-element" (datum))
138 (declare-function org-element-interpret-data "org-element" (data))
139 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
140 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
141 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
142 (declare-function org-element-property "org-element" (property element))
143 (declare-function org-element-put-property "org-element" (element property value))
144 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
145 (declare-function org-element-type "org-element" (element))
146 (declare-function org-element-update-syntax "org-element" ())
147 (declare-function org-id-find-id-file "org-id" (id))
148 (declare-function org-id-get-create "org-id" (&optional force))
149 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
150 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
151 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
152 (declare-function org-plot/gnuplot "org-plot" (&optional params))
153 (declare-function org-table-align "org-table" ())
154 (declare-function org-table-begin "org-table" (&optional table-type))
155 (declare-function org-table-beginning-of-field "org-table" (&optional n))
156 (declare-function org-table-blank-field "org-table" ())
157 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
158 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
159 (declare-function org-table-cut-region "org-table" (beg end))
160 (declare-function org-table-edit-field "org-table" (arg))
161 (declare-function org-table-end "org-table" (&optional table-type))
162 (declare-function org-table-end-of-field "org-table" (&optional n))
163 (declare-function org-table-insert-row "org-table" (&optional arg))
164 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
165 (declare-function org-table-maybe-eval-formula "org-table" ())
166 (declare-function org-table-maybe-recalculate-line "org-table" ())
167 (declare-function org-table-next-row "org-table" ())
168 (declare-function org-table-paste-rectangle "org-table" ())
169 (declare-function org-table-recalculate "org-table" (&optional all noalign))
170 (declare-function org-table-wrap-region "org-table" (arg))
171 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
172 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
173 (declare-function orgtbl-mode "org-table" (&optional arg))
174 (declare-function org-export-get-backend "ox" (name))
175 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
176 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
178 (defsubst org-uniquify (list)
179 "Non-destructively remove duplicate elements from LIST."
180 (let ((res (copy-sequence list))) (delete-dups res)))
182 (defsubst org-get-at-bol (property)
183 "Get text property PROPERTY at the beginning of line."
184 (get-text-property (point-at-bol) property))
186 (defsubst org-trim (s &optional keep-lead)
187 "Remove whitespace at the beginning and the end of string S.
188 When optional argument KEEP-LEAD is non-nil, removing blank lines
189 at the beginning of the string does not affect leading indentation."
190 (replace-regexp-in-string
191 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
192 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
194 ;; load languages based on value of `org-babel-load-languages'
195 (defvar org-babel-load-languages)
197 ;;;###autoload
198 (defun org-babel-do-load-languages (sym value)
199 "Load the languages defined in `org-babel-load-languages'."
200 (set-default sym value)
201 (dolist (pair org-babel-load-languages)
202 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
203 (if active
204 (require (intern (concat "ob-" lang)))
205 (funcall 'fmakunbound
206 (intern (concat "org-babel-execute:" lang)))
207 (funcall 'fmakunbound
208 (intern (concat "org-babel-expand-body:" lang)))))))
210 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
211 ;;;###autoload
212 (defun org-babel-load-file (file &optional compile)
213 "Load Emacs Lisp source code blocks in the Org FILE.
214 This function exports the source code using `org-babel-tangle'
215 and then loads the resulting file using `load-file'. With prefix
216 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
217 file to byte-code before it is loaded."
218 (interactive "fFile to load: \nP")
219 (let* ((age (lambda (file)
220 (float-time
221 (time-subtract (current-time)
222 (nth 5 (or (file-attributes (file-truename file))
223 (file-attributes file)))))))
224 (base-name (file-name-sans-extension file))
225 (exported-file (concat base-name ".el")))
226 ;; tangle if the Org file is newer than the elisp file
227 (unless (and (file-exists-p exported-file)
228 (> (funcall age file) (funcall age exported-file)))
229 ;; Tangle-file traversal returns reversed list of tangled files
230 ;; and we want to evaluate the first target.
231 (setq exported-file
232 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
233 (message "%s %s"
234 (if compile
235 (progn (byte-compile-file exported-file 'load)
236 "Compiled and loaded")
237 (progn (load-file exported-file) "Loaded"))
238 exported-file)))
240 (defcustom org-babel-load-languages '((emacs-lisp . t))
241 "Languages which can be evaluated in Org buffers.
242 This list can be used to load support for any of the languages
243 below, note that each language will depend on a different set of
244 system executables and/or Emacs modes. When a language is
245 \"loaded\", then code blocks in that language can be evaluated
246 with `org-babel-execute-src-block' bound by default to C-c
247 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
248 be set to remove code block evaluation from the C-c C-c
249 keybinding. By default only Emacs Lisp (which has no
250 requirements) is loaded."
251 :group 'org-babel
252 :set 'org-babel-do-load-languages
253 :version "24.1"
254 :type '(alist :tag "Babel Languages"
255 :key-type
256 (choice
257 (const :tag "Awk" awk)
258 (const :tag "C" C)
259 (const :tag "R" R)
260 (const :tag "Asymptote" asymptote)
261 (const :tag "Calc" calc)
262 (const :tag "Clojure" clojure)
263 (const :tag "CSS" css)
264 (const :tag "Ditaa" ditaa)
265 (const :tag "Dot" dot)
266 (const :tag "Emacs Lisp" emacs-lisp)
267 (const :tag "Forth" forth)
268 (const :tag "Fortran" fortran)
269 (const :tag "Gnuplot" gnuplot)
270 (const :tag "Haskell" haskell)
271 (const :tag "IO" io)
272 (const :tag "J" J)
273 (const :tag "Java" java)
274 (const :tag "Javascript" js)
275 (const :tag "LaTeX" latex)
276 (const :tag "Ledger" ledger)
277 (const :tag "Lilypond" lilypond)
278 (const :tag "Lisp" lisp)
279 (const :tag "Makefile" makefile)
280 (const :tag "Maxima" maxima)
281 (const :tag "Matlab" matlab)
282 (const :tag "Mscgen" mscgen)
283 (const :tag "Ocaml" ocaml)
284 (const :tag "Octave" octave)
285 (const :tag "Org" org)
286 (const :tag "Perl" perl)
287 (const :tag "Pico Lisp" picolisp)
288 (const :tag "PlantUML" plantuml)
289 (const :tag "Python" python)
290 (const :tag "Ruby" ruby)
291 (const :tag "Sass" sass)
292 (const :tag "Scala" scala)
293 (const :tag "Scheme" scheme)
294 (const :tag "Screen" screen)
295 (const :tag "Shell Script" shell)
296 (const :tag "Shen" shen)
297 (const :tag "Sql" sql)
298 (const :tag "Sqlite" sqlite)
299 (const :tag "Stan" stan)
300 (const :tag "ebnf2ps" ebnf2ps))
301 :value-type (boolean :tag "Activate" :value t)))
303 ;;;; Customization variables
304 (defcustom org-clone-delete-id nil
305 "Remove ID property of clones of a subtree.
306 When non-nil, clones of a subtree don't inherit the ID property.
307 Otherwise they inherit the ID property with a new unique
308 identifier."
309 :type 'boolean
310 :version "24.1"
311 :group 'org-id)
313 ;;; Version
314 (org-check-version)
316 ;;;###autoload
317 (defun org-version (&optional here full message)
318 "Show the Org version.
319 Interactively, or when MESSAGE is non-nil, show it in echo area.
320 With prefix argument, or when HERE is non-nil, insert it at point.
321 In non-interactive uses, a reduced version string is output unless
322 FULL is given."
323 (interactive (list current-prefix-arg t (not current-prefix-arg)))
324 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
325 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
326 (load-suffixes (list ".el"))
327 (org-install-dir
328 (ignore-errors (org-find-library-dir "org-loaddefs"))))
329 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
330 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
331 (let* ((load-suffixes save-load-suffixes)
332 (release (org-release))
333 (git-version (org-git-version))
334 (version (format "Org mode version %s (%s @ %s)"
335 release
336 git-version
337 (if org-install-dir
338 (if (string= org-dir org-install-dir)
339 org-install-dir
340 (concat "mixed installation! "
341 org-install-dir
342 " and "
343 org-dir))
344 "org-loaddefs.el can not be found!")))
345 (version1 (if full version release)))
346 (when here (insert version1))
347 (when message (message "%s" version1))
348 version1)))
350 (defconst org-version (org-version))
353 ;;; Syntax Constants
355 ;;;; Block
357 (defconst org-block-regexp
358 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
359 "Regular expression for hiding blocks.")
361 (defconst org-dblock-start-re
362 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
363 "Matches the start line of a dynamic block, with parameters.")
365 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
366 "Matches the end of a dynamic block.")
368 ;;;; Clock and Planning
370 (defconst org-clock-string "CLOCK:"
371 "String used as prefix for timestamps clocking work hours on an item.")
373 (defvar org-closed-string "CLOSED:"
374 "String used as the prefix for timestamps logging closing a TODO entry.")
376 (defvar org-deadline-string "DEADLINE:"
377 "String to mark deadline entries.
378 \\<org-mode-map>
379 A deadline is this string, followed by a time stamp. It must be
380 a word, terminated by a colon. You can insert a schedule keyword
381 and a timestamp with `\\[org-deadline]'.")
383 (defvar org-scheduled-string "SCHEDULED:"
384 "String to mark scheduled TODO entries.
385 \\<org-mode-map>
386 A schedule is this string, followed by a time stamp. It must be
387 a word, terminated by a colon. You can insert a schedule keyword
388 and a timestamp with `\\[org-schedule]'.")
390 (defconst org-ds-keyword-length
391 (+ 2
392 (apply #'max
393 (mapcar #'length
394 (list org-deadline-string org-scheduled-string
395 org-clock-string org-closed-string))))
396 "Maximum length of the DEADLINE and SCHEDULED keywords.")
398 (defconst org-planning-line-re
399 (concat "^[ \t]*"
400 (regexp-opt
401 (list org-closed-string org-deadline-string org-scheduled-string)
403 "Matches a line with planning info.
404 Matched keyword is in group 1.")
406 (defconst org-clock-line-re
407 (concat "^[ \t]*" org-clock-string)
408 "Matches a line with clock info.")
410 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
411 "Matches the DEADLINE keyword.")
413 (defconst org-deadline-time-regexp
414 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
415 "Matches the DEADLINE keyword together with a time stamp.")
417 (defconst org-deadline-time-hour-regexp
418 (concat "\\<" org-deadline-string
419 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
420 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
422 (defconst org-deadline-line-regexp
423 (concat "\\<\\(" org-deadline-string "\\).*")
424 "Matches the DEADLINE keyword and the rest of the line.")
426 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
427 "Matches the SCHEDULED keyword.")
429 (defconst org-scheduled-time-regexp
430 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
431 "Matches the SCHEDULED keyword together with a time stamp.")
433 (defconst org-scheduled-time-hour-regexp
434 (concat "\\<" org-scheduled-string
435 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
436 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
438 (defconst org-closed-time-regexp
439 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
440 "Matches the CLOSED keyword together with a time stamp.")
442 (defconst org-keyword-time-regexp
443 (concat "\\<"
444 (regexp-opt
445 (list org-scheduled-string org-deadline-string org-closed-string
446 org-clock-string)
448 " *[[<]\\([^]>]+\\)[]>]")
449 "Matches any of the 4 keywords, together with the time stamp.")
451 (defconst org-keyword-time-not-clock-regexp
452 (concat
453 "\\<"
454 (regexp-opt
455 (list org-scheduled-string org-deadline-string org-closed-string) t)
456 " *[[<]\\([^]>]+\\)[]>]")
457 "Matches any of the 3 keywords, together with the time stamp.")
459 (defconst org-maybe-keyword-time-regexp
460 (concat "\\(\\<"
461 (regexp-opt
462 (list org-scheduled-string org-deadline-string org-closed-string
463 org-clock-string)
465 "\\)?"
466 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
467 "\\|"
468 "<%%([^\r\n>]*>\\)")
469 "Matches a timestamp, possibly preceded by a keyword.")
471 (defconst org-all-time-keywords
472 (mapcar (lambda (w) (substring w 0 -1))
473 (list org-scheduled-string org-deadline-string
474 org-clock-string org-closed-string))
475 "List of time keywords.")
477 ;;;; Drawer
479 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
480 "Matches first or last line of a hidden block.
481 Group 1 contains drawer's name or \"END\".")
483 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
484 "Regular expression matching the first line of a property drawer.")
486 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
487 "Regular expression matching the last line of a property drawer.")
489 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
490 "Regular expression matching the first line of a clock drawer.")
492 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
493 "Regular expression matching the last line of a clock drawer.")
495 (defconst org-property-drawer-re
496 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
497 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
498 "[ \t]*:END:[ \t]*$")
499 "Matches an entire property drawer.")
501 (defconst org-clock-drawer-re
502 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
503 org-clock-drawer-end-re "\\)\n?")
504 "Matches an entire clock drawer.")
506 ;;;; Headline
508 (defconst org-heading-keyword-regexp-format
509 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
510 "Printf format for a regexp matching a headline with some keyword.
511 This regexp will match the headline of any node which has the
512 exact keyword that is put into the format. The keyword isn't in
513 any group by default, but the stars and the body are.")
515 (defconst org-heading-keyword-maybe-regexp-format
516 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
517 "Printf format for a regexp matching a headline, possibly with some keyword.
518 This regexp can match any headline with the specified keyword, or
519 without a keyword. The keyword isn't in any group by default,
520 but the stars and the body are.")
522 (defconst org-archive-tag "ARCHIVE"
523 "The tag that marks a subtree as archived.
524 An archived subtree does not open during visibility cycling, and does
525 not contribute to the agenda listings.")
527 (defconst org-comment-string "COMMENT"
528 "Entries starting with this keyword will never be exported.
529 \\<org-mode-map>
530 An entry can be toggled between COMMENT and normal with
531 `\\[org-toggle-comment]'.")
534 ;;;; LaTeX Environments and Fragments
536 (defconst org-latex-regexps
537 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
538 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
539 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
540 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
541 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
542 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
543 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
544 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
545 "Regular expressions for matching embedded LaTeX.")
547 ;;;; Node Property
549 (defconst org-effort-property "Effort"
550 "The property that is being used to keep track of effort estimates.
551 Effort estimates given in this property need to have the format H:MM.")
553 ;;;; Table
555 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
556 "Detect an org-type or table-type table.")
558 (defconst org-table-line-regexp "^[ \t]*|"
559 "Detect an org-type table line.")
561 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
562 "Detect an org-type table line.")
564 (defconst org-table-hline-regexp "^[ \t]*|-"
565 "Detect an org-type table hline.")
567 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
568 "Detect a table-type table hline.")
570 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
571 "Detect the first line outside a table when searching from within it.
572 This works for both table types.")
574 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
575 "Detect a #+TBLFM line.")
577 ;;;; Timestamp
579 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
580 "Regular expression for fast time stamp matching.")
582 (defconst org-ts-regexp-inactive
583 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
584 "Regular expression for fast inactive time stamp matching.")
586 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
587 "Regular expression for fast time stamp matching.")
589 (defconst org-ts-regexp0
590 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
591 "Regular expression matching time strings for analysis.
592 This one does not require the space after the date, so it can be used
593 on a string that terminates immediately after the date.")
595 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
596 "Regular expression matching time strings for analysis.")
598 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
599 "Regular expression matching time stamps, with groups.")
601 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
602 "Regular expression matching time stamps (also [..]), with groups.")
604 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
605 "Regular expression matching a time stamp range.")
607 (defconst org-tr-regexp-both
608 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
609 "Regular expression matching a time stamp range.")
611 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
612 org-ts-regexp "\\)?")
613 "Regular expression matching a time stamp or time stamp range.")
615 (defconst org-tsr-regexp-both
616 (concat org-ts-regexp-both "\\(--?-?"
617 org-ts-regexp-both "\\)?")
618 "Regular expression matching a time stamp or time stamp range.
619 The time stamps may be either active or inactive.")
621 (defconst org-repeat-re
622 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
623 "Regular expression for specifying repeated events.
624 After a match, group 1 contains the repeat expression.")
626 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
627 "Formats for `format-time-string' which are used for time stamps.")
630 ;;; The custom variables
632 (defgroup org nil
633 "Outline-based notes management and organizer."
634 :tag "Org"
635 :group 'outlines
636 :group 'calendar)
638 (defcustom org-mode-hook nil
639 "Mode hook for Org mode, run after the mode was turned on."
640 :group 'org
641 :type 'hook)
643 (defcustom org-load-hook nil
644 "Hook that is run after org.el has been loaded."
645 :group 'org
646 :type 'hook)
648 (defcustom org-log-buffer-setup-hook nil
649 "Hook that is run after an Org log buffer is created."
650 :group 'org
651 :version "24.1"
652 :type 'hook)
654 (defvar org-modules) ; defined below
655 (defvar org-modules-loaded nil
656 "Have the modules been loaded already?")
658 (defun org-load-modules-maybe (&optional force)
659 "Load all extensions listed in `org-modules'."
660 (when (or force (not org-modules-loaded))
661 (dolist (ext org-modules)
662 (condition-case nil (require ext)
663 (error (message "Problems while trying to load feature `%s'" ext))))
664 (setq org-modules-loaded t)))
666 (defun org-set-modules (var value)
667 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
668 (set var value)
669 (when (featurep 'org)
670 (org-load-modules-maybe 'force)
671 (org-element-cache-reset 'all)))
673 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
674 "Modules that should always be loaded together with org.el.
676 If a description starts with <C>, the file is not part of Emacs
677 and loading it will require that you have downloaded and properly
678 installed the Org mode distribution.
680 You can also use this system to load external packages (i.e. neither Org
681 core modules, nor modules from the CONTRIB directory). Just add symbols
682 to the end of the list. If the package is called org-xyz.el, then you need
683 to add the symbol `xyz', and the package must have a call to:
685 (provide \\='org-xyz)
687 For export specific modules, see also `org-export-backends'."
688 :group 'org
689 :set 'org-set-modules
690 :version "24.4"
691 :package-version '(Org . "8.0")
692 :type
693 '(set :greedy t
694 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
695 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
696 (const :tag " crypt: Encryption of subtrees" org-crypt)
697 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
698 (const :tag " docview: Links to doc-view buffers" org-docview)
699 (const :tag " eww: Store link to url of eww" org-eww)
700 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
701 (const :tag " habit: Track your consistency with habits" org-habit)
702 (const :tag " id: Global IDs for identifying entries" org-id)
703 (const :tag " info: Links to Info nodes" org-info)
704 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
705 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
706 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
707 (const :tag " mouse: Additional mouse support" org-mouse)
708 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
709 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
710 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
712 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
713 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
714 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
715 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
716 (const :tag "C collector: Collect properties into tables" org-collector)
717 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
718 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
719 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
720 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
721 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
722 (const :tag "C eval: Include command output as text" org-eval)
723 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
724 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
725 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
726 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
727 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
728 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
729 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
730 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
731 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
732 (const :tag "C man: Support for links to manpages in Org mode" org-man)
733 (const :tag "C mew: Links to Mew folders/messages" org-mew)
734 (const :tag "C mtags: Support for muse-like tags" org-mtags)
735 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
736 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
737 (const :tag "C registry: A registry for Org links" org-registry)
738 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
739 (const :tag "C secretary: Team management with org-mode" org-secretary)
740 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
741 (const :tag "C toc: Table of contents for Org buffer" org-toc)
742 (const :tag "C track: Keep up with Org mode development" org-track)
743 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
744 (const :tag "C vm: Links to VM folders/messages" org-vm)
745 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
746 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
747 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
749 (defvar org-export-registered-backends) ; From ox.el.
750 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
751 (declare-function org-export-backend-name "ox" (backend) t)
752 (defcustom org-export-backends '(ascii html icalendar latex odt)
753 "List of export back-ends that should be always available.
755 If a description starts with <C>, the file is not part of Emacs
756 and loading it will require that you have downloaded and properly
757 installed the Org mode distribution.
759 Unlike to `org-modules', libraries in this list will not be
760 loaded along with Org, but only once the export framework is
761 needed.
763 This variable needs to be set before org.el is loaded. If you
764 need to make a change while Emacs is running, use the customize
765 interface or run the following code, where VAL stands for the new
766 value of the variable, after updating it:
768 (progn
769 (setq org-export-registered-backends
770 (cl-remove-if-not
771 (lambda (backend)
772 (let ((name (org-export-backend-name backend)))
773 (or (memq name val)
774 (catch \\='parentp
775 (dolist (b val)
776 (and (org-export-derived-backend-p b name)
777 (throw \\='parentp t)))))))
778 org-export-registered-backends))
779 (let ((new-list (mapcar #\\='org-export-backend-name
780 org-export-registered-backends)))
781 (dolist (backend val)
782 (cond
783 ((not (load (format \"ox-%s\" backend) t t))
784 (message \"Problems while trying to load export back-end \\=`%s\\='\"
785 backend))
786 ((not (memq backend new-list)) (push backend new-list))))
787 (set-default \\='org-export-backends new-list)))
789 Adding a back-end to this list will also pull the back-end it
790 depends on, if any."
791 :group 'org
792 :group 'org-export
793 :version "26.1"
794 :package-version '(Org . "9.0")
795 :initialize 'custom-initialize-set
796 :set (lambda (var val)
797 (if (not (featurep 'ox)) (set-default var val)
798 ;; Any back-end not required anymore (not present in VAL and not
799 ;; a parent of any back-end in the new value) is removed from the
800 ;; list of registered back-ends.
801 (setq org-export-registered-backends
802 (cl-remove-if-not
803 (lambda (backend)
804 (let ((name (org-export-backend-name backend)))
805 (or (memq name val)
806 (catch 'parentp
807 (dolist (b val)
808 (and (org-export-derived-backend-p b name)
809 (throw 'parentp t)))))))
810 org-export-registered-backends))
811 ;; Now build NEW-LIST of both new back-ends and required
812 ;; parents.
813 (let ((new-list (mapcar #'org-export-backend-name
814 org-export-registered-backends)))
815 (dolist (backend val)
816 (cond
817 ((not (load (format "ox-%s" backend) t t))
818 (message "Problems while trying to load export back-end `%s'"
819 backend))
820 ((not (memq backend new-list)) (push backend new-list))))
821 ;; Set VAR to that list with fixed dependencies.
822 (set-default var new-list))))
823 :type '(set :greedy t
824 (const :tag " ascii Export buffer to ASCII format" ascii)
825 (const :tag " beamer Export buffer to Beamer presentation" beamer)
826 (const :tag " html Export buffer to HTML format" html)
827 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
828 (const :tag " latex Export buffer to LaTeX format" latex)
829 (const :tag " man Export buffer to MAN format" man)
830 (const :tag " md Export buffer to Markdown format" md)
831 (const :tag " odt Export buffer to ODT format" odt)
832 (const :tag " org Export buffer to Org format" org)
833 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
834 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
835 (const :tag "C deck Export buffer to deck.js presentations" deck)
836 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
837 (const :tag "C groff Export buffer to Groff format" groff)
838 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
839 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
840 (const :tag "C s5 Export buffer to s5 presentations" s5)
841 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
843 (eval-after-load 'ox
844 '(dolist (backend org-export-backends)
845 (condition-case nil (require (intern (format "ox-%s" backend)))
846 (error (message "Problems while trying to load export back-end `%s'"
847 backend)))))
849 (defcustom org-support-shift-select nil
850 "Non-nil means make shift-cursor commands select text when possible.
851 \\<org-mode-map>\
853 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
854 start selecting a region, or enlarge regions started in this way.
855 In Org mode, in special contexts, these same keys are used for
856 other purposes, important enough to compete with shift selection.
857 Org tries to balance these needs by supporting `shift-select-mode'
858 outside these special contexts, under control of this variable.
860 The default of this variable is nil, to avoid confusing behavior. Shifted
861 cursor keys will then execute Org commands in the following contexts:
862 - on a headline, changing TODO state (left/right) and priority (up/down)
863 - on a time stamp, changing the time
864 - in a plain list item, changing the bullet type
865 - in a property definition line, switching between allowed values
866 - in the BEGIN line of a clock table (changing the time block).
867 Outside these contexts, the commands will throw an error.
869 When this variable is t and the cursor is not in a special
870 context, Org mode will support shift-selection for making and
871 enlarging regions. To make this more effective, the bullet
872 cycling will no longer happen anywhere in an item line, but only
873 if the cursor is exactly on the bullet.
875 If you set this variable to the symbol `always', then the keys
876 will not be special in headlines, property lines, and item lines,
877 to make shift selection work there as well. If this is what you
878 want, you can use the following alternative commands:
879 `\\[org-todo]' and `\\[org-priority]' \
880 to change TODO state and priority,
881 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
882 can be used to switch TODO sets,
883 `\\[org-ctrl-c-minus]' to cycle item bullet types,
884 and properties can be edited by hand or in column view.
886 However, when the cursor is on a timestamp, shift-cursor commands
887 will still edit the time stamp - this is just too good to give up."
888 :group 'org
889 :type '(choice
890 (const :tag "Never" nil)
891 (const :tag "When outside special context" t)
892 (const :tag "Everywhere except timestamps" always)))
894 (defcustom org-loop-over-headlines-in-active-region nil
895 "Shall some commands act upon headlines in the active region?
897 When set to t, some commands will be performed in all headlines
898 within the active region.
900 When set to `start-level', some commands will be performed in all
901 headlines within the active region, provided that these headlines
902 are of the same level than the first one.
904 When set to a string, those commands will be performed on the
905 matching headlines within the active region. Such string must be
906 a tags/property/todo match as it is used in the agenda tags view.
908 The list of commands is: `org-schedule', `org-deadline',
909 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
910 `org-archive-to-archive-sibling'. The archiving commands skip
911 already archived entries."
912 :type '(choice (const :tag "Don't loop" nil)
913 (const :tag "All headlines in active region" t)
914 (const :tag "In active region, headlines at the same level than the first one" start-level)
915 (string :tag "Tags/Property/Todo matcher"))
916 :version "24.1"
917 :group 'org-todo
918 :group 'org-archive)
920 (defgroup org-startup nil
921 "Options concerning startup of Org mode."
922 :tag "Org Startup"
923 :group 'org)
925 (defcustom org-startup-folded t
926 "Non-nil means entering Org mode will switch to OVERVIEW.
928 This can also be configured on a per-file basis by adding one of
929 the following lines anywhere in the buffer:
931 #+STARTUP: fold (or `overview', this is equivalent)
932 #+STARTUP: nofold (or `showall', this is equivalent)
933 #+STARTUP: content
934 #+STARTUP: showeverything
936 Set `org-agenda-inhibit-startup' to a non-nil value if you want
937 to ignore this option when Org opens agenda files for the first
938 time."
939 :group 'org-startup
940 :type '(choice
941 (const :tag "nofold: show all" nil)
942 (const :tag "fold: overview" t)
943 (const :tag "content: all headlines" content)
944 (const :tag "show everything, even drawers" showeverything)))
946 (defcustom org-startup-truncated t
947 "Non-nil means entering Org mode will set `truncate-lines'.
948 This is useful since some lines containing links can be very long and
949 uninteresting. Also tables look terrible when wrapped.
951 The variable `org-startup-truncated' allows to configure
952 truncation for Org mode different to the other modes that use the
953 variable `truncate-lines' and as a shortcut instead of putting
954 the variable `truncate-lines' into the `org-mode-hook'. If one
955 wants to configure truncation for Org mode not statically but
956 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
957 the variable `truncate-lines' has to be used because in such a
958 case it is too late to set the variable `org-startup-truncated'."
959 :group 'org-startup
960 :type 'boolean)
962 (defcustom org-startup-indented nil
963 "Non-nil means turn on `org-indent-mode' on startup.
964 This can also be configured on a per-file basis by adding one of
965 the following lines anywhere in the buffer:
967 #+STARTUP: indent
968 #+STARTUP: noindent"
969 :group 'org-structure
970 :type '(choice
971 (const :tag "Not" nil)
972 (const :tag "Globally (slow on startup in large files)" t)))
974 (defcustom org-use-sub-superscripts t
975 "Non-nil means interpret \"_\" and \"^\" for display.
977 If you want to control how Org exports those characters, see
978 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
979 used to be an alias for `org-export-with-sub-superscripts' in
980 Org <8.0, it is not anymore.
982 When this option is turned on, you can use TeX-like syntax for
983 sub- and superscripts within the buffer. Several characters after
984 \"_\" or \"^\" will be considered as a single item - so grouping
985 with {} is normally not needed. For example, the following things
986 will be parsed as single sub- or superscripts:
988 10^24 or 10^tau several digits will be considered 1 item.
989 10^-12 or 10^-tau a leading sign with digits or a word
990 x^2-y^3 will be read as x^2 - y^3, because items are
991 terminated by almost any nonword/nondigit char.
992 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
994 Still, ambiguity is possible. So when in doubt, use {} to enclose
995 the sub/superscript. If you set this variable to the symbol `{}',
996 the braces are *required* in order to trigger interpretations as
997 sub/superscript. This can be helpful in documents that need \"_\"
998 frequently in plain text."
999 :group 'org-startup
1000 :version "24.4"
1001 :package-version '(Org . "8.0")
1002 :type '(choice
1003 (const :tag "Always interpret" t)
1004 (const :tag "Only with braces" {})
1005 (const :tag "Never interpret" nil)))
1007 (defcustom org-startup-with-beamer-mode nil
1008 "Non-nil means turn on `org-beamer-mode' on startup.
1009 This can also be configured on a per-file basis by adding one of
1010 the following lines anywhere in the buffer:
1012 #+STARTUP: beamer"
1013 :group 'org-startup
1014 :version "24.1"
1015 :type 'boolean)
1017 (defcustom org-startup-align-all-tables nil
1018 "Non-nil means align all tables when visiting a file.
1019 This is useful when the column width in tables is forced with <N> cookies
1020 in table fields. Such tables will look correct only after the first re-align.
1021 This can also be configured on a per-file basis by adding one of
1022 the following lines anywhere in the buffer:
1023 #+STARTUP: align
1024 #+STARTUP: noalign"
1025 :group 'org-startup
1026 :type 'boolean)
1028 (defcustom org-startup-with-inline-images nil
1029 "Non-nil means show inline images when loading a new Org file.
1030 This can also be configured on a per-file basis by adding one of
1031 the following lines anywhere in the buffer:
1032 #+STARTUP: inlineimages
1033 #+STARTUP: noinlineimages"
1034 :group 'org-startup
1035 :version "24.1"
1036 :type 'boolean)
1038 (defcustom org-startup-with-latex-preview nil
1039 "Non-nil means preview LaTeX fragments when loading a new Org file.
1041 This can also be configured on a per-file basis by adding one of
1042 the following lines anywhere in the buffer:
1043 #+STARTUP: latexpreview
1044 #+STARTUP: nolatexpreview"
1045 :group 'org-startup
1046 :version "24.4"
1047 :package-version '(Org . "8.0")
1048 :type 'boolean)
1050 (defcustom org-insert-mode-line-in-empty-file nil
1051 "Non-nil means insert the first line setting Org mode in empty files.
1052 When the function `org-mode' is called interactively in an empty file, this
1053 normally means that the file name does not automatically trigger Org mode.
1054 To ensure that the file will always be in Org mode in the future, a
1055 line enforcing Org mode will be inserted into the buffer, if this option
1056 has been set."
1057 :group 'org-startup
1058 :type 'boolean)
1060 (defcustom org-replace-disputed-keys nil
1061 "Non-nil means use alternative key bindings for some keys.
1062 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1063 These keys are also used by other packages like shift-selection-mode'
1064 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1065 If you want to use Org mode together with one of these other modes,
1066 or more generally if you would like to move some Org mode commands to
1067 other keys, set this variable and configure the keys with the variable
1068 `org-disputed-keys'.
1070 This option is only relevant at load-time of Org mode, and must be set
1071 *before* org.el is loaded. Changing it requires a restart of Emacs to
1072 become effective."
1073 :group 'org-startup
1074 :type 'boolean)
1076 (defcustom org-use-extra-keys nil
1077 "Non-nil means use extra key sequence definitions for certain commands.
1078 This happens automatically if `window-system' is nil. This
1079 variable lets you do the same manually. You must set it before
1080 loading Org."
1081 :group 'org-startup
1082 :type 'boolean)
1084 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1086 (defcustom org-disputed-keys
1087 '(([(shift up)] . [(meta p)])
1088 ([(shift down)] . [(meta n)])
1089 ([(shift left)] . [(meta -)])
1090 ([(shift right)] . [(meta +)])
1091 ([(control shift right)] . [(meta shift +)])
1092 ([(control shift left)] . [(meta shift -)]))
1093 "Keys for which Org mode and other modes compete.
1094 This is an alist, cars are the default keys, second element specifies
1095 the alternative to use when `org-replace-disputed-keys' is t.
1097 Keys can be specified in any syntax supported by `define-key'.
1098 The value of this option takes effect only at Org mode startup,
1099 therefore you'll have to restart Emacs to apply it after changing."
1100 :group 'org-startup
1101 :type 'alist)
1103 (defun org-key (key)
1104 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1105 Or return the original if not disputed."
1106 (when org-replace-disputed-keys
1107 (let* ((nkey (key-description key))
1108 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1109 org-disputed-keys)))
1110 (setq key (if x (cdr x) key))))
1111 key)
1113 (defun org-defkey (keymap key def)
1114 "Define a key, possibly translated, as returned by `org-key'."
1115 (define-key keymap (org-key key) def))
1117 (defcustom org-ellipsis nil
1118 "The ellipsis to use in the Org mode outline.
1120 When nil, just use the standard three dots.
1121 When a string, use that string instead.
1123 The change affects only Org mode (which will then use its own display table).
1124 Changing this requires executing `\\[org-mode]' in a buffer to become
1125 effective."
1126 :group 'org-startup
1127 :type '(choice (const :tag "Default" nil)
1128 (string :tag "String" :value "...#"))
1129 :safe #'string-or-null-p)
1131 (defvar org-display-table nil
1132 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1134 (defgroup org-keywords nil
1135 "Keywords in Org mode."
1136 :tag "Org Keywords"
1137 :group 'org)
1139 (defcustom org-closed-keep-when-no-todo nil
1140 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1141 :group 'org-todo
1142 :group 'org-keywords
1143 :version "24.4"
1144 :package-version '(Org . "8.0")
1145 :type 'boolean)
1147 (defgroup org-structure nil
1148 "Options concerning the general structure of Org files."
1149 :tag "Org Structure"
1150 :group 'org)
1152 (defgroup org-reveal-location nil
1153 "Options about how to make context of a location visible."
1154 :tag "Org Reveal Location"
1155 :group 'org-structure)
1157 (defcustom org-show-context-detail '((agenda . local)
1158 (bookmark-jump . lineage)
1159 (isearch . lineage)
1160 (default . ancestors))
1161 "Alist between context and visibility span when revealing a location.
1163 \\<org-mode-map>Some actions may move point into invisible
1164 locations. As a consequence, Org always expose a neighborhood
1165 around point. How much is shown depends on the initial action,
1166 or context. Valid contexts are
1168 agenda when exposing an entry from the agenda
1169 org-goto when using the command `org-goto' (`\\[org-goto]')
1170 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1171 tags-tree when constructing a sparse tree based on tags matches
1172 link-search when exposing search matches associated with a link
1173 mark-goto when exposing the jump goal of a mark
1174 bookmark-jump when exposing a bookmark location
1175 isearch when exiting from an incremental search
1176 default default for all contexts not set explicitly
1178 Allowed visibility spans are
1180 minimal show current headline; if point is not on headline,
1181 also show entry
1183 local show current headline, entry and next headline
1185 ancestors show current headline and its direct ancestors; if
1186 point is not on headline, also show entry
1188 lineage show current headline, its direct ancestors and all
1189 their children; if point is not on headline, also show
1190 entry and first child
1192 tree show current headline, its direct ancestors and all
1193 their children; if point is not on headline, also show
1194 entry and all children
1196 canonical show current headline, its direct ancestors along with
1197 their entries and children; if point is not located on
1198 the headline, also show current entry and all children
1200 As special cases, a nil or t value means show all contexts in
1201 `minimal' or `canonical' view, respectively.
1203 Some views can make displayed information very compact, but also
1204 make it harder to edit the location of the match. In such
1205 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1206 more context."
1207 :group 'org-reveal-location
1208 :version "26.1"
1209 :package-version '(Org . "9.0")
1210 :type '(choice
1211 (const :tag "Canonical" t)
1212 (const :tag "Minimal" nil)
1213 (repeat :greedy t :tag "Individual contexts"
1214 (cons
1215 (choice :tag "Context"
1216 (const agenda)
1217 (const org-goto)
1218 (const occur-tree)
1219 (const tags-tree)
1220 (const link-search)
1221 (const mark-goto)
1222 (const bookmark-jump)
1223 (const isearch)
1224 (const default))
1225 (choice :tag "Detail level"
1226 (const minimal)
1227 (const local)
1228 (const ancestors)
1229 (const lineage)
1230 (const tree)
1231 (const canonical))))))
1233 (defcustom org-indirect-buffer-display 'other-window
1234 "How should indirect tree buffers be displayed?
1236 This applies to indirect buffers created with the commands
1237 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1239 Valid values are:
1240 current-window Display in the current window
1241 other-window Just display in another window.
1242 dedicated-frame Create one new frame, and re-use it each time.
1243 new-frame Make a new frame each time. Note that in this case
1244 previously-made indirect buffers are kept, and you need to
1245 kill these buffers yourself."
1246 :group 'org-structure
1247 :group 'org-agenda-windows
1248 :type '(choice
1249 (const :tag "In current window" current-window)
1250 (const :tag "In current frame, other window" other-window)
1251 (const :tag "Each time a new frame" new-frame)
1252 (const :tag "One dedicated frame" dedicated-frame)))
1254 (defcustom org-use-speed-commands nil
1255 "Non-nil means activate single letter commands at beginning of a headline.
1256 This may also be a function to test for appropriate locations where speed
1257 commands should be active.
1259 For example, to activate speed commands when the point is on any
1260 star at the beginning of the headline, you can do this:
1262 (setq org-use-speed-commands
1263 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1264 :group 'org-structure
1265 :type '(choice
1266 (const :tag "Never" nil)
1267 (const :tag "At beginning of headline stars" t)
1268 (function)))
1270 (defcustom org-speed-commands-user nil
1271 "Alist of additional speed commands.
1272 This list will be checked before `org-speed-commands-default'
1273 when the variable `org-use-speed-commands' is non-nil
1274 and when the cursor is at the beginning of a headline.
1275 The car if each entry is a string with a single letter, which must
1276 be assigned to `self-insert-command' in the global map.
1277 The cdr is either a command to be called interactively, a function
1278 to be called, or a form to be evaluated.
1279 An entry that is just a list with a single string will be interpreted
1280 as a descriptive headline that will be added when listing the speed
1281 commands in the Help buffer using the `?' speed command."
1282 :group 'org-structure
1283 :type '(repeat :value ("k" . ignore)
1284 (choice :value ("k" . ignore)
1285 (list :tag "Descriptive Headline" (string :tag "Headline"))
1286 (cons :tag "Letter and Command"
1287 (string :tag "Command letter")
1288 (choice
1289 (function)
1290 (sexp))))))
1292 (defcustom org-bookmark-names-plist
1293 '(:last-capture "org-capture-last-stored"
1294 :last-refile "org-refile-last-stored"
1295 :last-capture-marker "org-capture-last-stored-marker")
1296 "Names for bookmarks automatically set by some Org commands.
1297 This can provide strings as names for a number of bookmarks Org sets
1298 automatically. The following keys are currently implemented:
1299 :last-capture
1300 :last-capture-marker
1301 :last-refile
1302 When a key does not show up in the property list, the corresponding bookmark
1303 is not set."
1304 :group 'org-structure
1305 :type 'plist)
1307 (defgroup org-cycle nil
1308 "Options concerning visibility cycling in Org mode."
1309 :tag "Org Cycle"
1310 :group 'org-structure)
1312 (defcustom org-cycle-skip-children-state-if-no-children t
1313 "Non-nil means skip CHILDREN state in entries that don't have any."
1314 :group 'org-cycle
1315 :type 'boolean)
1317 (defcustom org-cycle-max-level nil
1318 "Maximum level which should still be subject to visibility cycling.
1319 Levels higher than this will, for cycling, be treated as text, not a headline.
1320 When `org-odd-levels-only' is set, a value of N in this variable actually
1321 means 2N-1 stars as the limiting headline.
1322 When nil, cycle all levels.
1323 Note that the limiting level of cycling is also influenced by
1324 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1325 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1326 than its value."
1327 :group 'org-cycle
1328 :type '(choice
1329 (const :tag "No limit" nil)
1330 (integer :tag "Maximum level")))
1332 (defcustom org-hide-block-startup nil
1333 "Non-nil means entering Org mode will fold all blocks.
1334 This can also be set in on a per-file basis with
1336 #+STARTUP: hideblocks
1337 #+STARTUP: showblocks"
1338 :group 'org-startup
1339 :group 'org-cycle
1340 :type 'boolean)
1342 (defcustom org-cycle-global-at-bob nil
1343 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1345 This makes it possible to do global cycling without having to use `S-TAB'
1346 or `\\[universal-argument] TAB'. For this special case to work, the first \
1347 line of the buffer
1348 must not be a headline -- it may be empty or some other text.
1350 When used in this way, `org-cycle-hook' is disabled temporarily to make
1351 sure the cursor stays at the beginning of the buffer.
1353 When this option is nil, don't do anything special at the beginning of
1354 the buffer."
1355 :group 'org-cycle
1356 :type 'boolean)
1358 (defcustom org-cycle-level-after-item/entry-creation t
1359 "Non-nil means cycle entry level or item indentation in new empty entries.
1361 When the cursor is at the end of an empty headline, i.e., with only stars
1362 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1363 and then all possible ancestor states, before returning to the original state.
1364 This makes data entry extremely fast: M-RET to create a new headline,
1365 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1367 When the cursor is at the end of an empty plain list item, one TAB will
1368 make it a subitem, two or more tabs will back up to make this an item
1369 higher up in the item hierarchy."
1370 :group 'org-cycle
1371 :type 'boolean)
1373 (defcustom org-cycle-emulate-tab t
1374 "Where should `org-cycle' emulate TAB.
1375 nil Never
1376 white Only in completely white lines
1377 whitestart Only at the beginning of lines, before the first non-white char
1378 t Everywhere except in headlines
1379 exc-hl-bol Everywhere except at the start of a headline
1380 If TAB is used in a place where it does not emulate TAB, the current subtree
1381 visibility is cycled."
1382 :group 'org-cycle
1383 :type '(choice (const :tag "Never" nil)
1384 (const :tag "Only in completely white lines" white)
1385 (const :tag "Before first char in a line" whitestart)
1386 (const :tag "Everywhere except in headlines" t)
1387 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1389 (defcustom org-cycle-separator-lines 2
1390 "Number of empty lines needed to keep an empty line between collapsed trees.
1391 If you leave an empty line between the end of a subtree and the following
1392 headline, this empty line is hidden when the subtree is folded.
1393 Org mode will leave (exactly) one empty line visible if the number of
1394 empty lines is equal or larger to the number given in this variable.
1395 So the default 2 means at least 2 empty lines after the end of a subtree
1396 are needed to produce free space between a collapsed subtree and the
1397 following headline.
1399 If the number is negative, and the number of empty lines is at least -N,
1400 all empty lines are shown.
1402 Special case: when 0, never leave empty lines in collapsed view."
1403 :group 'org-cycle
1404 :type 'integer)
1405 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1407 (defcustom org-pre-cycle-hook nil
1408 "Hook that is run before visibility cycling is happening.
1409 The function(s) in this hook must accept a single argument which indicates
1410 the new state that will be set right after running this hook. The
1411 argument is a symbol. Before a global state change, it can have the values
1412 `overview', `content', or `all'. Before a local state change, it can have
1413 the values `folded', `children', or `subtree'."
1414 :group 'org-cycle
1415 :type 'hook)
1417 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1418 org-cycle-hide-drawers
1419 org-cycle-show-empty-lines
1420 org-optimize-window-after-visibility-change)
1421 "Hook that is run after `org-cycle' has changed the buffer visibility.
1422 The function(s) in this hook must accept a single argument which indicates
1423 the new state that was set by the most recent `org-cycle' command. The
1424 argument is a symbol. After a global state change, it can have the values
1425 `overview', `contents', or `all'. After a local state change, it can have
1426 the values `folded', `children', or `subtree'."
1427 :group 'org-cycle
1428 :type 'hook
1429 :version "26.1"
1430 :package-version '(Org . "8.3"))
1432 (defgroup org-edit-structure nil
1433 "Options concerning structure editing in Org mode."
1434 :tag "Org Edit Structure"
1435 :group 'org-structure)
1437 (defcustom org-odd-levels-only nil
1438 "Non-nil means skip even levels and only use odd levels for the outline.
1439 This has the effect that two stars are being added/taken away in
1440 promotion/demotion commands. It also influences how levels are
1441 handled by the exporters.
1442 Changing it requires restart of `font-lock-mode' to become effective
1443 for fontification also in regions already fontified.
1444 You may also set this on a per-file basis by adding one of the following
1445 lines to the buffer:
1447 #+STARTUP: odd
1448 #+STARTUP: oddeven"
1449 :group 'org-edit-structure
1450 :group 'org-appearance
1451 :type 'boolean)
1453 (defcustom org-adapt-indentation t
1454 "Non-nil means adapt indentation to outline node level.
1456 When this variable is set, Org assumes that you write outlines by
1457 indenting text in each node to align with the headline (after the
1458 stars). The following issues are influenced by this variable:
1460 - The indentation is increased by one space in a demotion
1461 command, and decreased by one in a promotion command. However,
1462 in the latter case, if shifting some line in the entry body
1463 would alter document structure (e.g., insert a new headline),
1464 indentation is not changed at all.
1466 - Property drawers and planning information is inserted indented
1467 when this variable is set. When nil, they will not be indented.
1469 - TAB indents a line relative to current level. The lines below
1470 a headline will be indented when this variable is set.
1472 Note that this is all about true indentation, by adding and
1473 removing space characters. See also `org-indent.el' which does
1474 level-dependent indentation in a virtual way, i.e. at display
1475 time in Emacs."
1476 :group 'org-edit-structure
1477 :type 'boolean)
1479 (defcustom org-special-ctrl-a/e nil
1480 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1482 When t, `C-a' will bring back the cursor to the beginning of the
1483 headline text, i.e. after the stars and after a possible TODO
1484 keyword. In an item, this will be the position after bullet and
1485 check-box, if any. When the cursor is already at that position,
1486 another `C-a' will bring it to the beginning of the line.
1488 `C-e' will jump to the end of the headline, ignoring the presence
1489 of tags in the headline. A second `C-e' will then jump to the
1490 true end of the line, after any tags. This also means that, when
1491 this variable is non-nil, `C-e' also will never jump beyond the
1492 end of the heading of a folded section, i.e. not after the
1493 ellipses.
1495 When set to the symbol `reversed', the first `C-a' or `C-e' works
1496 normally, going to the true line boundary first. Only a directly
1497 following, identical keypress will bring the cursor to the
1498 special positions.
1500 This may also be a cons cell where the behavior for `C-a' and
1501 `C-e' is set separately."
1502 :group 'org-edit-structure
1503 :type '(choice
1504 (const :tag "off" nil)
1505 (const :tag "on: after stars/bullet and before tags first" t)
1506 (const :tag "reversed: true line boundary first" reversed)
1507 (cons :tag "Set C-a and C-e separately"
1508 (choice :tag "Special C-a"
1509 (const :tag "off" nil)
1510 (const :tag "on: after stars/bullet first" t)
1511 (const :tag "reversed: before stars/bullet first" reversed))
1512 (choice :tag "Special C-e"
1513 (const :tag "off" nil)
1514 (const :tag "on: before tags first" t)
1515 (const :tag "reversed: after tags first" reversed)))))
1516 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1518 (defcustom org-special-ctrl-k nil
1519 "Non-nil means `C-k' will behave specially in headlines.
1520 When nil, `C-k' will call the default `kill-line' command.
1521 When t, the following will happen while the cursor is in the headline:
1523 - When the cursor is at the beginning of a headline, kill the entire
1524 line and possible the folded subtree below the line.
1525 - When in the middle of the headline text, kill the headline up to the tags.
1526 - When after the headline text, kill the tags."
1527 :group 'org-edit-structure
1528 :type 'boolean)
1530 (defcustom org-ctrl-k-protect-subtree nil
1531 "Non-nil means, do not delete a hidden subtree with C-k.
1532 When set to the symbol `error', simply throw an error when C-k is
1533 used to kill (part-of) a headline that has hidden text behind it.
1534 Any other non-nil value will result in a query to the user, if it is
1535 OK to kill that hidden subtree. When nil, kill without remorse."
1536 :group 'org-edit-structure
1537 :version "24.1"
1538 :type '(choice
1539 (const :tag "Do not protect hidden subtrees" nil)
1540 (const :tag "Protect hidden subtrees with a security query" t)
1541 (const :tag "Never kill a hidden subtree with C-k" error)))
1543 (defcustom org-special-ctrl-o t
1544 "Non-nil means, make `C-o' insert a row in tables."
1545 :group 'org-edit-structure
1546 :type 'boolean)
1548 (defcustom org-catch-invisible-edits nil
1549 "Check if in invisible region before inserting or deleting a character.
1550 Valid values are:
1552 nil Do not check, so just do invisible edits.
1553 error Throw an error and do nothing.
1554 show Make point visible, and do the requested edit.
1555 show-and-error Make point visible, then throw an error and abort the edit.
1556 smart Make point visible, and do insertion/deletion if it is
1557 adjacent to visible text and the change feels predictable.
1558 Never delete a previously invisible character or add in the
1559 middle or right after an invisible region. Basically, this
1560 allows insertion and backward-delete right before ellipses.
1561 FIXME: maybe in this case we should not even show?"
1562 :group 'org-edit-structure
1563 :version "24.1"
1564 :type '(choice
1565 (const :tag "Do not check" nil)
1566 (const :tag "Throw error when trying to edit" error)
1567 (const :tag "Unhide, but do not do the edit" show-and-error)
1568 (const :tag "Show invisible part and do the edit" show)
1569 (const :tag "Be smart and do the right thing" smart)))
1571 (defcustom org-yank-folded-subtrees t
1572 "Non-nil means when yanking subtrees, fold them.
1573 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1574 it starts with a heading and all other headings in it are either children
1575 or siblings, then fold all the subtrees. However, do this only if no
1576 text after the yank would be swallowed into a folded tree by this action."
1577 :group 'org-edit-structure
1578 :type 'boolean)
1580 (defcustom org-yank-adjusted-subtrees nil
1581 "Non-nil means when yanking subtrees, adjust the level.
1582 With this setting, `org-paste-subtree' is used to insert the subtree, see
1583 this function for details."
1584 :group 'org-edit-structure
1585 :type 'boolean)
1587 (defcustom org-M-RET-may-split-line '((default . t))
1588 "Non-nil means M-RET will split the line at the cursor position.
1589 When nil, it will go to the end of the line before making a
1590 new line.
1591 You may also set this option in a different way for different
1592 contexts. Valid contexts are:
1594 headline when creating a new headline
1595 item when creating a new item
1596 table in a table field
1597 default the value to be used for all contexts not explicitly
1598 customized"
1599 :group 'org-structure
1600 :group 'org-table
1601 :type '(choice
1602 (const :tag "Always" t)
1603 (const :tag "Never" nil)
1604 (repeat :greedy t :tag "Individual contexts"
1605 (cons
1606 (choice :tag "Context"
1607 (const headline)
1608 (const item)
1609 (const table)
1610 (const default))
1611 (boolean)))))
1614 (defcustom org-insert-heading-respect-content nil
1615 "Non-nil means insert new headings after the current subtree.
1616 \\<org-mode-map>
1617 When nil, the new heading is created directly after the current line.
1618 The commands `\\[org-insert-heading-respect-content]' and \
1619 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1620 for the duration of the command."
1621 :group 'org-structure
1622 :type 'boolean)
1624 (defcustom org-blank-before-new-entry '((heading . auto)
1625 (plain-list-item . auto))
1626 "Should `org-insert-heading' leave a blank line before new heading/item?
1627 The value is an alist, with `heading' and `plain-list-item' as CAR,
1628 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1629 which case Org will look at the surrounding headings/items and try to
1630 make an intelligent decision whether to insert a blank line or not."
1631 :group 'org-edit-structure
1632 :type '(list
1633 (cons (const heading)
1634 (choice (const :tag "Never" nil)
1635 (const :tag "Always" t)
1636 (const :tag "Auto" auto)))
1637 (cons (const plain-list-item)
1638 (choice (const :tag "Never" nil)
1639 (const :tag "Always" t)
1640 (const :tag "Auto" auto)))))
1642 (defcustom org-insert-heading-hook nil
1643 "Hook being run after inserting a new heading."
1644 :group 'org-edit-structure
1645 :type 'hook)
1647 (defcustom org-enable-fixed-width-editor t
1648 "Non-nil means lines starting with \":\" are treated as fixed-width.
1649 This currently only means they are never auto-wrapped.
1650 When nil, such lines will be treated like ordinary lines."
1651 :group 'org-edit-structure
1652 :type 'boolean)
1654 (defcustom org-goto-auto-isearch t
1655 "Non-nil means typing characters in `org-goto' starts incremental search.
1656 When nil, you can use these keybindings to navigate the buffer:
1658 q Quit the org-goto interface
1659 n Go to the next visible heading
1660 p Go to the previous visible heading
1661 f Go one heading forward on same level
1662 b Go one heading backward on same level
1663 u Go one heading up"
1664 :group 'org-edit-structure
1665 :type 'boolean)
1667 (defgroup org-sparse-trees nil
1668 "Options concerning sparse trees in Org mode."
1669 :tag "Org Sparse Trees"
1670 :group 'org-structure)
1672 (defcustom org-highlight-sparse-tree-matches t
1673 "Non-nil means highlight all matches that define a sparse tree.
1674 The highlights will automatically disappear the next time the buffer is
1675 changed by an edit command."
1676 :group 'org-sparse-trees
1677 :type 'boolean)
1679 (defcustom org-remove-highlights-with-change t
1680 "Non-nil means any change to the buffer will remove temporary highlights.
1681 \\<org-mode-map>\
1682 Such highlights are created by `org-occur' and `org-clock-display'.
1683 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1684 to get rid of the highlights.
1685 The highlights created by `org-toggle-latex-fragment' always need
1686 `\\[org-toggle-latex-fragment]' to be removed."
1687 :group 'org-sparse-trees
1688 :group 'org-time
1689 :type 'boolean)
1691 (defcustom org-occur-case-fold-search t
1692 "Non-nil means `org-occur' should be case-insensitive.
1693 If set to `smart' the search will be case-insensitive only if it
1694 doesn't specify any upper case character."
1695 :group 'org-sparse-trees
1696 :version "26.1"
1697 :type '(choice
1698 (const :tag "Case-sensitive" nil)
1699 (const :tag "Case-insensitive" t)
1700 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1702 (defcustom org-occur-hook '(org-first-headline-recenter)
1703 "Hook that is run after `org-occur' has constructed a sparse tree.
1704 This can be used to recenter the window to show as much of the structure
1705 as possible."
1706 :group 'org-sparse-trees
1707 :type 'hook)
1709 (defgroup org-imenu-and-speedbar nil
1710 "Options concerning imenu and speedbar in Org mode."
1711 :tag "Org Imenu and Speedbar"
1712 :group 'org-structure)
1714 (defcustom org-imenu-depth 2
1715 "The maximum level for Imenu access to Org headlines.
1716 This also applied for speedbar access."
1717 :group 'org-imenu-and-speedbar
1718 :type 'integer)
1720 (defgroup org-table nil
1721 "Options concerning tables in Org mode."
1722 :tag "Org Table"
1723 :group 'org)
1725 (defcustom org-enable-table-editor 'optimized
1726 "Non-nil means lines starting with \"|\" are handled by the table editor.
1727 When nil, such lines will be treated like ordinary lines.
1729 When equal to the symbol `optimized', the table editor will be optimized to
1730 do the following:
1731 - Automatic overwrite mode in front of whitespace in table fields.
1732 This makes the structure of the table stay in tact as long as the edited
1733 field does not exceed the column width.
1734 - Minimize the number of realigns. Normally, the table is aligned each time
1735 TAB or RET are pressed to move to another field. With optimization this
1736 happens only if changes to a field might have changed the column width.
1737 Optimization requires replacing the functions `self-insert-command',
1738 `delete-char', and `backward-delete-char' in Org buffers, with a
1739 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1740 good at guessing when a re-align will be necessary, but you can always
1741 force one with `\\[org-ctrl-c-ctrl-c]'.
1743 If you would like to use the optimized version in Org mode, but the
1744 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1746 This variable can be used to turn on and off the table editor during a session,
1747 but in order to toggle optimization, a restart is required.
1749 See also the variable `org-table-auto-blank-field'."
1750 :group 'org-table
1751 :type '(choice
1752 (const :tag "off" nil)
1753 (const :tag "on" t)
1754 (const :tag "on, optimized" optimized)))
1756 (defcustom org-self-insert-cluster-for-undo nil
1757 "Non-nil means cluster self-insert commands for undo when possible.
1758 If this is set, then, like in the Emacs command loop, 20 consecutive
1759 characters will be undone together.
1760 This is configurable, because there is some impact on typing performance."
1761 :group 'org-table
1762 :type 'boolean)
1764 (defcustom org-table-tab-recognizes-table.el t
1765 "Non-nil means TAB will automatically notice a table.el table.
1766 When it sees such a table, it moves point into it and - if necessary -
1767 calls `table-recognize-table'."
1768 :group 'org-table-editing
1769 :type 'boolean)
1771 (defgroup org-link nil
1772 "Options concerning links in Org mode."
1773 :tag "Org Link"
1774 :group 'org)
1776 (defvar-local org-link-abbrev-alist-local nil
1777 "Buffer-local version of `org-link-abbrev-alist', which see.
1778 The value of this is taken from the #+LINK lines.")
1780 (defcustom org-link-parameters
1781 '(("doi" :follow org--open-doi-link)
1782 ("elisp" :follow org--open-elisp-link)
1783 ("file" :complete org-file-complete-link)
1784 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1785 ("help" :follow org--open-help-link)
1786 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1787 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1788 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" 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)
1830 :version "26.1"
1831 :package-version '(Org . "9.1"))
1833 (defun org-link-get-parameter (type key)
1834 "Get TYPE link property for KEY.
1835 TYPE is a string and KEY is a plist keyword."
1836 (plist-get
1837 (cdr (assoc type org-link-parameters))
1838 key))
1840 (defun org-link-set-parameters (type &rest parameters)
1841 "Set link TYPE properties to PARAMETERS.
1842 PARAMETERS should be :key val pairs."
1843 (let ((data (assoc type org-link-parameters)))
1844 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1845 (push (cons type parameters) org-link-parameters)
1846 (org-make-link-regexps)
1847 (org-element-update-syntax))))
1849 (defun org-link-types ()
1850 "Return a list of known link types."
1851 (mapcar #'car org-link-parameters))
1853 (defcustom org-link-abbrev-alist nil
1854 "Alist of link abbreviations.
1855 The car of each element is a string, to be replaced at the start of a link.
1856 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1857 links in Org buffers can have an optional tag after a double colon, e.g.,
1859 [[linkkey:tag][description]]
1861 The `linkkey' must be a single word, starting with a letter, followed
1862 by letters, numbers, `-' or `_'.
1864 If REPLACE is a string, the tag will simply be appended to create the link.
1865 If the string contains \"%s\", the tag will be inserted there. If the string
1866 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1867 at that point (see the function `url-hexify-string'). If the string contains
1868 the specifier \"%(my-function)\", then the custom function `my-function' will
1869 be invoked: this function takes the tag as its only argument and must return
1870 a string.
1872 REPLACE may also be a function that will be called with the tag as the
1873 only argument to create the link, which should be returned as a string.
1875 See the manual for examples."
1876 :group 'org-link
1877 :type '(repeat
1878 (cons
1879 (string :tag "Protocol")
1880 (choice
1881 (string :tag "Format")
1882 (function)))))
1884 (defcustom org-descriptive-links t
1885 "Non-nil means Org will display descriptive links.
1886 E.g. [[http://orgmode.org][Org website]] will be displayed as
1887 \"Org Website\", hiding the link itself and just displaying its
1888 description. When set to nil, Org will display the full links
1889 literally.
1891 You can interactively set the value of this variable by calling
1892 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1893 :group 'org-link
1894 :type 'boolean)
1896 (defcustom org-link-file-path-type 'adaptive
1897 "How the path name in file links should be stored.
1898 Valid values are:
1900 relative Relative to the current directory, i.e. the directory of the file
1901 into which the link is being inserted.
1902 absolute Absolute path, if possible with ~ for home directory.
1903 noabbrev Absolute path, no abbreviation of home directory.
1904 adaptive Use relative path for files in the current directory and sub-
1905 directories of it. For other files, use an absolute path."
1906 :group 'org-link
1907 :type '(choice
1908 (const relative)
1909 (const absolute)
1910 (const noabbrev)
1911 (const adaptive)))
1913 (defvaralias 'org-activate-links 'org-highlight-links)
1914 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1915 "Types of links that should be highlighted in Org files.
1917 This is a list of symbols, each one of them leading to the
1918 highlighting of a certain link type.
1920 You can still open links that are not highlighted.
1922 In principle, it does not hurt to turn on highlighting for all
1923 link types. There may be a small gain when turning off unused
1924 link types. The types are:
1926 bracket The recommended [[link][description]] or [[link]] links with hiding.
1927 angle Links in angular brackets that may contain whitespace like
1928 <bbdb:Carsten Dominik>.
1929 plain Plain links in normal text, no whitespace, like http://google.com.
1930 radio Text that is matched by a radio target, see manual for details.
1931 tag Tag settings in a headline (link to tag search).
1932 date Time stamps (link to calendar).
1933 footnote Footnote labels.
1935 If you set this variable during an Emacs session, use `org-mode-restart'
1936 in the Org buffer so that the change takes effect."
1937 :group 'org-link
1938 :group 'org-appearance
1939 :type '(set :greedy t
1940 (const :tag "Double bracket links" bracket)
1941 (const :tag "Angular bracket links" angle)
1942 (const :tag "Plain text links" plain)
1943 (const :tag "Radio target matches" radio)
1944 (const :tag "Tags" tag)
1945 (const :tag "Timestamps" date)
1946 (const :tag "Footnotes" footnote)))
1948 (defcustom org-make-link-description-function nil
1949 "Function to use for generating link descriptions from links.
1950 When nil, the link location will be used. This function must take
1951 two parameters: the first one is the link, the second one is the
1952 description generated by `org-insert-link'. The function should
1953 return the description to use."
1954 :group 'org-link
1955 :type '(choice (const nil) (function)))
1957 (defgroup org-link-store nil
1958 "Options concerning storing links in Org mode."
1959 :tag "Org Store Link"
1960 :group 'org-link)
1962 (defcustom org-url-hexify-p t
1963 "When non-nil, hexify URL when creating a link."
1964 :type 'boolean
1965 :version "24.3"
1966 :group 'org-link-store)
1968 (defcustom org-email-link-description-format "Email %c: %.30s"
1969 "Format of the description part of a link to an email or usenet message.
1970 The following %-escapes will be replaced by corresponding information:
1972 %F full \"From\" field
1973 %f name, taken from \"From\" field, address if no name
1974 %T full \"To\" field
1975 %t first name in \"To\" field, address if no name
1976 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1977 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1978 %s subject
1979 %d date
1980 %m message-id.
1982 You may use normal field width specification between the % and the letter.
1983 This is for example useful to limit the length of the subject.
1985 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1986 :group 'org-link-store
1987 :type 'string)
1989 (defcustom org-from-is-user-regexp
1990 (let (r1 r2)
1991 (when (and user-mail-address (not (string= user-mail-address "")))
1992 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1993 (when (and user-full-name (not (string= user-full-name "")))
1994 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1995 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1996 "Regexp matched against the \"From:\" header of an email or usenet message.
1997 It should match if the message is from the user him/herself."
1998 :group 'org-link-store
1999 :type 'regexp)
2001 (defcustom org-context-in-file-links t
2002 "Non-nil means file links from `org-store-link' contain context.
2003 \\<org-mode-map>
2004 A search string will be added to the file name with :: as separator
2005 and used to find the context when the link is activated by the command
2006 `org-open-at-point'. When this option is t, the entire active region
2007 will be placed in the search string of the file link. If set to a
2008 positive integer, only the first n lines of context will be stored.
2010 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2011 \\[org-store-link]')
2012 negates this setting for the duration of the command."
2013 :group 'org-link-store
2014 :type '(choice boolean integer))
2016 (defcustom org-keep-stored-link-after-insertion nil
2017 "Non-nil means keep link in list for entire session.
2018 \\<org-mode-map>
2019 The command `org-store-link' adds a link pointing to the current
2020 location to an internal list. These links accumulate during a session.
2021 The command `org-insert-link' can be used to insert links into any
2022 Org file (offering completion for all stored links).
2024 When this option is nil, every link which has been inserted once using
2025 `\\[org-insert-link]' will be removed from the list, to make completing the \
2026 unused
2027 links more efficient."
2028 :group 'org-link-store
2029 :type 'boolean)
2031 (defgroup org-link-follow nil
2032 "Options concerning following links in Org mode."
2033 :tag "Org Follow Link"
2034 :group 'org-link)
2036 (defcustom org-link-translation-function nil
2037 "Function to translate links with different syntax to Org syntax.
2038 This can be used to translate links created for example by the Planner
2039 or emacs-wiki packages to Org syntax.
2040 The function must accept two parameters, a TYPE containing the link
2041 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2042 which is everything after the link protocol. It should return a cons
2043 with possibly modified values of type and path.
2044 Org contains a function for this, so if you set this variable to
2045 `org-translate-link-from-planner', you should be able follow many
2046 links created by planner."
2047 :group 'org-link-follow
2048 :type '(choice (const nil) (function)))
2050 (defcustom org-follow-link-hook nil
2051 "Hook that is run after a link has been followed."
2052 :group 'org-link-follow
2053 :type 'hook)
2055 (defcustom org-tab-follows-link nil
2056 "Non-nil means on links TAB will follow the link.
2057 Needs to be set before org.el is loaded.
2058 This really should not be used, it does not make sense, and the
2059 implementation is bad."
2060 :group 'org-link-follow
2061 :type 'boolean)
2063 (defcustom org-return-follows-link nil
2064 "Non-nil means on links RET will follow the link.
2065 In tables, the special behavior of RET has precedence."
2066 :group 'org-link-follow
2067 :type 'boolean)
2069 (defcustom org-mouse-1-follows-link
2070 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2071 "Non-nil means mouse-1 on a link will follow the link.
2072 A longer mouse click will still set point. Needs to be set
2073 before org.el is loaded."
2074 :group 'org-link-follow
2075 :version "24.4"
2076 :package-version '(Org . "8.3")
2077 :type '(choice
2078 (const :tag "A double click follows the link" double)
2079 (const :tag "Unconditionally follow the link with mouse-1" t)
2080 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2082 (defcustom org-mark-ring-length 4
2083 "Number of different positions to be recorded in the ring.
2084 Changing this requires a restart of Emacs to work correctly."
2085 :group 'org-link-follow
2086 :type 'integer)
2088 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2089 "Non-nil means internal fuzzy links can only match headlines.
2091 When nil, the a fuzzy link may point to a target or a named
2092 construct in the document. When set to the special value
2093 `query-to-create', offer to create a new headline when none
2094 matched.
2096 Spaces and statistics cookies are ignored during heading searches."
2097 :group 'org-link-follow
2098 :version "24.1"
2099 :type '(choice
2100 (const :tag "Use fuzzy text search" nil)
2101 (const :tag "Match only exact headline" t)
2102 (const :tag "Match exact headline or query to create it"
2103 query-to-create))
2104 :safe #'symbolp)
2106 (defcustom org-link-frame-setup
2107 '((vm . vm-visit-folder-other-frame)
2108 (vm-imap . vm-visit-imap-folder-other-frame)
2109 (gnus . org-gnus-no-new-news)
2110 (file . find-file-other-window)
2111 (wl . wl-other-frame))
2112 "Setup the frame configuration for following links.
2113 When following a link with Emacs, it may often be useful to display
2114 this link in another window or frame. This variable can be used to
2115 set this up for the different types of links.
2116 For VM, use any of
2117 `vm-visit-folder'
2118 `vm-visit-folder-other-window'
2119 `vm-visit-folder-other-frame'
2120 For Gnus, use any of
2121 `gnus'
2122 `gnus-other-frame'
2123 `org-gnus-no-new-news'
2124 For FILE, use any of
2125 `find-file'
2126 `find-file-other-window'
2127 `find-file-other-frame'
2128 For Wanderlust use any of
2129 `wl'
2130 `wl-other-frame'
2131 For the calendar, use the variable `calendar-setup'.
2132 For BBDB, it is currently only possible to display the matches in
2133 another window."
2134 :group 'org-link-follow
2135 :type '(list
2136 (cons (const vm)
2137 (choice
2138 (const vm-visit-folder)
2139 (const vm-visit-folder-other-window)
2140 (const vm-visit-folder-other-frame)))
2141 (cons (const vm-imap)
2142 (choice
2143 (const vm-visit-imap-folder)
2144 (const vm-visit-imap-folder-other-window)
2145 (const vm-visit-imap-folder-other-frame)))
2146 (cons (const gnus)
2147 (choice
2148 (const gnus)
2149 (const gnus-other-frame)
2150 (const org-gnus-no-new-news)))
2151 (cons (const file)
2152 (choice
2153 (const find-file)
2154 (const find-file-other-window)
2155 (const find-file-other-frame)))
2156 (cons (const wl)
2157 (choice
2158 (const wl)
2159 (const wl-other-frame)))))
2161 (defcustom org-display-internal-link-with-indirect-buffer nil
2162 "Non-nil means use indirect buffer to display infile links.
2163 Activating internal links (from one location in a file to another location
2164 in the same file) normally just jumps to the location. When the link is
2165 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2166 is displayed in
2167 another window. When this option is set, the other window actually displays
2168 an indirect buffer clone of the current buffer, to avoid any visibility
2169 changes to the current buffer."
2170 :group 'org-link-follow
2171 :type 'boolean)
2173 (defcustom org-open-non-existing-files nil
2174 "Non-nil means `org-open-file' will open non-existing files.
2175 When nil, an error will be generated.
2176 This variable applies only to external applications because they
2177 might choke on non-existing files. If the link is to a file that
2178 will be opened in Emacs, the variable is ignored."
2179 :group 'org-link-follow
2180 :type 'boolean)
2182 (defcustom org-open-directory-means-index-dot-org nil
2183 "Non-nil means a link to a directory really means to index.org.
2184 When nil, following a directory link will run dired or open a finder/explorer
2185 window on that directory."
2186 :group 'org-link-follow
2187 :type 'boolean)
2189 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2190 "Non-nil means ask for confirmation before executing shell links.
2191 Shell links can be dangerous: just think about a link
2193 [[shell:rm -rf ~/*][Google Search]]
2195 This link would show up in your Org document as \"Google Search\",
2196 but really it would remove your entire home directory.
2197 Therefore we advise against setting this variable to nil.
2198 Just change it to `y-or-n-p' if you want to confirm with a
2199 single keystroke rather than having to type \"yes\"."
2200 :group 'org-link-follow
2201 :type '(choice
2202 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2203 (const :tag "with y-or-n (faster)" y-or-n-p)
2204 (const :tag "no confirmation (dangerous)" nil)))
2205 (put 'org-confirm-shell-link-function
2206 'safe-local-variable
2207 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2209 (defcustom org-confirm-shell-link-not-regexp ""
2210 "A regexp to skip confirmation for shell links."
2211 :group 'org-link-follow
2212 :version "24.1"
2213 :type 'regexp)
2215 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2216 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2217 Elisp links can be dangerous: just think about a link
2219 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2221 This link would show up in your Org document as \"Google Search\",
2222 but really it would remove your entire home directory.
2223 Therefore we advise against setting this variable to nil.
2224 Just change it to `y-or-n-p' if you want to confirm with a
2225 single keystroke rather than having to type \"yes\"."
2226 :group 'org-link-follow
2227 :type '(choice
2228 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2229 (const :tag "with y-or-n (faster)" y-or-n-p)
2230 (const :tag "no confirmation (dangerous)" nil)))
2231 (put 'org-confirm-shell-link-function
2232 'safe-local-variable
2233 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2235 (defcustom org-confirm-elisp-link-not-regexp ""
2236 "A regexp to skip confirmation for Elisp links."
2237 :group 'org-link-follow
2238 :version "24.1"
2239 :type 'regexp)
2241 (defconst org-file-apps-defaults-gnu
2242 '((remote . emacs)
2243 (system . mailcap)
2244 (t . mailcap))
2245 "Default file applications on a UNIX or GNU/Linux system.
2246 See `org-file-apps'.")
2248 (defconst org-file-apps-defaults-macosx
2249 '((remote . emacs)
2250 (system . "open %s")
2251 ("ps.gz" . "gv %s")
2252 ("eps.gz" . "gv %s")
2253 ("dvi" . "xdvi %s")
2254 ("fig" . "xfig %s")
2255 (t . "open %s"))
2256 "Default file applications on a macOS system.
2257 The system \"open\" is known as a default, but we use X11 applications
2258 for some files for which the OS does not have a good default.
2259 See `org-file-apps'.")
2261 (defconst org-file-apps-defaults-windowsnt
2262 (list '(remote . emacs)
2263 (cons 'system (lambda (file _path)
2264 (with-no-warnings (w32-shell-execute "open" file))))
2265 (cons t (lambda (file _path)
2266 (with-no-warnings (w32-shell-execute "open" file)))))
2267 "Default file applications on a Windows NT system.
2268 The system \"open\" is used for most files.
2269 See `org-file-apps'.")
2271 (defcustom org-file-apps
2272 '((auto-mode . emacs)
2273 ("\\.mm\\'" . default)
2274 ("\\.x?html?\\'" . default)
2275 ("\\.pdf\\'" . default))
2276 "External applications for opening `file:path' items in a document.
2277 \\<org-mode-map>\
2279 Org mode uses system defaults for different file types, but
2280 you can use this variable to set the application for a given file
2281 extension. The entries in this list are cons cells where the car identifies
2282 files and the cdr the corresponding command.
2284 Possible values for the file identifier are:
2286 \"string\" A string as a file identifier can be interpreted in different
2287 ways, depending on its contents:
2289 - Alphanumeric characters only:
2290 Match links with this file extension.
2291 Example: (\"pdf\" . \"evince %s\")
2292 to open PDFs with evince.
2294 - Regular expression: Match links where the
2295 filename matches the regexp. If you want to
2296 use groups here, use shy groups.
2298 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2299 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2300 to open *.html and *.xhtml with firefox.
2302 - Regular expression which contains (non-shy) groups:
2303 Match links where the whole link, including \"::\", and
2304 anything after that, matches the regexp.
2305 In a custom command string, %1, %2, etc. are replaced with
2306 the parts of the link that were matched by the groups.
2307 For backwards compatibility, if a command string is given
2308 that does not use any of the group matches, this case is
2309 handled identically to the second one (i.e. match against
2310 file name only).
2311 In a custom function, you can access the group matches with
2312 (match-string n link).
2314 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2315 \"evince -p %1 %s\")
2316 to open [[file:document.pdf::5]] with evince at page 5.
2318 `directory' Matches a directory
2319 `remote' Matches a remote file, accessible through tramp or efs.
2320 Remote files most likely should be visited through Emacs
2321 because external applications cannot handle such paths.
2322 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2323 so all files Emacs knows how to handle. Using this with
2324 command `emacs' will open most files in Emacs. Beware that this
2325 will also open html files inside Emacs, unless you add
2326 (\"html\" . default) to the list as well.
2327 `system' The system command to open files, like `open' on Windows
2328 and macOS, and mailcap under GNU/Linux. This is the command
2329 that will be selected if you call `org-open-at-point' with a
2330 double prefix argument (`\\[universal-argument] \
2331 \\[universal-argument] \\[org-open-at-point]').
2332 t Default for files not matched by any of the other options.
2334 Possible values for the command are:
2336 `emacs' The file will be visited by the current Emacs process.
2337 `default' Use the default application for this file type, which is the
2338 association for t in the list, most likely in the system-specific
2339 part. This can be used to overrule an unwanted setting in the
2340 system-specific variable.
2341 `system' Use the system command for opening files, like \"open\".
2342 This command is specified by the entry whose car is `system'.
2343 Most likely, the system-specific version of this variable
2344 does define this command, but you can overrule/replace it
2345 here.
2346 `mailcap' Use command specified in the mailcaps.
2347 string A command to be executed by a shell; %s will be replaced
2348 by the path to the file.
2349 function A Lisp function, which will be called with two arguments:
2350 the file path and the original link string, without the
2351 \"file:\" prefix.
2353 For more examples, see the system specific constants
2354 `org-file-apps-defaults-macosx'
2355 `org-file-apps-defaults-windowsnt'
2356 `org-file-apps-defaults-gnu'."
2357 :group 'org-link-follow
2358 :type '(repeat
2359 (cons (choice :value ""
2360 (string :tag "Extension")
2361 (const :tag "System command to open files" system)
2362 (const :tag "Default for unrecognized files" t)
2363 (const :tag "Remote file" remote)
2364 (const :tag "Links to a directory" directory)
2365 (const :tag "Any files that have Emacs modes"
2366 auto-mode))
2367 (choice :value ""
2368 (const :tag "Visit with Emacs" emacs)
2369 (const :tag "Use default" default)
2370 (const :tag "Use the system command" system)
2371 (string :tag "Command")
2372 (function :tag "Function")))))
2374 (defcustom org-doi-server-url "http://dx.doi.org/"
2375 "The URL of the DOI server."
2376 :type 'string
2377 :version "24.3"
2378 :group 'org-link-follow)
2380 (defgroup org-refile nil
2381 "Options concerning refiling entries in Org mode."
2382 :tag "Org Refile"
2383 :group 'org)
2385 (defcustom org-directory "~/org"
2386 "Directory with Org files.
2387 This is just a default location to look for Org files. There is no need
2388 at all to put your files into this directory. It is used in the
2389 following situations:
2391 1. When a capture template specifies a target file that is not an
2392 absolute path. The path will then be interpreted relative to
2393 `org-directory'
2394 2. When the value of variable `org-agenda-files' is a single file, any
2395 relative paths in this file will be taken as relative to
2396 `org-directory'."
2397 :group 'org-refile
2398 :group 'org-capture
2399 :type 'directory)
2401 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2402 "Default target for storing notes.
2403 Used as a fall back file for org-capture.el, for templates that
2404 do not specify a target file."
2405 :group 'org-refile
2406 :group 'org-capture
2407 :type 'file)
2409 (defcustom org-goto-interface 'outline
2410 "The default interface to be used for `org-goto'.
2411 Allowed values are:
2412 outline The interface shows an outline of the relevant file
2413 and the correct heading is found by moving through
2414 the outline or by searching with incremental search.
2415 outline-path-completion Headlines in the current buffer are offered via
2416 completion. This is the interface also used by
2417 the refile command."
2418 :group 'org-refile
2419 :type '(choice
2420 (const :tag "Outline" outline)
2421 (const :tag "Outline-path-completion" outline-path-completion)))
2423 (defcustom org-goto-max-level 5
2424 "Maximum target level when running `org-goto' with refile interface."
2425 :group 'org-refile
2426 :type 'integer)
2428 (defcustom org-reverse-note-order nil
2429 "Non-nil means store new notes at the beginning of a file or entry.
2430 When nil, new notes will be filed to the end of a file or entry.
2431 This can also be a list with cons cells of regular expressions that
2432 are matched against file names, and values."
2433 :group 'org-capture
2434 :group 'org-refile
2435 :type '(choice
2436 (const :tag "Reverse always" t)
2437 (const :tag "Reverse never" nil)
2438 (repeat :tag "By file name regexp"
2439 (cons regexp boolean))))
2441 (defcustom org-log-refile nil
2442 "Information to record when a task is refiled.
2444 Possible values are:
2446 nil Don't add anything
2447 time Add a time stamp to the task
2448 note Prompt for a note and add it with template `org-log-note-headings'
2450 This option can also be set with on a per-file-basis with
2452 #+STARTUP: nologrefile
2453 #+STARTUP: logrefile
2454 #+STARTUP: lognoterefile
2456 You can have local logging settings for a subtree by setting the LOGGING
2457 property to one or more of these keywords.
2459 When bulk-refiling from the agenda, the value `note' is forbidden and
2460 will temporarily be changed to `time'."
2461 :group 'org-refile
2462 :group 'org-progress
2463 :version "24.1"
2464 :type '(choice
2465 (const :tag "No logging" nil)
2466 (const :tag "Record timestamp" time)
2467 (const :tag "Record timestamp with note." note)))
2469 (defcustom org-refile-targets nil
2470 "Targets for refiling entries with `\\[org-refile]'.
2471 This is a list of cons cells. Each cell contains:
2472 - a specification of the files to be considered, either a list of files,
2473 or a symbol whose function or variable value will be used to retrieve
2474 a file name or a list of file names. If you use `org-agenda-files' for
2475 that, all agenda files will be scanned for targets. Nil means consider
2476 headings in the current buffer.
2477 - A specification of how to find candidate refile targets. This may be
2478 any of:
2479 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2480 This tag has to be present in all target headlines, inheritance will
2481 not be considered.
2482 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2483 todo keyword.
2484 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2485 headlines that are refiling targets.
2486 - a cons cell (:level . N). Any headline of level N is considered a target.
2487 Note that, when `org-odd-levels-only' is set, level corresponds to
2488 order in hierarchy, not to the number of stars.
2489 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2490 Note that, when `org-odd-levels-only' is set, level corresponds to
2491 order in hierarchy, not to the number of stars.
2493 Each element of this list generates a set of possible targets.
2494 The union of these sets is presented (with completion) to
2495 the user by `org-refile'.
2497 You can set the variable `org-refile-target-verify-function' to a function
2498 to verify each headline found by the simple criteria above.
2500 When this variable is nil, all top-level headlines in the current buffer
2501 are used, equivalent to the value `((nil . (:level . 1))'."
2502 :group 'org-refile
2503 :type '(repeat
2504 (cons
2505 (choice :value org-agenda-files
2506 (const :tag "All agenda files" org-agenda-files)
2507 (const :tag "Current buffer" nil)
2508 (function) (variable) (file))
2509 (choice :tag "Identify target headline by"
2510 (cons :tag "Specific tag" (const :value :tag) (string))
2511 (cons :tag "TODO keyword" (const :value :todo) (string))
2512 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2513 (cons :tag "Level number" (const :value :level) (integer))
2514 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2516 (defcustom org-refile-target-verify-function nil
2517 "Function to verify if the headline at point should be a refile target.
2518 The function will be called without arguments, with point at the
2519 beginning of the headline. It should return t and leave point
2520 where it is if the headline is a valid target for refiling.
2522 If the target should not be selected, the function must return nil.
2523 In addition to this, it may move point to a place from where the search
2524 should be continued. For example, the function may decide that the entire
2525 subtree of the current entry should be excluded and move point to the end
2526 of the subtree."
2527 :group 'org-refile
2528 :type '(choice
2529 (const nil)
2530 (function)))
2532 (defcustom org-refile-use-cache nil
2533 "Non-nil means cache refile targets to speed up the process.
2534 \\<org-mode-map>\
2535 The cache for a particular file will be updated automatically when
2536 the buffer has been killed, or when any of the marker used for flagging
2537 refile targets no longer points at a live buffer.
2538 If you have added new entries to a buffer that might themselves be targets,
2539 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2540 if you find that easier, \
2541 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2542 \\[org-refile]'."
2543 :group 'org-refile
2544 :version "24.1"
2545 :type 'boolean)
2547 (defcustom org-refile-use-outline-path nil
2548 "Non-nil means provide refile targets as paths.
2549 So a level 3 headline will be available as level1/level2/level3.
2551 When the value is `file', also include the file name (without directory)
2552 into the path. In this case, you can also stop the completion after
2553 the file name, to get entries inserted as top level in the file.
2555 When `full-file-path', include the full file path."
2556 :group 'org-refile
2557 :type '(choice
2558 (const :tag "Not" nil)
2559 (const :tag "Yes" t)
2560 (const :tag "Start with file name" file)
2561 (const :tag "Start with full file path" full-file-path)))
2563 (defcustom org-outline-path-complete-in-steps t
2564 "Non-nil means complete the outline path in hierarchical steps.
2565 When Org uses the refile interface to select an outline path (see
2566 `org-refile-use-outline-path'), the completion of the path can be
2567 done in a single go, or it can be done in steps down the headline
2568 hierarchy. Going in steps is probably the best if you do not use
2569 a special completion package like `ido' or `icicles'. However,
2570 when using these packages, going in one step can be very fast,
2571 while still showing the whole path to the entry."
2572 :group 'org-refile
2573 :type 'boolean)
2575 (defcustom org-refile-allow-creating-parent-nodes nil
2576 "Non-nil means allow the creation of new nodes as refile targets.
2577 New nodes are then created by adding \"/new node name\" to the completion
2578 of an existing node. When the value of this variable is `confirm',
2579 new node creation must be confirmed by the user (recommended).
2580 When nil, the completion must match an existing entry.
2582 Note that, if the new heading is not seen by the criteria
2583 listed in `org-refile-targets', multiple instances of the same
2584 heading would be created by trying again to file under the new
2585 heading."
2586 :group 'org-refile
2587 :type '(choice
2588 (const :tag "Never" nil)
2589 (const :tag "Always" t)
2590 (const :tag "Prompt for confirmation" confirm)))
2592 (defcustom org-refile-active-region-within-subtree nil
2593 "Non-nil means also refile active region within a subtree.
2595 By default `org-refile' doesn't allow refiling regions if they
2596 don't contain a set of subtrees, but it might be convenient to
2597 do so sometimes: in that case, the first line of the region is
2598 converted to a headline before refiling."
2599 :group 'org-refile
2600 :version "24.1"
2601 :type 'boolean)
2603 (defgroup org-todo nil
2604 "Options concerning TODO items in Org mode."
2605 :tag "Org TODO"
2606 :group 'org)
2608 (defgroup org-progress nil
2609 "Options concerning Progress logging in Org mode."
2610 :tag "Org Progress"
2611 :group 'org-time)
2613 (defvar org-todo-interpretation-widgets
2614 '((:tag "Sequence (cycling hits every state)" sequence)
2615 (:tag "Type (cycling directly to DONE)" type))
2616 "The available interpretation symbols for customizing `org-todo-keywords'.
2617 Interested libraries should add to this list.")
2619 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2620 "List of TODO entry keyword sequences and their interpretation.
2621 \\<org-mode-map>This is a list of sequences.
2623 Each sequence starts with a symbol, either `sequence' or `type',
2624 indicating if the keywords should be interpreted as a sequence of
2625 action steps, or as different types of TODO items. The first
2626 keywords are states requiring action - these states will select a headline
2627 for inclusion into the global TODO list Org produces. If one of the
2628 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2629 signify that no further action is necessary. If \"|\" is not found,
2630 the last keyword is treated as the only DONE state of the sequence.
2632 The command `\\[org-todo]' cycles an entry through these states, and one
2633 additional state where no keyword is present. For details about this
2634 cycling, see the manual.
2636 TODO keywords and interpretation can also be set on a per-file basis with
2637 the special #+SEQ_TODO and #+TYP_TODO lines.
2639 Each keyword can optionally specify a character for fast state selection
2640 \(in combination with the variable `org-use-fast-todo-selection')
2641 and specifiers for state change logging, using the same syntax that
2642 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2643 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2644 indicates to record a time stamp each time this state is selected.
2646 Each keyword may also specify if a timestamp or a note should be
2647 recorded when entering or leaving the state, by adding additional
2648 characters in the parenthesis after the keyword. This looks like this:
2649 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2650 record only the time of the state change. With X and Y being either
2651 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2652 Y when leaving the state if and only if the *target* state does not
2653 define X. You may omit any of the fast-selection key or X or /Y,
2654 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2656 For backward compatibility, this variable may also be just a list
2657 of keywords. In this case the interpretation (sequence or type) will be
2658 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2659 :group 'org-todo
2660 :group 'org-keywords
2661 :type '(choice
2662 (repeat :tag "Old syntax, just keywords"
2663 (string :tag "Keyword"))
2664 (repeat :tag "New syntax"
2665 (cons
2666 (choice
2667 :tag "Interpretation"
2668 ;;Quick and dirty way to see
2669 ;;`org-todo-interpretations'. This takes the
2670 ;;place of item arguments
2671 :convert-widget
2672 (lambda (widget)
2673 (widget-put widget
2674 :args (mapcar
2675 (lambda (x)
2676 (widget-convert
2677 (cons 'const x)))
2678 org-todo-interpretation-widgets))
2679 widget))
2680 (repeat
2681 (string :tag "Keyword"))))))
2683 (defvar-local org-todo-keywords-1 nil
2684 "All TODO and DONE keywords active in a buffer.")
2685 (defvar org-todo-keywords-for-agenda nil)
2686 (defvar org-done-keywords-for-agenda nil)
2687 (defvar org-todo-keyword-alist-for-agenda nil)
2688 (defvar org-tag-alist-for-agenda nil
2689 "Alist of all tags from all agenda files.")
2690 (defvar org-tag-groups-alist-for-agenda nil
2691 "Alist of all groups tags from all current agenda files.")
2692 (defvar-local org-tag-groups-alist nil)
2693 (defvar org-agenda-contributing-files nil)
2694 (defvar-local org-current-tag-alist nil
2695 "Alist of all tag groups in current buffer.
2696 This variable takes into consideration `org-tag-alist',
2697 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2698 (defvar-local org-not-done-keywords nil)
2699 (defvar-local org-done-keywords nil)
2700 (defvar-local org-todo-heads nil)
2701 (defvar-local org-todo-sets nil)
2702 (defvar-local org-todo-log-states nil)
2703 (defvar-local org-todo-kwd-alist nil)
2704 (defvar-local org-todo-key-alist nil)
2705 (defvar-local org-todo-key-trigger nil)
2707 (defcustom org-todo-interpretation 'sequence
2708 "Controls how TODO keywords are interpreted.
2709 This variable is in principle obsolete and is only used for
2710 backward compatibility, if the interpretation of todo keywords is
2711 not given already in `org-todo-keywords'. See that variable for
2712 more information."
2713 :group 'org-todo
2714 :group 'org-keywords
2715 :type '(choice (const sequence)
2716 (const type)))
2718 (defcustom org-use-fast-todo-selection t
2719 "\\<org-mode-map>\
2720 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2721 This variable describes if and under what circumstances the cycling
2722 mechanism for TODO keywords will be replaced by a single-key, direct
2723 selection scheme.
2725 When nil, fast selection is never used.
2727 When the symbol `prefix', it will be used when `org-todo' is called
2728 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2729 in an Org buffer, and
2730 `\\[universal-argument] t' in an agenda buffer.
2732 When t, fast selection is used by default. In this case, the prefix
2733 argument forces cycling instead.
2735 In all cases, the special interface is only used if access keys have
2736 actually been assigned by the user, i.e. if keywords in the configuration
2737 are followed by a letter in parenthesis, like TODO(t)."
2738 :group 'org-todo
2739 :type '(choice
2740 (const :tag "Never" nil)
2741 (const :tag "By default" t)
2742 (const :tag "Only with C-u C-c C-t" prefix)))
2744 (defcustom org-provide-todo-statistics t
2745 "Non-nil means update todo statistics after insert and toggle.
2746 ALL-HEADLINES means update todo statistics by including headlines
2747 with no TODO keyword as well, counting them as not done.
2748 A list of TODO keywords means the same, but skip keywords that are
2749 not in this list.
2750 When set to a list of two lists, the first list contains keywords
2751 to consider as TODO keywords, the second list contains keywords
2752 to consider as DONE keywords.
2754 When this is set, todo statistics is updated in the parent of the
2755 current entry each time a todo state is changed."
2756 :group 'org-todo
2757 :type '(choice
2758 (const :tag "Yes, only for TODO entries" t)
2759 (const :tag "Yes, including all entries" all-headlines)
2760 (repeat :tag "Yes, for TODOs in this list"
2761 (string :tag "TODO keyword"))
2762 (list :tag "Yes, for TODOs and DONEs in these lists"
2763 (repeat (string :tag "TODO keyword"))
2764 (repeat (string :tag "DONE keyword")))
2765 (other :tag "No TODO statistics" nil)))
2767 (defcustom org-hierarchical-todo-statistics t
2768 "Non-nil means TODO statistics covers just direct children.
2769 When nil, all entries in the subtree are considered.
2770 This has only an effect if `org-provide-todo-statistics' is set.
2771 To set this to nil for only a single subtree, use a COOKIE_DATA
2772 property and include the word \"recursive\" into the value."
2773 :group 'org-todo
2774 :type 'boolean)
2776 (defcustom org-after-todo-state-change-hook nil
2777 "Hook which is run after the state of a TODO item was changed.
2778 The new state (a string with a TODO keyword, or nil) is available in the
2779 Lisp variable `org-state'."
2780 :group 'org-todo
2781 :type 'hook)
2783 (defvar org-blocker-hook nil
2784 "Hook for functions that are allowed to block a state change.
2786 Functions in this hook should not modify the buffer.
2787 Each function gets as its single argument a property list,
2788 see `org-trigger-hook' for more information about this list.
2790 If any of the functions in this hook returns nil, the state change
2791 is blocked.")
2793 (defvar org-trigger-hook nil
2794 "Hook for functions that are triggered by a state change.
2796 Each function gets as its single argument a property list with at
2797 least the following elements:
2799 (:type type-of-change :position pos-at-entry-start
2800 :from old-state :to new-state)
2802 Depending on the type, more properties may be present.
2804 This mechanism is currently implemented for:
2806 TODO state changes
2807 ------------------
2808 :type todo-state-change
2809 :from previous state (keyword as a string), or nil, or a symbol
2810 `todo' or `done', to indicate the general type of state.
2811 :to new state, like in :from")
2813 (defcustom org-enforce-todo-dependencies nil
2814 "Non-nil means undone TODO entries will block switching the parent to DONE.
2815 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2816 be blocked if any prior sibling is not yet done.
2817 Finally, if the parent is blocked because of ordered siblings of its own,
2818 the child will also be blocked."
2819 :set (lambda (var val)
2820 (set var val)
2821 (if val
2822 (add-hook 'org-blocker-hook
2823 'org-block-todo-from-children-or-siblings-or-parent)
2824 (remove-hook 'org-blocker-hook
2825 'org-block-todo-from-children-or-siblings-or-parent)))
2826 :group 'org-todo
2827 :type 'boolean)
2829 (defcustom org-enforce-todo-checkbox-dependencies nil
2830 "Non-nil means unchecked boxes will block switching the parent to DONE.
2831 When this is nil, checkboxes have no influence on switching TODO states.
2832 When non-nil, you first need to check off all check boxes before the TODO
2833 entry can be switched to DONE.
2834 This variable needs to be set before org.el is loaded, and you need to
2835 restart Emacs after a change to make the change effective. The only way
2836 to change is while Emacs is running is through the customize interface."
2837 :set (lambda (var val)
2838 (set var val)
2839 (if val
2840 (add-hook 'org-blocker-hook
2841 'org-block-todo-from-checkboxes)
2842 (remove-hook 'org-blocker-hook
2843 'org-block-todo-from-checkboxes)))
2844 :group 'org-todo
2845 :type 'boolean)
2847 (defcustom org-treat-insert-todo-heading-as-state-change nil
2848 "Non-nil means inserting a TODO heading is treated as state change.
2849 So when the command `\\[org-insert-todo-heading]' is used, state change
2850 logging will apply if appropriate. When nil, the new TODO item will
2851 be inserted directly, and no logging will take place."
2852 :group 'org-todo
2853 :type 'boolean)
2855 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2856 "Non-nil means switching TODO states with S-cursor counts as state change.
2857 This is the default behavior. However, setting this to nil allows a
2858 convenient way to select a TODO state and bypass any logging associated
2859 with that."
2860 :group 'org-todo
2861 :type 'boolean)
2863 (defcustom org-todo-state-tags-triggers nil
2864 "Tag changes that should be triggered by TODO state changes.
2865 This is a list. Each entry is
2867 (state-change (tag . flag) .......)
2869 State-change can be a string with a state, and empty string to indicate the
2870 state that has no TODO keyword, or it can be one of the symbols `todo'
2871 or `done', meaning any not-done or done state, respectively."
2872 :group 'org-todo
2873 :group 'org-tags
2874 :type '(repeat
2875 (cons (choice :tag "When changing to"
2876 (const :tag "Not-done state" todo)
2877 (const :tag "Done state" done)
2878 (string :tag "State"))
2879 (repeat
2880 (cons :tag "Tag action"
2881 (string :tag "Tag")
2882 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2884 (defcustom org-log-done nil
2885 "Information to record when a task moves to the DONE state.
2887 Possible values are:
2889 nil Don't add anything, just change the keyword
2890 time Add a time stamp to the task
2891 note Prompt for a note and add it with template `org-log-note-headings'
2893 This option can also be set with on a per-file-basis with
2895 #+STARTUP: nologdone
2896 #+STARTUP: logdone
2897 #+STARTUP: lognotedone
2899 You can have local logging settings for a subtree by setting the LOGGING
2900 property to one or more of these keywords."
2901 :group 'org-todo
2902 :group 'org-progress
2903 :type '(choice
2904 (const :tag "No logging" nil)
2905 (const :tag "Record CLOSED timestamp" time)
2906 (const :tag "Record CLOSED timestamp with note." note)))
2908 ;; Normalize old uses of org-log-done.
2909 (cond
2910 ((eq org-log-done t) (setq org-log-done 'time))
2911 ((and (listp org-log-done) (memq 'done org-log-done))
2912 (setq org-log-done 'note)))
2914 (defcustom org-log-reschedule nil
2915 "Information to record when the scheduling date of a tasks is modified.
2917 Possible values are:
2919 nil Don't add anything, just change the date
2920 time Add a time stamp to the task
2921 note Prompt for a note and add it with template `org-log-note-headings'
2923 This option can also be set with on a per-file-basis with
2925 #+STARTUP: nologreschedule
2926 #+STARTUP: logreschedule
2927 #+STARTUP: lognotereschedule"
2928 :group 'org-todo
2929 :group 'org-progress
2930 :type '(choice
2931 (const :tag "No logging" nil)
2932 (const :tag "Record timestamp" time)
2933 (const :tag "Record timestamp with note." note)))
2935 (defcustom org-log-redeadline nil
2936 "Information to record when the deadline date of a tasks is modified.
2938 Possible values are:
2940 nil Don't add anything, just change the date
2941 time Add a time stamp to the task
2942 note Prompt for a note and add it with template `org-log-note-headings'
2944 This option can also be set with on a per-file-basis with
2946 #+STARTUP: nologredeadline
2947 #+STARTUP: logredeadline
2948 #+STARTUP: lognoteredeadline
2950 You can have local logging settings for a subtree by setting the LOGGING
2951 property to one or more of these keywords."
2952 :group 'org-todo
2953 :group 'org-progress
2954 :type '(choice
2955 (const :tag "No logging" nil)
2956 (const :tag "Record timestamp" time)
2957 (const :tag "Record timestamp with note." note)))
2959 (defcustom org-log-note-clock-out nil
2960 "Non-nil means record a note when clocking out of an item.
2961 This can also be configured on a per-file basis by adding one of
2962 the following lines anywhere in the buffer:
2964 #+STARTUP: lognoteclock-out
2965 #+STARTUP: nolognoteclock-out"
2966 :group 'org-todo
2967 :group 'org-progress
2968 :type 'boolean)
2970 (defcustom org-log-done-with-time t
2971 "Non-nil means the CLOSED time stamp will contain date and time.
2972 When nil, only the date will be recorded."
2973 :group 'org-progress
2974 :type 'boolean)
2976 (defcustom org-log-note-headings
2977 '((done . "CLOSING NOTE %t")
2978 (state . "State %-12s from %-12S %t")
2979 (note . "Note taken on %t")
2980 (reschedule . "Rescheduled from %S on %t")
2981 (delschedule . "Not scheduled, was %S on %t")
2982 (redeadline . "New deadline from %S on %t")
2983 (deldeadline . "Removed deadline, was %S on %t")
2984 (refile . "Refiled on %t")
2985 (clock-out . ""))
2986 "Headings for notes added to entries.
2988 The value is an alist, with the car being a symbol indicating the
2989 note context, and the cdr is the heading to be used. The heading
2990 may also be the empty string. The following placeholders can be
2991 used:
2993 %t a time stamp.
2994 %T an active time stamp instead the default inactive one
2995 %d a short-format time stamp.
2996 %D an active short-format time stamp.
2997 %s the new TODO state or time stamp (inactive), in double quotes.
2998 %S the old TODO state or time stamp (inactive), in double quotes.
2999 %u the user name.
3000 %U full user name.
3002 In fact, it is not a good idea to change the `state' entry,
3003 because Agenda Log mode depends on the format of these entries."
3004 :group 'org-todo
3005 :group 'org-progress
3006 :type '(list :greedy t
3007 (cons (const :tag "Heading when closing an item" done) string)
3008 (cons (const :tag
3009 "Heading when changing todo state (todo sequence only)"
3010 state) string)
3011 (cons (const :tag "Heading when just taking a note" note) string)
3012 (cons (const :tag "Heading when rescheduling" reschedule) string)
3013 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3014 (cons (const :tag "Heading when changing deadline" redeadline) string)
3015 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3016 (cons (const :tag "Heading when refiling" refile) string)
3017 (cons (const :tag "Heading when clocking out" clock-out) string)))
3019 (unless (assq 'note org-log-note-headings)
3020 (push '(note . "%t") org-log-note-headings))
3022 (defcustom org-log-into-drawer nil
3023 "Non-nil means insert state change notes and time stamps into a drawer.
3024 When nil, state changes notes will be inserted after the headline and
3025 any scheduling and clock lines, but not inside a drawer.
3027 The value of this variable should be the name of the drawer to use.
3028 LOGBOOK is proposed as the default drawer for this purpose, you can
3029 also set this to a string to define the drawer of your choice.
3031 A value of t is also allowed, representing \"LOGBOOK\".
3033 A value of t or nil can also be set with on a per-file-basis with
3035 #+STARTUP: logdrawer
3036 #+STARTUP: nologdrawer
3038 If this variable is set, `org-log-state-notes-insert-after-drawers'
3039 will be ignored.
3041 You can set the property LOG_INTO_DRAWER to overrule this setting for
3042 a subtree.
3044 Do not check directly this variable in a Lisp program. Call
3045 function `org-log-into-drawer' instead."
3046 :group 'org-todo
3047 :group 'org-progress
3048 :type '(choice
3049 (const :tag "Not into a drawer" nil)
3050 (const :tag "LOGBOOK" t)
3051 (string :tag "Other")))
3053 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3055 (defun org-log-into-drawer ()
3056 "Name of the log drawer, as a string, or nil.
3057 This is the value of `org-log-into-drawer'. However, if the
3058 current entry has or inherits a LOG_INTO_DRAWER property, it will
3059 be used instead of the default value."
3060 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3061 (cond ((equal p "nil") nil)
3062 ((equal p "t") "LOGBOOK")
3063 ((stringp p) p)
3064 (p "LOGBOOK")
3065 ((stringp org-log-into-drawer) org-log-into-drawer)
3066 (org-log-into-drawer "LOGBOOK"))))
3068 (defcustom org-log-state-notes-insert-after-drawers nil
3069 "Non-nil means insert state change notes after any drawers in entry.
3070 Only the drawers that *immediately* follow the headline and the
3071 deadline/scheduled line are skipped.
3072 When nil, insert notes right after the heading and perhaps the line
3073 with deadline/scheduling if present.
3075 This variable will have no effect if `org-log-into-drawer' is
3076 set."
3077 :group 'org-todo
3078 :group 'org-progress
3079 :type 'boolean)
3081 (defcustom org-log-states-order-reversed t
3082 "Non-nil means the latest state note will be directly after heading.
3083 When nil, the state change notes will be ordered according to time.
3085 This option can also be set with on a per-file-basis with
3087 #+STARTUP: logstatesreversed
3088 #+STARTUP: nologstatesreversed"
3089 :group 'org-todo
3090 :group 'org-progress
3091 :type 'boolean)
3093 (defcustom org-todo-repeat-to-state nil
3094 "The TODO state to which a repeater should return the repeating task.
3095 By default this is the first task in a TODO sequence, or the previous state
3096 in a TODO_TYP set. But you can specify another task here.
3097 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3098 :group 'org-todo
3099 :version "24.1"
3100 :type '(choice (const :tag "Head of sequence" nil)
3101 (string :tag "Specific state")))
3103 (defcustom org-log-repeat 'time
3104 "Non-nil means record moving through the DONE state when triggering repeat.
3105 An auto-repeating task is immediately switched back to TODO when
3106 marked DONE. If you are not logging state changes (by adding \"@\"
3107 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3108 record a closing note, there will be no record of the task moving
3109 through DONE. This variable forces taking a note anyway.
3111 nil Don't force a record
3112 time Record a time stamp
3113 note Prompt for a note and add it with template `org-log-note-headings'
3115 This option can also be set with on a per-file-basis with
3117 #+STARTUP: nologrepeat
3118 #+STARTUP: logrepeat
3119 #+STARTUP: lognoterepeat
3121 You can have local logging settings for a subtree by setting the LOGGING
3122 property to one or more of these keywords."
3123 :group 'org-todo
3124 :group 'org-progress
3125 :type '(choice
3126 (const :tag "Don't force a record" nil)
3127 (const :tag "Force recording the DONE state" time)
3128 (const :tag "Force recording a note with the DONE state" note)))
3131 (defgroup org-priorities nil
3132 "Priorities in Org mode."
3133 :tag "Org Priorities"
3134 :group 'org-todo)
3136 (defcustom org-enable-priority-commands t
3137 "Non-nil means priority commands are active.
3138 When nil, these commands will be disabled, so that you never accidentally
3139 set a priority."
3140 :group 'org-priorities
3141 :type 'boolean)
3143 (defcustom org-highest-priority ?A
3144 "The highest priority of TODO items. A character like ?A, ?B etc.
3145 Must have a smaller ASCII number than `org-lowest-priority'."
3146 :group 'org-priorities
3147 :type 'character)
3149 (defcustom org-lowest-priority ?C
3150 "The lowest priority of TODO items. A character like ?A, ?B etc.
3151 Must have a larger ASCII number than `org-highest-priority'."
3152 :group 'org-priorities
3153 :type 'character)
3155 (defcustom org-default-priority ?B
3156 "The default priority of TODO items.
3157 This is the priority an item gets if no explicit priority is given.
3158 When starting to cycle on an empty priority the first step in the cycle
3159 depends on `org-priority-start-cycle-with-default'. The resulting first
3160 step priority must not exceed the range from `org-highest-priority' to
3161 `org-lowest-priority' which means that `org-default-priority' has to be
3162 in this range exclusive or inclusive the range boundaries. Else the
3163 first step refuses to set the default and the second will fall back
3164 to (depending on the command used) the highest or lowest priority."
3165 :group 'org-priorities
3166 :type 'character)
3168 (defcustom org-priority-start-cycle-with-default t
3169 "Non-nil means start with default priority when starting to cycle.
3170 When this is nil, the first step in the cycle will be (depending on the
3171 command used) one higher or lower than the default priority.
3172 See also `org-default-priority'."
3173 :group 'org-priorities
3174 :type 'boolean)
3176 (defcustom org-get-priority-function nil
3177 "Function to extract the priority from a string.
3178 The string is normally the headline. If this is nil Org computes the
3179 priority from the priority cookie like [#A] in the headline. It returns
3180 an integer, increasing by 1000 for each priority level.
3181 The user can set a different function here, which should take a string
3182 as an argument and return the numeric priority."
3183 :group 'org-priorities
3184 :version "24.1"
3185 :type '(choice
3186 (const nil)
3187 (function)))
3189 (defgroup org-time nil
3190 "Options concerning time stamps and deadlines in Org mode."
3191 :tag "Org Time"
3192 :group 'org)
3194 (defcustom org-time-stamp-rounding-minutes '(0 5)
3195 "Number of minutes to round time stamps to.
3196 \\<org-mode-map>\
3197 These are two values, the first applies when first creating a time stamp.
3198 The second applies when changing it with the commands `S-up' and `S-down'.
3199 When changing the time stamp, this means that it will change in steps
3200 of N minutes, as given by the second value.
3202 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3203 numbers should be factors of 60, so for example 5, 10, 15.
3205 When this is larger than 1, you can still force an exact time stamp by using
3206 a double prefix argument to a time stamp command like \
3207 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3208 and by using a prefix arg to `S-up/down' to specify the exact number
3209 of minutes to shift."
3210 :group 'org-time
3211 :get (lambda (var) ; Make sure both elements are there
3212 (if (integerp (default-value var))
3213 (list (default-value var) 5)
3214 (default-value var)))
3215 :type '(list
3216 (integer :tag "when inserting times")
3217 (integer :tag "when modifying times")))
3219 ;; Normalize old customizations of this variable.
3220 (when (integerp org-time-stamp-rounding-minutes)
3221 (setq org-time-stamp-rounding-minutes
3222 (list org-time-stamp-rounding-minutes
3223 org-time-stamp-rounding-minutes)))
3225 (defcustom org-display-custom-times nil
3226 "Non-nil means overlay custom formats over all time stamps.
3227 The formats are defined through the variable `org-time-stamp-custom-formats'.
3228 To turn this on on a per-file basis, insert anywhere in the file:
3229 #+STARTUP: customtime"
3230 :group 'org-time
3231 :set 'set-default
3232 :type 'sexp)
3233 (make-variable-buffer-local 'org-display-custom-times)
3235 (defcustom org-time-stamp-custom-formats
3236 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3237 "Custom formats for time stamps. See `format-time-string' for the syntax.
3238 These are overlaid over the default ISO format if the variable
3239 `org-display-custom-times' is set. Time like %H:%M should be at the
3240 end of the second format. The custom formats are also honored by export
3241 commands, if custom time display is turned on at the time of export."
3242 :group 'org-time
3243 :type 'sexp)
3245 (defun org-time-stamp-format (&optional long inactive)
3246 "Get the right format for a time string."
3247 (let ((f (if long (cdr org-time-stamp-formats)
3248 (car org-time-stamp-formats))))
3249 (if inactive
3250 (concat "[" (substring f 1 -1) "]")
3251 f)))
3253 (defcustom org-deadline-warning-days 14
3254 "Number of days before expiration during which a deadline becomes active.
3255 This variable governs the display in sparse trees and in the agenda.
3256 When 0 or negative, it means use this number (the absolute value of it)
3257 even if a deadline has a different individual lead time specified.
3259 Custom commands can set this variable in the options section."
3260 :group 'org-time
3261 :group 'org-agenda-daily/weekly
3262 :type 'integer)
3264 (defcustom org-scheduled-delay-days 0
3265 "Number of days before a scheduled item becomes active.
3266 This variable governs the display in sparse trees and in the agenda.
3267 The default value (i.e. 0) means: don't delay scheduled item.
3268 When negative, it means use this number (the absolute value of it)
3269 even if a scheduled item has a different individual delay time
3270 specified.
3272 Custom commands can set this variable in the options section."
3273 :group 'org-time
3274 :group 'org-agenda-daily/weekly
3275 :version "24.4"
3276 :package-version '(Org . "8.0")
3277 :type 'integer)
3279 (defcustom org-read-date-prefer-future t
3280 "Non-nil means assume future for incomplete date input from user.
3281 This affects the following situations:
3282 1. The user gives a month but not a year.
3283 For example, if it is April and you enter \"feb 2\", this will be read
3284 as Feb 2, *next* year. \"May 5\", however, will be this year.
3285 2. The user gives a day, but no month.
3286 For example, if today is the 15th, and you enter \"3\", Org will read
3287 this as the third of *next* month. However, if you enter \"17\",
3288 it will be considered as *this* month.
3290 If you set this variable to the symbol `time', then also the following
3291 will work:
3293 3. If the user gives a time.
3294 If the time is before now, it will be interpreted as tomorrow.
3296 Currently none of this works for ISO week specifications.
3298 When this option is nil, the current day, month and year will always be
3299 used as defaults.
3301 See also `org-agenda-jump-prefer-future'."
3302 :group 'org-time
3303 :type '(choice
3304 (const :tag "Never" nil)
3305 (const :tag "Check month and day" t)
3306 (const :tag "Check month, day, and time" time)))
3308 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3309 "Should the agenda jump command prefer the future for incomplete dates?
3310 The default is to do the same as configured in `org-read-date-prefer-future'.
3311 But you can also set a deviating value here.
3312 This may t or nil, or the symbol `org-read-date-prefer-future'."
3313 :group 'org-agenda
3314 :group 'org-time
3315 :version "24.1"
3316 :type '(choice
3317 (const :tag "Use org-read-date-prefer-future"
3318 org-read-date-prefer-future)
3319 (const :tag "Never" nil)
3320 (const :tag "Always" t)))
3322 (defcustom org-read-date-force-compatible-dates t
3323 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3325 Depending on the system Emacs is running on, certain dates cannot
3326 be represented with the type used internally to represent time.
3327 Dates between 1970-1-1 and 2038-1-1 can always be represented
3328 correctly. Some systems allow for earlier dates, some for later,
3329 some for both. One way to find out it to insert any date into an
3330 Org buffer, putting the cursor on the year and hitting S-up and
3331 S-down to test the range.
3333 When this variable is set to t, the date/time prompt will not let
3334 you specify dates outside the 1970-2037 range, so it is certain that
3335 these dates will work in whatever version of Emacs you are
3336 running, and also that you can move a file from one Emacs implementation
3337 to another. WHenever Org is forcing the year for you, it will display
3338 a message and beep.
3340 When this variable is nil, Org will check if the date is
3341 representable in the specific Emacs implementation you are using.
3342 If not, it will force a year, usually the current year, and beep
3343 to remind you. Currently this setting is not recommended because
3344 the likelihood that you will open your Org files in an Emacs that
3345 has limited date range is not negligible.
3347 A workaround for this problem is to use diary sexp dates for time
3348 stamps outside of this range."
3349 :group 'org-time
3350 :version "24.1"
3351 :type 'boolean)
3353 (defcustom org-read-date-display-live t
3354 "Non-nil means display current interpretation of date prompt live.
3355 This display will be in an overlay, in the minibuffer."
3356 :group 'org-time
3357 :type 'boolean)
3359 (defcustom org-read-date-popup-calendar t
3360 "Non-nil means pop up a calendar when prompting for a date.
3361 In the calendar, the date can be selected with mouse-1. However, the
3362 minibuffer will also be active, and you can simply enter the date as well.
3363 When nil, only the minibuffer will be available."
3364 :group 'org-time
3365 :type 'boolean)
3366 (defvaralias 'org-popup-calendar-for-date-prompt
3367 'org-read-date-popup-calendar)
3369 (defcustom org-extend-today-until 0
3370 "The hour when your day really ends. Must be an integer.
3371 This has influence for the following applications:
3372 - When switching the agenda to \"today\". It it is still earlier than
3373 the time given here, the day recognized as TODAY is actually yesterday.
3374 - When a date is read from the user and it is still before the time given
3375 here, the current date and time will be assumed to be yesterday, 23:59.
3376 Also, timestamps inserted in capture templates follow this rule.
3378 IMPORTANT: This is a feature whose implementation is and likely will
3379 remain incomplete. Really, it is only here because past midnight seems to
3380 be the favorite working time of John Wiegley :-)"
3381 :group 'org-time
3382 :type 'integer)
3384 (defcustom org-use-effective-time nil
3385 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3386 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3387 \"effective time\" of any timestamps between midnight and 8am will be
3388 23:59 of the previous day."
3389 :group 'org-time
3390 :version "24.1"
3391 :type 'boolean)
3393 (defcustom org-use-last-clock-out-time-as-effective-time nil
3394 "When non-nil, use the last clock out time for `org-todo'.
3395 Note that this option has precedence over the combined use of
3396 `org-use-effective-time' and `org-extend-today-until'."
3397 :group 'org-time
3398 :version "24.4"
3399 :package-version '(Org . "8.0")
3400 :type 'boolean)
3402 (defcustom org-edit-timestamp-down-means-later nil
3403 "Non-nil means S-down will increase the time in a time stamp.
3404 When nil, S-up will increase."
3405 :group 'org-time
3406 :type 'boolean)
3408 (defcustom org-calendar-follow-timestamp-change t
3409 "Non-nil means make the calendar window follow timestamp changes.
3410 When a timestamp is modified and the calendar window is visible, it will be
3411 moved to the new date."
3412 :group 'org-time
3413 :type 'boolean)
3415 (defgroup org-tags nil
3416 "Options concerning tags in Org mode."
3417 :tag "Org Tags"
3418 :group 'org)
3420 (defcustom org-tag-alist nil
3421 "Default tags available in Org files.
3423 The value of this variable is an alist. Associations either:
3425 (TAG)
3426 (TAG . SELECT)
3427 (SPECIAL)
3429 where TAG is a tag as a string, SELECT is character, used to
3430 select that tag through the fast tag selection interface, and
3431 SPECIAL is one of the following keywords: `:startgroup',
3432 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3433 `:newline'. These keywords are used to define a hierarchy of
3434 tags. See manual for details.
3436 When this variable is nil, Org mode bases tag input on what is
3437 already in the buffer. The value can be overridden locally by
3438 using a TAGS keyword, e.g.,
3440 #+TAGS: tag1 tag2
3442 See also `org-tag-persistent-alist' to sidestep this behavior."
3443 :group 'org-tags
3444 :type '(repeat
3445 (choice
3446 (cons (string :tag "Tag name")
3447 (character :tag "Access char"))
3448 (const :tag "Start radio group" (:startgroup))
3449 (const :tag "Start tag group, non distinct" (:startgrouptag))
3450 (const :tag "Group tags delimiter" (:grouptags))
3451 (const :tag "End radio group" (:endgroup))
3452 (const :tag "End tag group, non distinct" (:endgrouptag))
3453 (const :tag "New line" (:newline)))))
3455 (defcustom org-tag-persistent-alist nil
3456 "Tags always available in Org files.
3458 The value of this variable is an alist. Associations either:
3460 (TAG)
3461 (TAG . SELECT)
3462 (SPECIAL)
3464 where TAG is a tag as a string, SELECT is a character, used to
3465 select that tag through the fast tag selection interface, and
3466 SPECIAL is one of the following keywords: `:startgroup',
3467 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3468 `:newline'. These keywords are used to define a hierarchy of
3469 tags. See manual for details.
3471 Unlike to `org-tag-alist', tags defined in this variable do not
3472 depend on a local TAGS keyword. Instead, to disable these tags
3473 on a per-file basis, insert anywhere in the file:
3475 #+STARTUP: noptag"
3476 :group 'org-tags
3477 :type '(repeat
3478 (choice
3479 (cons (string :tag "Tag name")
3480 (character :tag "Access char"))
3481 (const :tag "Start radio group" (:startgroup))
3482 (const :tag "Start tag group, non distinct" (:startgrouptag))
3483 (const :tag "Group tags delimiter" (:grouptags))
3484 (const :tag "End radio group" (:endgroup))
3485 (const :tag "End tag group, non distinct" (:endgrouptag))
3486 (const :tag "New line" (:newline)))))
3488 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3489 "If non-nil, always offer completion for all tags of all agenda files.
3490 Instead of customizing this variable directly, you might want to
3491 set it locally for capture buffers, because there no list of
3492 tags in that file can be created dynamically (there are none).
3494 (add-hook \\='org-capture-mode-hook
3495 (lambda ()
3496 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3497 :group 'org-tags
3498 :version "24.1"
3499 :type 'boolean)
3501 (defvar org-file-tags nil
3502 "List of tags that can be inherited by all entries in the file.
3503 The tags will be inherited if the variable `org-use-tag-inheritance'
3504 says they should be.
3505 This variable is populated from #+FILETAGS lines.")
3507 (defcustom org-use-fast-tag-selection 'auto
3508 "Non-nil means use fast tag selection scheme.
3509 This is a special interface to select and deselect tags with single keys.
3510 When nil, fast selection is never used.
3511 When the symbol `auto', fast selection is used if and only if selection
3512 characters for tags have been configured, either through the variable
3513 `org-tag-alist' or through a #+TAGS line in the buffer.
3514 When t, fast selection is always used and selection keys are assigned
3515 automatically if necessary."
3516 :group 'org-tags
3517 :type '(choice
3518 (const :tag "Always" t)
3519 (const :tag "Never" nil)
3520 (const :tag "When selection characters are configured" auto)))
3522 (defcustom org-fast-tag-selection-single-key nil
3523 "Non-nil means fast tag selection exits after first change.
3524 When nil, you have to press RET to exit it.
3525 During fast tag selection, you can toggle this flag with `C-c'.
3526 This variable can also have the value `expert'. In this case, the window
3527 displaying the tags menu is not even shown, until you press C-c again."
3528 :group 'org-tags
3529 :type '(choice
3530 (const :tag "No" nil)
3531 (const :tag "Yes" t)
3532 (const :tag "Expert" expert)))
3534 (defvar org-fast-tag-selection-include-todo nil
3535 "Non-nil means fast tags selection interface will also offer TODO states.
3536 This is an undocumented feature, you should not rely on it.")
3538 (defcustom org-tags-column -77
3539 "The column to which tags should be indented in a headline.
3540 If this number is positive, it specifies the column. If it is negative,
3541 it means that the tags should be flushright to that column. For example,
3542 -80 works well for a normal 80 character screen.
3543 When 0, place tags directly after headline text, with only one space in
3544 between."
3545 :group 'org-tags
3546 :type 'integer)
3548 (defcustom org-auto-align-tags t
3549 "Non-nil keeps tags aligned when modifying headlines.
3550 Some operations (i.e. demoting) change the length of a headline and
3551 therefore shift the tags around. With this option turned on, after
3552 each such operation the tags are again aligned to `org-tags-column'."
3553 :group 'org-tags
3554 :type 'boolean)
3556 (defcustom org-use-tag-inheritance t
3557 "Non-nil means tags in levels apply also for sublevels.
3558 When nil, only the tags directly given in a specific line apply there.
3559 This may also be a list of tags that should be inherited, or a regexp that
3560 matches tags that should be inherited. Additional control is possible
3561 with the variable `org-tags-exclude-from-inheritance' which gives an
3562 explicit list of tags to be excluded from inheritance, even if the value of
3563 `org-use-tag-inheritance' would select it for inheritance.
3565 If this option is t, a match early-on in a tree can lead to a large
3566 number of matches in the subtree when constructing the agenda or creating
3567 a sparse tree. If you only want to see the first match in a tree during
3568 a search, check out the variable `org-tags-match-list-sublevels'."
3569 :group 'org-tags
3570 :type '(choice
3571 (const :tag "Not" nil)
3572 (const :tag "Always" t)
3573 (repeat :tag "Specific tags" (string :tag "Tag"))
3574 (regexp :tag "Tags matched by regexp")))
3576 (defcustom org-tags-exclude-from-inheritance nil
3577 "List of tags that should never be inherited.
3578 This is a way to exclude a few tags from inheritance. For way to do
3579 the opposite, to actively allow inheritance for selected tags,
3580 see the variable `org-use-tag-inheritance'."
3581 :group 'org-tags
3582 :type '(repeat (string :tag "Tag")))
3584 (defun org-tag-inherit-p (tag)
3585 "Check if TAG is one that should be inherited."
3586 (cond
3587 ((member tag org-tags-exclude-from-inheritance) nil)
3588 ((eq org-use-tag-inheritance t) t)
3589 ((not org-use-tag-inheritance) nil)
3590 ((stringp org-use-tag-inheritance)
3591 (string-match org-use-tag-inheritance tag))
3592 ((listp org-use-tag-inheritance)
3593 (member tag org-use-tag-inheritance))
3594 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3596 (defcustom org-tags-match-list-sublevels t
3597 "Non-nil means list also sublevels of headlines matching a search.
3598 This variable applies to tags/property searches, and also to stuck
3599 projects because this search is based on a tags match as well.
3601 When set to the symbol `indented', sublevels are indented with
3602 leading dots.
3604 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3605 the sublevels of a headline matching a tag search often also match
3606 the same search. Listing all of them can create very long lists.
3607 Setting this variable to nil causes subtrees of a match to be skipped.
3609 This variable is semi-obsolete and probably should always be true. It
3610 is better to limit inheritance to certain tags using the variables
3611 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3612 :group 'org-tags
3613 :type '(choice
3614 (const :tag "No, don't list them" nil)
3615 (const :tag "Yes, do list them" t)
3616 (const :tag "List them, indented with leading dots" indented)))
3618 (defcustom org-tags-sort-function nil
3619 "When set, tags are sorted using this function as a comparator."
3620 :group 'org-tags
3621 :type '(choice
3622 (const :tag "No sorting" nil)
3623 (const :tag "Alphabetical" string<)
3624 (const :tag "Reverse alphabetical" string>)
3625 (function :tag "Custom function" nil)))
3627 (defvar org-tags-history nil
3628 "History of minibuffer reads for tags.")
3629 (defvar org-last-tags-completion-table nil
3630 "The last used completion table for tags.")
3631 (defvar org-after-tags-change-hook nil
3632 "Hook that is run after the tags in a line have changed.")
3634 (defgroup org-properties nil
3635 "Options concerning properties in Org mode."
3636 :tag "Org Properties"
3637 :group 'org)
3639 (defcustom org-property-format "%-10s %s"
3640 "How property key/value pairs should be formatted by `indent-line'.
3641 When `indent-line' hits a property definition, it will format the line
3642 according to this format, mainly to make sure that the values are
3643 lined-up with respect to each other."
3644 :group 'org-properties
3645 :type 'string)
3647 (defcustom org-properties-postprocess-alist nil
3648 "Alist of properties and functions to adjust inserted values.
3649 Elements of this alist must be of the form
3651 ([string] [function])
3653 where [string] must be a property name and [function] must be a
3654 lambda expression: this lambda expression must take one argument,
3655 the value to adjust, and return the new value as a string.
3657 For example, this element will allow the property \"Remaining\"
3658 to be updated wrt the relation between the \"Effort\" property
3659 and the clock summary:
3661 ((\"Remaining\" (lambda(value)
3662 (let ((clocksum (org-clock-sum-current-item))
3663 (effort (org-duration-to-minutes
3664 (org-entry-get (point) \"Effort\"))))
3665 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3666 :group 'org-properties
3667 :version "24.1"
3668 :type '(alist :key-type (string :tag "Property")
3669 :value-type (function :tag "Function")))
3671 (defcustom org-use-property-inheritance nil
3672 "Non-nil means properties apply also for sublevels.
3674 This setting is chiefly used during property searches. Turning it on can
3675 cause significant overhead when doing a search, which is why it is not
3676 on by default.
3678 When nil, only the properties directly given in the current entry count.
3679 When t, every property is inherited. The value may also be a list of
3680 properties that should have inheritance, or a regular expression matching
3681 properties that should be inherited.
3683 However, note that some special properties use inheritance under special
3684 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3685 and the properties ending in \"_ALL\" when they are used as descriptor
3686 for valid values of a property.
3688 Note for programmers:
3689 When querying an entry with `org-entry-get', you can control if inheritance
3690 should be used. By default, `org-entry-get' looks only at the local
3691 properties. You can request inheritance by setting the inherit argument
3692 to t (to force inheritance) or to `selective' (to respect the setting
3693 in this variable)."
3694 :group 'org-properties
3695 :type '(choice
3696 (const :tag "Not" nil)
3697 (const :tag "Always" t)
3698 (repeat :tag "Specific properties" (string :tag "Property"))
3699 (regexp :tag "Properties matched by regexp")))
3701 (defun org-property-inherit-p (property)
3702 "Return a non-nil value if PROPERTY should be inherited."
3703 (cond
3704 ((eq org-use-property-inheritance t) t)
3705 ((not org-use-property-inheritance) nil)
3706 ((stringp org-use-property-inheritance)
3707 (string-match org-use-property-inheritance property))
3708 ((listp org-use-property-inheritance)
3709 (member-ignore-case property org-use-property-inheritance))
3710 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3712 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3713 "The default column format, if no other format has been defined.
3714 This variable can be set on the per-file basis by inserting a line
3716 #+COLUMNS: %25ITEM ....."
3717 :group 'org-properties
3718 :type 'string)
3720 (defcustom org-columns-ellipses ".."
3721 "The ellipses to be used when a field in column view is truncated.
3722 When this is the empty string, as many characters as possible are shown,
3723 but then there will be no visual indication that the field has been truncated.
3724 When this is a string of length N, the last N characters of a truncated
3725 field are replaced by this string. If the column is narrower than the
3726 ellipses string, only part of the ellipses string will be shown."
3727 :group 'org-properties
3728 :type 'string)
3730 (defconst org-global-properties-fixed
3731 '(("VISIBILITY_ALL" . "folded children content all")
3732 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3733 "List of property/value pairs that can be inherited by any entry.
3735 These are fixed values, for the preset properties. The user variable
3736 that can be used to add to this list is `org-global-properties'.
3738 The entries in this list are cons cells where the car is a property
3739 name and cdr is a string with the value. If the value represents
3740 multiple items like an \"_ALL\" property, separate the items by
3741 spaces.")
3743 (defcustom org-global-properties nil
3744 "List of property/value pairs that can be inherited by any entry.
3746 This list will be combined with the constant `org-global-properties-fixed'.
3748 The entries in this list are cons cells where the car is a property
3749 name and cdr is a string with the value.
3751 You can set buffer-local values for the same purpose in the variable
3752 `org-file-properties' this by adding lines like
3754 #+PROPERTY: NAME VALUE"
3755 :group 'org-properties
3756 :type '(repeat
3757 (cons (string :tag "Property")
3758 (string :tag "Value"))))
3760 (defvar-local org-file-properties nil
3761 "List of property/value pairs that can be inherited by any entry.
3762 Valid for the current buffer.
3763 This variable is populated from #+PROPERTY lines.")
3765 (defgroup org-agenda nil
3766 "Options concerning agenda views in Org mode."
3767 :tag "Org Agenda"
3768 :group 'org)
3770 (defvar-local org-category nil
3771 "Variable used by org files to set a category for agenda display.
3772 Such files should use a file variable to set it, for example
3774 # -*- mode: org; org-category: \"ELisp\"
3776 or contain a special line
3778 #+CATEGORY: ELisp
3780 If the file does not specify a category, then file's base name
3781 is used instead.")
3782 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3784 (defcustom org-agenda-files nil
3785 "The files to be used for agenda display.
3787 If an entry is a directory, all files in that directory that are matched
3788 by `org-agenda-file-regexp' will be part of the file list.
3790 If the value of the variable is not a list but a single file name, then
3791 the list of agenda files is actually stored and maintained in that file,
3792 one agenda file per line. In this file paths can be given relative to
3793 `org-directory'. Tilde expansion and environment variable substitution
3794 are also made.
3796 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3797 and removed with `\\[org-remove-file]'."
3798 :group 'org-agenda
3799 :type '(choice
3800 (repeat :tag "List of files and directories" file)
3801 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3803 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3804 "Regular expression to match files for `org-agenda-files'.
3805 If any element in the list in that variable contains a directory instead
3806 of a normal file, all files in that directory that are matched by this
3807 regular expression will be included."
3808 :group 'org-agenda
3809 :type 'regexp)
3811 (defcustom org-agenda-text-search-extra-files nil
3812 "List of extra files to be searched by text search commands.
3813 These files will be searched in addition to the agenda files by the
3814 commands `org-search-view' (`\\[org-agenda] s') \
3815 and `org-occur-in-agenda-files'.
3816 Note that these files will only be searched for text search commands,
3817 not for the other agenda views like todo lists, tag searches or the weekly
3818 agenda. This variable is intended to list notes and possibly archive files
3819 that should also be searched by these two commands.
3820 In fact, if the first element in the list is the symbol `agenda-archives',
3821 then all archive files of all agenda files will be added to the search
3822 scope."
3823 :group 'org-agenda
3824 :type '(set :greedy t
3825 (const :tag "Agenda Archives" agenda-archives)
3826 (repeat :inline t (file))))
3828 (defvaralias 'org-agenda-multi-occur-extra-files
3829 'org-agenda-text-search-extra-files)
3831 (defcustom org-agenda-skip-unavailable-files nil
3832 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3833 A nil value means to remove them, after a query, from the list."
3834 :group 'org-agenda
3835 :type 'boolean)
3837 (defcustom org-calendar-to-agenda-key [?c]
3838 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3839 The command `org-calendar-goto-agenda' will be bound to this key. The
3840 default is the character `c' because then `c' can be used to switch back and
3841 forth between agenda and calendar."
3842 :group 'org-agenda
3843 :type 'sexp)
3845 (defcustom org-calendar-insert-diary-entry-key [?i]
3846 "The key to be installed in `calendar-mode-map' for adding diary entries.
3847 This option is irrelevant until `org-agenda-diary-file' has been configured
3848 to point to an Org file. When that is the case, the command
3849 `org-agenda-diary-entry' will be bound to the key given here, by default
3850 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3851 if you want to continue doing this, you need to change this to a different
3852 key."
3853 :group 'org-agenda
3854 :type 'sexp)
3856 (defcustom org-agenda-diary-file 'diary-file
3857 "File to which to add new entries with the `i' key in agenda and calendar.
3858 When this is the symbol `diary-file', the functionality in the Emacs
3859 calendar will be used to add entries to the `diary-file'. But when this
3860 points to a file, `org-agenda-diary-entry' will be used instead."
3861 :group 'org-agenda
3862 :type '(choice
3863 (const :tag "The standard Emacs diary file" diary-file)
3864 (file :tag "Special Org file diary entries")))
3866 (eval-after-load "calendar"
3867 '(progn
3868 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3869 'org-calendar-goto-agenda)
3870 (add-hook 'calendar-mode-hook
3871 (lambda ()
3872 (unless (eq org-agenda-diary-file 'diary-file)
3873 (define-key calendar-mode-map
3874 org-calendar-insert-diary-entry-key
3875 'org-agenda-diary-entry))))))
3877 (defgroup org-latex nil
3878 "Options for embedding LaTeX code into Org mode."
3879 :tag "Org LaTeX"
3880 :group 'org)
3882 (defcustom org-format-latex-options
3883 '(:foreground default :background default :scale 1.0
3884 :html-foreground "Black" :html-background "Transparent"
3885 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3886 "Options for creating images from LaTeX fragments.
3887 This is a property list with the following properties:
3888 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3889 `default' means use the foreground of the default face.
3890 `auto' means use the foreground from the text face.
3891 :background the background color, or \"Transparent\".
3892 `default' means use the background of the default face.
3893 `auto' means use the background from the text face.
3894 :scale a scaling factor for the size of the images, to get more pixels
3895 :html-foreground, :html-background, :html-scale
3896 the same numbers for HTML export.
3897 :matchers a list indicating which matchers should be used to
3898 find LaTeX fragments. Valid members of this list are:
3899 \"begin\" find environments
3900 \"$1\" find single characters surrounded by $.$
3901 \"$\" find math expressions surrounded by $...$
3902 \"$$\" find math expressions surrounded by $$....$$
3903 \"\\(\" find math expressions surrounded by \\(...\\)
3904 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3905 :group 'org-latex
3906 :type 'plist)
3908 (defcustom org-format-latex-signal-error t
3909 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3910 When nil, just push out a message."
3911 :group 'org-latex
3912 :version "24.1"
3913 :type 'boolean)
3915 (defcustom org-latex-to-mathml-jar-file nil
3916 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3917 Use this to specify additional executable file say a jar file.
3919 When using MathToWeb as the converter, specify the full-path to
3920 your mathtoweb.jar file."
3921 :group 'org-latex
3922 :version "24.1"
3923 :type '(choice
3924 (const :tag "None" nil)
3925 (file :tag "JAR file" :must-match t)))
3927 (defcustom org-latex-to-mathml-convert-command nil
3928 "Command to convert LaTeX fragments to MathML.
3929 Replace format-specifiers in the command as noted below and use
3930 `shell-command' to convert LaTeX to MathML.
3931 %j: Executable file in fully expanded form as specified by
3932 `org-latex-to-mathml-jar-file'.
3933 %I: Input LaTeX file in fully expanded form.
3934 %i: The latex fragment to be converted.
3935 %o: Output MathML file.
3937 This command is used by `org-create-math-formula'.
3939 When using MathToWeb as the converter, set this option to
3940 \"java -jar %j -unicode -force -df %o %I\".
3942 When using LaTeXML set this option to
3943 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3944 :group 'org-latex
3945 :version "24.1"
3946 :type '(choice
3947 (const :tag "None" nil)
3948 (string :tag "\nShell command")))
3950 (defcustom org-preview-latex-default-process 'dvipng
3951 "The default process to convert LaTeX fragments to image files.
3952 All available processes and theirs documents can be found in
3953 `org-preview-latex-process-alist', which see."
3954 :group 'org-latex
3955 :version "26.1"
3956 :package-version '(Org . "9.0")
3957 :type 'symbol)
3959 (defcustom org-preview-latex-process-alist
3960 '((dvipng
3961 :programs ("latex" "dvipng")
3962 :description "dvi > png"
3963 :message "you need to install the programs: latex and dvipng."
3964 :image-input-type "dvi"
3965 :image-output-type "png"
3966 :image-size-adjust (1.0 . 1.0)
3967 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3968 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3969 (dvisvgm
3970 :programs ("latex" "dvisvgm")
3971 :description "dvi > svg"
3972 :message "you need to install the programs: latex and dvisvgm."
3973 :use-xcolor t
3974 :image-input-type "dvi"
3975 :image-output-type "svg"
3976 :image-size-adjust (1.7 . 1.5)
3977 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3978 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3979 (imagemagick
3980 :programs ("latex" "convert")
3981 :description "pdf > png"
3982 :message "you need to install the programs: latex and imagemagick."
3983 :use-xcolor t
3984 :image-input-type "pdf"
3985 :image-output-type "png"
3986 :image-size-adjust (1.0 . 1.0)
3987 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3988 :image-converter
3989 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3990 "Definitions of external processes for LaTeX previewing.
3991 Org mode can use some external commands to generate TeX snippet's images for
3992 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3993 `org-create-formula-image' how to call them.
3995 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3996 PROPERTIES accepts the following attributes:
3998 :programs list of strings, required programs.
3999 :description string, describe the process.
4000 :message string, message it when required programs cannot be found.
4001 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4002 :image-output-type string, output file type of image converter (e.g., \"png\").
4003 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4004 deal with background and foreground color of image.
4005 Otherwise, dvipng style background and foregroud color
4006 format are generated. You may then refer to them in
4007 command options with \"%F\" and \"%B\".
4008 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4009 image size showed in buffer and the cdr element is for
4010 HTML file. This option is only useful for process
4011 developers, users should use variable
4012 `org-format-latex-options' instead.
4013 :post-clean list of strings, files matched are to be cleaned up once
4014 the image is generated. When nil, the files with \".dvi\",
4015 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4016 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4017 be cleaned up.
4018 :latex-header list of strings, the LaTeX header of the snippet file.
4019 When nil, the fallback value is used instead, which is
4020 controlled by `org-format-latex-header',
4021 `org-latex-default-packages-alist' and
4022 `org-latex-packages-alist', which see.
4023 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4024 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4025 replaced with values defined below.
4026 :image-converter list of image converter commands strings. Each of them is
4027 given to the shell and supports any of the following
4028 place-holders defined below.
4030 Place-holders used by `:image-converter' and `:latex-compiler':
4032 %f input file name
4033 %b base name of input file
4034 %o base directory of input file
4035 %O absolute output file name
4037 Place-holders only used by `:image-converter':
4039 %F foreground of image
4040 %B background of image
4041 %D dpi, which is used to adjust image size by some processing commands.
4042 %S the image size scale ratio, which is used to adjust image size by some
4043 processing commands."
4044 :group 'org-latex
4045 :version "26.1"
4046 :package-version '(Org . "9.0")
4047 :type '(alist :tag "LaTeX to image backends"
4048 :value-type (plist)))
4050 (defcustom org-preview-latex-image-directory "ltximg/"
4051 "Path to store latex preview images.
4052 A relative path here creates many directories relative to the
4053 processed org files paths. An absolute path puts all preview
4054 images at the same place."
4055 :group 'org-latex
4056 :version "26.1"
4057 :package-version '(Org . "9.0")
4058 :type 'string)
4060 (defun org-format-latex-mathml-available-p ()
4061 "Return t if `org-latex-to-mathml-convert-command' is usable."
4062 (save-match-data
4063 (when (and (boundp 'org-latex-to-mathml-convert-command)
4064 org-latex-to-mathml-convert-command)
4065 (let ((executable (car (split-string
4066 org-latex-to-mathml-convert-command))))
4067 (when (executable-find executable)
4068 (if (string-match
4069 "%j" org-latex-to-mathml-convert-command)
4070 (file-readable-p org-latex-to-mathml-jar-file)
4071 t))))))
4073 (defcustom org-format-latex-header "\\documentclass{article}
4074 \\usepackage[usenames]{color}
4075 \[PACKAGES]
4076 \[DEFAULT-PACKAGES]
4077 \\pagestyle{empty} % do not remove
4078 % The settings below are copied from fullpage.sty
4079 \\setlength{\\textwidth}{\\paperwidth}
4080 \\addtolength{\\textwidth}{-3cm}
4081 \\setlength{\\oddsidemargin}{1.5cm}
4082 \\addtolength{\\oddsidemargin}{-2.54cm}
4083 \\setlength{\\evensidemargin}{\\oddsidemargin}
4084 \\setlength{\\textheight}{\\paperheight}
4085 \\addtolength{\\textheight}{-\\headheight}
4086 \\addtolength{\\textheight}{-\\headsep}
4087 \\addtolength{\\textheight}{-\\footskip}
4088 \\addtolength{\\textheight}{-3cm}
4089 \\setlength{\\topmargin}{1.5cm}
4090 \\addtolength{\\topmargin}{-2.54cm}"
4091 "The document header used for processing LaTeX fragments.
4092 It is imperative that this header make sure that no page number
4093 appears on the page. The package defined in the variables
4094 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4095 will either replace the placeholder \"[PACKAGES]\" in this
4096 header, or they will be appended."
4097 :group 'org-latex
4098 :type 'string)
4100 (defun org-set-packages-alist (var val)
4101 "Set the packages alist and make sure it has 3 elements per entry."
4102 (set var (mapcar (lambda (x)
4103 (if (and (consp x) (= (length x) 2))
4104 (list (car x) (nth 1 x) t)
4106 val)))
4108 (defun org-get-packages-alist (var)
4109 "Get the packages alist and make sure it has 3 elements per entry."
4110 (mapcar (lambda (x)
4111 (if (and (consp x) (= (length x) 2))
4112 (list (car x) (nth 1 x) t)
4114 (default-value var)))
4116 (defcustom org-latex-default-packages-alist
4117 '(("AUTO" "inputenc" t ("pdflatex"))
4118 ("T1" "fontenc" t ("pdflatex"))
4119 ("" "graphicx" t)
4120 ("" "grffile" t)
4121 ("" "longtable" nil)
4122 ("" "wrapfig" nil)
4123 ("" "rotating" nil)
4124 ("normalem" "ulem" t)
4125 ("" "amsmath" t)
4126 ("" "textcomp" t)
4127 ("" "amssymb" t)
4128 ("" "capt-of" nil)
4129 ("" "hyperref" nil))
4130 "Alist of default packages to be inserted in the header.
4132 Change this only if one of the packages here causes an
4133 incompatibility with another package you are using.
4135 The packages in this list are needed by one part or another of
4136 Org mode to function properly:
4138 - inputenc, fontenc: for basic font and character selection
4139 - graphicx: for including images
4140 - grffile: allow periods and spaces in graphics file names
4141 - longtable: For multipage tables
4142 - wrapfig: for figure placement
4143 - rotating: for sideways figures and tables
4144 - ulem: for underline and strike-through
4145 - amsmath: for subscript and superscript and math environments
4146 - textcomp, amssymb: for various symbols used
4147 for interpreting the entities in `org-entities'. You can skip
4148 some of these packages if you don't use any of their symbols.
4149 - capt-of: for captions outside of floats
4150 - hyperref: for cross references
4152 Therefore you should not modify this variable unless you know
4153 what you are doing. The one reason to change it anyway is that
4154 you might be loading some other package that conflicts with one
4155 of the default packages. Each element is either a cell or
4156 a string.
4158 A cell is of the format
4160 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4162 If SNIPPET-FLAG is non-nil, the package also needs to be included
4163 when compiling LaTeX snippets into images for inclusion into
4164 non-LaTeX output. COMPILERS is a list of compilers that should
4165 include the package, see `org-latex-compiler'. If the document
4166 compiler is not in the list, and the list is non-nil, the package
4167 will not be inserted in the final document.
4169 A string will be inserted as-is in the header of the document."
4170 :group 'org-latex
4171 :group 'org-export-latex
4172 :set 'org-set-packages-alist
4173 :get 'org-get-packages-alist
4174 :version "26.1"
4175 :package-version '(Org . "8.3")
4176 :type '(repeat
4177 (choice
4178 (list :tag "options/package pair"
4179 (string :tag "options")
4180 (string :tag "package")
4181 (boolean :tag "Snippet"))
4182 (string :tag "A line of LaTeX"))))
4184 (defcustom org-latex-packages-alist nil
4185 "Alist of packages to be inserted in every LaTeX header.
4187 These will be inserted after `org-latex-default-packages-alist'.
4188 Each element is either a cell or a string.
4190 A cell is of the format:
4192 (\"options\" \"package\" SNIPPET-FLAG)
4194 SNIPPET-FLAG, when non-nil, indicates that this package is also
4195 needed when turning LaTeX snippets into images for inclusion into
4196 non-LaTeX output.
4198 A string will be inserted as-is in the header of the document.
4200 Make sure that you only list packages here which:
4202 - you want in every file;
4203 - do not conflict with the setup in `org-format-latex-header';
4204 - do not conflict with the default packages in
4205 `org-latex-default-packages-alist'."
4206 :group 'org-latex
4207 :group 'org-export-latex
4208 :set 'org-set-packages-alist
4209 :get 'org-get-packages-alist
4210 :type '(repeat
4211 (choice
4212 (list :tag "options/package pair"
4213 (string :tag "options")
4214 (string :tag "package")
4215 (boolean :tag "Snippet"))
4216 (string :tag "A line of LaTeX"))))
4218 (defgroup org-appearance nil
4219 "Settings for Org mode appearance."
4220 :tag "Org Appearance"
4221 :group 'org)
4223 (defcustom org-level-color-stars-only nil
4224 "Non-nil means fontify only the stars in each headline.
4225 When nil, the entire headline is fontified.
4226 Changing it requires restart of `font-lock-mode' to become effective
4227 also in regions already fontified."
4228 :group 'org-appearance
4229 :type 'boolean)
4231 (defcustom org-hide-leading-stars nil
4232 "Non-nil means hide the first N-1 stars in a headline.
4233 This works by using the face `org-hide' for these stars. This
4234 face is white for a light background, and black for a dark
4235 background. You may have to customize the face `org-hide' to
4236 make this work.
4237 Changing it requires restart of `font-lock-mode' to become effective
4238 also in regions already fontified.
4239 You may also set this on a per-file basis by adding one of the following
4240 lines to the buffer:
4242 #+STARTUP: hidestars
4243 #+STARTUP: showstars"
4244 :group 'org-appearance
4245 :type 'boolean)
4247 (defcustom org-hidden-keywords nil
4248 "List of symbols corresponding to keywords to be hidden the org buffer.
4249 For example, a value \\='(title) for this list will make the document's title
4250 appear in the buffer without the initial #+TITLE: keyword."
4251 :group 'org-appearance
4252 :version "24.1"
4253 :type '(set (const :tag "#+AUTHOR" author)
4254 (const :tag "#+DATE" date)
4255 (const :tag "#+EMAIL" email)
4256 (const :tag "#+TITLE" title)))
4258 (defcustom org-custom-properties nil
4259 "List of properties (as strings) with a special meaning.
4260 The default use of these custom properties is to let the user
4261 hide them with `org-toggle-custom-properties-visibility'."
4262 :group 'org-properties
4263 :group 'org-appearance
4264 :version "24.3"
4265 :type '(repeat (string :tag "Property Name")))
4267 (defcustom org-fontify-done-headline nil
4268 "Non-nil means change the face of a headline if it is marked DONE.
4269 Normally, only the TODO/DONE keyword indicates the state of a headline.
4270 When this is non-nil, the headline after the keyword is set to the
4271 `org-headline-done' as an additional indication."
4272 :group 'org-appearance
4273 :type 'boolean)
4275 (defcustom org-fontify-emphasized-text t
4276 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4277 Changing this variable requires a restart of Emacs to take effect."
4278 :group 'org-appearance
4279 :type 'boolean)
4281 (defcustom org-fontify-whole-heading-line nil
4282 "Non-nil means fontify the whole line for headings.
4283 This is useful when setting a background color for the
4284 org-level-* faces."
4285 :group 'org-appearance
4286 :type 'boolean)
4288 (defcustom org-highlight-latex-and-related nil
4289 "Non-nil means highlight LaTeX related syntax in the buffer.
4290 When non nil, the value should be a list containing any of the
4291 following symbols:
4292 `latex' Highlight LaTeX snippets and environments.
4293 `script' Highlight subscript and superscript.
4294 `entities' Highlight entities."
4295 :group 'org-appearance
4296 :version "24.4"
4297 :package-version '(Org . "8.0")
4298 :type '(choice
4299 (const :tag "No highlighting" nil)
4300 (set :greedy t :tag "Highlight"
4301 (const :tag "LaTeX snippets and environments" latex)
4302 (const :tag "Subscript and superscript" script)
4303 (const :tag "Entities" entities))))
4305 (defcustom org-hide-emphasis-markers nil
4306 "Non-nil mean font-lock should hide the emphasis marker characters."
4307 :group 'org-appearance
4308 :type 'boolean)
4310 (defcustom org-hide-macro-markers nil
4311 "Non-nil mean font-lock should hide the brackets marking macro calls."
4312 :group 'org-appearance
4313 :type 'boolean)
4315 (defcustom org-pretty-entities nil
4316 "Non-nil means show entities as UTF8 characters.
4317 When nil, the \\name form remains in the buffer."
4318 :group 'org-appearance
4319 :version "24.1"
4320 :type 'boolean)
4322 (defcustom org-pretty-entities-include-sub-superscripts t
4323 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4324 :group 'org-appearance
4325 :version "24.1"
4326 :type 'boolean)
4328 (defvar org-emph-re nil
4329 "Regular expression for matching emphasis.
4330 After a match, the match groups contain these elements:
4331 0 The match of the full regular expression, including the characters
4332 before and after the proper match
4333 1 The character before the proper match, or empty at beginning of line
4334 2 The proper match, including the leading and trailing markers
4335 3 The leading marker like * or /, indicating the type of highlighting
4336 4 The text between the emphasis markers, not including the markers
4337 5 The character after the match, empty at the end of a line")
4339 (defvar org-verbatim-re nil
4340 "Regular expression for matching verbatim text.")
4342 (defvar org-emphasis-regexp-components) ; defined just below
4343 (defvar org-emphasis-alist) ; defined just below
4344 (defun org-set-emph-re (var val)
4345 "Set variable and compute the emphasis regular expression."
4346 (set var val)
4347 (when (and (boundp 'org-emphasis-alist)
4348 (boundp 'org-emphasis-regexp-components)
4349 org-emphasis-alist org-emphasis-regexp-components)
4350 (pcase-let*
4351 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4352 (body (if (<= nl 0) body
4353 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4354 (template
4355 (format (concat "\\([%s]\\|^\\)" ;before markers
4356 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4357 "\\([%s]\\|$\\)") ;after markers
4358 pre border border body border post)))
4359 (setq org-emph-re (format template "*/_+"))
4360 (setq org-verbatim-re (format template "=~")))))
4362 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4363 ;; set this option proved cumbersome. See this message/thread:
4364 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4365 (defvar org-emphasis-regexp-components
4366 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4367 "Components used to build the regular expression for emphasis.
4368 This is a list with five entries. Terminology: In an emphasis string
4369 like \" *strong word* \", we call the initial space PREMATCH, the final
4370 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4371 and \"trong wor\" is the body. The different components in this variable
4372 specify what is allowed/forbidden in each part:
4374 pre Chars allowed as prematch. Beginning of line will be allowed too.
4375 post Chars allowed as postmatch. End of line will be allowed too.
4376 border The chars *forbidden* as border characters.
4377 body-regexp A regexp like \".\" to match a body character. Don't use
4378 non-shy groups here, and don't allow newline here.
4379 newline The maximum number of newlines allowed in an emphasis exp.
4381 You need to reload Org or to restart Emacs after customizing this.")
4383 (defcustom org-emphasis-alist
4384 '(("*" bold)
4385 ("/" italic)
4386 ("_" underline)
4387 ("=" org-verbatim verbatim)
4388 ("~" org-code verbatim)
4389 ("+" (:strike-through t)))
4390 "Alist of characters and faces to emphasize text.
4391 Text starting and ending with a special character will be emphasized,
4392 for example *bold*, _underlined_ and /italic/. This variable sets the
4393 marker characters and the face to be used by font-lock for highlighting
4394 in Org buffers.
4396 You need to reload Org or to restart Emacs after customizing this."
4397 :group 'org-appearance
4398 :set 'org-set-emph-re
4399 :version "24.4"
4400 :package-version '(Org . "8.0")
4401 :type '(repeat
4402 (list
4403 (string :tag "Marker character")
4404 (choice
4405 (face :tag "Font-lock-face")
4406 (plist :tag "Face property list"))
4407 (option (const verbatim)))))
4409 (defvar org-protecting-blocks '("src" "example" "export")
4410 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4411 This is needed for font-lock setup.")
4413 ;;; Functions and variables from their packages
4414 ;; Declared here to avoid compiler warnings
4415 (defvar mark-active)
4417 ;; Various packages
4418 (declare-function calc-eval "calc" (str &optional separator &rest args))
4419 (declare-function calendar-forward-day "cal-move" (arg))
4420 (declare-function calendar-goto-date "cal-move" (date))
4421 (declare-function calendar-goto-today "cal-move" ())
4422 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4423 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4424 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4425 (declare-function cdlatex-tab "ext:cdlatex" ())
4426 (declare-function dired-get-filename
4427 "dired"
4428 (&optional localp no-error-if-not-filep))
4429 (declare-function iswitchb-read-buffer
4430 "iswitchb"
4431 (prompt &optional
4432 default require-match _predicate start matches-set))
4433 (declare-function org-agenda-change-all-lines
4434 "org-agenda"
4435 (newhead hdmarker &optional fixface just-this))
4436 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4437 "org-agenda"
4438 (&optional end))
4439 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4440 (declare-function org-agenda-format-item
4441 "org-agenda"
4442 (extra txt &optional level category tags dotime
4443 remove-re habitp))
4444 (declare-function org-agenda-maybe-redo "org-agenda" ())
4445 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4446 (declare-function org-agenda-save-markers-for-cut-and-paste
4447 "org-agenda"
4448 (beg end))
4449 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4450 (declare-function org-agenda-skip "org-agenda" ())
4451 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4452 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4453 (declare-function org-indent-mode "org-indent" (&optional arg))
4454 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4455 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4456 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4457 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4458 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4459 (declare-function parse-time-string "parse-time" (string))
4460 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4462 (defvar align-mode-rules-list)
4463 (defvar calc-embedded-close-formula)
4464 (defvar calc-embedded-open-formula)
4465 (defvar calc-embedded-open-mode)
4466 (defvar font-lock-unfontify-region-function)
4467 (defvar iswitchb-temp-buflist)
4468 (defvar org-agenda-tags-todo-honor-ignore-options)
4469 (defvar remember-data-file)
4470 (defvar texmathp-why)
4472 ;;;###autoload
4473 (defun turn-on-orgtbl ()
4474 "Unconditionally turn on `orgtbl-mode'."
4475 (require 'org-table)
4476 (orgtbl-mode 1))
4478 (defun org-at-table-p (&optional table-type)
4479 "Non-nil if the cursor is inside an Org table.
4480 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4481 If `org-enable-table-editor' is nil, return nil unconditionally."
4482 (and
4483 org-enable-table-editor
4484 (save-excursion
4485 (beginning-of-line)
4486 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4487 (or (not (derived-mode-p 'org-mode))
4488 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4489 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4491 (defun org-at-table.el-p ()
4492 "Non-nil when point is at a table.el table."
4493 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4494 (let ((element (org-element-at-point)))
4495 (and (eq (org-element-type element) 'table)
4496 (eq (org-element-property :type element) 'table.el)))))
4498 (defun org-at-table-hline-p ()
4499 "Non-nil when point is inside a hline in a table.
4500 Assume point is already in a table. If `org-enable-table-editor'
4501 is nil, return nil unconditionally."
4502 (and org-enable-table-editor
4503 (save-excursion
4504 (beginning-of-line)
4505 (looking-at org-table-hline-regexp))))
4507 (defun org-table-map-tables (function &optional quietly)
4508 "Apply FUNCTION to the start of all tables in the buffer."
4509 (org-with-wide-buffer
4510 (goto-char (point-min))
4511 (while (re-search-forward org-table-any-line-regexp nil t)
4512 (unless quietly
4513 (message "Mapping tables: %d%%"
4514 (floor (* 100.0 (point)) (buffer-size))))
4515 (beginning-of-line 1)
4516 (when (and (looking-at org-table-line-regexp)
4517 ;; Exclude tables in src/example/verbatim/clocktable blocks
4518 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4519 (save-excursion (funcall function))
4520 (or (looking-at org-table-line-regexp)
4521 (forward-char 1)))
4522 (re-search-forward org-table-any-border-regexp nil 1)))
4523 (unless quietly (message "Mapping tables: done")))
4525 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4526 (declare-function org-clock-update-mode-line "org-clock" ())
4527 (declare-function org-resolve-clocks "org-clock"
4528 (&optional also-non-dangling-p prompt last-valid))
4530 (defun org-at-TBLFM-p (&optional pos)
4531 "Non-nil when point (or POS) is in #+TBLFM line."
4532 (save-excursion
4533 (goto-char (or pos (point)))
4534 (beginning-of-line)
4535 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4536 (eq (org-element-type (org-element-at-point)) 'table))))
4538 (defvar org-clock-start-time)
4539 (defvar org-clock-marker (make-marker)
4540 "Marker recording the last clock-in.")
4541 (defvar org-clock-hd-marker (make-marker)
4542 "Marker recording the last clock-in, but the headline position.")
4543 (defvar org-clock-heading ""
4544 "The heading of the current clock entry.")
4545 (defun org-clock-is-active ()
4546 "Return the buffer where the clock is currently running.
4547 Return nil if no clock is running."
4548 (marker-buffer org-clock-marker))
4550 (defun org-check-running-clock ()
4551 "Check if the current buffer contains the running clock.
4552 If yes, offer to stop it and to save the buffer with the changes."
4553 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4554 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4555 (buffer-name))))
4556 (org-clock-out)
4557 (when (y-or-n-p "Save changed buffer?")
4558 (save-buffer))))
4560 (defun org-clocktable-try-shift (dir n)
4561 "Check if this line starts a clock table, if yes, shift the time block."
4562 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4563 (org-clocktable-shift dir n)))
4565 ;;;###autoload
4566 (defun org-clock-persistence-insinuate ()
4567 "Set up hooks for clock persistence."
4568 (require 'org-clock)
4569 (add-hook 'org-mode-hook 'org-clock-load)
4570 (add-hook 'kill-emacs-hook 'org-clock-save))
4572 (defgroup org-archive nil
4573 "Options concerning archiving in Org mode."
4574 :tag "Org Archive"
4575 :group 'org-structure)
4577 (defcustom org-archive-location "%s_archive::"
4578 "The location where subtrees should be archived.
4580 The value of this variable is a string, consisting of two parts,
4581 separated by a double-colon. The first part is a filename and
4582 the second part is a headline.
4584 When the filename is omitted, archiving happens in the same file.
4585 %s in the filename will be replaced by the current file
4586 name (without the directory part). Archiving to a different file
4587 is useful to keep archived entries from contributing to the
4588 Org Agenda.
4590 The archived entries will be filed as subtrees of the specified
4591 headline. When the headline is omitted, the subtrees are simply
4592 filed away at the end of the file, as top-level entries. Also in
4593 the heading you can use %s to represent the file name, this can be
4594 useful when using the same archive for a number of different files.
4596 Here are a few examples:
4597 \"%s_archive::\"
4598 If the current file is Projects.org, archive in file
4599 Projects.org_archive, as top-level trees. This is the default.
4601 \"::* Archived Tasks\"
4602 Archive in the current file, under the top-level headline
4603 \"* Archived Tasks\".
4605 \"~/org/archive.org::\"
4606 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4608 \"~/org/archive.org::* From %s\"
4609 Archive in file ~/org/archive.org (absolute path), under headlines
4610 \"From FILENAME\" where file name is the current file name.
4612 \"~/org/datetree.org::datetree/* Finished Tasks\"
4613 The \"datetree/\" string is special, signifying to archive
4614 items to the datetree. Items are placed in either the CLOSED
4615 date of the item, or the current date if there is no CLOSED date.
4616 The heading will be a subentry to the current date. There doesn't
4617 need to be a heading, but there always needs to be a slash after
4618 datetree. For example, to store archived items directly in the
4619 datetree, use \"~/org/datetree.org::datetree/\".
4621 \"basement::** Finished Tasks\"
4622 Archive in file ./basement (relative path), as level 3 trees
4623 below the level 2 heading \"** Finished Tasks\".
4625 You may set this option on a per-file basis by adding to the buffer a
4626 line like
4628 #+ARCHIVE: basement::** Finished Tasks
4630 You may also define it locally for a subtree by setting an ARCHIVE property
4631 in the entry. If such a property is found in an entry, or anywhere up
4632 the hierarchy, it will be used."
4633 :group 'org-archive
4634 :type 'string)
4636 (defcustom org-agenda-skip-archived-trees t
4637 "Non-nil means the agenda will skip any items located in archived trees.
4638 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4639 variable is no longer recommended, you should leave it at the value t.
4640 Instead, use the key `v' to cycle the archives-mode in the agenda."
4641 :group 'org-archive
4642 :group 'org-agenda-skip
4643 :type 'boolean)
4645 (defcustom org-columns-skip-archived-trees t
4646 "Non-nil means ignore archived trees when creating column view."
4647 :group 'org-archive
4648 :group 'org-properties
4649 :type 'boolean)
4651 (defcustom org-cycle-open-archived-trees nil
4652 "Non-nil means `org-cycle' will open archived trees.
4653 An archived tree is a tree marked with the tag ARCHIVE.
4654 When nil, archived trees will stay folded. You can still open them with
4655 normal outline commands like `show-all', but not with the cycling commands."
4656 :group 'org-archive
4657 :group 'org-cycle
4658 :type 'boolean)
4660 (defcustom org-sparse-tree-open-archived-trees nil
4661 "Non-nil means sparse tree construction shows matches in archived trees.
4662 When nil, matches in these trees are highlighted, but the trees are kept in
4663 collapsed state."
4664 :group 'org-archive
4665 :group 'org-sparse-trees
4666 :type 'boolean)
4668 (defcustom org-sparse-tree-default-date-type nil
4669 "The default date type when building a sparse tree.
4670 When this is nil, a date is a scheduled or a deadline timestamp.
4671 Otherwise, these types are allowed:
4673 all: all timestamps
4674 active: only active timestamps (<...>)
4675 inactive: only inactive timestamps ([...])
4676 scheduled: only scheduled timestamps
4677 deadline: only deadline timestamps"
4678 :type '(choice (const :tag "Scheduled or deadline" nil)
4679 (const :tag "All timestamps" all)
4680 (const :tag "Only active timestamps" active)
4681 (const :tag "Only inactive timestamps" inactive)
4682 (const :tag "Only scheduled timestamps" scheduled)
4683 (const :tag "Only deadline timestamps" deadline)
4684 (const :tag "Only closed timestamps" closed))
4685 :version "26.1"
4686 :package-version '(Org . "8.3")
4687 :group 'org-sparse-trees)
4689 (defun org-cycle-hide-archived-subtrees (state)
4690 "Re-hide all archived subtrees after a visibility state change."
4691 (when (and (not org-cycle-open-archived-trees)
4692 (not (memq state '(overview folded))))
4693 (save-excursion
4694 (let* ((globalp (memq state '(contents all)))
4695 (beg (if globalp (point-min) (point)))
4696 (end (if globalp (point-max) (org-end-of-subtree t))))
4697 (org-hide-archived-subtrees beg end)
4698 (goto-char beg)
4699 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4700 (message "%s" (substitute-command-keys
4701 "Subtree is archived and stays closed. Use \
4702 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4704 (defun org-force-cycle-archived ()
4705 "Cycle subtree even if it is archived."
4706 (interactive)
4707 (setq this-command 'org-cycle)
4708 (let ((org-cycle-open-archived-trees t))
4709 (call-interactively 'org-cycle)))
4711 (defun org-hide-archived-subtrees (beg end)
4712 "Re-hide all archived subtrees after a visibility state change."
4713 (org-with-wide-buffer
4714 (let ((case-fold-search nil)
4715 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4716 (goto-char beg)
4717 ;; Include headline point is currently on.
4718 (beginning-of-line)
4719 (while (and (< (point) end) (re-search-forward re end t))
4720 (when (member org-archive-tag (org-get-tags))
4721 (org-flag-subtree t)
4722 (org-end-of-subtree t))))))
4724 (declare-function outline-end-of-heading "outline" ())
4725 (declare-function outline-flag-region "outline" (from to flag))
4726 (defun org-flag-subtree (flag)
4727 (save-excursion
4728 (org-back-to-heading t)
4729 (outline-end-of-heading)
4730 (outline-flag-region (point)
4731 (progn (org-end-of-subtree t) (point))
4732 flag)))
4734 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4736 ;; Declare Column View Code
4738 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4739 (declare-function org-columns-compute "org-colview" (property))
4741 ;; Declare ID code
4743 (declare-function org-id-store-link "org-id")
4744 (declare-function org-id-locations-load "org-id")
4745 (declare-function org-id-locations-save "org-id")
4746 (defvar org-id-track-globally)
4748 ;;; Variables for pre-computed regular expressions, all buffer local
4750 (defvar-local org-todo-regexp nil
4751 "Matches any of the TODO state keywords.
4752 Since TODO keywords are case-sensitive, `case-fold-search' is
4753 expected to be bound to nil when matching against this regexp.")
4755 (defvar-local org-not-done-regexp nil
4756 "Matches any of the TODO state keywords except the last one.
4757 Since TODO keywords are case-sensitive, `case-fold-search' is
4758 expected to be bound to nil when matching against this regexp.")
4760 (defvar-local org-not-done-heading-regexp nil
4761 "Matches a TODO headline that is not done.
4762 Since TODO keywords are case-sensitive, `case-fold-search' is
4763 expected to be bound to nil when matching against this regexp.")
4765 (defvar-local org-todo-line-regexp nil
4766 "Matches a headline and puts TODO state into group 2 if present.
4767 Since TODO keywords are case-sensitive, `case-fold-search' is
4768 expected to be bound to nil when matching against this regexp.")
4770 (defvar-local org-complex-heading-regexp nil
4771 "Matches a headline and puts everything into groups:
4773 group 1: Stars
4774 group 2: The TODO keyword, maybe
4775 group 3: Priority cookie
4776 group 4: True headline
4777 group 5: Tags
4779 Since TODO keywords are case-sensitive, `case-fold-search' is
4780 expected to be bound to nil when matching against this regexp.")
4782 (defvar-local org-complex-heading-regexp-format nil
4783 "Printf format to make regexp to match an exact headline.
4784 This regexp will match the headline of any node which has the
4785 exact headline text that is put into the format, but may have any
4786 TODO state, priority and tags.")
4788 (defvar-local org-todo-line-tags-regexp nil
4789 "Matches a headline and puts TODO state into group 2 if present.
4790 Also put tags into group 4 if tags are present.")
4792 (defconst org-plain-time-of-day-regexp
4793 (concat
4794 "\\(\\<[012]?[0-9]"
4795 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4796 "\\(--?"
4797 "\\(\\<[012]?[0-9]"
4798 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4799 "\\)?")
4800 "Regular expression to match a plain time or time range.
4801 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4802 groups carry important information:
4803 0 the full match
4804 1 the first time, range or not
4805 8 the second time, if it is a range.")
4807 (defconst org-plain-time-extension-regexp
4808 (concat
4809 "\\(\\<[012]?[0-9]"
4810 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4811 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4812 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4813 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4814 groups carry important information:
4815 0 the full match
4816 7 hours of duration
4817 9 minutes of duration")
4819 (defconst org-stamp-time-of-day-regexp
4820 (concat
4821 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4822 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4823 "\\(--?"
4824 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4825 "Regular expression to match a timestamp time or time range.
4826 After a match, the following groups carry important information:
4827 0 the full match
4828 1 date plus weekday, for back referencing to make sure both times are on the same day
4829 2 the first time, range or not
4830 4 the second time, if it is a range.")
4832 (defconst org-startup-options
4833 '(("fold" org-startup-folded t)
4834 ("overview" org-startup-folded t)
4835 ("nofold" org-startup-folded nil)
4836 ("showall" org-startup-folded nil)
4837 ("showeverything" org-startup-folded showeverything)
4838 ("content" org-startup-folded content)
4839 ("indent" org-startup-indented t)
4840 ("noindent" org-startup-indented nil)
4841 ("hidestars" org-hide-leading-stars t)
4842 ("showstars" org-hide-leading-stars nil)
4843 ("odd" org-odd-levels-only t)
4844 ("oddeven" org-odd-levels-only nil)
4845 ("align" org-startup-align-all-tables t)
4846 ("noalign" org-startup-align-all-tables nil)
4847 ("inlineimages" org-startup-with-inline-images t)
4848 ("noinlineimages" org-startup-with-inline-images nil)
4849 ("latexpreview" org-startup-with-latex-preview t)
4850 ("nolatexpreview" org-startup-with-latex-preview nil)
4851 ("customtime" org-display-custom-times t)
4852 ("logdone" org-log-done time)
4853 ("lognotedone" org-log-done note)
4854 ("nologdone" org-log-done nil)
4855 ("lognoteclock-out" org-log-note-clock-out t)
4856 ("nolognoteclock-out" org-log-note-clock-out nil)
4857 ("logrepeat" org-log-repeat state)
4858 ("lognoterepeat" org-log-repeat note)
4859 ("logdrawer" org-log-into-drawer t)
4860 ("nologdrawer" org-log-into-drawer nil)
4861 ("logstatesreversed" org-log-states-order-reversed t)
4862 ("nologstatesreversed" org-log-states-order-reversed nil)
4863 ("nologrepeat" org-log-repeat nil)
4864 ("logreschedule" org-log-reschedule time)
4865 ("lognotereschedule" org-log-reschedule note)
4866 ("nologreschedule" org-log-reschedule nil)
4867 ("logredeadline" org-log-redeadline time)
4868 ("lognoteredeadline" org-log-redeadline note)
4869 ("nologredeadline" org-log-redeadline nil)
4870 ("logrefile" org-log-refile time)
4871 ("lognoterefile" org-log-refile note)
4872 ("nologrefile" org-log-refile nil)
4873 ("fninline" org-footnote-define-inline t)
4874 ("nofninline" org-footnote-define-inline nil)
4875 ("fnlocal" org-footnote-section nil)
4876 ("fnauto" org-footnote-auto-label t)
4877 ("fnprompt" org-footnote-auto-label nil)
4878 ("fnconfirm" org-footnote-auto-label confirm)
4879 ("fnplain" org-footnote-auto-label plain)
4880 ("fnadjust" org-footnote-auto-adjust t)
4881 ("nofnadjust" org-footnote-auto-adjust nil)
4882 ("constcgs" constants-unit-system cgs)
4883 ("constSI" constants-unit-system SI)
4884 ("noptag" org-tag-persistent-alist nil)
4885 ("hideblocks" org-hide-block-startup t)
4886 ("nohideblocks" org-hide-block-startup nil)
4887 ("beamer" org-startup-with-beamer-mode t)
4888 ("entitiespretty" org-pretty-entities t)
4889 ("entitiesplain" org-pretty-entities nil))
4890 "Variable associated with STARTUP options for org-mode.
4891 Each element is a list of three items: the startup options (as written
4892 in the #+STARTUP line), the corresponding variable, and the value to set
4893 this variable to if the option is found. An optional forth element PUSH
4894 means to push this value onto the list in the variable.")
4896 (defcustom org-group-tags t
4897 "When non-nil (the default), use group tags.
4898 This can be turned on/off through `org-toggle-tags-groups'."
4899 :group 'org-tags
4900 :group 'org-startup
4901 :type 'boolean)
4903 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4905 (defun org-toggle-tags-groups ()
4906 "Toggle support for group tags.
4907 Support for group tags is controlled by the option
4908 `org-group-tags', which is non-nil by default."
4909 (interactive)
4910 (setq org-group-tags (not org-group-tags))
4911 (cond ((and (derived-mode-p 'org-agenda-mode)
4912 org-group-tags)
4913 (org-agenda-redo))
4914 ((derived-mode-p 'org-mode)
4915 (let ((org-inhibit-startup t)) (org-mode))))
4916 (message "Groups tags support has been turned %s"
4917 (if org-group-tags "on" "off")))
4919 (defun org-set-regexps-and-options (&optional tags-only)
4920 "Precompute regular expressions used in the current buffer.
4921 When optional argument TAGS-ONLY is non-nil, only compute tags
4922 related expressions."
4923 (when (derived-mode-p 'org-mode)
4924 (let ((alist (org--setup-collect-keywords
4925 (org-make-options-regexp
4926 (append '("FILETAGS" "TAGS" "SETUPFILE")
4927 (and (not tags-only)
4928 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4929 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4930 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4931 ;; Startup options. Get this early since it does change
4932 ;; behavior for other options (e.g., tags).
4933 (let ((startup (cdr (assq 'startup alist))))
4934 (dolist (option startup)
4935 (let ((entry (assoc-string option org-startup-options t)))
4936 (when entry
4937 (let ((var (nth 1 entry))
4938 (val (nth 2 entry)))
4939 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4940 (unless (listp (symbol-value var))
4941 (set (make-local-variable var) nil))
4942 (add-to-list var val)))))))
4943 (setq-local org-file-tags
4944 (mapcar #'org-add-prop-inherited
4945 (cdr (assq 'filetags alist))))
4946 (setq org-current-tag-alist
4947 (append org-tag-persistent-alist
4948 (let ((tags (cdr (assq 'tags alist))))
4949 (if tags (org-tag-string-to-alist tags)
4950 org-tag-alist))))
4951 (setq org-tag-groups-alist
4952 (org-tag-alist-to-groups org-current-tag-alist))
4953 (unless tags-only
4954 ;; File properties.
4955 (setq-local org-file-properties (cdr (assq 'property alist)))
4956 ;; Archive location.
4957 (let ((archive (cdr (assq 'archive alist))))
4958 (when archive (setq-local org-archive-location archive)))
4959 ;; Category.
4960 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4961 (when cat
4962 (setq-local org-category (intern cat))
4963 (setq-local org-file-properties
4964 (org--update-property-plist
4965 "CATEGORY" cat org-file-properties))))
4966 ;; Columns.
4967 (let ((column (cdr (assq 'columns alist))))
4968 (when column (setq-local org-columns-default-format column)))
4969 ;; Constants.
4970 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4971 ;; Link abbreviations.
4972 (let ((links (cdr (assq 'link alist))))
4973 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4974 ;; Priorities.
4975 (let ((priorities (cdr (assq 'priorities alist))))
4976 (when priorities
4977 (setq-local org-highest-priority (nth 0 priorities))
4978 (setq-local org-lowest-priority (nth 1 priorities))
4979 (setq-local org-default-priority (nth 2 priorities))))
4980 ;; Scripts.
4981 (let ((scripts (assq 'scripts alist)))
4982 (when scripts
4983 (setq-local org-use-sub-superscripts (cdr scripts))))
4984 ;; TODO keywords.
4985 (setq-local org-todo-kwd-alist nil)
4986 (setq-local org-todo-key-alist nil)
4987 (setq-local org-todo-key-trigger nil)
4988 (setq-local org-todo-keywords-1 nil)
4989 (setq-local org-done-keywords nil)
4990 (setq-local org-todo-heads nil)
4991 (setq-local org-todo-sets nil)
4992 (setq-local org-todo-log-states nil)
4993 (let ((todo-sequences
4994 (or (nreverse (cdr (assq 'todo alist)))
4995 (let ((d (default-value 'org-todo-keywords)))
4996 (if (not (stringp (car d))) d
4997 ;; XXX: Backward compatibility code.
4998 (list (cons org-todo-interpretation d)))))))
4999 (dolist (sequence todo-sequences)
5000 (let* ((sequence (or (run-hook-with-args-until-success
5001 'org-todo-setup-filter-hook sequence)
5002 sequence))
5003 (sequence-type (car sequence))
5004 (keywords (cdr sequence))
5005 (sep (member "|" keywords))
5006 names alist)
5007 (dolist (k (remove "|" keywords))
5008 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5010 (error "Invalid TODO keyword %s" k))
5011 (let ((name (match-string 1 k))
5012 (key (match-string 2 k))
5013 (log (org-extract-log-state-settings k)))
5014 (push name names)
5015 (push (cons name (and key (string-to-char key))) alist)
5016 (when log (push log org-todo-log-states))))
5017 (let* ((names (nreverse names))
5018 (done (if sep (org-remove-keyword-keys (cdr sep))
5019 (last names)))
5020 (head (car names))
5021 (tail (list sequence-type head (car done) (org-last done))))
5022 (add-to-list 'org-todo-heads head 'append)
5023 (push names org-todo-sets)
5024 (setq org-done-keywords (append org-done-keywords done nil))
5025 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5026 (setq org-todo-key-alist
5027 (append org-todo-key-alist
5028 (and alist
5029 (append '((:startgroup))
5030 (nreverse alist)
5031 '((:endgroup))))))
5032 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5033 (setq org-todo-sets (nreverse org-todo-sets)
5034 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5035 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5036 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5037 ;; Compute the regular expressions and other local variables.
5038 ;; Using `org-outline-regexp-bol' would complicate them much,
5039 ;; because of the fixed white space at the end of that string.
5040 (unless org-done-keywords
5041 (setq org-done-keywords
5042 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5043 (setq org-not-done-keywords
5044 (org-delete-all org-done-keywords
5045 (copy-sequence org-todo-keywords-1))
5046 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5047 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5048 org-not-done-heading-regexp
5049 (format org-heading-keyword-regexp-format org-not-done-regexp)
5050 org-todo-line-regexp
5051 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5052 org-complex-heading-regexp
5053 (concat "^\\(\\*+\\)"
5054 "\\(?: +" org-todo-regexp "\\)?"
5055 "\\(?: +\\(\\[#.\\]\\)\\)?"
5056 "\\(?: +\\(.*?\\)\\)??"
5057 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5058 "[ \t]*$")
5059 org-complex-heading-regexp-format
5060 (concat "^\\(\\*+\\)"
5061 "\\(?: +" org-todo-regexp "\\)?"
5062 "\\(?: +\\(\\[#.\\]\\)\\)?"
5063 "\\(?: +"
5064 ;; Stats cookies can be stuck to body.
5065 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5066 "\\(%s\\)"
5067 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5068 "\\)"
5069 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5070 "[ \t]*$")
5071 org-todo-line-tags-regexp
5072 (concat "^\\(\\*+\\)"
5073 "\\(?: +" org-todo-regexp "\\)?"
5074 "\\(?: +\\(.*?\\)\\)??"
5075 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5076 "[ \t]*$"))
5077 (org-compute-latex-and-related-regexp)))))
5079 (defun org--setup-collect-keywords (regexp &optional files alist)
5080 "Return setup keywords values as an alist.
5082 REGEXP matches a subset of setup keywords. FILES is a list of
5083 file names already visited. It is used to avoid circular setup
5084 files. ALIST, when non-nil, is the alist computed so far.
5086 Return value contains the following keys: `archive', `category',
5087 `columns', `constants', `filetags', `link', `priorities',
5088 `property', `scripts', `startup', `tags' and `todo'."
5089 (org-with-wide-buffer
5090 (goto-char (point-min))
5091 (let ((case-fold-search t))
5092 (while (re-search-forward regexp nil t)
5093 (let ((element (org-element-at-point)))
5094 (when (eq (org-element-type element) 'keyword)
5095 (let ((key (org-element-property :key element))
5096 (value (org-element-property :value element)))
5097 (cond
5098 ((equal key "ARCHIVE")
5099 (when (org-string-nw-p value)
5100 (push (cons 'archive value) alist)))
5101 ((equal key "CATEGORY") (push (cons 'category value) alist))
5102 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5103 ((equal key "CONSTANTS")
5104 (let* ((constants (assq 'constants alist))
5105 (store (cdr constants)))
5106 (dolist (pair (org-split-string value))
5107 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5108 pair)
5109 (let* ((name (match-string 1 pair))
5110 (value (match-string 2 pair))
5111 (old (assoc name store)))
5112 (if old (setcdr old value)
5113 (push (cons name value) store)))))
5114 (if constants (setcdr constants store)
5115 (push (cons 'constants store) alist))))
5116 ((equal key "FILETAGS")
5117 (when (org-string-nw-p value)
5118 (let ((old (assq 'filetags alist))
5119 (new (apply #'nconc
5120 (mapcar (lambda (x) (org-split-string x ":"))
5121 (org-split-string value)))))
5122 (if old (setcdr old (append new (cdr old)))
5123 (push (cons 'filetags new) alist)))))
5124 ((equal key "LINK")
5125 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5126 (let ((links (assq 'link alist))
5127 (pair (cons (match-string-no-properties 1 value)
5128 (match-string-no-properties 2 value))))
5129 (if links (push pair (cdr links))
5130 (push (list 'link pair) alist)))))
5131 ((equal key "OPTIONS")
5132 (when (and (org-string-nw-p value)
5133 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5134 (push (cons 'scripts (read (match-string 1 value))) alist)))
5135 ((equal key "PRIORITIES")
5136 (push (cons 'priorities
5137 (let ((prio (org-split-string value)))
5138 (if (< (length prio) 3) '(?A ?C ?B)
5139 (mapcar #'string-to-char prio))))
5140 alist))
5141 ((equal key "PROPERTY")
5142 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5143 (let* ((property (assq 'property alist))
5144 (value (org--update-property-plist
5145 (match-string-no-properties 1 value)
5146 (match-string-no-properties 2 value)
5147 (cdr property))))
5148 (if property (setcdr property value)
5149 (push (cons 'property value) alist)))))
5150 ((equal key "STARTUP")
5151 (let ((startup (assq 'startup alist)))
5152 (if startup
5153 (setcdr startup
5154 (append (cdr startup) (org-split-string value)))
5155 (push (cons 'startup (org-split-string value)) alist))))
5156 ((equal key "TAGS")
5157 (let ((tag-cell (assq 'tags alist)))
5158 (if tag-cell
5159 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5160 (push (cons 'tags value) alist))))
5161 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5162 (let ((todo (assq 'todo alist))
5163 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5164 (org-split-string value))))
5165 (if todo (push value (cdr todo))
5166 (push (list 'todo value) alist))))
5167 ((equal key "SETUPFILE")
5168 (unless buffer-read-only ; Do not check in Gnus messages.
5169 (let ((f (and (org-string-nw-p value)
5170 (expand-file-name
5171 (org-unbracket-string "\"" "\"" value)))))
5172 (when (and f (file-readable-p f) (not (member f files)))
5173 (with-temp-buffer
5174 (setq default-directory (file-name-directory f))
5175 (insert-file-contents f)
5176 (setq alist
5177 ;; Fake Org mode to benefit from cache
5178 ;; without recurring needlessly.
5179 (let ((major-mode 'org-mode))
5180 (org--setup-collect-keywords
5181 regexp (cons f files) alist)))))))))))))))
5182 alist)
5184 (defun org-tag-string-to-alist (s)
5185 "Return tag alist associated to string S.
5186 S is a value for TAGS keyword or produced with
5187 `org-tag-alist-to-string'. Return value is an alist suitable for
5188 `org-tag-alist' or `org-tag-persistent-alist'."
5189 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5190 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5191 "\\|{.+?}\\)" ; regular expression
5192 "\\(?:(\\(.\\))\\)?\\'"))
5193 alist group-flag)
5194 (dolist (tokens lines (cdr (nreverse alist)))
5195 (push '(:newline) alist)
5196 (while tokens
5197 (let ((token (pop tokens)))
5198 (pcase token
5199 ("{"
5200 (push '(:startgroup) alist)
5201 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5202 ("}"
5203 (push '(:endgroup) alist)
5204 (setq group-flag nil))
5205 ("["
5206 (push '(:startgrouptag) alist)
5207 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5208 ("]"
5209 (push '(:endgrouptag) alist)
5210 (setq group-flag nil))
5211 (":"
5212 (push '(:grouptags) alist))
5213 ((guard (string-match tag-re token))
5214 (let ((tag (match-string 1 token))
5215 (key (and (match-beginning 2)
5216 (string-to-char (match-string 2 token)))))
5217 ;; Push all tags in groups, no matter if they already
5218 ;; appear somewhere else in the list.
5219 (when (or group-flag (not (assoc tag alist)))
5220 (push (cons tag key) alist))))))))))
5222 (defun org-tag-alist-to-string (alist &optional skip-key)
5223 "Return tag string associated to ALIST.
5225 ALIST is an alist, as defined in `org-tag-alist' or
5226 `org-tag-persistent-alist', or produced with
5227 `org-tag-string-to-alist'.
5229 Return value is a string suitable as a value for \"TAGS\"
5230 keyword.
5232 When optional argument SKIP-KEY is non-nil, skip selection keys
5233 next to tags."
5234 (mapconcat (lambda (token)
5235 (pcase token
5236 (`(:startgroup) "{")
5237 (`(:endgroup) "}")
5238 (`(:startgrouptag) "[")
5239 (`(:endgrouptag) "]")
5240 (`(:grouptags) ":")
5241 (`(:newline) "\\n")
5242 ((and
5243 (guard (not skip-key))
5244 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5245 (format "%s(%c)" tag key))
5246 (`(,(and tag (pred stringp)) . ,_) tag)
5247 (_ (user-error "Invalid tag token: %S" token))))
5248 alist
5249 " "))
5251 (defun org-tag-alist-to-groups (alist)
5252 "Return group alist from tag ALIST.
5253 ALIST is an alist, as defined in `org-tag-alist' or
5254 `org-tag-persistent-alist', or produced with
5255 `org-tag-string-to-alist'. Return value is an alist following
5256 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5257 a string, summarizing TAGS, as a list of strings."
5258 (let (groups group-status current-group)
5259 (dolist (token alist (nreverse groups))
5260 (pcase token
5261 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5262 (`(,(or :endgroup :endgrouptag))
5263 (when (eq group-status 'append)
5264 (push (nreverse current-group) groups))
5265 (setq group-status nil))
5266 (`(:grouptags) (setq group-status 'append))
5267 ((and `(,tag . ,_) (guard group-status))
5268 (if (eq group-status 'append) (push tag current-group)
5269 (setq current-group (list tag))))
5270 (_ nil)))))
5272 (defun org-file-contents (file &optional noerror)
5273 "Return the contents of FILE, as a string."
5274 (if (and file (file-readable-p file))
5275 (with-temp-buffer
5276 (insert-file-contents file)
5277 (buffer-string))
5278 (funcall (if noerror 'message 'error)
5279 "Cannot read file \"%s\"%s"
5280 file
5281 (let ((from (buffer-file-name (buffer-base-buffer))))
5282 (if from (concat " (referenced in file \"" from "\")") "")))))
5284 (defun org-extract-log-state-settings (x)
5285 "Extract the log state setting from a TODO keyword string.
5286 This will extract info from a string like \"WAIT(w@/!)\"."
5287 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5288 (let ((kw (match-string 1 x))
5289 (log1 (and (match-end 3) (match-string 3 x)))
5290 (log2 (and (match-end 4) (match-string 4 x))))
5291 (and (or log1 log2)
5292 (list kw
5293 (and log1 (if (equal log1 "!") 'time 'note))
5294 (and log2 (if (equal log2 "!") 'time 'note)))))))
5296 (defun org-remove-keyword-keys (list)
5297 "Remove a pair of parenthesis at the end of each string in LIST."
5298 (mapcar (lambda (x)
5299 (if (string-match "(.*)$" x)
5300 (substring x 0 (match-beginning 0))
5302 list))
5304 (defun org-assign-fast-keys (alist)
5305 "Assign fast keys to a keyword-key alist.
5306 Respect keys that are already there."
5307 (let (new e (alt ?0))
5308 (while (setq e (pop alist))
5309 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5310 (cdr e)) ;; Key already assigned.
5311 (push e new)
5312 (let ((clist (string-to-list (downcase (car e))))
5313 (used (append new alist)))
5314 (when (= (car clist) ?@)
5315 (pop clist))
5316 (while (and clist (rassoc (car clist) used))
5317 (pop clist))
5318 (unless clist
5319 (while (rassoc alt used)
5320 (cl-incf alt)))
5321 (push (cons (car e) (or (car clist) alt)) new))))
5322 (nreverse new)))
5324 ;;; Some variables used in various places
5326 (defvar org-window-configuration nil
5327 "Used in various places to store a window configuration.")
5328 (defvar org-selected-window nil
5329 "Used in various places to store a window configuration.")
5330 (defvar org-finish-function nil
5331 "Function to be called when `C-c C-c' is used.
5332 This is for getting out of special buffers like capture.")
5333 (defvar org-last-state)
5335 ;; Defined somewhere in this file, but used before definition.
5336 (defvar org-entities) ;; defined in org-entities.el
5337 (defvar org-struct-menu)
5338 (defvar org-org-menu)
5339 (defvar org-tbl-menu)
5341 ;;;; Define the Org mode
5343 ;; We use a before-change function to check if a table might need
5344 ;; an update.
5345 (defvar org-table-may-need-update t
5346 "Indicates that a table might need an update.
5347 This variable is set by `org-before-change-function'.
5348 `org-table-align' sets it back to nil.")
5349 (defun org-before-change-function (_beg _end)
5350 "Every change indicates that a table might need an update."
5351 (setq org-table-may-need-update t))
5352 (defvar org-mode-map)
5353 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5354 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5355 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5356 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5357 (defvar org-table-buffer-is-an nil)
5359 (defvar bidi-paragraph-direction)
5360 (defvar buffer-face-mode-face)
5362 (require 'outline)
5364 ;; Other stuff we need.
5365 (require 'time-date)
5366 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5367 (require 'easymenu)
5368 (autoload 'easy-menu-add "easymenu")
5369 (require 'overlay)
5371 ;; (require 'org-macs) moved higher up in the file before it is first used
5372 (require 'org-entities)
5373 ;; (require 'org-compat) moved higher up in the file before it is first used
5374 (require 'org-faces)
5375 (require 'org-list)
5376 (require 'org-pcomplete)
5377 (require 'org-src)
5378 (require 'org-footnote)
5379 (require 'org-macro)
5381 ;; babel
5382 (require 'ob)
5384 ;;;###autoload
5385 (define-derived-mode org-mode outline-mode "Org"
5386 "Outline-based notes management and organizer, alias
5387 \"Carsten's outline-mode for keeping track of everything.\"
5389 Org mode develops organizational tasks around a NOTES file which
5390 contains information about projects as plain text. Org mode is
5391 implemented on top of Outline mode, which is ideal to keep the content
5392 of large files well structured. It supports ToDo items, deadlines and
5393 time stamps, which magically appear in the diary listing of the Emacs
5394 calendar. Tables are easily created with a built-in table editor.
5395 Plain text URL-like links connect to websites, emails (VM), Usenet
5396 messages (Gnus), BBDB entries, and any files related to the project.
5397 For printing and sharing of notes, an Org file (or a part of it)
5398 can be exported as a structured ASCII or HTML file.
5400 The following commands are available:
5402 \\{org-mode-map}"
5404 ;; Get rid of Outline menus, they are not needed
5405 ;; Need to do this here because define-derived-mode sets up
5406 ;; the keymap so late. Still, it is a waste to call this each time
5407 ;; we switch another buffer into Org mode.
5408 (define-key org-mode-map [menu-bar headings] 'undefined)
5409 (define-key org-mode-map [menu-bar hide] 'undefined)
5410 (define-key org-mode-map [menu-bar show] 'undefined)
5412 (org-load-modules-maybe)
5413 (org-install-agenda-files-menu)
5414 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5415 (add-to-invisibility-spec '(org-cwidth))
5416 (add-to-invisibility-spec '(org-hide-block . t))
5417 (setq-local outline-regexp org-outline-regexp)
5418 (setq-local outline-level 'org-outline-level)
5419 (setq bidi-paragraph-direction 'left-to-right)
5420 (when (and org-ellipsis
5421 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5422 (fboundp 'make-glyph-code))
5423 (unless org-display-table
5424 (setq org-display-table (make-display-table)))
5425 (set-display-table-slot
5426 org-display-table 4
5427 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5428 (if (stringp org-ellipsis) org-ellipsis "..."))))
5429 (setq buffer-display-table org-display-table))
5430 (org-set-regexps-and-options)
5431 (org-set-font-lock-defaults)
5432 (when (and org-tag-faces (not org-tags-special-faces-re))
5433 ;; tag faces set outside customize.... force initialization.
5434 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5435 ;; Calc embedded
5436 (setq-local calc-embedded-open-mode "# ")
5437 ;; Modify a few syntax entries
5438 (modify-syntax-entry ?@ "w")
5439 (modify-syntax-entry ?\" "\"")
5440 (modify-syntax-entry ?\\ "_")
5441 (modify-syntax-entry ?~ "_")
5442 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5443 ;; Activate before-change-function
5444 (setq-local org-table-may-need-update t)
5445 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5446 ;; Check for running clock before killing a buffer
5447 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5448 ;; Initialize macros templates.
5449 (org-macro-initialize-templates)
5450 ;; Initialize radio targets.
5451 (org-update-radio-target-regexp)
5452 ;; Indentation.
5453 (setq-local indent-line-function 'org-indent-line)
5454 (setq-local indent-region-function 'org-indent-region)
5455 ;; Filling and auto-filling.
5456 (org-setup-filling)
5457 ;; Comments.
5458 (org-setup-comments-handling)
5459 ;; Initialize cache.
5460 (org-element-cache-reset)
5461 ;; Beginning/end of defun
5462 (setq-local beginning-of-defun-function 'org-backward-element)
5463 (setq-local end-of-defun-function
5464 (lambda ()
5465 (if (not (org-at-heading-p))
5466 (org-forward-element)
5467 (org-forward-element)
5468 (forward-char -1))))
5469 ;; Next error for sparse trees
5470 (setq-local next-error-function 'org-occur-next-match)
5471 ;; Make sure dependence stuff works reliably, even for users who set it
5472 ;; too late :-(
5473 (if org-enforce-todo-dependencies
5474 (add-hook 'org-blocker-hook
5475 'org-block-todo-from-children-or-siblings-or-parent)
5476 (remove-hook 'org-blocker-hook
5477 'org-block-todo-from-children-or-siblings-or-parent))
5478 (if org-enforce-todo-checkbox-dependencies
5479 (add-hook 'org-blocker-hook
5480 'org-block-todo-from-checkboxes)
5481 (remove-hook 'org-blocker-hook
5482 'org-block-todo-from-checkboxes))
5484 ;; Align options lines
5485 (setq-local
5486 align-mode-rules-list
5487 '((org-in-buffer-settings
5488 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5489 (modes . '(org-mode)))))
5491 ;; Imenu
5492 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5494 ;; Make isearch reveal context
5495 (setq-local outline-isearch-open-invisible-function
5496 (lambda (&rest _) (org-show-context 'isearch)))
5498 ;; Setup the pcomplete hooks
5499 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5500 (setq-local pcomplete-command-name-function 'org-command-at-point)
5501 (setq-local pcomplete-default-completion-function 'ignore)
5502 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5503 (setq-local pcomplete-termination-string "")
5504 (setq-local buffer-face-mode-face 'org-default)
5506 ;; If empty file that did not turn on Org mode automatically, make
5507 ;; it to.
5508 (when (and org-insert-mode-line-in-empty-file
5509 (called-interactively-p 'any)
5510 (= (point-min) (point-max)))
5511 (insert "# -*- mode: org -*-\n\n"))
5512 (unless org-inhibit-startup
5513 (org-unmodified
5514 (when org-startup-with-beamer-mode (org-beamer-mode))
5515 (when org-startup-align-all-tables
5516 (org-table-map-tables #'org-table-align t))
5517 (when org-startup-with-inline-images (org-display-inline-images))
5518 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5519 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5520 (when org-startup-truncated (setq truncate-lines t))
5521 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5522 (org-refresh-effort-properties)))
5523 ;; Try to set `org-hide' face correctly.
5524 (let ((foreground (org-find-invisible-foreground)))
5525 (when foreground
5526 (set-face-foreground 'org-hide foreground))))
5528 ;; Update `customize-package-emacs-version-alist'
5529 (add-to-list 'customize-package-emacs-version-alist
5530 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5531 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5532 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5533 ("9.0" . "26.1")))
5535 (defvar org-mode-transpose-word-syntax-table
5536 (let ((st (make-syntax-table text-mode-syntax-table)))
5537 (dolist (c org-emphasis-alist st)
5538 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5540 (when (fboundp 'abbrev-table-put)
5541 (abbrev-table-put org-mode-abbrev-table
5542 :parents (list text-mode-abbrev-table)))
5544 (defun org-find-invisible-foreground ()
5545 (let ((candidates (remove
5546 "unspecified-bg"
5547 (nconc
5548 (list (face-background 'default)
5549 (face-background 'org-default))
5550 (mapcar
5551 (lambda (alist)
5552 (when (boundp alist)
5553 (cdr (assq 'background-color (symbol-value alist)))))
5554 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5555 (list (face-foreground 'org-hide))))))
5556 (car (remove nil candidates))))
5558 (defun org-current-time (&optional rounding-minutes past)
5559 "Current time, possibly rounded to ROUNDING-MINUTES.
5560 When ROUNDING-MINUTES is not an integer, fall back on the car of
5561 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5562 the rounding returns a past time."
5563 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5564 (car org-time-stamp-rounding-minutes)))
5565 (time (decode-time)) res)
5566 (if (< r 1)
5567 (current-time)
5568 (setq res
5569 (apply 'encode-time
5570 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5571 (nthcdr 2 time))))
5572 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5573 (seconds-to-time (- (float-time res) (* r 60)))
5574 res))))
5576 (defun org-today ()
5577 "Return today date, considering `org-extend-today-until'."
5578 (time-to-days
5579 (time-subtract (current-time)
5580 (list 0 (* 3600 org-extend-today-until) 0))))
5582 ;;;; Font-Lock stuff, including the activators
5584 (defvar org-mouse-map (make-sparse-keymap))
5585 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5586 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5587 (when org-mouse-1-follows-link
5588 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5589 (when org-tab-follows-link
5590 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5591 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5593 (require 'font-lock)
5595 (defconst org-non-link-chars "]\t\n\r<>")
5596 (defvar org-link-types-re nil
5597 "Matches a link that has a url-like prefix like \"http:\"")
5598 (defvar org-link-re-with-space nil
5599 "Matches a link with spaces, optional angular brackets around it.")
5600 (defvar org-link-re-with-space2 nil
5601 "Matches a link with spaces, optional angular brackets around it.")
5602 (defvar org-link-re-with-space3 nil
5603 "Matches a link with spaces, only for internal part in bracket links.")
5604 (defvar org-angle-link-re nil
5605 "Matches link with angular brackets, spaces are allowed.")
5606 (defvar org-plain-link-re nil
5607 "Matches plain link, without spaces.")
5608 (defvar org-bracket-link-regexp nil
5609 "Matches a link in double brackets.")
5610 (defvar org-bracket-link-analytic-regexp nil
5611 "Regular expression used to analyze links.
5612 Here is what the match groups contain after a match:
5613 1: http:
5614 2: http
5615 3: path
5616 4: [desc]
5617 5: desc")
5618 (defvar org-bracket-link-analytic-regexp++ nil
5619 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5620 (defvar org-any-link-re nil
5621 "Regular expression matching any link.")
5623 (defconst org-match-sexp-depth 3
5624 "Number of stacked braces for sub/superscript matching.")
5626 (defun org-create-multibrace-regexp (left right n)
5627 "Create a regular expression which will match a balanced sexp.
5628 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5629 as single character strings.
5630 The regexp returned will match the entire expression including the
5631 delimiters. It will also define a single group which contains the
5632 match except for the outermost delimiters. The maximum depth of
5633 stacked delimiters is N. Escaping delimiters is not possible."
5634 (let* ((nothing (concat "[^" left right "]*?"))
5635 (or "\\|")
5636 (re nothing)
5637 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5638 (while (> n 1)
5639 (setq n (1- n)
5640 re (concat re or next)
5641 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5642 (concat left "\\(" re "\\)" right)))
5644 (defconst org-match-substring-regexp
5645 (concat
5646 "\\(\\S-\\)\\([_^]\\)\\("
5647 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5648 "\\|"
5649 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5650 "\\|"
5651 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5652 "The regular expression matching a sub- or superscript.")
5654 (defconst org-match-substring-with-braces-regexp
5655 (concat
5656 "\\(\\S-\\)\\([_^]\\)"
5657 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5658 "The regular expression matching a sub- or superscript, forcing braces.")
5660 (defun org-make-link-regexps ()
5661 "Update the link regular expressions.
5662 This should be called after the variable `org-link-parameters' has changed."
5663 (let ((types-re (regexp-opt (org-link-types) t)))
5664 (setq org-link-types-re
5665 (concat "\\`" types-re ":")
5666 org-link-re-with-space
5667 (concat "<?" types-re ":"
5668 "\\([^" org-non-link-chars " ]"
5669 "[^" org-non-link-chars "]*"
5670 "[^" org-non-link-chars " ]\\)>?")
5671 org-link-re-with-space2
5672 (concat "<?" types-re ":"
5673 "\\([^" org-non-link-chars " ]"
5674 "[^\t\n\r]*"
5675 "[^" org-non-link-chars " ]\\)>?")
5676 org-link-re-with-space3
5677 (concat "<?" types-re ":"
5678 "\\([^" org-non-link-chars " ]"
5679 "[^\t\n\r]*\\)")
5680 org-angle-link-re
5681 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5682 types-re)
5683 org-plain-link-re
5684 (concat
5685 "\\<" types-re ":"
5686 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5687 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5688 org-bracket-link-regexp
5689 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5690 org-bracket-link-analytic-regexp
5691 (concat
5692 "\\[\\["
5693 "\\(" types-re ":\\)?"
5694 "\\([^]]+\\)"
5695 "\\]"
5696 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5697 "\\]")
5698 org-bracket-link-analytic-regexp++
5699 (concat
5700 "\\[\\["
5701 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5702 "\\([^]]+\\)"
5703 "\\]"
5704 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5705 "\\]")
5706 org-any-link-re
5707 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5708 org-angle-link-re "\\)\\|\\("
5709 org-plain-link-re "\\)"))))
5711 (org-make-link-regexps)
5713 (defvar org-emph-face nil)
5715 (defun org-do-emphasis-faces (limit)
5716 "Run through the buffer and emphasize strings."
5717 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5718 (car org-emphasis-regexp-components))))
5719 (catch :exit
5720 (while (re-search-forward quick-re limit t)
5721 (let* ((marker (match-string 2))
5722 (verbatim? (member marker '("~" "="))))
5723 (when (save-excursion
5724 (goto-char (match-beginning 0))
5725 ;; Do not match headline stars. Do not consider
5726 ;; stars of a headline as closing marker for bold
5727 ;; markup either.
5728 (and (not (looking-at-p org-outline-regexp-bol))
5729 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5730 (not (string-match-p
5731 (concat org-outline-regexp-bol "\\'")
5732 (match-string 0)))))
5733 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5734 (font-lock-prepend-text-property
5735 (match-beginning 2) (match-end 2) 'face face)
5736 (when verbatim?
5737 (org-remove-flyspell-overlays-in
5738 (match-beginning 0) (match-end 0)))
5739 (add-text-properties (match-beginning 2) (match-end 2)
5740 '(font-lock-multiline t org-emphasis t))
5741 (when org-hide-emphasis-markers
5742 (add-text-properties (match-end 4) (match-beginning 5)
5743 '(invisible org-link))
5744 (add-text-properties (match-beginning 3) (match-end 3)
5745 '(invisible org-link)))
5746 (throw :exit t))))))))
5748 (defun org-emphasize (&optional char)
5749 "Insert or change an emphasis, i.e. a font like bold or italic.
5750 If there is an active region, change that region to a new emphasis.
5751 If there is no region, just insert the marker characters and position
5752 the cursor between them.
5753 CHAR should be the marker character. If it is a space, it means to
5754 remove the emphasis of the selected region.
5755 If CHAR is not given (for example in an interactive call) it will be
5756 prompted for."
5757 (interactive)
5758 (let ((erc org-emphasis-regexp-components)
5759 (string "") beg end move s)
5760 (if (org-region-active-p)
5761 (setq beg (region-beginning)
5762 end (region-end)
5763 string (buffer-substring beg end))
5764 (setq move t))
5766 (unless char
5767 (message "Emphasis marker or tag: [%s]"
5768 (mapconcat #'car org-emphasis-alist ""))
5769 (setq char (read-char-exclusive)))
5770 (if (equal char ?\s)
5771 (setq s ""
5772 move nil)
5773 (unless (assoc (char-to-string char) org-emphasis-alist)
5774 (user-error "No such emphasis marker: \"%c\"" char))
5775 (setq s (char-to-string char)))
5776 (while (and (> (length string) 1)
5777 (equal (substring string 0 1) (substring string -1))
5778 (assoc (substring string 0 1) org-emphasis-alist))
5779 (setq string (substring string 1 -1)))
5780 (setq string (concat s string s))
5781 (when beg (delete-region beg end))
5782 (unless (or (bolp)
5783 (string-match (concat "[" (nth 0 erc) "\n]")
5784 (char-to-string (char-before (point)))))
5785 (insert " "))
5786 (unless (or (eobp)
5787 (string-match (concat "[" (nth 1 erc) "\n]")
5788 (char-to-string (char-after (point)))))
5789 (insert " ") (backward-char 1))
5790 (insert string)
5791 (and move (backward-char 1))))
5793 (defconst org-nonsticky-props
5794 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5796 (defsubst org-rear-nonsticky-at (pos)
5797 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5799 (defun org-activate-plain-links (limit)
5800 "Add link properties for plain links."
5801 (when (and (re-search-forward org-plain-link-re limit t)
5802 (not (org-in-src-block-p)))
5804 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5805 'face))
5806 (link (match-string-no-properties 0))
5807 (type (match-string-no-properties 1))
5808 (path (match-string-no-properties 2))
5809 (link-start (match-beginning 0))
5810 (link-end (match-end 0))
5811 (link-face (org-link-get-parameter type :face))
5812 (help-echo (org-link-get-parameter type :help-echo))
5813 (htmlize-link (org-link-get-parameter type :htmlize-link))
5814 (activate-func (org-link-get-parameter type :activate-func)))
5815 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5816 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5817 (add-text-properties (match-beginning 0) (match-end 0)
5818 (list
5819 'mouse-face (or (org-link-get-parameter type :mouse-face)
5820 'highlight)
5821 'face (cond
5822 ;; A function that returns a face
5823 ((functionp link-face)
5824 (funcall link-face path))
5825 ;; a face
5826 ((facep link-face)
5827 link-face)
5828 ;; An anonymous face
5829 ((consp link-face)
5830 link-face)
5831 ;; default
5833 'org-link))
5834 'help-echo (cond
5835 ((stringp help-echo)
5836 help-echo)
5837 ((functionp help-echo)
5838 help-echo)
5840 (concat "LINK: "
5841 (save-match-data
5842 (org-link-unescape link)))))
5843 'htmlize-link (cond
5844 ((functionp htmlize-link)
5845 (funcall htmlize-link path))
5847 `(:uri ,link)))
5848 'keymap (or (org-link-get-parameter type :keymap)
5849 org-mouse-map)
5850 'org-link-start (match-beginning 0)))
5851 (org-rear-nonsticky-at (match-end 0))
5852 (when activate-func
5853 (funcall activate-func link-start link-end path nil))
5854 t))))
5856 (defun org-activate-code (limit)
5857 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5858 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5859 (remove-text-properties (match-beginning 0) (match-end 0)
5860 '(display t invisible t intangible t))
5863 (defcustom org-src-fontify-natively t
5864 "When non-nil, fontify code in code blocks.
5865 See also the `org-block' face."
5866 :type 'boolean
5867 :version "24.4"
5868 :package-version '(Org . "8.3")
5869 :group 'org-appearance
5870 :group 'org-babel)
5872 (defcustom org-allow-promoting-top-level-subtree nil
5873 "When non-nil, allow promoting a top level subtree.
5874 The leading star of the top level headline will be replaced
5875 by a #."
5876 :type 'boolean
5877 :version "24.1"
5878 :group 'org-appearance)
5880 (defun org-fontify-meta-lines-and-blocks (limit)
5881 (condition-case nil
5882 (org-fontify-meta-lines-and-blocks-1 limit)
5883 (error (message "org-mode fontification error in %S at %d"
5884 (current-buffer)
5885 (line-number-at-pos)))))
5887 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5888 "Fontify #+ lines and blocks."
5889 (let ((case-fold-search t))
5890 (when (re-search-forward
5891 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5892 limit t)
5893 (let ((beg (match-beginning 0))
5894 (block-start (match-end 0))
5895 (block-end nil)
5896 (lang (match-string 7))
5897 (beg1 (line-beginning-position 2))
5898 (dc1 (downcase (match-string 2)))
5899 (dc3 (downcase (match-string 3)))
5900 end end1 quoting block-type)
5901 (cond
5902 ((and (match-end 4) (equal dc3 "+begin"))
5903 ;; Truly a block
5904 (setq block-type (downcase (match-string 5))
5905 quoting (member block-type org-protecting-blocks))
5906 (when (re-search-forward
5907 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5908 nil t) ;; on purpose, we look further than LIMIT
5909 (setq end (min (point-max) (match-end 0))
5910 end1 (min (point-max) (1- (match-beginning 0))))
5911 (setq block-end (match-beginning 0))
5912 (when quoting
5913 (org-remove-flyspell-overlays-in beg1 end1)
5914 (remove-text-properties beg end
5915 '(display t invisible t intangible t)))
5916 (add-text-properties
5917 beg end '(font-lock-fontified t font-lock-multiline t))
5918 (add-text-properties beg beg1 '(face org-meta-line))
5919 (org-remove-flyspell-overlays-in beg beg1)
5920 (add-text-properties ; For end_src
5921 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5922 (org-remove-flyspell-overlays-in end1 end)
5923 (cond
5924 ((and lang (not (string= lang "")) org-src-fontify-natively)
5925 (org-src-font-lock-fontify-block lang block-start block-end)
5926 (add-text-properties beg1 block-end '(src-block t)))
5927 (quoting
5928 (add-text-properties beg1 (min (point-max) (1+ end1))
5929 (list 'face
5930 (list :inherit
5931 (let ((face-name
5932 (intern (format "org-block-%s" lang))))
5933 (append (and (facep face-name) (list face-name))
5934 '(org-block))))))) ; end of source block
5935 ((not org-fontify-quote-and-verse-blocks))
5936 ((string= block-type "quote")
5937 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5938 ((string= block-type "verse")
5939 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5940 (add-text-properties beg beg1 '(face org-block-begin-line))
5941 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5942 '(face org-block-end-line))
5944 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5945 (org-remove-flyspell-overlays-in
5946 (match-beginning 0)
5947 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5948 (add-text-properties
5949 beg (match-end 3)
5950 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5951 '(font-lock-fontified t invisible t)
5952 '(font-lock-fontified t face org-document-info-keyword)))
5953 (add-text-properties
5954 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5955 (if (string-equal dc1 "+title:")
5956 '(font-lock-fontified t face org-document-title)
5957 '(font-lock-fontified t face org-document-info))))
5958 ((string-prefix-p "+caption" dc1)
5959 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5960 (remove-text-properties (match-beginning 0) (match-end 0)
5961 '(display t invisible t intangible t))
5962 ;; Handle short captions.
5963 (save-excursion
5964 (beginning-of-line)
5965 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5966 (add-text-properties (line-beginning-position) (match-end 1)
5967 '(font-lock-fontified t face org-meta-line))
5968 (add-text-properties (match-end 0) (line-end-position)
5969 '(font-lock-fontified t face org-block))
5971 ((member dc3 '(" " ""))
5972 (org-remove-flyspell-overlays-in beg (match-end 0))
5973 (add-text-properties
5974 beg (match-end 0)
5975 '(font-lock-fontified t face font-lock-comment-face)))
5976 (t ;; just any other in-buffer setting, but not indented
5977 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5978 (remove-text-properties (match-beginning 0) (match-end 0)
5979 '(display t invisible t intangible t))
5980 (add-text-properties beg (match-end 0)
5981 '(font-lock-fontified t face org-meta-line))
5982 t))))))
5984 (defun org-fontify-drawers (limit)
5985 "Fontify drawers."
5986 (when (re-search-forward org-drawer-regexp limit t)
5987 (add-text-properties
5988 (match-beginning 0) (match-end 0)
5989 '(font-lock-fontified t face org-special-keyword))
5990 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5993 (defun org-fontify-macros (limit)
5994 "Fontify macros."
5995 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5996 (add-text-properties
5997 (match-beginning 0) (match-end 0)
5998 '(font-lock-fontified t face org-macro))
5999 (when org-hide-macro-markers
6000 (add-text-properties (match-end 2) (match-beginning 2)
6001 '(invisible t))
6002 (add-text-properties (match-beginning 1) (match-end 1)
6003 '(invisible t)))
6004 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6007 (defun org-activate-angle-links (limit)
6008 "Add text properties for angle links."
6009 (when (and (re-search-forward org-angle-link-re limit t)
6010 (not (org-in-src-block-p)))
6011 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6012 (add-text-properties (match-beginning 0) (match-end 0)
6013 (list 'mouse-face 'highlight
6014 'keymap org-mouse-map
6015 'font-lock-multiline t))
6016 (org-rear-nonsticky-at (match-end 0))
6019 (defun org-activate-footnote-links (limit)
6020 "Add text properties for footnotes."
6021 (let ((fn (org-footnote-next-reference-or-definition limit)))
6022 (when fn
6023 (let* ((beg (nth 1 fn))
6024 (end (nth 2 fn))
6025 (label (car fn))
6026 (referencep (/= (line-beginning-position) beg)))
6027 (when (and referencep (nth 3 fn))
6028 (save-excursion
6029 (goto-char beg)
6030 (search-forward (or label "fn:"))
6031 (org-remove-flyspell-overlays-in beg (match-end 0))))
6032 (add-text-properties beg end
6033 (list 'mouse-face 'highlight
6034 'keymap org-mouse-map
6035 'help-echo
6036 (if referencep "Footnote reference"
6037 "Footnote definition")
6038 'font-lock-fontified t
6039 'font-lock-multiline t
6040 'face 'org-footnote))))))
6042 (defun org-activate-bracket-links (limit)
6043 "Add text properties for bracketed links."
6044 (when (and (re-search-forward org-bracket-link-regexp limit t)
6045 (not (org-in-src-block-p)))
6046 (let* ((hl (save-match-data
6047 (org-link-expand-abbrev (match-string-no-properties 1))))
6048 (type (save-match-data
6049 (and (string-match org-plain-link-re hl)
6050 (match-string-no-properties 1 hl))))
6051 (path (save-match-data
6052 (and (string-match org-plain-link-re hl)
6053 (match-string-no-properties 2 hl))))
6054 (link-start (match-beginning 0))
6055 (link-end (match-end 0))
6056 (bracketp t)
6057 (help-echo (org-link-get-parameter type :help-echo))
6058 (help (cond
6059 ((stringp help-echo)
6060 help-echo)
6061 ((functionp help-echo)
6062 help-echo)
6064 (concat "LINK: "
6065 (save-match-data
6066 (org-link-unescape hl))))))
6067 (link-face (org-link-get-parameter type :face))
6068 (face (cond
6069 ;; A function that returns a face
6070 ((functionp link-face)
6071 (funcall link-face path))
6072 ;; a face
6073 ((facep link-face)
6074 link-face)
6075 ;; An anonymous face
6076 ((consp link-face)
6077 link-face)
6078 ;; default
6080 'org-link)))
6081 (keymap (or (org-link-get-parameter type :keymap)
6082 org-mouse-map))
6083 (mouse-face (or (org-link-get-parameter type :mouse-face)
6084 'highlight))
6085 (htmlize (org-link-get-parameter type :htmlize-link))
6086 (htmlize-link (cond
6087 ((functionp htmlize)
6088 (funcall htmlize))
6090 `(:uri ,(format "%s:%s" type path)))))
6091 (activate-func (org-link-get-parameter type :activate-func))
6092 ;; invisible part
6093 (ip (list 'invisible (or
6094 (org-link-get-parameter type :display)
6095 'org-link)
6096 'face face
6097 'keymap keymap
6098 'mouse-face mouse-face
6099 'font-lock-multiline t
6100 'help-echo help
6101 'htmlize-link htmlize-link))
6102 ;; visible part
6103 (vp (list 'keymap keymap
6104 'face face
6105 'mouse-face mouse-face
6106 'font-lock-multiline t
6107 'help-echo help
6108 'htmlize-link htmlize-link)))
6109 ;; We need to remove the invisible property here. Table narrowing
6110 ;; may have made some of this invisible.
6111 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6112 (remove-text-properties (match-beginning 0) (match-end 0)
6113 '(invisible nil))
6114 (if (match-end 3)
6115 (progn
6116 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6117 (org-rear-nonsticky-at (match-beginning 3))
6118 (add-text-properties (match-beginning 3) (match-end 3) vp)
6119 (org-rear-nonsticky-at (match-end 3))
6120 (add-text-properties (match-end 3) (match-end 0) ip)
6121 (org-rear-nonsticky-at (match-end 0)))
6122 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6123 (org-rear-nonsticky-at (match-beginning 1))
6124 (add-text-properties (match-beginning 1) (match-end 1) vp)
6125 (org-rear-nonsticky-at (match-end 1))
6126 (add-text-properties (match-end 1) (match-end 0) ip)
6127 (org-rear-nonsticky-at (match-end 0)))
6128 (when activate-func
6129 (funcall activate-func link-start link-end path bracketp))
6130 t)))
6132 (defun org-activate-dates (limit)
6133 "Add text properties for dates."
6134 (when (and (re-search-forward org-tsr-regexp-both limit t)
6135 (not (equal (char-before (match-beginning 0)) 91)))
6136 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6137 (add-text-properties (match-beginning 0) (match-end 0)
6138 (list 'mouse-face 'highlight
6139 'keymap org-mouse-map))
6140 (org-rear-nonsticky-at (match-end 0))
6141 (when org-display-custom-times
6142 (if (match-end 3)
6143 (org-display-custom-time (match-beginning 3) (match-end 3))
6144 (org-display-custom-time (match-beginning 1) (match-end 1))))
6147 (defvar-local org-target-link-regexp nil
6148 "Regular expression matching radio targets in plain text.")
6150 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6151 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6152 border border border))
6153 "Regular expression matching a link target.")
6155 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6156 "Regular expression matching a radio target.")
6158 (defconst org-any-target-regexp
6159 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6160 "Regular expression matching any target.")
6162 (defun org-activate-target-links (limit)
6163 "Add text properties for target matches."
6164 (when org-target-link-regexp
6165 (let ((case-fold-search t))
6166 (when (re-search-forward org-target-link-regexp limit t)
6167 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6168 (add-text-properties (match-beginning 1) (match-end 1)
6169 (list 'mouse-face 'highlight
6170 'keymap org-mouse-map
6171 'help-echo "Radio target link"
6172 'org-linked-text t))
6173 (org-rear-nonsticky-at (match-end 1))
6174 t))))
6176 (defun org-update-radio-target-regexp ()
6177 "Find all radio targets in this file and update the regular expression.
6178 Also refresh fontification if needed."
6179 (interactive)
6180 (let ((old-regexp org-target-link-regexp)
6181 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6182 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6183 (targets
6184 (org-with-wide-buffer
6185 (goto-char (point-min))
6186 (let (rtn)
6187 (while (re-search-forward org-radio-target-regexp nil t)
6188 ;; Make sure point is really within the object.
6189 (backward-char)
6190 (let ((obj (org-element-context)))
6191 (when (eq (org-element-type obj) 'radio-target)
6192 (cl-pushnew (org-element-property :value obj) rtn
6193 :test #'equal))))
6194 rtn))))
6195 (setq org-target-link-regexp
6196 (and targets
6197 (concat before-re
6198 (mapconcat
6199 (lambda (x)
6200 (replace-regexp-in-string
6201 " +" "\\s-+" (regexp-quote x) t t))
6202 targets
6203 "\\|")
6204 after-re)))
6205 (unless (equal old-regexp org-target-link-regexp)
6206 ;; Clean-up cache.
6207 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6208 ((not org-target-link-regexp) old-regexp)
6210 (concat before-re
6211 (mapconcat
6212 (lambda (re)
6213 (substring re (length before-re)
6214 (- (length after-re))))
6215 (list old-regexp org-target-link-regexp)
6216 "\\|")
6217 after-re)))))
6218 (org-with-wide-buffer
6219 (goto-char (point-min))
6220 (while (re-search-forward regexp nil t)
6221 (org-element-cache-refresh (match-beginning 1)))))
6222 ;; Re fontify buffer.
6223 (when (memq 'radio org-highlight-links)
6224 (org-restart-font-lock)))))
6226 (defun org-hide-wide-columns (limit)
6227 (let (s e)
6228 (setq s (text-property-any (point) (or limit (point-max))
6229 'org-cwidth t))
6230 (when s
6231 (setq e (next-single-property-change s 'org-cwidth))
6232 (add-text-properties s e '(invisible org-cwidth))
6233 (goto-char e)
6234 t)))
6236 (defvar org-latex-and-related-regexp nil
6237 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6239 (defun org-compute-latex-and-related-regexp ()
6240 "Compute regular expression for LaTeX, entities and sub/superscript.
6241 Result depends on variable `org-highlight-latex-and-related'."
6242 (setq-local
6243 org-latex-and-related-regexp
6244 (let* ((re-sub
6245 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6246 ((eq org-use-sub-superscripts '{})
6247 (list org-match-substring-with-braces-regexp))
6248 (org-use-sub-superscripts (list org-match-substring-regexp))))
6249 (re-latex
6250 (when (memq 'latex org-highlight-latex-and-related)
6251 (let ((matchers (plist-get org-format-latex-options :matchers)))
6252 (delq nil
6253 (mapcar (lambda (x)
6254 (and (member (car x) matchers) (nth 1 x)))
6255 org-latex-regexps)))))
6256 (re-entities
6257 (when (memq 'entities org-highlight-latex-and-related)
6258 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6259 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6261 (defun org-do-latex-and-related (limit)
6262 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6263 LIMIT bounds the search for syntax to highlight. Stop at first
6264 highlighted object, if any. Return t if some highlighting was
6265 done, nil otherwise."
6266 (when (org-string-nw-p org-latex-and-related-regexp)
6267 (catch 'found
6268 (while (re-search-forward org-latex-and-related-regexp limit t)
6269 (unless
6270 (cl-some
6271 (lambda (f)
6272 (memq f '(org-code org-verbatim underline org-special-keyword)))
6273 (save-excursion
6274 (goto-char (1+ (match-beginning 0)))
6275 (face-at-point nil t)))
6276 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6277 '(?_ ?^))
6279 0)))
6280 (font-lock-prepend-text-property
6281 (+ offset (match-beginning 0)) (match-end 0)
6282 'face 'org-latex-and-related)
6283 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6284 '(font-lock-multiline t)))
6285 (throw 'found t)))
6286 nil)))
6288 (defun org-restart-font-lock ()
6289 "Restart `font-lock-mode', to force refontification."
6290 (when (and (boundp 'font-lock-mode) font-lock-mode)
6291 (font-lock-mode -1)
6292 (font-lock-mode 1)))
6294 (defun org-activate-tags (limit)
6295 (when (re-search-forward
6296 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6297 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6298 (add-text-properties (match-beginning 1) (match-end 1)
6299 (list 'mouse-face 'highlight
6300 'keymap org-mouse-map))
6301 (org-rear-nonsticky-at (match-end 1))
6304 (defun org-outline-level ()
6305 "Compute the outline level of the heading at point.
6307 If this is called at a normal headline, the level is the number
6308 of stars. Use `org-reduced-level' to remove the effect of
6309 `org-odd-levels'. Unlike to `org-current-level', this function
6310 takes into consideration inlinetasks."
6311 (org-with-wide-buffer
6312 (end-of-line)
6313 (if (re-search-backward org-outline-regexp-bol nil t)
6314 (1- (- (match-end 0) (match-beginning 0)))
6315 0)))
6317 (defvar org-font-lock-keywords nil)
6319 (defsubst org-re-property (property &optional literal allow-null value)
6320 "Return a regexp matching a PROPERTY line.
6322 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6323 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6324 non-nil, match properties even without a value.
6326 Match group 3 is set to the value when it exists. If there is no
6327 value and ALLOW-NULL is non-nil, it is set to the empty string.
6329 With optional argument VALUE, match only property lines with
6330 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6331 unless LITERAL is non-nil."
6332 (concat
6333 "^\\(?4:[ \t]*\\)"
6334 (format "\\(?1::\\(?2:%s\\):\\)"
6335 (if literal property (regexp-quote property)))
6336 (cond (value
6337 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6338 (if literal value (regexp-quote value))))
6339 (allow-null
6340 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6342 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6344 (defconst org-property-re
6345 (org-re-property "\\S-+" 'literal t)
6346 "Regular expression matching a property line.
6347 There are four matching groups:
6348 1: :PROPKEY: including the leading and trailing colon,
6349 2: PROPKEY without the leading and trailing colon,
6350 3: PROPVAL without leading or trailing spaces,
6351 4: the indentation of the current line,
6352 5: trailing whitespace.")
6354 (defvar org-font-lock-hook nil
6355 "Functions to be called for special font lock stuff.")
6357 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6359 (defvar org-font-lock-set-keywords-hook nil
6360 "Functions that can manipulate `org-font-lock-extra-keywords'.
6361 This is called after `org-font-lock-extra-keywords' is defined, but before
6362 it is installed to be used by font lock. This can be useful if something
6363 needs to be inserted at a specific position in the font-lock sequence.")
6365 (defun org-font-lock-hook (limit)
6366 "Run `org-font-lock-hook' within LIMIT."
6367 (run-hook-with-args 'org-font-lock-hook limit))
6369 (defun org-set-font-lock-defaults ()
6370 "Set font lock defaults for the current buffer."
6371 (let* ((em org-fontify-emphasized-text)
6372 (lk org-highlight-links)
6373 (org-font-lock-extra-keywords
6374 (list
6375 ;; Call the hook
6376 '(org-font-lock-hook)
6377 ;; Headlines
6378 `(,(if org-fontify-whole-heading-line
6379 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6380 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6381 (1 (org-get-level-face 1))
6382 (2 (org-get-level-face 2))
6383 (3 (org-get-level-face 3)))
6384 ;; Table lines
6385 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6386 (1 'org-table t))
6387 ;; Table internals
6388 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6389 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6390 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6391 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6392 ;; Drawers
6393 '(org-fontify-drawers)
6394 ;; Properties
6395 (list org-property-re
6396 '(1 'org-special-keyword t)
6397 '(3 'org-property-value t))
6398 ;; Links
6399 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6400 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6401 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6402 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6403 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6404 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6405 (when (memq 'footnote lk) '(org-activate-footnote-links))
6406 ;; Targets.
6407 (list org-any-target-regexp '(0 'org-target t))
6408 ;; Diary sexps.
6409 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6410 ;; Macro
6411 '(org-fontify-macros)
6412 '(org-hide-wide-columns (0 nil append))
6413 ;; TODO keyword
6414 (list (format org-heading-keyword-regexp-format
6415 org-todo-regexp)
6416 '(2 (org-get-todo-face 2) t))
6417 ;; DONE
6418 (if org-fontify-done-headline
6419 (list (format org-heading-keyword-regexp-format
6420 (concat
6421 "\\(?:"
6422 (mapconcat 'regexp-quote org-done-keywords "\\|")
6423 "\\)"))
6424 '(2 'org-headline-done t))
6425 nil)
6426 ;; Priorities
6427 '(org-font-lock-add-priority-faces)
6428 ;; Tags
6429 '(org-font-lock-add-tag-faces)
6430 ;; Tags groups
6431 (when (and org-group-tags org-tag-groups-alist)
6432 (list (concat org-outline-regexp-bol ".+\\(:"
6433 (regexp-opt (mapcar 'car org-tag-groups-alist))
6434 ":\\).*$")
6435 '(1 'org-tag-group prepend)))
6436 ;; Special keywords
6437 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6438 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6439 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6440 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6441 ;; Emphasis
6442 (when em '(org-do-emphasis-faces))
6443 ;; Checkboxes
6444 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6445 1 'org-checkbox prepend)
6446 (when (cdr (assq 'checkbox org-list-automatic-rules))
6447 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6448 (0 (org-get-checkbox-statistics-face) t)))
6449 ;; Description list items
6450 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6451 1 'org-list-dt prepend)
6452 ;; ARCHIVEd headings
6453 (list (concat
6454 org-outline-regexp-bol
6455 "\\(.*:" org-archive-tag ":.*\\)")
6456 '(1 'org-archived prepend))
6457 ;; Specials
6458 '(org-do-latex-and-related)
6459 '(org-fontify-entities)
6460 '(org-raise-scripts)
6461 ;; Code
6462 '(org-activate-code (1 'org-code t))
6463 ;; COMMENT
6464 (list (format
6465 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6466 org-todo-regexp
6467 org-comment-string)
6468 '(9 'org-special-keyword t))
6469 ;; Blocks and meta lines
6470 '(org-fontify-meta-lines-and-blocks))))
6471 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6472 (run-hooks 'org-font-lock-set-keywords-hook)
6473 ;; Now set the full font-lock-keywords
6474 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6475 (setq-local font-lock-defaults
6476 '(org-font-lock-keywords t nil nil backward-paragraph))
6477 (kill-local-variable 'font-lock-keywords)
6478 nil))
6480 (defun org-toggle-pretty-entities ()
6481 "Toggle the composition display of entities as UTF8 characters."
6482 (interactive)
6483 (setq-local org-pretty-entities (not org-pretty-entities))
6484 (org-restart-font-lock)
6485 (if org-pretty-entities
6486 (message "Entities are now displayed as UTF8 characters")
6487 (save-restriction
6488 (widen)
6489 (decompose-region (point-min) (point-max))
6490 (message "Entities are now displayed as plain text"))))
6492 (defvar-local org-custom-properties-overlays nil
6493 "List of overlays used for custom properties.")
6495 (defun org-toggle-custom-properties-visibility ()
6496 "Display or hide properties in `org-custom-properties'."
6497 (interactive)
6498 (if org-custom-properties-overlays
6499 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6500 (setq org-custom-properties-overlays nil))
6501 (when org-custom-properties
6502 (org-with-wide-buffer
6503 (goto-char (point-min))
6504 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6505 (while (re-search-forward regexp nil t)
6506 (let ((end (cdr (save-match-data (org-get-property-block)))))
6507 (when (and end (< (point) end))
6508 ;; Hide first custom property in current drawer.
6509 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6510 (overlay-put o 'invisible t)
6511 (overlay-put o 'org-custom-property t)
6512 (push o org-custom-properties-overlays))
6513 ;; Hide additional custom properties in the same drawer.
6514 (while (re-search-forward regexp end t)
6515 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6516 (overlay-put o 'invisible t)
6517 (overlay-put o 'org-custom-property t)
6518 (push o org-custom-properties-overlays)))))
6519 ;; Each entry is limited to a single property drawer.
6520 (outline-next-heading)))))))
6522 (defun org-fontify-entities (limit)
6523 "Find an entity to fontify."
6524 (let (ee)
6525 (when org-pretty-entities
6526 (catch 'match
6527 ;; "\_ "-family is left out on purpose. Only the first one,
6528 ;; i.e., "\_ ", could be fontified anyway, and it would be
6529 ;; confusing when adding a second white space character.
6530 (while (re-search-forward
6531 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6532 limit t)
6533 (when (and (not (org-at-comment-p))
6534 (setq ee (org-entity-get (match-string 1)))
6535 (= (length (nth 6 ee)) 1))
6536 (let* ((end (if (equal (match-string 2) "{}")
6537 (match-end 2)
6538 (match-end 1))))
6539 (add-text-properties
6540 (match-beginning 0) end
6541 (list 'font-lock-fontified t))
6542 (compose-region (match-beginning 0) end
6543 (nth 6 ee) nil)
6544 (backward-char 1)
6545 (throw 'match t))))
6546 nil))))
6548 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6549 "Fontify string S like in Org mode."
6550 (with-temp-buffer
6551 (insert s)
6552 (let ((org-odd-levels-only odd-levels))
6553 (org-mode)
6554 (org-font-lock-ensure)
6555 (buffer-string))))
6557 (defvar org-m nil)
6558 (defvar org-l nil)
6559 (defvar org-f nil)
6560 (defun org-get-level-face (n)
6561 "Get the right face for match N in font-lock matching of headlines."
6562 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6563 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6564 (if org-cycle-level-faces
6565 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6566 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6567 (cond
6568 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6569 ((eq n 2) org-f)
6570 (t (unless org-level-color-stars-only org-f))))
6572 (defun org-face-from-face-or-color (context inherit face-or-color)
6573 "Create a face list that inherits INHERIT, but sets the foreground color.
6574 When FACE-OR-COLOR is not a string, just return it."
6575 (if (stringp face-or-color)
6576 (list :inherit inherit
6577 (cdr (assoc context org-faces-easy-properties))
6578 face-or-color)
6579 face-or-color))
6581 (defun org-get-todo-face (kwd)
6582 "Get the right face for a TODO keyword KWD.
6583 If KWD is a number, get the corresponding match group."
6584 (when (numberp kwd) (setq kwd (match-string kwd)))
6585 (or (org-face-from-face-or-color
6586 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6587 (and (member kwd org-done-keywords) 'org-done)
6588 'org-todo))
6590 (defun org-get-priority-face (priority)
6591 "Get the right face for PRIORITY.
6592 PRIORITY is a character."
6593 (or (org-face-from-face-or-color
6594 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6595 'org-priority))
6597 (defun org-get-tag-face (tag)
6598 "Get the right face for TAG.
6599 If TAG is a number, get the corresponding match group."
6600 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6601 (or (org-face-from-face-or-color
6602 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6603 'org-tag)))
6605 (defun org-font-lock-add-priority-faces (limit)
6606 "Add the special priority faces."
6607 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6608 (add-text-properties
6609 (match-beginning 1) (match-end 1)
6610 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6611 'font-lock-fontified t))))
6613 (defun org-font-lock-add-tag-faces (limit)
6614 "Add the special tag faces."
6615 (when (and org-tag-faces org-tags-special-faces-re)
6616 (while (re-search-forward org-tags-special-faces-re limit t)
6617 (add-text-properties (match-beginning 1) (match-end 1)
6618 (list 'face (org-get-tag-face 1)
6619 'font-lock-fontified t))
6620 (backward-char 1))))
6622 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6623 "Remove fontification and activation overlays from links."
6624 (font-lock-default-unfontify-region beg end)
6625 (let* ((buffer-undo-list t)
6626 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6627 (inhibit-modification-hooks t)
6628 deactivate-mark buffer-file-name buffer-file-truename)
6629 (decompose-region beg end)
6630 (remove-text-properties beg end
6631 '(mouse-face t keymap t org-linked-text t
6632 invisible t intangible t
6633 org-emphasis t))
6634 (org-remove-font-lock-display-properties beg end)))
6636 (defconst org-script-display '(((raise -0.3) (height 0.7))
6637 ((raise 0.3) (height 0.7))
6638 ((raise -0.5))
6639 ((raise 0.5)))
6640 "Display properties for showing superscripts and subscripts.")
6642 (defun org-remove-font-lock-display-properties (beg end)
6643 "Remove specific display properties that have been added by font lock.
6644 The will remove the raise properties that are used to show superscripts
6645 and subscripts."
6646 (let (next prop)
6647 (while (< beg end)
6648 (setq next (next-single-property-change beg 'display nil end)
6649 prop (get-text-property beg 'display))
6650 (when (member prop org-script-display)
6651 (put-text-property beg next 'display nil))
6652 (setq beg next))))
6654 (defun org-raise-scripts (limit)
6655 "Add raise properties to sub/superscripts."
6656 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6657 (re-search-forward
6658 (if (eq org-use-sub-superscripts t)
6659 org-match-substring-regexp
6660 org-match-substring-with-braces-regexp)
6661 limit t))
6662 (let* ((pos (point)) table-p comment-p
6663 (mpos (match-beginning 3))
6664 (emph-p (get-text-property mpos 'org-emphasis))
6665 (link-p (get-text-property mpos 'mouse-face))
6666 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6667 (goto-char (point-at-bol))
6668 (setq table-p (looking-at-p org-table-dataline-regexp)
6669 comment-p (looking-at-p "^[ \t]*#[ +]"))
6670 (goto-char pos)
6671 ;; Handle a_b^c
6672 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6673 (unless (or comment-p emph-p link-p keyw-p)
6674 (put-text-property (match-beginning 3) (match-end 0)
6675 'display
6676 (if (equal (char-after (match-beginning 2)) ?^)
6677 (nth (if table-p 3 1) org-script-display)
6678 (nth (if table-p 2 0) org-script-display)))
6679 (add-text-properties (match-beginning 2) (match-end 2)
6680 (list 'invisible t
6681 'org-dwidth t 'org-dwidth-n 1))
6682 (if (and (eq (char-after (match-beginning 3)) ?{)
6683 (eq (char-before (match-end 3)) ?}))
6684 (progn
6685 (add-text-properties
6686 (match-beginning 3) (1+ (match-beginning 3))
6687 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6688 (add-text-properties
6689 (1- (match-end 3)) (match-end 3)
6690 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6691 t)))
6693 ;;;; Visibility cycling, including org-goto and indirect buffer
6695 ;;; Cycling
6697 (defvar-local org-cycle-global-status nil)
6698 (put 'org-cycle-global-status 'org-state t)
6699 (defvar-local org-cycle-subtree-status nil)
6700 (put 'org-cycle-subtree-status 'org-state t)
6702 (defvar org-inlinetask-min-level)
6704 (defun org-unlogged-message (&rest args)
6705 "Display a message, but avoid logging it in the *Messages* buffer."
6706 (let ((message-log-max nil))
6707 (apply 'message args)))
6709 ;;;###autoload
6710 (defun org-cycle (&optional arg)
6711 "TAB-action and visibility cycling for Org mode.
6713 This is the command invoked in Org mode by the `TAB' key. Its main
6714 purpose is outline visibility cycling, but it also invokes other actions
6715 in special contexts.
6717 When this function is called with a `\\[universal-argument]' prefix, rotate \
6718 the entire
6719 buffer through 3 states (global cycling)
6720 1. OVERVIEW: Show only top-level headlines.
6721 2. CONTENTS: Show all headlines of all levels, but no body text.
6722 3. SHOW ALL: Show everything.
6724 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6725 switch to the startup visibility,
6726 determined by the variable `org-startup-folded', and by any VISIBILITY
6727 properties in the buffer.
6729 With a `\\[universal-argument] \\[universal-argument] \
6730 \\[universal-argument]' prefix argument, show the entire buffer, including
6731 any drawers.
6733 When inside a table, re-align the table and move to the next field.
6735 When point is at the beginning of a headline, rotate the subtree started
6736 by this line through 3 different states (local cycling)
6737 1. FOLDED: Only the main headline is shown.
6738 2. CHILDREN: The main headline and the direct children are shown.
6739 From this state, you can move to one of the children
6740 and zoom in further.
6741 3. SUBTREE: Show the entire subtree, including body text.
6742 If there is no subtree, switch directly from CHILDREN to FOLDED.
6744 When point is at the beginning of an empty headline and the variable
6745 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6746 of the headline by demoting and promoting it to likely levels. This
6747 speeds up creation document structure by pressing `TAB' once or several
6748 times right after creating a new headline.
6750 When there is a numeric prefix, go up to a heading with level ARG, do
6751 a `show-subtree' and return to the previous cursor position. If ARG
6752 is negative, go up that many levels.
6754 When point is not at the beginning of a headline, execute the global
6755 binding for `TAB', which is re-indenting the line. See the option
6756 `org-cycle-emulate-tab' for details.
6758 As a special case, if point is at the beginning of the buffer and there is
6759 no headline in line 1, this function will act as if called with prefix arg
6760 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6761 prefix arg, but only
6762 if the variable `org-cycle-global-at-bob' is t."
6763 (interactive "P")
6764 (org-load-modules-maybe)
6765 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6766 (and org-cycle-level-after-item/entry-creation
6767 (or (org-cycle-level)
6768 (org-cycle-item-indentation))))
6769 (let* ((limit-level
6770 (or org-cycle-max-level
6771 (and (boundp 'org-inlinetask-min-level)
6772 org-inlinetask-min-level
6773 (1- org-inlinetask-min-level))))
6774 (nstars (and limit-level
6775 (if org-odd-levels-only
6776 (and limit-level (1- (* limit-level 2)))
6777 limit-level)))
6778 (org-outline-regexp
6779 (if (not (derived-mode-p 'org-mode))
6780 outline-regexp
6781 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6782 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6783 (not (looking-at org-outline-regexp))))
6784 (org-cycle-hook
6785 (if bob-special
6786 (delq 'org-optimize-window-after-visibility-change
6787 (copy-sequence org-cycle-hook))
6788 org-cycle-hook))
6789 (pos (point)))
6791 (cond
6793 ((equal arg '(16))
6794 (setq last-command 'dummy)
6795 (org-set-startup-visibility)
6796 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6798 ((equal arg '(64))
6799 (outline-show-all)
6800 (org-unlogged-message "Entire buffer visible, including drawers"))
6802 ((equal arg '(4)) (org-cycle-internal-global))
6804 ;; Try hiding block at point.
6805 ((org-hide-block-toggle-maybe))
6807 ;; Try cdlatex TAB completion
6808 ((org-try-cdlatex-tab))
6810 ;; Table: enter it or move to the next field.
6811 ((org-at-table-p 'any)
6812 (if (org-at-table.el-p)
6813 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6814 Use `\\[org-edit-special]' to edit table.el tables"))
6815 (if arg (org-table-edit-field t)
6816 (org-table-justify-field-maybe)
6817 (call-interactively 'org-table-next-field))))
6819 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6821 ;; Global cycling: delegate to `org-cycle-internal-global'.
6822 (bob-special (org-cycle-internal-global))
6824 ;; Drawers: delegate to `org-flag-drawer'.
6825 ((save-excursion
6826 (beginning-of-line 1)
6827 (looking-at org-drawer-regexp))
6828 (org-flag-drawer ; toggle block visibility
6829 (not (get-char-property (match-end 0) 'invisible))))
6831 ;; Show-subtree, ARG levels up from here.
6832 ((integerp arg)
6833 (save-excursion
6834 (org-back-to-heading)
6835 (outline-up-heading (if (< arg 0) (- arg)
6836 (- (funcall outline-level) arg)))
6837 (org-show-subtree)))
6839 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6840 ((and (featurep 'org-inlinetask)
6841 (org-inlinetask-at-task-p)
6842 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6843 (org-inlinetask-toggle-visibility))
6845 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6846 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6847 (save-excursion (move-beginning-of-line 1)
6848 (looking-at org-outline-regexp)))
6849 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6850 (org-cycle-internal-local))
6852 ;; From there: TAB emulation and template completion.
6853 (buffer-read-only (org-back-to-heading))
6855 ((run-hook-with-args-until-success
6856 'org-tab-after-check-for-cycling-hook))
6858 ((org-try-structure-completion))
6860 ((run-hook-with-args-until-success
6861 'org-tab-before-tab-emulation-hook))
6863 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6864 (or (not (bolp))
6865 (not (looking-at org-outline-regexp))))
6866 (call-interactively (global-key-binding "\t")))
6868 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6869 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6870 (or (and (eq org-cycle-emulate-tab 'white)
6871 (= (match-end 0) (point-at-eol)))
6872 (and (eq org-cycle-emulate-tab 'whitestart)
6873 (>= (match-end 0) pos))))
6875 (eq org-cycle-emulate-tab t))
6876 (call-interactively (global-key-binding "\t")))
6878 (t (save-excursion
6879 (org-back-to-heading)
6880 (org-cycle)))))))
6882 (defun org-cycle-internal-global ()
6883 "Do the global cycling action."
6884 ;; Hack to avoid display of messages for .org attachments in Gnus
6885 (let ((ga (string-match "\\*fontification" (buffer-name))))
6886 (cond
6887 ((and (eq last-command this-command)
6888 (eq org-cycle-global-status 'overview))
6889 ;; We just created the overview - now do table of contents
6890 ;; This can be slow in very large buffers, so indicate action
6891 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6892 (unless ga (org-unlogged-message "CONTENTS..."))
6893 (org-content)
6894 (unless ga (org-unlogged-message "CONTENTS...done"))
6895 (setq org-cycle-global-status 'contents)
6896 (run-hook-with-args 'org-cycle-hook 'contents))
6898 ((and (eq last-command this-command)
6899 (eq org-cycle-global-status 'contents))
6900 ;; We just showed the table of contents - now show everything
6901 (run-hook-with-args 'org-pre-cycle-hook 'all)
6902 (outline-show-all)
6903 (unless ga (org-unlogged-message "SHOW ALL"))
6904 (setq org-cycle-global-status 'all)
6905 (run-hook-with-args 'org-cycle-hook 'all))
6908 ;; Default action: go to overview
6909 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6910 (org-overview)
6911 (unless ga (org-unlogged-message "OVERVIEW"))
6912 (setq org-cycle-global-status 'overview)
6913 (run-hook-with-args 'org-cycle-hook 'overview)))))
6915 (defvar org-called-with-limited-levels nil
6916 "Non-nil when `org-with-limited-levels' is currently active.")
6918 (defun org-cycle-internal-local ()
6919 "Do the local cycling action."
6920 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6921 ;; First, determine end of headline (EOH), end of subtree or item
6922 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6923 (save-excursion
6924 (if (org-at-item-p)
6925 (progn
6926 (beginning-of-line)
6927 (setq struct (org-list-struct))
6928 (setq eoh (point-at-eol))
6929 (setq eos (org-list-get-item-end-before-blank (point) struct))
6930 (setq has-children (org-list-has-child-p (point) struct)))
6931 (org-back-to-heading)
6932 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6933 (setq eos (save-excursion (org-end-of-subtree t t)
6934 (when (bolp) (backward-char)) (point)))
6935 (setq has-children
6936 (or (save-excursion
6937 (let ((level (funcall outline-level)))
6938 (outline-next-heading)
6939 (and (org-at-heading-p t)
6940 (> (funcall outline-level) level))))
6941 (save-excursion
6942 (org-list-search-forward (org-item-beginning-re) eos t)))))
6943 ;; Determine end invisible part of buffer (EOL)
6944 (beginning-of-line 2)
6945 (while (and (not (eobp)) ;This is like `next-line'.
6946 (get-char-property (1- (point)) 'invisible))
6947 (goto-char (next-single-char-property-change (point) 'invisible))
6948 (and (eolp) (beginning-of-line 2)))
6949 (setq eol (point)))
6950 ;; Find out what to do next and set `this-command'
6951 (cond
6952 ((= eos eoh)
6953 ;; Nothing is hidden behind this heading
6954 (unless (org-before-first-heading-p)
6955 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6956 (org-unlogged-message "EMPTY ENTRY")
6957 (setq org-cycle-subtree-status nil)
6958 (save-excursion
6959 (goto-char eos)
6960 (outline-next-heading)
6961 (when (outline-invisible-p) (org-flag-heading nil))))
6962 ((and (or (>= eol eos)
6963 (not (string-match "\\S-" (buffer-substring eol eos))))
6964 (or has-children
6965 (not (setq children-skipped
6966 org-cycle-skip-children-state-if-no-children))))
6967 ;; Entire subtree is hidden in one line: children view
6968 (unless (org-before-first-heading-p)
6969 (run-hook-with-args 'org-pre-cycle-hook 'children))
6970 (if (org-at-item-p)
6971 (org-list-set-item-visibility (point-at-bol) struct 'children)
6972 (org-show-entry)
6973 (org-with-limited-levels (org-show-children))
6974 ;; FIXME: This slows down the func way too much.
6975 ;; How keep drawers hidden in subtree anyway?
6976 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6977 ;; (org-cycle-hide-drawers 'subtree))
6979 ;; Fold every list in subtree to top-level items.
6980 (when (eq org-cycle-include-plain-lists 'integrate)
6981 (save-excursion
6982 (org-back-to-heading)
6983 (while (org-list-search-forward (org-item-beginning-re) eos t)
6984 (beginning-of-line 1)
6985 (let* ((struct (org-list-struct))
6986 (prevs (org-list-prevs-alist struct))
6987 (end (org-list-get-bottom-point struct)))
6988 (dolist (e (org-list-get-all-items (point) struct prevs))
6989 (org-list-set-item-visibility e struct 'folded))
6990 (goto-char (if (< end eos) end eos)))))))
6991 (org-unlogged-message "CHILDREN")
6992 (save-excursion
6993 (goto-char eos)
6994 (outline-next-heading)
6995 (when (outline-invisible-p) (org-flag-heading nil)))
6996 (setq org-cycle-subtree-status 'children)
6997 (unless (org-before-first-heading-p)
6998 (run-hook-with-args 'org-cycle-hook 'children)))
6999 ((or children-skipped
7000 (and (eq last-command this-command)
7001 (eq org-cycle-subtree-status 'children)))
7002 ;; We just showed the children, or no children are there,
7003 ;; now show everything.
7004 (unless (org-before-first-heading-p)
7005 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7006 (outline-flag-region eoh eos nil)
7007 (org-unlogged-message
7008 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7009 (setq org-cycle-subtree-status 'subtree)
7010 (unless (org-before-first-heading-p)
7011 (run-hook-with-args 'org-cycle-hook 'subtree)))
7013 ;; Default action: hide the subtree.
7014 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7015 (outline-flag-region eoh eos t)
7016 (org-unlogged-message "FOLDED")
7017 (setq org-cycle-subtree-status 'folded)
7018 (unless (org-before-first-heading-p)
7019 (run-hook-with-args 'org-cycle-hook 'folded))))))
7021 ;;;###autoload
7022 (defun org-global-cycle (&optional arg)
7023 "Cycle the global visibility. For details see `org-cycle'.
7024 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7025 With a numeric prefix, show all headlines up to that level."
7026 (interactive "P")
7027 (let ((org-cycle-include-plain-lists
7028 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7029 (cond
7030 ((integerp arg)
7031 (outline-show-all)
7032 (outline-hide-sublevels arg)
7033 (setq org-cycle-global-status 'contents))
7034 ((equal arg '(4))
7035 (org-set-startup-visibility)
7036 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7038 (org-cycle '(4))))))
7040 (defun org-set-startup-visibility ()
7041 "Set the visibility required by startup options and properties."
7042 (cond
7043 ((eq org-startup-folded t)
7044 (org-overview))
7045 ((eq org-startup-folded 'content)
7046 (org-content))
7047 ((or (eq org-startup-folded 'showeverything)
7048 (eq org-startup-folded nil))
7049 (outline-show-all)))
7050 (unless (eq org-startup-folded 'showeverything)
7051 (when org-hide-block-startup (org-hide-block-all))
7052 (org-set-visibility-according-to-property 'no-cleanup)
7053 (org-cycle-hide-archived-subtrees 'all)
7054 (org-cycle-hide-drawers 'all)
7055 (org-cycle-show-empty-lines t)))
7057 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7058 "Switch subtree visibilities according to :VISIBILITY: property."
7059 (interactive)
7060 (org-with-wide-buffer
7061 (goto-char (point-min))
7062 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7063 (if (not (org-at-property-p)) (outline-next-heading)
7064 (let ((state (match-string 3)))
7065 (save-excursion
7066 (org-back-to-heading t)
7067 (outline-hide-subtree)
7068 (org-reveal)
7069 (cond
7070 ((equal state "folded")
7071 (outline-hide-subtree))
7072 ((equal state "children")
7073 (org-show-hidden-entry)
7074 (org-show-children))
7075 ((equal state "content")
7076 (save-excursion
7077 (save-restriction
7078 (org-narrow-to-subtree)
7079 (org-content))))
7080 ((member state '("all" "showall"))
7081 (outline-show-subtree)))))))
7082 (unless no-cleanup
7083 (org-cycle-hide-archived-subtrees 'all)
7084 (org-cycle-hide-drawers 'all)
7085 (org-cycle-show-empty-lines 'all))))
7087 ;; This function uses outline-regexp instead of the more fundamental
7088 ;; org-outline-regexp so that org-cycle-global works outside of Org
7089 ;; buffers, where outline-regexp is needed.
7090 (defun org-overview ()
7091 "Switch to overview mode, showing only top-level headlines.
7092 This shows all headlines with a level equal or greater than the level
7093 of the first headline in the buffer. This is important, because if the
7094 first headline is not level one, then (hide-sublevels 1) gives confusing
7095 results."
7096 (interactive)
7097 (save-excursion
7098 (let ((level
7099 (save-excursion
7100 (goto-char (point-min))
7101 (when (re-search-forward (concat "^" outline-regexp) nil t)
7102 (goto-char (match-beginning 0))
7103 (funcall outline-level)))))
7104 (and level (outline-hide-sublevels level)))))
7106 (defun org-content (&optional arg)
7107 "Show all headlines in the buffer, like a table of contents.
7108 With numerical argument N, show content up to level N."
7109 (interactive "P")
7110 (org-overview)
7111 (save-excursion
7112 ;; Visit all headings and show their offspring
7113 (and (integerp arg) (org-overview))
7114 (goto-char (point-max))
7115 (catch 'exit
7116 (while (and (progn (condition-case nil
7117 (outline-previous-visible-heading 1)
7118 (error (goto-char (point-min))))
7120 (looking-at org-outline-regexp))
7121 (if (integerp arg)
7122 (org-show-children (1- arg))
7123 (outline-show-branches))
7124 (when (bobp) (throw 'exit nil))))))
7126 (defun org-optimize-window-after-visibility-change (state)
7127 "Adjust the window after a change in outline visibility.
7128 This function is the default value of the hook `org-cycle-hook'."
7129 (when (get-buffer-window (current-buffer))
7130 (cond
7131 ((eq state 'content) nil)
7132 ((eq state 'all) nil)
7133 ((eq state 'folded) nil)
7134 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7135 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7137 (defun org-remove-empty-overlays-at (pos)
7138 "Remove outline overlays that do not contain non-white stuff."
7139 (dolist (o (overlays-at pos))
7140 (and (eq 'outline (overlay-get o 'invisible))
7141 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7142 (overlay-end o))))
7143 (delete-overlay o))))
7145 (defun org-clean-visibility-after-subtree-move ()
7146 "Fix visibility issues after moving a subtree."
7147 ;; First, find a reasonable region to look at:
7148 ;; Start two siblings above, end three below
7149 (let* ((beg (save-excursion
7150 (and (org-get-last-sibling)
7151 (org-get-last-sibling))
7152 (point)))
7153 (end (save-excursion
7154 (and (org-get-next-sibling)
7155 (org-get-next-sibling)
7156 (org-get-next-sibling))
7157 (if (org-at-heading-p)
7158 (point-at-eol)
7159 (point))))
7160 (level (looking-at "\\*+"))
7161 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7162 (save-excursion
7163 (save-restriction
7164 (narrow-to-region beg end)
7165 (when re
7166 ;; Properly fold already folded siblings
7167 (goto-char (point-min))
7168 (while (re-search-forward re nil t)
7169 (when (and (not (outline-invisible-p))
7170 (save-excursion
7171 (goto-char (point-at-eol)) (outline-invisible-p)))
7172 (outline-hide-entry))))
7173 (org-cycle-show-empty-lines 'overview)
7174 (org-cycle-hide-drawers 'overview)))))
7176 (defun org-cycle-show-empty-lines (state)
7177 "Show empty lines above all visible headlines.
7178 The region to be covered depends on STATE when called through
7179 `org-cycle-hook'. Lisp program can use t for STATE to get the
7180 entire buffer covered. Note that an empty line is only shown if there
7181 are at least `org-cycle-separator-lines' empty lines before the headline."
7182 (when (/= org-cycle-separator-lines 0)
7183 (save-excursion
7184 (let* ((n (abs org-cycle-separator-lines))
7185 (re (cond
7186 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7187 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7188 (t (let ((ns (number-to-string (- n 2))))
7189 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7190 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7191 beg end)
7192 (cond
7193 ((memq state '(overview contents t))
7194 (setq beg (point-min) end (point-max)))
7195 ((memq state '(children folded))
7196 (setq beg (point)
7197 end (progn (org-end-of-subtree t t)
7198 (line-beginning-position 2)))))
7199 (when beg
7200 (goto-char beg)
7201 (while (re-search-forward re end t)
7202 (unless (get-char-property (match-end 1) 'invisible)
7203 (let ((e (match-end 1))
7204 (b (if (>= org-cycle-separator-lines 0)
7205 (match-beginning 1)
7206 (save-excursion
7207 (goto-char (match-beginning 0))
7208 (skip-chars-backward " \t\n")
7209 (line-end-position)))))
7210 (outline-flag-region b e nil))))))))
7211 ;; Never hide empty lines at the end of the file.
7212 (save-excursion
7213 (goto-char (point-max))
7214 (outline-previous-heading)
7215 (outline-end-of-heading)
7216 (when (and (looking-at "[ \t\n]+")
7217 (= (match-end 0) (point-max)))
7218 (outline-flag-region (point) (match-end 0) nil))))
7220 (defun org-show-empty-lines-in-parent ()
7221 "Move to the parent and re-show empty lines before visible headlines."
7222 (save-excursion
7223 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7224 (org-cycle-show-empty-lines context))))
7226 (defun org-files-list ()
7227 "Return `org-agenda-files' list, plus all open Org files.
7228 This is useful for operations that need to scan all of a user's
7229 open and agenda-wise Org files."
7230 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7231 (dolist (buf (buffer-list))
7232 (with-current-buffer buf
7233 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7234 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7235 files))
7237 (defsubst org-entry-beginning-position ()
7238 "Return the beginning position of the current entry."
7239 (save-excursion (org-back-to-heading t) (point)))
7241 (defsubst org-entry-end-position ()
7242 "Return the end position of the current entry."
7243 (save-excursion (outline-next-heading) (point)))
7245 (defun org-cycle-hide-drawers (state &optional exceptions)
7246 "Re-hide all drawers after a visibility state change.
7247 When non-nil, optional argument EXCEPTIONS is a list of strings
7248 specifying which drawers should not be hidden."
7249 (when (and (derived-mode-p 'org-mode)
7250 (not (memq state '(overview folded contents))))
7251 (save-excursion
7252 (let* ((globalp (memq state '(contents all)))
7253 (beg (if globalp (point-min) (point)))
7254 (end (if globalp (point-max)
7255 (if (eq state 'children)
7256 (save-excursion (outline-next-heading) (point))
7257 (org-end-of-subtree t)))))
7258 (goto-char beg)
7259 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7260 (unless (member-ignore-case (match-string 1) exceptions)
7261 (let ((drawer (org-element-at-point)))
7262 (when (memq (org-element-type drawer) '(drawer property-drawer))
7263 (org-flag-drawer t drawer)
7264 ;; Make sure to skip drawer entirely or we might flag
7265 ;; it another time when matching its ending line with
7266 ;; `org-drawer-regexp'.
7267 (goto-char (org-element-property :end drawer))))))))))
7269 (defun org-flag-drawer (flag &optional element)
7270 "When FLAG is non-nil, hide the drawer we are at.
7271 Otherwise make it visible. When optional argument ELEMENT is
7272 a parsed drawer, as returned by `org-element-at-point', hide or
7273 show that drawer instead."
7274 (let ((drawer (or element
7275 (and (save-excursion
7276 (beginning-of-line)
7277 (looking-at-p org-drawer-regexp))
7278 (org-element-at-point)))))
7279 (when (memq (org-element-type drawer) '(drawer property-drawer))
7280 (let ((post (org-element-property :post-affiliated drawer)))
7281 (save-excursion
7282 (outline-flag-region
7283 (progn (goto-char post) (line-end-position))
7284 (progn (goto-char (org-element-property :end drawer))
7285 (skip-chars-backward " \r\t\n")
7286 (line-end-position))
7287 flag))
7288 ;; When the drawer is hidden away, make sure point lies in
7289 ;; a visible part of the buffer.
7290 (when (and flag (> (line-beginning-position) post))
7291 (goto-char post))))))
7293 (defun org-subtree-end-visible-p ()
7294 "Is the end of the current subtree visible?"
7295 (pos-visible-in-window-p
7296 (save-excursion (org-end-of-subtree t) (point))))
7298 (defun org-first-headline-recenter ()
7299 "Move cursor to the first headline and recenter the headline."
7300 (let ((window (get-buffer-window)))
7301 (when window
7302 (goto-char (point-min))
7303 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7304 (set-window-start window (line-beginning-position))))))
7306 ;;; Saving and restoring visibility
7308 (defun org-outline-overlay-data (&optional use-markers)
7309 "Return a list of the locations of all outline overlays.
7310 These are overlays with the `invisible' property value `outline'.
7311 The return value is a list of cons cells, with start and stop
7312 positions for each overlay.
7313 If USE-MARKERS is set, return the positions as markers."
7314 (let (beg end)
7315 (org-with-wide-buffer
7316 (delq nil
7317 (mapcar (lambda (o)
7318 (when (eq (overlay-get o 'invisible) 'outline)
7319 (setq beg (overlay-start o)
7320 end (overlay-end o))
7321 (and beg end (> end beg)
7322 (if use-markers
7323 (cons (copy-marker beg)
7324 (copy-marker end t))
7325 (cons beg end)))))
7326 (overlays-in (point-min) (point-max)))))))
7328 (defun org-set-outline-overlay-data (data)
7329 "Create visibility overlays for all positions in DATA.
7330 DATA should have been made by `org-outline-overlay-data'."
7331 (org-with-wide-buffer
7332 (outline-show-all)
7333 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7335 ;;; Folding of blocks
7337 (defvar-local org-hide-block-overlays nil
7338 "Overlays hiding blocks.")
7340 (defun org-block-map (function &optional start end)
7341 "Call FUNCTION at the head of all source blocks in the current buffer.
7342 Optional arguments START and END can be used to limit the range."
7343 (let ((start (or start (point-min)))
7344 (end (or end (point-max))))
7345 (save-excursion
7346 (goto-char start)
7347 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7348 (save-excursion
7349 (save-match-data
7350 (goto-char (match-beginning 0))
7351 (funcall function)))))))
7353 (defun org-hide-block-toggle-all ()
7354 "Toggle the visibility of all blocks in the current buffer."
7355 (org-block-map 'org-hide-block-toggle))
7357 (defun org-hide-block-all ()
7358 "Fold all blocks in the current buffer."
7359 (interactive)
7360 (org-show-block-all)
7361 (org-block-map 'org-hide-block-toggle-maybe))
7363 (defun org-show-block-all ()
7364 "Unfold all blocks in the current buffer."
7365 (interactive)
7366 (mapc #'delete-overlay org-hide-block-overlays)
7367 (setq org-hide-block-overlays nil))
7369 (defun org-hide-block-toggle-maybe ()
7370 "Toggle visibility of block at point.
7371 Unlike to `org-hide-block-toggle', this function does not throw
7372 an error. Return a non-nil value when toggling is successful."
7373 (interactive)
7374 (ignore-errors (org-hide-block-toggle)))
7376 (defun org-hide-block-toggle (&optional force)
7377 "Toggle the visibility of the current block.
7378 When optional argument FORCE is `off', make block visible. If it
7379 is non-nil, hide it unconditionally. Throw an error when not at
7380 a block. Return a non-nil value when toggling is successful."
7381 (interactive)
7382 (let ((element (org-element-at-point)))
7383 (unless (memq (org-element-type element)
7384 '(center-block comment-block dynamic-block example-block
7385 export-block quote-block special-block
7386 src-block verse-block))
7387 (user-error "Not at a block"))
7388 (let* ((start (save-excursion
7389 (goto-char (org-element-property :post-affiliated element))
7390 (line-end-position)))
7391 (end (save-excursion
7392 (goto-char (org-element-property :end element))
7393 (skip-chars-backward " \r\t\n")
7394 (line-end-position)))
7395 (overlays (overlays-at start)))
7396 (cond
7397 ;; Do nothing when not before or at the block opening line or
7398 ;; at the block closing line.
7399 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7400 ((and (not (eq force 'off))
7401 (not (memq t (mapcar
7402 (lambda (o)
7403 (eq (overlay-get o 'invisible) 'org-hide-block))
7404 overlays))))
7405 (let ((ov (make-overlay start end)))
7406 (overlay-put ov 'invisible 'org-hide-block)
7407 ;; Make the block accessible to `isearch'.
7408 (overlay-put
7409 ov 'isearch-open-invisible
7410 (lambda (ov)
7411 (when (memq ov org-hide-block-overlays)
7412 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7413 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7414 (delete-overlay ov))))
7415 (push ov org-hide-block-overlays)
7416 ;; When the block is hidden away, make sure point is left in
7417 ;; a visible part of the buffer.
7418 (when (> (line-beginning-position) start)
7419 (goto-char start)
7420 (beginning-of-line))
7421 ;; Signal successful toggling.
7423 ((or (not force) (eq force 'off))
7424 (dolist (ov overlays t)
7425 (when (memq ov org-hide-block-overlays)
7426 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7427 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7428 (delete-overlay ov))))))))
7430 ;; Remove overlays when changing major mode
7431 (add-hook 'org-mode-hook
7432 (lambda () (add-hook 'change-major-mode-hook
7433 'org-show-block-all 'append 'local)))
7435 ;;; Org-goto
7437 (defvar org-goto-window-configuration nil)
7438 (defvar org-goto-marker nil)
7439 (defvar org-goto-map)
7440 (defun org-goto-map ()
7441 "Set the keymap `org-goto'."
7442 (setq org-goto-map
7443 (let ((map (make-sparse-keymap)))
7444 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7445 mouse-drag-region universal-argument org-occur)))
7446 (dolist (cmd cmds)
7447 (substitute-key-definition cmd cmd map global-map)))
7448 (suppress-keymap map)
7449 (org-defkey map "\C-m" 'org-goto-ret)
7450 (org-defkey map [(return)] 'org-goto-ret)
7451 (org-defkey map [(left)] 'org-goto-left)
7452 (org-defkey map [(right)] 'org-goto-right)
7453 (org-defkey map [(control ?g)] 'org-goto-quit)
7454 (org-defkey map "\C-i" 'org-cycle)
7455 (org-defkey map [(tab)] 'org-cycle)
7456 (org-defkey map [(down)] 'outline-next-visible-heading)
7457 (org-defkey map [(up)] 'outline-previous-visible-heading)
7458 (if org-goto-auto-isearch
7459 (if (fboundp 'define-key-after)
7460 (define-key-after map [t] 'org-goto-local-auto-isearch)
7461 nil)
7462 (org-defkey map "q" 'org-goto-quit)
7463 (org-defkey map "n" 'outline-next-visible-heading)
7464 (org-defkey map "p" 'outline-previous-visible-heading)
7465 (org-defkey map "f" 'outline-forward-same-level)
7466 (org-defkey map "b" 'outline-backward-same-level)
7467 (org-defkey map "u" 'outline-up-heading))
7468 (org-defkey map "/" 'org-occur)
7469 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7470 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7471 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7472 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7473 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7474 map)))
7476 (defconst org-goto-help
7477 "Browse buffer copy, to find location or copy text.%s
7478 RET=jump to location C-g=quit and return to previous location
7479 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7481 (defvar org-goto-start-pos) ; dynamically scoped parameter
7483 (defun org-goto (&optional alternative-interface)
7484 "Look up a different location in the current file, keeping current visibility.
7486 When you want look-up or go to a different location in a
7487 document, the fastest way is often to fold the entire buffer and
7488 then dive into the tree. This method has the disadvantage, that
7489 the previous location will be folded, which may not be what you
7490 want.
7492 This command works around this by showing a copy of the current
7493 buffer in an indirect buffer, in overview mode. You can dive
7494 into the tree in that copy, use org-occur and incremental search
7495 to find a location. When pressing RET or `Q', the command
7496 returns to the original buffer in which the visibility is still
7497 unchanged. After RET it will also jump to the location selected
7498 in the indirect buffer and expose the headline hierarchy above.
7500 With a prefix argument, use the alternative interface: e.g., if
7501 `org-goto-interface' is `outline' use `outline-path-completion'."
7502 (interactive "P")
7503 (org-goto-map)
7504 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7505 (org-refile-use-outline-path t)
7506 (org-refile-target-verify-function nil)
7507 (interface
7508 (if (not alternative-interface)
7509 org-goto-interface
7510 (if (eq org-goto-interface 'outline)
7511 'outline-path-completion
7512 'outline)))
7513 (org-goto-start-pos (point))
7514 (selected-point
7515 (if (eq interface 'outline)
7516 (car (org-get-location (current-buffer) org-goto-help))
7517 (let ((pa (org-refile-get-location "Goto")))
7518 (org-refile-check-position pa)
7519 (nth 3 pa)))))
7520 (if selected-point
7521 (progn
7522 (org-mark-ring-push org-goto-start-pos)
7523 (goto-char selected-point)
7524 (when (or (outline-invisible-p) (org-invisible-p2))
7525 (org-show-context 'org-goto)))
7526 (message "Quit"))))
7528 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7529 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7530 (defvar org-goto-local-auto-isearch-map) ; defined below
7532 (defun org-get-location (_buf help)
7533 "Let the user select a location in current buffer.
7534 This function uses a recursive edit. It returns the selected position
7535 or nil."
7536 (org-no-popups
7537 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7538 (isearch-hide-immediately nil)
7539 (isearch-search-fun-function
7540 (lambda () 'org-goto-local-search-headings))
7541 (org-goto-selected-point org-goto-exit-command))
7542 (save-excursion
7543 (save-window-excursion
7544 (delete-other-windows)
7545 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7546 (pop-to-buffer-same-window
7547 (condition-case nil
7548 (make-indirect-buffer (current-buffer) "*org-goto*")
7549 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7550 (with-output-to-temp-buffer "*Org Help*"
7551 (princ (format help (if org-goto-auto-isearch
7552 " Just type for auto-isearch."
7553 " n/p/f/b/u to navigate, q to quit."))))
7554 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7555 (setq buffer-read-only nil)
7556 (let ((org-startup-truncated t)
7557 (org-startup-folded nil)
7558 (org-startup-align-all-tables nil))
7559 (org-mode)
7560 (org-overview))
7561 (setq buffer-read-only t)
7562 (if (and (boundp 'org-goto-start-pos)
7563 (integer-or-marker-p org-goto-start-pos))
7564 (progn (goto-char org-goto-start-pos)
7565 (when (outline-invisible-p)
7566 (org-show-set-visibility 'lineage)))
7567 (goto-char (point-min)))
7568 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7569 (message "Select location and press RET")
7570 (use-local-map org-goto-map)
7571 (recursive-edit)))
7572 (kill-buffer "*org-goto*")
7573 (cons org-goto-selected-point org-goto-exit-command))))
7575 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7576 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7577 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7578 (if (fboundp 'isearch-other-control-char)
7579 (progn
7580 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7581 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7582 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7583 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7584 (define-key org-goto-local-auto-isearch-map [return] nil))
7586 (defun org-goto-local-search-headings (string bound noerror)
7587 "Search and make sure that any matches are in headlines."
7588 (catch 'return
7589 (while (if isearch-forward
7590 (search-forward string bound noerror)
7591 (search-backward string bound noerror))
7592 (when (save-match-data
7593 (and (save-excursion
7594 (beginning-of-line)
7595 (looking-at org-complex-heading-regexp))
7596 (or (not (match-beginning 5))
7597 (< (point) (match-beginning 5)))))
7598 (throw 'return (point))))))
7600 (defun org-goto-local-auto-isearch ()
7601 "Start isearch."
7602 (interactive)
7603 (goto-char (point-min))
7604 (let ((keys (this-command-keys)))
7605 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7606 (isearch-mode t)
7607 (isearch-process-search-char (string-to-char keys)))))
7609 (defun org-goto-ret (&optional _arg)
7610 "Finish `org-goto' by going to the new location."
7611 (interactive "P")
7612 (setq org-goto-selected-point (point))
7613 (setq org-goto-exit-command 'return)
7614 (throw 'exit nil))
7616 (defun org-goto-left ()
7617 "Finish `org-goto' by going to the new location."
7618 (interactive)
7619 (if (org-at-heading-p)
7620 (progn
7621 (beginning-of-line 1)
7622 (setq org-goto-selected-point (point)
7623 org-goto-exit-command 'left)
7624 (throw 'exit nil))
7625 (user-error "Not on a heading")))
7627 (defun org-goto-right ()
7628 "Finish `org-goto' by going to the new location."
7629 (interactive)
7630 (if (org-at-heading-p)
7631 (progn
7632 (setq org-goto-selected-point (point)
7633 org-goto-exit-command 'right)
7634 (throw 'exit nil))
7635 (user-error "Not on a heading")))
7637 (defun org-goto-quit ()
7638 "Finish `org-goto' without cursor motion."
7639 (interactive)
7640 (setq org-goto-selected-point nil)
7641 (setq org-goto-exit-command 'quit)
7642 (throw 'exit nil))
7644 ;;; Indirect buffer display of subtrees
7646 (defvar org-indirect-dedicated-frame nil
7647 "This is the frame being used for indirect tree display.")
7648 (defvar org-last-indirect-buffer nil)
7650 (defun org-tree-to-indirect-buffer (&optional arg)
7651 "Create indirect buffer and narrow it to current subtree.
7653 With a numerical prefix ARG, go up to this level and then take that tree.
7654 If ARG is negative, go up that many levels.
7656 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7657 indirect buffer previously made with this command, to avoid proliferation of
7658 indirect buffers. However, when you call the command with a \
7659 `\\[universal-argument]' prefix, or
7660 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7661 so that you can work with several indirect buffers at the same time. If
7662 `org-indirect-buffer-display' is `dedicated-frame', the \
7663 `\\[universal-argument]' prefix also
7664 requests that a new frame be made for the new buffer, so that the dedicated
7665 frame is not changed."
7666 (interactive "P")
7667 (let ((cbuf (current-buffer))
7668 (cwin (selected-window))
7669 (pos (point))
7670 beg end level heading ibuf)
7671 (save-excursion
7672 (org-back-to-heading t)
7673 (when (numberp arg)
7674 (setq level (org-outline-level))
7675 (when (< arg 0) (setq arg (+ level arg)))
7676 (while (> (setq level (org-outline-level)) arg)
7677 (org-up-heading-safe)))
7678 (setq beg (point)
7679 heading (org-get-heading 'no-tags))
7680 (org-end-of-subtree t t)
7681 (when (org-at-heading-p) (backward-char 1))
7682 (setq end (point)))
7683 (when (and (buffer-live-p org-last-indirect-buffer)
7684 (not (eq org-indirect-buffer-display 'new-frame))
7685 (not arg))
7686 (kill-buffer org-last-indirect-buffer))
7687 (setq ibuf (org-get-indirect-buffer cbuf heading)
7688 org-last-indirect-buffer ibuf)
7689 (cond
7690 ((or (eq org-indirect-buffer-display 'new-frame)
7691 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7692 (select-frame (make-frame))
7693 (delete-other-windows)
7694 (pop-to-buffer-same-window ibuf)
7695 (org-set-frame-title heading))
7696 ((eq org-indirect-buffer-display 'dedicated-frame)
7697 (raise-frame
7698 (select-frame (or (and org-indirect-dedicated-frame
7699 (frame-live-p org-indirect-dedicated-frame)
7700 org-indirect-dedicated-frame)
7701 (setq org-indirect-dedicated-frame (make-frame)))))
7702 (delete-other-windows)
7703 (pop-to-buffer-same-window ibuf)
7704 (org-set-frame-title (concat "Indirect: " heading)))
7705 ((eq org-indirect-buffer-display 'current-window)
7706 (pop-to-buffer-same-window ibuf))
7707 ((eq org-indirect-buffer-display 'other-window)
7708 (pop-to-buffer ibuf))
7709 (t (error "Invalid value")))
7710 (narrow-to-region beg end)
7711 (outline-show-all)
7712 (goto-char pos)
7713 (run-hook-with-args 'org-cycle-hook 'all)
7714 (and (window-live-p cwin) (select-window cwin))))
7716 (defun org-get-indirect-buffer (&optional buffer heading)
7717 (setq buffer (or buffer (current-buffer)))
7718 (let ((n 1) (base (buffer-name buffer)) bname)
7719 (while (buffer-live-p
7720 (get-buffer
7721 (setq bname
7722 (concat base "-"
7723 (if heading (concat heading "-" (number-to-string n))
7724 (number-to-string n))))))
7725 (setq n (1+ n)))
7726 (condition-case nil
7727 (make-indirect-buffer buffer bname 'clone)
7728 (error (make-indirect-buffer buffer bname)))))
7730 (defun org-set-frame-title (title)
7731 "Set the title of the current frame to the string TITLE."
7732 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7734 ;;;; Structure editing
7736 ;;; Inserting headlines
7738 (defun org--line-empty-p (n)
7739 "Is the Nth next line empty?
7741 Counts the current line as N = 1 and the previous line as N = 0;
7742 see `beginning-of-line'."
7743 (save-excursion
7744 (and (not (bobp))
7745 (or (beginning-of-line n) t)
7746 (save-match-data
7747 (looking-at "[ \t]*$")))))
7749 (defun org-previous-line-empty-p ()
7750 "Is the previous line a blank line?
7751 When NEXT is non-nil, check the next line instead."
7752 (org--line-empty-p 0))
7754 (defun org-next-line-empty-p ()
7755 "Is the previous line a blank line?
7756 When NEXT is non-nil, check the next line instead."
7757 (org--line-empty-p 2))
7759 (defun org--blank-before-heading-p (&optional parent)
7760 "Non-nil when an empty line should precede a new heading here.
7761 When optional argument PARENT is non-nil, consider parent
7762 headline instead of current one."
7763 (pcase (assq 'heading org-blank-before-new-entry)
7764 (`(heading . auto)
7765 (save-excursion
7766 (org-with-limited-levels
7767 (unless (and (org-before-first-heading-p)
7768 (not (outline-next-heading)))
7769 (org-back-to-heading t)
7770 (when parent (org-up-heading-safe))
7771 (cond ((not (bobp))
7772 (org-previous-line-empty-p))
7773 ((outline-next-heading)
7774 (org-previous-line-empty-p))
7775 ;; Ignore trailing spaces on last buffer line.
7776 ((progn (skip-chars-backward " \t") (bolp))
7777 (org-previous-line-empty-p))
7778 (t nil))))))
7779 (`(heading . ,value) value)
7780 (_ nil)))
7782 (defun org-insert-heading (&optional arg invisible-ok top)
7783 "Insert a new heading or an item with the same depth at point.
7785 If point is at the beginning of a heading, insert a new heading
7786 or a new headline above the current one. When at the beginning
7787 of a regular line of text, turn it into a heading.
7789 If point is in the middle of a line, split it and create a new
7790 headline with the text in the current line after point (see
7791 `org-M-RET-may-split-line' on how to modify this behavior). As
7792 a special case, on a headline, splitting can only happen on the
7793 title itself. E.g., this excludes breaking stars or tags.
7795 With a `\\[universal-argument]' prefix, set \
7796 `org-insert-heading-respect-content' to
7797 a non-nil value for the duration of the command. This forces the
7798 insertion of a heading after the current subtree, independently
7799 on the location of point.
7801 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7802 insert the heading at the end of the tree
7803 above the current heading. For example, if point is within a
7804 2nd-level heading, then it will insert a 2nd-level heading at
7805 the end of the 1st-level parent subtree.
7807 When INVISIBLE-OK is set, stop at invisible headlines when going
7808 back. This is important for non-interactive uses of the
7809 command.
7811 When optional argument TOP is non-nil, insert a level 1 heading,
7812 unconditionally."
7813 (interactive "P")
7814 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7815 (level (org-current-level))
7816 (stars (make-string (if (and level (not top)) level 1) ?*)))
7817 (cond
7818 ((or org-insert-heading-respect-content
7819 (member arg '((4) (16)))
7820 (and (not invisible-ok)
7821 (invisible-p (max (1- (point)) (point-min)))))
7822 ;; Position point at the location of insertion.
7823 (if (not level) ;before first headline
7824 (org-with-limited-levels (outline-next-heading))
7825 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7826 ;; is nil.
7827 (org-with-limited-levels (org-back-to-heading invisible-ok))
7828 (cond ((equal arg '(16))
7829 (org-up-heading-safe)
7830 (org-end-of-subtree t t))
7832 (org-end-of-subtree t t))))
7833 (unless (bolp) (insert "\n")) ;ensure final newline
7834 (unless (and blank? (org-previous-line-empty-p))
7835 (org-N-empty-lines-before-current (if blank? 1 0)))
7836 (insert stars " \n")
7837 (forward-char -1))
7838 ;; At a headline...
7839 ((org-at-heading-p)
7840 (cond ((bolp)
7841 (when blank? (save-excursion (insert "\n")))
7842 (save-excursion (insert stars " \n"))
7843 (unless (and blank? (org-previous-line-empty-p))
7844 (org-N-empty-lines-before-current (if blank? 1 0)))
7845 (end-of-line))
7846 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7847 (org-match-line org-complex-heading-regexp)
7848 (org-pos-in-match-range (point) 4))
7849 ;; Grab the text that should moved to the new headline.
7850 ;; Preserve tags.
7851 (let ((split (delete-and-extract-region (point) (match-end 4))))
7852 (if (looking-at "[ \t]*$") (replace-match "")
7853 (org-set-tags nil t))
7854 (end-of-line)
7855 (when blank? (insert "\n"))
7856 (insert "\n" stars " ")
7857 (when (org-string-nw-p split) (insert split))
7858 (when (eobp) (save-excursion (insert "\n")))))
7860 (end-of-line)
7861 (when blank? (insert "\n"))
7862 (insert "\n" stars " ")
7863 (when (eobp) (save-excursion (insert "\n"))))))
7864 ;; On regular text, turn line into a headline or split, if
7865 ;; appropriate.
7866 ((bolp)
7867 (insert stars " ")
7868 (unless (and blank? (org-previous-line-empty-p))
7869 (org-N-empty-lines-before-current (if blank? 1 0))))
7871 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7872 (end-of-line))
7873 (insert "\n" stars " ")
7874 (unless (and blank? (org-previous-line-empty-p))
7875 (org-N-empty-lines-before-current (if blank? 1 0))))))
7876 (run-hooks 'org-insert-heading-hook))
7878 (defun org-N-empty-lines-before-current (n)
7879 "Make the number of empty lines before current exactly N.
7880 So this will delete or add empty lines."
7881 (let ((column (current-column))
7882 (empty-lines (make-string n ?\n)))
7883 (beginning-of-line)
7884 (let ((p (point)))
7885 (skip-chars-backward " \r\t\n")
7886 (unless (bolp) (forward-line))
7887 (delete-region (point) p))
7888 (insert empty-lines)
7889 (move-to-column column)))
7891 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7892 "Return the heading of the current entry, without the stars.
7893 When NO-TAGS is non-nil, don't include tags.
7894 When NO-TODO is non-nil, don't include TODO keywords.
7895 When NO-PRIORITY is non-nil, don't include priority cookie.
7896 When NO-COMMENT is non-nil, don't include COMMENT string."
7897 (save-excursion
7898 (org-back-to-heading t)
7899 (let ((case-fold-search nil))
7900 (looking-at org-complex-heading-regexp)
7901 (let ((todo (and (not no-todo) (match-string 2)))
7902 (priority (and (not no-priority) (match-string 3)))
7903 (headline (pcase (match-string 4)
7904 (`nil "")
7905 ((and (guard no-comment) h)
7906 (replace-regexp-in-string
7907 (eval-when-compile
7908 (format "\\`%s[ \t]+" org-comment-string))
7909 "" h))
7910 (h h)))
7911 (tags (and (not no-tags) (match-string 5))))
7912 (mapconcat #'identity
7913 (delq nil (list todo priority headline tags))
7914 " ")))))
7916 (defvar orgstruct-mode) ; defined below
7918 (defun org-heading-components ()
7919 "Return the components of the current heading.
7920 This is a list with the following elements:
7921 - the level as an integer
7922 - the reduced level, different if `org-odd-levels-only' is set.
7923 - the TODO keyword, or nil
7924 - the priority character, like ?A, or nil if no priority is given
7925 - the headline text itself, or the tags string if no headline text
7926 - the tags string, or nil."
7927 (save-excursion
7928 (org-back-to-heading t)
7929 (when (let (case-fold-search)
7930 (looking-at
7931 (if orgstruct-mode
7932 org-heading-regexp
7933 org-complex-heading-regexp)))
7934 (if orgstruct-mode
7935 (list (length (match-string 1))
7936 (org-reduced-level (length (match-string 1)))
7939 (match-string 2)
7940 nil)
7941 (list (length (match-string 1))
7942 (org-reduced-level (length (match-string 1)))
7943 (match-string-no-properties 2)
7944 (and (match-end 3) (aref (match-string 3) 2))
7945 (match-string-no-properties 4)
7946 (match-string-no-properties 5))))))
7948 (defun org-get-entry ()
7949 "Get the entry text, after heading, entire subtree."
7950 (save-excursion
7951 (org-back-to-heading t)
7952 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7954 (defun org-edit-headline (&optional heading)
7955 "Edit the current headline.
7956 Set it to HEADING when provided."
7957 (interactive)
7958 (org-with-wide-buffer
7959 (org-back-to-heading t)
7960 (let ((case-fold-search nil))
7961 (when (looking-at org-complex-heading-regexp)
7962 (let* ((old (match-string-no-properties 4))
7963 (new (save-match-data
7964 (org-trim (or heading (read-string "Edit: " old))))))
7965 (unless (equal old new)
7966 (if old (replace-match new t t nil 4)
7967 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7968 (insert " " new))
7969 (org-set-tags nil t)
7970 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7972 (defun org-insert-heading-after-current ()
7973 "Insert a new heading with same level as current, after current subtree."
7974 (interactive)
7975 (org-back-to-heading)
7976 (org-insert-heading)
7977 (org-move-subtree-down)
7978 (end-of-line 1))
7980 (defun org-insert-heading-respect-content (&optional invisible-ok)
7981 "Insert heading with `org-insert-heading-respect-content' set to t."
7982 (interactive)
7983 (org-insert-heading '(4) invisible-ok))
7985 (defun org-insert-todo-heading-respect-content (&optional force-state)
7986 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7987 (interactive)
7988 (org-insert-todo-heading force-state '(4)))
7990 (defun org-insert-todo-heading (arg &optional force-heading)
7991 "Insert a new heading with the same level and TODO state as current heading.
7993 If the heading has no TODO state, or if the state is DONE, use
7994 the first state (TODO by default). Also with one prefix arg,
7995 force first state. With two prefix args, force inserting at the
7996 end of the parent subtree.
7998 When called at a plain list item, insert a new item with an
7999 unchecked check box."
8000 (interactive "P")
8001 (when (or force-heading (not (org-insert-item 'checkbox)))
8002 (org-insert-heading (or (and (equal arg '(16)) '(16))
8003 force-heading))
8004 (save-excursion
8005 (org-back-to-heading)
8006 (outline-previous-heading)
8007 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
8008 (let* ((new-mark-x
8009 (if (or (equal arg '(4))
8010 (not (match-beginning 2))
8011 (member (match-string 2) org-done-keywords))
8012 (car org-todo-keywords-1)
8013 (match-string 2)))
8014 (new-mark
8016 (run-hook-with-args-until-success
8017 'org-todo-get-default-hook new-mark-x nil)
8018 new-mark-x)))
8019 (beginning-of-line 1)
8020 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8021 (if org-treat-insert-todo-heading-as-state-change
8022 (org-todo new-mark)
8023 (insert new-mark " "))))
8024 (when org-provide-todo-statistics
8025 (org-update-parent-todo-statistics))))
8027 (defun org-insert-subheading (arg)
8028 "Insert a new subheading and demote it.
8029 Works for outline headings and for plain lists alike."
8030 (interactive "P")
8031 (org-insert-heading arg)
8032 (cond
8033 ((org-at-heading-p) (org-do-demote))
8034 ((org-at-item-p) (org-indent-item))))
8036 (defun org-insert-todo-subheading (arg)
8037 "Insert a new subheading with TODO keyword or checkbox and demote it.
8038 Works for outline headings and for plain lists alike."
8039 (interactive "P")
8040 (org-insert-todo-heading arg)
8041 (cond
8042 ((org-at-heading-p) (org-do-demote))
8043 ((org-at-item-p) (org-indent-item))))
8045 ;;; Promotion and Demotion
8047 (defvar org-after-demote-entry-hook nil
8048 "Hook run after an entry has been demoted.
8049 The cursor will be at the beginning of the entry.
8050 When a subtree is being demoted, the hook will be called for each node.")
8052 (defvar org-after-promote-entry-hook nil
8053 "Hook run after an entry has been promoted.
8054 The cursor will be at the beginning of the entry.
8055 When a subtree is being promoted, the hook will be called for each node.")
8057 (defun org-promote-subtree ()
8058 "Promote the entire subtree.
8059 See also `org-promote'."
8060 (interactive)
8061 (save-excursion
8062 (org-with-limited-levels (org-map-tree 'org-promote)))
8063 (org-fix-position-after-promote))
8065 (defun org-demote-subtree ()
8066 "Demote the entire subtree.
8067 See `org-demote' and `org-promote'."
8068 (interactive)
8069 (save-excursion
8070 (org-with-limited-levels (org-map-tree 'org-demote)))
8071 (org-fix-position-after-promote))
8073 (defun org-do-promote ()
8074 "Promote the current heading higher up the tree.
8075 If the region is active in `transient-mark-mode', promote all
8076 headings in the region."
8077 (interactive)
8078 (save-excursion
8079 (if (org-region-active-p)
8080 (org-map-region 'org-promote (region-beginning) (region-end))
8081 (org-promote)))
8082 (org-fix-position-after-promote))
8084 (defun org-do-demote ()
8085 "Demote the current heading lower down the tree.
8086 If the region is active in `transient-mark-mode', demote all
8087 headings in the region."
8088 (interactive)
8089 (save-excursion
8090 (if (org-region-active-p)
8091 (org-map-region 'org-demote (region-beginning) (region-end))
8092 (org-demote)))
8093 (org-fix-position-after-promote))
8095 (defun org-fix-position-after-promote ()
8096 "Fix cursor position and indentation after demoting/promoting."
8097 (let ((pos (point)))
8098 (when (save-excursion
8099 (beginning-of-line)
8100 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8101 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8102 (cond ((eobp) (insert " "))
8103 ((eolp) (insert " "))
8104 ((equal (char-after) ?\s) (forward-char 1))))))
8106 (defun org-current-level ()
8107 "Return the level of the current entry, or nil if before the first headline.
8108 The level is the number of stars at the beginning of the
8109 headline. Use `org-reduced-level' to remove the effect of
8110 `org-odd-levels'. Unlike to `org-outline-level', this function
8111 ignores inlinetasks."
8112 (let ((level (org-with-limited-levels (org-outline-level))))
8113 (and (> level 0) level)))
8115 (defun org-get-previous-line-level ()
8116 "Return the outline depth of the last headline before the current line.
8117 Returns 0 for the first headline in the buffer, and nil if before the
8118 first headline."
8119 (and (org-current-level)
8120 (or (and (/= (line-beginning-position) (point-min))
8121 (save-excursion (beginning-of-line 0) (org-current-level)))
8122 0)))
8124 (defun org-reduced-level (l)
8125 "Compute the effective level of a heading.
8126 This takes into account the setting of `org-odd-levels-only'."
8127 (cond
8128 ((zerop l) 0)
8129 (org-odd-levels-only (1+ (floor (/ l 2))))
8130 (t l)))
8132 (defun org-level-increment ()
8133 "Return the number of stars that will be added or removed at a
8134 time to headlines when structure editing, based on the value of
8135 `org-odd-levels-only'."
8136 (if org-odd-levels-only 2 1))
8138 (defun org-get-valid-level (level &optional change)
8139 "Rectify a level change under the influence of `org-odd-levels-only'.
8140 LEVEL is a current level, CHANGE is by how much the level should
8141 be modified. Even if CHANGE is nil, LEVEL may be returned
8142 modified because even level numbers will become the next higher
8143 odd number. Returns values greater than 0."
8144 (if org-odd-levels-only
8145 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8146 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8147 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8148 (max 1 (+ level (or change 0)))))
8150 (defun org-promote ()
8151 "Promote the current heading higher up the tree."
8152 (org-with-wide-buffer
8153 (org-back-to-heading t)
8154 (let* ((after-change-functions (remq 'flyspell-after-change-function
8155 after-change-functions))
8156 (level (save-match-data (funcall outline-level)))
8157 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8158 (diff (abs (- level (length up-head) -1))))
8159 (cond
8160 ((and (= level 1) org-allow-promoting-top-level-subtree)
8161 (replace-match "# " nil t))
8162 ((= level 1)
8163 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8164 (t (replace-match up-head nil t)))
8165 (unless (= level 1)
8166 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8167 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8168 (run-hooks 'org-after-promote-entry-hook))))
8170 (defun org-demote ()
8171 "Demote the current heading lower down the tree."
8172 (org-with-wide-buffer
8173 (org-back-to-heading t)
8174 (let* ((after-change-functions (remq 'flyspell-after-change-function
8175 after-change-functions))
8176 (level (save-match-data (funcall outline-level)))
8177 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8178 (diff (abs (- level (length down-head) -1))))
8179 (replace-match down-head nil t)
8180 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8181 (when org-adapt-indentation (org-fixup-indentation diff))
8182 (run-hooks 'org-after-demote-entry-hook))))
8184 (defun org-cycle-level ()
8185 "Cycle the level of an empty headline through possible states.
8186 This goes first to child, then to parent, level, then up the hierarchy.
8187 After top level, it switches back to sibling level."
8188 (interactive)
8189 (let ((org-adapt-indentation nil))
8190 (when (org-point-at-end-of-empty-headline)
8191 (setq this-command 'org-cycle-level) ; Only needed for caching
8192 (let ((cur-level (org-current-level))
8193 (prev-level (org-get-previous-line-level)))
8194 (cond
8195 ;; If first headline in file, promote to top-level.
8196 ((= prev-level 0)
8197 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8198 do (org-do-promote)))
8199 ;; If same level as prev, demote one.
8200 ((= prev-level cur-level)
8201 (org-do-demote))
8202 ;; If parent is top-level, promote to top level if not already.
8203 ((= prev-level 1)
8204 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8205 do (org-do-promote)))
8206 ;; If top-level, return to prev-level.
8207 ((= cur-level 1)
8208 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8209 do (org-do-demote)))
8210 ;; If less than prev-level, promote one.
8211 ((< cur-level prev-level)
8212 (org-do-promote))
8213 ;; If deeper than prev-level, promote until higher than
8214 ;; prev-level.
8215 ((> cur-level prev-level)
8216 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8217 do (org-do-promote))))
8218 t))))
8220 (defun org-map-tree (fun)
8221 "Call FUN for every heading underneath the current one."
8222 (org-back-to-heading t)
8223 (let ((level (funcall outline-level)))
8224 (save-excursion
8225 (funcall fun)
8226 (while (and (progn
8227 (outline-next-heading)
8228 (> (funcall outline-level) level))
8229 (not (eobp)))
8230 (funcall fun)))))
8232 (defun org-map-region (fun beg end)
8233 "Call FUN for every heading between BEG and END."
8234 (let ((org-ignore-region t))
8235 (save-excursion
8236 (setq end (copy-marker end))
8237 (goto-char beg)
8238 (when (and (re-search-forward org-outline-regexp-bol nil t)
8239 (< (point) end))
8240 (funcall fun))
8241 (while (and (progn
8242 (outline-next-heading)
8243 (< (point) end))
8244 (not (eobp)))
8245 (funcall fun)))))
8247 (defun org-fixup-indentation (diff)
8248 "Change the indentation in the current entry by DIFF.
8250 DIFF is an integer. Indentation is done according to the
8251 following rules:
8253 - Planning information and property drawers are always indented
8254 according to the new level of the headline;
8256 - Footnote definitions and their contents are ignored;
8258 - Inlinetasks' boundaries are not shifted;
8260 - Empty lines are ignored;
8262 - Other lines' indentation are shifted by DIFF columns, unless
8263 it would introduce a structural change in the document, in
8264 which case no shifting is done at all.
8266 Assume point is at a heading or an inlinetask beginning."
8267 (org-with-wide-buffer
8268 (narrow-to-region (line-beginning-position)
8269 (save-excursion
8270 (if (org-with-limited-levels (org-at-heading-p))
8271 (org-with-limited-levels (outline-next-heading))
8272 (org-inlinetask-goto-end))
8273 (point)))
8274 (forward-line)
8275 ;; Indent properly planning info and property drawer.
8276 (when (looking-at-p org-planning-line-re)
8277 (org-indent-line)
8278 (forward-line))
8279 (when (looking-at org-property-drawer-re)
8280 (goto-char (match-end 0))
8281 (forward-line)
8282 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8283 (catch 'no-shift
8284 (when (zerop diff) (throw 'no-shift nil))
8285 ;; If DIFF is negative, first check if a shift is possible at all
8286 ;; (e.g., it doesn't break structure). This can only happen if
8287 ;; some contents are not properly indented.
8288 (let ((case-fold-search t))
8289 (when (< diff 0)
8290 (let ((diff (- diff))
8291 (forbidden-re (concat org-outline-regexp
8292 "\\|"
8293 (substring org-footnote-definition-re 1))))
8294 (save-excursion
8295 (while (not (eobp))
8296 (cond
8297 ((looking-at-p "[ \t]*$") (forward-line))
8298 ((and (looking-at-p org-footnote-definition-re)
8299 (let ((e (org-element-at-point)))
8300 (and (eq (org-element-type e) 'footnote-definition)
8301 (goto-char (org-element-property :end e))))))
8302 ((looking-at-p org-outline-regexp) (forward-line))
8303 ;; Give up if shifting would move before column 0 or
8304 ;; if it would introduce a headline or a footnote
8305 ;; definition.
8307 (skip-chars-forward " \t")
8308 (let ((ind (current-column)))
8309 (when (or (< ind diff)
8310 (and (= ind diff) (looking-at-p forbidden-re)))
8311 (throw 'no-shift nil)))
8312 ;; Ignore contents of example blocks and source
8313 ;; blocks if their indentation is meant to be
8314 ;; preserved. Jump to block's closing line.
8315 (beginning-of-line)
8316 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8317 (let ((e (org-element-at-point)))
8318 (and (memq (org-element-type e)
8319 '(example-block src-block))
8320 (or org-src-preserve-indentation
8321 (org-element-property :preserve-indent e))
8322 (goto-char (org-element-property :end e))
8323 (progn (skip-chars-backward " \r\t\n")
8324 (beginning-of-line)
8325 t))))
8326 (forward-line))))))))
8327 ;; Shift lines but footnote definitions, inlinetasks boundaries
8328 ;; by DIFF. Also skip contents of source or example blocks
8329 ;; when indentation is meant to be preserved.
8330 (while (not (eobp))
8331 (cond
8332 ((and (looking-at-p org-footnote-definition-re)
8333 (let ((e (org-element-at-point)))
8334 (and (eq (org-element-type e) 'footnote-definition)
8335 (goto-char (org-element-property :end e))))))
8336 ((looking-at-p org-outline-regexp) (forward-line))
8337 ((looking-at-p "[ \t]*$") (forward-line))
8339 (indent-line-to (+ (org-get-indentation) diff))
8340 (beginning-of-line)
8341 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8342 (let ((e (org-element-at-point)))
8343 (and (memq (org-element-type e)
8344 '(example-block src-block))
8345 (or org-src-preserve-indentation
8346 (org-element-property :preserve-indent e))
8347 (goto-char (org-element-property :end e))
8348 (progn (skip-chars-backward " \r\t\n")
8349 (beginning-of-line)
8350 t))))
8351 (forward-line)))))))))
8353 (defun org-convert-to-odd-levels ()
8354 "Convert an Org file with all levels allowed to one with odd levels.
8355 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8356 level 5 etc."
8357 (interactive)
8358 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8359 (let ((outline-level 'org-outline-level)
8360 (org-odd-levels-only nil) n)
8361 (save-excursion
8362 (goto-char (point-min))
8363 (while (re-search-forward "^\\*\\*+ " nil t)
8364 (setq n (- (length (match-string 0)) 2))
8365 (while (>= (setq n (1- n)) 0)
8366 (org-demote))
8367 (end-of-line 1))))))
8369 (defun org-convert-to-oddeven-levels ()
8370 "Convert an Org file with only odd levels to one with odd/even levels.
8371 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8372 file contains a section with an even level, conversion would
8373 destroy the structure of the file. An error is signaled in this
8374 case."
8375 (interactive)
8376 (goto-char (point-min))
8377 ;; First check if there are no even levels
8378 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8379 (org-show-set-visibility 'canonical)
8380 (error "Not all levels are odd in this file. Conversion not possible"))
8381 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8382 (let ((outline-regexp org-outline-regexp)
8383 (outline-level 'org-outline-level)
8384 (org-odd-levels-only nil) n)
8385 (save-excursion
8386 (goto-char (point-min))
8387 (while (re-search-forward "^\\*\\*+ " nil t)
8388 (setq n (/ (1- (length (match-string 0))) 2))
8389 (while (>= (setq n (1- n)) 0)
8390 (org-promote))
8391 (end-of-line 1))))))
8393 (defun org-tr-level (n)
8394 "Make N odd if required."
8395 (if org-odd-levels-only (1+ (/ n 2)) n))
8397 ;;; Vertical tree motion, cutting and pasting of subtrees
8399 (defun org-move-subtree-up (&optional arg)
8400 "Move the current subtree up past ARG headlines of the same level."
8401 (interactive "p")
8402 (org-move-subtree-down (- (prefix-numeric-value arg))))
8404 (defun org-move-subtree-down (&optional arg)
8405 "Move the current subtree down past ARG headlines of the same level."
8406 (interactive "p")
8407 (setq arg (prefix-numeric-value arg))
8408 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8409 'org-get-last-sibling))
8410 (ins-point (make-marker))
8411 (cnt (abs arg))
8412 (col (current-column))
8413 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8414 ;; Select the tree
8415 (org-back-to-heading)
8416 (setq beg0 (point))
8417 (save-excursion
8418 (setq ne-beg (org-back-over-empty-lines))
8419 (setq beg (point)))
8420 (save-match-data
8421 (save-excursion (outline-end-of-heading)
8422 (setq folded (outline-invisible-p)))
8423 (progn (org-end-of-subtree nil t)
8424 (unless (eobp) (backward-char))))
8425 (outline-next-heading)
8426 (setq ne-end (org-back-over-empty-lines))
8427 (setq end (point))
8428 (goto-char beg0)
8429 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8430 ;; include less whitespace
8431 (save-excursion
8432 (goto-char beg)
8433 (forward-line (- ne-beg ne-end))
8434 (setq beg (point))))
8435 ;; Find insertion point, with error handling
8436 (while (> cnt 0)
8437 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8438 (progn (goto-char beg0)
8439 (user-error "Cannot move past superior level or buffer limit")))
8440 (setq cnt (1- cnt)))
8441 (when (> arg 0)
8442 ;; Moving forward - still need to move over subtree
8443 (org-end-of-subtree t t)
8444 (save-excursion
8445 (org-back-over-empty-lines)
8446 (or (bolp) (newline))))
8447 (setq ne-ins (org-back-over-empty-lines))
8448 (move-marker ins-point (point))
8449 (setq txt (buffer-substring beg end))
8450 (org-save-markers-in-region beg end)
8451 (delete-region beg end)
8452 (org-remove-empty-overlays-at beg)
8453 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8454 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8455 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8456 (let ((bbb (point)))
8457 (insert-before-markers txt)
8458 (org-reinstall-markers-in-region bbb)
8459 (move-marker ins-point bbb))
8460 (or (bolp) (insert "\n"))
8461 (setq ins-end (point))
8462 (goto-char ins-point)
8463 (org-skip-whitespace)
8464 (when (and (< arg 0)
8465 (org-first-sibling-p)
8466 (> ne-ins ne-beg))
8467 ;; Move whitespace back to beginning
8468 (save-excursion
8469 (goto-char ins-end)
8470 (let ((kill-whole-line t))
8471 (kill-line (- ne-ins ne-beg)) (point)))
8472 (insert (make-string (- ne-ins ne-beg) ?\n)))
8473 (move-marker ins-point nil)
8474 (if folded
8475 (outline-hide-subtree)
8476 (org-show-entry)
8477 (org-show-children)
8478 (org-cycle-hide-drawers 'children))
8479 (org-clean-visibility-after-subtree-move)
8480 ;; move back to the initial column we were at
8481 (move-to-column col)))
8483 (defvar org-subtree-clip ""
8484 "Clipboard for cut and paste of subtrees.
8485 This is actually only a copy of the kill, because we use the normal kill
8486 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8488 (defvar org-subtree-clip-folded nil
8489 "Was the last copied subtree folded?
8490 This is used to fold the tree back after pasting.")
8492 (defun org-cut-subtree (&optional n)
8493 "Cut the current subtree into the clipboard.
8494 With prefix arg N, cut this many sequential subtrees.
8495 This is a short-hand for marking the subtree and then cutting it."
8496 (interactive "p")
8497 (org-copy-subtree n 'cut))
8499 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8500 "Copy the current subtree it in the clipboard.
8501 With prefix arg N, copy this many sequential subtrees.
8502 This is a short-hand for marking the subtree and then copying it.
8503 If CUT is non-nil, actually cut the subtree.
8504 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8505 of some markers in the region, even if CUT is non-nil. This is
8506 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8507 (interactive "p")
8508 (let (beg end folded (beg0 (point)))
8509 (if (called-interactively-p 'any)
8510 (org-back-to-heading nil) ; take what looks like a subtree
8511 (org-back-to-heading t)) ; take what is really there
8512 (setq beg (point))
8513 (skip-chars-forward " \t\r\n")
8514 (save-match-data
8515 (if nosubtrees
8516 (outline-next-heading)
8517 (save-excursion (outline-end-of-heading)
8518 (setq folded (outline-invisible-p)))
8519 (ignore-errors (org-forward-heading-same-level (1- n) t))
8520 (org-end-of-subtree t t)))
8521 ;; Include the end of an inlinetask
8522 (when (and (featurep 'org-inlinetask)
8523 (looking-at-p (concat (org-inlinetask-outline-regexp)
8524 "END[ \t]*$")))
8525 (end-of-line))
8526 (setq end (point))
8527 (goto-char beg0)
8528 (when (> end beg)
8529 (setq org-subtree-clip-folded folded)
8530 (when (or cut force-store-markers)
8531 (org-save-markers-in-region beg end))
8532 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8533 (setq org-subtree-clip (current-kill 0))
8534 (message "%s: Subtree(s) with %d characters"
8535 (if cut "Cut" "Copied")
8536 (length org-subtree-clip)))))
8538 (defun org-paste-subtree (&optional level tree for-yank remove)
8539 "Paste the clipboard as a subtree, with modification of headline level.
8540 The entire subtree is promoted or demoted in order to match a new headline
8541 level.
8543 If the cursor is at the beginning of a headline, the same level as
8544 that headline is used to paste the tree.
8546 If not, the new level is derived from the *visible* headings
8547 before and after the insertion point, and taken to be the inferior headline
8548 level of the two. So if the previous visible heading is level 3 and the
8549 next is level 4 (or vice versa), level 4 will be used for insertion.
8550 This makes sure that the subtree remains an independent subtree and does
8551 not swallow low level entries.
8553 You can also force a different level, either by using a numeric prefix
8554 argument, or by inserting the heading marker by hand. For example, if the
8555 cursor is after \"*****\", then the tree will be shifted to level 5.
8557 If optional TREE is given, use this text instead of the kill ring.
8559 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8560 move back over whitespace before inserting, and move point to the end of
8561 the inserted text when done.
8563 When REMOVE is non-nil, remove the subtree from the clipboard."
8564 (interactive "P")
8565 (setq tree (or tree (and kill-ring (current-kill 0))))
8566 (unless (org-kill-is-subtree-p tree)
8567 (user-error "%s"
8568 (substitute-command-keys
8569 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8570 (org-with-limited-levels
8571 (let* ((visp (not (outline-invisible-p)))
8572 (txt tree)
8573 (^re_ "\\(\\*+\\)[ \t]*")
8574 (old-level (if (string-match org-outline-regexp-bol txt)
8575 (- (match-end 0) (match-beginning 0) 1)
8576 -1))
8577 (force-level (cond (level (prefix-numeric-value level))
8578 ((and (looking-at "[ \t]*$")
8579 (string-match
8580 "^\\*+$" (buffer-substring
8581 (point-at-bol) (point))))
8582 (- (match-end 0) (match-beginning 0)))
8583 ((and (bolp)
8584 (looking-at org-outline-regexp))
8585 (- (match-end 0) (point) 1))))
8586 (previous-level (save-excursion
8587 (condition-case nil
8588 (progn
8589 (outline-previous-visible-heading 1)
8590 (if (looking-at ^re_)
8591 (- (match-end 0) (match-beginning 0) 1)
8593 (error 1))))
8594 (next-level (save-excursion
8595 (condition-case nil
8596 (progn
8597 (or (looking-at org-outline-regexp)
8598 (outline-next-visible-heading 1))
8599 (if (looking-at ^re_)
8600 (- (match-end 0) (match-beginning 0) 1)
8602 (error 1))))
8603 (new-level (or force-level (max previous-level next-level)))
8604 (shift (if (or (= old-level -1)
8605 (= new-level -1)
8606 (= old-level new-level))
8608 (- new-level old-level)))
8609 (delta (if (> shift 0) -1 1))
8610 (func (if (> shift 0) 'org-demote 'org-promote))
8611 (org-odd-levels-only nil)
8612 beg end newend)
8613 ;; Remove the forced level indicator
8614 (when force-level
8615 (delete-region (point-at-bol) (point)))
8616 ;; Paste
8617 (beginning-of-line (if (bolp) 1 2))
8618 (setq beg (point))
8619 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8620 (insert-before-markers txt)
8621 (unless (string-suffix-p "\n" txt) (insert "\n"))
8622 (setq newend (point))
8623 (org-reinstall-markers-in-region beg)
8624 (setq end (point))
8625 (goto-char beg)
8626 (skip-chars-forward " \t\n\r")
8627 (setq beg (point))
8628 (when (and (outline-invisible-p) visp)
8629 (save-excursion (outline-show-heading)))
8630 ;; Shift if necessary
8631 (unless (= shift 0)
8632 (save-restriction
8633 (narrow-to-region beg end)
8634 (while (not (= shift 0))
8635 (org-map-region func (point-min) (point-max))
8636 (setq shift (+ delta shift)))
8637 (goto-char (point-min))
8638 (setq newend (point-max))))
8639 (when (or (called-interactively-p 'interactive) for-yank)
8640 (message "Clipboard pasted as level %d subtree" new-level))
8641 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8642 kill-ring
8643 (eq org-subtree-clip (current-kill 0))
8644 org-subtree-clip-folded)
8645 ;; The tree was folded before it was killed/copied
8646 (outline-hide-subtree))
8647 (and for-yank (goto-char newend))
8648 (and remove (setq kill-ring (cdr kill-ring))))))
8650 (defun org-kill-is-subtree-p (&optional txt)
8651 "Check if the current kill is an outline subtree, or a set of trees.
8652 Returns nil if kill does not start with a headline, or if the first
8653 headline level is not the largest headline level in the tree.
8654 So this will actually accept several entries of equal levels as well,
8655 which is OK for `org-paste-subtree'.
8656 If optional TXT is given, check this string instead of the current kill."
8657 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8658 (re (org-get-limited-outline-regexp))
8659 (^re (concat "^" re))
8660 (start-level (and kill
8661 (string-match
8662 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8663 kill)
8664 (- (match-end 2) (match-beginning 2) 1)))
8665 (start (1+ (or (match-beginning 2) -1))))
8666 (if (not start-level)
8667 (progn
8668 nil) ;; does not even start with a heading
8669 (catch 'exit
8670 (while (setq start (string-match ^re kill (1+ start)))
8671 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8672 (throw 'exit nil)))
8673 t))))
8675 (defvar org-markers-to-move nil
8676 "Markers that should be moved with a cut-and-paste operation.
8677 Those markers are stored together with their positions relative to
8678 the start of the region.")
8680 (defun org-save-markers-in-region (beg end)
8681 "Check markers in region.
8682 If these markers are between BEG and END, record their position relative
8683 to BEG, so that after moving the block of text, we can put the markers back
8684 into place.
8685 This function gets called just before an entry or tree gets cut from the
8686 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8687 called immediately, to move the markers with the entries."
8688 (setq org-markers-to-move nil)
8689 (when (featurep 'org-clock)
8690 (org-clock-save-markers-for-cut-and-paste beg end))
8691 (when (featurep 'org-agenda)
8692 (org-agenda-save-markers-for-cut-and-paste beg end)))
8694 (defun org-check-and-save-marker (marker beg end)
8695 "Check if MARKER is between BEG and END.
8696 If yes, remember the marker and the distance to BEG."
8697 (when (and (marker-buffer marker)
8698 (equal (marker-buffer marker) (current-buffer))
8699 (>= marker beg) (< marker end))
8700 (push (cons marker (- marker beg)) org-markers-to-move)))
8702 (defun org-reinstall-markers-in-region (beg)
8703 "Move all remembered markers to their position relative to BEG."
8704 (dolist (x org-markers-to-move)
8705 (move-marker (car x) (+ beg (cdr x))))
8706 (setq org-markers-to-move nil))
8708 (defun org-narrow-to-subtree ()
8709 "Narrow buffer to the current subtree."
8710 (interactive)
8711 (save-excursion
8712 (save-match-data
8713 (org-with-limited-levels
8714 (narrow-to-region
8715 (progn (org-back-to-heading t) (point))
8716 (progn (org-end-of-subtree t t)
8717 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8718 (point)))))))
8720 (defun org-narrow-to-block ()
8721 "Narrow buffer to the current block."
8722 (interactive)
8723 (let* ((case-fold-search t)
8724 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8725 "^[ \t]*#\\+end_.*")))
8726 (if blockp
8727 (narrow-to-region (car blockp) (cdr blockp))
8728 (user-error "Not in a block"))))
8730 (defun org-clone-subtree-with-time-shift (n &optional shift)
8731 "Clone the task (subtree) at point N times.
8732 The clones will be inserted as siblings.
8734 In interactive use, the user will be prompted for the number of
8735 clones to be produced. If the entry has a timestamp, the user
8736 will also be prompted for a time shift, which may be a repeater
8737 as used in time stamps, for example `+3d'. To disable this,
8738 you can call the function with a universal prefix argument.
8740 When a valid repeater is given and the entry contains any time
8741 stamps, the clones will become a sequence in time, with time
8742 stamps in the subtree shifted for each clone produced. If SHIFT
8743 is nil or the empty string, time stamps will be left alone. The
8744 ID property of the original subtree is removed.
8746 In each clone, all the CLOCK entries will be removed. This
8747 prevents Org from considering that the clocked times overlap.
8749 If the original subtree did contain time stamps with a repeater,
8750 the following will happen:
8751 - the repeater will be removed in each clone
8752 - an additional clone will be produced, with the current, unshifted
8753 date(s) in the entry.
8754 - the original entry will be placed *after* all the clones, with
8755 repeater intact.
8756 - the start days in the repeater in the original entry will be shifted
8757 to past the last clone.
8758 In this way you can spell out a number of instances of a repeating task,
8759 and still retain the repeater to cover future instances of the task.
8761 As described above, N+1 clones are produced when the original
8762 subtree has a repeater. Setting N to 0, then, can be used to
8763 remove the repeater from a subtree and create a shifted clone
8764 with the original repeater."
8765 (interactive "nNumber of clones to produce: ")
8766 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8767 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8768 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8769 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8770 (shift
8771 (or shift
8772 (if (and (not (equal current-prefix-arg '(4)))
8773 (save-excursion
8774 (goto-char beg)
8775 (re-search-forward org-ts-regexp-both end-of-tree t)))
8776 (read-from-minibuffer
8777 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8778 ""))) ;No time shift
8779 (doshift
8780 (and (org-string-nw-p shift)
8781 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8782 shift)
8783 (user-error "Invalid shift specification %s" shift)))))
8784 (goto-char end-of-tree)
8785 (unless (bolp) (insert "\n"))
8786 (let* ((end (point))
8787 (template (buffer-substring beg end))
8788 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8789 (shift-what (pcase (and doshift (match-string 2 shift))
8790 (`nil nil)
8791 ("d" 'day)
8792 ("w" (setq shift-n (* 7 shift-n)) 'day)
8793 ("m" 'month)
8794 ("y" 'year)
8795 (_ (error "Unsupported time unit"))))
8796 (nmin 1)
8797 (nmax n)
8798 (n-no-remove -1)
8799 (idprop (org-entry-get nil "ID")))
8800 (when (and doshift
8801 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8802 template))
8803 (delete-region beg end)
8804 (setq end beg)
8805 (setq nmin 0)
8806 (setq nmax (1+ nmax))
8807 (setq n-no-remove nmax))
8808 (goto-char end)
8809 (cl-loop for n from nmin to nmax do
8810 (insert
8811 ;; Prepare clone.
8812 (with-temp-buffer
8813 (insert template)
8814 (org-mode)
8815 (goto-char (point-min))
8816 (org-show-subtree)
8817 (and idprop (if org-clone-delete-id
8818 (org-entry-delete nil "ID")
8819 (org-id-get-create t)))
8820 (unless (= n 0)
8821 (while (re-search-forward org-clock-line-re nil t)
8822 (delete-region (line-beginning-position)
8823 (line-beginning-position 2)))
8824 (goto-char (point-min))
8825 (while (re-search-forward org-drawer-regexp nil t)
8826 (org-remove-empty-drawer-at (point))))
8827 (goto-char (point-min))
8828 (when doshift
8829 (while (re-search-forward org-ts-regexp-both nil t)
8830 (org-timestamp-change (* n shift-n) shift-what))
8831 (unless (= n n-no-remove)
8832 (goto-char (point-min))
8833 (while (re-search-forward org-ts-regexp nil t)
8834 (save-excursion
8835 (goto-char (match-beginning 0))
8836 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8837 (delete-region (match-beginning 1) (match-end 1)))))))
8838 (buffer-string)))))
8839 (goto-char beg)))
8841 ;;; Outline Sorting
8843 (defun org-sort (with-case)
8844 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8845 Optional argument WITH-CASE means sort case-sensitively."
8846 (interactive "P")
8847 (cond
8848 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8849 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8851 (org-call-with-arg 'org-sort-entries with-case))))
8853 (defun org-sort-remove-invisible (s)
8854 "Remove invisible part of links and emphasis markers from string S."
8855 (remove-text-properties 0 (length s) org-rm-props s)
8856 (replace-regexp-in-string
8857 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8858 (replace-regexp-in-string
8859 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8860 (org-link-display-format s)
8861 t t) t t))
8863 (defvar org-priority-regexp) ; defined later in the file
8865 (defvar org-after-sorting-entries-or-items-hook nil
8866 "Hook that is run after a bunch of entries or items have been sorted.
8867 When children are sorted, the cursor is in the parent line when this
8868 hook gets called. When a region or a plain list is sorted, the cursor
8869 will be in the first entry of the sorted region/list.")
8871 (defun org-sort-entries
8872 (&optional with-case sorting-type getkey-func compare-func property)
8873 "Sort entries on a certain level of an outline tree.
8874 If there is an active region, the entries in the region are sorted.
8875 Else, if the cursor is before the first entry, sort the top-level items.
8876 Else, the children of the entry at point are sorted.
8878 Sorting can be alphabetically, numerically, by date/time as given by
8879 a time stamp, by a property, by priority order, or by a custom function.
8881 The command prompts for the sorting type unless it has been given to the
8882 function through the SORTING-TYPE argument, which needs to be a character,
8883 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8884 the precise meaning of each character:
8886 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8887 c By creation time, which is assumed to be the first inactive time stamp
8888 at the beginning of a line.
8889 d By deadline date/time.
8890 k By clocking time.
8891 n Numerically, by converting the beginning of the entry/item to a number.
8892 o By order of TODO keywords.
8893 p By priority according to the cookie.
8894 r By the value of a property.
8895 s By scheduled date/time.
8896 t By date/time, either the first active time stamp in the entry, or, if
8897 none exist, by the first inactive one.
8899 Capital letters will reverse the sort order.
8901 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8902 called with point at the beginning of the record. It must return either
8903 a string or a number that should serve as the sorting key for that record.
8905 Comparing entries ignores case by default. However, with an optional argument
8906 WITH-CASE, the sorting considers case as well.
8908 Sorting is done against the visible part of the headlines, it ignores hidden
8909 links.
8911 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8912 (interactive "P")
8913 (let ((case-func (if with-case 'identity 'downcase))
8914 (cmstr
8915 ;; The clock marker is lost when using `sort-subr', let's
8916 ;; store the clocking string.
8917 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8918 (save-excursion
8919 (goto-char org-clock-marker)
8920 (buffer-substring-no-properties (line-beginning-position)
8921 (point)))))
8922 start beg end stars re re2
8923 txt what tmp)
8924 ;; Find beginning and end of region to sort
8925 (cond
8926 ((org-region-active-p)
8927 ;; we will sort the region
8928 (setq end (region-end)
8929 what "region")
8930 (goto-char (region-beginning))
8931 (unless (org-at-heading-p) (outline-next-heading))
8932 (setq start (point)))
8933 ((or (org-at-heading-p)
8934 (ignore-errors (progn (org-back-to-heading) t)))
8935 ;; we will sort the children of the current headline
8936 (org-back-to-heading)
8937 (setq start (point)
8938 end (progn (org-end-of-subtree t t)
8939 (or (bolp) (insert "\n"))
8940 (when (>= (org-back-over-empty-lines) 1)
8941 (forward-line 1))
8942 (point))
8943 what "children")
8944 (goto-char start)
8945 (outline-show-subtree)
8946 (outline-next-heading))
8948 ;; we will sort the top-level entries in this file
8949 (goto-char (point-min))
8950 (or (org-at-heading-p) (outline-next-heading))
8951 (setq start (point))
8952 (goto-char (point-max))
8953 (beginning-of-line 1)
8954 (when (looking-at ".*?\\S-")
8955 ;; File ends in a non-white line
8956 (end-of-line 1)
8957 (insert "\n"))
8958 (setq end (point-max))
8959 (setq what "top-level")
8960 (goto-char start)
8961 (outline-show-all)))
8963 (setq beg (point))
8964 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8966 (looking-at "\\(\\*+\\)")
8967 (setq stars (match-string 1)
8968 re (concat "^" (regexp-quote stars) " +")
8969 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8970 txt (buffer-substring beg end))
8971 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8972 (when (and (not (equal stars "*")) (string-match re2 txt))
8973 (user-error "Region to sort contains a level above the first entry"))
8975 (unless sorting-type
8976 (message
8977 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8978 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8979 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8980 what)
8981 (setq sorting-type (read-char-exclusive))
8983 (unless getkey-func
8984 (and (= (downcase sorting-type) ?f)
8985 (setq getkey-func
8986 (completing-read "Sort using function: "
8987 obarray 'fboundp t nil nil))
8988 (setq getkey-func (intern getkey-func))))
8990 (and (= (downcase sorting-type) ?r)
8991 (not property)
8992 (setq property
8993 (completing-read "Property: "
8994 (mapcar #'list (org-buffer-property-keys t))
8995 nil t))))
8997 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8998 (message "Sorting entries...")
9000 (save-restriction
9001 (narrow-to-region start end)
9002 (let ((dcst (downcase sorting-type))
9003 (case-fold-search nil)
9004 (now (current-time)))
9005 (sort-subr
9006 (/= dcst sorting-type)
9007 ;; This function moves to the beginning character of the "record" to
9008 ;; be sorted.
9009 (lambda nil
9010 (if (re-search-forward re nil t)
9011 (goto-char (match-beginning 0))
9012 (goto-char (point-max))))
9013 ;; This function moves to the last character of the "record" being
9014 ;; sorted.
9015 (lambda nil
9016 (save-match-data
9017 (condition-case nil
9018 (outline-forward-same-level 1)
9019 (error
9020 (goto-char (point-max))))))
9021 ;; This function returns the value that gets sorted against.
9022 (lambda nil
9023 (cond
9024 ((= dcst ?n)
9025 (if (looking-at org-complex-heading-regexp)
9026 (string-to-number (org-sort-remove-invisible (match-string 4)))
9027 nil))
9028 ((= dcst ?a)
9029 (if (looking-at org-complex-heading-regexp)
9030 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9031 nil))
9032 ((= dcst ?k)
9033 (or (get-text-property (point) :org-clock-minutes) 0))
9034 ((= dcst ?t)
9035 (let ((end (save-excursion (outline-next-heading) (point))))
9036 (if (or (re-search-forward org-ts-regexp end t)
9037 (re-search-forward org-ts-regexp-both end t))
9038 (org-time-string-to-seconds (match-string 0))
9039 (float-time now))))
9040 ((= dcst ?c)
9041 (let ((end (save-excursion (outline-next-heading) (point))))
9042 (if (re-search-forward
9043 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9044 end t)
9045 (org-time-string-to-seconds (match-string 0))
9046 (float-time now))))
9047 ((= dcst ?s)
9048 (let ((end (save-excursion (outline-next-heading) (point))))
9049 (if (re-search-forward org-scheduled-time-regexp end t)
9050 (org-time-string-to-seconds (match-string 1))
9051 (float-time now))))
9052 ((= dcst ?d)
9053 (let ((end (save-excursion (outline-next-heading) (point))))
9054 (if (re-search-forward org-deadline-time-regexp end t)
9055 (org-time-string-to-seconds (match-string 1))
9056 (float-time now))))
9057 ((= dcst ?p)
9058 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9059 (string-to-char (match-string 2))
9060 org-default-priority))
9061 ((= dcst ?r)
9062 (or (org-entry-get nil property) ""))
9063 ((= dcst ?o)
9064 (when (looking-at org-complex-heading-regexp)
9065 (let* ((m (match-string 2))
9066 (s (if (member m org-done-keywords) '- '+)))
9067 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9068 ((= dcst ?f)
9069 (if getkey-func
9070 (progn
9071 (setq tmp (funcall getkey-func))
9072 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9073 tmp)
9074 (error "Invalid key function `%s'" getkey-func)))
9075 (t (error "Invalid sorting type `%c'" sorting-type))))
9077 (cond
9078 ((= dcst ?a) 'string<)
9079 ((= dcst ?f) compare-func)
9080 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9081 (run-hooks 'org-after-sorting-entries-or-items-hook)
9082 ;; Reset the clock marker if needed
9083 (when cmstr
9084 (save-excursion
9085 (goto-char start)
9086 (search-forward cmstr nil t)
9087 (move-marker org-clock-marker (point))))
9088 (message "Sorting entries...done")))
9090 ;;; The orgstruct minor mode
9092 ;; Define a minor mode which can be used in other modes in order to
9093 ;; integrate the Org mode structure editing commands.
9095 ;; This is really a hack, because the Org mode structure commands use
9096 ;; keys which normally belong to the major mode. Here is how it
9097 ;; works: The minor mode defines all the keys necessary to operate the
9098 ;; structure commands, but wraps the commands into a function which
9099 ;; tests if the cursor is currently at a headline or a plain list
9100 ;; item. If that is the case, the structure command is used,
9101 ;; temporarily setting many Org mode variables like regular
9102 ;; expressions for filling etc. However, when any of those keys is
9103 ;; used at a different location, function uses `key-binding' to look
9104 ;; up if the key has an associated command in another currently active
9105 ;; keymap (minor modes, major mode, global), and executes that
9106 ;; command. There might be problems if any of the keys is otherwise
9107 ;; used as a prefix key.
9109 (defcustom orgstruct-heading-prefix-regexp ""
9110 "Regexp that matches the custom prefix of Org headlines in
9111 orgstruct(++)-mode."
9112 :group 'org
9113 :version "24.4"
9114 :package-version '(Org . "8.3")
9115 :type 'regexp)
9116 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9118 (defcustom orgstruct-setup-hook nil
9119 "Hook run after orgstruct-mode-map is filled."
9120 :group 'org
9121 :version "24.4"
9122 :package-version '(Org . "8.0")
9123 :type 'hook)
9125 (defvar orgstruct-initialized nil)
9127 (defvar org-local-vars nil
9128 "List of local variables, for use by `orgstruct-mode'.")
9130 ;;;###autoload
9131 (define-minor-mode orgstruct-mode
9132 "Toggle the minor mode `orgstruct-mode'.
9133 This mode is for using Org mode structure commands in other
9134 modes. The following keys behave as if Org mode were active, if
9135 the cursor is on a headline, or on a plain list item (both as
9136 defined by Org mode)."
9137 nil " OrgStruct" (make-sparse-keymap)
9138 (funcall (if orgstruct-mode
9139 'add-to-invisibility-spec
9140 'remove-from-invisibility-spec)
9141 '(outline . t))
9142 (when orgstruct-mode
9143 (org-load-modules-maybe)
9144 (unless orgstruct-initialized
9145 (orgstruct-setup)
9146 (setq orgstruct-initialized t))))
9148 ;;;###autoload
9149 (defun turn-on-orgstruct ()
9150 "Unconditionally turn on `orgstruct-mode'."
9151 (orgstruct-mode 1))
9153 (defvar-local orgstruct-is-++ nil
9154 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9155 (defvar-local org-fb-vars nil)
9156 (defun orgstruct++-mode (&optional arg)
9157 "Toggle `orgstruct-mode', the enhanced version of it.
9158 In addition to setting orgstruct-mode, this also exports all
9159 indentation and autofilling variables from Org mode into the
9160 buffer. It will also recognize item context in multiline items."
9161 (interactive "P")
9162 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9163 (if (< arg 1)
9164 (progn (orgstruct-mode -1)
9165 (dolist (v org-fb-vars)
9166 (set (make-local-variable (car v))
9167 (if (eq (car-safe (cadr v)) 'quote)
9168 (cl-cadadr v)
9169 (nth 1 v)))))
9170 (orgstruct-mode 1)
9171 (setq org-fb-vars nil)
9172 (unless org-local-vars
9173 (setq org-local-vars (org-get-local-variables)))
9174 (let (var val)
9175 (dolist (x org-local-vars)
9176 (when (string-match
9177 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9178 \\|fill-prefix\\|indent-\\)"
9179 (symbol-name (car x)))
9180 (setq var (car x) val (nth 1 x))
9181 (push (list var `(quote ,(eval var))) org-fb-vars)
9182 (set (make-local-variable var)
9183 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9184 (setq-local orgstruct-is-++ t))))
9186 ;;;###autoload
9187 (defun turn-on-orgstruct++ ()
9188 "Unconditionally turn on `orgstruct++-mode'."
9189 (orgstruct++-mode 1))
9191 (defun orgstruct-error ()
9192 "Error when there is no default binding for a structure key."
9193 (interactive)
9194 (funcall (if (fboundp 'user-error)
9195 'user-error
9196 'error)
9197 "This key has no function outside structure elements"))
9199 (defun orgstruct-setup ()
9200 "Setup orgstruct keymap."
9201 (dolist (cell '((org-demote . t)
9202 (org-metaleft . t)
9203 (org-metaright . t)
9204 (org-promote . t)
9205 (org-shiftmetaleft . t)
9206 (org-shiftmetaright . t)
9207 org-backward-element
9208 org-backward-heading-same-level
9209 org-ctrl-c-ret
9210 org-ctrl-c-minus
9211 org-ctrl-c-star
9212 org-cycle
9213 org-force-cycle-archived
9214 org-forward-heading-same-level
9215 org-insert-heading
9216 org-insert-heading-respect-content
9217 org-kill-note-or-show-branches
9218 org-mark-subtree
9219 org-meta-return
9220 org-metadown
9221 org-metaup
9222 org-narrow-to-subtree
9223 org-promote-subtree
9224 org-reveal
9225 org-shiftdown
9226 org-shiftleft
9227 org-shiftmetadown
9228 org-shiftmetaup
9229 org-shiftright
9230 org-shifttab
9231 org-shifttab
9232 org-shiftup
9233 org-show-children
9234 org-show-subtree
9235 org-sort
9236 org-up-element
9237 outline-demote
9238 outline-next-visible-heading
9239 outline-previous-visible-heading
9240 outline-promote
9241 outline-up-heading))
9242 (let ((f (or (car-safe cell) cell))
9243 (disable-when-heading-prefix (cdr-safe cell)))
9244 (when (fboundp f)
9245 (let ((new-bindings))
9246 (dolist (binding (nconc (where-is-internal f org-mode-map)
9247 (where-is-internal f outline-mode-map)))
9248 (push binding new-bindings)
9249 ;; TODO use local-function-key-map
9250 (dolist (rep '(("<tab>" . "TAB")
9251 ("<return>" . "RET")
9252 ("<escape>" . "ESC")
9253 ("<delete>" . "DEL")))
9254 (setq binding (read-kbd-macro
9255 (let ((case-fold-search))
9256 (replace-regexp-in-string
9257 (regexp-quote (cdr rep))
9258 (car rep)
9259 (key-description binding)))))
9260 (cl-pushnew binding new-bindings :test 'equal)))
9261 (dolist (binding new-bindings)
9262 (let ((key (lookup-key orgstruct-mode-map binding)))
9263 (when (or (not key) (numberp key))
9264 (ignore-errors
9265 (org-defkey orgstruct-mode-map
9266 binding
9267 (orgstruct-make-binding
9268 f binding disable-when-heading-prefix))))))))))
9269 (run-hooks 'orgstruct-setup-hook))
9271 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9272 "Create a function for binding in the structure minor mode.
9273 FUN is the command to call inside a table. KEY is the key that
9274 should be checked in for a command to execute outside of tables.
9275 Non-nil `disable-when-heading-prefix' means to disable the command
9276 if `orgstruct-heading-prefix-regexp' is not empty."
9277 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9278 (let ((nname name)
9279 (i 0))
9280 (while (fboundp (intern nname))
9281 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9282 (setq name (intern nname)))
9283 (eval
9284 (let ((bindings '((org-heading-regexp
9285 (concat "^"
9286 orgstruct-heading-prefix-regexp
9287 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9288 (org-outline-regexp
9289 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9290 (org-outline-regexp-bol
9291 (concat "^" org-outline-regexp))
9292 (outline-regexp org-outline-regexp)
9293 (outline-heading-end-regexp "\n")
9294 (outline-level 'org-outline-level)
9295 (outline-heading-alist))))
9296 `(defun ,name (arg)
9297 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9298 "Outside of structure, run the binding of `"
9299 (key-description key) "'."
9300 (when disable-when-heading-prefix
9301 (concat
9302 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9303 "back to the default binding due to limitations of Org's implementation of\n"
9304 "`" (symbol-name fun) "'.")))
9305 (interactive "p")
9306 (let* ((disable
9307 ,(and disable-when-heading-prefix
9308 '(not (string= orgstruct-heading-prefix-regexp ""))))
9309 (fallback
9310 (or disable
9311 (not
9312 (let* ,bindings
9313 (org-context-p 'headline 'item
9314 ,(when (memq fun
9315 '(org-insert-heading
9316 org-insert-heading-respect-content
9317 org-meta-return))
9318 '(when orgstruct-is-++
9319 'item-body))))))))
9320 (if fallback
9321 (let* ((orgstruct-mode)
9322 (binding
9323 (let ((key ,key))
9324 (catch 'exit
9325 (dolist
9326 (rep
9327 '(nil
9328 ("<\\([^>]*\\)tab>" . "\\1TAB")
9329 ("<\\([^>]*\\)return>" . "\\1RET")
9330 ("<\\([^>]*\\)escape>" . "\\1ESC")
9331 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9332 nil)
9333 (when rep
9334 (setq key (read-kbd-macro
9335 (let ((case-fold-search))
9336 (replace-regexp-in-string
9337 (car rep)
9338 (cdr rep)
9339 (key-description key))))))
9340 (when (key-binding key)
9341 (throw 'exit (key-binding key))))))))
9342 (if (keymapp binding)
9343 (org-set-transient-map binding)
9344 (let ((func (or binding
9345 (unless disable
9346 'orgstruct-error))))
9347 (when func
9348 (call-interactively func)))))
9349 (org-run-like-in-org-mode
9350 (lambda ()
9351 (interactive)
9352 (let* ,bindings
9353 (call-interactively ',fun)))))))))
9354 name))
9356 (defun org-contextualize-keys (alist contexts)
9357 "Return valid elements in ALIST depending on CONTEXTS.
9359 `org-agenda-custom-commands' or `org-capture-templates' are the
9360 values used for ALIST, and `org-agenda-custom-commands-contexts'
9361 or `org-capture-templates-contexts' are the associated contexts
9362 definitions."
9363 (let ((contexts
9364 ;; normalize contexts
9365 (mapcar
9366 (lambda(c) (cond ((listp (cadr c))
9367 (list (car c) (car c) (nth 1 c)))
9368 ((string= "" (cadr c))
9369 (list (car c) (car c) (nth 2 c)))
9370 (t c)))
9371 contexts))
9372 (a alist) r s)
9373 ;; loop over all commands or templates
9374 (dolist (c a)
9375 (let (vrules repl)
9376 (cond
9377 ((not (assoc (car c) contexts))
9378 (push c r))
9379 ((and (assoc (car c) contexts)
9380 (setq vrules (org-contextualize-validate-key
9381 (car c) contexts)))
9382 (mapc (lambda (vr)
9383 (unless (equal (car vr) (cadr vr))
9384 (setq repl vr)))
9385 vrules)
9386 (if (not repl) (push c r)
9387 (push (cadr repl) s)
9388 (push
9389 (cons (car c)
9390 (cdr (or (assoc (cadr repl) alist)
9391 (error "Undefined key `%s' as contextual replacement for `%s'"
9392 (cadr repl) (car c)))))
9393 r))))))
9394 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9395 (delq
9397 (delete-dups
9398 (mapcar (lambda (x)
9399 (let ((tpl (car x)))
9400 (unless (delq
9402 (mapcar (lambda (y)
9403 (equal y tpl))
9405 x)))
9406 (reverse r))))))
9408 (defun org-contextualize-validate-key (key contexts)
9409 "Check CONTEXTS for agenda or capture KEY."
9410 (let (res)
9411 (dolist (r contexts)
9412 (dolist (rr (car (last r)))
9413 (when
9414 (and (equal key (car r))
9415 (if (functionp rr) (funcall rr)
9416 (or (and (eq (car rr) 'in-file)
9417 (buffer-file-name)
9418 (string-match (cdr rr) (buffer-file-name)))
9419 (and (eq (car rr) 'in-mode)
9420 (string-match (cdr rr) (symbol-name major-mode)))
9421 (and (eq (car rr) 'in-buffer)
9422 (string-match (cdr rr) (buffer-name)))
9423 (when (and (eq (car rr) 'not-in-file)
9424 (buffer-file-name))
9425 (not (string-match (cdr rr) (buffer-file-name))))
9426 (when (eq (car rr) 'not-in-mode)
9427 (not (string-match (cdr rr) (symbol-name major-mode))))
9428 (when (eq (car rr) 'not-in-buffer)
9429 (not (string-match (cdr rr) (buffer-name)))))))
9430 (push r res))))
9431 (delete-dups (delq nil res))))
9433 (defun org-context-p (&rest contexts)
9434 "Check if local context is any of CONTEXTS.
9435 Possible values in the list of contexts are `table', `headline', and `item'."
9436 (let ((pos (point)))
9437 (goto-char (point-at-bol))
9438 (prog1 (or (and (memq 'table contexts)
9439 (looking-at "[ \t]*|"))
9440 (and (memq 'headline contexts)
9441 (looking-at org-outline-regexp))
9442 (and (memq 'item contexts)
9443 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9444 (and (memq 'item-body contexts)
9445 (org-in-item-p)))
9446 (goto-char pos))))
9448 (defconst org-unique-local-variables
9449 '(org-element--cache
9450 org-element--cache-objects
9451 org-element--cache-sync-keys
9452 org-element--cache-sync-requests
9453 org-element--cache-sync-timer)
9454 "List of local variables that cannot be transferred to another buffer.")
9456 (defun org-get-local-variables ()
9457 "Return a list of all local variables in an Org mode buffer."
9458 (delq nil
9459 (mapcar
9460 (lambda (x)
9461 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9462 (name (car binding)))
9463 (and (not (get name 'org-state))
9464 (not (memq name org-unique-local-variables))
9465 (string-match-p
9466 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9467 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9468 (symbol-name name))
9469 binding)))
9470 (with-temp-buffer
9471 (org-mode)
9472 (buffer-local-variables)))))
9474 (defun org-clone-local-variables (from-buffer &optional regexp)
9475 "Clone local variables from FROM-BUFFER.
9476 Optional argument REGEXP selects variables to clone."
9477 (dolist (pair (buffer-local-variables from-buffer))
9478 (let ((name (car pair)))
9479 (when (and (symbolp name)
9480 (not (memq name org-unique-local-variables))
9481 (or (null regexp) (string-match regexp (symbol-name name))))
9482 (set (make-local-variable name) (cdr pair))))))
9484 ;;;###autoload
9485 (defun org-run-like-in-org-mode (cmd)
9486 "Run a command, pretending that the current buffer is in Org mode.
9487 This will temporarily bind local variables that are typically bound in
9488 Org mode to the values they have in Org mode, and then interactively
9489 call CMD."
9490 (org-load-modules-maybe)
9491 (unless org-local-vars
9492 (setq org-local-vars (org-get-local-variables)))
9493 (let (binds)
9494 (dolist (var org-local-vars)
9495 (when (or (not (boundp (car var)))
9496 (eq (symbol-value (car var))
9497 (default-value (car var))))
9498 (push (list (car var) `(quote ,(cadr var))) binds)))
9499 (eval `(let ,binds
9500 (call-interactively (quote ,cmd))))))
9502 (defun org-get-category (&optional pos force-refresh)
9503 "Get the category applying to position POS."
9504 (save-match-data
9505 (when force-refresh (org-refresh-category-properties))
9506 (let ((pos (or pos (point))))
9507 (or (get-text-property pos 'org-category)
9508 (progn (org-refresh-category-properties)
9509 (get-text-property pos 'org-category))))))
9511 ;;; Refresh properties
9513 (defun org-refresh-properties (dprop tprop)
9514 "Refresh buffer text properties.
9515 DPROP is the drawer property and TPROP is either the
9516 corresponding text property to set, or an alist with each element
9517 being a text property (as a symbol) and a function to apply to
9518 the value of the drawer property."
9519 (let* ((case-fold-search t)
9520 (inhibit-read-only t)
9521 (inherit? (org-property-inherit-p dprop))
9522 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9523 (global (and inherit? (org--property-global-value dprop nil))))
9524 (org-with-silent-modifications
9525 (org-with-point-at 1
9526 ;; Set global values (e.g., values defined through
9527 ;; "#+PROPERTY:" keywords) to the whole buffer.
9528 (when global (put-text-property (point-min) (point-max) tprop global))
9529 ;; Set local values.
9530 (while (re-search-forward property-re nil t)
9531 (when (org-at-property-p)
9532 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9533 (outline-next-heading))))))
9535 (defun org-refresh-property (tprop p &optional inherit)
9536 "Refresh the buffer text property TPROP from the drawer property P.
9537 The refresh happens only for the current headline, or the whole
9538 sub-tree if optional argument INHERIT is non-nil."
9539 (unless (org-before-first-heading-p)
9540 (save-excursion
9541 (org-back-to-heading t)
9542 (let ((start (point))
9543 (end (save-excursion
9544 (if inherit (org-end-of-subtree t t)
9545 (or (outline-next-heading) (point-max))))))
9546 (if (symbolp tprop)
9547 ;; TPROP is a text property symbol.
9548 (put-text-property start end tprop p)
9549 ;; TPROP is an alist with (property . function) elements.
9550 (pcase-dolist (`(,prop . ,f) tprop)
9551 (put-text-property start end prop (funcall f p))))))))
9553 (defun org-refresh-category-properties ()
9554 "Refresh category text properties in the buffer."
9555 (let ((case-fold-search t)
9556 (inhibit-read-only t)
9557 (default-category
9558 (cond ((null org-category)
9559 (if buffer-file-name
9560 (file-name-sans-extension
9561 (file-name-nondirectory buffer-file-name))
9562 "???"))
9563 ((symbolp org-category) (symbol-name org-category))
9564 (t org-category))))
9565 (org-with-silent-modifications
9566 (org-with-wide-buffer
9567 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9568 ;; This is the default category for the buffer. If none is
9569 ;; found, fall-back to `org-category' or buffer file name.
9570 (put-text-property
9571 (point-min) (point-max)
9572 'org-category
9573 (catch 'buffer-category
9574 (goto-char (point-max))
9575 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9576 (let ((element (org-element-at-point)))
9577 (when (eq (org-element-type element) 'keyword)
9578 (throw 'buffer-category
9579 (org-element-property :value element)))))
9580 default-category))
9581 ;; Set sub-tree specific categories.
9582 (goto-char (point-min))
9583 (let ((regexp (org-re-property "CATEGORY")))
9584 (while (re-search-forward regexp nil t)
9585 (let ((value (match-string-no-properties 3)))
9586 (when (org-at-property-p)
9587 (put-text-property
9588 (save-excursion (org-back-to-heading t) (point))
9589 (save-excursion (org-end-of-subtree t t) (point))
9590 'org-category
9591 value)))))))))
9593 (defun org-refresh-stats-properties ()
9594 "Refresh stats text properties in the buffer."
9595 (let (stats)
9596 (org-with-silent-modifications
9597 (org-with-wide-buffer
9598 (goto-char (point-min))
9599 (while (re-search-forward
9600 (concat org-outline-regexp-bol ".*"
9601 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9602 nil t)
9603 (setq stats (cond ((equal (match-string 3) "0") 0)
9604 ((match-string 2)
9605 (/ (* (string-to-number (match-string 2)) 100)
9606 (string-to-number (match-string 3))))
9607 (t (string-to-number (match-string 1)))))
9608 (org-back-to-heading t)
9609 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9610 'org-stats stats))))))
9612 (defun org-refresh-effort-properties ()
9613 "Refresh effort properties"
9614 (org-refresh-properties
9615 org-effort-property
9616 '((effort . identity)
9617 (effort-minutes . org-duration-to-minutes))))
9619 ;;;; Link Stuff
9621 ;;; Link abbreviations
9623 (defun org-link-expand-abbrev (link)
9624 "Apply replacements as defined in `org-link-abbrev-alist'."
9625 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9626 (let* ((key (match-string 1 link))
9627 (as (or (assoc key org-link-abbrev-alist-local)
9628 (assoc key org-link-abbrev-alist)))
9629 (tag (and (match-end 2) (match-string 3 link)))
9630 rpl)
9631 (if (not as)
9632 link
9633 (setq rpl (cdr as))
9634 (cond
9635 ((symbolp rpl) (funcall rpl tag))
9636 ((string-match "%(\\([^)]+\\))" rpl)
9637 (replace-match
9638 (save-match-data
9639 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9640 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9641 ((string-match "%h" rpl)
9642 (replace-match (url-hexify-string (or tag "")) t t rpl))
9643 (t (concat rpl tag)))))
9644 link))
9646 ;;; Storing and inserting links
9648 (defvar org-insert-link-history nil
9649 "Minibuffer history for links inserted with `org-insert-link'.")
9651 (defvar org-stored-links nil
9652 "Contains the links stored with `org-store-link'.")
9654 (defvar org-store-link-plist nil
9655 "Plist with info about the most recently link created with `org-store-link'.")
9657 (defun org-store-link-functions ()
9658 "Return a list of functions that are called to create and store a link.
9659 The functions defined in the :store property of
9660 `org-link-parameters'.
9662 Each function will be called in turn until one returns a non-nil
9663 value. Each function should check if it is responsible for
9664 creating this link (for example by looking at the major mode).
9665 If not, it must exit and return nil. If yes, it should return
9666 a non-nil value after calling `org-store-link-props' with a list
9667 of properties and values. Special properties are:
9669 :type The link prefix, like \"http\". This must be given.
9670 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9671 This is obligatory as well.
9672 :description Optional default description for the second pair
9673 of brackets in an Org mode link. The user can still change
9674 this when inserting this link into an Org mode buffer.
9676 In addition to these, any additional properties can be specified
9677 and then used in capture templates."
9678 (cl-loop for link in org-link-parameters
9679 with store-func
9680 do (setq store-func (org-link-get-parameter (car link) :store))
9681 if store-func
9682 collect store-func))
9684 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9685 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9687 ;;;###autoload
9688 (defun org-store-link (arg)
9689 "Store an org-link to the current location.
9690 \\<org-mode-map>
9691 This link is added to `org-stored-links' and can later be inserted
9692 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9694 For some link types, a `\\[universal-argument]' prefix ARG is interpreted.
9695 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9696 For file links, ARG negates `org-context-in-file-links'.
9698 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9699 skipping storing functions that are not
9700 part of Org core.
9702 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9703 prefix ARG forces storing a link for each line in the
9704 active region."
9705 (interactive "P")
9706 (org-load-modules-maybe)
9707 (if (and (equal arg '(64)) (org-region-active-p))
9708 (save-excursion
9709 (let ((end (region-end)))
9710 (goto-char (region-beginning))
9711 (set-mark (point))
9712 (while (< (point-at-eol) end)
9713 (move-end-of-line 1) (activate-mark)
9714 (let (current-prefix-arg)
9715 (call-interactively 'org-store-link))
9716 (move-beginning-of-line 2)
9717 (set-mark (point)))))
9718 (setq org-store-link-plist nil)
9719 (let (link cpltxt desc description search
9720 txt custom-id agenda-link sfuns sfunsn)
9721 (cond
9723 ;; Store a link using an external link type
9724 ((and (not (equal arg '(16)))
9725 (setq sfuns
9726 (delq
9727 nil (mapcar (lambda (f)
9728 (let (fs) (if (funcall f) (push f fs))))
9729 (org-store-link-functions)))
9730 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9731 (or (and (cdr sfuns)
9732 (funcall (intern
9733 (completing-read
9734 "Which function for creating the link? "
9735 sfunsn nil t (car sfunsn)))))
9736 (funcall (caar sfuns)))
9737 (setq link (plist-get org-store-link-plist :link)
9738 desc (or (plist-get org-store-link-plist
9739 :description)
9740 link))))
9742 ;; Store a link from a source code buffer.
9743 ((org-src-edit-buffer-p)
9744 (let ((coderef-format (org-src-coderef-format)))
9745 (cond ((save-excursion
9746 (beginning-of-line)
9747 (looking-at (org-src-coderef-regexp coderef-format)))
9748 (setq link (format "(%s)" (match-string-no-properties 3))))
9749 ((called-interactively-p 'any)
9750 (let ((label (read-string "Code line label: ")))
9751 (end-of-line)
9752 (setq link (format coderef-format label))
9753 (let ((gc (- 79 (length link))))
9754 (if (< (current-column) gc)
9755 (org-move-to-column gc t)
9756 (insert " ")))
9757 (insert link)
9758 (setq link (concat "(" label ")"))
9759 (setq desc nil)))
9760 (t (setq link nil)))))
9762 ;; We are in the agenda, link to referenced location
9763 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9764 (let ((m (or (get-text-property (point) 'org-hd-marker)
9765 (get-text-property (point) 'org-marker))))
9766 (when m
9767 (org-with-point-at m
9768 (setq agenda-link
9769 (if (called-interactively-p 'any)
9770 (call-interactively 'org-store-link)
9771 (org-store-link nil)))))))
9773 ((eq major-mode 'calendar-mode)
9774 (let ((cd (calendar-cursor-to-date)))
9775 (setq link
9776 (format-time-string
9777 (car org-time-stamp-formats)
9778 (apply 'encode-time
9779 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9780 nil nil nil))))
9781 (org-store-link-props :type "calendar" :date cd)))
9783 ((eq major-mode 'help-mode)
9784 (setq link (concat "help:" (save-excursion
9785 (goto-char (point-min))
9786 (looking-at "^[^ ]+")
9787 (match-string 0))))
9788 (org-store-link-props :type "help"))
9790 ((eq major-mode 'w3-mode)
9791 (setq cpltxt (if (and (buffer-name)
9792 (not (string-match "Untitled" (buffer-name))))
9793 (buffer-name)
9794 (url-view-url t))
9795 link (url-view-url t))
9796 (org-store-link-props :type "w3" :url (url-view-url t)))
9798 ((eq major-mode 'image-mode)
9799 (setq cpltxt (concat "file:"
9800 (abbreviate-file-name buffer-file-name))
9801 link cpltxt)
9802 (org-store-link-props :type "image" :file buffer-file-name))
9804 ;; In dired, store a link to the file of the current line
9805 ((derived-mode-p 'dired-mode)
9806 (let ((file (dired-get-filename nil t)))
9807 (setq file (if file
9808 (abbreviate-file-name
9809 (expand-file-name (dired-get-filename nil t)))
9810 ;; otherwise, no file so use current directory.
9811 default-directory))
9812 (setq cpltxt (concat "file:" file)
9813 link cpltxt)))
9815 ((setq search (run-hook-with-args-until-success
9816 'org-create-file-search-functions))
9817 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9818 "::" search))
9819 (setq cpltxt (or description link)))
9821 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9822 (org-with-limited-levels
9823 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9824 (cond
9825 ;; Store a link using the target at point
9826 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9827 (setq cpltxt
9828 (concat "file:"
9829 (abbreviate-file-name
9830 (buffer-file-name (buffer-base-buffer)))
9831 "::" (match-string 1))
9832 link cpltxt))
9833 ((and (featurep 'org-id)
9834 (or (eq org-id-link-to-org-use-id t)
9835 (and (called-interactively-p 'any)
9836 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9837 (and (eq org-id-link-to-org-use-id
9838 'create-if-interactive-and-no-custom-id)
9839 (not custom-id))))
9840 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9841 ;; Store a link using the ID at point
9842 (setq link (condition-case nil
9843 (prog1 (org-id-store-link)
9844 (setq desc (or (plist-get org-store-link-plist
9845 :description)
9846 "")))
9847 (error
9848 ;; Probably before first headline, link only to file
9849 (concat "file:"
9850 (abbreviate-file-name
9851 (buffer-file-name (buffer-base-buffer))))))))
9853 ;; Just link to current headline
9854 (setq cpltxt (concat "file:"
9855 (abbreviate-file-name
9856 (buffer-file-name (buffer-base-buffer)))))
9857 ;; Add a context search string
9858 (when (org-xor org-context-in-file-links arg)
9859 (let* ((element (org-element-at-point))
9860 (name (org-element-property :name element)))
9861 (setq txt (cond
9862 ((org-at-heading-p) nil)
9863 (name)
9864 ((org-region-active-p)
9865 (buffer-substring (region-beginning) (region-end)))))
9866 (when (or (null txt) (string-match "\\S-" txt))
9867 (setq cpltxt
9868 (concat cpltxt "::"
9869 (condition-case nil
9870 (org-make-org-heading-search-string txt)
9871 (error "")))
9872 desc (or name
9873 (nth 4 (ignore-errors (org-heading-components)))
9874 "NONE")))))
9875 (when (string-match "::\\'" cpltxt)
9876 (setq cpltxt (substring cpltxt 0 -2)))
9877 (setq link cpltxt)))))
9879 ((buffer-file-name (buffer-base-buffer))
9880 ;; Just link to this file here.
9881 (setq cpltxt (concat "file:"
9882 (abbreviate-file-name
9883 (buffer-file-name (buffer-base-buffer)))))
9884 ;; Add a context string.
9885 (when (org-xor org-context-in-file-links arg)
9886 (setq txt (if (org-region-active-p)
9887 (buffer-substring (region-beginning) (region-end))
9888 (buffer-substring (point-at-bol) (point-at-eol))))
9889 ;; Only use search option if there is some text.
9890 (when (string-match "\\S-" txt)
9891 (setq cpltxt
9892 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9893 desc "NONE")))
9894 (setq link cpltxt))
9896 ((called-interactively-p 'interactive)
9897 (user-error "No method for storing a link from this buffer"))
9899 (t (setq link nil)))
9901 ;; We're done setting link and desc, clean up
9902 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9903 (setq link (or link cpltxt)
9904 desc (or desc cpltxt))
9905 (cond ((not desc))
9906 ((equal desc "NONE") (setq desc nil))
9907 (t (setq desc
9908 (replace-regexp-in-string
9909 org-bracket-link-analytic-regexp
9910 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9911 desc))))
9912 ;; Return the link
9913 (if (not (and (or (called-interactively-p 'any)
9914 executing-kbd-macro)
9915 link))
9916 (or agenda-link (and link (org-make-link-string link desc)))
9917 (push (list link desc) org-stored-links)
9918 (message "Stored: %s" (or desc link))
9919 (when custom-id
9920 (setq link (concat "file:" (abbreviate-file-name
9921 (buffer-file-name)) "::#" custom-id))
9922 (push (list link desc) org-stored-links))
9923 (car org-stored-links)))))
9925 (defun org-store-link-props (&rest plist)
9926 "Store link properties, extract names, addresses and dates."
9927 (let ((x (plist-get plist :from)))
9928 (when x
9929 (let ((adr (mail-extract-address-components x)))
9930 (setq plist (plist-put plist :fromname (car adr)))
9931 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9932 (let ((x (plist-get plist :to)))
9933 (when x
9934 (let ((adr (mail-extract-address-components x)))
9935 (setq plist (plist-put plist :toname (car adr)))
9936 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9937 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9938 (when x
9939 (setq plist (plist-put plist :date-timestamp
9940 (format-time-string
9941 (org-time-stamp-format t) x)))
9942 (setq plist (plist-put plist :date-timestamp-inactive
9943 (format-time-string
9944 (org-time-stamp-format t t) x)))))
9945 (let ((from (plist-get plist :from))
9946 (to (plist-get plist :to)))
9947 (when (and from to org-from-is-user-regexp)
9948 (setq plist
9949 (plist-put plist :fromto
9950 (if (string-match org-from-is-user-regexp from)
9951 (concat "to %t")
9952 (concat "from %f"))))))
9953 (setq org-store-link-plist plist))
9955 (defun org-add-link-props (&rest plist)
9956 "Add these properties to the link property list."
9957 (let (key value)
9958 (while plist
9959 (setq key (pop plist) value (pop plist))
9960 (setq org-store-link-plist
9961 (plist-put org-store-link-plist key value)))))
9963 (defun org-email-link-description (&optional fmt)
9964 "Return the description part of an email link.
9965 This takes information from `org-store-link-plist' and formats it
9966 according to FMT (default from `org-email-link-description-format')."
9967 (setq fmt (or fmt org-email-link-description-format))
9968 (let* ((p org-store-link-plist)
9969 (to (plist-get p :toaddress))
9970 (from (plist-get p :fromaddress))
9971 (table
9972 (list
9973 (cons "%c" (plist-get p :fromto))
9974 (cons "%F" (plist-get p :from))
9975 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9976 (cons "%T" (plist-get p :to))
9977 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9978 (cons "%s" (plist-get p :subject))
9979 (cons "%d" (plist-get p :date))
9980 (cons "%m" (plist-get p :message-id)))))
9981 (when (string-match "%c" fmt)
9982 ;; Check if the user wrote this message
9983 (if (and org-from-is-user-regexp from to
9984 (save-match-data (string-match org-from-is-user-regexp from)))
9985 (setq fmt (replace-match "to %t" t t fmt))
9986 (setq fmt (replace-match "from %f" t t fmt))))
9987 (org-replace-escapes fmt table)))
9989 (defun org-make-org-heading-search-string (&optional string)
9990 "Make search string for the current headline or STRING."
9991 (let ((s (or string
9992 (and (derived-mode-p 'org-mode)
9993 (save-excursion
9994 (org-back-to-heading t)
9995 (org-element-property :raw-value (org-element-at-point))))))
9996 (lines org-context-in-file-links))
9997 (or string (setq s (concat "*" s))) ; Add * for headlines
9998 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9999 (when (and string (integerp lines) (> lines 0))
10000 (let ((slines (org-split-string s "\n")))
10001 (when (< lines (length slines))
10002 (setq s (mapconcat
10003 'identity
10004 (reverse (nthcdr (- (length slines) lines)
10005 (reverse slines))) "\n")))))
10006 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10008 (defun org-make-link-string (link &optional description)
10009 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10010 (unless (org-string-nw-p link) (error "Empty link"))
10011 (let ((uri (cond ((string-match org-link-types-re link)
10012 (concat (match-string 1 link)
10013 (org-link-escape (substring link (match-end 1)))))
10014 ;; For readability, url-encode internal links only
10015 ;; when absolutely needed (i.e, when they contain
10016 ;; square brackets). File links however, are
10017 ;; encoded since, e.g., spaces are significant.
10018 ((or (file-name-absolute-p link)
10019 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10020 (org-link-escape link))
10021 (t link)))
10022 (description
10023 (and (org-string-nw-p description)
10024 ;; Remove brackets from description, as they are fatal.
10025 (replace-regexp-in-string
10026 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10027 (org-trim description)))))
10028 (format "[[%s]%s]"
10030 (if description (format "[%s]" description) ""))))
10032 (defconst org-link-escape-chars
10033 ;;%20 %5B %5D %25
10034 '(?\s ?\[ ?\] ?%)
10035 "List of characters that should be escaped in a link when stored to Org.
10036 This is the list that is used for internal purposes.")
10038 (defun org-link-escape (text &optional table merge)
10039 "Return percent escaped representation of TEXT.
10040 TEXT is a string with the text to escape.
10041 Optional argument TABLE is a list with characters that should be
10042 escaped. When nil, `org-link-escape-chars' is used.
10043 If optional argument MERGE is set, merge TABLE into
10044 `org-link-escape-chars'."
10045 (let ((characters-to-encode
10046 (cond ((null table) org-link-escape-chars)
10047 (merge (append org-link-escape-chars table))
10048 (t table))))
10049 (mapconcat
10050 (lambda (c)
10051 (if (or (memq c characters-to-encode)
10052 (and org-url-hexify-p (or (< c 32) (> c 126))))
10053 (mapconcat (lambda (e) (format "%%%.2X" e))
10054 (or (encode-coding-char c 'utf-8)
10055 (error "Unable to percent escape character: %c" c))
10057 (char-to-string c)))
10058 text "")))
10060 (defun org-link-unescape (str)
10061 "Unhex hexified Unicode parts in string STR.
10062 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10063 reciprocal of `org-link-escape', which see."
10064 (if (org-string-nw-p str)
10065 (replace-regexp-in-string
10066 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10067 str))
10069 (defun org-link-unescape-compound (hex)
10070 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10071 Note: this function also decodes single byte encodings like
10072 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10073 (save-match-data
10074 (let* ((bytes (cdr (split-string hex "%")))
10075 (ret "")
10076 (eat 0)
10077 (sum 0))
10078 (while bytes
10079 (let* ((val (string-to-number (pop bytes) 16))
10080 (shift-xor
10081 (if (= 0 eat)
10082 (cond
10083 ((>= val 252) (cons 6 252))
10084 ((>= val 248) (cons 5 248))
10085 ((>= val 240) (cons 4 240))
10086 ((>= val 224) (cons 3 224))
10087 ((>= val 192) (cons 2 192))
10088 (t (cons 0 0)))
10089 (cons 6 128))))
10090 (when (>= val 192) (setq eat (car shift-xor)))
10091 (setq val (logxor val (cdr shift-xor)))
10092 (setq sum (+ (lsh sum (car shift-xor)) val))
10093 (when (> eat 0) (setq eat (- eat 1)))
10094 (cond
10095 ((= 0 eat) ;multi byte
10096 (setq ret (concat ret (char-to-string sum)))
10097 (setq sum 0))
10098 ((not bytes) ; single byte(s)
10099 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10100 ret)))
10102 (defun org-link-unescape-single-byte-sequence (hex)
10103 "Unhexify hex-encoded single byte character sequences."
10104 (mapconcat (lambda (byte)
10105 (char-to-string (string-to-number byte 16)))
10106 (cdr (split-string hex "%")) ""))
10108 (defun org-xor (a b)
10109 "Exclusive or."
10110 (if a (not b) b))
10112 (defun org-fixup-message-id-for-http (s)
10113 "Replace special characters in a message id, so it can be used in an http query."
10114 (when (string-match "%" s)
10115 (setq s (mapconcat (lambda (c)
10116 (if (eq c ?%)
10117 "%25"
10118 (char-to-string c)))
10119 s "")))
10120 (while (string-match "<" s)
10121 (setq s (replace-match "%3C" t t s)))
10122 (while (string-match ">" s)
10123 (setq s (replace-match "%3E" t t s)))
10124 (while (string-match "@" s)
10125 (setq s (replace-match "%40" t t s)))
10128 (defun org-link-prettify (link)
10129 "Return a human-readable representation of LINK.
10130 The car of LINK must be a raw link.
10131 The cdr of LINK must be either a link description or nil."
10132 (let ((desc (or (cadr link) "<no description>")))
10133 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10134 "<" (car link) ">")))
10136 ;;;###autoload
10137 (defun org-insert-link-global ()
10138 "Insert a link like Org mode does.
10139 This command can be called in any mode to insert a link in Org syntax."
10140 (interactive)
10141 (org-load-modules-maybe)
10142 (org-run-like-in-org-mode 'org-insert-link))
10144 (defun org-insert-all-links (arg &optional pre post)
10145 "Insert all links in `org-stored-links'.
10146 When a universal prefix, do not delete the links from `org-stored-links'.
10147 When `ARG' is a number, insert the last N link(s).
10148 `PRE' and `POST' are optional arguments to define a string to
10149 prepend or to append."
10150 (interactive "P")
10151 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10152 (links (copy-sequence org-stored-links))
10153 (pr (or pre "- "))
10154 (po (or post "\n"))
10155 (cnt 1) l)
10156 (if (null org-stored-links)
10157 (message "No link to insert")
10158 (while (and (or (listp arg) (>= arg cnt))
10159 (setq l (if (listp arg)
10160 (pop links)
10161 (pop org-stored-links))))
10162 (setq cnt (1+ cnt))
10163 (insert pr)
10164 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10165 (insert po)))))
10167 (defun org-insert-last-stored-link (arg)
10168 "Insert the last link stored in `org-stored-links'."
10169 (interactive "p")
10170 (org-insert-all-links arg "" "\n"))
10172 (defun org-link-fontify-links-to-this-file ()
10173 "Fontify links to the current file in `org-stored-links'."
10174 (let ((f (buffer-file-name)) a b)
10175 (setq a (mapcar (lambda(l)
10176 (let ((ll (car l)))
10177 (when (and (string-match "^file:\\(.+\\)::" ll)
10178 (equal f (expand-file-name (match-string 1 ll))))
10179 ll)))
10180 org-stored-links))
10181 (when (featurep 'org-id)
10182 (setq b (mapcar (lambda(l)
10183 (let ((ll (car l)))
10184 (when (and (string-match "^id:\\(.+\\)$" ll)
10185 (equal f (expand-file-name
10186 (or (org-id-find-id-file
10187 (match-string 1 ll)) ""))))
10188 ll)))
10189 org-stored-links)))
10190 (mapcar (lambda(l)
10191 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10192 (delq nil (append a b)))))
10194 (defvar org--links-history nil)
10195 (defun org-insert-link (&optional complete-file link-location default-description)
10196 "Insert a link. At the prompt, enter the link.
10198 Completion can be used to insert any of the link protocol prefixes in use.
10200 The history can be used to select a link previously stored with
10201 `org-store-link'. When the empty string is entered (i.e. if you just
10202 press `RET' at the prompt), the link defaults to the most recently
10203 stored link. As `SPC' triggers completion in the minibuffer, you need to
10204 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10206 You will also be prompted for a description, and if one is given, it will
10207 be displayed in the buffer instead of the link.
10209 If there is already a link at point, this command will allow you to edit
10210 link and description parts.
10212 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10213 file name can be
10214 selected using completion. The path to the file will be relative to the
10215 current directory if the file is in the current directory or a subdirectory.
10216 Otherwise, the link will be the absolute path as completed in the minibuffer
10217 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10218 option `org-link-file-path-type'.
10220 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10221 absolute path even if the file is in
10222 the current directory or below.
10224 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10225 prefix negates `org-keep-stored-link-after-insertion'.
10227 If `org-make-link-description-function' is non-nil, this function will be
10228 called with the link target, and the result will be the default
10229 link description.
10231 If the LINK-LOCATION parameter is non-nil, this value will be used as
10232 the link location instead of reading one interactively.
10234 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10235 as the default description."
10236 (interactive "P")
10237 (let* ((wcf (current-window-configuration))
10238 (origbuf (current-buffer))
10239 (region (when (org-region-active-p)
10240 (buffer-substring (region-beginning) (region-end))))
10241 (remove (and region (list (region-beginning) (region-end))))
10242 (desc region)
10243 (link link-location)
10244 (abbrevs org-link-abbrev-alist-local)
10245 entry all-prefixes auto-desc)
10246 (cond
10247 (link-location) ; specified by arg, just use it.
10248 ((org-in-regexp org-bracket-link-regexp 1)
10249 ;; We do have a link at point, and we are going to edit it.
10250 (setq remove (list (match-beginning 0) (match-end 0)))
10251 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10252 (setq link (read-string "Link: "
10253 (org-link-unescape
10254 (match-string-no-properties 1)))))
10255 ((or (org-in-regexp org-angle-link-re)
10256 (org-in-regexp org-plain-link-re))
10257 ;; Convert to bracket link
10258 (setq remove (list (match-beginning 0) (match-end 0))
10259 link (read-string "Link: "
10260 (org-unbracket-string "<" ">" (match-string 0)))))
10261 ((member complete-file '((4) (16)))
10262 ;; Completing read for file names.
10263 (setq link (org-file-complete-link complete-file)))
10265 ;; Read link, with completion for stored links.
10266 (org-link-fontify-links-to-this-file)
10267 (org-switch-to-buffer-other-window "*Org Links*")
10268 (with-current-buffer "*Org Links*"
10269 (erase-buffer)
10270 (insert "Insert a link.
10271 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10272 (when org-stored-links
10273 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10274 (insert (mapconcat 'org-link-prettify
10275 (reverse org-stored-links) "\n")))
10276 (goto-char (point-min)))
10277 (let ((cw (selected-window)))
10278 (select-window (get-buffer-window "*Org Links*" 'visible))
10279 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10280 (unless (pos-visible-in-window-p (point-max))
10281 (org-fit-window-to-buffer))
10282 (and (window-live-p cw) (select-window cw)))
10283 (setq all-prefixes (append (mapcar 'car abbrevs)
10284 (mapcar 'car org-link-abbrev-alist)
10285 (org-link-types)))
10286 (unwind-protect
10287 ;; Fake a link history, containing the stored links.
10288 (let ((org--links-history
10289 (append (mapcar #'car org-stored-links)
10290 org-insert-link-history)))
10291 (setq link
10292 (org-completing-read
10293 "Link: "
10294 (append
10295 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10296 (mapcar #'car org-stored-links))
10297 nil nil nil
10298 'org--links-history
10299 (caar org-stored-links)))
10300 (unless (org-string-nw-p link) (user-error "No link selected"))
10301 (dolist (l org-stored-links)
10302 (when (equal link (cadr l))
10303 (setq link (car l))
10304 (setq auto-desc t)))
10305 (when (or (member link all-prefixes)
10306 (and (equal ":" (substring link -1))
10307 (member (substring link 0 -1) all-prefixes)
10308 (setq link (substring link 0 -1))))
10309 (setq link (with-current-buffer origbuf
10310 (org-link-try-special-completion link)))))
10311 (set-window-configuration wcf)
10312 (kill-buffer "*Org Links*"))
10313 (setq entry (assoc link org-stored-links))
10314 (or entry (push link org-insert-link-history))
10315 (setq desc (or desc (nth 1 entry)))))
10317 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10318 (not org-keep-stored-link-after-insertion))
10319 (setq org-stored-links (delq (assoc link org-stored-links)
10320 org-stored-links)))
10322 (when (and (string-match org-plain-link-re link)
10323 (not (string-match org-ts-regexp link)))
10324 ;; URL-like link, normalize the use of angular brackets.
10325 (setq link (org-unbracket-string "<" ">" link)))
10327 ;; Check if we are linking to the current file with a search
10328 ;; option If yes, simplify the link by using only the search
10329 ;; option.
10330 (when (and buffer-file-name
10331 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10332 (let* ((path (match-string 1 link))
10333 (case-fold-search nil)
10334 (search (match-string 2 link)))
10335 (save-match-data
10336 (when (equal (file-truename buffer-file-name) (file-truename path))
10337 ;; We are linking to this same file, with a search option
10338 (setq link search)))))
10340 ;; Check if we can/should use a relative path. If yes, simplify the link
10341 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10342 (let* ((type (match-string 1 link))
10343 (path (match-string 2 link))
10344 (origpath path)
10345 (case-fold-search nil))
10346 (cond
10347 ((or (eq org-link-file-path-type 'absolute)
10348 (equal complete-file '(16)))
10349 (setq path (abbreviate-file-name (expand-file-name path))))
10350 ((eq org-link-file-path-type 'noabbrev)
10351 (setq path (expand-file-name path)))
10352 ((eq org-link-file-path-type 'relative)
10353 (setq path (file-relative-name path)))
10355 (save-match-data
10356 (if (string-match (concat "^" (regexp-quote
10357 (expand-file-name
10358 (file-name-as-directory
10359 default-directory))))
10360 (expand-file-name path))
10361 ;; We are linking a file with relative path name.
10362 (setq path (substring (expand-file-name path)
10363 (match-end 0)))
10364 (setq path (abbreviate-file-name (expand-file-name path)))))))
10365 (setq link (concat type path))
10366 (when (equal desc origpath)
10367 (setq desc path))))
10369 (if org-make-link-description-function
10370 (setq desc
10371 (or (condition-case nil
10372 (funcall org-make-link-description-function link desc)
10373 (error (progn (message "Can't get link description from `%s'"
10374 (symbol-name org-make-link-description-function))
10375 (sit-for 2) nil)))
10376 (read-string "Description: " default-description)))
10377 (if default-description (setq desc default-description)
10378 (setq desc (or (and auto-desc desc)
10379 (read-string "Description: " desc)))))
10381 (unless (string-match "\\S-" desc) (setq desc nil))
10382 (when remove (apply 'delete-region remove))
10383 (insert (org-make-link-string link desc))
10384 ;; Redisplay so as the new link has proper invisible characters.
10385 (sit-for 0)))
10387 (defun org-link-try-special-completion (type)
10388 "If there is completion support for link type TYPE, offer it."
10389 (let ((fun (org-link-get-parameter type :complete)))
10390 (if (functionp fun)
10391 (funcall fun)
10392 (read-string "Link (no completion support): " (concat type ":")))))
10394 (defun org-file-complete-link (&optional arg)
10395 "Create a file link using completion."
10396 (let ((file (read-file-name "File: "))
10397 (pwd (file-name-as-directory (expand-file-name ".")))
10398 (pwd1 (file-name-as-directory (abbreviate-file-name
10399 (expand-file-name ".")))))
10400 (cond ((equal arg '(16))
10401 (concat "file:"
10402 (abbreviate-file-name (expand-file-name file))))
10403 ((string-match
10404 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10405 (concat "file:" (match-string 1 file)))
10406 ((string-match
10407 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10408 (expand-file-name file))
10409 (concat "file:"
10410 (match-string 1 (expand-file-name file))))
10411 (t (concat "file:" file)))))
10413 (defun org-completing-read (&rest args)
10414 "Completing-read with SPACE being a normal character."
10415 (let ((enable-recursive-minibuffers t)
10416 (minibuffer-local-completion-map
10417 (copy-keymap minibuffer-local-completion-map)))
10418 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10419 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10420 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10421 'org-time-stamp-inactive)
10422 (apply #'completing-read args)))
10424 ;;; Opening/following a link
10426 (defvar org-link-search-failed nil)
10428 (defvar org-open-link-functions nil
10429 "Hook for functions finding a plain text link.
10430 These functions must take a single argument, the link content.
10431 They will be called for links that look like [[link text][description]]
10432 when LINK TEXT does not have a protocol like \"http:\" and does not look
10433 like a filename (e.g. \"./blue.png\").
10435 These functions will be called *before* Org attempts to resolve the
10436 link by doing text searches in the current buffer - so if you want a
10437 link \"[[target]]\" to still find \"<<target>>\", your function should
10438 handle this as a special case.
10440 When the function does handle the link, it must return a non-nil value.
10441 If it decides that it is not responsible for this link, it must return
10442 nil to indicate that that Org can continue with other options like
10443 exact and fuzzy text search.")
10445 (defun org-next-link (&optional search-backward)
10446 "Move forward to the next link.
10447 If the link is in hidden text, expose it."
10448 (interactive "P")
10449 (when (and org-link-search-failed (eq this-command last-command))
10450 (goto-char (point-min))
10451 (message "Link search wrapped back to beginning of buffer"))
10452 (setq org-link-search-failed nil)
10453 (let* ((pos (point))
10454 (ct (org-context))
10455 (a (assq :link ct))
10456 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10457 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10458 ((looking-at org-any-link-re)
10459 ;; Don't stay stuck at link without an org-link face
10460 (forward-char (if search-backward -1 1))))
10461 (if (funcall srch-fun org-any-link-re nil t)
10462 (progn
10463 (goto-char (match-beginning 0))
10464 (when (outline-invisible-p) (org-show-context)))
10465 (goto-char pos)
10466 (setq org-link-search-failed t)
10467 (message "No further link found"))))
10469 (defun org-previous-link ()
10470 "Move backward to the previous link.
10471 If the link is in hidden text, expose it."
10472 (interactive)
10473 (funcall 'org-next-link t))
10475 (defun org-translate-link (s)
10476 "Translate a link string if a translation function has been defined."
10477 (with-temp-buffer
10478 (insert (org-trim s))
10479 (org-trim (org-element-interpret-data (org-element-context)))))
10481 (defun org-translate-link-from-planner (type path)
10482 "Translate a link from Emacs Planner syntax so that Org can follow it.
10483 This is still an experimental function, your mileage may vary."
10484 (cond
10485 ((member type '("http" "https" "news" "ftp"))
10486 ;; standard Internet links are the same.
10487 nil)
10488 ((and (equal type "irc") (string-match "^//" path))
10489 ;; Planner has two / at the beginning of an irc link, we have 1.
10490 ;; We should have zero, actually....
10491 (setq path (substring path 1)))
10492 ((and (equal type "lisp") (string-match "^/" path))
10493 ;; Planner has a slash, we do not.
10494 (setq type "elisp" path (substring path 1)))
10495 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10496 ;; A typical message link. Planner has the id after the final slash,
10497 ;; we separate it with a hash mark
10498 (setq path (concat (match-string 1 path) "#"
10499 (org-unbracket-string "<" ">" (match-string 2 path))))))
10500 (cons type path))
10502 (defun org-find-file-at-mouse (ev)
10503 "Open file link or URL at mouse."
10504 (interactive "e")
10505 (mouse-set-point ev)
10506 (org-open-at-point 'in-emacs))
10508 (defun org-open-at-mouse (ev)
10509 "Open file link or URL at mouse.
10510 See the docstring of `org-open-file' for details."
10511 (interactive "e")
10512 (mouse-set-point ev)
10513 (when (eq major-mode 'org-agenda-mode)
10514 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10515 (org-open-at-point))
10517 (defvar org-window-config-before-follow-link nil
10518 "The window configuration before following a link.
10519 This is saved in case the need arises to restore it.")
10521 ;;;###autoload
10522 (defun org-open-at-point-global ()
10523 "Follow a link or time-stamp like Org mode does.
10524 This command can be called in any mode to follow an external link
10525 or a time-stamp that has Org mode syntax. Its behavior is
10526 undefined when called on internal links (e.g., fuzzy links).
10527 Raise an error when there is nothing to follow. "
10528 (interactive)
10529 (cond ((org-in-regexp org-any-link-re)
10530 (org-open-link-from-string (match-string-no-properties 0)))
10531 ((or (org-in-regexp org-ts-regexp-both nil t)
10532 (org-in-regexp org-tsr-regexp-both nil t))
10533 (org-follow-timestamp-link))
10534 (t (user-error "No link found"))))
10536 ;;;###autoload
10537 (defun org-open-link-from-string (s &optional arg reference-buffer)
10538 "Open a link in the string S, as if it was in Org mode."
10539 (interactive "sLink: \nP")
10540 (let ((reference-buffer (or reference-buffer (current-buffer))))
10541 (with-temp-buffer
10542 (let ((org-inhibit-startup (not reference-buffer)))
10543 (org-mode)
10544 (insert s)
10545 (goto-char (point-min))
10546 (when reference-buffer
10547 (setq org-link-abbrev-alist-local
10548 (with-current-buffer reference-buffer
10549 org-link-abbrev-alist-local)))
10550 (org-open-at-point arg reference-buffer)))))
10552 (defvar org-open-at-point-functions nil
10553 "Hook that is run when following a link at point.
10555 Functions in this hook must return t if they identify and follow
10556 a link at point. If they don't find anything interesting at point,
10557 they must return nil.")
10559 (defvar org-link-search-inhibit-query nil)
10560 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10561 (defun org--open-doi-link (path)
10562 "Open a \"doi\" type link.
10563 PATH is a the path to search for, as a string."
10564 (browse-url (url-encode-url (concat org-doi-server-url path))))
10566 (defun org--open-elisp-link (path)
10567 "Open a \"elisp\" type link.
10568 PATH is the sexp to evaluate, as a string."
10569 (let ((cmd path))
10570 (if (or (and (org-string-nw-p
10571 org-confirm-elisp-link-not-regexp)
10572 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10573 (not org-confirm-elisp-link-function)
10574 (funcall org-confirm-elisp-link-function
10575 (format "Execute \"%s\" as elisp? "
10576 (org-add-props cmd nil 'face 'org-warning))))
10577 (message "%s => %s" cmd
10578 (if (eq (string-to-char cmd) ?\()
10579 (eval (read cmd))
10580 (call-interactively (read cmd))))
10581 (user-error "Abort"))))
10583 (defun org--open-help-link (path)
10584 "Open a \"help\" type link.
10585 PATH is a symbol name, as a string."
10586 (pcase (intern path)
10587 ((and (pred fboundp) variable) (describe-function variable))
10588 ((and (pred boundp) function) (describe-variable function))
10589 (name (user-error "Unknown function or variable: %s" name))))
10591 (defun org--open-shell-link (path)
10592 "Open a \"shell\" type link.
10593 PATH is the command to execute, as a string."
10594 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10595 (cmd path))
10596 (if (or (and (org-string-nw-p
10597 org-confirm-shell-link-not-regexp)
10598 (string-match
10599 org-confirm-shell-link-not-regexp cmd))
10600 (not org-confirm-shell-link-function)
10601 (funcall org-confirm-shell-link-function
10602 (format "Execute \"%s\" in shell? "
10603 (org-add-props cmd nil
10604 'face 'org-warning))))
10605 (progn
10606 (message "Executing %s" cmd)
10607 (shell-command cmd buf)
10608 (when (featurep 'midnight)
10609 (setq clean-buffer-list-kill-buffer-names
10610 (cons (buffer-name buf)
10611 clean-buffer-list-kill-buffer-names))))
10612 (user-error "Abort"))))
10614 (defun org-open-at-point (&optional arg reference-buffer)
10615 "Open link, timestamp, footnote or tags at point.
10617 When point is on a link, follow it. Normally, files will be
10618 opened by an appropriate application. If the optional prefix
10619 argument ARG is non-nil, Emacs will visit the file. With
10620 a double prefix argument, try to open outside of Emacs, in the
10621 application the system uses for this file type.
10623 When point is on a timestamp, open the agenda at the day
10624 specified.
10626 When point is a footnote definition, move to the first reference
10627 found. If it is on a reference, move to the associated
10628 definition.
10630 When point is on a headline, display a list of every link in the
10631 entry, so it is possible to pick one, or all, of them. If point
10632 is on a tag, call `org-tags-view' instead.
10634 When optional argument REFERENCE-BUFFER is non-nil, it should
10635 specify a buffer from where the link search should happen. This
10636 is used internally by `org-open-link-from-string'.
10638 On top of syntactically correct links, this function will open
10639 the link at point in comments or comment blocks and the first
10640 link in a property drawer line."
10641 (interactive "P")
10642 ;; On a code block, open block's results.
10643 (unless (call-interactively 'org-babel-open-src-block-result)
10644 (org-load-modules-maybe)
10645 (setq org-window-config-before-follow-link (current-window-configuration))
10646 (org-remove-occur-highlights nil nil t)
10647 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10648 (let* ((context
10649 ;; Only consider supported types, even if they are not
10650 ;; the closest one.
10651 (org-element-lineage
10652 (org-element-context)
10653 '(clock comment comment-block footnote-definition
10654 footnote-reference headline inlinetask keyword link
10655 node-property timestamp)
10657 (type (org-element-type context))
10658 (value (org-element-property :value context)))
10659 (cond
10660 ((not context) (user-error "No link found"))
10661 ;; Exception: open timestamps and links in properties
10662 ;; drawers, keywords and comments.
10663 ((memq type '(comment comment-block keyword node-property))
10664 (call-interactively #'org-open-at-point-global))
10665 ;; On a headline or an inlinetask, but not on a timestamp,
10666 ;; a link, a footnote reference or on tags.
10667 ((and (memq type '(headline inlinetask))
10668 ;; Not on tags.
10669 (let ((case-fold-search nil))
10670 (save-excursion
10671 (beginning-of-line)
10672 (looking-at org-complex-heading-regexp))
10673 (or (not (match-beginning 5))
10674 (< (point) (match-beginning 5)))))
10675 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10676 (links (car data))
10677 (links-end (cdr data)))
10678 (if links
10679 (dolist (link (if (stringp links) (list links) links))
10680 (search-forward link nil links-end)
10681 (goto-char (match-beginning 0))
10682 (org-open-at-point))
10683 (require 'org-attach)
10684 (org-attach-reveal 'if-exists))))
10685 ;; On a clock line, make sure point is on the timestamp
10686 ;; before opening it.
10687 ((and (eq type 'clock)
10688 value
10689 (>= (point) (org-element-property :begin value))
10690 (<= (point) (org-element-property :end value)))
10691 (org-follow-timestamp-link))
10692 ;; Do nothing on white spaces after an object.
10693 ((>= (point)
10694 (save-excursion
10695 (goto-char (org-element-property :end context))
10696 (skip-chars-backward " \t")
10697 (point)))
10698 (user-error "No link found"))
10699 ((eq type 'timestamp) (org-follow-timestamp-link))
10700 ;; On tags within a headline or an inlinetask.
10701 ((and (memq type '(headline inlinetask))
10702 (let ((case-fold-search nil))
10703 (save-excursion (beginning-of-line)
10704 (looking-at org-complex-heading-regexp))
10705 (and (match-beginning 5)
10706 (>= (point) (match-beginning 5)))))
10707 (org-tags-view arg (substring (match-string 5) 0 -1)))
10708 ((eq type 'link)
10709 (let ((type (org-element-property :type context))
10710 (path (org-link-unescape (org-element-property :path context))))
10711 ;; Switch back to REFERENCE-BUFFER needed when called in
10712 ;; a temporary buffer through `org-open-link-from-string'.
10713 (with-current-buffer (or reference-buffer (current-buffer))
10714 (cond
10715 ((equal type "file")
10716 (if (string-match "[*?{]" (file-name-nondirectory path))
10717 (dired path)
10718 ;; Look into `org-link-parameters' in order to find
10719 ;; a DEDICATED-FUNCTION to open file. The function
10720 ;; will be applied on raw link instead of parsed
10721 ;; link due to the limitation in `org-add-link-type'
10722 ;; ("open" function called with a single argument).
10723 ;; If no such function is found, fallback to
10724 ;; `org-open-file'.
10725 (let* ((option (org-element-property :search-option context))
10726 (app (org-element-property :application context))
10727 (dedicated-function
10728 (org-link-get-parameter
10729 (if app (concat type "+" app) type)
10730 :follow)))
10731 (if dedicated-function
10732 (funcall dedicated-function
10733 (concat path
10734 (and option (concat "::" option))))
10735 (apply #'org-open-file
10736 path
10737 (cond (arg)
10738 ((equal app "emacs") 'emacs)
10739 ((equal app "sys") 'system))
10740 (cond ((not option) nil)
10741 ((string-match-p "\\`[0-9]+\\'" option)
10742 (list (string-to-number option)))
10743 (t (list nil
10744 (org-link-unescape option)))))))))
10745 ((functionp (org-link-get-parameter type :follow))
10746 (funcall (org-link-get-parameter type :follow) path))
10747 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10748 (unless (run-hook-with-args-until-success
10749 'org-open-link-functions path)
10750 (if (not arg) (org-mark-ring-push)
10751 (switch-to-buffer-other-window
10752 (org-get-buffer-for-internal-link (current-buffer))))
10753 (let ((destination
10754 (org-with-wide-buffer
10755 (if (equal type "radio")
10756 (org-search-radio-target
10757 (org-element-property :path context))
10758 (org-link-search
10759 (if (member type '("custom-id" "coderef"))
10760 (org-element-property :raw-link context)
10761 path)
10762 ;; Prevent fuzzy links from matching
10763 ;; themselves.
10764 (and (equal type "fuzzy")
10765 (+ 2 (org-element-property :begin context)))))
10766 (point))))
10767 (unless (and (<= (point-min) destination)
10768 (>= (point-max) destination))
10769 (widen))
10770 (goto-char destination))))
10771 (t (browse-url-at-point))))))
10772 ;; On a footnote reference or at a footnote definition's label.
10773 ((or (eq type 'footnote-reference)
10774 (and (eq type 'footnote-definition)
10775 (save-excursion
10776 ;; Do not validate action when point is on the
10777 ;; spaces right after the footnote label, in
10778 ;; order to be on par with behaviour on links.
10779 (skip-chars-forward " \t")
10780 (let ((begin
10781 (org-element-property :contents-begin context)))
10782 (if begin (< (point) begin)
10783 (= (org-element-property :post-affiliated context)
10784 (line-beginning-position)))))))
10785 (org-footnote-action))
10786 (t (user-error "No link found")))))
10787 (run-hook-with-args 'org-follow-link-hook)))
10789 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10790 "Offer links in the current entry and return the selected link.
10791 If there is only one link, return it.
10792 If NTH is an integer, return the NTH link found.
10793 If ZERO is a string, check also this string for a link, and if
10794 there is one, return it."
10795 (with-current-buffer buffer
10796 (org-with-wide-buffer
10797 (goto-char marker)
10798 (let ((cnt ?0)
10799 have-zero end links link c)
10800 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10801 (push (match-string 0 zero) links)
10802 (setq cnt (1- cnt) have-zero t))
10803 (save-excursion
10804 (org-back-to-heading t)
10805 (setq end (save-excursion (outline-next-heading) (point)))
10806 (while (re-search-forward org-any-link-re end t)
10807 (push (match-string 0) links))
10808 (setq links (org-uniquify (reverse links))))
10809 (cond
10810 ((null links)
10811 (message "No links"))
10812 ((equal (length links) 1)
10813 (setq link (car links)))
10814 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10815 (setq link (nth (if have-zero nth (1- nth)) links)))
10816 (t ; we have to select a link
10817 (save-excursion
10818 (save-window-excursion
10819 (delete-other-windows)
10820 (with-output-to-temp-buffer "*Select Link*"
10821 (dolist (l links)
10822 (cond
10823 ((not (string-match org-bracket-link-regexp l))
10824 (princ (format "[%c] %s\n" (cl-incf cnt)
10825 (org-unbracket-string "<" ">" l))))
10826 ((match-end 3)
10827 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10828 (match-string 3 l) (match-string 1 l))))
10829 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10830 (match-string 1 l)))))))
10831 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10832 (message "Select link to open, RET to open all:")
10833 (setq c (read-char-exclusive))
10834 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10835 (when (equal c ?q) (user-error "Abort"))
10836 (if (equal c ?\C-m)
10837 (setq link links)
10838 (setq nth (- c ?0))
10839 (when have-zero (setq nth (1+ nth)))
10840 (unless (and (integerp nth) (>= (length links) nth))
10841 (user-error "Invalid link selection"))
10842 (setq link (nth (1- nth) links)))))
10843 (cons link end)))))
10845 ;; TODO: These functions are deprecated since `org-open-at-point'
10846 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10847 (defun org-open-file-with-system (path)
10848 "Open file at PATH using the system way of opening it."
10849 (org-open-file path 'system))
10850 (defun org-open-file-with-emacs (path)
10851 "Open file at PATH in Emacs."
10852 (org-open-file path 'emacs))
10855 ;;; File search
10857 (defvar org-create-file-search-functions nil
10858 "List of functions to construct the right search string for a file link.
10859 These functions are called in turn with point at the location to
10860 which the link should point.
10862 A function in the hook should first test if it would like to
10863 handle this file type, for example by checking the `major-mode'
10864 or the file extension. If it decides not to handle this file, it
10865 should just return nil to give other functions a chance. If it
10866 does handle the file, it must return the search string to be used
10867 when following the link. The search string will be part of the
10868 file link, given after a double colon, and `org-open-at-point'
10869 will automatically search for it. If special measures must be
10870 taken to make the search successful, another function should be
10871 added to the companion hook `org-execute-file-search-functions',
10872 which see.
10874 A function in this hook may also use `setq' to set the variable
10875 `description' to provide a suggestion for the descriptive text to
10876 be used for this link when it gets inserted into an Org buffer
10877 with \\[org-insert-link].")
10879 (defvar org-execute-file-search-functions nil
10880 "List of functions to execute a file search triggered by a link.
10882 Functions added to this hook must accept a single argument, the
10883 search string that was part of the file link, the part after the
10884 double colon. The function must first check if it would like to
10885 handle this search, for example by checking the `major-mode' or
10886 the file extension. If it decides not to handle this search, it
10887 should just return nil to give other functions a chance. If it
10888 does handle the search, it must return a non-nil value to keep
10889 other functions from trying.
10891 Each function can access the current prefix argument through the
10892 variable `current-prefix-arg'. Note that a single prefix is used
10893 to force opening a link in Emacs, so it may be good to only use a
10894 numeric or double prefix to guide the search function.
10896 In case this is needed, a function in this hook can also restore
10897 the window configuration before `org-open-at-point' was called using:
10899 (set-window-configuration org-window-config-before-follow-link)")
10901 (defun org-search-radio-target (target)
10902 "Search a radio target matching TARGET in current buffer.
10903 White spaces are not significant."
10904 (let ((re (format "<<<%s>>>"
10905 (mapconcat #'regexp-quote
10906 (org-split-string target "[ \t\n]+")
10907 "[ \t]+\\(?:\n[ \t]*\\)?")))
10908 (origin (point)))
10909 (goto-char (point-min))
10910 (catch :radio-match
10911 (while (re-search-forward re nil t)
10912 (backward-char)
10913 (let ((object (org-element-context)))
10914 (when (eq (org-element-type object) 'radio-target)
10915 (goto-char (org-element-property :begin object))
10916 (org-show-context 'link-search)
10917 (throw :radio-match nil))))
10918 (goto-char origin)
10919 (user-error "No match for radio target: %s" target))))
10921 (defun org-link-search (s &optional avoid-pos stealth)
10922 "Search for a search string S.
10924 If S starts with \"#\", it triggers a custom ID search.
10926 If S is enclosed within parenthesis, it initiates a coderef
10927 search.
10929 If S is surrounded by forward slashes, it is interpreted as
10930 a regular expression. In Org mode files, this will create an
10931 `org-occur' sparse tree. In ordinary files, `occur' will be used
10932 to list matches. If the current buffer is in `dired-mode', grep
10933 will be used to search in all files.
10935 When AVOID-POS is given, ignore matches near that position.
10937 When optional argument STEALTH is non-nil, do not modify
10938 visibility around point, thus ignoring `org-show-context-detail'
10939 variable.
10941 Search is case-insensitive and ignores white spaces. Return type
10942 of matched result, which is either `dedicated' or `fuzzy'."
10943 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10944 (let* ((case-fold-search t)
10945 (origin (point))
10946 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10947 (starred (eq (string-to-char normalized) ?*))
10948 (words (split-string (if starred (substring s 1) s)))
10949 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
10950 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10951 type)
10952 (cond
10953 ;; Check if there are any special search functions.
10954 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10955 ((eq (string-to-char s) ?#)
10956 ;; Look for a custom ID S if S starts with "#".
10957 (let* ((id (substring normalized 1))
10958 (match (org-find-property "CUSTOM_ID" id)))
10959 (if match (progn (goto-char match) (setf type 'dedicated))
10960 (error "No match for custom ID: %s" id))))
10961 ((string-match "\\`(\\(.*\\))\\'" normalized)
10962 ;; Look for coderef targets if S is enclosed within parenthesis.
10963 (let ((coderef (match-string-no-properties 1 normalized))
10964 (re (substring s-single-re 1 -1)))
10965 (goto-char (point-min))
10966 (catch :coderef-match
10967 (while (re-search-forward re nil t)
10968 (let ((element (org-element-at-point)))
10969 (when (and (memq (org-element-type element)
10970 '(example-block src-block))
10971 ;; Build proper regexp according to current
10972 ;; block's label format.
10973 (let ((label-fmt
10974 (regexp-quote
10975 (or (org-element-property :label-fmt element)
10976 org-coderef-label-format))))
10977 (save-excursion
10978 (beginning-of-line)
10979 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10980 (format label-fmt coderef))))))
10981 (setq type 'dedicated)
10982 (goto-char (match-beginning 1))
10983 (throw :coderef-match nil))))
10984 (goto-char origin)
10985 (error "No match for coderef: %s" coderef))))
10986 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10987 ;; Look for a regular expression.
10988 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10989 (match-string 1 s)))
10990 ;; From here, we handle fuzzy links.
10992 ;; Look for targets, only if not in a headline search.
10993 ((and (not starred)
10994 (let ((target (format "<<%s>>" s-multi-re)))
10995 (catch :target-match
10996 (goto-char (point-min))
10997 (while (re-search-forward target nil t)
10998 (backward-char)
10999 (let ((context (org-element-context)))
11000 (when (eq (org-element-type context) 'target)
11001 (setq type 'dedicated)
11002 (goto-char (org-element-property :begin context))
11003 (throw :target-match t))))
11004 nil))))
11005 ;; Look for elements named after S, only if not in a headline
11006 ;; search.
11007 ((and (not starred)
11008 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11009 (catch :name-match
11010 (goto-char (point-min))
11011 (while (re-search-forward name nil t)
11012 (let ((element (org-element-at-point)))
11013 (when (equal words
11014 (split-string
11015 (org-element-property :name element)))
11016 (setq type 'dedicated)
11017 (beginning-of-line)
11018 (throw :name-match t))))
11019 nil))))
11020 ;; Regular text search. Prefer headlines in Org mode buffers.
11021 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11022 ;; statistics cookies and tags.
11023 ((and (derived-mode-p 'org-mode)
11024 (let ((title-re
11025 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11026 org-outline-regexp-bol
11027 org-comment-string
11028 (mapconcat #'regexp-quote words ".+")))
11029 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11030 (comment-re (eval-when-compile
11031 (format "\\`%s[ \t]+" org-comment-string))))
11032 (goto-char (point-min))
11033 (catch :found
11034 (while (re-search-forward title-re nil t)
11035 (when (equal words
11036 (split-string
11037 (replace-regexp-in-string
11038 cookie-re ""
11039 (replace-regexp-in-string
11040 comment-re "" (org-get-heading t t t)))))
11041 (throw :found t)))
11042 nil)))
11043 (beginning-of-line)
11044 (setq type 'dedicated))
11045 ;; Offer to create non-existent headline depending on
11046 ;; `org-link-search-must-match-exact-headline'.
11047 ((and (derived-mode-p 'org-mode)
11048 (not org-link-search-inhibit-query)
11049 (eq org-link-search-must-match-exact-headline 'query-to-create)
11050 (yes-or-no-p "No match - create this as a new heading? "))
11051 (goto-char (point-max))
11052 (unless (bolp) (newline))
11053 (org-insert-heading nil t t)
11054 (insert s "\n")
11055 (beginning-of-line 0))
11056 ;; Only headlines are looked after. No need to process
11057 ;; further: throw an error.
11058 ((and (derived-mode-p 'org-mode)
11059 (or starred org-link-search-must-match-exact-headline))
11060 (goto-char origin)
11061 (error "No match for fuzzy expression: %s" normalized))
11062 ;; Regular text search.
11063 ((catch :fuzzy-match
11064 (goto-char (point-min))
11065 (while (re-search-forward s-multi-re nil t)
11066 ;; Skip match if it contains AVOID-POS or it is included in
11067 ;; a link with a description but outside the description.
11068 (unless (or (and avoid-pos
11069 (<= (match-beginning 0) avoid-pos)
11070 (> (match-end 0) avoid-pos))
11071 (and (save-match-data
11072 (org-in-regexp org-bracket-link-regexp))
11073 (match-beginning 3)
11074 (or (> (match-beginning 3) (point))
11075 (<= (match-end 3) (point)))
11076 (org-element-lineage
11077 (save-match-data (org-element-context))
11078 '(link) t)))
11079 (goto-char (match-beginning 0))
11080 (setq type 'fuzzy)
11081 (throw :fuzzy-match t)))
11082 nil))
11083 ;; All failed. Throw an error.
11084 (t (goto-char origin)
11085 (error "No match for fuzzy expression: %s" normalized)))
11086 ;; Disclose surroundings of match, if appropriate.
11087 (when (and (derived-mode-p 'org-mode) (not stealth))
11088 (org-show-context 'link-search))
11089 type))
11091 (defun org-get-buffer-for-internal-link (buffer)
11092 "Return a buffer to be used for displaying the link target of internal links."
11093 (cond
11094 ((not org-display-internal-link-with-indirect-buffer)
11095 buffer)
11096 ((string-suffix-p "(Clone)" (buffer-name buffer))
11097 (message "Buffer is already a clone, not making another one")
11098 ;; we also do not modify visibility in this case
11099 buffer)
11100 (t ; make a new indirect buffer for displaying the link
11101 (let* ((bn (buffer-name buffer))
11102 (ibn (concat bn "(Clone)"))
11103 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11104 (with-current-buffer ib (org-overview))
11105 ib))))
11107 (defun org-do-occur (regexp &optional cleanup)
11108 "Call the Emacs command `occur'.
11109 If CLEANUP is non-nil, remove the printout of the regular expression
11110 in the *Occur* buffer. This is useful if the regex is long and not useful
11111 to read."
11112 (occur regexp)
11113 (when cleanup
11114 (let ((cwin (selected-window)) win beg end)
11115 (when (setq win (get-buffer-window "*Occur*"))
11116 (select-window win))
11117 (goto-char (point-min))
11118 (when (re-search-forward "match[a-z]+" nil t)
11119 (setq beg (match-end 0))
11120 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11121 (setq end (1- (match-beginning 0)))))
11122 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11123 (goto-char (point-min))
11124 (select-window cwin))))
11126 ;;; The mark ring for links jumps
11128 (defvar org-mark-ring nil
11129 "Mark ring for positions before jumps in Org mode.")
11130 (defvar org-mark-ring-last-goto nil
11131 "Last position in the mark ring used to go back.")
11132 ;; Fill and close the ring
11133 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11134 (dotimes (_ org-mark-ring-length)
11135 (push (make-marker) org-mark-ring))
11136 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11137 org-mark-ring)
11139 (defun org-mark-ring-push (&optional pos buffer)
11140 "Put the current position or POS into the mark ring and rotate it."
11141 (interactive)
11142 (setq pos (or pos (point)))
11143 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11144 (move-marker (car org-mark-ring)
11145 (or pos (point))
11146 (or buffer (current-buffer)))
11147 (message "%s"
11148 (substitute-command-keys
11149 "Position saved to mark ring, go back with \
11150 `\\[org-mark-ring-goto]'.")))
11152 (defun org-mark-ring-goto (&optional n)
11153 "Jump to the previous position in the mark ring.
11154 With prefix arg N, jump back that many stored positions. When
11155 called several times in succession, walk through the entire ring.
11156 Org mode commands jumping to a different position in the current file,
11157 or to another Org file, automatically push the old position onto the ring."
11158 (interactive "p")
11159 (let (p m)
11160 (if (eq last-command this-command)
11161 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11162 (setq p org-mark-ring))
11163 (setq org-mark-ring-last-goto p)
11164 (setq m (car p))
11165 (pop-to-buffer-same-window (marker-buffer m))
11166 (goto-char m)
11167 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11169 (defun org-add-angle-brackets (s)
11170 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11171 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11174 ;;; Following specific links
11176 (defvar org-agenda-buffer-tmp-name)
11177 (defvar org-agenda-start-on-weekday)
11178 (defun org-follow-timestamp-link ()
11179 "Open an agenda view for the time-stamp date/range at point."
11180 (cond
11181 ((org-at-date-range-p t)
11182 (let ((org-agenda-start-on-weekday)
11183 (t1 (match-string 1))
11184 (t2 (match-string 2)) tt1 tt2)
11185 (setq tt1 (time-to-days (org-time-string-to-time t1))
11186 tt2 (time-to-days (org-time-string-to-time t2)))
11187 (let ((org-agenda-buffer-tmp-name
11188 (format "*Org Agenda(a:%s)"
11189 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11190 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11191 ((org-at-timestamp-p t)
11192 (let ((org-agenda-buffer-tmp-name
11193 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11194 (org-agenda-list nil (time-to-days (org-time-string-to-time
11195 (substring (match-string 1) 0 10)))
11196 1)))
11197 (t (error "This should not happen"))))
11200 ;;; Following file links
11201 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11202 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11203 (declare-function mailcap-mime-info
11204 "mailcap" (string &optional request no-decode))
11205 (defvar org-wait nil)
11206 (defun org-open-file (path &optional in-emacs line search)
11207 "Open the file at PATH.
11208 First, this expands any special file name abbreviations. Then the
11209 configuration variable `org-file-apps' is checked if it contains an
11210 entry for this file type, and if yes, the corresponding command is launched.
11212 If no application is found, Emacs simply visits the file.
11214 With optional prefix argument IN-EMACS, Emacs will visit the file.
11215 With a double \\[universal-argument] \\[universal-argument] \
11216 prefix arg, Org tries to avoid opening in Emacs
11217 and to use an external application to visit the file.
11219 Optional LINE specifies a line to go to, optional SEARCH a string
11220 to search for. If LINE or SEARCH is given, the file will be
11221 opened in Emacs, unless an entry from org-file-apps that makes
11222 use of groups in a regexp matches.
11224 If you want to change the way frames are used when following a
11225 link, please customize `org-link-frame-setup'.
11227 If the file does not exist, an error is thrown."
11228 (let* ((file (if (equal path "")
11229 buffer-file-name
11230 (substitute-in-file-name (expand-file-name path))))
11231 (file-apps (append org-file-apps (org-default-apps)))
11232 (apps (cl-remove-if
11233 'org-file-apps-entry-match-against-dlink-p file-apps))
11234 (apps-dlink (cl-remove-if-not
11235 'org-file-apps-entry-match-against-dlink-p file-apps))
11236 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11237 (dirp (unless remp (file-directory-p file)))
11238 (file (if (and dirp org-open-directory-means-index-dot-org)
11239 (concat (file-name-as-directory file) "index.org")
11240 file))
11241 (a-m-a-p (assq 'auto-mode apps))
11242 (dfile (downcase file))
11243 ;; Reconstruct the original link from the PATH, LINE and
11244 ;; SEARCH args.
11245 (link (cond (line (concat file "::" (number-to-string line)))
11246 (search (concat file "::" search))
11247 (t file)))
11248 (dlink (downcase link))
11249 (ext
11250 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11251 (match-string 1 dfile)))
11252 (save-position-maybe
11253 (let ((old-buffer (current-buffer))
11254 (old-pos (point))
11255 (old-mode major-mode))
11256 (lambda ()
11257 (and (derived-mode-p 'org-mode)
11258 (eq old-mode 'org-mode)
11259 (or (not (eq old-buffer (current-buffer)))
11260 (not (eq old-pos (point))))
11261 (org-mark-ring-push old-pos old-buffer)))))
11262 cmd link-match-data)
11263 (cond
11264 ((member in-emacs '((16) system))
11265 (setq cmd (cdr (assq 'system apps))))
11266 (in-emacs (setq cmd 'emacs))
11268 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11269 (and dirp (cdr (assq 'directory apps)))
11270 ;; First, try matching against apps-dlink if we
11271 ;; get a match here, store the match data for
11272 ;; later.
11273 (let ((match (assoc-default dlink apps-dlink
11274 'string-match)))
11275 (if match
11276 (progn (setq link-match-data (match-data))
11277 match)
11278 (progn (setq in-emacs (or in-emacs line search))
11279 nil))) ; if we have no match in apps-dlink,
11280 ; always open the file in emacs if line or search
11281 ; is given (for backwards compatibility)
11282 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11283 'string-match)
11284 (cdr (assoc ext apps))
11285 (cdr (assq t apps))))))
11286 (when (eq cmd 'system)
11287 (setq cmd (cdr (assq 'system apps))))
11288 (when (eq cmd 'default)
11289 (setq cmd (cdr (assoc t apps))))
11290 (when (eq cmd 'mailcap)
11291 (require 'mailcap)
11292 (mailcap-parse-mailcaps)
11293 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11294 (command (mailcap-mime-info mime-type)))
11295 (if (stringp command)
11296 (setq cmd command)
11297 (setq cmd 'emacs))))
11298 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11299 (not (file-exists-p file))
11300 (not org-open-non-existing-files))
11301 (user-error "No such file: %s" file))
11302 (cond
11303 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11304 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11305 (while (string-match "['\"]%s['\"]" cmd)
11306 (setq cmd (replace-match "%s" t t cmd)))
11307 (setq cmd (replace-regexp-in-string
11308 "%s"
11309 (shell-quote-argument (convert-standard-filename file))
11311 nil t))
11313 ;; Replace "%1", "%2" etc. in command with group matches from regex
11314 (save-match-data
11315 (let ((match-index 1)
11316 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11317 (set-match-data link-match-data)
11318 (while (<= match-index number-of-groups)
11319 (let ((regex (concat "%" (number-to-string match-index)))
11320 (replace-with (match-string match-index dlink)))
11321 (while (string-match regex cmd)
11322 (setq cmd (replace-match replace-with t t cmd))))
11323 (setq match-index (+ match-index 1)))))
11325 (save-window-excursion
11326 (message "Running %s...done" cmd)
11327 (start-process-shell-command cmd nil cmd)
11328 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11329 ((or (stringp cmd)
11330 (eq cmd 'emacs))
11331 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11332 (widen)
11333 (cond (line (org-goto-line line)
11334 (when (derived-mode-p 'org-mode) (org-reveal)))
11335 (search (condition-case err
11336 (org-link-search search)
11337 ;; Save position before error-ing out so user
11338 ;; can easily move back to the original buffer.
11339 (error (funcall save-position-maybe)
11340 (error (nth 1 err)))))))
11341 ((functionp cmd)
11342 (save-match-data
11343 (set-match-data link-match-data)
11344 (condition-case nil
11345 (funcall cmd file link)
11346 ;; FIXME: Remove this check when most default installations
11347 ;; of Emacs have at least Org 9.0.
11348 ((debug wrong-number-of-arguments wrong-type-argument
11349 invalid-function)
11350 (user-error "Please see Org News for version 9.0 about \
11351 `org-file-apps'--Lisp error: %S" cmd)))))
11352 ((consp cmd)
11353 ;; FIXME: Remove this check when most default installations of
11354 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11355 ;; fall back to `org-link-frame-setup' for an old usage of
11356 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11357 (user-error "Please see Org News for version 9.0 about \
11358 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11359 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11360 (funcall save-position-maybe)))
11362 (defun org-file-apps-entry-match-against-dlink-p (entry)
11363 "This function returns non-nil if `entry' uses a regular
11364 expression which should be matched against the whole link by
11365 org-open-file.
11367 It assumes that is the case when the entry uses a regular
11368 expression which has at least one grouping construct and the
11369 action is either a lisp form or a command string containing
11370 `%1', i.e. using at least one subexpression match as a
11371 parameter."
11372 (let ((selector (car entry))
11373 (action (cdr entry)))
11374 (if (stringp selector)
11375 (and (> (regexp-opt-depth selector) 0)
11376 (or (and (stringp action)
11377 (string-match "%[0-9]" action))
11378 (consp action)))
11379 nil)))
11381 (defun org-default-apps ()
11382 "Return the default applications for this operating system."
11383 (cond
11384 ((eq system-type 'darwin)
11385 org-file-apps-defaults-macosx)
11386 ((eq system-type 'windows-nt)
11387 org-file-apps-defaults-windowsnt)
11388 (t org-file-apps-defaults-gnu)))
11390 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11391 "Convert extensions to regular expressions in the cars of LIST.
11392 Also, weed out any non-string entries, because the return value is used
11393 only for regexp matching.
11394 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11395 point to the symbol `emacs', indicating that the file should
11396 be opened in Emacs."
11397 (append
11398 (delq nil
11399 (mapcar (lambda (x)
11400 (unless (not (stringp (car x)))
11401 (if (string-match "\\W" (car x))
11403 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11404 list))
11405 (when add-auto-mode
11406 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11408 (defvar ange-ftp-name-format)
11409 (defun org-file-remote-p (file)
11410 "Test whether FILE specifies a location on a remote system.
11411 Return non-nil if the location is indeed remote.
11413 For example, the filename \"/user@host:/foo\" specifies a location
11414 on the system \"/user@host:\"."
11415 (cond ((fboundp 'file-remote-p)
11416 (file-remote-p file))
11417 ((fboundp 'tramp-handle-file-remote-p)
11418 (tramp-handle-file-remote-p file))
11419 ((and (boundp 'ange-ftp-name-format)
11420 (string-match (car ange-ftp-name-format) file))
11421 t)))
11424 ;;;; Refiling
11426 (defun org-get-org-file ()
11427 "Read a filename, with default directory `org-directory'."
11428 (let ((default (or org-default-notes-file remember-data-file)))
11429 (read-file-name (format "File name [%s]: " default)
11430 (file-name-as-directory org-directory)
11431 default)))
11433 (defun org-notes-order-reversed-p ()
11434 "Check if the current file should receive notes in reversed order."
11435 (cond
11436 ((not org-reverse-note-order) nil)
11437 ((eq t org-reverse-note-order) t)
11438 ((not (listp org-reverse-note-order)) nil)
11439 (t (catch 'exit
11440 (dolist (entry org-reverse-note-order)
11441 (when (string-match (car entry) buffer-file-name)
11442 (throw 'exit (cdr entry))))))))
11444 (defvar org-refile-target-table nil
11445 "The list of refile targets, created by `org-refile'.")
11447 (defvar org-agenda-new-buffers nil
11448 "Buffers created to visit agenda files.")
11450 (defvar org-refile-cache nil
11451 "Cache for refile targets.")
11453 (defvar org-refile-markers nil
11454 "All the markers used for caching refile locations.")
11456 (defun org-refile-marker (pos)
11457 "Get a new refile marker, but only if caching is in use."
11458 (if (not org-refile-use-cache)
11460 (let ((m (make-marker)))
11461 (move-marker m pos)
11462 (push m org-refile-markers)
11463 m)))
11465 (defun org-refile-cache-clear ()
11466 "Clear the refile cache and disable all the markers."
11467 (dolist (m org-refile-markers) (move-marker m nil))
11468 (setq org-refile-markers nil)
11469 (setq org-refile-cache nil)
11470 (message "Refile cache has been cleared"))
11472 (defun org-refile-cache-check-set (set)
11473 "Check if all the markers in the cache still have live buffers."
11474 (let (marker)
11475 (catch 'exit
11476 (while (and set (setq marker (nth 3 (pop set))))
11477 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11478 (when (and marker (null (marker-buffer marker)))
11479 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11480 (sit-for 3)
11481 (throw 'exit nil)))
11482 t)))
11484 (defun org-refile-cache-put (set &rest identifiers)
11485 "Push the refile targets SET into the cache, under IDENTIFIERS."
11486 (let* ((key (sha1 (prin1-to-string identifiers)))
11487 (entry (assoc key org-refile-cache)))
11488 (if entry
11489 (setcdr entry set)
11490 (push (cons key set) org-refile-cache))))
11492 (defun org-refile-cache-get (&rest identifiers)
11493 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11494 (cond
11495 ((not org-refile-cache) nil)
11496 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11498 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11499 org-refile-cache))))
11500 (and set (org-refile-cache-check-set set) set)))))
11502 (defvar org-outline-path-cache nil
11503 "Alist between buffer positions and outline paths.
11504 It value is an alist (POSITION . PATH) where POSITION is the
11505 buffer position at the beginning of an entry and PATH is a list
11506 of strings describing the outline path for that entry, in reverse
11507 order.")
11509 (defun org-refile-get-targets (&optional default-buffer)
11510 "Produce a table with refile targets."
11511 (let ((case-fold-search nil)
11512 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11513 (entries (or org-refile-targets '((nil . (:level . 1)))))
11514 targets tgs files desc descre)
11515 (message "Getting targets...")
11516 (with-current-buffer (or default-buffer (current-buffer))
11517 (dolist (entry entries)
11518 (setq files (car entry) desc (cdr entry))
11519 (cond
11520 ((null files) (setq files (list (current-buffer))))
11521 ((eq files 'org-agenda-files)
11522 (setq files (org-agenda-files 'unrestricted)))
11523 ((and (symbolp files) (fboundp files))
11524 (setq files (funcall files)))
11525 ((and (symbolp files) (boundp files))
11526 (setq files (symbol-value files))))
11527 (when (stringp files) (setq files (list files)))
11528 (cond
11529 ((eq (car desc) :tag)
11530 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11531 ((eq (car desc) :todo)
11532 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11533 ((eq (car desc) :regexp)
11534 (setq descre (cdr desc)))
11535 ((eq (car desc) :level)
11536 (setq descre (concat "^\\*\\{" (number-to-string
11537 (if org-odd-levels-only
11538 (1- (* 2 (cdr desc)))
11539 (cdr desc)))
11540 "\\}[ \t]")))
11541 ((eq (car desc) :maxlevel)
11542 (setq descre (concat "^\\*\\{1," (number-to-string
11543 (if org-odd-levels-only
11544 (1- (* 2 (cdr desc)))
11545 (cdr desc)))
11546 "\\}[ \t]")))
11547 (t (error "Bad refiling target description %s" desc)))
11548 (dolist (f files)
11549 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11551 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11552 (progn
11553 (when (bufferp f)
11554 (setq f (buffer-file-name (buffer-base-buffer f))))
11555 (setq f (and f (expand-file-name f)))
11556 (when (eq org-refile-use-outline-path 'file)
11557 (push (list (file-name-nondirectory f) f nil nil) tgs))
11558 (org-with-wide-buffer
11559 (goto-char (point-min))
11560 (setq org-outline-path-cache nil)
11561 (while (re-search-forward descre nil t)
11562 (beginning-of-line)
11563 (let ((case-fold-search nil))
11564 (looking-at org-complex-heading-regexp))
11565 (let ((begin (point))
11566 (heading (match-string-no-properties 4)))
11567 (unless (or (and
11568 org-refile-target-verify-function
11569 (not
11570 (funcall org-refile-target-verify-function)))
11571 (not heading))
11572 (let ((re (format org-complex-heading-regexp-format
11573 (regexp-quote heading)))
11574 (target
11575 (if (not org-refile-use-outline-path) heading
11576 (mapconcat
11577 #'org-protect-slash
11578 (append
11579 (pcase org-refile-use-outline-path
11580 (`file (list (file-name-nondirectory
11581 (buffer-file-name
11582 (buffer-base-buffer)))))
11583 (`full-file-path
11584 (list (buffer-file-name
11585 (buffer-base-buffer))))
11586 (_ nil))
11587 (org-get-outline-path t t))
11588 "/"))))
11589 (push (list target f re (org-refile-marker (point)))
11590 tgs)))
11591 (when (= (point) begin)
11592 ;; Verification function has not moved point.
11593 (end-of-line)))))))
11594 (when org-refile-use-cache
11595 (org-refile-cache-put tgs (buffer-file-name) descre))
11596 (setq targets (append tgs targets))))))
11597 (message "Getting targets...done")
11598 (nreverse targets)))
11600 (defun org-protect-slash (s)
11601 (replace-regexp-in-string "/" "\\/" s nil t))
11603 (defun org--get-outline-path-1 (&optional use-cache)
11604 "Return outline path to current headline.
11606 Outline path is a list of strings, in reverse order. When
11607 optional argument USE-CACHE is non-nil, make use of a cache. See
11608 `org-get-outline-path' for details.
11610 Assume buffer is widened and point is on a headline."
11611 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11612 (let ((p (point))
11613 (heading (let ((case-fold-search nil))
11614 (looking-at org-complex-heading-regexp)
11615 (if (not (match-end 4)) ""
11616 ;; Remove statistics cookies.
11617 (org-trim
11618 (org-link-display-format
11619 (replace-regexp-in-string
11620 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11621 (match-string-no-properties 4))))))))
11622 (if (org-up-heading-safe)
11623 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11624 (when use-cache
11625 (push (cons p path) org-outline-path-cache))
11626 path)
11627 ;; This is a new root node. Since we assume we are moving
11628 ;; forward, we can drop previous cache so as to limit number
11629 ;; of associations there.
11630 (let ((path (list heading)))
11631 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11632 path)))))
11634 (defun org-get-outline-path (&optional with-self use-cache)
11635 "Return the outline path to the current entry.
11637 An outline path is a list of ancestors for current headline, as
11638 a list of strings. Statistics cookies are removed and links are
11639 replaced with their description, if any, or their path otherwise.
11641 When optional argument WITH-SELF is non-nil, the path also
11642 includes the current headline.
11644 When optional argument USE-CACHE is non-nil, cache outline paths
11645 between calls to this function so as to avoid backtracking. This
11646 argument is useful when planning to find more than one outline
11647 path in the same document. In that case, there are two
11648 conditions to satisfy:
11649 - `org-outline-path-cache' is set to nil before starting the
11650 process;
11651 - outline paths are computed by increasing buffer positions."
11652 (org-with-wide-buffer
11653 (and (or (and with-self (org-back-to-heading t))
11654 (org-up-heading-safe))
11655 (reverse (org--get-outline-path-1 use-cache)))))
11657 (defun org-format-outline-path (path &optional width prefix separator)
11658 "Format the outline path PATH for display.
11659 WIDTH is the maximum number of characters that is available.
11660 PREFIX is a prefix to be included in the returned string,
11661 such as the file name.
11662 SEPARATOR is inserted between the different parts of the path,
11663 the default is \"/\"."
11664 (setq width (or width 79))
11665 (setq path (delq nil path))
11666 (unless (> width 0)
11667 (user-error "Argument `width' must be positive"))
11668 (setq separator (or separator "/"))
11669 (let* ((org-odd-levels-only nil)
11670 (fpath (concat
11671 prefix (and prefix path separator)
11672 (mapconcat
11673 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11674 (cl-loop for head in path
11675 for n from 0
11676 collect (org-add-props
11677 head nil 'face
11678 (nth (% n org-n-level-faces) org-level-faces)))
11679 separator))))
11680 (when (> (length fpath) width)
11681 (if (< width 7)
11682 ;; It's unlikely that `width' will be this small, but don't
11683 ;; waste characters by adding ".." if it is.
11684 (setq fpath (substring fpath 0 width))
11685 (setf (substring fpath (- width 2)) "..")))
11686 fpath))
11688 (defun org-display-outline-path (&optional file current separator just-return-string)
11689 "Display the current outline path in the echo area.
11691 If FILE is non-nil, prepend the output with the file name.
11692 If CURRENT is non-nil, append the current heading to the output.
11693 SEPARATOR is passed through to `org-format-outline-path'. It separates
11694 the different parts of the path and defaults to \"/\".
11695 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11696 (interactive "P")
11697 (let* (case-fold-search
11698 (bfn (buffer-file-name (buffer-base-buffer)))
11699 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11700 res)
11701 (when current (setq path (append path
11702 (save-excursion
11703 (org-back-to-heading t)
11704 (when (looking-at org-complex-heading-regexp)
11705 (list (match-string 4)))))))
11706 (setq res
11707 (org-format-outline-path
11708 path
11709 (1- (frame-width))
11710 (and file bfn (concat (file-name-nondirectory bfn) separator))
11711 separator))
11712 (if just-return-string
11713 (org-no-properties res)
11714 (org-unlogged-message "%s" res))))
11716 (defvar org-refile-history nil
11717 "History for refiling operations.")
11719 (defvar org-after-refile-insert-hook nil
11720 "Hook run after `org-refile' has inserted its stuff at the new location.
11721 Note that this is still *before* the stuff will be removed from
11722 the *old* location.")
11724 (defvar org-capture-last-stored-marker)
11725 (defvar org-refile-keep nil
11726 "Non-nil means `org-refile' will copy instead of refile.")
11728 (defun org-copy ()
11729 "Like `org-refile', but copy."
11730 (interactive)
11731 (let ((org-refile-keep t))
11732 (funcall 'org-refile nil nil nil "Copy")))
11734 (defun org-refile (&optional arg default-buffer rfloc msg)
11735 "Move the entry or entries at point to another heading.
11737 The list of target headings is compiled using the information in
11738 `org-refile-targets', which see.
11740 At the target location, the entry is filed as a subitem of the
11741 target heading. Depending on `org-reverse-note-order', the new
11742 subitem will either be the first or the last subitem.
11744 If there is an active region, all entries in that region will be
11745 refiled. However, the region must fulfill the requirement that
11746 the first heading sets the top-level of the moved text.
11748 With a `\\[universal-argument]' ARG, the command will only visit the target \
11749 location
11750 and not actually move anything.
11752 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11753 location where the last
11754 refiling operation has put the subtree.
11756 With a numeric prefix argument of `2', refile to the running clock.
11758 With a numeric prefix argument of `3', emulate `org-refile-keep'
11759 being set to t and copy to the target location, don't move it.
11760 Beware that keeping refiled entries may result in duplicated ID
11761 properties.
11763 RFLOC can be a refile location obtained in a different way.
11765 MSG is a string to replace \"Refile\" in the default prompt with
11766 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11768 See also `org-refile-use-outline-path'.
11770 If you are using target caching (see `org-refile-use-cache'), you
11771 have to clear the target cache in order to find new targets.
11772 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11773 prefix argument (`C-u C-u C-u C-c C-w')."
11774 (interactive "P")
11775 (if (member arg '(0 (64)))
11776 (org-refile-cache-clear)
11777 (let* ((actionmsg (cond (msg msg)
11778 ((equal arg 3) "Refile (and keep)")
11779 (t "Refile")))
11780 (regionp (org-region-active-p))
11781 (region-start (and regionp (region-beginning)))
11782 (region-end (and regionp (region-end)))
11783 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11784 pos it nbuf file level reversed)
11785 (setq last-command nil)
11786 (when regionp
11787 (goto-char region-start)
11788 (or (bolp) (goto-char (point-at-bol)))
11789 (setq region-start (point))
11790 (unless (or (org-kill-is-subtree-p
11791 (buffer-substring region-start region-end))
11792 (prog1 org-refile-active-region-within-subtree
11793 (let ((s (point-at-eol)))
11794 (org-toggle-heading)
11795 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11796 (user-error "The region is not a (sequence of) subtree(s)")))
11797 (if (equal arg '(16))
11798 (org-refile-goto-last-stored)
11799 (when (or
11800 (and (equal arg 2)
11801 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11802 (prog1
11803 (setq it (list (or org-clock-heading "running clock")
11804 (buffer-file-name
11805 (marker-buffer org-clock-hd-marker))
11807 (marker-position org-clock-hd-marker)))
11808 (setq arg nil)))
11809 (setq it
11810 (or rfloc
11811 (let (heading-text)
11812 (save-excursion
11813 (unless (and arg (listp arg))
11814 (org-back-to-heading t)
11815 (setq heading-text
11816 (replace-regexp-in-string
11817 org-bracket-link-regexp
11818 "\\3"
11819 (or (nth 4 (org-heading-components))
11820 ""))))
11821 (org-refile-get-location
11822 (cond ((and arg (listp arg)) "Goto")
11823 (regionp (concat actionmsg " region to"))
11824 (t (concat actionmsg " subtree \""
11825 heading-text "\" to")))
11826 default-buffer
11827 (and (not (equal '(4) arg))
11828 org-refile-allow-creating-parent-nodes)))))))
11829 (setq file (nth 1 it)
11830 pos (nth 3 it))
11831 (when (and (not arg)
11833 (equal (buffer-file-name) file)
11834 (if regionp
11835 (and (>= pos region-start)
11836 (<= pos region-end))
11837 (and (>= pos (point))
11838 (< pos (save-excursion
11839 (org-end-of-subtree t t))))))
11840 (error "Cannot refile to position inside the tree or region"))
11841 (setq nbuf (or (find-buffer-visiting file)
11842 (find-file-noselect file)))
11843 (if (and arg (not (equal arg 3)))
11844 (progn
11845 (pop-to-buffer-same-window nbuf)
11846 (goto-char pos)
11847 (org-show-context 'org-goto))
11848 (if regionp
11849 (progn
11850 (org-kill-new (buffer-substring region-start region-end))
11851 (org-save-markers-in-region region-start region-end))
11852 (org-copy-subtree 1 nil t))
11853 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11854 (find-file-noselect file)))
11855 (setq reversed (org-notes-order-reversed-p))
11856 (org-with-wide-buffer
11857 (if pos
11858 (progn
11859 (goto-char pos)
11860 (setq level (org-get-valid-level (funcall outline-level) 1))
11861 (goto-char
11862 (if reversed
11863 (or (outline-next-heading) (point-max))
11864 (or (save-excursion (org-get-next-sibling))
11865 (org-end-of-subtree t t)
11866 (point-max)))))
11867 (setq level 1)
11868 (if (not reversed)
11869 (goto-char (point-max))
11870 (goto-char (point-min))
11871 (or (outline-next-heading) (goto-char (point-max)))))
11872 (unless (bolp) (newline))
11873 (org-paste-subtree level nil nil t)
11874 (when org-log-refile
11875 (org-add-log-setup 'refile nil nil org-log-refile)
11876 (unless (eq org-log-refile 'note)
11877 (save-excursion (org-add-log-note))))
11878 (and org-auto-align-tags
11879 (let ((org-loop-over-headlines-in-active-region nil))
11880 (org-set-tags nil t)))
11881 (let ((bookmark-name (plist-get org-bookmark-names-plist
11882 :last-refile)))
11883 (when bookmark-name
11884 (with-demoted-errors
11885 (bookmark-set bookmark-name))))
11886 ;; If we are refiling for capture, make sure that the
11887 ;; last-capture pointers point here
11888 (when (bound-and-true-p org-capture-is-refiling)
11889 (let ((bookmark-name (plist-get org-bookmark-names-plist
11890 :last-capture-marker)))
11891 (when bookmark-name
11892 (with-demoted-errors
11893 (bookmark-set bookmark-name))))
11894 (move-marker org-capture-last-stored-marker (point)))
11895 (when (fboundp 'deactivate-mark) (deactivate-mark))
11896 (run-hooks 'org-after-refile-insert-hook)))
11897 (unless org-refile-keep
11898 (if regionp
11899 (delete-region (point) (+ (point) (- region-end region-start)))
11900 (delete-region
11901 (and (org-back-to-heading t) (point))
11902 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11903 (when (featurep 'org-inlinetask)
11904 (org-inlinetask-remove-END-maybe))
11905 (setq org-markers-to-move nil)
11906 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11908 (defun org-refile-goto-last-stored ()
11909 "Go to the location where the last refile was stored."
11910 (interactive)
11911 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11912 (message "This is the location of the last refile"))
11914 (defun org-refile--get-location (refloc tbl)
11915 "When user refile to REFLOC, find the associated target in TBL.
11916 Also check `org-refile-target-table'."
11917 (car (delq
11919 (mapcar
11920 (lambda (r) (or (assoc r tbl)
11921 (assoc r org-refile-target-table)))
11922 (list (replace-regexp-in-string "/$" "" refloc)
11923 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11925 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11926 "Prompt the user for a refile location, using PROMPT.
11927 PROMPT should not be suffixed with a colon and a space, because
11928 this function appends the default value from
11929 `org-refile-history' automatically, if that is not empty."
11930 (let ((org-refile-targets org-refile-targets)
11931 (org-refile-use-outline-path org-refile-use-outline-path))
11932 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11933 (unless org-refile-target-table
11934 (user-error "No refile targets"))
11935 (let* ((cbuf (current-buffer))
11936 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11937 (cfunc (if (and org-refile-use-outline-path
11938 org-outline-path-complete-in-steps)
11939 #'org-olpath-completing-read
11940 #'completing-read))
11941 (extra (if org-refile-use-outline-path "/" ""))
11942 (cbnex (concat (buffer-name) extra))
11943 (filename (and cfn (expand-file-name cfn)))
11944 (tbl (mapcar
11945 (lambda (x)
11946 (if (and (not (member org-refile-use-outline-path
11947 '(file full-file-path)))
11948 (not (equal filename (nth 1 x))))
11949 (cons (concat (car x) extra " ("
11950 (file-name-nondirectory (nth 1 x)) ")")
11951 (cdr x))
11952 (cons (concat (car x) extra) (cdr x))))
11953 org-refile-target-table))
11954 (completion-ignore-case t)
11955 cdef
11956 (prompt (concat prompt
11957 (or (and (car org-refile-history)
11958 (concat " (default " (car org-refile-history) ")"))
11959 (and (assoc cbnex tbl) (setq cdef cbnex)
11960 (concat " (default " cbnex ")"))) ": "))
11961 pa answ parent-target child parent old-hist)
11962 (setq old-hist org-refile-history)
11963 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11964 nil 'org-refile-history (or cdef (car org-refile-history))))
11965 (if (setq pa (org-refile--get-location answ tbl))
11966 (progn
11967 (org-refile-check-position pa)
11968 (when (or (not org-refile-history)
11969 (not (eq old-hist org-refile-history))
11970 (not (equal (car pa) (car org-refile-history))))
11971 (setq org-refile-history
11972 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11973 org-refile-history
11974 (cdr org-refile-history))))
11975 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11976 (pop org-refile-history)))
11978 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11979 (progn
11980 (setq parent (match-string 1 answ)
11981 child (match-string 2 answ))
11982 (setq parent-target (org-refile--get-location parent tbl))
11983 (when (and parent-target
11984 (or (eq new-nodes t)
11985 (and (eq new-nodes 'confirm)
11986 (y-or-n-p (format "Create new node \"%s\"? "
11987 child)))))
11988 (org-refile-new-child parent-target child)))
11989 (user-error "Invalid target location")))))
11991 (declare-function org-string-nw-p "org-macs" (s))
11992 (defun org-refile-check-position (refile-pointer)
11993 "Check if the refile pointer matches the headline to which it points."
11994 (let* ((file (nth 1 refile-pointer))
11995 (re (nth 2 refile-pointer))
11996 (pos (nth 3 refile-pointer))
11997 buffer)
11998 (if (and (not (markerp pos)) (not file))
11999 (user-error "Please indicate a target file in the refile path")
12000 (when (org-string-nw-p re)
12001 (setq buffer (if (markerp pos)
12002 (marker-buffer pos)
12003 (or (find-buffer-visiting file)
12004 (find-file-noselect file))))
12005 (with-current-buffer buffer
12006 (org-with-wide-buffer
12007 (goto-char pos)
12008 (beginning-of-line 1)
12009 (unless (looking-at-p re)
12010 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12012 (defun org-refile-new-child (parent-target child)
12013 "Use refile target PARENT-TARGET to add new CHILD below it."
12014 (unless parent-target
12015 (error "Cannot find parent for new node"))
12016 (let ((file (nth 1 parent-target))
12017 (pos (nth 3 parent-target))
12018 level)
12019 (with-current-buffer (or (find-buffer-visiting file)
12020 (find-file-noselect file))
12021 (org-with-wide-buffer
12022 (if pos
12023 (goto-char pos)
12024 (goto-char (point-max))
12025 (unless (bolp) (newline)))
12026 (when (looking-at org-outline-regexp)
12027 (setq level (funcall outline-level))
12028 (org-end-of-subtree t t))
12029 (org-back-over-empty-lines)
12030 (insert "\n" (make-string
12031 (if pos (org-get-valid-level level 1) 1) ?*)
12032 " " child "\n")
12033 (beginning-of-line 0)
12034 (list (concat (car parent-target) "/" child) file "" (point))))))
12036 (defun org-olpath-completing-read (prompt collection &rest args)
12037 "Read an outline path like a file name."
12038 (let ((thetable collection))
12039 (apply #'completing-read
12040 prompt
12041 (lambda (string predicate &optional flag)
12042 (cond
12043 ((eq flag nil) (try-completion string thetable))
12044 ((eq flag t)
12045 (let ((l (length string)))
12046 (mapcar (lambda (x)
12047 (let ((r (substring x l))
12048 (f (if (string-match " ([^)]*)$" x)
12049 (match-string 0 x)
12050 "")))
12051 (if (string-match "/" r)
12052 (concat string (substring r 0 (match-end 0)) f)
12053 x)))
12054 (all-completions string thetable predicate))))
12055 ;; Exact match?
12056 ((eq flag 'lambda) (assoc string thetable))))
12057 args)))
12059 ;;;; Dynamic blocks
12061 (defun org-find-dblock (name)
12062 "Find the first dynamic block with name NAME in the buffer.
12063 If not found, stay at current position and return nil."
12064 (let ((case-fold-search t) pos)
12065 (save-excursion
12066 (goto-char (point-min))
12067 (setq pos (and (re-search-forward
12068 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12069 (match-beginning 0))))
12070 (when pos (goto-char pos))
12071 pos))
12073 (defun org-create-dblock (plist)
12074 "Create a dynamic block section, with parameters taken from PLIST.
12075 PLIST must contain a :name entry which is used as the name of the block."
12076 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12077 (end-of-line 1)
12078 (newline))
12079 (let ((col (current-column))
12080 (name (plist-get plist :name)))
12081 (insert "#+BEGIN: " name)
12082 (while plist
12083 (if (eq (car plist) :name)
12084 (setq plist (cddr plist))
12085 (insert " " (prin1-to-string (pop plist)))))
12086 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12087 (beginning-of-line -2)))
12089 (defun org-prepare-dblock ()
12090 "Prepare dynamic block for refresh.
12091 This empties the block, puts the cursor at the insert position and returns
12092 the property list including an extra property :name with the block name."
12093 (unless (looking-at org-dblock-start-re)
12094 (user-error "Not at a dynamic block"))
12095 (let* ((begdel (1+ (match-end 0)))
12096 (name (org-no-properties (match-string 1)))
12097 (params (append (list :name name)
12098 (read (concat "(" (match-string 3) ")")))))
12099 (save-excursion
12100 (beginning-of-line 1)
12101 (skip-chars-forward " \t")
12102 (setq params (plist-put params :indentation-column (current-column))))
12103 (unless (re-search-forward org-dblock-end-re nil t)
12104 (error "Dynamic block not terminated"))
12105 (setq params
12106 (append params
12107 (list :content (buffer-substring
12108 begdel (match-beginning 0)))))
12109 (delete-region begdel (match-beginning 0))
12110 (goto-char begdel)
12111 (open-line 1)
12112 params))
12114 (defun org-map-dblocks (&optional command)
12115 "Apply COMMAND to all dynamic blocks in the current buffer.
12116 If COMMAND is not given, use `org-update-dblock'."
12117 (let ((cmd (or command 'org-update-dblock)))
12118 (save-excursion
12119 (goto-char (point-min))
12120 (while (re-search-forward org-dblock-start-re nil t)
12121 (goto-char (match-beginning 0))
12122 (save-excursion
12123 (condition-case nil
12124 (funcall cmd)
12125 (error (message "Error during update of dynamic block"))))
12126 (unless (re-search-forward org-dblock-end-re nil t)
12127 (error "Dynamic block not terminated"))))))
12129 (defun org-dblock-update (&optional arg)
12130 "User command for updating dynamic blocks.
12131 Update the dynamic block at point. With prefix ARG, update all dynamic
12132 blocks in the buffer."
12133 (interactive "P")
12134 (if arg
12135 (org-update-all-dblocks)
12136 (or (looking-at org-dblock-start-re)
12137 (org-beginning-of-dblock))
12138 (org-update-dblock)))
12140 (defun org-update-dblock ()
12141 "Update the dynamic block at point.
12142 This means to empty the block, parse for parameters and then call
12143 the correct writing function."
12144 (interactive)
12145 (save-excursion
12146 (let* ((win (selected-window))
12147 (pos (point))
12148 (line (org-current-line))
12149 (params (org-prepare-dblock))
12150 (name (plist-get params :name))
12151 (indent (plist-get params :indentation-column))
12152 (cmd (intern (concat "org-dblock-write:" name))))
12153 (message "Updating dynamic block `%s' at line %d..." name line)
12154 (funcall cmd params)
12155 (message "Updating dynamic block `%s' at line %d...done" name line)
12156 (goto-char pos)
12157 (when (and indent (> indent 0))
12158 (setq indent (make-string indent ?\ ))
12159 (save-excursion
12160 (select-window win)
12161 (org-beginning-of-dblock)
12162 (forward-line 1)
12163 (while (not (looking-at org-dblock-end-re))
12164 (insert indent)
12165 (beginning-of-line 2))
12166 (when (looking-at org-dblock-end-re)
12167 (and (looking-at "[ \t]+")
12168 (replace-match ""))
12169 (insert indent)))))))
12171 (defun org-beginning-of-dblock ()
12172 "Find the beginning of the dynamic block at point.
12173 Error if there is no such block at point."
12174 (let ((pos (point))
12175 beg)
12176 (end-of-line 1)
12177 (if (and (re-search-backward org-dblock-start-re nil t)
12178 (setq beg (match-beginning 0))
12179 (re-search-forward org-dblock-end-re nil t)
12180 (> (match-end 0) pos))
12181 (goto-char beg)
12182 (goto-char pos)
12183 (error "Not in a dynamic block"))))
12185 (defun org-update-all-dblocks ()
12186 "Update all dynamic blocks in the buffer.
12187 This function can be used in a hook."
12188 (interactive)
12189 (when (derived-mode-p 'org-mode)
12190 (org-map-dblocks 'org-update-dblock)))
12193 ;;;; Completion
12195 (declare-function org-export-backend-options "ox" (cl-x) t)
12196 (defun org-get-export-keywords ()
12197 "Return a list of all currently understood export keywords.
12198 Export keywords include options, block names, attributes and
12199 keywords relative to each registered export back-end."
12200 (let (keywords)
12201 (dolist (backend
12202 (bound-and-true-p org-export-registered-backends)
12203 (delq nil keywords))
12204 ;; Back-end name (for keywords, like #+LATEX:)
12205 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12206 (dolist (option-entry (org-export-backend-options backend))
12207 ;; Back-end options.
12208 (push (nth 1 option-entry) keywords)))))
12210 (defconst org-options-keywords
12211 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12212 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12213 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12214 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12215 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12217 (defcustom org-structure-template-alist
12218 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12219 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12220 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12221 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12222 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12223 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12224 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12225 ("L" "#+LaTeX: ")
12226 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12227 ("H" "#+HTML: ")
12228 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12229 ("A" "#+ASCII: ")
12230 ("i" "#+INDEX: ?")
12231 ("I" "#+INCLUDE: %file ?"))
12232 "Structure completion elements.
12233 This is a list of abbreviation keys and values. The value gets inserted
12234 if you type `<' followed by the key and then press the completion key,
12235 usually `TAB'. %file will be replaced by a file name after prompting
12236 for the file using completion. The cursor will be placed at the position
12237 of the `?' in the template.
12238 There are two templates for each key, the first uses the original Org syntax,
12239 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12240 the default when the /org-mtags.el/ module has been loaded. See also the
12241 variable `org-mtags-prefer-muse-templates'."
12242 :group 'org-completion
12243 :type '(repeat
12244 (list
12245 (string :tag "Key")
12246 (string :tag "Template")))
12247 :version "26.1"
12248 :package-version '(Org . "8.3"))
12250 (defun org-try-structure-completion ()
12251 "Try to complete a structure template before point.
12252 This looks for strings like \"<e\" on an otherwise empty line and
12253 expands them."
12254 (let ((l (buffer-substring (point-at-bol) (point)))
12256 (when (and (looking-at "[ \t]*$")
12257 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12258 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12259 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12260 (match-beginning 1)) a)
12261 t)))
12263 (defun org-complete-expand-structure-template (start cell)
12264 "Expand a structure template."
12265 (let ((rpl (nth 1 cell))
12266 (ind ""))
12267 (delete-region start (point))
12268 (when (string-match "\\`[ \t]*#\\+" rpl)
12269 (cond
12270 ((bolp))
12271 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12272 (setq ind (buffer-substring (point-at-bol) (point))))
12273 (t (newline))))
12274 (setq start (point))
12275 (when (string-match "%file" rpl)
12276 (setq rpl (replace-match
12277 (concat
12278 "\""
12279 (save-match-data
12280 (abbreviate-file-name (read-file-name "Include file: ")))
12281 "\"")
12282 t t rpl)))
12283 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12284 (concat "\n" ind)))
12285 (insert rpl)
12286 (when (re-search-backward "\\?" start t) (delete-char 1))))
12288 ;;;; TODO, DEADLINE, Comments
12290 (defun org-toggle-comment ()
12291 "Change the COMMENT state of an entry."
12292 (interactive)
12293 (save-excursion
12294 (org-back-to-heading)
12295 (let ((case-fold-search nil))
12296 (looking-at org-complex-heading-regexp))
12297 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12298 (skip-chars-forward " \t")
12299 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12300 (if (org-in-commented-heading-p t)
12301 (delete-region (point)
12302 (progn (search-forward " " (line-end-position) 'move)
12303 (skip-chars-forward " \t")
12304 (point)))
12305 (insert org-comment-string)
12306 (unless (eolp) (insert " ")))))
12308 (defvar org-last-todo-state-is-todo nil
12309 "This is non-nil when the last TODO state change led to a TODO state.
12310 If the last change removed the TODO tag or switched to DONE, then
12311 this is nil.")
12313 (defvar org-setting-tags nil) ; dynamically skipped
12315 (defvar org-todo-setup-filter-hook nil
12316 "Hook for functions that pre-filter todo specs.
12317 Each function takes a todo spec and returns either nil or the spec
12318 transformed into canonical form." )
12320 (defvar org-todo-get-default-hook nil
12321 "Hook for functions that get a default item for todo.
12322 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12323 nil or a string to be used for the todo mark." )
12325 (defvar org-agenda-headline-snapshot-before-repeat)
12327 (defun org-current-effective-time ()
12328 "Return current time adjusted for `org-extend-today-until' variable."
12329 (let* ((ct (org-current-time))
12330 (dct (decode-time ct))
12331 (ct1
12332 (cond
12333 (org-use-last-clock-out-time-as-effective-time
12334 (or (org-clock-get-last-clock-out-time) ct))
12335 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12336 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12337 (t ct))))
12338 ct1))
12340 (defun org-todo-yesterday (&optional arg)
12341 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12342 (interactive "P")
12343 (if (eq major-mode 'org-agenda-mode)
12344 (apply 'org-agenda-todo-yesterday arg)
12345 (let* ((org-use-effective-time t)
12346 (hour (nth 2 (decode-time (org-current-time))))
12347 (org-extend-today-until (1+ hour)))
12348 (org-todo arg))))
12350 (defvar org-block-entry-blocking ""
12351 "First entry preventing the TODO state change.")
12353 (defun org-cancel-repeater ()
12354 "Cancel a repeater by setting its numeric value to zero."
12355 (interactive)
12356 (save-excursion
12357 (org-back-to-heading t)
12358 (let ((bound1 (point))
12359 (bound0 (save-excursion (outline-next-heading) (point))))
12360 (when (and (re-search-forward
12361 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12362 org-deadline-time-regexp "\\)\\|\\("
12363 org-ts-regexp "\\)")
12364 bound0 t)
12365 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12366 bound1 t))
12367 (replace-match "0" t nil nil 1)))))
12369 (defvar org-state) ;; dynamically scoped into this function
12370 (defun org-todo (&optional arg)
12371 "Change the TODO state of an item.
12373 The state of an item is given by a keyword at the start of the heading,
12374 like
12375 *** TODO Write paper
12376 *** DONE Call mom
12378 The different keywords are specified in the variable `org-todo-keywords'.
12379 By default the available states are \"TODO\" and \"DONE\". So, for this
12380 example: when the item starts with TODO, it is changed to DONE.
12381 When it starts with DONE, the DONE is removed. And when neither TODO nor
12382 DONE are present, add TODO at the beginning of the heading.
12384 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12385 state.
12386 With numeric prefix ARG, switch to that state.
12387 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12388 next set of TODO \
12389 keywords (nextset).
12390 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12391 prefix, circumvent any state blocking.
12392 With a numeric prefix arg of 0, inhibit note taking for the change.
12393 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12395 When called through ELisp, arg is also interpreted in the following way:
12396 `none' -> empty state
12397 \"\" -> switch to empty state
12398 `done' -> switch to DONE
12399 `nextset' -> switch to the next set of keywords
12400 `previousset' -> switch to the previous set of keywords
12401 \"WAITING\" -> switch to the specified keyword, but only if it
12402 really is a member of `org-todo-keywords'."
12403 (interactive "P")
12404 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12405 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12406 'region-start-level 'region))
12407 org-loop-over-headlines-in-active-region)
12408 (org-map-entries
12409 `(org-todo ,arg)
12410 org-loop-over-headlines-in-active-region
12411 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12412 (when (equal arg '(16)) (setq arg 'nextset))
12413 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12414 (let ((org-blocker-hook org-blocker-hook)
12415 commentp
12416 case-fold-search)
12417 (when (equal arg '(64))
12418 (setq arg nil org-blocker-hook nil))
12419 (when (and org-blocker-hook
12420 (or org-inhibit-blocking
12421 (org-entry-get nil "NOBLOCKING")))
12422 (setq org-blocker-hook nil))
12423 (save-excursion
12424 (catch 'exit
12425 (org-back-to-heading t)
12426 (when (org-in-commented-heading-p t)
12427 (org-toggle-comment)
12428 (setq commentp t))
12429 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12430 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12431 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12432 (let* ((match-data (match-data))
12433 (startpos (point-at-bol))
12434 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12435 (org-log-done org-log-done)
12436 (org-log-repeat org-log-repeat)
12437 (org-todo-log-states org-todo-log-states)
12438 (org-inhibit-logging
12439 (if (equal arg 0)
12440 (progn (setq arg nil) 'note) org-inhibit-logging))
12441 (this (match-string 1))
12442 (hl-pos (match-beginning 0))
12443 (head (org-get-todo-sequence-head this))
12444 (ass (assoc head org-todo-kwd-alist))
12445 (interpret (nth 1 ass))
12446 (done-word (nth 3 ass))
12447 (final-done-word (nth 4 ass))
12448 (org-last-state (or this ""))
12449 (completion-ignore-case t)
12450 (member (member this org-todo-keywords-1))
12451 (tail (cdr member))
12452 (org-state (cond
12453 ((and org-todo-key-trigger
12454 (or (and (equal arg '(4))
12455 (eq org-use-fast-todo-selection 'prefix))
12456 (and (not arg) org-use-fast-todo-selection
12457 (not (eq org-use-fast-todo-selection
12458 'prefix)))))
12459 ;; Use fast selection
12460 (org-fast-todo-selection))
12461 ((and (equal arg '(4))
12462 (or (not org-use-fast-todo-selection)
12463 (not org-todo-key-trigger)))
12464 ;; Read a state with completion
12465 (completing-read
12466 "State: " (mapcar #'list org-todo-keywords-1)
12467 nil t))
12468 ((eq arg 'right)
12469 (if this
12470 (if tail (car tail) nil)
12471 (car org-todo-keywords-1)))
12472 ((eq arg 'left)
12473 (unless (equal member org-todo-keywords-1)
12474 (if this
12475 (nth (- (length org-todo-keywords-1)
12476 (length tail) 2)
12477 org-todo-keywords-1)
12478 (org-last org-todo-keywords-1))))
12479 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12480 (setq arg nil))) ; hack to fall back to cycling
12481 (arg
12482 ;; user or caller requests a specific state
12483 (cond
12484 ((equal arg "") nil)
12485 ((eq arg 'none) nil)
12486 ((eq arg 'done) (or done-word (car org-done-keywords)))
12487 ((eq arg 'nextset)
12488 (or (car (cdr (member head org-todo-heads)))
12489 (car org-todo-heads)))
12490 ((eq arg 'previousset)
12491 (let ((org-todo-heads (reverse org-todo-heads)))
12492 (or (car (cdr (member head org-todo-heads)))
12493 (car org-todo-heads))))
12494 ((car (member arg org-todo-keywords-1)))
12495 ((stringp arg)
12496 (user-error "State `%s' not valid in this file" arg))
12497 ((nth (1- (prefix-numeric-value arg))
12498 org-todo-keywords-1))))
12499 ((null member) (or head (car org-todo-keywords-1)))
12500 ((equal this final-done-word) nil) ;; -> make empty
12501 ((null tail) nil) ;; -> first entry
12502 ((memq interpret '(type priority))
12503 (if (eq this-command last-command)
12504 (car tail)
12505 (if (> (length tail) 0)
12506 (or done-word (car org-done-keywords))
12507 nil)))
12509 (car tail))))
12510 (org-state (or
12511 (run-hook-with-args-until-success
12512 'org-todo-get-default-hook org-state org-last-state)
12513 org-state))
12514 (next (if org-state (concat " " org-state " ") " "))
12515 (change-plist (list :type 'todo-state-change :from this :to org-state
12516 :position startpos))
12517 dolog now-done-p)
12518 (when org-blocker-hook
12519 (setq org-last-todo-state-is-todo
12520 (not (member this org-done-keywords)))
12521 (unless (save-excursion
12522 (save-match-data
12523 (org-with-wide-buffer
12524 (run-hook-with-args-until-failure
12525 'org-blocker-hook change-plist))))
12526 (if (called-interactively-p 'interactive)
12527 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12528 this org-state org-block-entry-blocking)
12529 ;; fail silently
12530 (message "TODO state change from %s to %s blocked (by \"%s\")"
12531 this org-state org-block-entry-blocking)
12532 (throw 'exit nil))))
12533 (store-match-data match-data)
12534 (replace-match next t t)
12535 (cond ((equal this org-state)
12536 (message "TODO state was already %s" (org-trim next)))
12537 ((pos-visible-in-window-p hl-pos)
12538 (message "TODO state changed to %s" (org-trim next))))
12539 (unless head
12540 (setq head (org-get-todo-sequence-head org-state)
12541 ass (assoc head org-todo-kwd-alist)
12542 interpret (nth 1 ass)
12543 done-word (nth 3 ass)
12544 final-done-word (nth 4 ass)))
12545 (when (memq arg '(nextset previousset))
12546 (message "Keyword-Set %d/%d: %s"
12547 (- (length org-todo-sets) -1
12548 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12549 (length org-todo-sets)
12550 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12551 (setq org-last-todo-state-is-todo
12552 (not (member org-state org-done-keywords)))
12553 (setq now-done-p (and (member org-state org-done-keywords)
12554 (not (member this org-done-keywords))))
12555 (and logging (org-local-logging logging))
12556 (when (and (or org-todo-log-states org-log-done)
12557 (not (eq org-inhibit-logging t))
12558 (not (memq arg '(nextset previousset))))
12559 ;; we need to look at recording a time and note
12560 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12561 (nth 2 (assoc this org-todo-log-states))))
12562 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12563 (setq dolog 'time))
12564 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12565 (and org-state
12566 (member org-state org-not-done-keywords)
12567 (not (member this org-not-done-keywords))))
12568 ;; This is now a todo state and was not one before
12569 ;; If there was a CLOSED time stamp, get rid of it.
12570 (org-add-planning-info nil nil 'closed))
12571 (when (and now-done-p org-log-done)
12572 ;; It is now done, and it was not done before
12573 (org-add-planning-info 'closed (org-current-effective-time))
12574 (when (and (not dolog) (eq 'note org-log-done))
12575 (org-add-log-setup 'done org-state this 'note)))
12576 (when (and org-state dolog)
12577 ;; This is a non-nil state, and we need to log it
12578 (org-add-log-setup 'state org-state this dolog)))
12579 ;; Fixup tag positioning
12580 (org-todo-trigger-tag-changes org-state)
12581 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12582 (when org-provide-todo-statistics
12583 (org-update-parent-todo-statistics))
12584 (run-hooks 'org-after-todo-state-change-hook)
12585 (when (and arg (not (member org-state org-done-keywords)))
12586 (setq head (org-get-todo-sequence-head org-state)))
12587 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12588 ;; Do we need to trigger a repeat?
12589 (when now-done-p
12590 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12591 ;; This is for the agenda, take a snapshot of the headline.
12592 (save-match-data
12593 (setq org-agenda-headline-snapshot-before-repeat
12594 (org-get-heading))))
12595 (org-auto-repeat-maybe org-state))
12596 ;; Fixup cursor location if close to the keyword
12597 (when (and (outline-on-heading-p)
12598 (not (bolp))
12599 (save-excursion (beginning-of-line 1)
12600 (looking-at org-todo-line-regexp))
12601 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12602 (goto-char (or (match-end 2) (match-end 1)))
12603 (and (looking-at " ") (just-one-space)))
12604 (when org-trigger-hook
12605 (save-excursion
12606 (run-hook-with-args 'org-trigger-hook change-plist)))
12607 (when commentp (org-toggle-comment))))))))
12609 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12610 "Block turning an entry into a TODO, using the hierarchy.
12611 This checks whether the current task should be blocked from state
12612 changes. Such blocking occurs when:
12614 1. The task has children which are not all in a completed state.
12616 2. A task has a parent with the property :ORDERED:, and there
12617 are siblings prior to the current task with incomplete
12618 status.
12620 3. The parent of the task is blocked because it has siblings that should
12621 be done first, or is child of a block grandparent TODO entry."
12623 (if (not org-enforce-todo-dependencies)
12624 t ; if locally turned off don't block
12625 (catch 'dont-block
12626 ;; If this is not a todo state change, or if this entry is already DONE,
12627 ;; do not block
12628 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12629 (member (plist-get change-plist :from)
12630 (cons 'done org-done-keywords))
12631 (member (plist-get change-plist :to)
12632 (cons 'todo org-not-done-keywords))
12633 (not (plist-get change-plist :to)))
12634 (throw 'dont-block t))
12635 ;; If this task has children, and any are undone, it's blocked
12636 (save-excursion
12637 (org-back-to-heading t)
12638 (let ((this-level (funcall outline-level)))
12639 (outline-next-heading)
12640 (let ((child-level (funcall outline-level)))
12641 (while (and (not (eobp))
12642 (> child-level this-level))
12643 ;; this todo has children, check whether they are all
12644 ;; completed
12645 (when (and (not (org-entry-is-done-p))
12646 (org-entry-is-todo-p))
12647 (setq org-block-entry-blocking (org-get-heading))
12648 (throw 'dont-block nil))
12649 (outline-next-heading)
12650 (setq child-level (funcall outline-level))))))
12651 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12652 ;; any previous siblings are undone, it's blocked
12653 (save-excursion
12654 (org-back-to-heading t)
12655 (let* ((pos (point))
12656 (parent-pos (and (org-up-heading-safe) (point)))
12657 (case-fold-search nil))
12658 (unless parent-pos (throw 'dont-block t)) ; no parent
12659 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12660 (forward-line 1)
12661 (re-search-forward org-not-done-heading-regexp pos t))
12662 (setq org-block-entry-blocking (match-string 0))
12663 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12664 ;; Search further up the hierarchy, to see if an ancestor is blocked
12665 (while t
12666 (goto-char parent-pos)
12667 (unless (looking-at org-not-done-heading-regexp)
12668 (throw 'dont-block t)) ; do not block, parent is not a TODO
12669 (setq pos (point))
12670 (setq parent-pos (and (org-up-heading-safe) (point)))
12671 (unless parent-pos (throw 'dont-block t)) ; no parent
12672 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12673 (forward-line 1)
12674 (re-search-forward org-not-done-heading-regexp pos t)
12675 (setq org-block-entry-blocking (org-get-heading)))
12676 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12678 (defcustom org-track-ordered-property-with-tag nil
12679 "Should the ORDERED property also be shown as a tag?
12680 The ORDERED property decides if an entry should require subtasks to be
12681 completed in sequence. Since a property is not very visible, setting
12682 this option means that toggling the ORDERED property with the command
12683 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12684 not relevant for the behavior, but it makes things more visible.
12686 Note that toggling the tag with tags commands will not change the property
12687 and therefore not influence behavior!
12689 This can be t, meaning the tag ORDERED should be used, It can also be a
12690 string to select a different tag for this task."
12691 :group 'org-todo
12692 :type '(choice
12693 (const :tag "No tracking" nil)
12694 (const :tag "Track with ORDERED tag" t)
12695 (string :tag "Use other tag")))
12697 (defun org-toggle-ordered-property ()
12698 "Toggle the ORDERED property of the current entry.
12699 For better visibility, you can track the value of this property with a tag.
12700 See variable `org-track-ordered-property-with-tag'."
12701 (interactive)
12702 (let* ((t1 org-track-ordered-property-with-tag)
12703 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12704 (save-excursion
12705 (org-back-to-heading)
12706 (if (org-entry-get nil "ORDERED")
12707 (progn
12708 (org-delete-property "ORDERED")
12709 (and tag (org-toggle-tag tag 'off))
12710 (message "Subtasks can be completed in arbitrary order"))
12711 (org-entry-put nil "ORDERED" "t")
12712 (and tag (org-toggle-tag tag 'on))
12713 (message "Subtasks must be completed in sequence")))))
12715 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12716 (defun org-block-todo-from-checkboxes (change-plist)
12717 "Block turning an entry into a TODO, using checkboxes.
12718 This checks whether the current task should be blocked from state
12719 changes because there are unchecked boxes in this entry."
12720 (if (not org-enforce-todo-checkbox-dependencies)
12721 t ; if locally turned off don't block
12722 (catch 'dont-block
12723 ;; If this is not a todo state change, or if this entry is already DONE,
12724 ;; do not block
12725 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12726 (member (plist-get change-plist :from)
12727 (cons 'done org-done-keywords))
12728 (member (plist-get change-plist :to)
12729 (cons 'todo org-not-done-keywords))
12730 (not (plist-get change-plist :to)))
12731 (throw 'dont-block t))
12732 ;; If this task has checkboxes that are not checked, it's blocked
12733 (save-excursion
12734 (org-back-to-heading t)
12735 (let ((beg (point)) end)
12736 (outline-next-heading)
12737 (setq end (point))
12738 (goto-char beg)
12739 (when (org-list-search-forward
12740 (concat (org-item-beginning-re)
12741 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12742 "\\[[- ]\\]")
12743 end t)
12744 (when (boundp 'org-blocked-by-checkboxes)
12745 (setq org-blocked-by-checkboxes t))
12746 (throw 'dont-block nil))))
12747 t))) ; do not block
12749 (defun org-entry-blocked-p ()
12750 "Non-nil if entry at point is blocked."
12751 (and (not (org-entry-get nil "NOBLOCKING"))
12752 (member (org-entry-get nil "TODO") org-not-done-keywords)
12753 (not (run-hook-with-args-until-failure
12754 'org-blocker-hook
12755 (list :type 'todo-state-change
12756 :position (point)
12757 :from 'todo
12758 :to 'done)))))
12760 (defun org-update-statistics-cookies (all)
12761 "Update the statistics cookie, either from TODO or from checkboxes.
12762 This should be called with the cursor in a line with a statistics
12763 cookie. When called with a \\[universal-argument] prefix, update
12764 all statistics cookies in the buffer."
12765 (interactive "P")
12766 (if all
12767 (progn
12768 (org-update-checkbox-count 'all)
12769 (org-map-entries 'org-update-parent-todo-statistics))
12770 (if (not (org-at-heading-p))
12771 (org-update-checkbox-count)
12772 (let ((pos (point-marker))
12773 end l1 l2)
12774 (ignore-errors (org-back-to-heading t))
12775 (if (not (org-at-heading-p))
12776 (org-update-checkbox-count)
12777 (setq l1 (org-outline-level))
12778 (setq end (save-excursion
12779 (outline-next-heading)
12780 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12781 (point)))
12782 (if (and (save-excursion
12783 (re-search-forward
12784 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12785 (not (save-excursion (re-search-forward
12786 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12787 (org-update-checkbox-count)
12788 (if (and l2 (> l2 l1))
12789 (progn
12790 (goto-char end)
12791 (org-update-parent-todo-statistics))
12792 (goto-char pos)
12793 (beginning-of-line 1)
12794 (while (re-search-forward
12795 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12796 (point-at-eol) t)
12797 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12798 (goto-char pos)
12799 (move-marker pos nil)))))
12801 (defvar org-entry-property-inherited-from) ;; defined below
12802 (defun org-update-parent-todo-statistics ()
12803 "Update any statistics cookie in the parent of the current headline.
12804 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12805 the entire subtree and this will travel up the hierarchy and update
12806 statistics everywhere."
12807 (let* ((prop (save-excursion (org-up-heading-safe)
12808 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12809 (recursive (or (not org-hierarchical-todo-statistics)
12810 (and prop (string-match "\\<recursive\\>" prop))))
12811 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12813 (first t)
12814 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12815 level ltoggle l1 new ndel
12816 (cnt-all 0) (cnt-done 0) is-percent kwd
12817 checkbox-beg cookie-present)
12818 (catch 'exit
12819 (save-excursion
12820 (beginning-of-line 1)
12821 (setq ltoggle (funcall outline-level))
12822 ;; Three situations are to consider:
12824 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12825 ;; to the top-level ancestor on the headline;
12827 ;; 2. If parent has "recursive" property, repeat up to the
12828 ;; headline setting that property, taking inheritance into
12829 ;; account;
12831 ;; 3. Else, move up to direct parent and proceed only once.
12832 (while (and (setq level (org-up-heading-safe))
12833 (or recursive first)
12834 (>= (point) lim))
12835 (setq first nil cookie-present nil)
12836 (unless (and level
12837 (not (string-match
12838 "\\<checkbox\\>"
12839 (downcase (or (org-entry-get nil "COOKIE_DATA")
12840 "")))))
12841 (throw 'exit nil))
12842 (while (re-search-forward box-re (point-at-eol) t)
12843 (setq cnt-all 0 cnt-done 0 cookie-present t)
12844 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12845 (save-match-data
12846 (unless (outline-next-heading) (throw 'exit nil))
12847 (while (and (looking-at org-complex-heading-regexp)
12848 (> (setq l1 (length (match-string 1))) level))
12849 (setq kwd (and (or recursive (= l1 ltoggle))
12850 (match-string 2)))
12851 (if (or (eq org-provide-todo-statistics 'all-headlines)
12852 (and (eq org-provide-todo-statistics t)
12853 (or (member kwd org-done-keywords)))
12854 (and (listp org-provide-todo-statistics)
12855 (stringp (car org-provide-todo-statistics))
12856 (or (member kwd org-provide-todo-statistics)
12857 (member kwd org-done-keywords)))
12858 (and (listp org-provide-todo-statistics)
12859 (listp (car org-provide-todo-statistics))
12860 (or (member kwd (car org-provide-todo-statistics))
12861 (and (member kwd org-done-keywords)
12862 (member kwd (cadr org-provide-todo-statistics))))))
12863 (setq cnt-all (1+ cnt-all))
12864 (and (eq org-provide-todo-statistics t)
12866 (setq cnt-all (1+ cnt-all))))
12867 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12868 (member kwd org-done-keywords))
12869 (and (listp org-provide-todo-statistics)
12870 (listp (car org-provide-todo-statistics))
12871 (member kwd org-done-keywords)
12872 (member kwd (cadr org-provide-todo-statistics)))
12873 (and (listp org-provide-todo-statistics)
12874 (stringp (car org-provide-todo-statistics))
12875 (member kwd org-done-keywords)))
12876 (setq cnt-done (1+ cnt-done)))
12877 (outline-next-heading)))
12878 (setq new
12879 (if is-percent
12880 (format "[%d%%]" (floor (* 100.0 cnt-done)
12881 (max 1 cnt-all)))
12882 (format "[%d/%d]" cnt-done cnt-all))
12883 ndel (- (match-end 0) checkbox-beg))
12884 (goto-char checkbox-beg)
12885 (insert new)
12886 (delete-region (point) (+ (point) ndel))
12887 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12888 (when cookie-present
12889 (run-hook-with-args 'org-after-todo-statistics-hook
12890 cnt-done (- cnt-all cnt-done))))))
12891 (run-hooks 'org-todo-statistics-hook)))
12893 (defvar org-after-todo-statistics-hook nil
12894 "Hook that is called after a TODO statistics cookie has been updated.
12895 Each function is called with two arguments: the number of not-done entries
12896 and the number of done entries.
12898 For example, the following function, when added to this hook, will switch
12899 an entry to DONE when all children are done, and back to TODO when new
12900 entries are set to a TODO status. Note that this hook is only called
12901 when there is a statistics cookie in the headline!
12903 (defun org-summary-todo (n-done n-not-done)
12904 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12905 (let (org-log-done org-log-states) ; turn off logging
12906 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12909 (defvar org-todo-statistics-hook nil
12910 "Hook that is run whenever Org thinks TODO statistics should be updated.
12911 This hook runs even if there is no statistics cookie present, in which case
12912 `org-after-todo-statistics-hook' would not run.")
12914 (defun org-todo-trigger-tag-changes (state)
12915 "Apply the changes defined in `org-todo-state-tags-triggers'."
12916 (let ((l org-todo-state-tags-triggers)
12917 changes)
12918 (when (or (not state) (equal state ""))
12919 (setq changes (append changes (cdr (assoc "" l)))))
12920 (when (and (stringp state) (> (length state) 0))
12921 (setq changes (append changes (cdr (assoc state l)))))
12922 (when (member state org-not-done-keywords)
12923 (setq changes (append changes (cdr (assq 'todo l)))))
12924 (when (member state org-done-keywords)
12925 (setq changes (append changes (cdr (assq 'done l)))))
12926 (dolist (c changes)
12927 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12929 (defun org-local-logging (value)
12930 "Get logging settings from a property VALUE."
12931 ;; Directly set the variables, they are already local.
12932 (setq org-log-done nil
12933 org-log-repeat nil
12934 org-todo-log-states nil)
12935 (dolist (w (org-split-string value))
12936 (let (a)
12937 (cond
12938 ((setq a (assoc w org-startup-options))
12939 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12940 (set (nth 1 a) (nth 2 a))))
12941 ((setq a (org-extract-log-state-settings w))
12942 (and (member (car a) org-todo-keywords-1)
12943 (push a org-todo-log-states)))))))
12945 (defun org-get-todo-sequence-head (kwd)
12946 "Return the head of the TODO sequence to which KWD belongs.
12947 If KWD is not set, check if there is a text property remembering the
12948 right sequence."
12949 (let (p)
12950 (cond
12951 ((not kwd)
12952 (or (get-text-property (point-at-bol) 'org-todo-head)
12953 (progn
12954 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12955 nil (point-at-eol)))
12956 (get-text-property p 'org-todo-head))))
12957 ((not (member kwd org-todo-keywords-1))
12958 (car org-todo-keywords-1))
12959 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12961 (defun org-fast-todo-selection ()
12962 "Fast TODO keyword selection with single keys.
12963 Returns the new TODO keyword, or nil if no state change should occur."
12964 (let* ((fulltable org-todo-key-alist)
12965 (done-keywords org-done-keywords) ;; needed for the faces.
12966 (maxlen (apply 'max (mapcar
12967 (lambda (x)
12968 (if (stringp (car x)) (string-width (car x)) 0))
12969 fulltable)))
12970 (expert nil)
12971 (fwidth (+ maxlen 3 1 3))
12972 (ncol (/ (- (window-width) 4) fwidth))
12973 tg cnt e c tbl
12974 groups ingroup)
12975 (save-excursion
12976 (save-window-excursion
12977 (if expert
12978 (set-buffer (get-buffer-create " *Org todo*"))
12979 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12980 (erase-buffer)
12981 (setq-local org-done-keywords done-keywords)
12982 (setq tbl fulltable cnt 0)
12983 (while (setq e (pop tbl))
12984 (cond
12985 ((equal e '(:startgroup))
12986 (push '() groups) (setq ingroup t)
12987 (unless (= cnt 0)
12988 (setq cnt 0)
12989 (insert "\n"))
12990 (insert "{ "))
12991 ((equal e '(:endgroup))
12992 (setq ingroup nil cnt 0)
12993 (insert "}\n"))
12994 ((equal e '(:newline))
12995 (unless (= cnt 0)
12996 (setq cnt 0)
12997 (insert "\n")
12998 (setq e (car tbl))
12999 (while (equal (car tbl) '(:newline))
13000 (insert "\n")
13001 (setq tbl (cdr tbl)))))
13003 (setq tg (car e) c (cdr e))
13004 (when ingroup (push tg (car groups)))
13005 (setq tg (org-add-props tg nil 'face
13006 (org-get-todo-face tg)))
13007 (when (and (= cnt 0) (not ingroup)) (insert " "))
13008 (insert "[" c "] " tg (make-string
13009 (- fwidth 4 (length tg)) ?\ ))
13010 (when (= (setq cnt (1+ cnt)) ncol)
13011 (insert "\n")
13012 (when ingroup (insert " "))
13013 (setq cnt 0)))))
13014 (insert "\n")
13015 (goto-char (point-min))
13016 (unless expert (org-fit-window-to-buffer))
13017 (message "[a-z..]:Set [SPC]:clear")
13018 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13019 (cond
13020 ((or (= c ?\C-g)
13021 (and (= c ?q) (not (rassoc c fulltable))))
13022 (setq quit-flag t))
13023 ((= c ?\ ) nil)
13024 ((setq e (rassoc c fulltable) tg (car e))
13026 (t (setq quit-flag t)))))))
13028 (defun org-entry-is-todo-p ()
13029 (member (org-get-todo-state) org-not-done-keywords))
13031 (defun org-entry-is-done-p ()
13032 (member (org-get-todo-state) org-done-keywords))
13034 (defun org-get-todo-state ()
13035 "Return the TODO keyword of the current subtree."
13036 (save-excursion
13037 (org-back-to-heading t)
13038 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13039 (match-end 2)
13040 (match-string 2))))
13042 (defun org-at-date-range-p (&optional inactive-ok)
13043 "Non-nil if point is inside a date range.
13045 When optional argument INACTIVE-OK is non-nil, also consider
13046 inactive time ranges.
13048 When this function returns a non-nil value, match data is set
13049 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13050 on INACTIVE-OK."
13051 (interactive)
13052 (save-excursion
13053 (catch 'exit
13054 (let ((pos (point)))
13055 (skip-chars-backward "^[<\r\n")
13056 (skip-chars-backward "<[")
13057 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13058 (>= (match-end 0) pos)
13059 (throw 'exit t))
13060 (skip-chars-backward "^<[\r\n")
13061 (skip-chars-backward "<[")
13062 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13063 (>= (match-end 0) pos)
13064 (throw 'exit t)))
13065 nil)))
13067 (defun org-get-repeat (&optional timestamp)
13068 "Check if there is a time-stamp with repeater in this entry.
13070 Return the repeater, as a string, or nil. Also return nil when
13071 this function is called before first heading.
13073 When optional argument TIMESTAMP is a string, extract the
13074 repeater from there instead."
13075 (save-match-data
13076 (cond (timestamp
13077 (and (string-match org-repeat-re timestamp)
13078 (match-string-no-properties 1 timestamp)))
13079 ((org-before-first-heading-p) nil)
13081 (save-excursion
13082 (org-back-to-heading t)
13083 (let ((end (org-entry-end-position)))
13084 (catch :repeat
13085 (while (re-search-forward org-repeat-re end t)
13086 (when (save-match-data (org-at-timestamp-p))
13087 (throw :repeat (match-string-no-properties 1)))))))))))
13089 (defvar org-last-changed-timestamp)
13090 (defvar org-last-inserted-timestamp)
13091 (defvar org-log-post-message)
13092 (defvar org-log-note-purpose)
13093 (defvar org-log-note-how nil)
13094 (defvar org-log-note-extra)
13095 (defun org-auto-repeat-maybe (done-word)
13096 "Check if the current headline contains a repeated time-stamp.
13098 If yes, set TODO state back to what it was and change the base date
13099 of repeating deadline/scheduled time stamps to new date.
13101 This function is run automatically after each state change to a DONE state."
13102 (let* ((repeat (org-get-repeat))
13103 (aa (assoc org-last-state org-todo-kwd-alist))
13104 (interpret (nth 1 aa))
13105 (head (nth 2 aa))
13106 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13107 (msg "Entry repeats: ")
13108 (org-log-done nil)
13109 (org-todo-log-states nil)
13110 (end (copy-marker (org-entry-end-position))))
13111 (unwind-protect
13112 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13113 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13114 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13115 org-todo-repeat-to-state)))
13116 (org-todo (cond
13117 ((and to-state (member to-state org-todo-keywords-1))
13118 to-state)
13119 ((eq interpret 'type) org-last-state)
13120 (head)
13121 (t 'none))))
13122 (org-back-to-heading t)
13123 (org-add-planning-info nil nil 'closed)
13124 ;; When `org-log-repeat' is non-nil or entry contains
13125 ;; a clock, set LAST_REPEAT property.
13126 (when (or org-log-repeat
13127 (catch :clock
13128 (while (re-search-forward org-clock-line-re end t)
13129 (when (org-at-clock-log-p) (throw :clock t)))))
13130 (org-entry-put nil "LAST_REPEAT" (format-time-string
13131 (org-time-stamp-format t t)
13132 (current-time))))
13133 (when org-log-repeat
13134 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13135 (memq 'org-add-log-note post-command-hook))
13136 ;; We are already setup for some record.
13137 (when (eq org-log-repeat 'note)
13138 ;; Make sure we take a note, not only a time stamp.
13139 (setq org-log-note-how 'note))
13140 ;; Set up for taking a record.
13141 (org-add-log-setup 'state
13142 (or done-word (car org-done-keywords))
13143 org-last-state
13144 org-log-repeat)))
13145 (let ((planning-re (regexp-opt
13146 (list org-scheduled-string org-deadline-string))))
13147 (while (re-search-forward org-ts-regexp end t)
13148 (let* ((ts (match-string 0))
13149 (planning? (org-at-planning-p))
13150 (type (if (not planning?) "Plain:"
13151 (save-excursion
13152 (re-search-backward
13153 planning-re (line-beginning-position) t)
13154 (match-string 0)))))
13155 (cond
13156 ;; Ignore fake time-stamps (e.g., within comments).
13157 ((not (org-at-timestamp-p t)))
13158 ;; Time-stamps without a repeater are usually
13159 ;; skipped. However, a SCHEDULED time-stamp without
13160 ;; one is removed, as they are no longer relevant.
13161 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13162 ts))
13163 (when (equal type org-scheduled-string)
13164 (org-remove-timestamp-with-keyword type)))
13166 (let ((n (string-to-number (match-string 2 ts)))
13167 (what (match-string 3 ts)))
13168 (when (equal what "w") (setq n (* n 7) what "d"))
13169 (when (and (equal what "h")
13170 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13171 ts)))
13172 (user-error
13173 "Cannot repeat in Repeat in %d hour(s) because no hour \
13174 has been set"
13176 ;; Preparation, see if we need to modify the start
13177 ;; date for the change.
13178 (when (match-end 1)
13179 (let ((time (save-match-data
13180 (org-time-string-to-time ts))))
13181 (cond
13182 ((equal (match-string 1 ts) ".")
13183 ;; Shift starting date to today
13184 (org-timestamp-change
13185 (- (org-today) (time-to-days time))
13186 'day))
13187 ((equal (match-string 1 ts) "+")
13188 (let ((nshiftmax 10)
13189 (nshift 0))
13190 (while (or (= nshift 0)
13191 (not (time-less-p (current-time) time)))
13192 (when (= (cl-incf nshift) nshiftmax)
13193 (or (y-or-n-p
13194 (format "%d repeater intervals were not \
13195 enough to shift date past today. Continue? "
13196 nshift))
13197 (user-error "Abort")))
13198 (org-timestamp-change n (cdr (assoc what whata)))
13199 (org-in-regexp org-ts-regexp3)
13200 (setq ts (match-string 1))
13201 (setq time
13202 (save-match-data
13203 (org-time-string-to-time ts)))))
13204 (org-timestamp-change (- n) (cdr (assoc what whata)))
13205 ;; Rematch, so that we have everything in place
13206 ;; for the real shift.
13207 (org-in-regexp org-ts-regexp3)
13208 (setq ts (match-string 1))
13209 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13210 ts)))))
13211 (save-excursion
13212 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13213 (setq msg
13214 (concat
13215 msg type " " org-last-changed-timestamp " "))))))))
13216 (setq org-log-post-message msg)
13217 (message "%s" msg))
13218 (set-marker end nil))))
13220 (defun org-show-todo-tree (arg)
13221 "Make a compact tree which shows all headlines marked with TODO.
13222 The tree will show the lines where the regexp matches, and all higher
13223 headlines above the match.
13224 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13225 With a numeric prefix N, construct a sparse tree for the Nth element
13226 of `org-todo-keywords-1'."
13227 (interactive "P")
13228 (let ((case-fold-search nil)
13229 (kwd-re
13230 (cond ((null arg) org-not-done-regexp)
13231 ((equal arg '(4))
13232 (let ((kwd
13233 (completing-read "Keyword (or KWD1|KWD2|...): "
13234 (mapcar #'list org-todo-keywords-1))))
13235 (concat "\\("
13236 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13237 "\\)\\>")))
13238 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13239 (regexp-quote (nth (1- (prefix-numeric-value arg))
13240 org-todo-keywords-1)))
13241 (t (user-error "Invalid prefix argument: %s" arg)))))
13242 (message "%d TODO entries found"
13243 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13245 (defun org--deadline-or-schedule (arg type time)
13246 "Insert DEADLINE or SCHEDULE information in current entry.
13247 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13248 `org-schedule' for information about ARG and TIME arguments."
13249 (let* ((deadline? (eq type 'deadline))
13250 (keyword (if deadline? org-deadline-string org-scheduled-string))
13251 (log (if deadline? org-log-redeadline org-log-reschedule))
13252 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13253 (old-date-time (and old-date (org-time-string-to-time old-date)))
13254 ;; Save repeater cookie from either TIME or current scheduled
13255 ;; time stamp. We are going to insert it back at the end of
13256 ;; the process.
13257 (repeater (or (and (org-string-nw-p time)
13258 ;; We use `org-repeat-re' because we need
13259 ;; to tell the difference between a real
13260 ;; repeater and a time delta, e.g. "+2d".
13261 (string-match org-repeat-re time)
13262 (match-string 1 time))
13263 (and (org-string-nw-p old-date)
13264 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13265 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13266 old-date)
13267 (match-string 1 old-date)))))
13268 (pcase arg
13269 (`(4)
13270 (when (and old-date log)
13271 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13272 nil old-date log))
13273 (org-remove-timestamp-with-keyword keyword)
13274 (message (if deadline? "Item no longer has a deadline."
13275 "Item is no longer scheduled.")))
13276 (`(16)
13277 (save-excursion
13278 (org-back-to-heading t)
13279 (let ((regexp (if deadline? org-deadline-time-regexp
13280 org-scheduled-time-regexp)))
13281 (if (not (re-search-forward regexp (line-end-position 2) t))
13282 (user-error (if deadline? "No deadline information to update"
13283 "No scheduled information to update"))
13284 (let* ((rpl0 (match-string 1))
13285 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13286 (msg (if deadline? "Warn starting from" "Delay until")))
13287 (replace-match
13288 (concat keyword
13289 " <" rpl
13290 (format " -%dd"
13291 (abs (- (time-to-days
13292 (save-match-data
13293 (org-read-date
13294 nil t nil msg old-date-time)))
13295 (time-to-days old-date-time))))
13296 ">") t t))))))
13298 (org-add-planning-info type time 'closed)
13299 (when (and old-date
13301 (not (equal old-date org-last-inserted-timestamp)))
13302 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13303 org-last-inserted-timestamp
13304 old-date
13305 log))
13306 (when repeater
13307 (save-excursion
13308 (org-back-to-heading t)
13309 (when (re-search-forward
13310 (concat keyword " " org-last-inserted-timestamp)
13311 (line-end-position 2)
13313 (goto-char (1- (match-end 0)))
13314 (insert " " repeater)
13315 (setq org-last-inserted-timestamp
13316 (concat (substring org-last-inserted-timestamp 0 -1)
13317 " " repeater
13318 (substring org-last-inserted-timestamp -1))))))
13319 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13320 org-last-inserted-timestamp)))))
13322 (defun org-deadline (arg &optional time)
13323 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13324 With one universal prefix argument, remove any deadline from the item.
13325 With two universal prefix arguments, prompt for a warning delay.
13326 With argument TIME, set the deadline at the corresponding date. TIME
13327 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13328 (interactive "P")
13329 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13330 (org-map-entries
13331 (lambda () (org--deadline-or-schedule arg 'deadline time))
13333 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13334 'region-start-level
13335 'region)
13336 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13337 (org--deadline-or-schedule arg 'deadline time)))
13339 (defun org-schedule (arg &optional time)
13340 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13341 With one universal prefix argument, remove any scheduling date from the item.
13342 With two universal prefix arguments, prompt for a delay cookie.
13343 With argument TIME, scheduled at the corresponding date. TIME can
13344 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13345 (interactive "P")
13346 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13347 (org-map-entries
13348 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13350 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13351 'region-start-level
13352 'region)
13353 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13354 (org--deadline-or-schedule arg 'scheduled time)))
13356 (defun org-get-scheduled-time (pom &optional inherit)
13357 "Get the scheduled time as a time tuple, of a format suitable
13358 for calling org-schedule with, or if there is no scheduling,
13359 returns nil."
13360 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13361 (when time
13362 (apply 'encode-time (org-parse-time-string time)))))
13364 (defun org-get-deadline-time (pom &optional inherit)
13365 "Get the deadline as a time tuple, of a format suitable for
13366 calling org-deadline with, or if there is no scheduling, returns
13367 nil."
13368 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13369 (when time
13370 (apply 'encode-time (org-parse-time-string time)))))
13372 (defun org-remove-timestamp-with-keyword (keyword)
13373 "Remove all time stamps with KEYWORD in the current entry."
13374 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13375 beg)
13376 (save-excursion
13377 (org-back-to-heading t)
13378 (setq beg (point))
13379 (outline-next-heading)
13380 (while (re-search-backward re beg t)
13381 (replace-match "")
13382 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13383 (equal (char-before) ?\ ))
13384 (backward-delete-char 1)
13385 (when (string-match "^[ \t]*$" (buffer-substring
13386 (point-at-bol) (point-at-eol)))
13387 (delete-region (point-at-bol)
13388 (min (point-max) (1+ (point-at-eol))))))))))
13390 (defvar org-time-was-given) ; dynamically scoped parameter
13391 (defvar org-end-time-was-given) ; dynamically scoped parameter
13393 (defun org-at-planning-p ()
13394 "Non-nil when point is on a planning info line."
13395 ;; This is as accurate and faster than `org-element-at-point' since
13396 ;; planning info location is fixed in the section.
13397 (org-with-wide-buffer
13398 (beginning-of-line)
13399 (and (looking-at-p org-planning-line-re)
13400 (eq (point)
13401 (ignore-errors
13402 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13403 (org-back-to-heading t)
13404 (org-with-limited-levels (org-back-to-heading t)))
13405 (line-beginning-position 2))))))
13407 (defun org-add-planning-info (what &optional time &rest remove)
13408 "Insert new timestamp with keyword in the planning line.
13409 WHAT indicates what kind of time stamp to add. It is a symbol
13410 among `closed', `deadline', `scheduled' and nil. TIME indicates
13411 the time to use. If none is given, the user is prompted for
13412 a date. REMOVE indicates what kind of entries to remove. An old
13413 WHAT entry will also be removed."
13414 (let (org-time-was-given org-end-time-was-given default-time default-input)
13415 (catch 'exit
13416 (when (and (memq what '(scheduled deadline))
13417 (or (not time)
13418 (and (stringp time)
13419 (string-match "^[-+]+[0-9]" time))))
13420 ;; Try to get a default date/time from existing timestamp
13421 (save-excursion
13422 (org-back-to-heading t)
13423 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13424 (when (re-search-forward (if (eq what 'scheduled)
13425 org-scheduled-time-regexp
13426 org-deadline-time-regexp)
13427 end t)
13428 (setq ts (match-string 1)
13429 default-time (apply 'encode-time (org-parse-time-string ts))
13430 default-input (and ts (org-get-compact-tod ts)))))))
13431 (when what
13432 (setq time
13433 (if (stringp time)
13434 ;; This is a string (relative or absolute), set
13435 ;; proper date.
13436 (apply #'encode-time
13437 (org-read-date-analyze
13438 time default-time (decode-time default-time)))
13439 ;; If necessary, get the time from the user
13440 (or time (org-read-date nil 'to-time nil nil
13441 default-time default-input)))))
13443 (org-with-wide-buffer
13444 (org-back-to-heading t)
13445 (forward-line)
13446 (unless (bolp) (insert "\n"))
13447 (cond ((looking-at-p org-planning-line-re)
13448 ;; Move to current indentation.
13449 (skip-chars-forward " \t")
13450 ;; Check if we have to remove something.
13451 (dolist (type (if what (cons what remove) remove))
13452 (save-excursion
13453 (when (re-search-forward
13454 (cl-case type
13455 (closed org-closed-time-regexp)
13456 (deadline org-deadline-time-regexp)
13457 (scheduled org-scheduled-time-regexp)
13458 (otherwise
13459 (error "Invalid planning type: %s" type)))
13460 (line-end-position) t)
13461 ;; Delete until next keyword or end of line.
13462 (delete-region
13463 (match-beginning 0)
13464 (if (re-search-forward org-keyword-time-not-clock-regexp
13465 (line-end-position)
13467 (match-beginning 0)
13468 (line-end-position))))))
13469 ;; If there is nothing more to add and no more keyword
13470 ;; is left, remove the line completely.
13471 (if (and (looking-at-p "[ \t]*$") (not what))
13472 (delete-region (line-beginning-position)
13473 (line-beginning-position 2))
13474 ;; If we removed last keyword, do not leave trailing
13475 ;; white space at the end of line.
13476 (let ((p (point)))
13477 (save-excursion
13478 (end-of-line)
13479 (unless (= (skip-chars-backward " \t" p) 0)
13480 (delete-region (point) (line-end-position)))))))
13481 ((not what) (throw 'exit nil)) ; Nothing to do.
13482 (t (insert-before-markers "\n")
13483 (backward-char 1)
13484 (when org-adapt-indentation
13485 (indent-to-column (1+ (org-outline-level))))))
13486 (when what
13487 ;; Insert planning keyword.
13488 (insert (cl-case what
13489 (closed org-closed-string)
13490 (deadline org-deadline-string)
13491 (scheduled org-scheduled-string)
13492 (otherwise (error "Invalid planning type: %s" what)))
13493 " ")
13494 ;; Insert associated timestamp.
13495 (let ((ts (org-insert-time-stamp
13496 time
13497 (or org-time-was-given
13498 (and (eq what 'closed) org-log-done-with-time))
13499 (eq what 'closed)
13500 nil nil (list org-end-time-was-given))))
13501 (unless (eolp) (insert " "))
13502 ts))))))
13504 (defvar org-log-note-marker (make-marker)
13505 "Marker pointing at the entry where the note is to be inserted.")
13506 (defvar org-log-note-purpose nil)
13507 (defvar org-log-note-state nil)
13508 (defvar org-log-note-previous-state nil)
13509 (defvar org-log-note-extra nil)
13510 (defvar org-log-note-window-configuration nil)
13511 (defvar org-log-note-return-to (make-marker))
13512 (defvar org-log-note-effective-time nil
13513 "Remembered current time so that dynamically scoped
13514 `org-extend-today-until' affects timestamps in state change log")
13516 (defvar org-log-post-message nil
13517 "Message to be displayed after a log note has been stored.
13518 The auto-repeater uses this.")
13520 (defun org-add-note ()
13521 "Add a note to the current entry.
13522 This is done in the same way as adding a state change note."
13523 (interactive)
13524 (org-add-log-setup 'note))
13526 (defun org-log-beginning (&optional create)
13527 "Return expected start of log notes in current entry.
13528 When optional argument CREATE is non-nil, the function creates
13529 a drawer to store notes, if necessary. Returned position ignores
13530 narrowing."
13531 (org-with-wide-buffer
13532 (let ((drawer (org-log-into-drawer)))
13533 (cond
13534 (drawer
13535 (org-end-of-meta-data)
13536 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13537 (end (if (org-at-heading-p) (point)
13538 (save-excursion (outline-next-heading) (point))))
13539 (case-fold-search t))
13540 (catch 'exit
13541 ;; Try to find existing drawer.
13542 (while (re-search-forward regexp end t)
13543 (let ((element (org-element-at-point)))
13544 (when (eq (org-element-type element) 'drawer)
13545 (let ((cend (org-element-property :contents-end element)))
13546 (when (and (not org-log-states-order-reversed) cend)
13547 (goto-char cend)))
13548 (throw 'exit nil))))
13549 ;; No drawer found. Create one, if permitted.
13550 (when create
13551 (unless (bolp) (insert "\n"))
13552 (let ((beg (point)))
13553 (insert ":" drawer ":\n:END:\n")
13554 (org-indent-region beg (point)))
13555 (end-of-line -1)))))
13557 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13558 (skip-chars-forward " \t\n")
13559 (beginning-of-line)
13560 (unless org-log-states-order-reversed
13561 (org-skip-over-state-notes)
13562 (skip-chars-backward " \t\n")
13563 (forward-line)))))
13564 (if (bolp) (point) (line-beginning-position 2))))
13566 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13567 "Set up the post command hook to take a note.
13568 If this is about to TODO state change, the new state is expected in STATE.
13569 HOW is an indicator what kind of note should be created.
13570 EXTRA is additional text that will be inserted into the notes buffer."
13571 (move-marker org-log-note-marker (point))
13572 (setq org-log-note-purpose purpose
13573 org-log-note-state state
13574 org-log-note-previous-state prev-state
13575 org-log-note-how how
13576 org-log-note-extra extra
13577 org-log-note-effective-time (org-current-effective-time))
13578 (add-hook 'post-command-hook 'org-add-log-note 'append))
13580 (defun org-skip-over-state-notes ()
13581 "Skip past the list of State notes in an entry."
13582 (when (ignore-errors (goto-char (org-in-item-p)))
13583 (let* ((struct (org-list-struct))
13584 (prevs (org-list-prevs-alist struct))
13585 (regexp
13586 (concat "[ \t]*- +"
13587 (replace-regexp-in-string
13588 " +" " +"
13589 (org-replace-escapes
13590 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13591 `(("%d" . ,org-ts-regexp-inactive)
13592 ("%D" . ,org-ts-regexp)
13593 ("%s" . "\"\\S-+\"")
13594 ("%S" . "\"\\S-+\"")
13595 ("%t" . ,org-ts-regexp-inactive)
13596 ("%T" . ,org-ts-regexp)
13597 ("%u" . ".*?")
13598 ("%U" . ".*?")))))))
13599 (while (looking-at-p regexp)
13600 (goto-char (or (org-list-get-next-item (point) struct prevs)
13601 (org-list-get-item-end (point) struct)))))))
13603 (defun org-add-log-note (&optional _purpose)
13604 "Pop up a window for taking a note, and add this note later."
13605 (remove-hook 'post-command-hook 'org-add-log-note)
13606 (setq org-log-note-window-configuration (current-window-configuration))
13607 (delete-other-windows)
13608 (move-marker org-log-note-return-to (point))
13609 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13610 (goto-char org-log-note-marker)
13611 (org-switch-to-buffer-other-window "*Org Note*")
13612 (erase-buffer)
13613 (if (memq org-log-note-how '(time state))
13614 (let (current-prefix-arg) (org-store-log-note))
13615 (let ((org-inhibit-startup t)) (org-mode))
13616 (insert (format "# Insert note for %s.
13617 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13618 (cond
13619 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13620 ((eq org-log-note-purpose 'done) "closed todo item")
13621 ((eq org-log-note-purpose 'state)
13622 (format "state change from \"%s\" to \"%s\""
13623 (or org-log-note-previous-state "")
13624 (or org-log-note-state "")))
13625 ((eq org-log-note-purpose 'reschedule)
13626 "rescheduling")
13627 ((eq org-log-note-purpose 'delschedule)
13628 "no longer scheduled")
13629 ((eq org-log-note-purpose 'redeadline)
13630 "changing deadline")
13631 ((eq org-log-note-purpose 'deldeadline)
13632 "removing deadline")
13633 ((eq org-log-note-purpose 'refile)
13634 "refiling")
13635 ((eq org-log-note-purpose 'note)
13636 "this entry")
13637 (t (error "This should not happen")))))
13638 (when org-log-note-extra (insert org-log-note-extra))
13639 (setq-local org-finish-function 'org-store-log-note)
13640 (run-hooks 'org-log-buffer-setup-hook)))
13642 (defvar org-note-abort nil) ; dynamically scoped
13643 (defun org-store-log-note ()
13644 "Finish taking a log note, and insert it to where it belongs."
13645 (let ((txt (prog1 (buffer-string)
13646 (kill-buffer)))
13647 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13648 lines)
13649 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13650 (setq txt (replace-match "" t t txt)))
13651 (when (string-match "\\s-+\\'" txt)
13652 (setq txt (replace-match "" t t txt)))
13653 (setq lines (org-split-string txt "\n"))
13654 (when (org-string-nw-p note)
13655 (setq note
13656 (org-replace-escapes
13657 note
13658 (list (cons "%u" (user-login-name))
13659 (cons "%U" user-full-name)
13660 (cons "%t" (format-time-string
13661 (org-time-stamp-format 'long 'inactive)
13662 org-log-note-effective-time))
13663 (cons "%T" (format-time-string
13664 (org-time-stamp-format 'long nil)
13665 org-log-note-effective-time))
13666 (cons "%d" (format-time-string
13667 (org-time-stamp-format nil 'inactive)
13668 org-log-note-effective-time))
13669 (cons "%D" (format-time-string
13670 (org-time-stamp-format nil nil)
13671 org-log-note-effective-time))
13672 (cons "%s" (cond
13673 ((not org-log-note-state) "")
13674 ((string-match-p org-ts-regexp
13675 org-log-note-state)
13676 (format "\"[%s]\""
13677 (substring org-log-note-state 1 -1)))
13678 (t (format "\"%s\"" org-log-note-state))))
13679 (cons "%S"
13680 (cond
13681 ((not org-log-note-previous-state) "")
13682 ((string-match-p org-ts-regexp
13683 org-log-note-previous-state)
13684 (format "\"[%s]\""
13685 (substring
13686 org-log-note-previous-state 1 -1)))
13687 (t (format "\"%s\""
13688 org-log-note-previous-state)))))))
13689 (when lines (setq note (concat note " \\\\")))
13690 (push note lines))
13691 (when (and lines (not (or current-prefix-arg org-note-abort)))
13692 (with-current-buffer (marker-buffer org-log-note-marker)
13693 (org-with-wide-buffer
13694 ;; Find location for the new note.
13695 (goto-char org-log-note-marker)
13696 (set-marker org-log-note-marker nil)
13697 ;; Note associated to a clock is to be located right after
13698 ;; the clock. Do not move point.
13699 (unless (eq org-log-note-purpose 'clock-out)
13700 (goto-char (org-log-beginning t)))
13701 ;; Make sure point is at the beginning of an empty line.
13702 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13703 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13704 ;; In an existing list, add a new item at the top level.
13705 ;; Otherwise, indent line like a regular one.
13706 (let ((itemp (org-in-item-p)))
13707 (if itemp
13708 (indent-line-to
13709 (let ((struct (save-excursion
13710 (goto-char itemp) (org-list-struct))))
13711 (org-list-get-ind (org-list-get-top-point struct) struct)))
13712 (org-indent-line)))
13713 (insert (org-list-bullet-string "-") (pop lines))
13714 (let ((ind (org-list-item-body-column (line-beginning-position))))
13715 (dolist (line lines)
13716 (insert "\n")
13717 (indent-line-to ind)
13718 (insert line)))
13719 (message "Note stored")
13720 (org-back-to-heading t)
13721 (org-cycle-hide-drawers 'children))
13722 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13723 ;; from within `org-add-log-note' because `buffer-undo-list'
13724 ;; is then modified outside of `org-with-remote-undo'.
13725 (when (eq this-command 'org-agenda-todo)
13726 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13727 ;; Don't add undo information when called from `org-agenda-todo'.
13728 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13729 (set-window-configuration org-log-note-window-configuration)
13730 (with-current-buffer (marker-buffer org-log-note-return-to)
13731 (goto-char org-log-note-return-to))
13732 (move-marker org-log-note-return-to nil)
13733 (when org-log-post-message (message "%s" org-log-post-message))))
13735 (defun org-remove-empty-drawer-at (pos)
13736 "Remove an empty drawer at position POS.
13737 POS may also be a marker."
13738 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13739 (org-with-wide-buffer
13740 (goto-char pos)
13741 (let ((drawer (org-element-at-point)))
13742 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13743 (not (org-element-property :contents-begin drawer)))
13744 (delete-region (org-element-property :begin drawer)
13745 (progn (goto-char (org-element-property :end drawer))
13746 (skip-chars-backward " \r\t\n")
13747 (forward-line)
13748 (point))))))))
13750 (defvar org-ts-type nil)
13751 (defun org-sparse-tree (&optional arg type)
13752 "Create a sparse tree, prompt for the details.
13753 This command can create sparse trees. You first need to select the type
13754 of match used to create the tree:
13756 t Show all TODO entries.
13757 T Show entries with a specific TODO keyword.
13758 m Show entries selected by a tags/property match.
13759 p Enter a property name and its value (both with completion on existing
13760 names/values) and show entries with that property.
13761 r Show entries matching a regular expression (`/' can be used as well).
13762 b Show deadlines and scheduled items before a date.
13763 a Show deadlines and scheduled items after a date.
13764 d Show deadlines due within `org-deadline-warning-days'.
13765 D Show deadlines and scheduled items between a date range."
13766 (interactive "P")
13767 (setq type (or type org-sparse-tree-default-date-type))
13768 (setq org-ts-type type)
13769 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13770 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13771 \[c]ycle through date types: %s"
13772 (cl-case type
13773 (all "all timestamps")
13774 (scheduled "only scheduled")
13775 (deadline "only deadline")
13776 (active "only active timestamps")
13777 (inactive "only inactive timestamps")
13778 (closed "with a closed time-stamp")
13779 (otherwise "scheduled/deadline")))
13780 (let ((answer (read-char-exclusive)))
13781 (cl-case answer
13783 (org-sparse-tree
13785 (cadr
13786 (memq type '(nil all scheduled deadline active inactive closed)))))
13787 (?d (call-interactively 'org-check-deadlines))
13788 (?b (call-interactively 'org-check-before-date))
13789 (?a (call-interactively 'org-check-after-date))
13790 (?D (call-interactively 'org-check-dates-range))
13791 (?t (call-interactively 'org-show-todo-tree))
13792 (?T (org-show-todo-tree '(4)))
13793 (?m (call-interactively 'org-match-sparse-tree))
13794 ((?p ?P)
13795 (let* ((kwd (completing-read
13796 "Property: " (mapcar #'list (org-buffer-property-keys))))
13797 (value (completing-read
13798 "Value: " (mapcar #'list (org-property-values kwd)))))
13799 (unless (string-match "\\`{.*}\\'" value)
13800 (setq value (concat "\"" value "\"")))
13801 (org-match-sparse-tree arg (concat kwd "=" value))))
13802 ((?r ?R ?/) (call-interactively 'org-occur))
13803 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13805 (defvar-local org-occur-highlights nil
13806 "List of overlays used for occur matches.")
13807 (defvar-local org-occur-parameters nil
13808 "Parameters of the active org-occur calls.
13809 This is a list, each call to org-occur pushes as cons cell,
13810 containing the regular expression and the callback, onto the list.
13811 The list can contain several entries if `org-occur' has been called
13812 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13813 will only contain one set of parameters. When the highlights are
13814 removed (for example with `C-c C-c', or with the next edit (depending
13815 on `org-remove-highlights-with-change'), this variable is emptied
13816 as well.")
13818 (defun org-occur (regexp &optional keep-previous callback)
13819 "Make a compact tree which shows all matches of REGEXP.
13821 The tree will show the lines where the regexp matches, and any other context
13822 defined in `org-show-context-detail', which see.
13824 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13825 done by a previous call to `org-occur' will be kept, to allow stacking of
13826 calls to this command.
13828 Optional argument CALLBACK can be a function of no argument. In this case,
13829 it is called with point at the end of the match, match data being set
13830 accordingly. Current match is shown only if the return value is non-nil.
13831 The function must neither move point nor alter narrowing."
13832 (interactive "sRegexp: \nP")
13833 (when (equal regexp "")
13834 (user-error "Regexp cannot be empty"))
13835 (unless keep-previous
13836 (org-remove-occur-highlights nil nil t))
13837 (push (cons regexp callback) org-occur-parameters)
13838 (let ((cnt 0))
13839 (save-excursion
13840 (goto-char (point-min))
13841 (when (or (not keep-previous) ; do not want to keep
13842 (not org-occur-highlights)) ; no previous matches
13843 ;; hide everything
13844 (org-overview))
13845 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13846 (isearch-no-upper-case-p regexp t)
13847 org-occur-case-fold-search)))
13848 (while (re-search-forward regexp nil t)
13849 (when (or (not callback)
13850 (save-match-data (funcall callback)))
13851 (setq cnt (1+ cnt))
13852 (when org-highlight-sparse-tree-matches
13853 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13854 (org-show-context 'occur-tree)))))
13855 (when org-remove-highlights-with-change
13856 (add-hook 'before-change-functions 'org-remove-occur-highlights
13857 nil 'local))
13858 (unless org-sparse-tree-open-archived-trees
13859 (org-hide-archived-subtrees (point-min) (point-max)))
13860 (run-hooks 'org-occur-hook)
13861 (when (called-interactively-p 'interactive)
13862 (message "%d match(es) for regexp %s" cnt regexp))
13863 cnt))
13865 (defun org-occur-next-match (&optional n _reset)
13866 "Function for `next-error-function' to find sparse tree matches.
13867 N is the number of matches to move, when negative move backwards.
13868 This function always goes back to the starting point when no
13869 match is found."
13870 (let* ((limit (if (< n 0) (point-min) (point-max)))
13871 (search-func (if (< n 0)
13872 'previous-single-char-property-change
13873 'next-single-char-property-change))
13874 (n (abs n))
13875 (pos (point))
13877 (catch 'exit
13878 (while (setq p1 (funcall search-func (point) 'org-type))
13879 (when (equal p1 limit)
13880 (goto-char pos)
13881 (user-error "No more matches"))
13882 (when (equal (get-char-property p1 'org-type) 'org-occur)
13883 (setq n (1- n))
13884 (when (= n 0)
13885 (goto-char p1)
13886 (throw 'exit (point))))
13887 (goto-char p1))
13888 (goto-char p1)
13889 (user-error "No more matches"))))
13891 (defun org-show-context (&optional key)
13892 "Make sure point and context are visible.
13893 Optional argument KEY, when non-nil, is a symbol. See
13894 `org-show-context-detail' for allowed values and how much is to
13895 be shown."
13896 (org-show-set-visibility
13897 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13898 ((cdr (assq key org-show-context-detail)))
13899 (t (cdr (assq 'default org-show-context-detail))))))
13901 (defun org-show-set-visibility (detail)
13902 "Set visibility around point according to DETAIL.
13903 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13904 `tree', `canonical' or t. See `org-show-context-detail' for more
13905 information."
13906 ;; Show current heading and possibly its entry, following headline
13907 ;; or all children.
13908 (if (and (org-at-heading-p) (not (eq detail 'local)))
13909 (org-flag-heading nil)
13910 (org-show-entry)
13911 ;; If point is hidden within a drawer or a block, make sure to
13912 ;; expose it.
13913 (dolist (o (overlays-at (point)))
13914 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13915 (delete-overlay o)))
13916 (unless (org-before-first-heading-p)
13917 (org-with-limited-levels
13918 (cl-case detail
13919 ((tree canonical t) (org-show-children))
13920 ((nil minimal ancestors))
13921 (t (save-excursion
13922 (outline-next-heading)
13923 (org-flag-heading nil)))))))
13924 ;; Show all siblings.
13925 (when (eq detail 'lineage) (org-show-siblings))
13926 ;; Show ancestors, possibly with their children.
13927 (when (memq detail '(ancestors lineage tree canonical t))
13928 (save-excursion
13929 (while (org-up-heading-safe)
13930 (org-flag-heading nil)
13931 (when (memq detail '(canonical t)) (org-show-entry))
13932 (when (memq detail '(tree canonical t)) (org-show-children))))))
13934 (defvar org-reveal-start-hook nil
13935 "Hook run before revealing a location.")
13937 (defun org-reveal (&optional siblings)
13938 "Show current entry, hierarchy above it, and the following headline.
13940 This can be used to show a consistent set of context around
13941 locations exposed with `org-show-context'.
13943 With optional argument SIBLINGS, on each level of the hierarchy all
13944 siblings are shown. This repairs the tree structure to what it would
13945 look like when opened with hierarchical calls to `org-cycle'.
13947 With a \\[universal-argument] \\[universal-argument] prefix, \
13948 go to the parent and show the entire tree."
13949 (interactive "P")
13950 (run-hooks 'org-reveal-start-hook)
13951 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13952 ((equal siblings '(16))
13953 (save-excursion
13954 (when (org-up-heading-safe)
13955 (org-show-subtree)
13956 (run-hook-with-args 'org-cycle-hook 'subtree))))
13957 (t (org-show-set-visibility 'lineage))))
13959 (defun org-highlight-new-match (beg end)
13960 "Highlight from BEG to END and mark the highlight is an occur headline."
13961 (let ((ov (make-overlay beg end)))
13962 (overlay-put ov 'face 'secondary-selection)
13963 (overlay-put ov 'org-type 'org-occur)
13964 (push ov org-occur-highlights)))
13966 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13967 "Remove the occur highlights from the buffer.
13968 BEG and END are ignored. If NOREMOVE is nil, remove this function
13969 from the `before-change-functions' in the current buffer."
13970 (interactive)
13971 (unless org-inhibit-highlight-removal
13972 (mapc #'delete-overlay org-occur-highlights)
13973 (setq org-occur-highlights nil)
13974 (setq org-occur-parameters nil)
13975 (unless noremove
13976 (remove-hook 'before-change-functions
13977 'org-remove-occur-highlights 'local))))
13979 ;;;; Priorities
13981 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13982 "Regular expression matching the priority indicator.")
13984 (defvar org-remove-priority-next-time nil)
13986 (defun org-priority-up ()
13987 "Increase the priority of the current item."
13988 (interactive)
13989 (org-priority 'up))
13991 (defun org-priority-down ()
13992 "Decrease the priority of the current item."
13993 (interactive)
13994 (org-priority 'down))
13996 (defun org-priority (&optional action _show)
13997 "Change the priority of an item.
13998 ACTION can be `set', `up', `down', or a character."
13999 (interactive "P")
14000 (if (equal action '(4))
14001 (org-show-priority)
14002 (unless org-enable-priority-commands
14003 (user-error "Priority commands are disabled"))
14004 (setq action (or action 'set))
14005 (let (current new news have remove)
14006 (save-excursion
14007 (org-back-to-heading t)
14008 (when (looking-at org-priority-regexp)
14009 (setq current (string-to-char (match-string 2))
14010 have t))
14011 (cond
14012 ((eq action 'remove)
14013 (setq remove t new ?\ ))
14014 ((or (eq action 'set)
14015 (integerp action))
14016 (if (not (eq action 'set))
14017 (setq new action)
14018 (message "Priority %c-%c, SPC to remove: "
14019 org-highest-priority org-lowest-priority)
14020 (save-match-data
14021 (setq new (read-char-exclusive))))
14022 (when (and (= (upcase org-highest-priority) org-highest-priority)
14023 (= (upcase org-lowest-priority) org-lowest-priority))
14024 (setq new (upcase new)))
14025 (cond ((equal new ?\ ) (setq remove t))
14026 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14027 (user-error "Priority must be between `%c' and `%c'"
14028 org-highest-priority org-lowest-priority))))
14029 ((eq action 'up)
14030 (setq new (if have
14031 (1- current) ; normal cycling
14032 ;; last priority was empty
14033 (if (eq last-command this-command)
14034 org-lowest-priority ; wrap around empty to lowest
14035 ;; default
14036 (if org-priority-start-cycle-with-default
14037 org-default-priority
14038 (1- org-default-priority))))))
14039 ((eq action 'down)
14040 (setq new (if have
14041 (1+ current) ; normal cycling
14042 ;; last priority was empty
14043 (if (eq last-command this-command)
14044 org-highest-priority ; wrap around empty to highest
14045 ;; default
14046 (if org-priority-start-cycle-with-default
14047 org-default-priority
14048 (1+ org-default-priority))))))
14049 (t (user-error "Invalid action")))
14050 (when (or (< (upcase new) org-highest-priority)
14051 (> (upcase new) org-lowest-priority))
14052 (if (and (memq action '(up down))
14053 (not have) (not (eq last-command this-command)))
14054 ;; `new' is from default priority
14055 (error
14056 "The default can not be set, see `org-default-priority' why")
14057 ;; normal cycling: `new' is beyond highest/lowest priority
14058 ;; and is wrapped around to the empty priority
14059 (setq remove t)))
14060 (setq news (format "%c" new))
14061 (if have
14062 (if remove
14063 (replace-match "" t t nil 1)
14064 (replace-match news t t nil 2))
14065 (if remove
14066 (user-error "No priority cookie found in line")
14067 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14068 (if (match-end 2)
14069 (progn
14070 (goto-char (match-end 2))
14071 (insert " [#" news "]"))
14072 (goto-char (match-beginning 3))
14073 (insert "[#" news "] "))))
14074 (org-set-tags nil 'align))
14075 (if remove
14076 (message "Priority removed")
14077 (message "Priority of current item set to %s" news)))))
14079 (defun org-show-priority ()
14080 "Show the priority of the current item.
14081 This priority is composed of the main priority given with the [#A] cookies,
14082 and by additional input from the age of a schedules or deadline entry."
14083 (interactive)
14084 (let ((pri (if (eq major-mode 'org-agenda-mode)
14085 (org-get-at-bol 'priority)
14086 (save-excursion
14087 (save-match-data
14088 (beginning-of-line)
14089 (and (looking-at org-heading-regexp)
14090 (org-get-priority (match-string 0))))))))
14091 (message "Priority is %d" (if pri pri -1000))))
14093 (defun org-get-priority (s)
14094 "Find priority cookie and return priority."
14095 (save-match-data
14096 (if (functionp org-get-priority-function)
14097 (funcall org-get-priority-function)
14098 (if (not (string-match org-priority-regexp s))
14099 (* 1000 (- org-lowest-priority org-default-priority))
14100 (* 1000 (- org-lowest-priority
14101 (string-to-char (match-string 2 s))))))))
14103 ;;;; Tags
14105 (defvar org-agenda-archives-mode)
14106 (defvar org-map-continue-from nil
14107 "Position from where mapping should continue.
14108 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14110 (defvar org-scanner-tags nil
14111 "The current tag list while the tags scanner is running.")
14113 (defvar org-trust-scanner-tags nil
14114 "Should `org-get-tags-at' use the tags for the scanner.
14115 This is for internal dynamical scoping only.
14116 When this is non-nil, the function `org-get-tags-at' will return the value
14117 of `org-scanner-tags' instead of building the list by itself. This
14118 can lead to large speed-ups when the tags scanner is used in a file with
14119 many entries, and when the list of tags is retrieved, for example to
14120 obtain a list of properties. Building the tags list for each entry in such
14121 a file becomes an N^2 operation - but with this variable set, it scales
14122 as N.")
14124 (defvar org--matcher-tags-todo-only nil)
14126 (defun org-scan-tags (action matcher todo-only &optional start-level)
14127 "Scan headline tags with inheritance and produce output ACTION.
14129 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14130 or `agenda' to produce an entry list for an agenda view. It can also be
14131 a Lisp form or a function that should be called at each matched headline, in
14132 this case the return value is a list of all return values from these calls.
14134 MATCHER is a function accepting three arguments, returning
14135 a non-nil value whenever a given set of tags qualifies a headline
14136 for inclusion. See `org-make-tags-matcher' for more information.
14137 As a special case, it can also be set to t (respectively nil) in
14138 order to match all (respectively none) headline.
14140 When TODO-ONLY is non-nil, only lines with a not-done TODO
14141 keyword are included in the output.
14143 START-LEVEL can be a string with asterisks, reducing the scope to
14144 headlines matching this string."
14145 (require 'org-agenda)
14146 (let* ((re (concat "^"
14147 (if start-level
14148 ;; Get the correct level to match
14149 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14150 org-outline-regexp)
14151 " *\\(\\<\\("
14152 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14153 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14154 (props (list 'face 'default
14155 'done-face 'org-agenda-done
14156 'undone-face 'default
14157 'mouse-face 'highlight
14158 'org-not-done-regexp org-not-done-regexp
14159 'org-todo-regexp org-todo-regexp
14160 'org-complex-heading-regexp org-complex-heading-regexp
14161 'help-echo
14162 (format "mouse-2 or RET jump to org file %s"
14163 (abbreviate-file-name
14164 (or (buffer-file-name (buffer-base-buffer))
14165 (buffer-name (buffer-base-buffer)))))))
14166 (org-map-continue-from nil)
14167 lspos tags tags-list
14168 (tags-alist (list (cons 0 org-file-tags)))
14169 (llast 0) rtn rtn1 level category i txt
14170 todo marker entry priority
14171 ts-date ts-date-type ts-date-pair)
14172 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14173 (setq action (list 'lambda nil action)))
14174 (save-excursion
14175 (goto-char (point-min))
14176 (when (eq action 'sparse-tree)
14177 (org-overview)
14178 (org-remove-occur-highlights))
14179 (while (let (case-fold-search)
14180 (re-search-forward re nil t))
14181 (setq org-map-continue-from nil)
14182 (catch :skip
14183 (setq todo
14184 ;; TODO: is the 1-2 difference a bug?
14185 (when (match-end 1) (match-string-no-properties 2))
14186 tags (when (match-end 4) (match-string-no-properties 4)))
14187 (goto-char (setq lspos (match-beginning 0)))
14188 (setq level (org-reduced-level (org-outline-level))
14189 category (org-get-category))
14190 (when (eq action 'agenda)
14191 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14192 ts-date (car ts-date-pair)
14193 ts-date-type (cdr ts-date-pair)))
14194 (setq i llast llast level)
14195 ;; remove tag lists from same and sublevels
14196 (while (>= i level)
14197 (when (setq entry (assoc i tags-alist))
14198 (setq tags-alist (delete entry tags-alist)))
14199 (setq i (1- i)))
14200 ;; add the next tags
14201 (when tags
14202 (setq tags (org-split-string tags ":")
14203 tags-alist
14204 (cons (cons level tags) tags-alist)))
14205 ;; compile tags for current headline
14206 (setq tags-list
14207 (if org-use-tag-inheritance
14208 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14209 tags)
14210 org-scanner-tags tags-list)
14211 (when org-use-tag-inheritance
14212 (setcdr (car tags-alist)
14213 (mapcar (lambda (x)
14214 (setq x (copy-sequence x))
14215 (org-add-prop-inherited x))
14216 (cdar tags-alist))))
14217 (when (and tags org-use-tag-inheritance
14218 (or (not (eq t org-use-tag-inheritance))
14219 org-tags-exclude-from-inheritance))
14220 ;; Selective inheritance, remove uninherited ones.
14221 (setcdr (car tags-alist)
14222 (org-remove-uninherited-tags (cdar tags-alist))))
14223 (when (and
14225 ;; eval matcher only when the todo condition is OK
14226 (and (or (not todo-only) (member todo org-not-done-keywords))
14227 (if (functionp matcher)
14228 (let ((case-fold-search t) (org-trust-scanner-tags t))
14229 (funcall matcher todo tags-list level))
14230 matcher))
14232 ;; Call the skipper, but return t if it does not
14233 ;; skip, so that the `and' form continues evaluating.
14234 (progn
14235 (unless (eq action 'sparse-tree) (org-agenda-skip))
14238 ;; Check if timestamps are deselecting this entry
14239 (or (not todo-only)
14240 (and (member todo org-not-done-keywords)
14241 (or (not org-agenda-tags-todo-honor-ignore-options)
14242 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14244 ;; select this headline
14245 (cond
14246 ((eq action 'sparse-tree)
14247 (and org-highlight-sparse-tree-matches
14248 (org-get-heading) (match-end 0)
14249 (org-highlight-new-match
14250 (match-beginning 1) (match-end 1)))
14251 (org-show-context 'tags-tree))
14252 ((eq action 'agenda)
14253 (setq txt (org-agenda-format-item
14255 (concat
14256 (if (eq org-tags-match-list-sublevels 'indented)
14257 (make-string (1- level) ?.) "")
14258 (org-get-heading))
14259 (make-string level ?\s)
14260 category
14261 tags-list)
14262 priority (org-get-priority txt))
14263 (goto-char lspos)
14264 (setq marker (org-agenda-new-marker))
14265 (org-add-props txt props
14266 'org-marker marker 'org-hd-marker marker 'org-category category
14267 'todo-state todo
14268 'ts-date ts-date
14269 'priority priority
14270 'type (concat "tagsmatch" ts-date-type))
14271 (push txt rtn))
14272 ((functionp action)
14273 (setq org-map-continue-from nil)
14274 (save-excursion
14275 (setq rtn1 (funcall action))
14276 (push rtn1 rtn)))
14277 (t (user-error "Invalid action")))
14279 ;; if we are to skip sublevels, jump to end of subtree
14280 (unless org-tags-match-list-sublevels
14281 (org-end-of-subtree t)
14282 (backward-char 1))))
14283 ;; Get the correct position from where to continue
14284 (if org-map-continue-from
14285 (goto-char org-map-continue-from)
14286 (and (= (point) lspos) (end-of-line 1)))))
14287 (when (and (eq action 'sparse-tree)
14288 (not org-sparse-tree-open-archived-trees))
14289 (org-hide-archived-subtrees (point-min) (point-max)))
14290 (nreverse rtn)))
14292 (defun org-remove-uninherited-tags (tags)
14293 "Remove all tags that are not inherited from the list TAGS."
14294 (cond
14295 ((eq org-use-tag-inheritance t)
14296 (if org-tags-exclude-from-inheritance
14297 (org-delete-all org-tags-exclude-from-inheritance tags)
14298 tags))
14299 ((not org-use-tag-inheritance) nil)
14300 ((stringp org-use-tag-inheritance)
14301 (delq nil (mapcar
14302 (lambda (x)
14303 (if (and (string-match org-use-tag-inheritance x)
14304 (not (member x org-tags-exclude-from-inheritance)))
14305 x nil))
14306 tags)))
14307 ((listp org-use-tag-inheritance)
14308 (delq nil (mapcar
14309 (lambda (x)
14310 (if (member x org-use-tag-inheritance) x nil))
14311 tags)))))
14313 (defun org-match-sparse-tree (&optional todo-only match)
14314 "Create a sparse tree according to tags string MATCH.
14316 MATCH is a string with match syntax. It can contain a selection
14317 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14318 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14319 those. See the manual for details.
14321 If optional argument TODO-ONLY is non-nil, only select lines that
14322 are also TODO tasks."
14323 (interactive "P")
14324 (org-agenda-prepare-buffers (list (current-buffer)))
14325 (let ((org--matcher-tags-todo-only todo-only))
14326 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14327 org--matcher-tags-todo-only)))
14329 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14331 (defvar org-cached-props nil)
14332 (defun org-cached-entry-get (pom property)
14333 (if (or (eq t org-use-property-inheritance)
14334 (and (stringp org-use-property-inheritance)
14335 (let ((case-fold-search t))
14336 (string-match-p org-use-property-inheritance property)))
14337 (and (listp org-use-property-inheritance)
14338 (member-ignore-case property org-use-property-inheritance)))
14339 ;; Caching is not possible, check it directly.
14340 (org-entry-get pom property 'inherit)
14341 ;; Get all properties, so we can do complicated checks easily.
14342 (cdr (assoc-string property
14343 (or org-cached-props
14344 (setq org-cached-props (org-entry-properties pom)))
14345 t))))
14347 (defun org-global-tags-completion-table (&optional files)
14348 "Return the list of all tags in all agenda buffer/files.
14349 Optional FILES argument is a list of files which can be used
14350 instead of the agenda files."
14351 (save-excursion
14352 (org-uniquify
14353 (delq nil
14354 (apply #'append
14355 (mapcar
14356 (lambda (file)
14357 (set-buffer (find-file-noselect file))
14358 (mapcar (lambda (x)
14359 (and (stringp (car-safe x))
14360 (list (car-safe x))))
14361 (or org-current-tag-alist (org-get-buffer-tags))))
14362 (if (car-safe files) files
14363 (org-agenda-files))))))))
14365 (defun org-make-tags-matcher (match)
14366 "Create the TAGS/TODO matcher form for the selection string MATCH.
14368 Returns a cons of the selection string MATCH and a function
14369 implementing the matcher.
14371 The matcher is to be called at an Org entry, with point on the
14372 headline, and returns non-nil if the entry matches the selection
14373 string MATCH. It must be called with three arguments: the TODO
14374 keyword at the entry (or nil if none), the list of all tags at
14375 the entry including inherited ones and the reduced level of the
14376 headline. Additionally, the category of the entry, if any, must
14377 be specified as the text property `org-category' on the headline.
14379 This function sets the variable `org--matcher-tags-todo-only' to
14380 a non-nil value if the matcher restricts matching to TODO
14381 entries, otherwise it is not touched.
14383 See also `org-scan-tags'."
14384 (unless match
14385 ;; Get a new match request, with completion against the global
14386 ;; tags table and the local tags in current buffer.
14387 (let ((org-last-tags-completion-table
14388 (org-uniquify
14389 (delq nil (append (org-get-buffer-tags)
14390 (org-global-tags-completion-table))))))
14391 (setq match
14392 (completing-read
14393 "Match: "
14394 'org-tags-completion-function nil nil nil 'org-tags-history))))
14396 (let ((match0 match)
14397 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14398 (start 0)
14399 tagsmatch todomatch tagsmatcher todomatcher)
14401 ;; Expand group tags.
14402 (setq match (org-tags-expand match))
14404 ;; Check if there is a TODO part of this match, which would be the
14405 ;; part after a "/". To make sure that this slash is not part of
14406 ;; a property value to be matched against, we also check that
14407 ;; there is no / after that slash. First, find the last slash.
14408 (let ((s 0))
14409 (while (string-match "/+" match s)
14410 (setq start (match-beginning 0))
14411 (setq s (match-end 0))))
14412 (if (and (string-match "/+" match start)
14413 (not (string-match-p "\"" match start)))
14414 ;; Match contains also a TODO-matching request.
14415 (progn
14416 (setq tagsmatch (substring match 0 (match-beginning 0)))
14417 (setq todomatch (substring match (match-end 0)))
14418 (when (string-prefix-p "!" todomatch)
14419 (setq org--matcher-tags-todo-only t)
14420 (setq todomatch (substring todomatch 1)))
14421 (when (string-match "\\`\\s-*\\'" todomatch)
14422 (setq todomatch nil)))
14423 ;; Only matching tags.
14424 (setq tagsmatch match)
14425 (setq todomatch nil))
14427 ;; Make the tags matcher.
14428 (when (org-string-nw-p tagsmatch)
14429 (let ((orlist nil)
14430 (orterms (org-split-string tagsmatch "|"))
14431 term)
14432 (while (setq term (pop orterms))
14433 (while (and (equal (substring term -1) "\\") orterms)
14434 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14435 (while (string-match re term)
14436 (let* ((rest (substring term (match-end 0)))
14437 (minus (and (match-end 1)
14438 (equal (match-string 1 term) "-")))
14439 (tag (save-match-data
14440 (replace-regexp-in-string
14441 "\\\\-" "-" (match-string 2 term))))
14442 (regexp (eq (string-to-char tag) ?{))
14443 (levelp (match-end 4))
14444 (propp (match-end 5))
14446 (cond
14447 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14448 (levelp
14449 `(,(org-op-to-function (match-string 3 term))
14450 level
14451 ,(string-to-number (match-string 4 term))))
14452 (propp
14453 (let* ((gv (pcase (upcase (match-string 5 term))
14454 ("CATEGORY"
14455 '(get-text-property (point) 'org-category))
14456 ("TODO" 'todo)
14457 (p `(org-cached-entry-get nil ,p))))
14458 (pv (match-string 7 term))
14459 (regexp (eq (string-to-char pv) ?{))
14460 (strp (eq (string-to-char pv) ?\"))
14461 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14462 (po (org-op-to-function (match-string 6 term)
14463 (if timep 'time strp))))
14464 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14465 (when timep (setq pv (org-matcher-time pv)))
14466 (cond ((and regexp (eq po 'org<>))
14467 `(not (string-match ,pv (or ,gv ""))))
14468 (regexp `(string-match ,pv (or ,gv "")))
14469 (strp `(,po (or ,gv "") ,pv))
14471 `(,po
14472 (string-to-number (or ,gv ""))
14473 ,(string-to-number pv))))))
14474 (t `(member ,tag tags-list)))))
14475 (push (if minus `(not ,mm) mm) tagsmatcher)
14476 (setq term rest)))
14477 (push `(and ,@tagsmatcher) orlist)
14478 (setq tagsmatcher nil))
14479 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14481 ;; Make the TODO matcher.
14482 (when (org-string-nw-p todomatch)
14483 (let ((orlist nil))
14484 (dolist (term (org-split-string todomatch "|"))
14485 (while (string-match re term)
14486 (let* ((minus (and (match-end 1)
14487 (equal (match-string 1 term) "-")))
14488 (kwd (match-string 2 term))
14489 (regexp (eq (string-to-char kwd) ?{))
14490 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14491 `(equal todo ,kwd))))
14492 (push (if minus `(not ,mm) mm) todomatcher))
14493 (setq term (substring term (match-end 0))))
14494 (push (if (> (length todomatcher) 1)
14495 (cons 'and todomatcher)
14496 (car todomatcher))
14497 orlist)
14498 (setq todomatcher nil))
14499 (setq todomatcher (cons 'or orlist))))
14501 ;; Return the string and function of the matcher. If no
14502 ;; tags-specific or todo-specific matcher exists, match
14503 ;; everything.
14504 (let ((matcher (if (and tagsmatcher todomatcher)
14505 `(and ,tagsmatcher ,todomatcher)
14506 (or tagsmatcher todomatcher t))))
14507 (when org--matcher-tags-todo-only
14508 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14509 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14511 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14512 "Expand group tags in MATCH.
14514 This replaces every group tag in MATCH with a regexp tag search.
14515 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14516 will be replaced like this:
14518 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14519 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14520 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14522 Replacing by a regexp preserves the structure of the match.
14523 E.g., this expansion
14525 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14527 will match anything tagged with \"Lab\" and \"Home\", or tagged
14528 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14530 A group tag in MATCH can contain regular expressions of its own.
14531 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14532 will be replaced like this:
14534 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14536 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14537 assumed to be a single group tag, and the function will return
14538 the list of tags in this group.
14540 When DOWNCASE is non-nil, expand downcased TAGS."
14541 (if org-group-tags
14542 (let* ((case-fold-search t)
14543 (stable org-mode-syntax-table)
14544 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14545 (taggroups (if downcased
14546 (mapcar (lambda (tg) (mapcar #'downcase tg))
14547 taggroups)
14548 taggroups))
14549 (taggroups-keys (mapcar #'car taggroups))
14550 (return-match (if downcased (downcase match) match))
14551 (count 0)
14552 (work-already-expanded tags-already-expanded)
14553 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14554 ;; @ and _ are allowed as word-components in tags.
14555 (modify-syntax-entry ?@ "w" stable)
14556 (modify-syntax-entry ?_ "w" stable)
14557 ;; Temporarily replace regexp-expressions in the match-expression.
14558 (while (string-match "{.+?}" return-match)
14559 (cl-incf count)
14560 (push (match-string 0 return-match) regexps-in-match)
14561 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14562 (while (and taggroups-keys
14563 (with-syntax-table stable
14564 (string-match
14565 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14566 (regexp-opt taggroups-keys) "\\>\\)")
14567 return-match)))
14568 (let* ((dir (match-string 1 return-match))
14569 (tag (match-string 2 return-match))
14570 (tag (if downcased (downcase tag) tag)))
14571 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14572 (member tag work-already-expanded))
14573 (setq tags-in-group (assoc tag taggroups))
14574 (push tag work-already-expanded)
14575 ;; Recursively expand each tag in the group, if the tag hasn't
14576 ;; already been expanded. Restore the match-data after all recursive calls.
14577 (save-match-data
14578 (let (tags-expanded)
14579 (dolist (x (cdr tags-in-group))
14580 (if (and (member x taggroups-keys)
14581 (not (member x work-already-expanded)))
14582 (setq tags-expanded
14583 (delete-dups
14584 (append
14585 (org-tags-expand x t downcased
14586 work-already-expanded)
14587 tags-expanded)))
14588 (setq tags-expanded
14589 (append (list x) tags-expanded)))
14590 (setq work-already-expanded
14591 (delete-dups
14592 (append tags-expanded
14593 work-already-expanded))))
14594 (setq tags-in-group
14595 (delete-dups (cons (car tags-in-group)
14596 tags-expanded)))))
14597 ;; Filter tag-regexps from tags.
14598 (setq regexp-in-group-escaped
14599 (delq nil (mapcar (lambda (x)
14600 (if (stringp x)
14601 (and (equal "{" (substring x 0 1))
14602 (equal "}" (substring x -1))
14605 tags-in-group))
14606 regexp-in-group
14607 (mapcar (lambda (x)
14608 (substring x 1 -1))
14609 regexp-in-group-escaped)
14610 tags-in-group
14611 (delq nil (mapcar (lambda (x)
14612 (if (stringp x)
14613 (and (not (equal "{" (substring x 0 1)))
14614 (not (equal "}" (substring x -1)))
14617 tags-in-group)))
14618 ;; If single-as-list, do no more in the while-loop.
14619 (if (not single-as-list)
14620 (progn
14621 (when regexp-in-group
14622 (setq regexp-in-group
14623 (concat "\\|"
14624 (mapconcat 'identity regexp-in-group
14625 "\\|"))))
14626 (setq tags-in-group
14627 (concat dir
14628 "{\\<"
14629 (regexp-opt tags-in-group)
14630 "\\>"
14631 regexp-in-group
14632 "}"))
14633 (when (stringp tags-in-group)
14634 (org-add-props tags-in-group '(grouptag t)))
14635 (setq return-match
14636 (replace-match tags-in-group t t return-match)))
14637 (setq tags-in-group
14638 (append regexp-in-group-escaped tags-in-group))))
14639 (setq taggroups-keys (delete tag taggroups-keys))))
14640 ;; Add the regular expressions back into the match-expression again.
14641 (while regexps-in-match
14642 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14643 (pop regexps-in-match)
14644 return-match t t))
14645 (cl-decf count))
14646 (if single-as-list
14647 (if tags-in-group tags-in-group (list return-match))
14648 return-match))
14649 (if single-as-list
14650 (list (if downcased (downcase match) match))
14651 match)))
14653 (defun org-op-to-function (op &optional stringp)
14654 "Turn an operator into the appropriate function."
14655 (setq op
14656 (cond
14657 ((equal op "<" ) '(< string< org-time<))
14658 ((equal op ">" ) '(> org-string> org-time>))
14659 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14660 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14661 ((member op '("=" "==")) '(= string= org-time=))
14662 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14663 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14665 (defun org<> (a b) (not (= a b)))
14666 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14667 (defun org-string>= (a b) (not (string< a b)))
14668 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14669 (defun org-string<> (a b) (not (string= a b)))
14670 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14671 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14672 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14673 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14674 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14675 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14676 (defun org-2ft (s)
14677 "Convert S to a floating point time.
14678 If S is already a number, just return it. If it is a string, parse
14679 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14680 (cond
14681 ((numberp s) s)
14682 ((stringp s)
14683 (condition-case nil
14684 (float-time (apply 'encode-time (org-parse-time-string s)))
14685 (error 0.)))
14686 (t 0.)))
14688 (defun org-time-today ()
14689 "Time in seconds today at 0:00.
14690 Returns the float number of seconds since the beginning of the
14691 epoch to the beginning of today (00:00)."
14692 (float-time (apply 'encode-time
14693 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14695 (defun org-matcher-time (s)
14696 "Interpret a time comparison value."
14697 (save-match-data
14698 (cond
14699 ((string= s "<now>") (float-time))
14700 ((string= s "<today>") (org-time-today))
14701 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14702 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14703 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14704 (+ (org-time-today)
14705 (* (string-to-number (match-string 1 s))
14706 (cdr (assoc (match-string 2 s)
14707 '(("d" . 86400.0) ("w" . 604800.0)
14708 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14709 (t (org-2ft s)))))
14711 (defun org-match-any-p (re list)
14712 "Does re match any element of list?"
14713 (setq list (mapcar (lambda (x) (string-match re x)) list))
14714 (delq nil list))
14716 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14717 (defvar org-tags-overlay (make-overlay 1 1))
14718 (delete-overlay org-tags-overlay)
14720 (defun org-get-local-tags-at (&optional pos)
14721 "Get a list of tags defined in the current headline."
14722 (org-get-tags-at pos 'local))
14724 (defun org-get-local-tags ()
14725 "Get a list of tags defined in the current headline."
14726 (org-get-tags-at nil 'local))
14728 (defun org-get-tags-at (&optional pos local)
14729 "Get a list of all headline tags applicable at POS.
14730 POS defaults to point. If tags are inherited, the list contains
14731 the targets in the same sequence as the headlines appear, i.e.
14732 the tags of the current headline come last.
14733 When LOCAL is non-nil, only return tags from the current headline,
14734 ignore inherited ones."
14735 (interactive)
14736 (if (and org-trust-scanner-tags
14737 (or (not pos) (equal pos (point)))
14738 (not local))
14739 org-scanner-tags
14740 (let (tags ltags lastpos parent)
14741 (save-excursion
14742 (save-restriction
14743 (widen)
14744 (goto-char (or pos (point)))
14745 (save-match-data
14746 (catch 'done
14747 (condition-case nil
14748 (progn
14749 (org-back-to-heading t)
14750 (while (not (equal lastpos (point)))
14751 (setq lastpos (point))
14752 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14753 (setq ltags (org-split-string
14754 (match-string-no-properties 1) ":"))
14755 (when parent
14756 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14757 (setq tags (append
14758 (if parent
14759 (org-remove-uninherited-tags ltags)
14760 ltags)
14761 tags)))
14762 (or org-use-tag-inheritance (throw 'done t))
14763 (when local (throw 'done t))
14764 (or (org-up-heading-safe) (error nil))
14765 (setq parent t)))
14766 (error nil)))))
14767 (if local
14768 tags
14769 (reverse (delete-dups
14770 (reverse (append
14771 (org-remove-uninherited-tags
14772 org-file-tags)
14773 tags)))))))))
14775 (defun org-add-prop-inherited (s)
14776 (add-text-properties 0 (length s) '(inherited t) s)
14779 (defun org-toggle-tag (tag &optional onoff)
14780 "Toggle the tag TAG for the current line.
14781 If ONOFF is `on' or `off', don't toggle but set to this state."
14782 (let (res current)
14783 (save-excursion
14784 (org-back-to-heading t)
14785 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14786 (point-at-eol) t)
14787 (progn
14788 (setq current (match-string 1))
14789 (replace-match ""))
14790 (setq current ""))
14791 (setq current (nreverse (org-split-string current ":")))
14792 (cond
14793 ((eq onoff 'on)
14794 (setq res t)
14795 (or (member tag current) (push tag current)))
14796 ((eq onoff 'off)
14797 (or (not (member tag current)) (setq current (delete tag current))))
14798 (t (if (member tag current)
14799 (setq current (delete tag current))
14800 (setq res t)
14801 (push tag current))))
14802 (end-of-line 1)
14803 (if current
14804 (progn
14805 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14806 (org-set-tags nil t))
14807 (delete-horizontal-space))
14808 (run-hooks 'org-after-tags-change-hook))
14809 res))
14811 (defun org--align-tags-here (to-col)
14812 "Align tags on the current headline to TO-COL.
14813 Assume point is on a headline."
14814 (let ((pos (point)))
14815 (beginning-of-line)
14816 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14817 (>= pos (match-beginning 2)))
14818 ;; No tags or point within tags: do not align.
14819 (goto-char pos)
14820 (goto-char (match-beginning 1))
14821 (let ((shift (max (- (if (>= to-col 0) to-col
14822 (- (abs to-col) (string-width (match-string 2))))
14823 (current-column))
14824 1)))
14825 (replace-match (make-string shift ?\s) nil nil nil 1)
14826 ;; Preserve initial position, if possible. In any case, stop
14827 ;; before tags.
14828 (when (< pos (point)) (goto-char pos))))))
14830 (defun org-set-tags-command (&optional arg just-align)
14831 "Call the set-tags command for the current entry."
14832 (interactive "P")
14833 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14834 (org-set-tags arg just-align)
14835 (save-excursion
14836 (unless (and (org-region-active-p)
14837 org-loop-over-headlines-in-active-region)
14838 (org-back-to-heading t))
14839 (org-set-tags arg just-align))))
14841 (defun org-set-tags-to (data)
14842 "Set the tags of the current entry to DATA, replacing the current tags.
14843 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14844 If DATA is nil or the empty string, any tags will be removed."
14845 (interactive "sTags: ")
14846 (setq data
14847 (cond
14848 ((eq data nil) "")
14849 ((equal data "") "")
14850 ((stringp data)
14851 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14852 ":"))
14853 ((listp data)
14854 (concat ":" (mapconcat 'identity data ":") ":"))))
14855 (when data
14856 (save-excursion
14857 (org-back-to-heading t)
14858 (when (let ((case-fold-search nil))
14859 (looking-at org-complex-heading-regexp))
14860 (if (match-end 5)
14861 (progn
14862 (goto-char (match-beginning 5))
14863 (insert data)
14864 (delete-region (point) (point-at-eol))
14865 (org-set-tags nil 'align))
14866 (goto-char (point-at-eol))
14867 (insert " " data)
14868 (org-set-tags nil 'align)))
14869 (beginning-of-line 1)
14870 (when (looking-at ".*?\\([ \t]+\\)$")
14871 (delete-region (match-beginning 1) (match-end 1))))))
14873 (defun org-align-all-tags ()
14874 "Align the tags in all headings."
14875 (interactive)
14876 (save-excursion
14877 (or (ignore-errors (org-back-to-heading t))
14878 (outline-next-heading))
14879 (if (org-at-heading-p)
14880 (org-set-tags t)
14881 (message "No headings"))))
14883 (defvar org-indent-indentation-per-level)
14884 (defun org-set-tags (&optional arg just-align)
14885 "Set the tags for the current headline.
14886 With prefix ARG, realign all tags in headings in the current buffer.
14887 When JUST-ALIGN is non-nil, only align tags."
14888 (interactive "P")
14889 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14890 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14891 'region-start-level
14892 'region))
14893 org-loop-over-headlines-in-active-region)
14894 (org-map-entries
14895 ;; We don't use ARG and JUST-ALIGN here because these args
14896 ;; are not useful when looping over headlines.
14897 #'org-set-tags
14898 org-loop-over-headlines-in-active-region
14900 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14901 (let ((org-setting-tags t))
14902 (if arg
14903 (save-excursion
14904 (goto-char (point-min))
14905 (while (re-search-forward org-outline-regexp-bol nil t)
14906 (org-set-tags nil t)
14907 (end-of-line))
14908 (message "All tags realigned to column %d" org-tags-column))
14909 (let* ((current (org-get-tags-string))
14910 (tags
14911 (if just-align current
14912 ;; Get a new set of tags from the user.
14913 (save-excursion
14914 (let* ((seen)
14915 (table
14916 (setq
14917 org-last-tags-completion-table
14918 ;; Uniquify tags in alists, yet preserve
14919 ;; structure (i.e., keywords).
14920 (delq nil
14921 (mapcar
14922 (lambda (pair)
14923 (let ((head (car pair)))
14924 (cond ((symbolp head) pair)
14925 ((member head seen) nil)
14926 (t (push head seen)
14927 pair))))
14928 (append
14929 (or org-current-tag-alist
14930 (org-get-buffer-tags))
14931 (and
14932 org-complete-tags-always-offer-all-agenda-tags
14933 (org-global-tags-completion-table
14934 (org-agenda-files))))))))
14935 (current-tags (org-split-string current ":"))
14936 (inherited-tags
14937 (nreverse (nthcdr (length current-tags)
14938 (nreverse (org-get-tags-at))))))
14939 (replace-regexp-in-string
14940 "\\([-+&]+\\|,\\)"
14942 (if (or (eq t org-use-fast-tag-selection)
14943 (and org-use-fast-tag-selection
14944 (delq nil (mapcar #'cdr table))))
14945 (org-fast-tag-selection
14946 current-tags inherited-tags table
14947 (and org-fast-tag-selection-include-todo
14948 org-todo-key-alist))
14949 (let ((org-add-colon-after-tag-completion
14950 (< 1 (length table))))
14951 (org-trim
14952 (completing-read
14953 "Tags: "
14954 #'org-tags-completion-function
14955 nil nil current 'org-tags-history))))))))))
14957 (when org-tags-sort-function
14958 (setq tags
14959 (mapconcat
14960 #'identity
14961 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14962 org-tags-sort-function)
14963 ":")))
14965 (if (not (org-string-nw-p tags)) (setq tags "")
14966 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14967 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14969 ;; Insert new tags at the correct column.
14970 (unless (equal current tags)
14971 (save-excursion
14972 (beginning-of-line)
14973 (let ((case-fold-search nil))
14974 (looking-at org-complex-heading-regexp))
14975 ;; Remove current tags, if any.
14976 (when (match-end 5) (replace-match "" nil nil nil 5))
14977 ;; Insert new tags, if any. Otherwise, remove trailing
14978 ;; white spaces.
14979 (end-of-line)
14980 (if (not (equal tags ""))
14981 ;; When text is being inserted on an invisible
14982 ;; region boundary, it can be inadvertently sucked
14983 ;; into invisibility.
14984 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14985 (skip-chars-backward " \t")
14986 (delete-region (point) (line-end-position)))))
14987 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14988 ;; is on.
14989 (unless (equal tags "")
14990 (let* ((level (save-excursion
14991 (beginning-of-line)
14992 (skip-chars-forward "\\*")))
14993 (offset (if (bound-and-true-p org-indent-mode)
14994 (* (1- org-indent-indentation-per-level)
14995 (1- level))
14997 (tags-column
14998 (+ org-tags-column
14999 (if (> org-tags-column 0) (- offset) offset))))
15000 (org--align-tags-here tags-column))))
15001 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15003 (defun org-change-tag-in-region (beg end tag off)
15004 "Add or remove TAG for each entry in the region.
15005 This works in the agenda, and also in an Org buffer."
15006 (interactive
15007 (list (region-beginning) (region-end)
15008 (let ((org-last-tags-completion-table
15009 (if (derived-mode-p 'org-mode)
15010 (org-uniquify
15011 (delq nil (append (org-get-buffer-tags)
15012 (org-global-tags-completion-table))))
15013 (org-global-tags-completion-table))))
15014 (completing-read
15015 "Tag: " 'org-tags-completion-function nil nil nil
15016 'org-tags-history))
15017 (progn
15018 (message "[s]et or [r]emove? ")
15019 (equal (read-char-exclusive) ?r))))
15020 (when (fboundp 'deactivate-mark) (deactivate-mark))
15021 (let ((agendap (equal major-mode 'org-agenda-mode))
15022 l1 l2 m buf pos newhead (cnt 0))
15023 (goto-char end)
15024 (setq l2 (1- (org-current-line)))
15025 (goto-char beg)
15026 (setq l1 (org-current-line))
15027 (cl-loop for l from l1 to l2 do
15028 (org-goto-line l)
15029 (setq m (get-text-property (point) 'org-hd-marker))
15030 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15031 (and agendap m))
15032 (setq buf (if agendap (marker-buffer m) (current-buffer))
15033 pos (if agendap m (point)))
15034 (with-current-buffer buf
15035 (save-excursion
15036 (save-restriction
15037 (goto-char pos)
15038 (setq cnt (1+ cnt))
15039 (org-toggle-tag tag (if off 'off 'on))
15040 (setq newhead (org-get-heading)))))
15041 (and agendap (org-agenda-change-all-lines newhead m))))
15042 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15044 (defun org-tags-completion-function (string _predicate &optional flag)
15045 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15046 (confirm (lambda (x) (stringp (car x)))))
15047 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15048 (setq s1 (match-string 1 string)
15049 s2 (match-string 2 string))
15050 (setq s1 "" s2 string))
15051 (cond
15052 ((eq flag nil)
15053 ;; try completion
15054 (setq rtn (try-completion s2 ctable confirm))
15055 (when (stringp rtn)
15056 (setq rtn
15057 (concat s1 s2 (substring rtn (length s2))
15058 (if (and org-add-colon-after-tag-completion
15059 (assoc rtn ctable))
15060 ":" ""))))
15061 rtn)
15062 ((eq flag t)
15063 ;; all-completions
15064 (all-completions s2 ctable confirm))
15065 ((eq flag 'lambda)
15066 ;; exact match?
15067 (assoc s2 ctable)))))
15069 (defun org-fast-tag-insert (kwd tags face &optional end)
15070 "Insert KDW, and the TAGS, the latter with face FACE.
15071 Also insert END."
15072 (insert (format "%-12s" (concat kwd ":"))
15073 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15074 (or end "")))
15076 (defun org-fast-tag-show-exit (flag)
15077 (save-excursion
15078 (org-goto-line 3)
15079 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15080 (replace-match ""))
15081 (when flag
15082 (end-of-line 1)
15083 (org-move-to-column (- (window-width) 19) t)
15084 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15086 (defun org-set-current-tags-overlay (current prefix)
15087 "Add an overlay to CURRENT tag with PREFIX."
15088 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15089 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15090 (org-overlay-display org-tags-overlay (concat prefix s))))
15092 (defvar org-last-tag-selection-key nil)
15093 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15094 "Fast tag selection with single keys.
15095 CURRENT is the current list of tags in the headline, INHERITED is the
15096 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15097 possibly with grouping information. TODO-TABLE is a similar table with
15098 TODO keywords, should these have keys assigned to them.
15099 If the keys are nil, a-z are automatically assigned.
15100 Returns the new tags string, or nil to not change the current settings."
15101 (let* ((fulltable (append table todo-table))
15102 (maxlen (apply 'max (mapcar
15103 (lambda (x)
15104 (if (stringp (car x)) (string-width (car x)) 0))
15105 fulltable)))
15106 (buf (current-buffer))
15107 (expert (eq org-fast-tag-selection-single-key 'expert))
15108 (buffer-tags nil)
15109 (fwidth (+ maxlen 3 1 3))
15110 (ncol (/ (- (window-width) 4) fwidth))
15111 (i-face 'org-done)
15112 (c-face 'org-todo)
15113 tg cnt e c char c1 c2 ntable tbl rtn
15114 ov-start ov-end ov-prefix
15115 (exit-after-next org-fast-tag-selection-single-key)
15116 (done-keywords org-done-keywords)
15117 groups ingroup intaggroup)
15118 (save-excursion
15119 (beginning-of-line 1)
15120 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15121 (setq ov-start (match-beginning 1)
15122 ov-end (match-end 1)
15123 ov-prefix "")
15124 (setq ov-start (1- (point-at-eol))
15125 ov-end (1+ ov-start))
15126 (skip-chars-forward "^\n\r")
15127 (setq ov-prefix
15128 (concat
15129 (buffer-substring (1- (point)) (point))
15130 (if (> (current-column) org-tags-column)
15132 (make-string (- org-tags-column (current-column)) ?\ ))))))
15133 (move-overlay org-tags-overlay ov-start ov-end)
15134 (save-window-excursion
15135 (if expert
15136 (set-buffer (get-buffer-create " *Org tags*"))
15137 (delete-other-windows)
15138 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15139 (org-switch-to-buffer-other-window " *Org tags*"))
15140 (erase-buffer)
15141 (setq-local org-done-keywords done-keywords)
15142 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15143 (org-fast-tag-insert "Current" current c-face "\n\n")
15144 (org-fast-tag-show-exit exit-after-next)
15145 (org-set-current-tags-overlay current ov-prefix)
15146 (setq tbl fulltable char ?a cnt 0)
15147 (while (setq e (pop tbl))
15148 (cond
15149 ((eq (car e) :startgroup)
15150 (push '() groups) (setq ingroup t)
15151 (unless (zerop cnt)
15152 (setq cnt 0)
15153 (insert "\n"))
15154 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15155 ((eq (car e) :endgroup)
15156 (setq ingroup nil cnt 0)
15157 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15158 ((eq (car e) :startgrouptag)
15159 (setq intaggroup t)
15160 (unless (zerop cnt)
15161 (setq cnt 0)
15162 (insert "\n"))
15163 (insert "[ "))
15164 ((eq (car e) :endgrouptag)
15165 (setq intaggroup nil cnt 0)
15166 (insert "]\n"))
15167 ((equal e '(:newline))
15168 (unless (zerop cnt)
15169 (setq cnt 0)
15170 (insert "\n")
15171 (setq e (car tbl))
15172 (while (equal (car tbl) '(:newline))
15173 (insert "\n")
15174 (setq tbl (cdr tbl)))))
15175 ((equal e '(:grouptags)) (insert " : "))
15177 (setq tg (copy-sequence (car e)) c2 nil)
15178 (if (cdr e)
15179 (setq c (cdr e))
15180 ;; automatically assign a character.
15181 (setq c1 (string-to-char
15182 (downcase (substring
15183 tg (if (= (string-to-char tg) ?@) 1 0)))))
15184 (if (or (rassoc c1 ntable) (rassoc c1 table))
15185 (while (or (rassoc char ntable) (rassoc char table))
15186 (setq char (1+ char)))
15187 (setq c2 c1))
15188 (setq c (or c2 char)))
15189 (when ingroup (push tg (car groups)))
15190 (setq tg (org-add-props tg nil 'face
15191 (cond
15192 ((not (assoc tg table))
15193 (org-get-todo-face tg))
15194 ((member tg current) c-face)
15195 ((member tg inherited) i-face))))
15196 (when (equal (caar tbl) :grouptags)
15197 (org-add-props tg nil 'face 'org-tag-group))
15198 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15199 (insert "[" c "] " tg (make-string
15200 (- fwidth 4 (length tg)) ?\ ))
15201 (push (cons tg c) ntable)
15202 (when (= (cl-incf cnt) ncol)
15203 (insert "\n")
15204 (when (or ingroup intaggroup) (insert " "))
15205 (setq cnt 0)))))
15206 (setq ntable (nreverse ntable))
15207 (insert "\n")
15208 (goto-char (point-min))
15209 (unless expert (org-fit-window-to-buffer))
15210 (setq rtn
15211 (catch 'exit
15212 (while t
15213 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15214 (if (not groups) "no " "")
15215 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15216 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15217 (setq org-last-tag-selection-key c)
15218 (cond
15219 ((= c ?\r) (throw 'exit t))
15220 ((= c ?!)
15221 (setq groups (not groups))
15222 (goto-char (point-min))
15223 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15224 ((= c ?\C-c)
15225 (if (not expert)
15226 (org-fast-tag-show-exit
15227 (setq exit-after-next (not exit-after-next)))
15228 (setq expert nil)
15229 (delete-other-windows)
15230 (set-window-buffer (split-window-vertically) " *Org tags*")
15231 (org-switch-to-buffer-other-window " *Org tags*")
15232 (org-fit-window-to-buffer)))
15233 ((or (= c ?\C-g)
15234 (and (= c ?q) (not (rassoc c ntable))))
15235 (delete-overlay org-tags-overlay)
15236 (setq quit-flag t))
15237 ((= c ?\ )
15238 (setq current nil)
15239 (when exit-after-next (setq exit-after-next 'now)))
15240 ((= c ?\t)
15241 (condition-case nil
15242 (setq tg (completing-read
15243 "Tag: "
15244 (or buffer-tags
15245 (with-current-buffer buf
15246 (setq buffer-tags
15247 (org-get-buffer-tags))))))
15248 (quit (setq tg "")))
15249 (when (string-match "\\S-" tg)
15250 (cl-pushnew (list tg) buffer-tags :test #'equal)
15251 (if (member tg current)
15252 (setq current (delete tg current))
15253 (push tg current)))
15254 (when exit-after-next (setq exit-after-next 'now)))
15255 ((setq e (rassoc c todo-table) tg (car e))
15256 (with-current-buffer buf
15257 (save-excursion (org-todo tg)))
15258 (when exit-after-next (setq exit-after-next 'now)))
15259 ((setq e (rassoc c ntable) tg (car e))
15260 (if (member tg current)
15261 (setq current (delete tg current))
15262 (cl-loop for g in groups do
15263 (when (member tg g)
15264 (dolist (x g) (setq current (delete x current)))))
15265 (push tg current))
15266 (when exit-after-next (setq exit-after-next 'now))))
15268 ;; Create a sorted list
15269 (setq current
15270 (sort current
15271 (lambda (a b)
15272 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15273 (when (eq exit-after-next 'now) (throw 'exit t))
15274 (goto-char (point-min))
15275 (beginning-of-line 2)
15276 (delete-region (point) (point-at-eol))
15277 (org-fast-tag-insert "Current" current c-face)
15278 (org-set-current-tags-overlay current ov-prefix)
15279 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15280 (setq tg (match-string 1))
15281 (add-text-properties
15282 (match-beginning 1) (match-end 1)
15283 (list 'face
15284 (cond
15285 ((member tg current) c-face)
15286 ((member tg inherited) i-face)
15287 (t (get-text-property (match-beginning 1) 'face))))))
15288 (goto-char (point-min)))))
15289 (delete-overlay org-tags-overlay)
15290 (if rtn
15291 (mapconcat 'identity current ":")
15292 nil))))
15294 (defun org-get-tags-string ()
15295 "Get the TAGS string in the current headline."
15296 (unless (org-at-heading-p t)
15297 (user-error "Not on a heading"))
15298 (save-excursion
15299 (beginning-of-line 1)
15300 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15301 (match-string-no-properties 1)
15302 "")))
15304 (defun org-get-tags ()
15305 "Get the list of tags specified in the current headline."
15306 (org-split-string (org-get-tags-string) ":"))
15308 (defun org-get-buffer-tags ()
15309 "Get a table of all tags used in the buffer, for completion."
15310 (org-with-wide-buffer
15311 (goto-char (point-min))
15312 (let ((tag-re (concat org-outline-regexp-bol
15313 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15314 tags)
15315 (while (re-search-forward tag-re nil t)
15316 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15317 (push tag tags)))
15318 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15320 ;;;; The mapping API
15322 (defvar org-agenda-skip-comment-trees)
15323 (defvar org-agenda-skip-function)
15324 (defun org-map-entries (func &optional match scope &rest skip)
15325 "Call FUNC at each headline selected by MATCH in SCOPE.
15327 FUNC is a function or a lisp form. The function will be called without
15328 arguments, with the cursor positioned at the beginning of the headline.
15329 The return values of all calls to the function will be collected and
15330 returned as a list.
15332 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15333 does not need to preserve point. After evaluation, the cursor will be
15334 moved to the end of the line (presumably of the headline of the
15335 processed entry) and search continues from there. Under some
15336 circumstances, this may not produce the wanted results. For example,
15337 if you have removed (e.g. archived) the current (sub)tree it could
15338 mean that the next entry will be skipped entirely. In such cases, you
15339 can specify the position from where search should continue by making
15340 FUNC set the variable `org-map-continue-from' to the desired buffer
15341 position.
15343 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15344 Only headlines that are matched by this query will be considered during
15345 the iteration. When MATCH is nil or t, all headlines will be
15346 visited by the iteration.
15348 SCOPE determines the scope of this command. It can be any of:
15350 nil The current buffer, respecting the restriction if any
15351 tree The subtree started with the entry at point
15352 region The entries within the active region, if any
15353 region-start-level
15354 The entries within the active region, but only those at
15355 the same level than the first one.
15356 file The current buffer, without restriction
15357 file-with-archives
15358 The current buffer, and any archives associated with it
15359 agenda All agenda files
15360 agenda-with-archives
15361 All agenda files with any archive files associated with them
15362 \(file1 file2 ...)
15363 If this is a list, all files in the list will be scanned
15365 The remaining args are treated as settings for the skipping facilities of
15366 the scanner. The following items can be given here:
15368 archive skip trees with the archive tag
15369 comment skip trees with the COMMENT keyword
15370 function or Emacs Lisp form:
15371 will be used as value for `org-agenda-skip-function', so
15372 whenever the function returns a position, FUNC will not be
15373 called for that entry and search will continue from the
15374 position returned
15376 If your function needs to retrieve the tags including inherited tags
15377 at the *current* entry, you can use the value of the variable
15378 `org-scanner-tags' which will be much faster than getting the value
15379 with `org-get-tags-at'. If your function gets properties with
15380 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15381 to t around the call to `org-entry-properties' to get the same speedup.
15382 Note that if your function moves around to retrieve tags and properties at
15383 a *different* entry, you cannot use these techniques."
15384 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15385 (not (org-region-active-p)))
15386 (let* ((org-agenda-archives-mode nil) ; just to make sure
15387 (org-agenda-skip-archived-trees (memq 'archive skip))
15388 (org-agenda-skip-comment-trees (memq 'comment skip))
15389 (org-agenda-skip-function
15390 (car (org-delete-all '(comment archive) skip)))
15391 (org-tags-match-list-sublevels t)
15392 (start-level (eq scope 'region-start-level))
15393 matcher res
15394 org-todo-keywords-for-agenda
15395 org-done-keywords-for-agenda
15396 org-todo-keyword-alist-for-agenda
15397 org-tag-alist-for-agenda
15398 org--matcher-tags-todo-only)
15400 (cond
15401 ((eq match t) (setq matcher t))
15402 ((eq match nil) (setq matcher t))
15403 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15405 (save-excursion
15406 (save-restriction
15407 (cond ((eq scope 'tree)
15408 (org-back-to-heading t)
15409 (org-narrow-to-subtree)
15410 (setq scope nil))
15411 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15412 (org-region-active-p))
15413 ;; If needed, set start-level to a string like "2"
15414 (when start-level
15415 (save-excursion
15416 (goto-char (region-beginning))
15417 (unless (org-at-heading-p) (outline-next-heading))
15418 (setq start-level (org-current-level))))
15419 (narrow-to-region (region-beginning)
15420 (save-excursion
15421 (goto-char (region-end))
15422 (unless (and (bolp) (org-at-heading-p))
15423 (outline-next-heading))
15424 (point)))
15425 (setq scope nil)))
15427 (if (not scope)
15428 (progn
15429 (org-agenda-prepare-buffers
15430 (and buffer-file-name (list buffer-file-name)))
15431 (setq res
15432 (org-scan-tags
15433 func matcher org--matcher-tags-todo-only start-level)))
15434 ;; Get the right scope
15435 (cond
15436 ((and scope (listp scope) (symbolp (car scope)))
15437 (setq scope (eval scope)))
15438 ((eq scope 'agenda)
15439 (setq scope (org-agenda-files t)))
15440 ((eq scope 'agenda-with-archives)
15441 (setq scope (org-agenda-files t))
15442 (setq scope (org-add-archive-files scope)))
15443 ((eq scope 'file)
15444 (setq scope (and buffer-file-name (list buffer-file-name))))
15445 ((eq scope 'file-with-archives)
15446 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15447 (org-agenda-prepare-buffers scope)
15448 (dolist (file scope)
15449 (with-current-buffer (org-find-base-buffer-visiting file)
15450 (org-with-wide-buffer
15451 (goto-char (point-min))
15452 (setq res
15453 (append
15455 (org-scan-tags
15456 func matcher org--matcher-tags-todo-only)))))))))
15457 res)))
15459 ;;; Properties API
15461 (defconst org-special-properties
15462 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15463 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15464 "The special properties valid in Org mode.
15465 These are properties that are not defined in the property drawer,
15466 but in some other way.")
15468 (defconst org-default-properties
15469 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15470 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15471 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15472 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15473 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15474 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15475 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15476 "Some properties that are used by Org mode for various purposes.
15477 Being in this list makes sure that they are offered for completion.")
15479 (defun org--valid-property-p (property)
15480 "Non nil when string PROPERTY is a valid property name."
15481 (not
15482 (or (equal property "")
15483 (string-match-p "\\s-" property))))
15485 (defun org--update-property-plist (key val props)
15486 "Associate KEY to VAL in alist PROPS.
15487 Modifications are made by side-effect. Return new alist."
15488 (let* ((appending (string= (substring key -1) "+"))
15489 (key (if appending (substring key 0 -1) key))
15490 (old (assoc-string key props t)))
15491 (if (not old) (cons (cons key val) props)
15492 (setcdr old (if appending (concat (cdr old) " " val) val))
15493 props)))
15495 (defun org-get-property-block (&optional beg force)
15496 "Return the (beg . end) range of the body of the property drawer.
15497 BEG is the beginning of the current subtree, or of the part
15498 before the first headline. If it is not given, it will be found.
15499 If the drawer does not exist, create it if FORCE is non-nil, or
15500 return nil."
15501 (org-with-wide-buffer
15502 (when beg (goto-char beg))
15503 (unless (org-before-first-heading-p)
15504 (let ((beg (cond (beg)
15505 ((or (not (featurep 'org-inlinetask))
15506 (org-inlinetask-in-task-p))
15507 (org-back-to-heading t))
15508 (t (org-with-limited-levels (org-back-to-heading t))))))
15509 (forward-line)
15510 (when (looking-at-p org-planning-line-re) (forward-line))
15511 (cond ((looking-at org-property-drawer-re)
15512 (forward-line)
15513 (cons (point) (progn (goto-char (match-end 0))
15514 (line-beginning-position))))
15515 (force
15516 (goto-char beg)
15517 (org-insert-property-drawer)
15518 (let ((pos (save-excursion (search-forward ":END:")
15519 (line-beginning-position))))
15520 (cons pos pos))))))))
15522 (defun org-at-property-p ()
15523 "Non-nil when point is inside a property drawer.
15524 See `org-property-re' for match data, if applicable."
15525 (save-excursion
15526 (beginning-of-line)
15527 (and (looking-at org-property-re)
15528 (let ((property-drawer (save-match-data (org-get-property-block))))
15529 (and property-drawer
15530 (>= (point) (car property-drawer))
15531 (< (point) (cdr property-drawer)))))))
15533 (defun org-property-action ()
15534 "Do an action on properties."
15535 (interactive)
15536 (unless (org-at-property-p) (user-error "Not at a property"))
15537 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15538 (let ((c (read-char-exclusive)))
15539 (cl-case c
15540 (?s (call-interactively #'org-set-property))
15541 (?d (call-interactively #'org-delete-property))
15542 (?D (call-interactively #'org-delete-property-globally))
15543 (?c (call-interactively #'org-compute-property-at-point))
15544 (otherwise (user-error "No such property action %c" c)))))
15546 (defun org-inc-effort ()
15547 "Increment the value of the effort property in the current entry."
15548 (interactive)
15549 (org-set-effort nil t))
15551 (defvar org-clock-effort) ; Defined in org-clock.el.
15552 (defvar org-clock-current-task) ; Defined in org-clock.el.
15553 (defun org-set-effort (&optional value increment)
15554 "Set the effort property of the current entry.
15555 With numerical prefix arg, use the nth allowed value, 0 stands for the
15556 10th allowed value.
15558 When INCREMENT is non-nil, set the property to the next allowed value."
15559 (interactive "P")
15560 (when (equal value 0) (setq value 10))
15561 (let* ((completion-ignore-case t)
15562 (prop org-effort-property)
15563 (cur (org-entry-get nil prop))
15564 (allowed (org-property-get-allowed-values nil prop 'table))
15565 (existing (mapcar 'list (org-property-values prop)))
15566 (heading (nth 4 (org-heading-components)))
15568 (val (cond
15569 ((stringp value) value)
15570 ((and allowed (integerp value))
15571 (or (car (nth (1- value) allowed))
15572 (car (org-last allowed))))
15573 ((and allowed increment)
15574 (or (cl-caadr (member (list cur) allowed))
15575 (user-error "Allowed effort values are not set")))
15576 (allowed
15577 (message "Select 1-9,0, [RET%s]: %s"
15578 (if cur (concat "=" cur) "")
15579 (mapconcat 'car allowed " "))
15580 (setq rpl (read-char-exclusive))
15581 (if (equal rpl ?\r)
15583 (setq rpl (- rpl ?0))
15584 (when (equal rpl 0) (setq rpl 10))
15585 (if (and (> rpl 0) (<= rpl (length allowed)))
15586 (car (nth (1- rpl) allowed))
15587 (org-completing-read "Effort: " allowed nil))))
15589 (org-completing-read
15590 (concat "Effort" (and cur (string-match "\\S-" cur)
15591 (concat " [" cur "]"))
15592 ": ")
15593 existing nil nil "" nil cur)))))
15594 (unless (equal (org-entry-get nil prop) val)
15595 (org-entry-put nil prop val))
15596 (org-refresh-property
15597 '((effort . identity)
15598 (effort-minutes . org-duration-to-minutes))
15599 val)
15600 (when (equal heading (bound-and-true-p org-clock-current-task))
15601 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15602 (org-clock-update-mode-line))
15603 (message "%s is now %s" prop val)))
15605 (defun org-entry-properties (&optional pom which)
15606 "Get all properties of the current entry.
15608 When POM is a buffer position, get all properties from the entry
15609 there instead.
15611 This includes the TODO keyword, the tags, time strings for
15612 deadline, scheduled, and clocking, and any additional properties
15613 defined in the entry.
15615 If WHICH is nil or `all', get all properties. If WHICH is
15616 `special' or `standard', only get that subclass. If WHICH is
15617 a string, only get that property.
15619 Return value is an alist. Keys are properties, as upcased
15620 strings."
15621 (org-with-point-at pom
15622 (when (and (derived-mode-p 'org-mode)
15623 (ignore-errors (org-back-to-heading t)))
15624 (catch 'exit
15625 (let* ((beg (point))
15626 (specific (and (stringp which) (upcase which)))
15627 (which (cond ((not specific) which)
15628 ((member specific org-special-properties) 'special)
15629 (t 'standard)))
15630 props)
15631 ;; Get the special properties, like TODO and TAGS.
15632 (when (memq which '(nil all special))
15633 (when (or (not specific) (string= specific "CLOCKSUM"))
15634 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15635 (when clocksum
15636 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15637 props)))
15638 (when specific (throw 'exit props)))
15639 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15640 (let ((clocksumt (get-text-property (point)
15641 :org-clock-minutes-today)))
15642 (when clocksumt
15643 (push (cons "CLOCKSUM_T"
15644 (org-duration-from-minutes clocksumt))
15645 props)))
15646 (when specific (throw 'exit props)))
15647 (when (or (not specific) (string= specific "ITEM"))
15648 (let ((case-fold-search nil))
15649 (when (looking-at org-complex-heading-regexp)
15650 (push (cons "ITEM"
15651 (let ((title (match-string-no-properties 4)))
15652 (if (org-string-nw-p title)
15653 (org-remove-tabs title)
15654 "")))
15655 props)))
15656 (when specific (throw 'exit props)))
15657 (when (or (not specific) (string= specific "TODO"))
15658 (let ((case-fold-search nil))
15659 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15660 (push (cons "TODO" (match-string-no-properties 2)) props)))
15661 (when specific (throw 'exit props)))
15662 (when (or (not specific) (string= specific "PRIORITY"))
15663 (push (cons "PRIORITY"
15664 (if (looking-at org-priority-regexp)
15665 (match-string-no-properties 2)
15666 (char-to-string org-default-priority)))
15667 props)
15668 (when specific (throw 'exit props)))
15669 (when (or (not specific) (string= specific "FILE"))
15670 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15671 props)
15672 (when specific (throw 'exit props)))
15673 (when (or (not specific) (string= specific "TAGS"))
15674 (let ((value (org-string-nw-p (org-get-tags-string))))
15675 (when value (push (cons "TAGS" value) props)))
15676 (when specific (throw 'exit props)))
15677 (when (or (not specific) (string= specific "ALLTAGS"))
15678 (let ((value (org-get-tags-at)))
15679 (when value
15680 (push (cons "ALLTAGS"
15681 (format ":%s:" (mapconcat #'identity value ":")))
15682 props)))
15683 (when specific (throw 'exit props)))
15684 (when (or (not specific) (string= specific "BLOCKED"))
15685 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15686 (when specific (throw 'exit props)))
15687 (when (or (not specific)
15688 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15689 (forward-line)
15690 (when (looking-at-p org-planning-line-re)
15691 (end-of-line)
15692 (let ((bol (line-beginning-position))
15693 ;; Backward compatibility: time keywords used to
15694 ;; be configurable (before 8.3). Make sure we
15695 ;; get the correct keyword.
15696 (key-assoc `(("CLOSED" . ,org-closed-string)
15697 ("DEADLINE" . ,org-deadline-string)
15698 ("SCHEDULED" . ,org-scheduled-string))))
15699 (dolist (pair (if specific (list (assoc specific key-assoc))
15700 key-assoc))
15701 (save-excursion
15702 (when (search-backward (cdr pair) bol t)
15703 (goto-char (match-end 0))
15704 (skip-chars-forward " \t")
15705 (and (looking-at org-ts-regexp-both)
15706 (push (cons (car pair)
15707 (match-string-no-properties 0))
15708 props)))))))
15709 (when specific (throw 'exit props)))
15710 (when (or (not specific)
15711 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15712 (let ((find-ts
15713 (lambda (end ts)
15714 ;; Fix next time-stamp before END. TS is the
15715 ;; list of time-stamps found so far.
15716 (let ((ts ts)
15717 (regexp (cond
15718 ((string= specific "TIMESTAMP")
15719 org-ts-regexp)
15720 ((string= specific "TIMESTAMP_IA")
15721 org-ts-regexp-inactive)
15722 ((assoc "TIMESTAMP_IA" ts)
15723 org-ts-regexp)
15724 ((assoc "TIMESTAMP" ts)
15725 org-ts-regexp-inactive)
15726 (t org-ts-regexp-both))))
15727 (catch 'next
15728 (while (re-search-forward regexp end t)
15729 (backward-char)
15730 (let ((object (org-element-context)))
15731 ;; Accept to match timestamps in node
15732 ;; properties, too.
15733 (when (memq (org-element-type object)
15734 '(node-property timestamp))
15735 (let ((type
15736 (org-element-property :type object)))
15737 (cond
15738 ((and (memq type '(active active-range))
15739 (not (equal specific "TIMESTAMP_IA")))
15740 (unless (assoc "TIMESTAMP" ts)
15741 (push (cons "TIMESTAMP"
15742 (org-element-property
15743 :raw-value object))
15745 (when specific (throw 'exit ts))))
15746 ((and (memq type '(inactive inactive-range))
15747 (not (string= specific "TIMESTAMP")))
15748 (unless (assoc "TIMESTAMP_IA" ts)
15749 (push (cons "TIMESTAMP_IA"
15750 (org-element-property
15751 :raw-value object))
15753 (when specific (throw 'exit ts))))))
15754 ;; Both timestamp types are found,
15755 ;; move to next part.
15756 (when (= (length ts) 2) (throw 'next ts)))))
15757 ts)))))
15758 (goto-char beg)
15759 ;; First look for timestamps within headline.
15760 (let ((ts (funcall find-ts (line-end-position) nil)))
15761 (if (= (length ts) 2) (setq props (nconc ts props))
15762 ;; Then find timestamps in the section, skipping
15763 ;; planning line.
15764 (let ((end (save-excursion (outline-next-heading))))
15765 (forward-line)
15766 (when (looking-at-p org-planning-line-re) (forward-line))
15767 (setq props (nconc (funcall find-ts end ts) props))))))))
15768 ;; Get the standard properties, like :PROP:.
15769 (when (memq which '(nil all standard))
15770 ;; If we are looking after a specific property, delegate
15771 ;; to `org-entry-get', which is faster. However, make an
15772 ;; exception for "CATEGORY", since it can be also set
15773 ;; through keywords (i.e. #+CATEGORY).
15774 (if (and specific (not (equal specific "CATEGORY")))
15775 (let ((value (org-entry-get beg specific nil t)))
15776 (throw 'exit (and value (list (cons specific value)))))
15777 (let ((range (org-get-property-block beg)))
15778 (when range
15779 (let ((end (cdr range)) seen-base)
15780 (goto-char (car range))
15781 ;; Unlike to `org--update-property-plist', we
15782 ;; handle the case where base values is found
15783 ;; after its extension. We also forbid standard
15784 ;; properties to be named as special properties.
15785 (while (re-search-forward org-property-re end t)
15786 (let* ((key (upcase (match-string-no-properties 2)))
15787 (extendp (string-match-p "\\+\\'" key))
15788 (key-base (if extendp (substring key 0 -1) key))
15789 (value (match-string-no-properties 3)))
15790 (cond
15791 ((member-ignore-case key-base org-special-properties))
15792 (extendp
15793 (setq props
15794 (org--update-property-plist key value props)))
15795 ((member key seen-base))
15796 (t (push key seen-base)
15797 (let ((p (assoc-string key props t)))
15798 (if p (setcdr p (concat value " " (cdr p)))
15799 (push (cons key value) props))))))))))))
15800 (unless (assoc "CATEGORY" props)
15801 (push (cons "CATEGORY" (org-get-category beg)) props)
15802 (when (string= specific "CATEGORY") (throw 'exit props)))
15803 ;; Return value.
15804 props)))))
15806 (defun org--property-local-values (property literal-nil)
15807 "Return value for PROPERTY in current entry.
15808 Value is a list whose car is the base value for PROPERTY and cdr
15809 a list of accumulated values. Return nil if neither is found in
15810 the entry. Also return nil when PROPERTY is set to \"nil\",
15811 unless LITERAL-NIL is non-nil."
15812 (let ((range (org-get-property-block)))
15813 (when range
15814 (goto-char (car range))
15815 (let* ((case-fold-search t)
15816 (end (cdr range))
15817 (value
15818 ;; Base value.
15819 (save-excursion
15820 (let ((v (and (re-search-forward
15821 (org-re-property property nil t) end t)
15822 (match-string-no-properties 3))))
15823 (list (if literal-nil v (org-not-nil v)))))))
15824 ;; Find additional values.
15825 (let* ((property+ (org-re-property (concat property "+") nil t)))
15826 (while (re-search-forward property+ end t)
15827 (push (match-string-no-properties 3) value)))
15828 ;; Return final values.
15829 (and (not (equal value '(nil))) (nreverse value))))))
15831 (defun org--property-global-value (property literal-nil)
15832 "Return value for PROPERTY in current buffer.
15833 Return value is a string. Return nil if property is not set
15834 globally. Also return nil when PROPERTY is set to \"nil\",
15835 unless LITERAL-NIL is non-nil."
15836 (let ((global
15837 (cdr (or (assoc-string property org-file-properties t)
15838 (assoc-string property org-global-properties t)
15839 (assoc-string property org-global-properties-fixed t)))))
15840 (if literal-nil global (org-not-nil global))))
15842 (defun org-entry-get (pom property &optional inherit literal-nil)
15843 "Get value of PROPERTY for entry or content at point-or-marker POM.
15845 If INHERIT is non-nil and the entry does not have the property,
15846 then also check higher levels of the hierarchy. If INHERIT is
15847 the symbol `selective', use inheritance only if the setting in
15848 `org-use-property-inheritance' selects PROPERTY for inheritance.
15850 If the property is present but empty, the return value is the
15851 empty string. If the property is not present at all, nil is
15852 returned. In any other case, return the value as a string.
15853 Search is case-insensitive.
15855 If LITERAL-NIL is set, return the string value \"nil\" as
15856 a string, do not interpret it as the list atom nil. This is used
15857 for inheritance when a \"nil\" value can supersede a non-nil
15858 value higher up the hierarchy."
15859 (org-with-point-at pom
15860 (cond
15861 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15862 ;; We need a special property. Use `org-entry-properties' to
15863 ;; retrieve it, but specify the wanted property.
15864 (cdr (assoc-string property (org-entry-properties nil property))))
15865 ((and inherit
15866 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15867 (org-entry-get-with-inheritance property literal-nil))
15869 (let* ((local (org--property-local-values property literal-nil))
15870 (value (and local (mapconcat #'identity (delq nil local) " "))))
15871 (if literal-nil value (org-not-nil value)))))))
15873 (defun org-property-or-variable-value (var &optional inherit)
15874 "Check if there is a property fixing the value of VAR.
15875 If yes, return this value. If not, return the current value of the variable."
15876 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15877 (if (and prop (stringp prop) (string-match "\\S-" prop))
15878 (read prop)
15879 (symbol-value var))))
15881 (defun org-entry-delete (pom property)
15882 "Delete PROPERTY from entry at point-or-marker POM.
15883 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15884 non-nil when a property was removed."
15885 (org-with-point-at pom
15886 (pcase (org-get-property-block)
15887 (`(,begin . ,origin)
15888 (let* ((end (copy-marker origin))
15889 (re (org-re-property
15890 (concat (regexp-quote property) "\\+?") t t)))
15891 (goto-char begin)
15892 (while (re-search-forward re end t)
15893 (delete-region (match-beginning 0) (line-beginning-position 2)))
15894 ;; If drawer is empty, remove it altogether.
15895 (when (= begin end)
15896 (delete-region (line-beginning-position 0)
15897 (line-beginning-position 2)))
15898 ;; Return non-nil if some property was removed.
15899 (prog1 (/= end origin) (set-marker end nil))))
15900 (_ nil))))
15902 ;; Multi-values properties are properties that contain multiple values
15903 ;; These values are assumed to be single words, separated by whitespace.
15904 (defun org-entry-add-to-multivalued-property (pom property value)
15905 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15906 (let* ((old (org-entry-get pom property))
15907 (values (and old (org-split-string old "[ \t]"))))
15908 (setq value (org-entry-protect-space value))
15909 (unless (member value values)
15910 (setq values (append values (list value)))
15911 (org-entry-put pom property
15912 (mapconcat 'identity values " ")))))
15914 (defun org-entry-remove-from-multivalued-property (pom property value)
15915 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15916 (let* ((old (org-entry-get pom property))
15917 (values (and old (org-split-string old "[ \t]"))))
15918 (setq value (org-entry-protect-space value))
15919 (when (member value values)
15920 (setq values (delete value values))
15921 (org-entry-put pom property
15922 (mapconcat 'identity values " ")))))
15924 (defun org-entry-member-in-multivalued-property (pom property value)
15925 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15926 (let* ((old (org-entry-get pom property))
15927 (values (and old (org-split-string old "[ \t]"))))
15928 (setq value (org-entry-protect-space value))
15929 (member value values)))
15931 (defun org-entry-get-multivalued-property (pom property)
15932 "Return a list of values in a multivalued property."
15933 (let* ((value (org-entry-get pom property))
15934 (values (and value (org-split-string value "[ \t]"))))
15935 (mapcar 'org-entry-restore-space values)))
15937 (defun org-entry-put-multivalued-property (pom property &rest values)
15938 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15939 VALUES should be a list of strings. Spaces will be protected."
15940 (org-entry-put pom property
15941 (mapconcat 'org-entry-protect-space values " "))
15942 (let* ((value (org-entry-get pom property))
15943 (values (and value (org-split-string value "[ \t]"))))
15944 (mapcar 'org-entry-restore-space values)))
15946 (defun org-entry-protect-space (s)
15947 "Protect spaces and newline in string S."
15948 (while (string-match " " s)
15949 (setq s (replace-match "%20" t t s)))
15950 (while (string-match "\n" s)
15951 (setq s (replace-match "%0A" t t s)))
15954 (defun org-entry-restore-space (s)
15955 "Restore spaces and newline in string S."
15956 (while (string-match "%20" s)
15957 (setq s (replace-match " " t t s)))
15958 (while (string-match "%0A" s)
15959 (setq s (replace-match "\n" t t s)))
15962 (defvar org-entry-property-inherited-from (make-marker)
15963 "Marker pointing to the entry from where a property was inherited.
15964 Each call to `org-entry-get-with-inheritance' will set this marker to the
15965 location of the entry where the inheritance search matched. If there was
15966 no match, the marker will point nowhere.
15967 Note that also `org-entry-get' calls this function, if the INHERIT flag
15968 is set.")
15970 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15971 "Get PROPERTY of entry or content at point, search higher levels if needed.
15972 The search will stop at the first ancestor which has the property defined.
15973 If the value found is \"nil\", return nil to show that the property
15974 should be considered as undefined (this is the meaning of nil here).
15975 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15976 (move-marker org-entry-property-inherited-from nil)
15977 (org-with-wide-buffer
15978 (let (value)
15979 (catch 'exit
15980 (while t
15981 (let ((v (org--property-local-values property literal-nil)))
15982 (when v
15983 (setq value
15984 (concat (mapconcat #'identity (delq nil v) " ")
15985 (and value " ")
15986 value)))
15987 (cond
15988 ((car v)
15989 (org-back-to-heading t)
15990 (move-marker org-entry-property-inherited-from (point))
15991 (throw 'exit nil))
15992 ((org-up-heading-safe))
15994 (let ((global (org--property-global-value property literal-nil)))
15995 (cond ((not global))
15996 (value (setq value (concat global " " value)))
15997 (t (setq value global))))
15998 (throw 'exit nil))))))
15999 (if literal-nil value (org-not-nil value)))))
16001 (defvar org-property-changed-functions nil
16002 "Hook called when the value of a property has changed.
16003 Each hook function should accept two arguments, the name of the property
16004 and the new value.")
16006 (defun org-entry-put (pom property value)
16007 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16009 If the value is nil, it is converted to the empty string. If it
16010 is not a string, an error is raised. Also raise an error on
16011 invalid property names.
16013 PROPERTY can be any regular property (see
16014 `org-special-properties'). It can also be \"TODO\",
16015 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16017 For the last two properties, VALUE may have any of the special
16018 values \"earlier\" and \"later\". The function then increases or
16019 decreases scheduled or deadline date by one day."
16020 (cond ((null value) (setq value ""))
16021 ((not (stringp value)) (error "Properties values should be strings"))
16022 ((not (org--valid-property-p property))
16023 (user-error "Invalid property name: \"%s\"" property)))
16024 (org-with-point-at pom
16025 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16026 (org-back-to-heading t)
16027 (org-with-limited-levels (org-back-to-heading t)))
16028 (let ((beg (point)))
16029 (cond
16030 ((equal property "TODO")
16031 (cond ((not (org-string-nw-p value)) (setq value 'none))
16032 ((not (member value org-todo-keywords-1))
16033 (user-error "\"%s\" is not a valid TODO state" value)))
16034 (org-todo value)
16035 (org-set-tags nil 'align))
16036 ((equal property "PRIORITY")
16037 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16038 (org-set-tags nil 'align))
16039 ((equal property "SCHEDULED")
16040 (forward-line)
16041 (if (and (looking-at-p org-planning-line-re)
16042 (re-search-forward
16043 org-scheduled-time-regexp (line-end-position) t))
16044 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16045 ((string= value "later") (org-timestamp-change 1 'day))
16046 ((string= value "") (org-schedule '(4)))
16047 (t (org-schedule nil value)))
16048 (if (member value '("earlier" "later" ""))
16049 (call-interactively #'org-schedule)
16050 (org-schedule nil value))))
16051 ((equal property "DEADLINE")
16052 (forward-line)
16053 (if (and (looking-at-p org-planning-line-re)
16054 (re-search-forward
16055 org-deadline-time-regexp (line-end-position) t))
16056 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16057 ((string= value "later") (org-timestamp-change 1 'day))
16058 ((string= value "") (org-deadline '(4)))
16059 (t (org-deadline nil value)))
16060 (if (member value '("earlier" "later" ""))
16061 (call-interactively #'org-deadline)
16062 (org-deadline nil value))))
16063 ((member property org-special-properties)
16064 (error "The %s property cannot be set with `org-entry-put'" property))
16066 (let* ((range (org-get-property-block beg 'force))
16067 (end (cdr range))
16068 (case-fold-search t))
16069 (goto-char (car range))
16070 (if (re-search-forward (org-re-property property nil t) end t)
16071 (progn (delete-region (match-beginning 0) (match-end 0))
16072 (goto-char (match-beginning 0)))
16073 (goto-char end)
16074 (insert "\n")
16075 (backward-char))
16076 (insert ":" property ":")
16077 (when value (insert " " value))
16078 (org-indent-line)))))
16079 (run-hook-with-args 'org-property-changed-functions property value)))
16081 (defun org-buffer-property-keys
16082 (&optional specials defaults columns ignore-malformed)
16083 "Get all property keys in the current buffer.
16085 When SPECIALS is non-nil, also list the special properties that
16086 reflect things like tags and TODO state.
16088 When DEFAULTS is non-nil, also include properties that has
16089 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16090 DESCRIPTION, LOCATION, and LOGGING and others.
16092 When COLUMNS in non-nil, also include property names given in
16093 COLUMN formats in the current buffer.
16095 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16096 automatically performed, such drawers will be silently ignored."
16097 (let ((case-fold-search t)
16098 (props (append
16099 (and specials org-special-properties)
16100 (and defaults (cons org-effort-property org-default-properties))
16101 nil)))
16102 (org-with-wide-buffer
16103 (goto-char (point-min))
16104 (while (re-search-forward org-property-start-re nil t)
16105 (let ((range (org-get-property-block)))
16106 (catch 'skip
16107 (unless range
16108 (when (and (not ignore-malformed)
16109 (not (org-before-first-heading-p))
16110 (y-or-n-p (format "Malformed drawer at %d, repair?"
16111 (line-beginning-position))))
16112 (org-get-property-block nil t))
16113 (throw 'skip nil))
16114 (goto-char (car range))
16115 (let ((begin (car range))
16116 (end (cdr range)))
16117 ;; Make sure that found property block is not located
16118 ;; before current point, as it would generate an infloop.
16119 ;; It can happen, for example, in the following
16120 ;; situation:
16122 ;; * Headline
16123 ;; :PROPERTIES:
16124 ;; ...
16125 ;; :END:
16126 ;; *************** Inlinetask
16127 ;; #+BEGIN_EXAMPLE
16128 ;; :PROPERTIES:
16129 ;; #+END_EXAMPLE
16131 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16132 (while (< (point) end)
16133 (let ((p (progn (looking-at org-property-re)
16134 (match-string-no-properties 2))))
16135 ;; Only add true property name, not extension symbol.
16136 (push (if (not (string-match-p "\\+\\'" p)) p
16137 (substring p 0 -1))
16138 props))
16139 (forward-line))))
16140 (outline-next-heading)))
16141 (when columns
16142 (goto-char (point-min))
16143 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16144 (let ((element (org-element-at-point)))
16145 (when (memq (org-element-type element) '(keyword node-property))
16146 (let ((value (org-element-property :value element))
16147 (start 0))
16148 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16149 (setq start (match-end 0))
16150 (let ((p (match-string-no-properties 1 value)))
16151 (unless (member-ignore-case p org-special-properties)
16152 (push p props))))))))))
16153 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16155 (defun org-property-values (key)
16156 "List all non-nil values of property KEY in current buffer."
16157 (org-with-wide-buffer
16158 (goto-char (point-min))
16159 (let ((case-fold-search t)
16160 (re (org-re-property key))
16161 values)
16162 (while (re-search-forward re nil t)
16163 (push (org-entry-get (point) key) values))
16164 (delete-dups values))))
16166 (defun org-insert-property-drawer ()
16167 "Insert a property drawer into the current entry."
16168 (org-with-wide-buffer
16169 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16170 (org-back-to-heading t)
16171 (org-with-limited-levels (org-back-to-heading t)))
16172 (forward-line)
16173 (when (looking-at-p org-planning-line-re) (forward-line))
16174 (unless (looking-at-p org-property-drawer-re)
16175 ;; Make sure we start editing a line from current entry, not from
16176 ;; next one. It prevents extending text properties or overlays
16177 ;; belonging to the latter.
16178 (when (bolp) (backward-char))
16179 (let ((begin (1+ (point)))
16180 (inhibit-read-only t))
16181 (insert "\n:PROPERTIES:\n:END:")
16182 (when (eobp) (insert "\n"))
16183 (org-indent-region begin (point))))))
16185 (defun org-insert-drawer (&optional arg drawer)
16186 "Insert a drawer at point.
16188 When optional argument ARG is non-nil, insert a property drawer.
16190 Optional argument DRAWER, when non-nil, is a string representing
16191 drawer's name. Otherwise, the user is prompted for a name.
16193 If a region is active, insert the drawer around that region
16194 instead.
16196 Point is left between drawer's boundaries."
16197 (interactive "P")
16198 (let* ((drawer (if arg "PROPERTIES"
16199 (or drawer (read-from-minibuffer "Drawer: ")))))
16200 (cond
16201 ;; With C-u, fall back on `org-insert-property-drawer'
16202 (arg (org-insert-property-drawer))
16203 ;; Check validity of suggested drawer's name.
16204 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16205 (user-error "Invalid drawer name"))
16206 ;; With an active region, insert a drawer at point.
16207 ((not (org-region-active-p))
16208 (progn
16209 (unless (bolp) (insert "\n"))
16210 (insert (format ":%s:\n\n:END:\n" drawer))
16211 (forward-line -2)))
16212 ;; Otherwise, insert the drawer at point
16214 (let ((rbeg (region-beginning))
16215 (rend (copy-marker (region-end))))
16216 (unwind-protect
16217 (progn
16218 (goto-char rbeg)
16219 (beginning-of-line)
16220 (when (save-excursion
16221 (re-search-forward org-outline-regexp-bol rend t))
16222 (user-error "Drawers cannot contain headlines"))
16223 ;; Position point at the beginning of the first
16224 ;; non-blank line in region. Insert drawer's opening
16225 ;; there, then indent it.
16226 (org-skip-whitespace)
16227 (beginning-of-line)
16228 (insert ":" drawer ":\n")
16229 (forward-line -1)
16230 (indent-for-tab-command)
16231 ;; Move point to the beginning of the first blank line
16232 ;; after the last non-blank line in region. Insert
16233 ;; drawer's closing, then indent it.
16234 (goto-char rend)
16235 (skip-chars-backward " \r\t\n")
16236 (insert "\n:END:")
16237 (deactivate-mark t)
16238 (indent-for-tab-command)
16239 (unless (eolp) (insert "\n")))
16240 ;; Clear marker, whatever the outcome of insertion is.
16241 (set-marker rend nil)))))))
16243 (defvar org-property-set-functions-alist nil
16244 "Property set function alist.
16245 Each entry should have the following format:
16247 (PROPERTY . READ-FUNCTION)
16249 The read function will be called with the same argument as
16250 `org-completing-read'.")
16252 (defun org-set-property-function (property)
16253 "Get the function that should be used to set PROPERTY.
16254 This is computed according to `org-property-set-functions-alist'."
16255 (or (cdr (assoc property org-property-set-functions-alist))
16256 'org-completing-read))
16258 (defun org-read-property-value (property)
16259 "Read PROPERTY value from user."
16260 (let* ((completion-ignore-case t)
16261 (allowed (org-property-get-allowed-values nil property 'table))
16262 (cur (org-entry-get nil property))
16263 (prompt (concat property " value"
16264 (if (and cur (string-match "\\S-" cur))
16265 (concat " [" cur "]") "") ": "))
16266 (set-function (org-set-property-function property))
16267 (val (if allowed
16268 (funcall set-function prompt allowed nil
16269 (not (get-text-property 0 'org-unrestricted
16270 (caar allowed))))
16271 (funcall set-function prompt
16272 (mapcar 'list (org-property-values property))
16273 nil nil "" nil cur))))
16274 (org-trim val)))
16276 (defvar org-last-set-property nil)
16277 (defvar org-last-set-property-value nil)
16278 (defun org-read-property-name ()
16279 "Read a property name."
16280 (let ((completion-ignore-case t)
16281 (default-prop (or (and (org-at-property-p)
16282 (match-string-no-properties 2))
16283 org-last-set-property)))
16284 (org-completing-read
16285 (concat "Property"
16286 (if default-prop (concat " [" default-prop "]") "")
16287 ": ")
16288 (mapcar #'list (org-buffer-property-keys nil t t))
16289 nil nil nil nil default-prop)))
16291 (defun org-set-property-and-value (use-last)
16292 "Allow to set [PROPERTY]: [value] direction from prompt.
16293 When use-default, don't even ask, just use the last
16294 \"[PROPERTY]: [value]\" string from the history."
16295 (interactive "P")
16296 (let* ((completion-ignore-case t)
16297 (pv (or (and use-last org-last-set-property-value)
16298 (org-completing-read
16299 "Enter a \"[Property]: [value]\" pair: "
16300 nil nil nil nil nil
16301 org-last-set-property-value)))
16302 prop val)
16303 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16304 (setq prop (match-string 1 pv)
16305 val (match-string 2 pv))
16306 (org-set-property prop val))))
16308 (defun org-set-property (property value)
16309 "In the current entry, set PROPERTY to VALUE.
16311 When called interactively, this will prompt for a property name, offering
16312 completion on existing and default properties. And then it will prompt
16313 for a value, offering completion either on allowed values (via an inherited
16314 xxx_ALL property) or on existing values in other instances of this property
16315 in the current file.
16317 Throw an error when trying to set a property with an invalid name."
16318 (interactive (list nil nil))
16319 (let ((property (or property (org-read-property-name))))
16320 ;; `org-entry-put' also makes the following check, but this one
16321 ;; avoids polluting `org-last-set-property' and
16322 ;; `org-last-set-property-value' needlessly.
16323 (unless (org--valid-property-p property)
16324 (user-error "Invalid property name: \"%s\"" property))
16325 (let ((value (or value (org-read-property-value property)))
16326 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16327 (setq org-last-set-property property)
16328 (setq org-last-set-property-value (concat property ": " value))
16329 ;; Possibly postprocess the inserted value:
16330 (when fn (setq value (funcall fn value)))
16331 (unless (equal (org-entry-get nil property) value)
16332 (org-entry-put nil property value)))))
16334 (defun org-find-property (property &optional value)
16335 "Find first entry in buffer that sets PROPERTY.
16337 When optional argument VALUE is non-nil, only consider an entry
16338 if it contains PROPERTY set to this value. If PROPERTY should be
16339 explicitly set to nil, use string \"nil\" for VALUE.
16341 Return position where the entry begins, or nil if there is no
16342 such entry. If narrowing is in effect, only search the visible
16343 part of the buffer."
16344 (save-excursion
16345 (goto-char (point-min))
16346 (let ((case-fold-search t)
16347 (re (org-re-property property nil (not value) value)))
16348 (catch 'exit
16349 (while (re-search-forward re nil t)
16350 (when (if value (org-at-property-p)
16351 (org-entry-get (point) property nil t))
16352 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16354 (defun org-delete-property (property)
16355 "In the current entry, delete PROPERTY."
16356 (interactive
16357 (let* ((completion-ignore-case t)
16358 (cat (org-entry-get (point) "CATEGORY"))
16359 (props0 (org-entry-properties nil 'standard))
16360 (props (if cat props0
16361 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16362 (prop (if (< 1 (length props))
16363 (completing-read "Property: " props nil t)
16364 (caar props))))
16365 (list prop)))
16366 (if (not property)
16367 (message "No property to delete in this entry")
16368 (org-entry-delete nil property)
16369 (message "Property \"%s\" deleted" property)))
16371 (defun org-delete-property-globally (property)
16372 "Remove PROPERTY globally, from all entries.
16373 This function ignores narrowing, if any."
16374 (interactive
16375 (let* ((completion-ignore-case t)
16376 (prop (completing-read
16377 "Globally remove property: "
16378 (mapcar #'list (org-buffer-property-keys)))))
16379 (list prop)))
16380 (org-with-wide-buffer
16381 (goto-char (point-min))
16382 (let ((count 0)
16383 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16384 (while (re-search-forward re nil t)
16385 (when (org-entry-delete (point) property) (cl-incf count)))
16386 (message "Property \"%s\" removed from %d entries" property count))))
16388 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16390 (defun org-compute-property-at-point ()
16391 "Compute the property at point.
16392 This looks for an enclosing column format, extracts the operator and
16393 then applies it to the property in the column format's scope."
16394 (interactive)
16395 (unless (org-at-property-p)
16396 (user-error "Not at a property"))
16397 (let ((prop (match-string-no-properties 2)))
16398 (org-columns-get-format-and-top-level)
16399 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16400 (user-error "No operator defined for property %s" prop))
16401 (org-columns-compute prop)))
16403 (defvar org-property-allowed-value-functions nil
16404 "Hook for functions supplying allowed values for a specific property.
16405 The functions must take a single argument, the name of the property, and
16406 return a flat list of allowed values. If \":ETC\" is one of
16407 the values, this means that these values are intended as defaults for
16408 completion, but that other values should be allowed too.
16409 The functions must return nil if they are not responsible for this
16410 property.")
16412 (defun org-property-get-allowed-values (pom property &optional table)
16413 "Get allowed values for the property PROPERTY.
16414 When TABLE is non-nil, return an alist that can directly be used for
16415 completion."
16416 (let (vals)
16417 (cond
16418 ((equal property "TODO")
16419 (setq vals (org-with-point-at pom
16420 (append org-todo-keywords-1 '("")))))
16421 ((equal property "PRIORITY")
16422 (let ((n org-lowest-priority))
16423 (while (>= n org-highest-priority)
16424 (push (char-to-string n) vals)
16425 (setq n (1- n)))))
16426 ((equal property "CATEGORY"))
16427 ((member property org-special-properties))
16428 ((setq vals (run-hook-with-args-until-success
16429 'org-property-allowed-value-functions property)))
16431 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16432 (when (and vals (string-match "\\S-" vals))
16433 (setq vals (car (read-from-string (concat "(" vals ")"))))
16434 (setq vals (mapcar (lambda (x)
16435 (cond ((stringp x) x)
16436 ((numberp x) (number-to-string x))
16437 ((symbolp x) (symbol-name x))
16438 (t "???")))
16439 vals)))))
16440 (when (member ":ETC" vals)
16441 (setq vals (remove ":ETC" vals))
16442 (org-add-props (car vals) '(org-unrestricted t)))
16443 (if table (mapcar 'list vals) vals)))
16445 (defun org-property-previous-allowed-value (&optional _previous)
16446 "Switch to the next allowed value for this property."
16447 (interactive)
16448 (org-property-next-allowed-value t))
16450 (defun org-property-next-allowed-value (&optional previous)
16451 "Switch to the next allowed value for this property."
16452 (interactive)
16453 (unless (org-at-property-p)
16454 (user-error "Not at a property"))
16455 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16456 (key (match-string 2))
16457 (value (match-string 3))
16458 (allowed (or (org-property-get-allowed-values (point) key)
16459 (and (member value '("[ ]" "[-]" "[X]"))
16460 '("[ ]" "[X]"))))
16461 (heading (save-match-data (nth 4 (org-heading-components))))
16462 nval)
16463 (unless allowed
16464 (user-error "Allowed values for this property have not been defined"))
16465 (when previous (setq allowed (reverse allowed)))
16466 (when (member value allowed)
16467 (setq nval (car (cdr (member value allowed)))))
16468 (setq nval (or nval (car allowed)))
16469 (when (equal nval value)
16470 (user-error "Only one allowed value for this property"))
16471 (org-at-property-p)
16472 (replace-match (concat " :" key ": " nval) t t)
16473 (org-indent-line)
16474 (beginning-of-line 1)
16475 (skip-chars-forward " \t")
16476 (when (equal prop org-effort-property)
16477 (org-refresh-property
16478 '((effort . identity)
16479 (effort-minutes . org-duration-to-minutes))
16480 nval)
16481 (when (string= org-clock-current-task heading)
16482 (setq org-clock-effort nval)
16483 (org-clock-update-mode-line)))
16484 (run-hook-with-args 'org-property-changed-functions key nval)))
16486 (defun org-find-olp (path &optional this-buffer)
16487 "Return a marker pointing to the entry at outline path OLP.
16488 If anything goes wrong, throw an error.
16489 You can wrap this call to catch the error like this:
16491 (condition-case msg
16492 (org-mobile-locate-entry (match-string 4))
16493 (error (nth 1 msg)))
16495 The return value will then be either a string with the error message,
16496 or a marker if everything is OK.
16498 If THIS-BUFFER is set, the outline path does not contain a file,
16499 only headings."
16500 (let* ((file (if this-buffer buffer-file-name (pop path)))
16501 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16502 (level 1)
16503 (lmin 1)
16504 (lmax 1)
16505 end found flevel)
16506 (unless buffer (error "File not found :%s" file))
16507 (with-current-buffer buffer
16508 (org-with-wide-buffer
16509 (goto-char (point-min))
16510 (dolist (heading path)
16511 (let ((re (format org-complex-heading-regexp-format
16512 (regexp-quote heading)))
16513 (cnt 0))
16514 (while (re-search-forward re end t)
16515 (setq level (- (match-end 1) (match-beginning 1)))
16516 (when (and (>= level lmin) (<= level lmax))
16517 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16518 (when (= cnt 0)
16519 (error "Heading not found on level %d: %s" lmax heading))
16520 (when (> cnt 1)
16521 (error "Heading not unique on level %d: %s" lmax heading))
16522 (goto-char found)
16523 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16524 (setq end (save-excursion (org-end-of-subtree t t)))))
16525 (when (org-at-heading-p)
16526 (point-marker))))))
16528 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16529 "Find node HEADING in BUFFER.
16530 Return a marker to the heading if it was found, or nil if not.
16531 If POS-ONLY is set, return just the position instead of a marker.
16533 The heading text must match exact, but it may have a TODO keyword,
16534 a priority cookie and tags in the standard locations."
16535 (with-current-buffer (or buffer (current-buffer))
16536 (org-with-wide-buffer
16537 (goto-char (point-min))
16538 (let (case-fold-search)
16539 (when (re-search-forward
16540 (format org-complex-heading-regexp-format
16541 (regexp-quote heading)) nil t)
16542 (if pos-only
16543 (match-beginning 0)
16544 (move-marker (make-marker) (match-beginning 0))))))))
16546 (defun org-find-exact-heading-in-directory (heading &optional dir)
16547 "Find Org node headline HEADING in all .org files in directory DIR.
16548 When the target headline is found, return a marker to this location."
16549 (let ((files (directory-files (or dir default-directory)
16550 t "\\`[^.#].*\\.org\\'"))
16551 visiting m buffer)
16552 (catch 'found
16553 (dolist (file files)
16554 (message "trying %s" file)
16555 (setq visiting (org-find-base-buffer-visiting file))
16556 (setq buffer (or visiting (find-file-noselect file)))
16557 (setq m (org-find-exact-headline-in-buffer
16558 heading buffer))
16559 (when (and (not m) (not visiting)) (kill-buffer buffer))
16560 (and m (throw 'found m))))))
16562 (defun org-find-entry-with-id (ident)
16563 "Locate the entry that contains the ID property with exact value IDENT.
16564 IDENT can be a string, a symbol or a number, this function will search for
16565 the string representation of it.
16566 Return the position where this entry starts, or nil if there is no such entry."
16567 (interactive "sID: ")
16568 (let ((id (cond
16569 ((stringp ident) ident)
16570 ((symbolp ident) (symbol-name ident))
16571 ((numberp ident) (number-to-string ident))
16572 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16573 (org-with-wide-buffer (org-find-property "ID" id))))
16575 ;;;; Timestamps
16577 (defvar org-last-changed-timestamp nil)
16578 (defvar org-last-inserted-timestamp nil
16579 "The last time stamp inserted with `org-insert-time-stamp'.")
16581 (defun org-time-stamp (arg &optional inactive)
16582 "Prompt for a date/time and insert a time stamp.
16584 If the user specifies a time like HH:MM or if this command is
16585 called with at least one prefix argument, the time stamp contains
16586 the date and the time. Otherwise, only the date is included.
16588 All parts of a date not specified by the user are filled in from
16589 the timestamp at point, if any, or the current date/time
16590 otherwise.
16592 If there is already a timestamp at the cursor, it is replaced.
16594 With two universal prefix arguments, insert an active timestamp
16595 with the current time without prompting the user.
16597 When called from lisp, the timestamp is inactive if INACTIVE is
16598 non-nil."
16599 (interactive "P")
16600 (let* ((ts (cond
16601 ((org-at-date-range-p t)
16602 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16603 ((org-at-timestamp-p t) (match-string 0))))
16604 ;; Default time is either the timestamp at point or today.
16605 ;; When entering a range, only the range start is considered.
16606 (default-time (if (not ts) (current-time)
16607 (apply #'encode-time (org-parse-time-string ts))))
16608 (default-input (and ts (org-get-compact-tod ts)))
16609 (repeater (and ts
16610 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16611 (match-string 0 ts)))
16612 org-time-was-given
16613 org-end-time-was-given
16614 (time
16615 (and (if (equal arg '(16)) (current-time)
16616 ;; Preserve `this-command' and `last-command'.
16617 (let ((this-command this-command)
16618 (last-command last-command))
16619 (org-read-date
16620 arg 'totime nil nil default-time default-input
16621 inactive))))))
16622 (cond
16623 ((and ts
16624 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16625 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16626 (insert "--")
16627 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16629 ;; Make sure we're on a timestamp. When in the middle of a date
16630 ;; range, move arbitrarily to range end.
16631 (unless (org-at-timestamp-p t)
16632 (skip-chars-forward "-")
16633 (org-at-timestamp-p t))
16634 (replace-match "")
16635 (setq org-last-changed-timestamp
16636 (org-insert-time-stamp
16637 time (or org-time-was-given arg)
16638 inactive nil nil (list org-end-time-was-given)))
16639 (when repeater
16640 (backward-char)
16641 (insert " " repeater)
16642 (setq org-last-changed-timestamp
16643 (concat (substring org-last-inserted-timestamp 0 -1)
16644 " " repeater ">")))
16645 (message "Timestamp updated"))
16646 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16647 (t (org-insert-time-stamp
16648 time (or org-time-was-given arg) inactive nil nil
16649 (list org-end-time-was-given))))))
16651 ;; FIXME: can we use this for something else, like computing time differences?
16652 (defun org-get-compact-tod (s)
16653 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16654 (let* ((t1 (match-string 1 s))
16655 (h1 (string-to-number (match-string 2 s)))
16656 (m1 (string-to-number (match-string 3 s)))
16657 (t2 (and (match-end 4) (match-string 5 s)))
16658 (h2 (and t2 (string-to-number (match-string 6 s))))
16659 (m2 (and t2 (string-to-number (match-string 7 s))))
16660 dh dm)
16661 (if (not t2)
16663 (setq dh (- h2 h1) dm (- m2 m1))
16664 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16665 (concat t1 "+" (number-to-string dh)
16666 (and (/= 0 dm) (format ":%02d" dm)))))))
16668 (defun org-time-stamp-inactive (&optional arg)
16669 "Insert an inactive time stamp.
16670 An inactive time stamp is enclosed in square brackets instead of angle
16671 brackets. It is inactive in the sense that it does not trigger agenda entries,
16672 does not link to the calendar and cannot be changed with the S-cursor keys.
16673 So these are more for recording a certain time/date."
16674 (interactive "P")
16675 (org-time-stamp arg 'inactive))
16677 (defvar org-date-ovl (make-overlay 1 1))
16678 (overlay-put org-date-ovl 'face 'org-date-selected)
16679 (delete-overlay org-date-ovl)
16681 (defvar org-ans1) ; dynamically scoped parameter
16682 (defvar org-ans2) ; dynamically scoped parameter
16684 (defvar org-plain-time-of-day-regexp) ; defined below
16686 (defvar org-overriding-default-time nil) ; dynamically scoped
16687 (defvar org-read-date-overlay nil)
16688 (defvar org-dcst nil) ; dynamically scoped
16689 (defvar org-read-date-history nil)
16690 (defvar org-read-date-final-answer nil)
16691 (defvar org-read-date-analyze-futurep nil)
16692 (defvar org-read-date-analyze-forced-year nil)
16693 (defvar org-read-date-inactive)
16695 (defvar org-read-date-minibuffer-local-map
16696 (let* ((map (make-sparse-keymap)))
16697 (set-keymap-parent map minibuffer-local-map)
16698 (org-defkey map (kbd ".")
16699 (lambda () (interactive)
16700 ;; Are we at the beginning of the prompt?
16701 (if (looking-back "^[^:]+: "
16702 (let ((inhibit-field-text-motion t))
16703 (line-beginning-position)))
16704 (org-eval-in-calendar '(calendar-goto-today))
16705 (insert "."))))
16706 (org-defkey map (kbd "C-.")
16707 (lambda () (interactive)
16708 (org-eval-in-calendar '(calendar-goto-today))))
16709 (org-defkey map [(meta shift left)]
16710 (lambda () (interactive)
16711 (org-eval-in-calendar '(calendar-backward-month 1))))
16712 (org-defkey map [(meta shift right)]
16713 (lambda () (interactive)
16714 (org-eval-in-calendar '(calendar-forward-month 1))))
16715 (org-defkey map [(meta shift up)]
16716 (lambda () (interactive)
16717 (org-eval-in-calendar '(calendar-backward-year 1))))
16718 (org-defkey map [(meta shift down)]
16719 (lambda () (interactive)
16720 (org-eval-in-calendar '(calendar-forward-year 1))))
16721 (org-defkey map [?\e (shift left)]
16722 (lambda () (interactive)
16723 (org-eval-in-calendar '(calendar-backward-month 1))))
16724 (org-defkey map [?\e (shift right)]
16725 (lambda () (interactive)
16726 (org-eval-in-calendar '(calendar-forward-month 1))))
16727 (org-defkey map [?\e (shift up)]
16728 (lambda () (interactive)
16729 (org-eval-in-calendar '(calendar-backward-year 1))))
16730 (org-defkey map [?\e (shift down)]
16731 (lambda () (interactive)
16732 (org-eval-in-calendar '(calendar-forward-year 1))))
16733 (org-defkey map [(shift up)]
16734 (lambda () (interactive)
16735 (org-eval-in-calendar '(calendar-backward-week 1))))
16736 (org-defkey map [(shift down)]
16737 (lambda () (interactive)
16738 (org-eval-in-calendar '(calendar-forward-week 1))))
16739 (org-defkey map [(shift left)]
16740 (lambda () (interactive)
16741 (org-eval-in-calendar '(calendar-backward-day 1))))
16742 (org-defkey map [(shift right)]
16743 (lambda () (interactive)
16744 (org-eval-in-calendar '(calendar-forward-day 1))))
16745 (org-defkey map "!"
16746 (lambda () (interactive)
16747 (org-eval-in-calendar '(diary-view-entries))
16748 (message "")))
16749 (org-defkey map ">"
16750 (lambda () (interactive)
16751 (org-eval-in-calendar '(calendar-scroll-left 1))))
16752 (org-defkey map "<"
16753 (lambda () (interactive)
16754 (org-eval-in-calendar '(calendar-scroll-right 1))))
16755 (org-defkey map "\C-v"
16756 (lambda () (interactive)
16757 (org-eval-in-calendar
16758 '(calendar-scroll-left-three-months 1))))
16759 (org-defkey map "\M-v"
16760 (lambda () (interactive)
16761 (org-eval-in-calendar
16762 '(calendar-scroll-right-three-months 1))))
16763 map)
16764 "Keymap for minibuffer commands when using `org-read-date'.")
16766 (defvar org-def)
16767 (defvar org-defdecode)
16768 (defvar org-with-time)
16770 (defvar calendar-setup) ; Dynamically scoped.
16771 (defun org-read-date (&optional with-time to-time from-string prompt
16772 default-time default-input inactive)
16773 "Read a date, possibly a time, and make things smooth for the user.
16774 The prompt will suggest to enter an ISO date, but you can also enter anything
16775 which will at least partially be understood by `parse-time-string'.
16776 Unrecognized parts of the date will default to the current day, month, year,
16777 hour and minute. If this command is called to replace a timestamp at point,
16778 or to enter the second timestamp of a range, the default time is taken
16779 from the existing stamp. Furthermore, the command prefers the future,
16780 so if you are giving a date where the year is not given, and the day-month
16781 combination is already past in the current year, it will assume you
16782 mean next year. For details, see the manual. A few examples:
16784 3-2-5 --> 2003-02-05
16785 feb 15 --> currentyear-02-15
16786 2/15 --> currentyear-02-15
16787 sep 12 9 --> 2009-09-12
16788 12:45 --> today 12:45
16789 22 sept 0:34 --> currentyear-09-22 0:34
16790 12 --> currentyear-currentmonth-12
16791 Fri --> nearest Friday after today
16792 -Tue --> last Tuesday
16793 etc.
16795 Furthermore you can specify a relative date by giving, as the *first* thing
16796 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16797 change in days weeks, months, years.
16798 With a single plus or minus, the date is relative to today. With a double
16799 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16800 +4d --> four days from today
16801 +4 --> same as above
16802 +2w --> two weeks from today
16803 ++5 --> five days from default date
16805 The function understands only English month and weekday abbreviations.
16807 While prompting, a calendar is popped up - you can also select the
16808 date with the mouse (button 1). The calendar shows a period of three
16809 months. To scroll it to other months, use the keys `>' and `<'.
16810 If you don't like the calendar, turn it off with
16811 (setq org-read-date-popup-calendar nil)
16813 With optional argument TO-TIME, the date will immediately be converted
16814 to an internal time.
16815 With an optional argument WITH-TIME, the prompt will suggest to
16816 also insert a time. Note that when WITH-TIME is not set, you can
16817 still enter a time, and this function will inform the calling routine
16818 about this change. The calling routine may then choose to change the
16819 format used to insert the time stamp into the buffer to include the time.
16820 With optional argument FROM-STRING, read from this string instead from
16821 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16822 the time/date that is used for everything that is not specified by the
16823 user."
16824 (require 'parse-time)
16825 (let* ((org-with-time with-time)
16826 (org-time-stamp-rounding-minutes
16827 (if (equal org-with-time '(16))
16828 '(0 0)
16829 org-time-stamp-rounding-minutes))
16830 (org-dcst org-display-custom-times)
16831 (ct (org-current-time))
16832 (org-def (or org-overriding-default-time default-time ct))
16833 (org-defdecode (decode-time org-def))
16834 (cur-frame (selected-frame))
16835 (mouse-autoselect-window nil) ; Don't let the mouse jump
16836 (calendar-setup
16837 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16838 (calendar-move-hook nil)
16839 (calendar-view-diary-initially-flag nil)
16840 (calendar-view-holidays-initially-flag nil)
16841 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16842 ;; Rationalize `org-def' and `org-defdecode', if required.
16843 (when (< (nth 2 org-defdecode) org-extend-today-until)
16844 (setf (nth 2 org-defdecode) -1)
16845 (setf (nth 1 org-defdecode) 59)
16846 (setq org-def (apply #'encode-time org-defdecode))
16847 (setq org-defdecode (decode-time org-def)))
16848 (let* ((timestr (format-time-string
16849 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16850 org-def))
16851 (prompt (concat (if prompt (concat prompt " ") "")
16852 (format "Date+time [%s]: " timestr))))
16853 (cond
16854 (from-string (setq ans from-string))
16855 (org-read-date-popup-calendar
16856 (save-excursion
16857 (save-window-excursion
16858 (calendar)
16859 (when (eq calendar-setup 'calendar-only)
16860 (setq cal-frame
16861 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16862 (select-frame cal-frame))
16863 (org-eval-in-calendar '(setq cursor-type nil) t)
16864 (unwind-protect
16865 (progn
16866 (calendar-forward-day (- (time-to-days org-def)
16867 (calendar-absolute-from-gregorian
16868 (calendar-current-date))))
16869 (org-eval-in-calendar nil t)
16870 (let* ((old-map (current-local-map))
16871 (map (copy-keymap calendar-mode-map))
16872 (minibuffer-local-map
16873 (copy-keymap org-read-date-minibuffer-local-map)))
16874 (org-defkey map (kbd "RET") 'org-calendar-select)
16875 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16876 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16877 (unwind-protect
16878 (progn
16879 (use-local-map map)
16880 (setq org-read-date-inactive inactive)
16881 (add-hook 'post-command-hook 'org-read-date-display)
16882 (setq org-ans0
16883 (read-string prompt
16884 default-input
16885 'org-read-date-history
16886 nil))
16887 ;; org-ans0: from prompt
16888 ;; org-ans1: from mouse click
16889 ;; org-ans2: from calendar motion
16890 (setq ans
16891 (concat org-ans0 " " (or org-ans1 org-ans2))))
16892 (remove-hook 'post-command-hook 'org-read-date-display)
16893 (use-local-map old-map)
16894 (when org-read-date-overlay
16895 (delete-overlay org-read-date-overlay)
16896 (setq org-read-date-overlay nil)))))
16897 (bury-buffer "*Calendar*")
16898 (when cal-frame
16899 (delete-frame cal-frame)
16900 (select-frame-set-input-focus cur-frame))))))
16902 (t ; Naked prompt only
16903 (unwind-protect
16904 (setq ans (read-string prompt default-input
16905 'org-read-date-history timestr))
16906 (when org-read-date-overlay
16907 (delete-overlay org-read-date-overlay)
16908 (setq org-read-date-overlay nil))))))
16910 (setq final (org-read-date-analyze ans org-def org-defdecode))
16912 (when org-read-date-analyze-forced-year
16913 (message "Year was forced into %s"
16914 (if org-read-date-force-compatible-dates
16915 "compatible range (1970-2037)"
16916 "range representable on this machine"))
16917 (ding))
16919 ;; One round trip to get rid of 34th of August and stuff like that....
16920 (setq final (decode-time (apply 'encode-time final)))
16922 (setq org-read-date-final-answer ans)
16924 (if to-time
16925 (apply 'encode-time final)
16926 (if (and (boundp 'org-time-was-given) org-time-was-given)
16927 (format "%04d-%02d-%02d %02d:%02d"
16928 (nth 5 final) (nth 4 final) (nth 3 final)
16929 (nth 2 final) (nth 1 final))
16930 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16932 (defun org-read-date-display ()
16933 "Display the current date prompt interpretation in the minibuffer."
16934 (when org-read-date-display-live
16935 (when org-read-date-overlay
16936 (delete-overlay org-read-date-overlay))
16937 (when (minibufferp (current-buffer))
16938 (save-excursion
16939 (end-of-line 1)
16940 (while (not (equal (buffer-substring
16941 (max (point-min) (- (point) 4)) (point))
16942 " "))
16943 (insert " ")))
16944 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16945 " " (or org-ans1 org-ans2)))
16946 (org-end-time-was-given nil)
16947 (f (org-read-date-analyze ans org-def org-defdecode))
16948 (fmts (if org-dcst
16949 org-time-stamp-custom-formats
16950 org-time-stamp-formats))
16951 (fmt (if (or org-with-time
16952 (and (boundp 'org-time-was-given) org-time-was-given))
16953 (cdr fmts)
16954 (car fmts)))
16955 (txt (format-time-string fmt (apply 'encode-time f)))
16956 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16957 (txt (concat "=> " txt)))
16958 (when (and org-end-time-was-given
16959 (string-match org-plain-time-of-day-regexp txt))
16960 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16961 org-end-time-was-given
16962 (substring txt (match-end 0)))))
16963 (when org-read-date-analyze-futurep
16964 (setq txt (concat txt " (=>F)")))
16965 (setq org-read-date-overlay
16966 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16967 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16969 (defun org-read-date-analyze (ans def defdecode)
16970 "Analyze the combined answer of the date prompt."
16971 ;; FIXME: cleanup and comment
16972 ;; Pass `current-time' result to `decode-time' (instead of calling
16973 ;; without arguments) so that only `current-time' has to be
16974 ;; overriden in tests.
16975 (let ((org-def def)
16976 (org-defdecode defdecode)
16977 (nowdecode (decode-time (current-time)))
16978 delta deltan deltaw deltadef year month day
16979 hour minute second wday pm h2 m2 tl wday1
16980 iso-year iso-weekday iso-week iso-date futurep kill-year)
16981 (setq org-read-date-analyze-futurep nil
16982 org-read-date-analyze-forced-year nil)
16983 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16984 (setq ans "+0"))
16986 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16987 (setq ans (replace-match "" t t ans)
16988 deltan (car delta)
16989 deltaw (nth 1 delta)
16990 deltadef (nth 2 delta)))
16992 ;; Check if there is an iso week date in there. If yes, store the
16993 ;; info and postpone interpreting it until the rest of the parsing
16994 ;; is done.
16995 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16996 (setq iso-year (when (match-end 1)
16997 (org-small-year-to-year
16998 (string-to-number (match-string 1 ans))))
16999 iso-weekday (when (match-end 3)
17000 (string-to-number (match-string 3 ans)))
17001 iso-week (string-to-number (match-string 2 ans)))
17002 (setq ans (replace-match "" t t ans)))
17004 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17005 (when (string-match
17006 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17007 (setq year (if (match-end 2)
17008 (string-to-number (match-string 2 ans))
17009 (progn (setq kill-year t)
17010 (string-to-number (format-time-string "%Y"))))
17011 month (string-to-number (match-string 3 ans))
17012 day (string-to-number (match-string 4 ans)))
17013 (setq year (org-small-year-to-year year))
17014 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17015 t nil ans)))
17017 ;; Help matching dotted european dates
17018 (when (string-match
17019 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17020 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17021 (setq kill-year t)
17022 (string-to-number (format-time-string "%Y")))
17023 day (string-to-number (match-string 1 ans))
17024 month (string-to-number (match-string 2 ans))
17025 ans (replace-match (format "%04d-%02d-%02d" year month day)
17026 t nil ans)))
17028 ;; Help matching american dates, like 5/30 or 5/30/7
17029 (when (string-match
17030 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17031 (setq year (if (match-end 4)
17032 (string-to-number (match-string 4 ans))
17033 (progn (setq kill-year t)
17034 (string-to-number (format-time-string "%Y"))))
17035 month (string-to-number (match-string 1 ans))
17036 day (string-to-number (match-string 2 ans)))
17037 (setq year (org-small-year-to-year year))
17038 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17039 t nil ans)))
17040 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17041 ;; If there is a time with am/pm, and *no* time without it, we convert
17042 ;; so that matching will be successful.
17043 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17044 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17045 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17046 (setq hour (string-to-number (match-string 1 ans))
17047 minute (if (match-end 3)
17048 (string-to-number (match-string 3 ans))
17050 pm (equal ?p
17051 (string-to-char (downcase (match-string 4 ans)))))
17052 (if (and (= hour 12) (not pm))
17053 (setq hour 0)
17054 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17055 (setq ans (replace-match (format "%02d:%02d" hour minute)
17056 t t ans))))
17058 ;; Check if a time range is given as a duration
17059 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17060 (setq hour (string-to-number (match-string 1 ans))
17061 h2 (+ hour (string-to-number (match-string 3 ans)))
17062 minute (string-to-number (match-string 2 ans))
17063 m2 (+ minute (if (match-end 5) (string-to-number
17064 (match-string 5 ans))0)))
17065 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17066 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17067 t t ans)))
17069 ;; Check if there is a time range
17070 (when (boundp 'org-end-time-was-given)
17071 (setq org-time-was-given nil)
17072 (when (and (string-match org-plain-time-of-day-regexp ans)
17073 (match-end 8))
17074 (setq org-end-time-was-given (match-string 8 ans))
17075 (setq ans (concat (substring ans 0 (match-beginning 7))
17076 (substring ans (match-end 7))))))
17078 (setq tl (parse-time-string ans)
17079 day (or (nth 3 tl) (nth 3 org-defdecode))
17080 month
17081 (cond ((nth 4 tl))
17082 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17083 ;; Day was specified. Make sure DAY+MONTH
17084 ;; combination happens in the future.
17085 ((nth 3 tl)
17086 (setq futurep t)
17087 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17088 (nth 4 nowdecode)))
17089 (t (nth 4 org-defdecode)))
17090 year
17091 (cond ((and (not kill-year) (nth 5 tl)))
17092 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17093 ;; Month was guessed in the future and is at least
17094 ;; equal to NOWDECODE's. Fix year accordingly.
17095 (futurep
17096 (if (or (> month (nth 4 nowdecode))
17097 (>= day (nth 3 nowdecode)))
17098 (nth 5 nowdecode)
17099 (1+ (nth 5 nowdecode))))
17100 ;; Month was specified. Make sure MONTH+YEAR
17101 ;; combination happens in the future.
17102 ((nth 4 tl)
17103 (setq futurep t)
17104 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17105 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17106 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17107 (t (nth 5 nowdecode))))
17108 (t (nth 5 org-defdecode)))
17109 hour (or (nth 2 tl) (nth 2 org-defdecode))
17110 minute (or (nth 1 tl) (nth 1 org-defdecode))
17111 second (or (nth 0 tl) 0)
17112 wday (nth 6 tl))
17114 (when (and (eq org-read-date-prefer-future 'time)
17115 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17116 (equal day (nth 3 nowdecode))
17117 (equal month (nth 4 nowdecode))
17118 (equal year (nth 5 nowdecode))
17119 (nth 2 tl)
17120 (or (< (nth 2 tl) (nth 2 nowdecode))
17121 (and (= (nth 2 tl) (nth 2 nowdecode))
17122 (nth 1 tl)
17123 (< (nth 1 tl) (nth 1 nowdecode)))))
17124 (setq day (1+ day)
17125 futurep t))
17127 ;; Special date definitions below
17128 (cond
17129 (iso-week
17130 ;; There was an iso week
17131 (require 'cal-iso)
17132 (setq futurep nil)
17133 (setq year (or iso-year year)
17134 day (or iso-weekday wday 1)
17135 wday nil ; to make sure that the trigger below does not match
17136 iso-date (calendar-gregorian-from-absolute
17137 (calendar-iso-to-absolute
17138 (list iso-week day year))))
17139 ; FIXME: Should we also push ISO weeks into the future?
17140 ; (when (and org-read-date-prefer-future
17141 ; (not iso-year)
17142 ; (< (calendar-absolute-from-gregorian iso-date)
17143 ; (time-to-days (current-time))))
17144 ; (setq year (1+ year)
17145 ; iso-date (calendar-gregorian-from-absolute
17146 ; (calendar-iso-to-absolute
17147 ; (list iso-week day year)))))
17148 (setq month (car iso-date)
17149 year (nth 2 iso-date)
17150 day (nth 1 iso-date)))
17151 (deltan
17152 (setq futurep nil)
17153 (unless deltadef
17154 ;; Pass `current-time' result to `decode-time' (instead of
17155 ;; calling without arguments) so that only `current-time' has
17156 ;; to be overriden in tests.
17157 (let ((now (decode-time (current-time))))
17158 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17159 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17160 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17161 ((equal deltaw "m") (setq month (+ month deltan)))
17162 ((equal deltaw "y") (setq year (+ year deltan)))))
17163 ((and wday (not (nth 3 tl)))
17164 ;; Weekday was given, but no day, so pick that day in the week
17165 ;; on or after the derived date.
17166 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17167 (unless (equal wday wday1)
17168 (setq day (+ day (% (- wday wday1 -7) 7))))))
17169 (when (and (boundp 'org-time-was-given)
17170 (nth 2 tl))
17171 (setq org-time-was-given t))
17172 (when (< year 100) (setq year (+ 2000 year)))
17173 ;; Check of the date is representable
17174 (if org-read-date-force-compatible-dates
17175 (progn
17176 (when (< year 1970)
17177 (setq year 1970 org-read-date-analyze-forced-year t))
17178 (when (> year 2037)
17179 (setq year 2037 org-read-date-analyze-forced-year t)))
17180 (condition-case nil
17181 (ignore (encode-time second minute hour day month year))
17182 (error
17183 (setq year (nth 5 org-defdecode))
17184 (setq org-read-date-analyze-forced-year t))))
17185 (setq org-read-date-analyze-futurep futurep)
17186 (list second minute hour day month year)))
17188 (defvar parse-time-weekdays)
17189 (defun org-read-date-get-relative (s today default)
17190 "Check string S for special relative date string.
17191 TODAY and DEFAULT are internal times, for today and for a default.
17192 Return shift list (N what def-flag)
17193 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17194 N is the number of WHATs to shift.
17195 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17196 the DEFAULT date rather than TODAY."
17197 (require 'parse-time)
17198 (when (and
17199 (string-match
17200 (concat
17201 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17202 "\\([0-9]+\\)?"
17203 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17204 "\\([ \t]\\|$\\)") s)
17205 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17206 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17207 (string-to-char (substring (match-string 1 s) -1))
17208 ?+))
17209 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17210 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17211 (what (if (match-end 3) (match-string 3 s) "d"))
17212 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17213 (date (if rel default today))
17214 (wday (nth 6 (decode-time date)))
17215 delta)
17216 (if wday1
17217 (progn
17218 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17219 (when (= delta 0) (setq delta 7))
17220 (when (= dir ?-)
17221 (setq delta (- delta 7))
17222 (when (= delta 0) (setq delta -7)))
17223 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17224 (list delta "d" rel))
17225 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17227 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17228 "Turn a user-specified date into the internal representation.
17229 The internal representation needed by the calendar is (month day year).
17230 This is a wrapper to handle the brain-dead convention in calendar that
17231 user function argument order change dependent on argument order."
17232 (pcase calendar-date-style
17233 (`american (list arg1 arg2 arg3))
17234 (`european (list arg2 arg1 arg3))
17235 (`iso (list arg2 arg3 arg1))))
17237 (defun org-eval-in-calendar (form &optional keepdate)
17238 "Eval FORM in the calendar window and return to current window.
17239 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17240 (let ((sf (selected-frame))
17241 (sw (selected-window)))
17242 (select-window (get-buffer-window "*Calendar*" t))
17243 (eval form)
17244 (when (and (not keepdate) (calendar-cursor-to-date))
17245 (let* ((date (calendar-cursor-to-date))
17246 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17247 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17248 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17249 (select-window sw)
17250 (select-frame-set-input-focus sf)))
17252 (defun org-calendar-select ()
17253 "Return to `org-read-date' with the date currently selected.
17254 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17255 (interactive)
17256 (when (calendar-cursor-to-date)
17257 (let* ((date (calendar-cursor-to-date))
17258 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17259 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17260 (when (active-minibuffer-window) (exit-minibuffer))))
17262 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17263 "Insert a date stamp for the date given by the internal TIME.
17264 See `format-time-string' for the format of TIME.
17265 WITH-HM means use the stamp format that includes the time of the day.
17266 INACTIVE means use square brackets instead of angular ones, so that the
17267 stamp will not contribute to the agenda.
17268 PRE and POST are optional strings to be inserted before and after the
17269 stamp.
17270 The command returns the inserted time stamp."
17271 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17272 stamp)
17273 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17274 (insert-before-markers (or pre ""))
17275 (when (listp extra)
17276 (setq extra (car extra))
17277 (if (and (stringp extra)
17278 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17279 (setq extra (format "-%02d:%02d"
17280 (string-to-number (match-string 1 extra))
17281 (string-to-number (match-string 2 extra))))
17282 (setq extra nil)))
17283 (when extra
17284 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17285 (insert-before-markers (setq stamp (format-time-string fmt time)))
17286 (insert-before-markers (or post ""))
17287 (setq org-last-inserted-timestamp stamp)))
17289 (defun org-toggle-time-stamp-overlays ()
17290 "Toggle the use of custom time stamp formats."
17291 (interactive)
17292 (setq org-display-custom-times (not org-display-custom-times))
17293 (unless org-display-custom-times
17294 (let ((p (point-min)) (bmp (buffer-modified-p)))
17295 (while (setq p (next-single-property-change p 'display))
17296 (when (and (get-text-property p 'display)
17297 (eq (get-text-property p 'face) 'org-date))
17298 (remove-text-properties
17299 p (setq p (next-single-property-change p 'display))
17300 '(display t))))
17301 (set-buffer-modified-p bmp)))
17302 (org-restart-font-lock)
17303 (setq org-table-may-need-update t)
17304 (if org-display-custom-times
17305 (message "Time stamps are overlaid with custom format")
17306 (message "Time stamp overlays removed")))
17308 (defun org-display-custom-time (beg end)
17309 "Overlay modified time stamp format over timestamp between BEG and END."
17310 (let* ((ts (buffer-substring beg end))
17311 t1 w1 with-hm tf time str w2 (off 0))
17312 (save-match-data
17313 (setq t1 (org-parse-time-string ts t))
17314 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17315 (setq off (- (match-end 0) (match-beginning 0)))))
17316 (setq end (- end off))
17317 (setq w1 (- end beg)
17318 with-hm (and (nth 1 t1) (nth 2 t1))
17319 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17320 time (org-fix-decoded-time t1)
17321 str (org-add-props
17322 (format-time-string
17323 (substring tf 1 -1) (apply 'encode-time time))
17324 nil 'mouse-face 'highlight)
17325 w2 (length str))
17326 (unless (= w2 w1)
17327 (add-text-properties (1+ beg) (+ 2 beg)
17328 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17329 (put-text-property beg end 'display str)))
17331 (defun org-fix-decoded-time (time)
17332 "Set 0 instead of nil for the first 6 elements of time.
17333 Don't touch the rest."
17334 (let ((n 0))
17335 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17337 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17338 "Difference between TIMESTAMP-STRING and now in days.
17339 If SECONDS is non-nil, return the difference in seconds."
17340 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17341 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17342 (funcall fdiff (current-time)))))
17344 (defun org-deadline-close-p (timestamp-string &optional ndays)
17345 "Is the time in TIMESTAMP-STRING close to the current date?"
17346 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17347 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17348 (not (org-entry-is-done-p))))
17350 (defun org-get-wdays (ts &optional delay zero-delay)
17351 "Get the deadline lead time appropriate for timestring TS.
17352 When DELAY is non-nil, get the delay time for scheduled items
17353 instead of the deadline lead time. When ZERO-DELAY is non-nil
17354 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17355 don't try to find the delay cookie in the scheduled timestamp."
17356 (let ((tv (if delay org-scheduled-delay-days
17357 org-deadline-warning-days)))
17358 (cond
17359 ((or (and delay (< tv 0))
17360 (and delay zero-delay (<= tv 0))
17361 (and (not delay) (<= tv 0)))
17362 ;; Enforce this value no matter what
17363 (- tv))
17364 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17365 ;; lead time is specified.
17366 (floor (* (string-to-number (match-string 1 ts))
17367 (cdr (assoc (match-string 2 ts)
17368 '(("d" . 1) ("w" . 7)
17369 ("m" . 30.4) ("y" . 365.25)
17370 ("h" . 0.041667)))))))
17371 ;; go for the default.
17372 (t tv))))
17374 (defun org-calendar-select-mouse (ev)
17375 "Return to `org-read-date' with the date currently selected.
17376 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17377 (interactive "e")
17378 (mouse-set-point ev)
17379 (when (calendar-cursor-to-date)
17380 (let* ((date (calendar-cursor-to-date))
17381 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17382 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17383 (when (active-minibuffer-window) (exit-minibuffer))))
17385 (defun org-check-deadlines (ndays)
17386 "Check if there are any deadlines due or past due.
17387 A deadline is considered due if it happens within `org-deadline-warning-days'
17388 days from today's date. If the deadline appears in an entry marked DONE,
17389 it is not shown. A numeric prefix argument NDAYS can be used to test that
17390 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17391 are shown."
17392 (interactive "P")
17393 (let* ((org-warn-days
17394 (cond
17395 ((equal ndays '(4)) 100000)
17396 (ndays (prefix-numeric-value ndays))
17397 (t (abs org-deadline-warning-days))))
17398 (case-fold-search nil)
17399 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17400 (callback
17401 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17402 (message "%d deadlines past-due or due within %d days"
17403 (org-occur regexp nil callback)
17404 org-warn-days)))
17406 (defsubst org-re-timestamp (type)
17407 "Return a regexp for timestamp TYPE.
17408 Allowed values for TYPE are:
17410 all: all timestamps
17411 active: only active timestamps (<...>)
17412 inactive: only inactive timestamps ([...])
17413 scheduled: only scheduled timestamps
17414 deadline: only deadline timestamps
17415 closed: only closed time-stamps
17417 When TYPE is nil, fall back on returning a regexp that matches
17418 both scheduled and deadline timestamps."
17419 (cl-case type
17420 (all org-ts-regexp-both)
17421 (active org-ts-regexp)
17422 (inactive org-ts-regexp-inactive)
17423 (scheduled org-scheduled-time-regexp)
17424 (deadline org-deadline-time-regexp)
17425 (closed org-closed-time-regexp)
17426 (otherwise
17427 (concat "\\<"
17428 (regexp-opt (list org-deadline-string org-scheduled-string))
17429 " *<\\([^>]+\\)>"))))
17431 (defun org-check-before-date (d)
17432 "Check if there are deadlines or scheduled entries before date D."
17433 (interactive (list (org-read-date)))
17434 (let* ((case-fold-search nil)
17435 (regexp (org-re-timestamp org-ts-type))
17436 (ts-type org-ts-type)
17437 (callback
17438 (lambda ()
17439 (let ((match (match-string 1)))
17440 (and (if (memq ts-type '(active inactive all))
17441 (eq (org-element-type (save-excursion
17442 (backward-char)
17443 (org-element-context)))
17444 'timestamp)
17445 (org-at-planning-p))
17446 (time-less-p
17447 (org-time-string-to-time match)
17448 (org-time-string-to-time d)))))))
17449 (message "%d entries before %s"
17450 (org-occur regexp nil callback)
17451 d)))
17453 (defun org-check-after-date (d)
17454 "Check if there are deadlines or scheduled entries after date D."
17455 (interactive (list (org-read-date)))
17456 (let* ((case-fold-search nil)
17457 (regexp (org-re-timestamp org-ts-type))
17458 (ts-type org-ts-type)
17459 (callback
17460 (lambda ()
17461 (let ((match (match-string 1)))
17462 (and (if (memq ts-type '(active inactive all))
17463 (eq (org-element-type (save-excursion
17464 (backward-char)
17465 (org-element-context)))
17466 'timestamp)
17467 (org-at-planning-p))
17468 (not (time-less-p
17469 (org-time-string-to-time match)
17470 (org-time-string-to-time d))))))))
17471 (message "%d entries after %s"
17472 (org-occur regexp nil callback)
17473 d)))
17475 (defun org-check-dates-range (start-date end-date)
17476 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17477 (interactive (list (org-read-date nil nil nil "Range starts")
17478 (org-read-date nil nil nil "Range end")))
17479 (let ((case-fold-search nil)
17480 (regexp (org-re-timestamp org-ts-type))
17481 (callback
17482 (let ((type org-ts-type))
17483 (lambda ()
17484 (let ((match (match-string 1)))
17485 (and
17486 (if (memq type '(active inactive all))
17487 (eq (org-element-type (save-excursion
17488 (backward-char)
17489 (org-element-context)))
17490 'timestamp)
17491 (org-at-planning-p))
17492 (not (time-less-p
17493 (org-time-string-to-time match)
17494 (org-time-string-to-time start-date)))
17495 (time-less-p
17496 (org-time-string-to-time match)
17497 (org-time-string-to-time end-date))))))))
17498 (message "%d entries between %s and %s"
17499 (org-occur regexp nil callback) start-date end-date)))
17501 (defun org-evaluate-time-range (&optional to-buffer)
17502 "Evaluate a time range by computing the difference between start and end.
17503 Normally the result is just printed in the echo area, but with prefix arg
17504 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17505 If the time range is actually in a table, the result is inserted into the
17506 next column.
17507 For time difference computation, a year is assumed to be exactly 365
17508 days in order to avoid rounding problems."
17509 (interactive "P")
17511 (org-clock-update-time-maybe)
17512 (save-excursion
17513 (unless (org-at-date-range-p t)
17514 (goto-char (point-at-bol))
17515 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17516 (unless (org-at-date-range-p t)
17517 (user-error "Not at a time-stamp range, and none found in current line")))
17518 (let* ((ts1 (match-string 1))
17519 (ts2 (match-string 2))
17520 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17521 (match-end (match-end 0))
17522 (time1 (org-time-string-to-time ts1))
17523 (time2 (org-time-string-to-time ts2))
17524 (t1 (float-time time1))
17525 (t2 (float-time time2))
17526 (diff (abs (- t2 t1)))
17527 (negative (< (- t2 t1) 0))
17528 ;; (ys (floor (* 365 24 60 60)))
17529 (ds (* 24 60 60))
17530 (hs (* 60 60))
17531 (fy "%dy %dd %02d:%02d")
17532 (fy1 "%dy %dd")
17533 (fd "%dd %02d:%02d")
17534 (fd1 "%dd")
17535 (fh "%02d:%02d")
17536 y d h m align)
17537 (if havetime
17538 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17540 d (floor (/ diff ds)) diff (mod diff ds)
17541 h (floor (/ diff hs)) diff (mod diff hs)
17542 m (floor (/ diff 60)))
17543 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17545 d (floor (+ (/ diff ds) 0.5))
17546 h 0 m 0))
17547 (if (not to-buffer)
17548 (message "%s" (org-make-tdiff-string y d h m))
17549 (if (org-at-table-p)
17550 (progn
17551 (goto-char match-end)
17552 (setq align t)
17553 (and (looking-at " *|") (goto-char (match-end 0))))
17554 (goto-char match-end))
17555 (when (looking-at
17556 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17557 (replace-match ""))
17558 (when negative (insert " -"))
17559 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17560 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17561 (insert " " (format fh h m))))
17562 (when align (org-table-align))
17563 (message "Time difference inserted")))))
17565 (defun org-make-tdiff-string (y d h m)
17566 (let ((fmt "")
17567 (l nil))
17568 (when (> y 0)
17569 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17570 (push y l))
17571 (when (> d 0)
17572 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17573 (push d l))
17574 (when (> h 0)
17575 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17576 (push h l))
17577 (when (> m 0)
17578 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17579 (push m l))
17580 (apply 'format fmt (nreverse l))))
17582 (defun org-time-string-to-time (s &optional buffer pos)
17583 "Convert a timestamp string into internal time."
17584 (condition-case errdata
17585 (apply 'encode-time (org-parse-time-string s))
17586 (error (error "Bad timestamp `%s'%s\nError was: %s"
17587 s (if (not (and buffer pos))
17589 (format-message " at %d in buffer `%s'" pos buffer))
17590 (cdr errdata)))))
17592 (defun org-time-string-to-seconds (s)
17593 "Convert a timestamp string to a number of seconds."
17594 (float-time (org-time-string-to-time s)))
17596 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17598 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17599 "Convert time stamp S to an absolute day number.
17601 If DAYNR in non-nil, and there is a specifier for a cyclic time
17602 stamp, get the closest date to DAYNR. If PREFER is
17603 `past' (respectively `future') return a date past (respectively
17604 after) or equal to DAYNR.
17606 POS is the location of time stamp S, as a buffer position in
17607 BUFFER.
17609 Diary sexp timestamps are matched against DAYNR, when non-nil.
17610 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17611 signalled."
17612 (cond
17613 ((string-match "\\`%%\\((.*)\\)" s)
17614 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17615 ;; only able to match individual dates. If it fails, raise an
17616 ;; error.
17617 (if (and daynr
17618 (org-diary-sexp-entry
17619 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17620 daynr
17621 (signal 'org-diary-sexp-no-match (list s))))
17622 (daynr (org-closest-date s daynr prefer))
17623 (t (time-to-days
17624 (condition-case errdata
17625 (apply #'encode-time (org-parse-time-string s))
17626 (error (error "Bad timestamp `%s'%s\nError was: %s"
17628 (if (not (and buffer pos)) ""
17629 (format-message " at %d in buffer `%s'" pos buffer))
17630 (cdr errdata))))))))
17632 (defun org-days-to-iso-week (days)
17633 "Return the iso week number."
17634 (require 'cal-iso)
17635 (car (calendar-iso-from-absolute days)))
17637 (defun org-small-year-to-year (year)
17638 "Convert 2-digit years into 4-digit years.
17639 YEAR is expanded into one of the 30 next years, if possible, or
17640 into a past one. Any year larger than 99 is returned unchanged."
17641 (if (>= year 100) year
17642 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17643 (century (/ current 100))
17644 (offset (- year (% current 100))))
17645 (cond ((> offset 30) (+ (* (1- century) 100) year))
17646 ((> offset -70) (+ (* century 100) year))
17647 (t (+ (* (1+ century) 100) year))))))
17649 (defun org-time-from-absolute (d)
17650 "Return the time corresponding to date D.
17651 D may be an absolute day number, or a calendar-type list (month day year)."
17652 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17653 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17655 (defvar org-agenda-current-date)
17656 (defun org-calendar-holiday ()
17657 "List of holidays, for Diary display in Org mode."
17658 (require 'holidays)
17659 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17660 (and hl (mapconcat #'identity hl "; "))))
17662 (defun org-diary-sexp-entry (sexp entry d)
17663 "Process a SEXP diary ENTRY for date D."
17664 (require 'diary-lib)
17665 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17666 ;; dynamically.
17667 (let* ((sexp `(let ((entry ,entry)
17668 (date ',d))
17669 ,(car (read-from-string sexp))))
17670 (result (if calendar-debug-sexp (eval sexp)
17671 (condition-case nil
17672 (eval sexp)
17673 (error
17674 (beep)
17675 (message "Bad sexp at line %d in %s: %s"
17676 (org-current-line)
17677 (buffer-file-name) sexp)
17678 (sleep-for 2))))))
17679 (cond ((stringp result) (split-string result "; "))
17680 ((and (consp result)
17681 (not (consp (cdr result)))
17682 (stringp (cdr result))) (cdr result))
17683 ((and (consp result)
17684 (stringp (car result))) result)
17685 (result entry))))
17687 (defun org-diary-to-ical-string (frombuf)
17688 "Get iCalendar entries from diary entries in buffer FROMBUF.
17689 This uses the icalendar.el library."
17690 (let* ((tmpdir temporary-file-directory)
17691 (tmpfile (make-temp-name
17692 (expand-file-name "orgics" tmpdir)))
17693 buf rtn b e)
17694 (with-current-buffer frombuf
17695 (icalendar-export-region (point-min) (point-max) tmpfile)
17696 (setq buf (find-buffer-visiting tmpfile))
17697 (set-buffer buf)
17698 (goto-char (point-min))
17699 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17700 (setq b (match-beginning 0)))
17701 (goto-char (point-max))
17702 (when (re-search-backward "^END:VEVENT" nil t)
17703 (setq e (match-end 0)))
17704 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17705 (kill-buffer buf)
17706 (delete-file tmpfile)
17707 rtn))
17709 (defun org-closest-date (start current prefer)
17710 "Return closest date to CURRENT starting from START.
17712 CURRENT and START are both time stamps.
17714 When PREFER is `past', return a date that is either CURRENT or
17715 past. When PREFER is `future', return a date that is either
17716 CURRENT or future.
17718 Only time stamps with a repeater are modified. Any other time
17719 stamp stay unchanged. In any case, return value is an absolute
17720 day number."
17721 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17722 ;; No repeater. Do not shift time stamp.
17723 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17724 (let ((value (string-to-number (match-string 1 start)))
17725 (type (match-string 2 start)))
17726 (if (= 0 value)
17727 ;; Repeater with a 0-value is considered as void.
17728 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17729 (let* ((base (org-date-to-gregorian start))
17730 (target (org-date-to-gregorian current))
17731 (sday (calendar-absolute-from-gregorian base))
17732 (cday (calendar-absolute-from-gregorian target))
17733 n1 n2)
17734 ;; If START is already past CURRENT, just return START.
17735 (if (<= cday sday) sday
17736 ;; Compute closest date before (N1) and closest date past
17737 ;; (N2) CURRENT.
17738 (pcase type
17739 ("h"
17740 (let ((missing-hours
17741 (mod (+ (- (* 24 (- cday sday))
17742 (nth 2 (org-parse-time-string start)))
17743 org-extend-today-until)
17744 value)))
17745 (setf n1 (if (= missing-hours 0) cday
17746 (- cday (1+ (/ missing-hours 24)))))
17747 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17748 ((or "d" "w")
17749 (let ((value (if (equal type "w") (* 7 value) value)))
17750 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17751 (setf n2 (+ n1 value))))
17752 ("m"
17753 (let* ((add-months
17754 (lambda (d n)
17755 ;; Add N months to gregorian date D, i.e.,
17756 ;; a list (MONTH DAY YEAR). Return a valid
17757 ;; gregorian date.
17758 (let ((m (+ (nth 0 d) n)))
17759 (list (mod m 12)
17760 (nth 1 d)
17761 (+ (/ m 12) (nth 2 d))))))
17762 (months ; Complete months to TARGET.
17763 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17764 (- (nth 0 target) (nth 0 base))
17765 ;; If START's day is greater than
17766 ;; TARGET's, remove incomplete month.
17767 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17768 value)
17769 value))
17770 (before (funcall add-months base months)))
17771 (setf n1 (calendar-absolute-from-gregorian before))
17772 (setf n2
17773 (calendar-absolute-from-gregorian
17774 (funcall add-months before value)))))
17776 (let* ((d (nth 1 base))
17777 (m (nth 0 base))
17778 (y (nth 2 base))
17779 (years ; Complete years to TARGET.
17780 (* (/ (- (nth 2 target)
17782 ;; If START's month and day are
17783 ;; greater than TARGET's, remove
17784 ;; incomplete year.
17785 (if (or (> (nth 0 target) m)
17786 (and (= (nth 0 target) m)
17787 (> (nth 1 target) d)))
17790 value)
17791 value))
17792 (before (list m d (+ y years))))
17793 (setf n1 (calendar-absolute-from-gregorian before))
17794 (setf n2 (calendar-absolute-from-gregorian
17795 (list m d (+ (nth 2 before) value)))))))
17796 ;; Handle PREFER parameter, if any.
17797 (cond
17798 ((eq prefer 'past) (if (= cday n2) n2 n1))
17799 ((eq prefer 'future) (if (= cday n1) n1 n2))
17800 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17802 (defun org-date-to-gregorian (d)
17803 "Turn any specification of date D into a Gregorian date for the calendar."
17804 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17805 ((and (listp d) (= (length d) 3)) d)
17806 ((stringp d)
17807 (let ((d (org-parse-time-string d)))
17808 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17809 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17811 (defun org-parse-time-string (s &optional nodefault)
17812 "Parse the standard Org time string.
17813 This should be a lot faster than the normal `parse-time-string'.
17814 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17815 hour and minute fields will be nil if not given."
17816 (cond ((string-match org-ts-regexp0 s)
17817 (list 0
17818 (when (or (match-beginning 8) (not nodefault))
17819 (string-to-number (or (match-string 8 s) "0")))
17820 (when (or (match-beginning 7) (not nodefault))
17821 (string-to-number (or (match-string 7 s) "0")))
17822 (string-to-number (match-string 4 s))
17823 (string-to-number (match-string 3 s))
17824 (string-to-number (match-string 2 s))
17825 nil nil nil))
17826 ((string-match "^<[^>]+>$" s)
17827 (decode-time (seconds-to-time (org-matcher-time s))))
17828 (t (error "Not a standard Org time string: %s" s))))
17830 (defun org-timestamp-up (&optional arg)
17831 "Increase the date item at the cursor by one.
17832 If the cursor is on the year, change the year. If it is on the month,
17833 the day or the time, change that.
17834 With prefix ARG, change by that many units."
17835 (interactive "p")
17836 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17838 (defun org-timestamp-down (&optional arg)
17839 "Decrease the date item at the cursor by one.
17840 If the cursor is on the year, change the year. If it is on the month,
17841 the day or the time, change that.
17842 With prefix ARG, change by that many units."
17843 (interactive "p")
17844 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17846 (defun org-timestamp-up-day (&optional arg)
17847 "Increase the date in the time stamp by one day.
17848 With prefix ARG, change that many days."
17849 (interactive "p")
17850 (if (and (not (org-at-timestamp-p t))
17851 (org-at-heading-p))
17852 (org-todo 'up)
17853 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17855 (defun org-timestamp-down-day (&optional arg)
17856 "Decrease the date in the time stamp by one day.
17857 With prefix ARG, change that many days."
17858 (interactive "p")
17859 (if (and (not (org-at-timestamp-p t))
17860 (org-at-heading-p))
17861 (org-todo 'down)
17862 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17864 (defun org-at-timestamp-p (&optional inactive-ok)
17865 "Non-nil if point is inside a timestamp.
17867 When optional argument INACTIVE-OK is non-nil, also consider
17868 inactive timestamps.
17870 When this function returns a non-nil value, match data is set
17871 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17872 INACTIVE-OK.
17874 Return the position of the point as a symbol among `bracket',
17875 `after', `year', `month', `hour', `minute', `day' or a number of
17876 character from the last know part of the time stamp.
17878 This function checks context and only return non-nil for valid
17879 time stamps. If you need to match anything looking like a time
17880 stamp, or if you are sure about the context, consider using
17881 `org-in-regexp', e.g.,
17883 (org-in-regexp org-ts-regexp)
17885 Unlike to `org-element-context', the function recognizes time
17886 stamps in properties drawers, planning lines and clocks."
17887 (interactive)
17888 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17889 (pos (point))
17890 (match
17891 (let ((boundaries (org-in-regexp tsr)))
17892 (save-match-data
17893 (cond ((null boundaries) nil)
17894 ((org-at-planning-p))
17895 ((org-at-property-p))
17896 ;; CLOCK lines only contain inactive time-stamps.
17897 ((and inactive-ok (org-at-clock-log-p)))
17899 (eq 'timestamp
17900 (save-excursion
17901 (when (= pos (cdr boundaries)) (forward-char -1))
17902 (org-element-type (org-element-context))))))))))
17903 (cond
17904 ((not match) nil)
17905 ((= pos (match-beginning 0)) 'bracket)
17906 ;; Distinguish location right before the closing bracket from
17907 ;; right after it.
17908 ((= pos (1- (match-end 0))) 'bracket)
17909 ((= pos (match-end 0)) 'after)
17910 ((org-pos-in-match-range pos 2) 'year)
17911 ((org-pos-in-match-range pos 3) 'month)
17912 ((org-pos-in-match-range pos 7) 'hour)
17913 ((org-pos-in-match-range pos 8) 'minute)
17914 ((or (org-pos-in-match-range pos 4)
17915 (org-pos-in-match-range pos 5)) 'day)
17916 ((and (> pos (or (match-end 8) (match-end 5)))
17917 (< pos (match-end 0)))
17918 (- pos (or (match-end 8) (match-end 5))))
17919 (t 'day))))
17921 (defun org-toggle-timestamp-type ()
17922 "Toggle the type (<active> or [inactive]) of a time stamp."
17923 (interactive)
17924 (when (org-at-timestamp-p t)
17925 (let ((beg (match-beginning 0)) (end (match-end 0))
17926 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17927 (save-excursion
17928 (goto-char beg)
17929 (while (re-search-forward "[][<>]" end t)
17930 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17931 t t)))
17932 (message "Timestamp is now %sactive"
17933 (if (equal (char-after beg) ?<) "" "in")))))
17935 (defun org-at-clock-log-p ()
17936 "Non-nil if point is on a clock log line."
17937 (and (org-match-line org-clock-line-re)
17938 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17940 (defvar org-clock-history) ; defined in org-clock.el
17941 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17942 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17943 "Change the date in the time stamp at point.
17944 The date will be changed by N times WHAT. WHAT can be `day', `month',
17945 `year', `minute', `second'. If WHAT is not given, the cursor position
17946 in the timestamp determines what will be changed.
17947 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17948 (let ((origin (point))
17949 (timestamp? (org-at-timestamp-p t))
17950 origin-cat
17951 with-hm inactive
17952 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17953 extra rem
17954 ts time time0 fixnext clrgx)
17955 (unless timestamp? (user-error "Not at a timestamp"))
17956 (if (and (not what) (eq timestamp? 'bracket))
17957 (org-toggle-timestamp-type)
17958 ;; Point isn't on brackets. Remember the part of the time-stamp
17959 ;; the point was in. Indeed, size of time-stamps may change,
17960 ;; but point must be kept in the same category nonetheless.
17961 (setq origin-cat timestamp?)
17962 (when (and (not what) (not (eq timestamp? 'day))
17963 org-display-custom-times
17964 (get-text-property (point) 'display)
17965 (not (get-text-property (1- (point)) 'display)))
17966 (setq timestamp? 'day))
17967 (setq timestamp? (or what timestamp?)
17968 inactive (= (char-after (match-beginning 0)) ?\[)
17969 ts (match-string 0))
17970 (replace-match "")
17971 (when (string-match
17972 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17974 (setq extra (match-string 1 ts))
17975 (when suppress-tmp-delay
17976 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17977 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17978 (setq with-hm t))
17979 (setq time0 (org-parse-time-string ts))
17980 (when (and updown
17981 (eq timestamp? 'minute)
17982 (not current-prefix-arg))
17983 ;; This looks like s-up and s-down. Change by one rounding step.
17984 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17985 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17986 (setcar (cdr time0) (+ (nth 1 time0)
17987 (if (> n 0) (- rem) (- dm rem))))))
17988 (setq time
17989 (apply #'encode-time
17990 (or (car time0) 0)
17991 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17992 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17993 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17994 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17995 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17996 (nthcdr 6 time0)))
17997 (when (and (memq timestamp? '(hour minute))
17998 extra
17999 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18000 (setq extra (org-modify-ts-extra
18001 extra
18002 (if (eq timestamp? 'hour) 2 5)
18003 n dm)))
18004 (when (integerp timestamp?)
18005 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
18006 (when (eq what 'calendar)
18007 (let ((cal-date (org-get-date-from-calendar)))
18008 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18009 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18010 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18011 (setcar time0 (or (car time0) 0))
18012 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18013 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18014 (setq time (apply 'encode-time time0))))
18015 ;; Insert the new time-stamp, and ensure point stays in the same
18016 ;; category as before (i.e. not after the last position in that
18017 ;; category).
18018 (let ((pos (point)))
18019 ;; Stay before inserted string. `save-excursion' is of no use.
18020 (setq org-last-changed-timestamp
18021 (org-insert-time-stamp time with-hm inactive nil nil extra))
18022 (goto-char pos))
18023 (save-match-data
18024 (looking-at org-ts-regexp3)
18025 (goto-char
18026 (pcase origin-cat
18027 ;; `day' category ends before `hour' if any, or at the end
18028 ;; of the day name.
18029 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18030 (`hour (min (match-end 7) origin))
18031 (`minute (min (1- (match-end 8)) origin))
18032 ((pred integerp) (min (1- (match-end 0)) origin))
18033 ;; Point was right after the time-stamp. However, the
18034 ;; time-stamp length might have changed, so refer to
18035 ;; (match-end 0) instead.
18036 (`after (match-end 0))
18037 ;; `year' and `month' have both fixed size: point couldn't
18038 ;; have moved into another part.
18039 (_ origin))))
18040 ;; Update clock if on a CLOCK line.
18041 (org-clock-update-time-maybe)
18042 ;; Maybe adjust the closest clock in `org-clock-history'
18043 (when org-clock-adjust-closest
18044 (if (not (and (org-at-clock-log-p)
18045 (< 1 (length (delq nil (mapcar 'marker-position
18046 org-clock-history))))))
18047 (message "No clock to adjust")
18048 (cond ((save-excursion ; fix previous clock?
18049 (re-search-backward org-ts-regexp0 nil t)
18050 (looking-back (concat org-clock-string " \\[")
18051 (line-beginning-position)))
18052 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18053 ((save-excursion ; fix next clock?
18054 (re-search-backward org-ts-regexp0 nil t)
18055 (looking-at (concat org-ts-regexp0 "\\] =>")))
18056 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18057 (save-window-excursion
18058 ;; Find closest clock to point, adjust the previous/next one in history
18059 (let* ((p (save-excursion (org-back-to-heading t)))
18060 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18061 (clfixnth
18062 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18063 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18064 (if (not clfixpos)
18065 (message "No clock to adjust")
18066 (save-excursion
18067 (org-goto-marker-or-bmk clfixpos)
18068 (org-show-subtree)
18069 (when (re-search-forward clrgx nil t)
18070 (goto-char (match-beginning 1))
18071 (let (org-clock-adjust-closest)
18072 (org-timestamp-change n timestamp? updown))
18073 (message "Clock adjusted in %s for heading: %s"
18074 (file-name-nondirectory (buffer-file-name))
18075 (org-get-heading t t)))))))))
18076 ;; Try to recenter the calendar window, if any.
18077 (when (and org-calendar-follow-timestamp-change
18078 (get-buffer-window "*Calendar*" t)
18079 (memq timestamp? '(day month year)))
18080 (org-recenter-calendar (time-to-days time))))))
18082 (defun org-modify-ts-extra (s pos n dm)
18083 "Change the different parts of the lead-time and repeat fields in timestamp."
18084 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18085 ng h m new rem)
18086 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18087 (cond
18088 ((or (org-pos-in-match-range pos 2)
18089 (org-pos-in-match-range pos 3))
18090 (setq m (string-to-number (match-string 3 s))
18091 h (string-to-number (match-string 2 s)))
18092 (if (org-pos-in-match-range pos 2)
18093 (setq h (+ h n))
18094 (setq n (* dm (with-no-warnings (signum n))))
18095 (unless (= 0 (setq rem (% m dm)))
18096 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18097 (setq m (+ m n)))
18098 (when (< m 0) (setq m (+ m 60) h (1- h)))
18099 (when (> m 59) (setq m (- m 60) h (1+ h)))
18100 (setq h (mod h 24))
18101 (setq ng 1 new (format "-%02d:%02d" h m)))
18102 ((org-pos-in-match-range pos 6)
18103 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18104 ((org-pos-in-match-range pos 5)
18105 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18107 ((org-pos-in-match-range pos 9)
18108 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18109 ((org-pos-in-match-range pos 8)
18110 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18112 (when ng
18113 (setq s (concat
18114 (substring s 0 (match-beginning ng))
18116 (substring s (match-end ng))))))
18119 (defun org-recenter-calendar (d)
18120 "If the calendar is visible, recenter it to date D."
18121 (let ((cwin (get-buffer-window "*Calendar*" t)))
18122 (when cwin
18123 (let ((calendar-move-hook nil))
18124 (with-selected-window cwin
18125 (calendar-goto-date
18126 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18128 (defun org-goto-calendar (&optional arg)
18129 "Go to the Emacs calendar at the current date.
18130 If there is a time stamp in the current line, go to that date.
18131 A prefix ARG can be used to force the current date."
18132 (interactive "P")
18133 (let ((tsr org-ts-regexp) diff
18134 (calendar-move-hook nil)
18135 (calendar-view-holidays-initially-flag nil)
18136 (calendar-view-diary-initially-flag nil))
18137 (when (or (org-at-timestamp-p)
18138 (save-excursion
18139 (beginning-of-line 1)
18140 (looking-at (concat ".*" tsr))))
18141 (let ((d1 (time-to-days (current-time)))
18142 (d2 (time-to-days
18143 (org-time-string-to-time (match-string 1)))))
18144 (setq diff (- d2 d1))))
18145 (calendar)
18146 (calendar-goto-today)
18147 (when (and diff (not arg)) (calendar-forward-day diff))))
18149 (defun org-get-date-from-calendar ()
18150 "Return a list (month day year) of date at point in calendar."
18151 (with-current-buffer "*Calendar*"
18152 (save-match-data
18153 (calendar-cursor-to-date))))
18155 (defun org-date-from-calendar ()
18156 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18157 If there is already a time stamp at the cursor position, update it."
18158 (interactive)
18159 (if (org-at-timestamp-p t)
18160 (org-timestamp-change 0 'calendar)
18161 (let ((cal-date (org-get-date-from-calendar)))
18162 (org-insert-time-stamp
18163 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18165 (defcustom org-effort-durations
18166 `(("min" . 1)
18167 ("h" . 60)
18168 ("d" . ,(* 60 8))
18169 ("w" . ,(* 60 8 5))
18170 ("m" . ,(* 60 8 5 4))
18171 ("y" . ,(* 60 8 5 40)))
18172 "Conversion factor to minutes for an effort modifier.
18174 Each entry has the form (MODIFIER . MINUTES).
18176 In an effort string, a number followed by MODIFIER is multiplied
18177 by the specified number of MINUTES to obtain an effort in
18178 minutes.
18180 For example, if the value of this variable is ((\"hours\" . 60)), then an
18181 effort string \"2hours\" is equivalent to 120 minutes."
18182 :group 'org-agenda
18183 :version "26.1"
18184 :package-version '(Org . "8.3")
18185 :type '(alist :key-type (string :tag "Modifier")
18186 :value-type (number :tag "Minutes")))
18188 (defcustom org-image-actual-width t
18189 "Should we use the actual width of images when inlining them?
18191 When set to t, always use the image width.
18193 When set to a number, use imagemagick (when available) to set
18194 the image's width to this value.
18196 When set to a number in a list, try to get the width from any
18197 #+ATTR.* keyword if it matches a width specification like
18199 #+ATTR_HTML: :width 300px
18201 and fall back on that number if none is found.
18203 When set to nil, try to get the width from an #+ATTR.* keyword
18204 and fall back on the original width if none is found.
18206 This requires Emacs >= 24.1, build with imagemagick support."
18207 :group 'org-appearance
18208 :version "24.4"
18209 :package-version '(Org . "8.0")
18210 :type '(choice
18211 (const :tag "Use the image width" t)
18212 (integer :tag "Use a number of pixels")
18213 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18214 (const :tag "Use #+ATTR* or don't resize" nil)))
18216 (defcustom org-agenda-inhibit-startup nil
18217 "Inhibit startup when preparing agenda buffers.
18218 When this variable is t, the initialization of the Org agenda
18219 buffers is inhibited: e.g. the visibility state is not set, the
18220 tables are not re-aligned, etc."
18221 :type 'boolean
18222 :version "24.3"
18223 :group 'org-agenda)
18225 (defcustom org-agenda-ignore-properties nil
18226 "Avoid updating text properties when building the agenda.
18227 Properties are used to prepare buffers for effort estimates,
18228 appointments, statistics and subtree-local categories.
18229 If you don't use these in the agenda, you can add them to this
18230 list and agenda building will be a bit faster.
18231 The value is a list, with zero or more of the symbols `effort', `appt',
18232 `stats' or `category'."
18233 :type '(set :greedy t
18234 (const effort)
18235 (const appt)
18236 (const stats)
18237 (const category))
18238 :version "26.1"
18239 :package-version '(Org . "8.3")
18240 :group 'org-agenda)
18242 ;;;; Files
18244 (defun org-save-all-org-buffers ()
18245 "Save all Org buffers without user confirmation."
18246 (interactive)
18247 (message "Saving all Org buffers...")
18248 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18249 (when (featurep 'org-id) (org-id-locations-save))
18250 (message "Saving all Org buffers... done"))
18252 (defun org-revert-all-org-buffers ()
18253 "Revert all Org buffers.
18254 Prompt for confirmation when there are unsaved changes.
18255 Be sure you know what you are doing before letting this function
18256 overwrite your changes.
18258 This function is useful in a setup where one tracks org files
18259 with a version control system, to revert on one machine after pulling
18260 changes from another. I believe the procedure must be like this:
18262 1. M-x org-save-all-org-buffers
18263 2. Pull changes from the other machine, resolve conflicts
18264 3. M-x org-revert-all-org-buffers"
18265 (interactive)
18266 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18267 (user-error "Abort"))
18268 (save-excursion
18269 (save-window-excursion
18270 (dolist (b (buffer-list))
18271 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18272 (with-current-buffer b buffer-file-name))
18273 (pop-to-buffer-same-window b)
18274 (revert-buffer t 'no-confirm)))
18275 (when (and (featurep 'org-id) org-id-track-globally)
18276 (org-id-locations-load)))))
18278 ;;;; Agenda files
18280 ;;;###autoload
18281 (defun org-switchb (&optional arg)
18282 "Switch between Org buffers.
18284 With `\\[universal-argument]' prefix, restrict available buffers to files.
18286 With `\\[universal-argument] \\[universal-argument]' \
18287 prefix, restrict available buffers to agenda files."
18288 (interactive "P")
18289 (let ((blist (org-buffer-list
18290 (cond ((equal arg '(4)) 'files)
18291 ((equal arg '(16)) 'agenda)))))
18292 (pop-to-buffer-same-window
18293 (completing-read "Org buffer: "
18294 (mapcar #'list (mapcar #'buffer-name blist))
18295 nil t))))
18297 (defun org-buffer-list (&optional predicate exclude-tmp)
18298 "Return a list of Org buffers.
18299 PREDICATE can be `export', `files' or `agenda'.
18301 export restrict the list to Export buffers.
18302 files restrict the list to buffers visiting Org files.
18303 agenda restrict the list to buffers visiting agenda files.
18305 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18306 (let* ((bfn nil)
18307 (agenda-files (and (eq predicate 'agenda)
18308 (mapcar 'file-truename (org-agenda-files t))))
18309 (filter
18310 (cond
18311 ((eq predicate 'files)
18312 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18313 ((eq predicate 'export)
18314 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18315 ((eq predicate 'agenda)
18316 (lambda (b)
18317 (with-current-buffer b
18318 (and (derived-mode-p 'org-mode)
18319 (setq bfn (buffer-file-name b))
18320 (member (file-truename bfn) agenda-files)))))
18321 (t (lambda (b) (with-current-buffer b
18322 (or (derived-mode-p 'org-mode)
18323 (string-match "\\*Org .*Export"
18324 (buffer-name b)))))))))
18325 (delq nil
18326 (mapcar
18327 (lambda(b)
18328 (if (and (funcall filter b)
18329 (or (not exclude-tmp)
18330 (not (string-match "tmp" (buffer-name b)))))
18332 nil))
18333 (buffer-list)))))
18335 (defun org-agenda-files (&optional unrestricted archives)
18336 "Get the list of agenda files.
18337 Optional UNRESTRICTED means return the full list even if a restriction
18338 is currently in place.
18339 When ARCHIVES is t, include all archive files that are really being
18340 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18341 `org-agenda-archives-mode' is t."
18342 (let ((files
18343 (cond
18344 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18345 ((stringp org-agenda-files) (org-read-agenda-file-list))
18346 ((listp org-agenda-files) org-agenda-files)
18347 (t (error "Invalid value of `org-agenda-files'")))))
18348 (setq files (apply 'append
18349 (mapcar (lambda (f)
18350 (if (file-directory-p f)
18351 (directory-files
18352 f t org-agenda-file-regexp)
18353 (list f)))
18354 files)))
18355 (when org-agenda-skip-unavailable-files
18356 (setq files (delq nil
18357 (mapcar (function
18358 (lambda (file)
18359 (and (file-readable-p file) file)))
18360 files))))
18361 (when (or (eq archives t)
18362 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18363 (setq files (org-add-archive-files files)))
18364 files))
18366 (defun org-agenda-file-p (&optional file)
18367 "Return non-nil, if FILE is an agenda file.
18368 If FILE is omitted, use the file associated with the current
18369 buffer."
18370 (let ((fname (or file (buffer-file-name))))
18371 (and fname
18372 (member (file-truename fname)
18373 (mapcar #'file-truename (org-agenda-files t))))))
18375 (defun org-edit-agenda-file-list ()
18376 "Edit the list of agenda files.
18377 Depending on setup, this either uses customize to edit the variable
18378 `org-agenda-files', or it visits the file that is holding the list. In the
18379 latter case, the buffer is set up in a way that saving it automatically kills
18380 the buffer and restores the previous window configuration."
18381 (interactive)
18382 (if (stringp org-agenda-files)
18383 (let ((cw (current-window-configuration)))
18384 (find-file org-agenda-files)
18385 (setq-local org-window-configuration cw)
18386 (add-hook 'after-save-hook
18387 (lambda ()
18388 (set-window-configuration
18389 (prog1 org-window-configuration
18390 (kill-buffer (current-buffer))))
18391 (org-install-agenda-files-menu)
18392 (message "New agenda file list installed"))
18393 nil 'local)
18394 (message "%s" (substitute-command-keys
18395 "Edit list and finish with \\[save-buffer]")))
18396 (customize-variable 'org-agenda-files)))
18398 (defun org-store-new-agenda-file-list (list)
18399 "Set new value for the agenda file list and save it correctly."
18400 (if (stringp org-agenda-files)
18401 (let ((fe (org-read-agenda-file-list t)) b u)
18402 (while (setq b (find-buffer-visiting org-agenda-files))
18403 (kill-buffer b))
18404 (with-temp-file org-agenda-files
18405 (insert
18406 (mapconcat
18407 (lambda (f) ;; Keep un-expanded entries.
18408 (if (setq u (assoc f fe))
18409 (cdr u)
18411 list "\n")
18412 "\n")))
18413 (let ((org-mode-hook nil) (org-inhibit-startup t)
18414 (org-insert-mode-line-in-empty-file nil))
18415 (setq org-agenda-files list)
18416 (customize-save-variable 'org-agenda-files org-agenda-files))))
18418 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18419 "Read the list of agenda files from a file.
18420 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18421 filenames, used by `org-store-new-agenda-file-list' to write back
18422 un-expanded file names."
18423 (when (file-directory-p org-agenda-files)
18424 (error "`org-agenda-files' cannot be a single directory"))
18425 (when (stringp org-agenda-files)
18426 (with-temp-buffer
18427 (insert-file-contents org-agenda-files)
18428 (mapcar
18429 (lambda (f)
18430 (let ((e (expand-file-name (substitute-in-file-name f)
18431 org-directory)))
18432 (if pair-with-expansion
18433 (cons e f)
18434 e)))
18435 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18437 ;;;###autoload
18438 (defun org-cycle-agenda-files ()
18439 "Cycle through the files in `org-agenda-files'.
18440 If the current buffer visits an agenda file, find the next one in the list.
18441 If the current buffer does not, find the first agenda file."
18442 (interactive)
18443 (let* ((fs (or (org-agenda-files t)
18444 (user-error "No agenda files")))
18445 (files (copy-sequence fs))
18446 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18447 file)
18448 (when tcf
18449 (while (and (setq file (pop files))
18450 (not (equal (file-truename file) tcf)))))
18451 (find-file (car (or files fs)))
18452 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18454 (defun org-agenda-file-to-front (&optional to-end)
18455 "Move/add the current file to the top of the agenda file list.
18456 If the file is not present in the list, it is added to the front. If it is
18457 present, it is moved there. With optional argument TO-END, add/move to the
18458 end of the list."
18459 (interactive "P")
18460 (let ((org-agenda-skip-unavailable-files nil)
18461 (file-alist (mapcar (lambda (x)
18462 (cons (file-truename x) x))
18463 (org-agenda-files t)))
18464 (ctf (file-truename
18465 (or buffer-file-name
18466 (user-error "Please save the current buffer to a file"))))
18467 x had)
18468 (setq x (assoc ctf file-alist) had x)
18470 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18471 (if to-end
18472 (setq file-alist (append (delq x file-alist) (list x)))
18473 (setq file-alist (cons x (delq x file-alist))))
18474 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18475 (org-install-agenda-files-menu)
18476 (message "File %s to %s of agenda file list"
18477 (if had "moved" "added") (if to-end "end" "front"))))
18479 (defun org-remove-file (&optional file)
18480 "Remove current file from the list of files in variable `org-agenda-files'.
18481 These are the files which are being checked for agenda entries.
18482 Optional argument FILE means use this file instead of the current."
18483 (interactive)
18484 (let* ((org-agenda-skip-unavailable-files nil)
18485 (file (or file buffer-file-name
18486 (user-error "Current buffer does not visit a file")))
18487 (true-file (file-truename file))
18488 (afile (abbreviate-file-name file))
18489 (files (delq nil (mapcar
18490 (lambda (x)
18491 (unless (equal true-file
18492 (file-truename x))
18494 (org-agenda-files t)))))
18495 (if (not (= (length files) (length (org-agenda-files t))))
18496 (progn
18497 (org-store-new-agenda-file-list files)
18498 (org-install-agenda-files-menu)
18499 (message "Removed from Org Agenda list: %s" afile))
18500 (message "File was not in list: %s (not removed)" afile))))
18502 (defun org-file-menu-entry (file)
18503 (vector file (list 'find-file file) t))
18505 (defun org-check-agenda-file (file)
18506 "Make sure FILE exists. If not, ask user what to do."
18507 (unless (file-exists-p file)
18508 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18509 (abbreviate-file-name file))
18510 (let ((r (downcase (read-char-exclusive))))
18511 (cond
18512 ((equal r ?r)
18513 (org-remove-file file)
18514 (throw 'nextfile t))
18515 (t (user-error "Abort"))))))
18517 (defun org-get-agenda-file-buffer (file)
18518 "Get an agenda buffer visiting FILE.
18519 If the buffer needs to be created, add it to the list of buffers
18520 which might be released later."
18521 (let ((buf (org-find-base-buffer-visiting file)))
18522 (if buf
18523 buf ; just return it
18524 ;; Make a new buffer and remember it
18525 (setq buf (find-file-noselect file))
18526 (when buf (push buf org-agenda-new-buffers))
18527 buf)))
18529 (defun org-release-buffers (blist)
18530 "Release all buffers in list, asking the user for confirmation when needed.
18531 When a buffer is unmodified, it is just killed. When modified, it is saved
18532 \(if the user agrees) and then killed."
18533 (let (file)
18534 (dolist (buf blist)
18535 (setq file (buffer-file-name buf))
18536 (when (and (buffer-modified-p buf)
18537 file
18538 (y-or-n-p (format "Save file %s? " file)))
18539 (with-current-buffer buf (save-buffer)))
18540 (kill-buffer buf))))
18542 (defun org-agenda-prepare-buffers (files)
18543 "Create buffers for all agenda files, protect archived trees and comments."
18544 (interactive)
18545 (let ((pa '(:org-archived t))
18546 (pc '(:org-comment t))
18547 (pall '(:org-archived t :org-comment t))
18548 (inhibit-read-only t)
18549 (org-inhibit-startup org-agenda-inhibit-startup)
18550 (rea (concat ":" org-archive-tag ":"))
18551 re pos)
18552 (setq org-tag-alist-for-agenda nil
18553 org-tag-groups-alist-for-agenda nil)
18554 (save-excursion
18555 (save-restriction
18556 (dolist (file files)
18557 (catch 'nextfile
18558 (if (bufferp file)
18559 (set-buffer file)
18560 (org-check-agenda-file file)
18561 (set-buffer (org-get-agenda-file-buffer file)))
18562 (widen)
18563 (org-set-regexps-and-options 'tags-only)
18564 (setq pos (point))
18565 (or (memq 'category org-agenda-ignore-properties)
18566 (org-refresh-category-properties))
18567 (or (memq 'stats org-agenda-ignore-properties)
18568 (org-refresh-stats-properties))
18569 (or (memq 'effort org-agenda-ignore-properties)
18570 (org-refresh-effort-properties))
18571 (or (memq 'appt org-agenda-ignore-properties)
18572 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18573 (setq org-todo-keywords-for-agenda
18574 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18575 (setq org-done-keywords-for-agenda
18576 (append org-done-keywords-for-agenda org-done-keywords))
18577 (setq org-todo-keyword-alist-for-agenda
18578 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18579 (setq org-tag-alist-for-agenda
18580 (org-uniquify
18581 (append org-tag-alist-for-agenda
18582 org-current-tag-alist)))
18583 ;; Merge current file's tag groups into global
18584 ;; `org-tag-groups-alist-for-agenda'.
18585 (when org-group-tags
18586 (dolist (alist org-tag-groups-alist)
18587 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18588 (if old
18589 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18590 (push alist org-tag-groups-alist-for-agenda)))))
18591 (org-with-silent-modifications
18592 (save-excursion
18593 (remove-text-properties (point-min) (point-max) pall)
18594 (when org-agenda-skip-archived-trees
18595 (goto-char (point-min))
18596 (while (re-search-forward rea nil t)
18597 (when (org-at-heading-p t)
18598 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18599 (goto-char (point-min))
18600 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18601 (while (re-search-forward re nil t)
18602 (when (save-match-data (org-in-commented-heading-p t))
18603 (add-text-properties
18604 (match-beginning 0) (org-end-of-subtree t) pc)))))
18605 (goto-char pos)))))
18606 (setq org-todo-keywords-for-agenda
18607 (org-uniquify org-todo-keywords-for-agenda))
18608 (setq org-todo-keyword-alist-for-agenda
18609 (org-uniquify org-todo-keyword-alist-for-agenda))))
18612 ;;;; CDLaTeX minor mode
18614 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18615 "Keymap for the minor `org-cdlatex-mode'.")
18617 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18618 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18619 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18620 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18621 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18623 (defvar org-cdlatex-texmathp-advice-is-done nil
18624 "Flag remembering if we have applied the advice to texmathp already.")
18626 (define-minor-mode org-cdlatex-mode
18627 "Toggle the minor `org-cdlatex-mode'.
18628 This mode supports entering LaTeX environment and math in LaTeX fragments
18629 in Org mode.
18630 \\{org-cdlatex-mode-map}"
18631 nil " OCDL" nil
18632 (when org-cdlatex-mode
18633 (require 'cdlatex)
18634 (run-hooks 'cdlatex-mode-hook)
18635 (cdlatex-compute-tables))
18636 (unless org-cdlatex-texmathp-advice-is-done
18637 (setq org-cdlatex-texmathp-advice-is-done t)
18638 (defadvice texmathp (around org-math-always-on activate)
18639 "Always return t in Org buffers.
18640 This is because we want to insert math symbols without dollars even outside
18641 the LaTeX math segments. If Org mode thinks that point is actually inside
18642 an embedded LaTeX fragment, let `texmathp' do its job.
18643 `\\[org-cdlatex-mode-map]'"
18644 (interactive)
18645 (let (p)
18646 (cond
18647 ((not (derived-mode-p 'org-mode)) ad-do-it)
18648 ((eq this-command 'cdlatex-math-symbol)
18649 (setq ad-return-value t
18650 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18652 (let ((p (org-inside-LaTeX-fragment-p)))
18653 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18654 (setq ad-return-value t
18655 texmathp-why '("Org mode embedded math" . 0))
18656 (when p ad-do-it)))))))))
18658 (defun turn-on-org-cdlatex ()
18659 "Unconditionally turn on `org-cdlatex-mode'."
18660 (org-cdlatex-mode 1))
18662 (defun org-try-cdlatex-tab ()
18663 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18664 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18665 - inside a LaTeX fragment, or
18666 - after the first word in a line, where an abbreviation expansion could
18667 insert a LaTeX environment."
18668 (when org-cdlatex-mode
18669 (cond
18670 ;; Before any word on the line: No expansion possible.
18671 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18672 ;; Just after first word on the line: Expand it. Make sure it
18673 ;; cannot happen on headlines, though.
18674 ((save-excursion
18675 (skip-chars-backward "a-zA-Z0-9*")
18676 (skip-chars-backward " \t")
18677 (and (bolp) (not (org-at-heading-p))))
18678 (cdlatex-tab) t)
18679 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18681 (defun org-cdlatex-underscore-caret (&optional _arg)
18682 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18683 Revert to the normal definition outside of these fragments."
18684 (interactive "P")
18685 (if (org-inside-LaTeX-fragment-p)
18686 (call-interactively 'cdlatex-sub-superscript)
18687 (let (org-cdlatex-mode)
18688 (call-interactively (key-binding (vector last-input-event))))))
18690 (defun org-cdlatex-math-modify (&optional _arg)
18691 "Execute `cdlatex-math-modify' in LaTeX fragments.
18692 Revert to the normal definition outside of these fragments."
18693 (interactive "P")
18694 (if (org-inside-LaTeX-fragment-p)
18695 (call-interactively 'cdlatex-math-modify)
18696 (let (org-cdlatex-mode)
18697 (call-interactively (key-binding (vector last-input-event))))))
18699 (defun org-cdlatex-environment-indent (&optional environment item)
18700 "Execute `cdlatex-environment' and indent the inserted environment.
18702 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18704 The inserted environment is indented to current indentation
18705 unless point is at the beginning of the line, in which the
18706 environment remains unintended."
18707 (interactive)
18708 ;; cdlatex-environment always return nil. Therefore, capture output
18709 ;; first and determine if an environment was selected.
18710 (let* ((beg (point-marker))
18711 (end (copy-marker (point) t))
18712 (inserted (progn
18713 (ignore-errors (cdlatex-environment environment item))
18714 (< beg end)))
18715 ;; Figure out how many lines to move forward after the
18716 ;; environment has been inserted.
18717 (lines (when inserted
18718 (save-excursion
18719 (- (cl-loop while (< beg (point))
18720 with x = 0
18721 do (forward-line -1)
18722 (cl-incf x)
18723 finally return x)
18724 (if (progn (goto-char beg)
18725 (and (progn (skip-chars-forward " \t") (eolp))
18726 (progn (skip-chars-backward " \t") (bolp))))
18727 1 0)))))
18728 (env (org-trim (delete-and-extract-region beg end))))
18729 (when inserted
18730 ;; Get indentation of next line unless at column 0.
18731 (let ((ind (if (bolp) 0
18732 (save-excursion
18733 (org-return-indent)
18734 (prog1 (org-get-indentation)
18735 (when (progn (skip-chars-forward " \t") (eolp))
18736 (delete-region beg (point)))))))
18737 (bol (progn (skip-chars-backward " \t") (bolp))))
18738 ;; Insert a newline before environment unless at column zero
18739 ;; to "escape" the current line. Insert a newline if
18740 ;; something is one the same line as \end{ENVIRONMENT}.
18741 (insert
18742 (concat (unless bol "\n") env
18743 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18744 (unless (zerop ind)
18745 (save-excursion
18746 (goto-char beg)
18747 (while (< (point) end)
18748 (unless (eolp) (indent-line-to ind))
18749 (forward-line))))
18750 (goto-char beg)
18751 (forward-line lines)
18752 (indent-line-to ind)))
18753 (set-marker beg nil)
18754 (set-marker end nil)))
18757 ;;;; LaTeX fragments
18759 (defun org-inside-LaTeX-fragment-p ()
18760 "Test if point is inside a LaTeX fragment.
18761 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18762 sequence appearing also before point.
18763 Even though the matchers for math are configurable, this function assumes
18764 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18765 delimiters are skipped when they have been removed by customization.
18766 The return value is nil, or a cons cell with the delimiter and the
18767 position of this delimiter.
18769 This function does a reasonably good job, but can locally be fooled by
18770 for example currency specifications. For example it will assume being in
18771 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18772 fragments that are properly closed, but during editing, we have to live
18773 with the uncertainty caused by missing closing delimiters. This function
18774 looks only before point, not after."
18775 (catch 'exit
18776 (let ((pos (point))
18777 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18778 (lim (progn
18779 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18780 (point)))
18781 dd-on str (start 0) m re)
18782 (goto-char pos)
18783 (when dodollar
18784 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18785 re (nth 1 (assoc "$" org-latex-regexps)))
18786 (while (string-match re str start)
18787 (cond
18788 ((= (match-end 0) (length str))
18789 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18790 ((= (match-end 0) (- (length str) 5))
18791 (throw 'exit nil))
18792 (t (setq start (match-end 0))))))
18793 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18794 (goto-char pos)
18795 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18796 (and (match-beginning 2) (throw 'exit nil))
18797 ;; count $$
18798 (while (re-search-backward "\\$\\$" lim t)
18799 (setq dd-on (not dd-on)))
18800 (goto-char pos)
18801 (when dd-on (cons "$$" m))))))
18803 (defun org-inside-latex-macro-p ()
18804 "Is point inside a LaTeX macro or its arguments?"
18805 (save-match-data
18806 (org-in-regexp
18807 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18809 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18810 "Build an overlay between BEG and END using IMAGE file.
18811 Argument IMAGETYPE is the extension of the displayed image,
18812 as a string. It defaults to \"png\"."
18813 (let ((ov (make-overlay beg end))
18814 (imagetype (or (intern imagetype) 'png)))
18815 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18816 (overlay-put ov 'evaporate t)
18817 (overlay-put ov
18818 'modification-hooks
18819 (list (lambda (o _flag _beg _end &optional _l)
18820 (delete-overlay o))))
18821 (overlay-put ov
18822 'display
18823 (list 'image :type imagetype :file image :ascent 'center))))
18825 (defun org--list-latex-overlays (&optional beg end)
18826 "List all Org LaTeX overlays in current buffer.
18827 Limit to overlays between BEG and END when those are provided."
18828 (cl-remove-if-not
18829 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18830 (overlays-in (or beg (point-min)) (or end (point-max)))))
18832 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18833 "Remove all overlays with LaTeX fragment images in current buffer.
18834 When optional arguments BEG and END are non-nil, remove all
18835 overlays between them instead. Return a non-nil value when some
18836 overlays were removed, nil otherwise."
18837 (let ((overlays (org--list-latex-overlays beg end)))
18838 (mapc #'delete-overlay overlays)
18839 overlays))
18841 (defun org-toggle-latex-fragment (&optional arg)
18842 "Preview the LaTeX fragment at point, or all locally or globally.
18844 If the cursor is on a LaTeX fragment, create the image and overlay
18845 it over the source code, if there is none. Remove it otherwise.
18846 If there is no fragment at point, display all fragments in the
18847 current section.
18849 With prefix ARG, preview or clear image for all fragments in the
18850 current subtree or in the whole buffer when used before the first
18851 headline. With a prefix ARG `\\[universal-argument] \
18852 \\[universal-argument]' preview or clear images
18853 for all fragments in the buffer."
18854 (interactive "P")
18855 (when (display-graphic-p)
18856 (catch 'exit
18857 (save-excursion
18858 (let (beg end msg)
18859 (cond
18860 ((or (equal arg '(16))
18861 (and (equal arg '(4))
18862 (org-with-limited-levels (org-before-first-heading-p))))
18863 (if (org-remove-latex-fragment-image-overlays)
18864 (progn (message "LaTeX fragments images removed from buffer")
18865 (throw 'exit nil))
18866 (setq msg "Creating images for buffer...")))
18867 ((equal arg '(4))
18868 (org-with-limited-levels (org-back-to-heading t))
18869 (setq beg (point))
18870 (setq end (progn (org-end-of-subtree t) (point)))
18871 (if (org-remove-latex-fragment-image-overlays beg end)
18872 (progn
18873 (message "LaTeX fragment images removed from subtree")
18874 (throw 'exit nil))
18875 (setq msg "Creating images for subtree...")))
18876 ((let ((datum (org-element-context)))
18877 (when (memq (org-element-type datum)
18878 '(latex-environment latex-fragment))
18879 (setq beg (org-element-property :begin datum))
18880 (setq end (org-element-property :end datum))
18881 (if (org-remove-latex-fragment-image-overlays beg end)
18882 (progn (message "LaTeX fragment image removed")
18883 (throw 'exit nil))
18884 (setq msg "Creating image...")))))
18886 (org-with-limited-levels
18887 (setq beg (if (org-at-heading-p) (line-beginning-position)
18888 (outline-previous-heading)
18889 (point)))
18890 (setq end (progn (outline-next-heading) (point)))
18891 (if (org-remove-latex-fragment-image-overlays beg end)
18892 (progn
18893 (message "LaTeX fragment images removed from section")
18894 (throw 'exit nil))
18895 (setq msg "Creating images for section...")))))
18896 (let ((file (buffer-file-name (buffer-base-buffer))))
18897 (org-format-latex
18898 (concat org-preview-latex-image-directory "org-ltximg")
18899 beg end
18900 ;; Emacs cannot overlay images from remote hosts. Create
18901 ;; it in `temporary-file-directory' instead.
18902 (if (or (not file) (file-remote-p file))
18903 temporary-file-directory
18904 default-directory)
18905 'overlays msg 'forbuffer org-preview-latex-default-process))
18906 (message (concat msg "done")))))))
18908 (defun org-format-latex
18909 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18910 "Replace LaTeX fragments with links to an image.
18912 The function takes care of creating the replacement image.
18914 Only consider fragments between BEG and END when those are
18915 provided.
18917 When optional argument OVERLAYS is non-nil, display the image on
18918 top of the fragment instead of replacing it.
18920 PROCESSING-TYPE is the conversion method to use, as a symbol.
18922 Some of the options can be changed using the variable
18923 `org-format-latex-options', which see."
18924 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18925 (unless (eq processing-type 'verbatim)
18926 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18927 (cnt 0)
18928 checkdir-flag)
18929 (goto-char (or beg (point-min)))
18930 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18931 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18932 (overlay-recenter (or end (point-max))))
18933 (while (re-search-forward math-regexp end t)
18934 (unless (and overlays
18935 (eq (get-char-property (point) 'org-overlay-type)
18936 'org-latex-overlay))
18937 (let* ((context (org-element-context))
18938 (type (org-element-type context)))
18939 (when (memq type '(latex-environment latex-fragment))
18940 (let ((block-type (eq type 'latex-environment))
18941 (value (org-element-property :value context))
18942 (beg (org-element-property :begin context))
18943 (end (save-excursion
18944 (goto-char (org-element-property :end context))
18945 (skip-chars-backward " \r\t\n")
18946 (point))))
18947 (cond
18948 ((eq processing-type 'mathjax)
18949 ;; Prepare for MathJax processing.
18950 (if (not (string-match "\\`\\$\\$?" value))
18951 (goto-char end)
18952 (delete-region beg end)
18953 (if (string= (match-string 0 value) "$$")
18954 (insert "\\[" (substring value 2 -2) "\\]")
18955 (insert "\\(" (substring value 1 -1) "\\)"))))
18956 ((assq processing-type org-preview-latex-process-alist)
18957 ;; Process to an image.
18958 (cl-incf cnt)
18959 (goto-char beg)
18960 (let* ((processing-info
18961 (cdr (assq processing-type org-preview-latex-process-alist)))
18962 (face (face-at-point))
18963 ;; Get the colors from the face at point.
18965 (let ((color (plist-get org-format-latex-options
18966 :foreground)))
18967 (if (and forbuffer (eq color 'auto))
18968 (face-attribute face :foreground nil 'default)
18969 color)))
18971 (let ((color (plist-get org-format-latex-options
18972 :background)))
18973 (if (and forbuffer (eq color 'auto))
18974 (face-attribute face :background nil 'default)
18975 color)))
18976 (hash (sha1 (prin1-to-string
18977 (list org-format-latex-header
18978 org-latex-default-packages-alist
18979 org-latex-packages-alist
18980 org-format-latex-options
18981 forbuffer value fg bg))))
18982 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18983 (absprefix (expand-file-name prefix dir))
18984 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18985 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18986 (sep (and block-type "\n\n"))
18987 (link (concat sep "[[file:" linkfile "]]" sep))
18988 (options
18989 (org-combine-plists
18990 org-format-latex-options
18991 `(:foreground ,fg :background ,bg))))
18992 (when msg (message msg cnt))
18993 (unless checkdir-flag ; Ensure the directory exists.
18994 (setq checkdir-flag t)
18995 (let ((todir (file-name-directory absprefix)))
18996 (unless (file-directory-p todir)
18997 (make-directory todir t))))
18998 (unless (file-exists-p movefile)
18999 (org-create-formula-image
19000 value movefile options forbuffer processing-type))
19001 (if overlays
19002 (progn
19003 (dolist (o (overlays-in beg end))
19004 (when (eq (overlay-get o 'org-overlay-type)
19005 'org-latex-overlay)
19006 (delete-overlay o)))
19007 (org--format-latex-make-overlay beg end movefile imagetype)
19008 (goto-char end))
19009 (delete-region beg end)
19010 (insert
19011 (org-add-props link
19012 (list 'org-latex-src
19013 (replace-regexp-in-string "\"" "" value)
19014 'org-latex-src-embed-type
19015 (if block-type 'paragraph 'character)))))))
19016 ((eq processing-type 'mathml)
19017 ;; Process to MathML.
19018 (unless (org-format-latex-mathml-available-p)
19019 (user-error "LaTeX to MathML converter not configured"))
19020 (cl-incf cnt)
19021 (when msg (message msg cnt))
19022 (goto-char beg)
19023 (delete-region beg end)
19024 (insert (org-format-latex-as-mathml
19025 value block-type prefix dir)))
19027 (error "Unknown conversion process %s for LaTeX fragments"
19028 processing-type)))))))))))
19030 (defun org-create-math-formula (latex-frag &optional mathml-file)
19031 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19032 Use `org-latex-to-mathml-convert-command'. If the conversion is
19033 sucessful, return the portion between \"<math...> </math>\"
19034 elements otherwise return nil. When MATHML-FILE is specified,
19035 write the results in to that file. When invoked as an
19036 interactive command, prompt for LATEX-FRAG, with initial value
19037 set to the current active region and echo the results for user
19038 inspection."
19039 (interactive (list (let ((frag (when (org-region-active-p)
19040 (buffer-substring-no-properties
19041 (region-beginning) (region-end)))))
19042 (read-string "LaTeX Fragment: " frag nil frag))))
19043 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19044 (let* ((tmp-in-file
19045 (let ((file (file-relative-name
19046 (make-temp-name (expand-file-name "ltxmathml-in")))))
19047 (write-region latex-frag nil file)
19048 file))
19049 (tmp-out-file (file-relative-name
19050 (make-temp-name (expand-file-name "ltxmathml-out"))))
19051 (cmd (format-spec
19052 org-latex-to-mathml-convert-command
19053 `((?j . ,(and org-latex-to-mathml-jar-file
19054 (shell-quote-argument
19055 (expand-file-name
19056 org-latex-to-mathml-jar-file))))
19057 (?I . ,(shell-quote-argument tmp-in-file))
19058 (?i . ,latex-frag)
19059 (?o . ,(shell-quote-argument tmp-out-file)))))
19060 mathml shell-command-output)
19061 (when (called-interactively-p 'any)
19062 (unless (org-format-latex-mathml-available-p)
19063 (user-error "LaTeX to MathML converter not configured")))
19064 (message "Running %s" cmd)
19065 (setq shell-command-output (shell-command-to-string cmd))
19066 (setq mathml
19067 (when (file-readable-p tmp-out-file)
19068 (with-current-buffer (find-file-noselect tmp-out-file t)
19069 (goto-char (point-min))
19070 (when (re-search-forward
19071 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19072 (regexp-quote
19073 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19074 nil t)
19075 (prog1 (match-string 0) (kill-buffer))))))
19076 (cond
19077 (mathml
19078 (setq mathml
19079 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19080 (when mathml-file
19081 (write-region mathml nil mathml-file))
19082 (when (called-interactively-p 'any)
19083 (message mathml)))
19084 ((message "LaTeX to MathML conversion failed")
19085 (message shell-command-output)))
19086 (delete-file tmp-in-file)
19087 (when (file-exists-p tmp-out-file)
19088 (delete-file tmp-out-file))
19089 mathml))
19091 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19092 prefix &optional dir)
19093 "Use `org-create-math-formula' but check local cache first."
19094 (let* ((absprefix (expand-file-name prefix dir))
19095 (print-length nil) (print-level nil)
19096 (formula-id (concat
19097 "formula-"
19098 (sha1
19099 (prin1-to-string
19100 (list latex-frag
19101 org-latex-to-mathml-convert-command)))))
19102 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19103 (formula-cache-dir (file-name-directory formula-cache)))
19105 (unless (file-directory-p formula-cache-dir)
19106 (make-directory formula-cache-dir t))
19108 (unless (file-exists-p formula-cache)
19109 (org-create-math-formula latex-frag formula-cache))
19111 (if (file-exists-p formula-cache)
19112 ;; Successful conversion. Return the link to MathML file.
19113 (org-add-props
19114 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19115 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19116 'org-latex-src-embed-type (if latex-frag-type
19117 'paragraph 'character)))
19118 ;; Failed conversion. Return the LaTeX fragment verbatim
19119 latex-frag)))
19121 (defun org--get-display-dpi ()
19122 "Get the DPI of the display.
19123 The function assumes that the display has the same pixel width in
19124 the horizontal and vertical directions."
19125 (if (display-graphic-p)
19126 (round (/ (display-pixel-height)
19127 (/ (display-mm-height) 25.4)))
19128 (error "Attempt to calculate the dpi of a non-graphic display")))
19130 (defun org-create-formula-image
19131 (string tofile options buffer &optional processing-type)
19132 "Create an image from LaTeX source using external processes.
19134 The LaTeX STRING is saved to a temporary LaTeX file, then
19135 converted to an image file by process PROCESSING-TYPE defined in
19136 `org-preview-latex-process-alist'. A nil value defaults to
19137 `org-preview-latex-default-process'.
19139 The generated image file is eventually moved to TOFILE.
19141 The OPTIONS argument controls the size, foreground color and
19142 background color of the generated image.
19144 When BUFFER non-nil, this function is used for LaTeX previewing.
19145 Otherwise, it is used to deal with LaTeX snippets showed in
19146 a HTML file."
19147 (let* ((processing-type (or processing-type
19148 org-preview-latex-default-process))
19149 (processing-info
19150 (cdr (assq processing-type org-preview-latex-process-alist)))
19151 (programs (plist-get processing-info :programs))
19152 (error-message (or (plist-get processing-info :message) ""))
19153 (use-xcolor (plist-get processing-info :use-xcolor))
19154 (image-input-type (plist-get processing-info :image-input-type))
19155 (image-output-type (plist-get processing-info :image-output-type))
19156 (post-clean (or (plist-get processing-info :post-clean)
19157 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19158 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19159 (latex-header
19160 (or (plist-get processing-info :latex-header)
19161 (org-latex-make-preamble
19162 (org-export-get-environment (org-export-get-backend 'latex))
19163 org-format-latex-header
19164 'snippet)))
19165 (latex-compiler (plist-get processing-info :latex-compiler))
19166 (image-converter (plist-get processing-info :image-converter))
19167 (tmpdir temporary-file-directory)
19168 (texfilebase (make-temp-name
19169 (expand-file-name "orgtex" tmpdir)))
19170 (texfile (concat texfilebase ".tex"))
19171 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19172 '(1.0 . 1.0)))
19173 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19174 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19175 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19176 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19177 "Black"))
19178 (bg (or (plist-get options (if buffer :background :html-background))
19179 "Transparent"))
19180 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19181 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19182 (dolist (program programs)
19183 (org-check-external-command program error-message))
19184 (if use-xcolor
19185 (progn (if (eq fg 'default)
19186 (setq fg (org-latex-color :foreground))
19187 (setq fg (org-latex-color-format fg)))
19188 (if (eq bg 'default)
19189 (setq bg (org-latex-color :background))
19190 (setq bg (org-latex-color-format
19191 (if (string= bg "Transparent") "white" bg))))
19192 (with-temp-file texfile
19193 (insert latex-header)
19194 (insert "\n\\begin{document}\n"
19195 "\\definecolor{fg}{rgb}{" fg "}\n"
19196 "\\definecolor{bg}{rgb}{" bg "}\n"
19197 "\n\\pagecolor{bg}\n"
19198 "\n{\\color{fg}\n"
19199 string
19200 "\n}\n"
19201 "\n\\end{document}\n")))
19202 (if (eq fg 'default)
19203 (setq fg (org-dvipng-color :foreground))
19204 (unless (string= fg "Transparent")
19205 (setq fg (org-dvipng-color-format fg))))
19206 (if (eq bg 'default)
19207 (setq bg (org-dvipng-color :background))
19208 (unless (string= bg "Transparent")
19209 (setq bg (org-dvipng-color-format bg))))
19210 (with-temp-file texfile
19211 (insert latex-header)
19212 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19214 (let* ((err-msg (format "Please adjust '%s' part of \
19215 `org-preview-latex-process-alist'."
19216 processing-type))
19217 (image-input-file
19218 (org-compile-file
19219 texfile latex-compiler image-input-type err-msg log-buf))
19220 (image-output-file
19221 (org-compile-file
19222 image-input-file image-converter image-output-type err-msg log-buf
19223 `((?F . ,(shell-quote-argument fg))
19224 (?B . ,(shell-quote-argument bg))
19225 (?D . ,(shell-quote-argument (format "%s" dpi)))
19226 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19227 (copy-file image-output-file tofile 'replace)
19228 (dolist (e post-clean)
19229 (when (file-exists-p (concat texfilebase e))
19230 (delete-file (concat texfilebase e))))
19231 image-output-file)))
19233 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19234 "Fill a LaTeX header template TPL.
19235 In the template, the following place holders will be recognized:
19237 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19238 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19239 [PACKAGES] \\usepackage statements for PKG
19240 [NO-PACKAGES] do not include PKG
19241 [EXTRA] the string EXTRA
19242 [NO-EXTRA] do not include EXTRA
19244 For backward compatibility, if both the positive and the negative place
19245 holder is missing, the positive one (without the \"NO-\") will be
19246 assumed to be present at the end of the template.
19247 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19248 EXTRA is a string.
19249 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19250 (let (rpl (end ""))
19251 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19252 (setq rpl (if (or (match-end 1) (not def-pkg))
19253 "" (org-latex-packages-to-string def-pkg snippets-p t))
19254 tpl (replace-match rpl t t tpl))
19255 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19257 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19258 (setq rpl (if (or (match-end 1) (not pkg))
19259 "" (org-latex-packages-to-string pkg snippets-p t))
19260 tpl (replace-match rpl t t tpl))
19261 (when pkg (setq end
19262 (concat end "\n"
19263 (org-latex-packages-to-string pkg snippets-p)))))
19265 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19266 (setq rpl (if (or (match-end 1) (not extra))
19267 "" (concat extra "\n"))
19268 tpl (replace-match rpl t t tpl))
19269 (when (and extra (string-match "\\S-" extra))
19270 (setq end (concat end "\n" extra))))
19272 (if (string-match "\\S-" end)
19273 (concat tpl "\n" end)
19274 tpl)))
19276 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19277 "Turn an alist of packages into a string with the \\usepackage macros."
19278 (setq pkg (mapconcat (lambda(p)
19279 (cond
19280 ((stringp p) p)
19281 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19282 (format "%% Package %s omitted" (cadr p)))
19283 ((equal "" (car p))
19284 (format "\\usepackage{%s}" (cadr p)))
19286 (format "\\usepackage[%s]{%s}"
19287 (car p) (cadr p)))))
19289 "\n"))
19290 (if newline (concat pkg "\n") pkg))
19292 (defun org-dvipng-color (attr)
19293 "Return a RGB color specification for dvipng."
19294 (org-dvipng-color-format (face-attribute 'default attr nil)))
19296 (defun org-dvipng-color-format (color-name)
19297 "Convert COLOR-NAME to a RGB color value for dvipng."
19298 (apply #'format "rgb %s %s %s"
19299 (mapcar 'org-normalize-color
19300 (color-values color-name))))
19302 (defun org-latex-color (attr)
19303 "Return a RGB color for the LaTeX color package."
19304 (org-latex-color-format (face-attribute 'default attr nil)))
19306 (defun org-latex-color-format (color-name)
19307 "Convert COLOR-NAME to a RGB color value."
19308 (apply #'format "%s,%s,%s"
19309 (mapcar 'org-normalize-color
19310 (color-values color-name))))
19312 (defun org-normalize-color (value)
19313 "Return string to be used as color value for an RGB component."
19314 (format "%g" (/ value 65535.0)))
19318 ;; Image display
19320 (defvar-local org-inline-image-overlays nil)
19322 (defun org-toggle-inline-images (&optional include-linked)
19323 "Toggle the display of inline images.
19324 INCLUDE-LINKED is passed to `org-display-inline-images'."
19325 (interactive "P")
19326 (if org-inline-image-overlays
19327 (progn
19328 (org-remove-inline-images)
19329 (when (called-interactively-p 'interactive)
19330 (message "Inline image display turned off")))
19331 (org-display-inline-images include-linked)
19332 (when (called-interactively-p 'interactive)
19333 (message (if org-inline-image-overlays
19334 (format "%d images displayed inline"
19335 (length org-inline-image-overlays))
19336 "No images to display inline")))))
19338 (defun org-redisplay-inline-images ()
19339 "Refresh the display of inline images."
19340 (interactive)
19341 (if (not org-inline-image-overlays)
19342 (org-toggle-inline-images)
19343 (org-toggle-inline-images)
19344 (org-toggle-inline-images)))
19346 (defun org-display-inline-images (&optional include-linked refresh beg end)
19347 "Display inline images.
19349 An inline image is a link which follows either of these
19350 conventions:
19352 1. Its path is a file with an extension matching return value
19353 from `image-file-name-regexp' and it has no contents.
19355 2. Its description consists in a single link of the previous
19356 type.
19358 When optional argument INCLUDE-LINKED is non-nil, also links with
19359 a text description part will be inlined. This can be nice for
19360 a quick look at those images, but it does not reflect what
19361 exported files will look like.
19363 When optional argument REFRESH is non-nil, refresh existing
19364 images between BEG and END. This will create new image displays
19365 only if necessary. BEG and END default to the buffer
19366 boundaries."
19367 (interactive "P")
19368 (when (display-graphic-p)
19369 (unless refresh
19370 (org-remove-inline-images)
19371 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19372 (org-with-wide-buffer
19373 (goto-char (or beg (point-min)))
19374 (let ((case-fold-search t)
19375 (file-extension-re (image-file-name-regexp)))
19376 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19377 (let ((link (save-match-data (org-element-context))))
19378 ;; Check if we're at an inline image.
19379 (when (and (equal (org-element-property :type link) "file")
19380 (or include-linked
19381 (not (org-element-property :contents-begin link)))
19382 (let ((parent (org-element-property :parent link)))
19383 (or (not (eq (org-element-type parent) 'link))
19384 (not (cdr (org-element-contents parent)))))
19385 (string-match-p file-extension-re
19386 (org-element-property :path link)))
19387 (let ((file (expand-file-name
19388 (org-link-unescape
19389 (org-element-property :path link)))))
19390 (when (file-exists-p file)
19391 (let ((width
19392 ;; Apply `org-image-actual-width' specifications.
19393 (cond
19394 ((not (image-type-available-p 'imagemagick)) nil)
19395 ((eq org-image-actual-width t) nil)
19396 ((listp org-image-actual-width)
19398 ;; First try to find a width among
19399 ;; attributes associated to the paragraph
19400 ;; containing link.
19401 (let ((paragraph
19402 (let ((e link))
19403 (while (and (setq e (org-element-property
19404 :parent e))
19405 (not (eq (org-element-type e)
19406 'paragraph))))
19407 e)))
19408 (when paragraph
19409 (save-excursion
19410 (goto-char (org-element-property :begin paragraph))
19411 (when
19412 (re-search-forward
19413 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19414 (org-element-property
19415 :post-affiliated paragraph)
19417 (string-to-number (match-string 1))))))
19418 ;; Otherwise, fall-back to provided number.
19419 (car org-image-actual-width)))
19420 ((numberp org-image-actual-width)
19421 org-image-actual-width)))
19422 (old (get-char-property-and-overlay
19423 (org-element-property :begin link)
19424 'org-image-overlay)))
19425 (if (and (car-safe old) refresh)
19426 (image-refresh (overlay-get (cdr old) 'display))
19427 (let ((image (create-image file
19428 (and width 'imagemagick)
19430 :width width)))
19431 (when image
19432 (let* ((link
19433 ;; If inline image is the description
19434 ;; of another link, be sure to
19435 ;; consider the latter as the one to
19436 ;; apply the overlay on.
19437 (let ((parent
19438 (org-element-property :parent link)))
19439 (if (eq (org-element-type parent) 'link)
19440 parent
19441 link)))
19442 (ov (make-overlay
19443 (org-element-property :begin link)
19444 (progn
19445 (goto-char
19446 (org-element-property :end link))
19447 (skip-chars-backward " \t")
19448 (point)))))
19449 (overlay-put ov 'display image)
19450 (overlay-put ov 'face 'default)
19451 (overlay-put ov 'org-image-overlay t)
19452 (overlay-put
19453 ov 'modification-hooks
19454 (list 'org-display-inline-remove-overlay))
19455 (push ov org-inline-image-overlays)))))))))))))))
19457 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19458 "Remove inline-display overlay if a corresponding region is modified."
19459 (let ((inhibit-modification-hooks t))
19460 (when (and ov after)
19461 (delete ov org-inline-image-overlays)
19462 (delete-overlay ov))))
19464 (defun org-remove-inline-images ()
19465 "Remove inline display of images."
19466 (interactive)
19467 (mapc #'delete-overlay org-inline-image-overlays)
19468 (setq org-inline-image-overlays nil))
19470 ;;;; Key bindings
19472 ;; Outline functions from `outline-mode-prefix-map'
19473 ;; that can be remapped in Org:
19474 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19475 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19476 (define-key org-mode-map [remap outline-forward-same-level]
19477 'org-forward-heading-same-level)
19478 (define-key org-mode-map [remap outline-backward-same-level]
19479 'org-backward-heading-same-level)
19480 (define-key org-mode-map [remap outline-show-branches]
19481 'org-kill-note-or-show-branches)
19482 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19483 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19484 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19485 (define-key org-mode-map [remap outline-next-visible-heading]
19486 'org-next-visible-heading)
19487 (define-key org-mode-map [remap outline-previous-visible-heading]
19488 'org-previous-visible-heading)
19489 (define-key org-mode-map [remap show-children] 'org-show-children)
19491 ;; Outline functions from `outline-mode-prefix-map' that can not
19492 ;; be remapped in Org:
19494 ;; - the column "key binding" shows whether the Outline function is still
19495 ;; available in Org mode on the same key that it has been bound to in
19496 ;; Outline mode:
19497 ;; - "overridden": key used for a different functionality in Org mode
19498 ;; - else: key still bound to the same Outline function in Org mode
19500 ;; | Outline function | key binding | Org replacement |
19501 ;; |------------------------------------+-------------+--------------------------|
19502 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19503 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19504 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19505 ;; | `show-entry' | overridden | no replacement |
19506 ;; | `show-branches' | `C-c C-k' | still same function |
19507 ;; | `show-subtree' | overridden | visibility cycling |
19508 ;; | `show-all' | overridden | no replacement |
19509 ;; | `hide-subtree' | overridden | visibility cycling |
19510 ;; | `hide-body' | overridden | no replacement |
19511 ;; | `hide-entry' | overridden | visibility cycling |
19512 ;; | `hide-leaves' | overridden | no replacement |
19513 ;; | `hide-sublevels' | overridden | no replacement |
19514 ;; | `hide-other' | overridden | no replacement |
19516 ;; Make `C-c C-x' a prefix key
19517 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19519 ;; TAB key with modifiers
19520 (org-defkey org-mode-map "\C-i" 'org-cycle)
19521 (org-defkey org-mode-map [(tab)] 'org-cycle)
19522 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19523 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19524 ;; The following line is necessary under Suse GNU/Linux
19525 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19526 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19527 (define-key org-mode-map [backtab] 'org-shifttab)
19529 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19530 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19531 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19533 ;; Cursor keys with modifiers
19534 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19535 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19536 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19537 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19539 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19540 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19541 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19542 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19543 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19544 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19546 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19547 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19548 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19549 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19551 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19552 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19553 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19554 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19556 ;; Babel keys
19557 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19558 (dolist (pair org-babel-key-bindings)
19559 (define-key org-babel-map (car pair) (cdr pair)))
19561 ;;; Extra keys for tty access.
19562 ;; We only set them when really needed because otherwise the
19563 ;; menus don't show the simple keys
19565 (when (or org-use-extra-keys (not window-system))
19566 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19567 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19568 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19569 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19570 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19571 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19572 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19573 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19574 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19575 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19576 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19577 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19578 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19579 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19580 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19581 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19582 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19583 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19584 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19585 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19586 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19587 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19588 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19589 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19590 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19591 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19592 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19593 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19595 ;; All the other keys
19597 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19598 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19599 (if (boundp 'narrow-map)
19600 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19601 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19602 (if (boundp 'narrow-map)
19603 (org-defkey narrow-map "b" 'org-narrow-to-block)
19604 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19605 (if (boundp 'narrow-map)
19606 (org-defkey narrow-map "e" 'org-narrow-to-element)
19607 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19608 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19609 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19610 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19611 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19612 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19613 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19614 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19615 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19616 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19617 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19618 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19619 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19620 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19621 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19622 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19623 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19624 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19625 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19626 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19627 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19628 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19629 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19630 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19631 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19632 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19633 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19634 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19635 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19636 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19637 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19638 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19639 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19640 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19641 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19642 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19643 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19644 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19645 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19646 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19647 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19648 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19649 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19650 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19651 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19652 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19653 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19654 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19655 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19656 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19657 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19658 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19659 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19660 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19661 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19662 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19663 (org-defkey org-mode-map "\C-c^" 'org-sort)
19664 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19665 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19666 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19667 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19668 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19669 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19670 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19671 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19672 (org-defkey org-mode-map "\C-m" 'org-return)
19673 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19674 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19675 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19676 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19677 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19678 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19679 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19680 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19681 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19682 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19683 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19684 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19685 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19686 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19687 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19688 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19689 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19690 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19691 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19692 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19693 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19694 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19695 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19696 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19697 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19699 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19700 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19701 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19703 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19704 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19705 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19706 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19707 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19708 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19709 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19710 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19711 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19712 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19713 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19714 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19715 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19716 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19717 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19718 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19719 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19720 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19721 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19722 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19723 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19724 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19726 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19727 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19728 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19729 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19730 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19732 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19734 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19736 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19737 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19739 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19742 (defconst org-speed-commands-default
19744 ("Outline Navigation")
19745 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19746 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19747 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19748 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19749 ("F" . org-next-block)
19750 ("B" . org-previous-block)
19751 ("u" . (org-speed-move-safe 'outline-up-heading))
19752 ("j" . org-goto)
19753 ("g" . (org-refile t))
19754 ("Outline Visibility")
19755 ("c" . org-cycle)
19756 ("C" . org-shifttab)
19757 (" " . org-display-outline-path)
19758 ("s" . org-narrow-to-subtree)
19759 ("=" . org-columns)
19760 ("Outline Structure Editing")
19761 ("U" . org-metaup)
19762 ("D" . org-metadown)
19763 ("r" . org-metaright)
19764 ("l" . org-metaleft)
19765 ("R" . org-shiftmetaright)
19766 ("L" . org-shiftmetaleft)
19767 ("i" . (progn (forward-char 1) (call-interactively
19768 'org-insert-heading-respect-content)))
19769 ("^" . org-sort)
19770 ("w" . org-refile)
19771 ("a" . org-archive-subtree-default-with-confirmation)
19772 ("@" . org-mark-subtree)
19773 ("#" . org-toggle-comment)
19774 ("Clock Commands")
19775 ("I" . org-clock-in)
19776 ("O" . org-clock-out)
19777 ("Meta Data Editing")
19778 ("t" . org-todo)
19779 ("," . (org-priority))
19780 ("0" . (org-priority ?\ ))
19781 ("1" . (org-priority ?A))
19782 ("2" . (org-priority ?B))
19783 ("3" . (org-priority ?C))
19784 (":" . org-set-tags-command)
19785 ("e" . org-set-effort)
19786 ("E" . org-inc-effort)
19787 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19788 (org-entry-put (point) "APPT_WARNTIME" m)))
19789 ("Agenda Views etc")
19790 ("v" . org-agenda)
19791 ("/" . org-sparse-tree)
19792 ("Misc")
19793 ("o" . org-open-at-point)
19794 ("?" . org-speed-command-help)
19795 ("<" . (org-agenda-set-restriction-lock 'subtree))
19796 (">" . (org-agenda-remove-restriction-lock))
19798 "The default speed commands.")
19800 (defun org-print-speed-command (e)
19801 (if (> (length (car e)) 1)
19802 (progn
19803 (princ "\n")
19804 (princ (car e))
19805 (princ "\n")
19806 (princ (make-string (length (car e)) ?-))
19807 (princ "\n"))
19808 (princ (car e))
19809 (princ " ")
19810 (if (symbolp (cdr e))
19811 (princ (symbol-name (cdr e)))
19812 (prin1 (cdr e)))
19813 (princ "\n")))
19815 (defun org-speed-command-help ()
19816 "Show the available speed commands."
19817 (interactive)
19818 (if (not org-use-speed-commands)
19819 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19820 (with-output-to-temp-buffer "*Help*"
19821 (princ "User-defined Speed commands\n===========================\n")
19822 (mapc #'org-print-speed-command org-speed-commands-user)
19823 (princ "\n")
19824 (princ "Built-in Speed commands\n=======================\n")
19825 (mapc #'org-print-speed-command org-speed-commands-default))
19826 (with-current-buffer "*Help*"
19827 (setq truncate-lines t))))
19829 (defun org-speed-move-safe (cmd)
19830 "Execute CMD, but make sure that the cursor always ends up in a headline.
19831 If not, return to the original position and throw an error."
19832 (interactive)
19833 (let ((pos (point)))
19834 (call-interactively cmd)
19835 (unless (and (bolp) (org-at-heading-p))
19836 (goto-char pos)
19837 (error "Boundary reached while executing %s" cmd))))
19839 (defvar org-self-insert-command-undo-counter 0)
19841 (defvar org-table-auto-blank-field) ; defined in org-table.el
19842 (defvar org-speed-command nil)
19844 (defun org-speed-command-activate (keys)
19845 "Hook for activating single-letter speed commands.
19846 `org-speed-commands-default' specifies a minimal command set.
19847 Use `org-speed-commands-user' for further customization."
19848 (when (or (and (bolp) (looking-at org-outline-regexp))
19849 (and (functionp org-use-speed-commands)
19850 (funcall org-use-speed-commands)))
19851 (cdr (assoc keys (append org-speed-commands-user
19852 org-speed-commands-default)))))
19854 (defun org-babel-speed-command-activate (keys)
19855 "Hook for activating single-letter code block commands."
19856 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19857 (cdr (assoc keys org-babel-key-bindings))))
19859 (defcustom org-speed-command-hook
19860 '(org-speed-command-activate org-babel-speed-command-activate)
19861 "Hook for activating speed commands at strategic locations.
19862 Hook functions are called in sequence until a valid handler is
19863 found.
19865 Each hook takes a single argument, a user-pressed command key
19866 which is also a `self-insert-command' from the global map.
19868 Within the hook, examine the cursor position and the command key
19869 and return nil or a valid handler as appropriate. Handler could
19870 be one of an interactive command, a function, or a form.
19872 Set `org-use-speed-commands' to non-nil value to enable this
19873 hook. The default setting is `org-speed-command-activate'."
19874 :group 'org-structure
19875 :version "24.1"
19876 :type 'hook)
19878 (defun org-self-insert-command (N)
19879 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19880 If the cursor is in a table looking at whitespace, the whitespace is
19881 overwritten, and the table is not marked as requiring realignment."
19882 (interactive "p")
19883 (org-check-before-invisible-edit 'insert)
19884 (cond
19885 ((and org-use-speed-commands
19886 (let ((kv (this-command-keys-vector)))
19887 (setq org-speed-command
19888 (run-hook-with-args-until-success
19889 'org-speed-command-hook
19890 (make-string 1 (aref kv (1- (length kv))))))))
19891 (cond
19892 ((commandp org-speed-command)
19893 (setq this-command org-speed-command)
19894 (call-interactively org-speed-command))
19895 ((functionp org-speed-command)
19896 (funcall org-speed-command))
19897 ((and org-speed-command (listp org-speed-command))
19898 (eval org-speed-command))
19899 (t (let (org-use-speed-commands)
19900 (call-interactively 'org-self-insert-command)))))
19901 ((and
19902 (org-at-table-p)
19903 (progn
19904 ;; Check if we blank the field, and if that triggers align.
19905 (and (featurep 'org-table) org-table-auto-blank-field
19906 (memq last-command
19907 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19908 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19909 ;; Got extra space, this field does not determine
19910 ;; column width.
19911 (let (org-table-may-need-update) (org-table-blank-field))
19912 ;; No extra space, this field may determine column
19913 ;; width.
19914 (org-table-blank-field)))
19916 (eq N 1)
19917 (looking-at "[^|\n]* \\( \\)|"))
19918 ;; There is room for insertion without re-aligning the table.
19919 (delete-region (match-beginning 1) (match-end 1))
19920 (self-insert-command N))
19922 (setq org-table-may-need-update t)
19923 (self-insert-command N)
19924 (org-fix-tags-on-the-fly)
19925 (when org-self-insert-cluster-for-undo
19926 (if (not (eq last-command 'org-self-insert-command))
19927 (setq org-self-insert-command-undo-counter 1)
19928 (if (>= org-self-insert-command-undo-counter 20)
19929 (setq org-self-insert-command-undo-counter 1)
19930 (and (> org-self-insert-command-undo-counter 0)
19931 buffer-undo-list (listp buffer-undo-list)
19932 (not (cadr buffer-undo-list)) ; remove nil entry
19933 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19934 (setq org-self-insert-command-undo-counter
19935 (1+ org-self-insert-command-undo-counter))))))))
19937 (defun org-check-before-invisible-edit (kind)
19938 "Check is editing if kind KIND would be dangerous with invisible text around.
19939 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19940 ;; First, try to get out of here as quickly as possible, to reduce overhead
19941 (when (and org-catch-invisible-edits
19942 (or (not (boundp 'visible-mode)) (not visible-mode))
19943 (or (get-char-property (point) 'invisible)
19944 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19945 ;; OK, we need to take a closer look
19946 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19947 (invisible-before-point (unless (bobp) (get-char-property
19948 (1- (point)) 'invisible)))
19949 (border-and-ok-direction
19951 ;; Check if we are acting predictably before invisible text
19952 (and invisible-at-point (not invisible-before-point)
19953 (memq kind '(insert delete-backward)))
19954 ;; Check if we are acting predictably after invisible text
19955 ;; This works not well, and I have turned it off. It seems
19956 ;; better to always show and stop after invisible text.
19957 ;; (and (not invisible-at-point) invisible-before-point
19958 ;; (memq kind '(insert delete)))
19960 (when (or (memq invisible-at-point '(outline org-hide-block t))
19961 (memq invisible-before-point '(outline org-hide-block t)))
19962 (when (eq org-catch-invisible-edits 'error)
19963 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19964 (if (and org-custom-properties-overlays
19965 (y-or-n-p "Display invisible properties in this buffer? "))
19966 (org-toggle-custom-properties-visibility)
19967 ;; Make the area visible
19968 (save-excursion
19969 (when invisible-before-point
19970 (goto-char (previous-single-char-property-change
19971 (point) 'invisible)))
19972 (outline-show-subtree))
19973 (cond
19974 ((eq org-catch-invisible-edits 'show)
19975 ;; That's it, we do the edit after showing
19976 (message
19977 "Unfolding invisible region around point before editing")
19978 (sit-for 1))
19979 ((and (eq org-catch-invisible-edits 'smart)
19980 border-and-ok-direction)
19981 (message "Unfolding invisible region around point before editing"))
19983 ;; Don't do the edit, make the user repeat it in full visibility
19984 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19986 (defun org-fix-tags-on-the-fly ()
19987 "Align tags in headline at point.
19988 Unlike to `org-set-tags', it ignores region and sorting."
19989 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19990 (org-at-heading-p))
19991 (let ((org-ignore-region t)
19992 (org-tags-sort-function nil))
19993 (org-set-tags nil t))))
19995 (defun org-delete-backward-char (N)
19996 "Like `delete-backward-char', insert whitespace at field end in tables.
19997 When deleting backwards, in tables this function will insert whitespace in
19998 front of the next \"|\" separator, to keep the table aligned. The table will
19999 still be marked for re-alignment if the field did fill the entire column,
20000 because, in this case the deletion might narrow the column."
20001 (interactive "p")
20002 (save-match-data
20003 (org-check-before-invisible-edit 'delete-backward)
20004 (if (and (org-at-table-p)
20005 (eq N 1)
20006 (string-match "|" (buffer-substring (point-at-bol) (point)))
20007 (looking-at ".*?|"))
20008 (let ((pos (point))
20009 (noalign (looking-at "[^|\n\r]* |"))
20010 (c org-table-may-need-update))
20011 (backward-delete-char N)
20012 (unless overwrite-mode
20013 (skip-chars-forward "^|")
20014 (insert " ")
20015 (goto-char (1- pos)))
20016 ;; noalign: if there were two spaces at the end, this field
20017 ;; does not determine the width of the column.
20018 (when noalign (setq org-table-may-need-update c)))
20019 (backward-delete-char N)
20020 (org-fix-tags-on-the-fly))))
20022 (defun org-delete-char (N)
20023 "Like `delete-char', but insert whitespace at field end in tables.
20024 When deleting characters, in tables this function will insert whitespace in
20025 front of the next \"|\" separator, to keep the table aligned. The table will
20026 still be marked for re-alignment if the field did fill the entire column,
20027 because, in this case the deletion might narrow the column."
20028 (interactive "p")
20029 (save-match-data
20030 (org-check-before-invisible-edit 'delete)
20031 (if (and (org-at-table-p)
20032 (not (bolp))
20033 (not (= (char-after) ?|))
20034 (eq N 1))
20035 (if (looking-at ".*?|")
20036 (let ((pos (point))
20037 (noalign (looking-at "[^|\n\r]* |"))
20038 (c org-table-may-need-update))
20039 (replace-match
20040 (concat (substring (match-string 0) 1 -1) " |") nil t)
20041 (goto-char pos)
20042 ;; noalign: if there were two spaces at the end, this field
20043 ;; does not determine the width of the column.
20044 (when noalign (setq org-table-may-need-update c)))
20045 (delete-char N))
20046 (delete-char N)
20047 (org-fix-tags-on-the-fly))))
20049 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20050 (put 'org-self-insert-command 'delete-selection
20051 (lambda ()
20052 (not (run-hook-with-args-until-success
20053 'self-insert-uses-region-functions))))
20054 (put 'orgtbl-self-insert-command 'delete-selection
20055 (lambda ()
20056 (not (run-hook-with-args-until-success
20057 'self-insert-uses-region-functions))))
20058 (put 'org-delete-char 'delete-selection 'supersede)
20059 (put 'org-delete-backward-char 'delete-selection 'supersede)
20060 (put 'org-yank 'delete-selection 'yank)
20062 ;; Make `flyspell-mode' delay after some commands
20063 (put 'org-self-insert-command 'flyspell-delayed t)
20064 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20065 (put 'org-delete-char 'flyspell-delayed t)
20066 (put 'org-delete-backward-char 'flyspell-delayed t)
20068 ;; Make pabbrev-mode expand after Org mode commands
20069 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20070 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20072 (defun org-remap (map &rest commands)
20073 "In MAP, remap the functions given in COMMANDS.
20074 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20075 (let (new old)
20076 (while commands
20077 (setq old (pop commands) new (pop commands))
20078 (org-defkey map (vector 'remap old) new))))
20080 (defun org-transpose-words ()
20081 "Transpose words for Org.
20082 This uses the `org-mode-transpose-word-syntax-table' syntax
20083 table, which interprets characters in `org-emphasis-alist' as
20084 word constituents."
20085 (interactive)
20086 (with-syntax-table org-mode-transpose-word-syntax-table
20087 (call-interactively 'transpose-words)))
20088 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20090 (when (eq org-enable-table-editor 'optimized)
20091 ;; If the user wants maximum table support, we need to hijack
20092 ;; some standard editing functions
20093 (org-remap org-mode-map
20094 'self-insert-command 'org-self-insert-command
20095 'delete-char 'org-delete-char
20096 'delete-backward-char 'org-delete-backward-char)
20097 (org-defkey org-mode-map "|" 'org-force-self-insert))
20099 (defvar org-ctrl-c-ctrl-c-hook nil
20100 "Hook for functions attaching themselves to `C-c C-c'.
20102 This can be used to add additional functionality to the C-c C-c
20103 key which executes context-dependent commands. This hook is run
20104 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20105 run after the last test.
20107 Each function will be called with no arguments. The function
20108 must check if the context is appropriate for it to act. If yes,
20109 it should do its thing and then return a non-nil value. If the
20110 context is wrong, just do nothing and return nil.")
20112 (defvar org-ctrl-c-ctrl-c-final-hook nil
20113 "Hook for functions attaching themselves to `C-c C-c'.
20115 This can be used to add additional functionality to the C-c C-c
20116 key which executes context-dependent commands. This hook is run
20117 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20118 before the first test.
20120 Each function will be called with no arguments. The function
20121 must check if the context is appropriate for it to act. If yes,
20122 it should do its thing and then return a non-nil value. If the
20123 context is wrong, just do nothing and return nil.")
20125 (defvar org-tab-first-hook nil
20126 "Hook for functions to attach themselves to TAB.
20127 See `org-ctrl-c-ctrl-c-hook' for more information.
20128 This hook runs as the first action when TAB is pressed, even before
20129 `org-cycle' messes around with the `outline-regexp' to cater for
20130 inline tasks and plain list item folding.
20131 If any function in this hook returns t, any other actions that
20132 would have been caused by TAB (such as table field motion or visibility
20133 cycling) will not occur.")
20135 (defvar org-tab-after-check-for-table-hook nil
20136 "Hook for functions to attach themselves to TAB.
20137 See `org-ctrl-c-ctrl-c-hook' for more information.
20138 This hook runs after it has been established that the cursor is not in a
20139 table, but before checking if the cursor is in a headline or if global cycling
20140 should be done.
20141 If any function in this hook returns t, not other actions like visibility
20142 cycling will be done.")
20144 (defvar org-tab-after-check-for-cycling-hook nil
20145 "Hook for functions to attach themselves to TAB.
20146 See `org-ctrl-c-ctrl-c-hook' for more information.
20147 This hook runs after it has been established that not table field motion and
20148 not visibility should be done because of current context. This is probably
20149 the place where a package like yasnippets can hook in.")
20151 (defvar org-tab-before-tab-emulation-hook nil
20152 "Hook for functions to attach themselves to TAB.
20153 See `org-ctrl-c-ctrl-c-hook' for more information.
20154 This hook runs after every other options for TAB have been exhausted, but
20155 before indentation and \t insertion takes place.")
20157 (defvar org-metaleft-hook nil
20158 "Hook for functions attaching themselves to `M-left'.
20159 See `org-ctrl-c-ctrl-c-hook' for more information.")
20160 (defvar org-metaright-hook nil
20161 "Hook for functions attaching themselves to `M-right'.
20162 See `org-ctrl-c-ctrl-c-hook' for more information.")
20163 (defvar org-metaup-hook nil
20164 "Hook for functions attaching themselves to `M-up'.
20165 See `org-ctrl-c-ctrl-c-hook' for more information.")
20166 (defvar org-metadown-hook nil
20167 "Hook for functions attaching themselves to `M-down'.
20168 See `org-ctrl-c-ctrl-c-hook' for more information.")
20169 (defvar org-shiftmetaleft-hook nil
20170 "Hook for functions attaching themselves to `M-S-left'.
20171 See `org-ctrl-c-ctrl-c-hook' for more information.")
20172 (defvar org-shiftmetaright-hook nil
20173 "Hook for functions attaching themselves to `M-S-right'.
20174 See `org-ctrl-c-ctrl-c-hook' for more information.")
20175 (defvar org-shiftmetaup-hook nil
20176 "Hook for functions attaching themselves to `M-S-up'.
20177 See `org-ctrl-c-ctrl-c-hook' for more information.")
20178 (defvar org-shiftmetadown-hook nil
20179 "Hook for functions attaching themselves to `M-S-down'.
20180 See `org-ctrl-c-ctrl-c-hook' for more information.")
20181 (defvar org-metareturn-hook nil
20182 "Hook for functions attaching themselves to `M-RET'.
20183 See `org-ctrl-c-ctrl-c-hook' for more information.")
20184 (defvar org-shiftup-hook nil
20185 "Hook for functions attaching themselves to `S-up'.
20186 See `org-ctrl-c-ctrl-c-hook' for more information.")
20187 (defvar org-shiftup-final-hook nil
20188 "Hook for functions attaching themselves to `S-up'.
20189 This one runs after all other options except shift-select have been excluded.
20190 See `org-ctrl-c-ctrl-c-hook' for more information.")
20191 (defvar org-shiftdown-hook nil
20192 "Hook for functions attaching themselves to `S-down'.
20193 See `org-ctrl-c-ctrl-c-hook' for more information.")
20194 (defvar org-shiftdown-final-hook nil
20195 "Hook for functions attaching themselves to `S-down'.
20196 This one runs after all other options except shift-select have been excluded.
20197 See `org-ctrl-c-ctrl-c-hook' for more information.")
20198 (defvar org-shiftleft-hook nil
20199 "Hook for functions attaching themselves to `S-left'.
20200 See `org-ctrl-c-ctrl-c-hook' for more information.")
20201 (defvar org-shiftleft-final-hook nil
20202 "Hook for functions attaching themselves to `S-left'.
20203 This one runs after all other options except shift-select have been excluded.
20204 See `org-ctrl-c-ctrl-c-hook' for more information.")
20205 (defvar org-shiftright-hook nil
20206 "Hook for functions attaching themselves to `S-right'.
20207 See `org-ctrl-c-ctrl-c-hook' for more information.")
20208 (defvar org-shiftright-final-hook nil
20209 "Hook for functions attaching themselves to `S-right'.
20210 This one runs after all other options except shift-select have been excluded.
20211 See `org-ctrl-c-ctrl-c-hook' for more information.")
20213 (defun org-modifier-cursor-error ()
20214 "Throw an error, a modified cursor command was applied in wrong context."
20215 (user-error "This command is active in special context like tables, headlines or items"))
20217 (defun org-shiftselect-error ()
20218 "Throw an error because Shift-Cursor command was applied in wrong context."
20219 (if (and (boundp 'shift-select-mode) shift-select-mode)
20220 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20221 (user-error "This command works only in special context like headlines or timestamps")))
20223 (defun org-call-for-shift-select (cmd)
20224 (let ((this-command-keys-shift-translated t))
20225 (call-interactively cmd)))
20227 (defun org-shifttab (&optional arg)
20228 "Global visibility cycling or move to previous table field.
20229 Call `org-table-previous-field' within a table.
20230 When ARG is nil, cycle globally through visibility states.
20231 When ARG is a numeric prefix, show contents of this level."
20232 (interactive "P")
20233 (cond
20234 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20235 ((integerp arg)
20236 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20237 (message "Content view to level: %d" arg)
20238 (org-content (prefix-numeric-value arg2))
20239 (org-cycle-show-empty-lines t)
20240 (setq org-cycle-global-status 'overview)))
20241 (t (call-interactively 'org-global-cycle))))
20243 (defun org-shiftmetaleft ()
20244 "Promote subtree or delete table column.
20245 Calls `org-promote-subtree', `org-outdent-item-tree', or
20246 `org-table-delete-column', depending on context. See the
20247 individual commands for more information."
20248 (interactive)
20249 (cond
20250 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20251 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20252 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20253 ((if (not (org-region-active-p)) (org-at-item-p)
20254 (save-excursion (goto-char (region-beginning))
20255 (org-at-item-p)))
20256 (call-interactively 'org-outdent-item-tree))
20257 (t (org-modifier-cursor-error))))
20259 (defun org-shiftmetaright ()
20260 "Demote subtree or insert table column.
20261 Calls `org-demote-subtree', `org-indent-item-tree', or
20262 `org-table-insert-column', depending on context. See the
20263 individual commands for more information."
20264 (interactive)
20265 (cond
20266 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20267 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20268 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20269 ((if (not (org-region-active-p)) (org-at-item-p)
20270 (save-excursion (goto-char (region-beginning))
20271 (org-at-item-p)))
20272 (call-interactively 'org-indent-item-tree))
20273 (t (org-modifier-cursor-error))))
20275 (defun org-shiftmetaup (&optional _arg)
20276 "Drag the line at point up.
20277 In a table, kill the current row.
20278 On a clock timestamp, update the value of the timestamp like `S-<up>'
20279 but also adjust the previous clocked item in the clock history.
20280 Everywhere else, drag the line at point up."
20281 (interactive "P")
20282 (cond
20283 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20284 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20285 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20286 (call-interactively 'org-timestamp-up)))
20287 (t (call-interactively 'org-drag-line-backward))))
20289 (defun org-shiftmetadown (&optional _arg)
20290 "Drag the line at point down.
20291 In a table, insert an empty row at the current line.
20292 On a clock timestamp, update the value of the timestamp like `S-<down>'
20293 but also adjust the previous clocked item in the clock history.
20294 Everywhere else, drag the line at point down."
20295 (interactive "P")
20296 (cond
20297 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20298 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20299 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20300 (call-interactively 'org-timestamp-down)))
20301 (t (call-interactively 'org-drag-line-forward))))
20303 (defsubst org-hidden-tree-error ()
20304 (user-error
20305 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20307 (defun org-metaleft (&optional _arg)
20308 "Promote heading, list item at point or move table column left.
20310 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20311 depending on context. With no specific context, calls the Emacs
20312 default `backward-word'. See the individual commands for more
20313 information.
20315 This function runs the hook `org-metaleft-hook' as a first step,
20316 and returns at first non-nil value."
20317 (interactive "P")
20318 (cond
20319 ((run-hook-with-args-until-success 'org-metaleft-hook))
20320 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20321 ((org-with-limited-levels
20322 (or (org-at-heading-p)
20323 (and (org-region-active-p)
20324 (save-excursion
20325 (goto-char (region-beginning))
20326 (org-at-heading-p)))))
20327 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20328 (call-interactively 'org-do-promote))
20329 ;; At an inline task.
20330 ((org-at-heading-p)
20331 (call-interactively 'org-inlinetask-promote))
20332 ((or (org-at-item-p)
20333 (and (org-region-active-p)
20334 (save-excursion
20335 (goto-char (region-beginning))
20336 (org-at-item-p))))
20337 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20338 (call-interactively 'org-outdent-item))
20339 (t (call-interactively 'backward-word))))
20341 (defun org-metaright (&optional _arg)
20342 "Demote heading, list item at point or move table column right.
20344 In front of a drawer or a block keyword, indent it correctly.
20346 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20347 `org-indent-drawer' or `org-indent-block' depending on context.
20348 With no specific context, calls the Emacs default `forward-word'.
20349 See the individual commands for more information.
20351 This function runs the hook `org-metaright-hook' as a first step,
20352 and returns at first non-nil value."
20353 (interactive "P")
20354 (cond
20355 ((run-hook-with-args-until-success 'org-metaright-hook))
20356 ((org-at-table-p) (call-interactively 'org-table-move-column))
20357 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20358 ((org-at-block-p) (call-interactively 'org-indent-block))
20359 ((org-with-limited-levels
20360 (or (org-at-heading-p)
20361 (and (org-region-active-p)
20362 (save-excursion
20363 (goto-char (region-beginning))
20364 (org-at-heading-p)))))
20365 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20366 (call-interactively 'org-do-demote))
20367 ;; At an inline task.
20368 ((org-at-heading-p)
20369 (call-interactively 'org-inlinetask-demote))
20370 ((or (org-at-item-p)
20371 (and (org-region-active-p)
20372 (save-excursion
20373 (goto-char (region-beginning))
20374 (org-at-item-p))))
20375 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20376 (call-interactively 'org-indent-item))
20377 (t (call-interactively 'forward-word))))
20379 (defun org-check-for-hidden (what)
20380 "Check if there are hidden headlines/items in the current visual line.
20381 WHAT can be either `headlines' or `items'. If the current line is
20382 an outline or item heading and it has a folded subtree below it,
20383 this function returns t, nil otherwise."
20384 (let ((re (cond
20385 ((eq what 'headlines) org-outline-regexp-bol)
20386 ((eq what 'items) (org-item-beginning-re))
20387 (t (error "This should not happen"))))
20388 beg end)
20389 (save-excursion
20390 (catch 'exit
20391 (unless (org-region-active-p)
20392 (setq beg (point-at-bol))
20393 (beginning-of-line 2)
20394 (while (and (not (eobp)) ;; this is like `next-line'
20395 (get-char-property (1- (point)) 'invisible))
20396 (beginning-of-line 2))
20397 (setq end (point))
20398 (goto-char beg)
20399 (goto-char (point-at-eol))
20400 (setq end (max end (point)))
20401 (while (re-search-forward re end t)
20402 (when (get-char-property (match-beginning 0) 'invisible)
20403 (throw 'exit t))))
20404 nil))))
20406 (defun org-metaup (&optional _arg)
20407 "Move subtree up or move table row up.
20408 Calls `org-move-subtree-up' or `org-table-move-row' or
20409 `org-move-item-up', depending on context. See the individual commands
20410 for more information."
20411 (interactive "P")
20412 (cond
20413 ((run-hook-with-args-until-success 'org-metaup-hook))
20414 ((org-region-active-p)
20415 (let* ((a (min (region-beginning) (region-end)))
20416 (b (1- (max (region-beginning) (region-end))))
20417 (c (save-excursion (goto-char a)
20418 (move-beginning-of-line 0)))
20419 (d (save-excursion (goto-char a)
20420 (move-end-of-line 0) (point))))
20421 (transpose-regions a b c d)
20422 (goto-char c)))
20423 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20424 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20425 ((org-at-item-p) (call-interactively 'org-move-item-up))
20426 (t (org-drag-element-backward))))
20428 (defun org-metadown (&optional _arg)
20429 "Move subtree down or move table row down.
20430 Calls `org-move-subtree-down' or `org-table-move-row' or
20431 `org-move-item-down', depending on context. See the individual
20432 commands for more information."
20433 (interactive "P")
20434 (cond
20435 ((run-hook-with-args-until-success 'org-metadown-hook))
20436 ((org-region-active-p)
20437 (let* ((a (min (region-beginning) (region-end)))
20438 (b (max (region-beginning) (region-end)))
20439 (c (save-excursion (goto-char b)
20440 (move-beginning-of-line 1)))
20441 (d (save-excursion (goto-char b)
20442 (move-end-of-line 1) (1+ (point)))))
20443 (transpose-regions a b c d)
20444 (goto-char d)))
20445 ((org-at-table-p) (call-interactively 'org-table-move-row))
20446 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20447 ((org-at-item-p) (call-interactively 'org-move-item-down))
20448 (t (org-drag-element-forward))))
20450 (defun org-shiftup (&optional arg)
20451 "Increase item in timestamp or increase priority of current headline.
20452 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20453 depending on context. See the individual commands for more information."
20454 (interactive "P")
20455 (cond
20456 ((run-hook-with-args-until-success 'org-shiftup-hook))
20457 ((and org-support-shift-select (org-region-active-p))
20458 (org-call-for-shift-select 'previous-line))
20459 ((org-at-timestamp-p t)
20460 (call-interactively (if org-edit-timestamp-down-means-later
20461 'org-timestamp-down 'org-timestamp-up)))
20462 ((and (not (eq org-support-shift-select 'always))
20463 org-enable-priority-commands
20464 (org-at-heading-p))
20465 (call-interactively 'org-priority-up))
20466 ((and (not org-support-shift-select) (org-at-item-p))
20467 (call-interactively 'org-previous-item))
20468 ((org-clocktable-try-shift 'up arg))
20469 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20470 (org-support-shift-select
20471 (org-call-for-shift-select 'previous-line))
20472 (t (org-shiftselect-error))))
20474 (defun org-shiftdown (&optional arg)
20475 "Decrease item in timestamp or decrease priority of current headline.
20476 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20477 depending on context. See the individual commands for more information."
20478 (interactive "P")
20479 (cond
20480 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20481 ((and org-support-shift-select (org-region-active-p))
20482 (org-call-for-shift-select 'next-line))
20483 ((org-at-timestamp-p t)
20484 (call-interactively (if org-edit-timestamp-down-means-later
20485 'org-timestamp-up 'org-timestamp-down)))
20486 ((and (not (eq org-support-shift-select 'always))
20487 org-enable-priority-commands
20488 (org-at-heading-p))
20489 (call-interactively 'org-priority-down))
20490 ((and (not org-support-shift-select) (org-at-item-p))
20491 (call-interactively 'org-next-item))
20492 ((org-clocktable-try-shift 'down arg))
20493 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20494 (org-support-shift-select
20495 (org-call-for-shift-select 'next-line))
20496 (t (org-shiftselect-error))))
20498 (defun org-shiftright (&optional arg)
20499 "Cycle the thing at point or in the current line, depending on context.
20500 Depending on context, this does one of the following:
20502 - switch a timestamp at point one day into the future
20503 - on a headline, switch to the next TODO keyword.
20504 - on an item, switch entire list to the next bullet type
20505 - on a property line, switch to the next allowed value
20506 - on a clocktable definition line, move time block into the future"
20507 (interactive "P")
20508 (cond
20509 ((run-hook-with-args-until-success 'org-shiftright-hook))
20510 ((and org-support-shift-select (org-region-active-p))
20511 (org-call-for-shift-select 'forward-char))
20512 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20513 ((and (not (eq org-support-shift-select 'always))
20514 (org-at-heading-p))
20515 (let ((org-inhibit-logging
20516 (not org-treat-S-cursor-todo-selection-as-state-change))
20517 (org-inhibit-blocking
20518 (not org-treat-S-cursor-todo-selection-as-state-change)))
20519 (org-call-with-arg 'org-todo 'right)))
20520 ((or (and org-support-shift-select
20521 (not (eq org-support-shift-select 'always))
20522 (org-at-item-bullet-p))
20523 (and (not org-support-shift-select) (org-at-item-p)))
20524 (org-call-with-arg 'org-cycle-list-bullet nil))
20525 ((and (not (eq org-support-shift-select 'always))
20526 (org-at-property-p))
20527 (call-interactively 'org-property-next-allowed-value))
20528 ((org-clocktable-try-shift 'right arg))
20529 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20530 (org-support-shift-select
20531 (org-call-for-shift-select 'forward-char))
20532 (t (org-shiftselect-error))))
20534 (defun org-shiftleft (&optional arg)
20535 "Cycle the thing at point or in the current line, depending on context.
20536 Depending on context, this does one of the following:
20538 - switch a timestamp at point one day into the past
20539 - on a headline, switch to the previous TODO keyword.
20540 - on an item, switch entire list to the previous bullet type
20541 - on a property line, switch to the previous allowed value
20542 - on a clocktable definition line, move time block into the past"
20543 (interactive "P")
20544 (cond
20545 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20546 ((and org-support-shift-select (org-region-active-p))
20547 (org-call-for-shift-select 'backward-char))
20548 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20549 ((and (not (eq org-support-shift-select 'always))
20550 (org-at-heading-p))
20551 (let ((org-inhibit-logging
20552 (not org-treat-S-cursor-todo-selection-as-state-change))
20553 (org-inhibit-blocking
20554 (not org-treat-S-cursor-todo-selection-as-state-change)))
20555 (org-call-with-arg 'org-todo 'left)))
20556 ((or (and org-support-shift-select
20557 (not (eq org-support-shift-select 'always))
20558 (org-at-item-bullet-p))
20559 (and (not org-support-shift-select) (org-at-item-p)))
20560 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20561 ((and (not (eq org-support-shift-select 'always))
20562 (org-at-property-p))
20563 (call-interactively 'org-property-previous-allowed-value))
20564 ((org-clocktable-try-shift 'left arg))
20565 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20566 (org-support-shift-select
20567 (org-call-for-shift-select 'backward-char))
20568 (t (org-shiftselect-error))))
20570 (defun org-shiftcontrolright ()
20571 "Switch to next TODO set."
20572 (interactive)
20573 (cond
20574 ((and org-support-shift-select (org-region-active-p))
20575 (org-call-for-shift-select 'forward-word))
20576 ((and (not (eq org-support-shift-select 'always))
20577 (org-at-heading-p))
20578 (org-call-with-arg 'org-todo 'nextset))
20579 (org-support-shift-select
20580 (org-call-for-shift-select 'forward-word))
20581 (t (org-shiftselect-error))))
20583 (defun org-shiftcontrolleft ()
20584 "Switch to previous TODO set."
20585 (interactive)
20586 (cond
20587 ((and org-support-shift-select (org-region-active-p))
20588 (org-call-for-shift-select 'backward-word))
20589 ((and (not (eq org-support-shift-select 'always))
20590 (org-at-heading-p))
20591 (org-call-with-arg 'org-todo 'previousset))
20592 (org-support-shift-select
20593 (org-call-for-shift-select 'backward-word))
20594 (t (org-shiftselect-error))))
20596 (defun org-shiftcontrolup (&optional n)
20597 "Change timestamps synchronously up in CLOCK log lines.
20598 Optional argument N tells to change by that many units."
20599 (interactive "P")
20600 (if (and (org-at-clock-log-p) (org-in-regexp org-ts-regexp-inactive))
20601 (let (org-support-shift-select)
20602 (org-clock-timestamps-up n))
20603 (user-error "Not at a clock log")))
20605 (defun org-shiftcontroldown (&optional n)
20606 "Change timestamps synchronously down in CLOCK log lines.
20607 Optional argument N tells to change by that many units."
20608 (interactive "P")
20609 (if (and (org-at-clock-log-p) (org-in-regexp org-ts-regexp-inactive))
20610 (let (org-support-shift-select)
20611 (org-clock-timestamps-down n))
20612 (user-error "Not at a clock log")))
20614 (defun org-increase-number-at-point (&optional inc)
20615 "Increment the number at point.
20616 With an optional prefix numeric argument INC, increment using
20617 this numeric value."
20618 (interactive "p")
20619 (if (not (number-at-point))
20620 (user-error "Not on a number")
20621 (unless inc (setq inc 1))
20622 (let ((pos (point))
20623 (beg (skip-chars-backward "-+^/*0-9eE."))
20624 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20625 (setq nap (buffer-substring-no-properties
20626 (+ pos beg) (+ pos beg end)))
20627 (delete-region (+ pos beg) (+ pos beg end))
20628 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20629 (when (org-at-table-p)
20630 (org-table-align)
20631 (org-table-end-of-field 1))))
20633 (defun org-decrease-number-at-point (&optional inc)
20634 "Decrement the number at point.
20635 With an optional prefix numeric argument INC, decrement using
20636 this numeric value."
20637 (interactive "p")
20638 (org-increase-number-at-point (- (or inc 1))))
20640 (defun org-ctrl-c-ret ()
20641 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20642 (interactive)
20643 (cond
20644 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20645 (t (call-interactively 'org-insert-heading))))
20647 (defun org-find-visible ()
20648 (let ((s (point)))
20649 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20650 (get-char-property s 'invisible)))
20652 (defun org-find-invisible ()
20653 (let ((s (point)))
20654 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20655 (not (get-char-property s 'invisible))))
20658 (defun org-copy-visible (beg end)
20659 "Copy the visible parts of the region."
20660 (interactive "r")
20661 (let (snippets s)
20662 (save-excursion
20663 (save-restriction
20664 (narrow-to-region beg end)
20665 (setq s (goto-char (point-min)))
20666 (while (not (= (point) (point-max)))
20667 (goto-char (org-find-invisible))
20668 (push (buffer-substring s (point)) snippets)
20669 (setq s (goto-char (org-find-visible))))))
20670 (kill-new (apply 'concat (nreverse snippets)))))
20672 (defun org-copy-special ()
20673 "Copy region in table or copy current subtree.
20674 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20675 context. See the individual commands for more information."
20676 (interactive)
20677 (call-interactively
20678 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20680 (defun org-cut-special ()
20681 "Cut region in table or cut current subtree.
20682 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20683 context. See the individual commands for more information."
20684 (interactive)
20685 (call-interactively
20686 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20688 (defun org-paste-special (arg)
20689 "Paste rectangular region into table, or past subtree relative to level.
20690 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20691 See the individual commands for more information."
20692 (interactive "P")
20693 (if (org-at-table-p)
20694 (org-table-paste-rectangle)
20695 (org-paste-subtree arg)))
20697 (defun org-edit-special (&optional arg)
20698 "Call a special editor for the element at point.
20699 When at a table, call the formula editor with `org-table-edit-formulas'.
20700 When in a source code block, call `org-edit-src-code'.
20701 When in a fixed-width region, call `org-edit-fixed-width-region'.
20702 When in an export block, call `org-edit-export-block'.
20703 When in a LaTeX environment, call `org-edit-latex-environment'.
20704 When at an #+INCLUDE keyword, visit the included file.
20705 When at a footnote reference, call `org-edit-footnote-reference'
20706 On a link, call `ffap' to visit the link at point.
20707 Otherwise, return a user error."
20708 (interactive "P")
20709 (let ((element (org-element-at-point)))
20710 (barf-if-buffer-read-only)
20711 (pcase (org-element-type element)
20712 (`src-block
20713 (if (not arg) (org-edit-src-code)
20714 (let* ((info (org-babel-get-src-block-info))
20715 (lang (nth 0 info))
20716 (params (nth 2 info))
20717 (session (cdr (assq :session params))))
20718 (if (not session) (org-edit-src-code)
20719 ;; At a src-block with a session and function called with
20720 ;; an ARG: switch to the buffer related to the inferior
20721 ;; process.
20722 (switch-to-buffer
20723 (funcall (intern (concat "org-babel-prep-session:" lang))
20724 session params))))))
20725 (`keyword
20726 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20727 (org-open-link-from-string
20728 (format "[[%s]]"
20729 (expand-file-name
20730 (let ((value (org-element-property :value element)))
20731 (cond ((not (org-string-nw-p value))
20732 (user-error "No file to edit"))
20733 ((string-match "\\`\"\\(.*?\\)\"" value)
20734 (match-string 1 value))
20735 ((string-match "\\`[^ \t\"]\\S-*" value)
20736 (match-string 0 value))
20737 (t (user-error "No valid file specified")))))))
20738 (user-error "No special environment to edit here")))
20739 (`table
20740 (if (eq (org-element-property :type element) 'table.el)
20741 (org-edit-table.el)
20742 (call-interactively 'org-table-edit-formulas)))
20743 ;; Only Org tables contain `table-row' type elements.
20744 (`table-row (call-interactively 'org-table-edit-formulas))
20745 (`example-block (org-edit-src-code))
20746 (`export-block (org-edit-export-block))
20747 (`fixed-width (org-edit-fixed-width-region))
20748 (`latex-environment (org-edit-latex-environment))
20750 ;; No notable element at point. Though, we may be at a link or
20751 ;; a footnote reference, which are objects. Thus, scan deeper.
20752 (let ((context (org-element-context element)))
20753 (pcase (org-element-type context)
20754 (`footnote-reference (org-edit-footnote-reference))
20755 (`inline-src-block (org-edit-inline-src-code))
20756 (`link (call-interactively #'ffap))
20757 (_ (user-error "No special environment to edit here"))))))))
20759 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20760 (defun org-ctrl-c-ctrl-c (&optional arg)
20761 "Set tags in headline, or update according to changed information at point.
20763 This command does many different things, depending on context:
20765 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20766 this is what we do.
20768 - If the cursor is on a statistics cookie, update it.
20770 - If the cursor is in a headline, prompt for tags and insert them
20771 into the current line, aligned to `org-tags-column'. When called
20772 with prefix arg, realign all tags in the current buffer.
20774 - If the cursor is in one of the special #+KEYWORD lines, this
20775 triggers scanning the buffer for these lines and updating the
20776 information.
20778 - If the cursor is inside a table, realign the table. This command
20779 works even if the automatic table editor has been turned off.
20781 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20782 the entire table.
20784 - If the cursor is at a footnote reference or definition, jump to
20785 the corresponding definition or references, respectively.
20787 - If the cursor is a the beginning of a dynamic block, update it.
20789 - If the current buffer is a capture buffer, close note and file it.
20791 - If the cursor is on a <<<target>>>, update radio targets and
20792 corresponding links in this buffer.
20794 - If the cursor is on a numbered item in a plain list, renumber the
20795 ordered list.
20797 - If the cursor is on a checkbox, toggle it.
20799 - If the cursor is on a code block, evaluate it. The variable
20800 `org-confirm-babel-evaluate' can be used to control prompting
20801 before code block evaluation, by default every code block
20802 evaluation requires confirmation. Code block evaluation can be
20803 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20804 (interactive "P")
20805 (cond
20806 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20807 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20808 (org-remove-occur-highlights)
20809 (message "Temporary highlights/overlays removed from current buffer"))
20810 ((and (local-variable-p 'org-finish-function)
20811 (fboundp org-finish-function))
20812 (funcall org-finish-function))
20813 ((org-babel-hash-at-point))
20814 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20816 (let* ((context
20817 (org-element-lineage
20818 (org-element-context)
20819 ;; Limit to supported contexts.
20820 '(babel-call clock dynamic-block footnote-definition
20821 footnote-reference inline-babel-call inline-src-block
20822 inlinetask item keyword node-property paragraph
20823 plain-list property-drawer radio-target src-block
20824 statistics-cookie table table-cell table-row
20825 timestamp)
20827 (type (org-element-type context)))
20828 ;; For convenience: at the first line of a paragraph on the same
20829 ;; line as an item, apply function on that item instead.
20830 (when (eq type 'paragraph)
20831 (let ((parent (org-element-property :parent context)))
20832 (when (and (eq (org-element-type parent) 'item)
20833 (= (line-beginning-position)
20834 (org-element-property :begin parent)))
20835 (setq context parent)
20836 (setq type 'item))))
20837 ;; Act according to type of element or object at point.
20839 ;; Do nothing on a blank line, except if it is contained in
20840 ;; a src block. Hence, we first check if point is in such
20841 ;; a block and then if it is at a blank line.
20842 (pcase type
20843 ((or `inline-src-block `src-block)
20844 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20845 (org-babel-eval-wipe-error-buffer)
20846 (org-babel-execute-src-block
20847 current-prefix-arg (org-babel-get-src-block-info nil context))))
20848 ((guard (org-match-line "[ \t]*$"))
20849 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20850 (user-error
20851 (substitute-command-keys
20852 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20853 ((or `babel-call `inline-babel-call)
20854 (let ((info (org-babel-lob-get-info context)))
20855 (when info (org-babel-execute-src-block nil info))))
20856 (`clock (org-clock-update-time-maybe))
20857 (`dynamic-block
20858 (save-excursion
20859 (goto-char (org-element-property :post-affiliated context))
20860 (org-update-dblock)))
20861 (`footnote-definition
20862 (goto-char (org-element-property :post-affiliated context))
20863 (call-interactively 'org-footnote-action))
20864 (`footnote-reference (call-interactively #'org-footnote-action))
20865 ((or `headline `inlinetask)
20866 (save-excursion (goto-char (org-element-property :begin context))
20867 (call-interactively #'org-set-tags)))
20868 (`item
20869 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20870 ;; unconditionally, whereas `C-u' will toggle its presence.
20871 ;; Without a universal argument, if the item has a checkbox,
20872 ;; toggle it. Otherwise repair the list.
20873 (let* ((box (org-element-property :checkbox context))
20874 (struct (org-element-property :structure context))
20875 (old-struct (copy-tree struct))
20876 (parents (org-list-parents-alist struct))
20877 (prevs (org-list-prevs-alist struct))
20878 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20879 (org-list-set-checkbox
20880 (org-element-property :begin context) struct
20881 (cond ((equal arg '(16)) "[-]")
20882 ((and (not box) (equal arg '(4))) "[ ]")
20883 ((or (not box) (equal arg '(4))) nil)
20884 ((eq box 'on) "[ ]")
20885 (t "[X]")))
20886 ;; Mimic `org-list-write-struct' but with grabbing a return
20887 ;; value from `org-list-struct-fix-box'.
20888 (org-list-struct-fix-ind struct parents 2)
20889 (org-list-struct-fix-item-end struct)
20890 (org-list-struct-fix-bul struct prevs)
20891 (org-list-struct-fix-ind struct parents)
20892 (let ((block-item
20893 (org-list-struct-fix-box struct parents prevs orderedp)))
20894 (if (and box (equal struct old-struct))
20895 (if (equal arg '(16))
20896 (message "Checkboxes already reset")
20897 (user-error "Cannot toggle this checkbox: %s"
20898 (if (eq box 'on)
20899 "all subitems checked"
20900 "unchecked subitems")))
20901 (org-list-struct-apply-struct struct old-struct)
20902 (org-update-checkbox-count-maybe))
20903 (when block-item
20904 (message "Checkboxes were removed due to empty box at line %d"
20905 (org-current-line block-item))))))
20906 (`keyword
20907 (let ((org-inhibit-startup-visibility-stuff t)
20908 (org-startup-align-all-tables nil))
20909 (when (boundp 'org-table-coordinate-overlays)
20910 (mapc #'delete-overlay org-table-coordinate-overlays)
20911 (setq org-table-coordinate-overlays nil))
20912 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20913 (message "Local setup has been refreshed"))
20914 (`plain-list
20915 ;; At a plain list, with a double C-u argument, set
20916 ;; checkboxes of each item to "[-]", whereas a single one
20917 ;; will toggle their presence according to the state of the
20918 ;; first item in the list. Without an argument, repair the
20919 ;; list.
20920 (let* ((begin (org-element-property :contents-begin context))
20921 (beginm (move-marker (make-marker) begin))
20922 (struct (org-element-property :structure context))
20923 (old-struct (copy-tree struct))
20924 (first-box (save-excursion
20925 (goto-char begin)
20926 (looking-at org-list-full-item-re)
20927 (match-string-no-properties 3)))
20928 (new-box (cond ((equal arg '(16)) "[-]")
20929 ((equal arg '(4)) (unless first-box "[ ]"))
20930 ((equal first-box "[X]") "[ ]")
20931 (t "[X]"))))
20932 (cond
20933 (arg
20934 (dolist (pos
20935 (org-list-get-all-items
20936 begin struct (org-list-prevs-alist struct)))
20937 (org-list-set-checkbox pos struct new-box)))
20938 ((and first-box (eq (point) begin))
20939 ;; For convenience, when point is at bol on the first
20940 ;; item of the list and no argument is provided, simply
20941 ;; toggle checkbox of that item, if any.
20942 (org-list-set-checkbox begin struct new-box)))
20943 (org-list-write-struct
20944 struct (org-list-parents-alist struct) old-struct)
20945 (org-update-checkbox-count-maybe)
20946 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20947 ((or `property-drawer `node-property)
20948 (call-interactively #'org-property-action))
20949 (`radio-target
20950 (call-interactively #'org-update-radio-target-regexp))
20951 (`statistics-cookie
20952 (call-interactively #'org-update-statistics-cookies))
20953 ((or `table `table-cell `table-row)
20954 ;; At a table, recalculate every field and align it. Also
20955 ;; send the table if necessary. If the table has
20956 ;; a `table.el' type, just give up. At a table row or cell,
20957 ;; maybe recalculate line but always align table.
20958 (if (eq (org-element-property :type context) 'table.el)
20959 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20960 Use `\\[org-edit-special]' to edit table.el tables"))
20961 (let ((org-enable-table-editor t))
20962 (if (or (eq type 'table)
20963 ;; Check if point is at a TBLFM line.
20964 (and (eq type 'table-row)
20965 (= (point) (org-element-property :end context))))
20966 (save-excursion
20967 (if (org-at-TBLFM-p)
20968 (progn (require 'org-table)
20969 (org-table-calc-current-TBLFM))
20970 (goto-char (org-element-property :contents-begin context))
20971 (org-call-with-arg 'org-table-recalculate (or arg t))
20972 (orgtbl-send-table 'maybe)))
20973 (org-table-maybe-eval-formula)
20974 (cond (arg (call-interactively #'org-table-recalculate))
20975 ((org-table-maybe-recalculate-line))
20976 (t (org-table-align)))))))
20977 (`timestamp (org-timestamp-change 0 'day))
20978 ((and `nil (guard (org-at-heading-p)))
20979 ;; When point is on an unsupported object type, we can miss
20980 ;; the fact that it also is at a heading. Handle it here.
20981 (call-interactively #'org-set-tags))
20982 ((guard
20983 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20985 (user-error
20986 (substitute-command-keys
20987 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20989 (defun org-mode-restart ()
20990 (interactive)
20991 (let ((indent-status (bound-and-true-p org-indent-mode)))
20992 (funcall major-mode)
20993 (hack-local-variables)
20994 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20995 (org-indent-mode -1)))
20996 (message "%s restarted" major-mode))
20998 (defun org-kill-note-or-show-branches ()
20999 "Abort storing current note, or call `outline-show-branches'."
21000 (interactive)
21001 (if (not org-finish-function)
21002 (progn
21003 (outline-hide-subtree)
21004 (call-interactively 'outline-show-branches))
21005 (let ((org-note-abort t))
21006 (funcall org-finish-function))))
21008 (defun org-delete-indentation (&optional arg)
21009 "Join current line to previous and fix whitespace at join.
21011 If previous line is a headline add to headline title. Otherwise
21012 the function calls `delete-indentation'.
21014 With a non-nil optional argument, join it to the following one."
21015 (interactive "*P")
21016 (if (save-excursion
21017 (beginning-of-line (if arg 1 0))
21018 (let ((case-fold-search nil))
21019 (looking-at org-complex-heading-regexp)))
21020 ;; At headline.
21021 (let ((tags-column (when (match-beginning 5)
21022 (save-excursion (goto-char (match-beginning 5))
21023 (current-column))))
21024 (string (concat " " (progn (when arg (forward-line 1))
21025 (org-trim (delete-and-extract-region
21026 (line-beginning-position)
21027 (line-end-position)))))))
21028 (unless (bobp) (delete-region (point) (1- (point))))
21029 (goto-char (or (match-end 4)
21030 (match-beginning 5)
21031 (match-end 0)))
21032 (skip-chars-backward " \t")
21033 (save-excursion (insert string))
21034 ;; Adjust alignment of tags.
21035 (cond
21036 ((not tags-column)) ;no tags
21037 (org-auto-align-tags (org-set-tags nil t))
21038 (t (org--align-tags-here tags-column)))) ;preserve tags column
21039 (delete-indentation arg)))
21041 (defun org-open-line (n)
21042 "Insert a new row in tables, call `open-line' elsewhere.
21043 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21044 As a special case, when a document starts with a table, allow to
21045 call `open-line' on the very first character."
21046 (interactive "*p")
21047 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21048 (org-table-insert-row)
21049 (open-line n)))
21051 (defun org-return (&optional indent)
21052 "Goto next table row or insert a newline.
21054 Calls `org-table-next-row' or `newline', depending on context.
21056 When optional INDENT argument is non-nil, call
21057 `newline-and-indent' instead of `newline'.
21059 When `org-return-follows-link' is non-nil and point is on
21060 a timestamp or a link, call `org-open-at-point'. However, it
21061 will not happen if point is in a table or on a \"dead\"
21062 object (e.g., within a comment). In these case, you need to use
21063 `org-open-at-point' directly."
21064 (interactive)
21065 (let ((context (if org-return-follows-link (org-element-context)
21066 (org-element-at-point))))
21067 (cond
21068 ;; In a table, call `org-table-next-row'.
21069 ((or (and (eq (org-element-type context) 'table)
21070 (>= (point) (org-element-property :contents-begin context))
21071 (< (point) (org-element-property :contents-end context)))
21072 (org-element-lineage context '(table-row table-cell) t))
21073 (org-table-justify-field-maybe)
21074 (call-interactively #'org-table-next-row))
21075 ;; On a link or a timestamp, call `org-open-at-point' if
21076 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21077 ;; locations, e.g., in a comment, as `org-open-at-point'.
21078 ((and org-return-follows-link
21079 (or (org-in-regexp org-ts-regexp-both nil t)
21080 (org-in-regexp org-tsr-regexp-both nil t)
21081 (org-in-regexp org-any-link-re nil t)))
21082 (call-interactively #'org-open-at-point))
21083 ;; Insert newline in heading, but preserve tags.
21084 ((and (not (bolp))
21085 (save-excursion (beginning-of-line)
21086 (let ((case-fold-search nil))
21087 (looking-at org-complex-heading-regexp))))
21088 ;; At headline. Split line. However, if point is on keyword,
21089 ;; priority cookie or tags, do not break any of them: add
21090 ;; a newline after the headline instead.
21091 (let ((tags-column (and (match-beginning 5)
21092 (save-excursion (goto-char (match-beginning 5))
21093 (current-column))))
21094 (string
21095 (when (and (match-end 4) (org-point-in-group (point) 4))
21096 (delete-and-extract-region (point) (match-end 4)))))
21097 ;; Adjust tag alignment.
21098 (cond
21099 ((not (and tags-column string)))
21100 (org-auto-align-tags (org-set-tags nil t))
21101 (t (org--align-tags-here tags-column))) ;preserve tags column
21102 (end-of-line)
21103 (org-show-entry)
21104 (if indent (newline-and-indent) (newline))
21105 (when string (save-excursion (insert (org-trim string))))))
21106 ;; In a list, make sure indenting keeps trailing text within.
21107 ((and indent
21108 (not (eolp))
21109 (org-element-lineage context '(item)))
21110 (let ((trailing-data
21111 (delete-and-extract-region (point) (line-end-position))))
21112 (newline-and-indent)
21113 (save-excursion (insert trailing-data))))
21114 (t (if indent (newline-and-indent) (newline))))))
21116 (defun org-return-indent ()
21117 "Goto next table row or insert a newline and indent.
21118 Calls `org-table-next-row' or `newline-and-indent', depending on
21119 context. See the individual commands for more information."
21120 (interactive)
21121 (org-return t))
21123 (defun org-ctrl-c-star ()
21124 "Compute table, or change heading status of lines.
21125 Calls `org-table-recalculate' or `org-toggle-heading',
21126 depending on context."
21127 (interactive)
21128 (cond
21129 ((org-at-table-p)
21130 (call-interactively 'org-table-recalculate))
21132 ;; Convert all lines in region to list items
21133 (call-interactively 'org-toggle-heading))))
21135 (defun org-ctrl-c-minus ()
21136 "Insert separator line in table or modify bullet status of line.
21137 Also turns a plain line or a region of lines into list items.
21138 Calls `org-table-insert-hline', `org-toggle-item', or
21139 `org-cycle-list-bullet', depending on context."
21140 (interactive)
21141 (cond
21142 ((org-at-table-p)
21143 (call-interactively 'org-table-insert-hline))
21144 ((org-region-active-p)
21145 (call-interactively 'org-toggle-item))
21146 ((org-in-item-p)
21147 (call-interactively 'org-cycle-list-bullet))
21149 (call-interactively 'org-toggle-item))))
21151 (defun org-toggle-heading (&optional nstars)
21152 "Convert headings to normal text, or items or text to headings.
21153 If there is no active region, only convert the current line.
21155 With a `\\[universal-argument]' prefix, convert the whole list at
21156 point into heading.
21158 In a region:
21160 - If the first non blank line is a headline, remove the stars
21161 from all headlines in the region.
21163 - If it is a normal line, turn each and every normal line (i.e.,
21164 not an heading or an item) in the region into headings. If you
21165 want to convert only the first line of this region, use one
21166 universal prefix argument.
21168 - If it is a plain list item, turn all plain list items into headings.
21170 When converting a line into a heading, the number of stars is chosen
21171 such that the lines become children of the current entry. However,
21172 when a numeric prefix argument is given, its value determines the
21173 number of stars to add."
21174 (interactive "P")
21175 (let ((skip-blanks
21176 (function
21177 ;; Return beginning of first non-blank line, starting from
21178 ;; line at POS.
21179 (lambda (pos)
21180 (save-excursion
21181 (goto-char pos)
21182 (while (org-at-comment-p) (forward-line))
21183 (skip-chars-forward " \r\t\n")
21184 (point-at-bol)))))
21185 beg end toggled)
21186 ;; Determine boundaries of changes. If a universal prefix has
21187 ;; been given, put the list in a region. If region ends at a bol,
21188 ;; do not consider the last line to be in the region.
21190 (when (and current-prefix-arg (org-at-item-p))
21191 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21192 (org-mark-element))
21194 (if (org-region-active-p)
21195 (setq beg (funcall skip-blanks (region-beginning))
21196 end (copy-marker (save-excursion
21197 (goto-char (region-end))
21198 (if (bolp) (point) (point-at-eol)))))
21199 (setq beg (funcall skip-blanks (point-at-bol))
21200 end (copy-marker (point-at-eol))))
21201 ;; Ensure inline tasks don't count as headings.
21202 (org-with-limited-levels
21203 (save-excursion
21204 (goto-char beg)
21205 (cond
21206 ;; Case 1. Started at an heading: de-star headings.
21207 ((org-at-heading-p)
21208 (while (< (point) end)
21209 (when (org-at-heading-p t)
21210 (looking-at org-outline-regexp) (replace-match "")
21211 (setq toggled t))
21212 (forward-line)))
21213 ;; Case 2. Started at an item: change items into headlines.
21214 ;; One star will be added by `org-list-to-subtree'.
21215 ((org-at-item-p)
21216 (while (< (point) end)
21217 (when (org-at-item-p)
21218 ;; Pay attention to cases when region ends before list.
21219 (let* ((struct (org-list-struct))
21220 (list-end
21221 (min (org-list-get-bottom-point struct) (1+ end))))
21222 (save-restriction
21223 (narrow-to-region (point) list-end)
21224 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21225 (setq toggled t))
21226 (forward-line)))
21227 ;; Case 3. Started at normal text: make every line an heading,
21228 ;; skipping headlines and items.
21229 (t (let* ((stars
21230 (make-string
21231 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21232 (add-stars
21233 (cond (nstars "") ; stars from prefix only
21234 ((equal stars "") "*") ; before first heading
21235 (org-odd-levels-only "**") ; inside heading, odd
21236 (t "*"))) ; inside heading, oddeven
21237 (rpl (concat stars add-stars " "))
21238 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21239 (while (< (point) (if (equal nstars '(4)) lend end))
21240 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21241 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21242 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21243 (forward-line)))))))
21244 (unless toggled (message "Cannot toggle heading from here"))))
21246 (defun org-meta-return (&optional arg)
21247 "Insert a new heading or wrap a region in a table.
21248 Calls `org-insert-heading', `org-insert-item' or
21249 `org-table-wrap-region', depending on context. When called with
21250 an argument, unconditionally call `org-insert-heading'."
21251 (interactive "P")
21252 (org-check-before-invisible-edit 'insert)
21253 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21254 (call-interactively (cond (arg #'org-insert-heading)
21255 ((org-at-table-p) #'org-table-wrap-region)
21256 ((org-in-item-p) #'org-insert-item)
21257 (t #'org-insert-heading)))))
21259 ;;; Menu entries
21261 (defsubst org-in-subtree-not-table-p ()
21262 "Are we in a subtree and not in a table?"
21263 (and (not (org-before-first-heading-p))
21264 (not (org-at-table-p))))
21266 ;; Define the Org mode menus
21267 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21268 '("Tbl"
21269 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21270 ["Next Field" org-cycle (org-at-table-p)]
21271 ["Previous Field" org-shifttab (org-at-table-p)]
21272 ["Next Row" org-return (org-at-table-p)]
21273 "--"
21274 ["Blank Field" org-table-blank-field (org-at-table-p)]
21275 ["Edit Field" org-table-edit-field (org-at-table-p)]
21276 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21277 "--"
21278 ("Column"
21279 ["Move Column Left" org-metaleft (org-at-table-p)]
21280 ["Move Column Right" org-metaright (org-at-table-p)]
21281 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21282 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21283 ("Row"
21284 ["Move Row Up" org-metaup (org-at-table-p)]
21285 ["Move Row Down" org-metadown (org-at-table-p)]
21286 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21287 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21288 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21289 "--"
21290 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21291 ("Rectangle"
21292 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21293 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21294 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21295 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21296 "--"
21297 ("Calculate"
21298 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21299 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21300 ["Edit Formulas" org-edit-special (org-at-table-p)]
21301 "--"
21302 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21303 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21304 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21305 "--"
21306 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21307 "--"
21308 ["Sum Column/Rectangle" org-table-sum
21309 (or (org-at-table-p) (org-region-active-p))]
21310 ["Which Column?" org-table-current-column (org-at-table-p)])
21311 ["Debug Formulas"
21312 org-table-toggle-formula-debugger
21313 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21314 ["Show Col/Row Numbers"
21315 org-table-toggle-coordinate-overlays
21316 :style toggle
21317 :selected (bound-and-true-p org-table-overlay-coordinates)]
21318 "--"
21319 ["Create" org-table-create (and (not (org-at-table-p))
21320 org-enable-table-editor)]
21321 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21322 ["Import from File" org-table-import (not (org-at-table-p))]
21323 ["Export to File" org-table-export (org-at-table-p)]
21324 "--"
21325 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21326 "--"
21327 ("Plot"
21328 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21329 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21331 (easy-menu-define org-org-menu org-mode-map "Org menu"
21332 '("Org"
21333 ("Show/Hide"
21334 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21335 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21336 ["Sparse Tree..." org-sparse-tree t]
21337 ["Reveal Context" org-reveal t]
21338 ["Show All" outline-show-all t]
21339 "--"
21340 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21341 "--"
21342 ["New Heading" org-insert-heading t]
21343 ("Navigate Headings"
21344 ["Up" outline-up-heading t]
21345 ["Next" outline-next-visible-heading t]
21346 ["Previous" outline-previous-visible-heading t]
21347 ["Next Same Level" outline-forward-same-level t]
21348 ["Previous Same Level" outline-backward-same-level t]
21349 "--"
21350 ["Jump" org-goto t])
21351 ("Edit Structure"
21352 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21353 "--"
21354 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21355 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21356 "--"
21357 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21358 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21359 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21360 "--"
21361 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21362 "--"
21363 ["Copy visible text" org-copy-visible t]
21364 "--"
21365 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21366 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21367 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21368 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21369 "--"
21370 ["Sort Region/Children" org-sort t]
21371 "--"
21372 ["Convert to odd levels" org-convert-to-odd-levels t]
21373 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21374 ("Editing"
21375 ["Emphasis..." org-emphasize t]
21376 ["Edit Source Example" org-edit-special t]
21377 "--"
21378 ["Footnote new/jump" org-footnote-action t]
21379 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21380 ("Archive"
21381 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21382 "--"
21383 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21384 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21385 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21387 "--"
21388 ("Hyperlinks"
21389 ["Store Link (Global)" org-store-link t]
21390 ["Find existing link to here" org-occur-link-in-agenda-files t]
21391 ["Insert Link" org-insert-link t]
21392 ["Follow Link" org-open-at-point t]
21393 "--"
21394 ["Next link" org-next-link t]
21395 ["Previous link" org-previous-link t]
21396 "--"
21397 ["Descriptive Links"
21398 org-toggle-link-display
21399 :style radio
21400 :selected org-descriptive-links
21402 ["Literal Links"
21403 org-toggle-link-display
21404 :style radio
21405 :selected (not org-descriptive-links)])
21406 "--"
21407 ("TODO Lists"
21408 ["TODO/DONE/-" org-todo t]
21409 ("Select keyword"
21410 ["Next keyword" org-shiftright (org-at-heading-p)]
21411 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21412 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21413 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21414 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21415 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21416 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21417 "--"
21418 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21419 :selected org-enforce-todo-dependencies :style toggle :active t]
21420 "Settings for tree at point"
21421 ["Do Children sequentially" org-toggle-ordered-property :style radio
21422 :selected (org-entry-get nil "ORDERED")
21423 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21424 ["Do Children parallel" org-toggle-ordered-property :style radio
21425 :selected (not (org-entry-get nil "ORDERED"))
21426 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21427 "--"
21428 ["Set Priority" org-priority t]
21429 ["Priority Up" org-shiftup t]
21430 ["Priority Down" org-shiftdown t]
21431 "--"
21432 ["Get news from all feeds" org-feed-update-all t]
21433 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21434 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21435 ("TAGS and Properties"
21436 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21437 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21438 "--"
21439 ["Set property" org-set-property (not (org-before-first-heading-p))]
21440 ["Column view of properties" org-columns t]
21441 ["Insert Column View DBlock" org-columns-insert-dblock t])
21442 ("Dates and Scheduling"
21443 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21444 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21445 ("Change Date"
21446 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21447 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21448 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21449 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21450 ["Compute Time Range" org-evaluate-time-range t]
21451 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21452 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21453 "--"
21454 ["Custom time format" org-toggle-time-stamp-overlays
21455 :style radio :selected org-display-custom-times]
21456 "--"
21457 ["Goto Calendar" org-goto-calendar t]
21458 ["Date from Calendar" org-date-from-calendar t]
21459 "--"
21460 ["Start/Restart Timer" org-timer-start t]
21461 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21462 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21463 ["Insert Timer String" org-timer t]
21464 ["Insert Timer Item" org-timer-item t])
21465 ("Logging work"
21466 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21467 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21468 ["Clock out" org-clock-out t]
21469 ["Clock cancel" org-clock-cancel t]
21470 "--"
21471 ["Mark as default task" org-clock-mark-default-task t]
21472 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21473 ["Goto running clock" org-clock-goto t]
21474 "--"
21475 ["Display times" org-clock-display t]
21476 ["Create clock table" org-clock-report t]
21477 "--"
21478 ["Record DONE time"
21479 (progn (setq org-log-done (not org-log-done))
21480 (message "Switching to %s will %s record a timestamp"
21481 (car org-done-keywords)
21482 (if org-log-done "automatically" "not")))
21483 :style toggle :selected org-log-done])
21484 "--"
21485 ["Agenda Command..." org-agenda t]
21486 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21487 ("File List for Agenda")
21488 ("Special views current file"
21489 ["TODO Tree" org-show-todo-tree t]
21490 ["Check Deadlines" org-check-deadlines t]
21491 ["Tags/Property tree" org-match-sparse-tree t])
21492 "--"
21493 ["Export/Publish..." org-export-dispatch t]
21494 ("LaTeX"
21495 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21496 :selected org-cdlatex-mode]
21497 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21498 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21499 ["Modify math symbol" org-cdlatex-math-modify
21500 (org-inside-LaTeX-fragment-p)]
21501 ["Insert citation" org-reftex-citation t])
21502 "--"
21503 ("MobileOrg"
21504 ["Push Files and Views" org-mobile-push t]
21505 ["Get Captured and Flagged" org-mobile-pull t]
21506 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21507 "--"
21508 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21509 "--"
21510 ("Documentation"
21511 ["Show Version" org-version t]
21512 ["Info Documentation" org-info t])
21513 ("Customize"
21514 ["Browse Org Group" org-customize t]
21515 "--"
21516 ["Expand This Menu" org-create-customize-menu
21517 (fboundp 'customize-menu-create)])
21518 ["Send bug report" org-submit-bug-report t]
21519 "--"
21520 ("Refresh/Reload"
21521 ["Refresh setup current buffer" org-mode-restart t]
21522 ["Reload Org (after update)" org-reload t]
21523 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21526 (defun org-info (&optional node)
21527 "Read documentation for Org in the info system.
21528 With optional NODE, go directly to that node."
21529 (interactive)
21530 (info (format "(org)%s" (or node ""))))
21532 ;;;###autoload
21533 (defun org-submit-bug-report ()
21534 "Submit a bug report on Org via mail.
21536 Don't hesitate to report any problems or inaccurate documentation.
21538 If you don't have setup sending mail from (X)Emacs, please copy the
21539 output buffer into your mail program, as it gives us important
21540 information about your Org version and configuration."
21541 (interactive)
21542 (require 'reporter)
21543 (defvar reporter-prompt-for-summary-p)
21544 (org-load-modules-maybe)
21545 (org-require-autoloaded-modules)
21546 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21547 (reporter-submit-bug-report
21548 "emacs-orgmode@gnu.org"
21549 (org-version nil 'full)
21550 (let (list)
21551 (save-window-excursion
21552 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21553 (delete-other-windows)
21554 (erase-buffer)
21555 (insert "You are about to submit a bug report to the Org mailing list.
21557 We would like to add your full Org and Outline configuration to the
21558 bug report. This greatly simplifies the work of the maintainer and
21559 other experts on the mailing list.
21561 HOWEVER, some variables you have customized may contain private
21562 information. The names of customers, colleagues, or friends, might
21563 appear in the form of file names, tags, todo states, or search strings.
21564 If you answer yes to the prompt, you might want to check and remove
21565 such private information before sending the email.")
21566 (add-text-properties (point-min) (point-max) '(face org-warning))
21567 (when (yes-or-no-p "Include your Org configuration ")
21568 (mapatoms
21569 (lambda (v)
21570 (and (boundp v)
21571 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21572 (or (and (symbol-value v)
21573 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21574 (and
21575 (get v 'custom-type) (get v 'standard-value)
21576 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21577 (push v list)))))
21578 (kill-buffer (get-buffer "*Warn about privacy*"))
21579 list))
21580 nil nil
21581 "Remember to cover the basics, that is, what you expected to happen and
21582 what in fact did happen. You don't know how to make a good report? See
21584 http://orgmode.org/manual/Feedback.html#Feedback
21586 Your bug report will be posted to the Org mailing list.
21587 ------------------------------------------------------------------------")
21588 (save-excursion
21589 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21590 (replace-match "\\1Bug: \\3 [\\2]")))))
21593 (defun org-install-agenda-files-menu ()
21594 (let ((bl (buffer-list)))
21595 (save-excursion
21596 (while bl
21597 (set-buffer (pop bl))
21598 (when (derived-mode-p 'org-mode) (setq bl nil)))
21599 (when (derived-mode-p 'org-mode)
21600 (easy-menu-change
21601 '("Org") "File List for Agenda"
21602 (append
21603 (list
21604 ["Edit File List" (org-edit-agenda-file-list) t]
21605 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21606 ["Remove Current File from List" org-remove-file t]
21607 ["Cycle through agenda files" org-cycle-agenda-files t]
21608 ["Occur in all agenda files" org-occur-in-agenda-files t]
21609 "--")
21610 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21612 ;;;; Documentation
21614 (defun org-require-autoloaded-modules ()
21615 (interactive)
21616 (mapc #'require
21617 '(org-agenda org-archive org-attach org-clock org-colview org-id
21618 org-table org-timer)))
21620 ;;;###autoload
21621 (defun org-reload (&optional uncompiled)
21622 "Reload all org lisp files.
21623 With prefix arg UNCOMPILED, load the uncompiled versions."
21624 (interactive "P")
21625 (require 'loadhist)
21626 (let* ((org-dir (org-find-library-dir "org"))
21627 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21628 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21629 (remove-re (format "\\`%s\\'"
21630 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21631 (feats (delete-dups
21632 (mapcar 'file-name-sans-extension
21633 (mapcar 'file-name-nondirectory
21634 (delq nil
21635 (mapcar 'feature-file
21636 features))))))
21637 (lfeat (append
21638 (sort
21639 (setq feats
21640 (delq nil (mapcar
21641 (lambda (f)
21642 (if (and (string-match feature-re f)
21643 (not (string-match remove-re f)))
21644 f nil))
21645 feats)))
21646 'string-lessp)
21647 (list "org-version" "org")))
21648 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21649 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21650 load-uncore load-misses)
21651 (setq load-misses
21652 (delq 't
21653 (mapcar (lambda (f)
21654 (or (org-load-noerror-mustsuffix (concat org-dir f))
21655 (and (string= org-dir contrib-dir)
21656 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21657 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21658 (add-to-list 'load-uncore f 'append)
21661 lfeat)))
21662 (when load-uncore
21663 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21664 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21665 (if load-misses
21666 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21667 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21668 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21670 ;;;###autoload
21671 (defun org-customize ()
21672 "Call the customize function with org as argument."
21673 (interactive)
21674 (org-load-modules-maybe)
21675 (org-require-autoloaded-modules)
21676 (customize-browse 'org))
21678 (defun org-create-customize-menu ()
21679 "Create a full customization menu for Org mode, insert it into the menu."
21680 (interactive)
21681 (org-load-modules-maybe)
21682 (org-require-autoloaded-modules)
21683 (if (fboundp 'customize-menu-create)
21684 (progn
21685 (easy-menu-change
21686 '("Org") "Customize"
21687 `(["Browse Org group" org-customize t]
21688 "--"
21689 ,(customize-menu-create 'org)
21690 ["Set" Custom-set t]
21691 ["Save" Custom-save t]
21692 ["Reset to Current" Custom-reset-current t]
21693 ["Reset to Saved" Custom-reset-saved t]
21694 ["Reset to Standard Settings" Custom-reset-standard t]))
21695 (message "\"Org\"-menu now contains full customization menu"))
21696 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21698 ;;;; Miscellaneous stuff
21700 ;;; Generally useful functions
21702 (defun org-get-at-eol (property n)
21703 "Get text property PROPERTY at the end of line less N characters."
21704 (get-text-property (- (point-at-eol) n) property))
21706 (defun org-find-text-property-in-string (prop s)
21707 "Return the first non-nil value of property PROP in string S."
21708 (or (get-text-property 0 prop s)
21709 (get-text-property (or (next-single-property-change 0 prop s) 0)
21710 prop s)))
21712 (defun org-display-warning (message)
21713 "Display the given MESSAGE as a warning."
21714 (display-warning 'org message :warning))
21716 (defun org-eval (form)
21717 "Eval FORM and return result."
21718 (condition-case error
21719 (eval form)
21720 (error (format "%%![Error: %s]" error))))
21722 (defun org-in-clocktable-p ()
21723 "Check if the cursor is in a clocktable."
21724 (let ((pos (point)) start)
21725 (save-excursion
21726 (end-of-line 1)
21727 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21728 (setq start (match-beginning 0))
21729 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21730 (>= (match-end 0) pos)
21731 start))))
21733 (defun org-in-verbatim-emphasis ()
21734 (save-match-data
21735 (and (org-in-regexp org-verbatim-re 2)
21736 (>= (point) (match-beginning 3))
21737 (<= (point) (match-end 4)))))
21739 (defun org-overlay-display (ovl text &optional face evap)
21740 "Make overlay OVL display TEXT with face FACE."
21741 (overlay-put ovl 'display text)
21742 (if face (overlay-put ovl 'face face))
21743 (if evap (overlay-put ovl 'evaporate t)))
21745 (defun org-overlay-before-string (ovl text &optional face evap)
21746 "Make overlay OVL display TEXT with face FACE."
21747 (if face (org-add-props text nil 'face face))
21748 (overlay-put ovl 'before-string text)
21749 (if evap (overlay-put ovl 'evaporate t)))
21751 (defun org-find-overlays (prop &optional pos delete)
21752 "Find all overlays specifying PROP at POS or point.
21753 If DELETE is non-nil, delete all those overlays."
21754 (let (found)
21755 (dolist (ov (overlays-at (or pos (point))) found)
21756 (cond ((not (overlay-get ov prop)))
21757 (delete (delete-overlay ov))
21758 (t (push ov found))))))
21760 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21761 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21762 (if (and marker (marker-buffer marker)
21763 (buffer-live-p (marker-buffer marker)))
21764 (progn
21765 (pop-to-buffer-same-window (marker-buffer marker))
21766 (when (or (> marker (point-max)) (< marker (point-min)))
21767 (widen))
21768 (goto-char marker)
21769 (org-show-context 'org-goto))
21770 (if bookmark
21771 (bookmark-jump bookmark)
21772 (error "Cannot find location"))))
21774 (defun org-quote-csv-field (s)
21775 "Quote field for inclusion in CSV material."
21776 (if (string-match "[\",]" s)
21777 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21780 (defun org-force-self-insert (N)
21781 "Needed to enforce self-insert under remapping."
21782 (interactive "p")
21783 (self-insert-command N))
21785 (defun org-string-width (s)
21786 "Compute width of string, ignoring invisible characters.
21787 This ignores character with invisibility property `org-link', and also
21788 characters with property `org-cwidth', because these will become invisible
21789 upon the next fontification round."
21790 (let (b l)
21791 (when (or (eq t buffer-invisibility-spec)
21792 (assq 'org-link buffer-invisibility-spec))
21793 (while (setq b (text-property-any 0 (length s)
21794 'invisible 'org-link s))
21795 (setq s (concat (substring s 0 b)
21796 (substring s (or (next-single-property-change
21797 b 'invisible s)
21798 (length s)))))))
21799 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21800 (setq s (concat (substring s 0 b)
21801 (substring s (or (next-single-property-change
21802 b 'org-cwidth s)
21803 (length s))))))
21804 (setq l (string-width s) b -1)
21805 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21806 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21809 (defun org-shorten-string (s maxlength)
21810 "Shorten string S so that it is no longer than MAXLENGTH characters.
21811 If the string is shorter or has length MAXLENGTH, just return the
21812 original string. If it is longer, the functions finds a space in the
21813 string, breaks this string off at that locations and adds three dots
21814 as ellipsis. Including the ellipsis, the string will not be longer
21815 than MAXLENGTH. If finding a good breaking point in the string does
21816 not work, the string is just chopped off in the middle of a word
21817 if necessary."
21818 (if (<= (length s) maxlength)
21820 (let* ((n (max (- maxlength 4) 1))
21821 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21822 (if (string-match re s)
21823 (concat (match-string 1 s) "...")
21824 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21826 (defun org-get-indentation (&optional line)
21827 "Get the indentation of the current line, interpreting tabs.
21828 When LINE is given, assume it represents a line and compute its indentation."
21829 (if line
21830 (when (string-match "^ *" (org-remove-tabs line))
21831 (match-end 0))
21832 (save-excursion
21833 (beginning-of-line 1)
21834 (skip-chars-forward " \t")
21835 (current-column))))
21837 (defun org-get-string-indentation (s)
21838 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21839 (let ((n -1) (i 0) (w tab-width) c)
21840 (catch 'exit
21841 (while (< (setq n (1+ n)) (length s))
21842 (setq c (aref s n))
21843 (cond ((= c ?\ ) (setq i (1+ i)))
21844 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21845 (t (throw 'exit t)))))
21848 (defun org-remove-tabs (s &optional width)
21849 "Replace tabulators in S with spaces.
21850 Assumes that s is a single line, starting in column 0."
21851 (setq width (or width tab-width))
21852 (while (string-match "\t" s)
21853 (setq s (replace-match
21854 (make-string
21855 (- (* width (/ (+ (match-beginning 0) width) width))
21856 (match-beginning 0)) ?\ )
21857 t t s)))
21860 (defun org-fix-indentation (line ind)
21861 "Fix indentation in LINE.
21862 IND is a cons cell with target and minimum indentation.
21863 If the current indentation in LINE is smaller than the minimum,
21864 leave it alone. If it is larger than ind, set it to the target."
21865 (let* ((l (org-remove-tabs line))
21866 (i (org-get-indentation l))
21867 (i1 (car ind)) (i2 (cdr ind)))
21868 (when (>= i i2) (setq l (substring line i2)))
21869 (if (> i1 0)
21870 (concat (make-string i1 ?\ ) l)
21871 l)))
21873 (defun org-remove-indentation (code &optional n)
21874 "Remove maximum common indentation in string CODE and return it.
21875 N may optionally be the number of columns to remove. Return CODE
21876 as-is if removal failed."
21877 (with-temp-buffer
21878 (insert code)
21879 (if (org-do-remove-indentation n) (buffer-string) code)))
21881 (defun org-do-remove-indentation (&optional n)
21882 "Remove the maximum common indentation from the buffer.
21883 When optional argument N is a positive integer, remove exactly
21884 that much characters from indentation, if possible. Return nil
21885 if it fails."
21886 (catch :exit
21887 (goto-char (point-min))
21888 ;; Find maximum common indentation, if not specified.
21889 (let ((n (or n
21890 (let ((min-ind (point-max)))
21891 (save-excursion
21892 (while (re-search-forward "^[ \t]*\\S-" nil t)
21893 (let ((ind (1- (current-column))))
21894 (if (zerop ind) (throw :exit nil)
21895 (setq min-ind (min min-ind ind))))))
21896 min-ind))))
21897 (if (zerop n) (throw :exit nil)
21898 ;; Remove exactly N indentation, but give up if not possible.
21899 (while (not (eobp))
21900 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21901 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21902 ((< ind n) (throw :exit nil))
21903 (t (indent-line-to (- ind n))))
21904 (forward-line)))
21905 ;; Signal success.
21906 t))))
21908 (defun org-fill-template (template alist)
21909 "Find each %key of ALIST in TEMPLATE and replace it."
21910 (let ((case-fold-search nil))
21911 (dolist (entry (sort (copy-sequence alist)
21912 (lambda (a b) (< (length (car a)) (length (car b))))))
21913 (setq template
21914 (replace-regexp-in-string
21915 (concat "%" (regexp-quote (car entry)))
21916 (or (cdr entry) "") template t t)))
21917 template))
21919 (defun org-base-buffer (buffer)
21920 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21921 (if (not buffer)
21922 buffer
21923 (or (buffer-base-buffer buffer)
21924 buffer)))
21926 (defun org-wrap (string &optional width lines)
21927 "Wrap string to either a number of lines, or a width in characters.
21928 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21929 that costs. If there is a word longer than WIDTH, the text is actually
21930 wrapped to the length of that word.
21931 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21932 many lines, whatever width that takes.
21933 The return value is a list of lines, without newlines at the end."
21934 (let* ((words (org-split-string string "[ \t\n]+"))
21935 (maxword (apply 'max (mapcar 'org-string-width words)))
21936 w ll)
21937 (cond (width
21938 (org-do-wrap words (max maxword width)))
21939 (lines
21940 (setq w maxword)
21941 (setq ll (org-do-wrap words maxword))
21942 (if (<= (length ll) lines)
21944 (setq ll words)
21945 (while (> (length ll) lines)
21946 (setq w (1+ w))
21947 (setq ll (org-do-wrap words w)))
21948 ll))
21949 (t (error "Cannot wrap this")))))
21951 (defun org-do-wrap (words width)
21952 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21953 (let (lines line)
21954 (while words
21955 (setq line (pop words))
21956 (while (and words (< (+ (length line) (length (car words))) width))
21957 (setq line (concat line " " (pop words))))
21958 (setq lines (push line lines)))
21959 (nreverse lines)))
21961 (defun org-split-string (string &optional separators)
21962 "Splits STRING into substrings at SEPARATORS.
21963 SEPARATORS is a regular expression.
21964 No empty strings are returned if there are matches at the beginning
21965 and end of string."
21966 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
21967 (let ((start 0) notfirst list)
21968 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
21969 (if (and notfirst
21970 (= start (match-beginning 0))
21971 (< start (length string)))
21972 (1+ start) start))
21973 (< (match-beginning 0) (length string)))
21974 (setq notfirst t)
21975 (or (eq (match-beginning 0) 0)
21976 (and (eq (match-beginning 0) (match-end 0))
21977 (eq (match-beginning 0) start))
21978 (push (substring string start (match-beginning 0)) list))
21979 (setq start (match-end 0)))
21980 (or (eq start (length string))
21981 (push (substring string start) list))
21982 (nreverse list)))
21984 (defun org-quote-vert (s)
21985 "Replace \"|\" with \"\\vert\"."
21986 (while (string-match "|" s)
21987 (setq s (replace-match "\\vert" t t s)))
21990 (defun org-uuidgen-p (s)
21991 "Is S an ID created by UUIDGEN?"
21992 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21994 (defun org-in-src-block-p (&optional inside)
21995 "Whether point is in a code source block.
21996 When INSIDE is non-nil, don't consider we are within a src block
21997 when point is at #+BEGIN_SRC or #+END_SRC."
21998 (let ((case-fold-search t))
21999 (or (and (eq (get-char-property (point) 'src-block) t))
22000 (and (not inside)
22001 (save-match-data
22002 (save-excursion
22003 (beginning-of-line)
22004 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22006 (defun org-context ()
22007 "Return a list of contexts of the current cursor position.
22008 If several contexts apply, all are returned.
22009 Each context entry is a list with a symbol naming the context, and
22010 two positions indicating start and end of the context. Possible
22011 contexts are:
22013 :headline anywhere in a headline
22014 :headline-stars on the leading stars in a headline
22015 :todo-keyword on a TODO keyword (including DONE) in a headline
22016 :tags on the TAGS in a headline
22017 :priority on the priority cookie in a headline
22018 :item on the first line of a plain list item
22019 :item-bullet on the bullet/number of a plain list item
22020 :checkbox on the checkbox in a plain list item
22021 :table in an Org table
22022 :table-special on a special filed in a table
22023 :table-table in a table.el table
22024 :clocktable in a clocktable
22025 :src-block in a source block
22026 :link on a hyperlink
22027 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22028 :target on a <<target>>
22029 :radio-target on a <<<radio-target>>>
22030 :latex-fragment on a LaTeX fragment
22031 :latex-preview on a LaTeX fragment with overlaid preview image
22033 This function expects the position to be visible because it uses font-lock
22034 faces as a help to recognize the following contexts: :table-special, :link,
22035 and :keyword."
22036 (let* ((f (get-text-property (point) 'face))
22037 (faces (if (listp f) f (list f)))
22038 (case-fold-search t)
22039 (p (point)) clist o)
22040 ;; First the large context
22041 (cond
22042 ((org-at-heading-p t)
22043 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22044 (when (progn
22045 (beginning-of-line 1)
22046 (looking-at org-todo-line-tags-regexp))
22047 (push (org-point-in-group p 1 :headline-stars) clist)
22048 (push (org-point-in-group p 2 :todo-keyword) clist)
22049 (push (org-point-in-group p 4 :tags) clist))
22050 (goto-char p)
22051 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22052 (when (looking-at "\\[#[A-Z0-9]\\]")
22053 (push (org-point-in-group p 0 :priority) clist)))
22055 ((org-at-item-p)
22056 (push (org-point-in-group p 2 :item-bullet) clist)
22057 (push (list :item (point-at-bol)
22058 (save-excursion (org-end-of-item) (point)))
22059 clist)
22060 (and (org-at-item-checkbox-p)
22061 (push (org-point-in-group p 0 :checkbox) clist)))
22063 ((org-at-table-p)
22064 (push (list :table (org-table-begin) (org-table-end)) clist)
22065 (when (memq 'org-formula faces)
22066 (push (list :table-special
22067 (previous-single-property-change p 'face)
22068 (next-single-property-change p 'face)) clist)))
22069 ((org-at-table-p 'any)
22070 (push (list :table-table) clist)))
22071 (goto-char p)
22073 (let ((case-fold-search t))
22074 ;; New the "medium" contexts: clocktables, source blocks
22075 (cond ((org-in-clocktable-p)
22076 (push (list :clocktable
22077 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22078 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22079 (match-beginning 1))
22080 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22081 (match-end 0))) clist))
22082 ((org-in-src-block-p)
22083 (push (list :src-block
22084 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22085 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22086 (match-beginning 1))
22087 (and (search-forward "#+END_SRC" nil t)
22088 (match-beginning 0))) clist))))
22089 (goto-char p)
22091 ;; Now the small context
22092 (cond
22093 ((org-at-timestamp-p)
22094 (push (org-point-in-group p 0 :timestamp) clist))
22095 ((memq 'org-link faces)
22096 (push (list :link
22097 (previous-single-property-change p 'face)
22098 (next-single-property-change p 'face)) clist))
22099 ((memq 'org-special-keyword faces)
22100 (push (list :keyword
22101 (previous-single-property-change p 'face)
22102 (next-single-property-change p 'face)) clist))
22103 ((org-at-target-p)
22104 (push (org-point-in-group p 0 :target) clist)
22105 (goto-char (1- (match-beginning 0)))
22106 (when (looking-at org-radio-target-regexp)
22107 (push (org-point-in-group p 0 :radio-target) clist))
22108 (goto-char p))
22109 ((setq o (cl-some
22110 (lambda (o)
22111 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22113 (overlays-at (point))))
22114 (push (list :latex-fragment
22115 (overlay-start o) (overlay-end o)) clist)
22116 (push (list :latex-preview
22117 (overlay-start o) (overlay-end o)) clist))
22118 ((org-inside-LaTeX-fragment-p)
22119 ;; FIXME: positions wrong.
22120 (push (list :latex-fragment (point) (point)) clist)))
22122 (setq clist (nreverse (delq nil clist)))
22123 clist))
22125 (defun org-in-regexp (regexp &optional nlines visually)
22126 "Check if point is inside a match of REGEXP.
22128 Normally only the current line is checked, but you can include
22129 NLINES extra lines around point into the search. If VISUALLY is
22130 set, require that the cursor is not after the match but really
22131 on, so that the block visually is on the match.
22133 Return nil or a cons cell (BEG . END) where BEG and END are,
22134 respectively, the positions at the beginning and the end of the
22135 match."
22136 (catch :exit
22137 (let ((pos (point))
22138 (eol (line-end-position (if nlines (1+ nlines) 1))))
22139 (save-excursion
22140 (beginning-of-line (- 1 (or nlines 0)))
22141 (while (and (re-search-forward regexp eol t)
22142 (<= (match-beginning 0) pos))
22143 (let ((end (match-end 0)))
22144 (when (or (> end pos) (and (= end pos) (not visually)))
22145 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22147 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22148 "Non-nil when point is between matches of START-RE and END-RE.
22150 Also return a non-nil value when point is on one of the matches.
22152 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22153 buffer positions. Default values are the positions of headlines
22154 surrounding the point.
22156 The functions returns a cons cell whose car (resp. cdr) is the
22157 position before START-RE (resp. after END-RE)."
22158 (save-match-data
22159 (let ((pos (point))
22160 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22161 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22162 beg end)
22163 (save-excursion
22164 ;; Point is on a block when on START-RE or if START-RE can be
22165 ;; found before it...
22166 (and (or (org-in-regexp start-re)
22167 (re-search-backward start-re limit-up t))
22168 (setq beg (match-beginning 0))
22169 ;; ... and END-RE after it...
22170 (goto-char (match-end 0))
22171 (re-search-forward end-re limit-down t)
22172 (> (setq end (match-end 0)) pos)
22173 ;; ... without another START-RE in-between.
22174 (goto-char (match-beginning 0))
22175 (not (re-search-backward start-re (1+ beg) t))
22176 ;; Return value.
22177 (cons beg end))))))
22179 (defun org-in-block-p (names)
22180 "Non-nil when point belongs to a block whose name belongs to NAMES.
22182 NAMES is a list of strings containing names of blocks.
22184 Return first block name matched, or nil. Beware that in case of
22185 nested blocks, the returned name may not belong to the closest
22186 block from point."
22187 (save-match-data
22188 (catch 'exit
22189 (let ((case-fold-search t)
22190 (lim-up (save-excursion (outline-previous-heading)))
22191 (lim-down (save-excursion (outline-next-heading))))
22192 (dolist (name names)
22193 (let ((n (regexp-quote name)))
22194 (when (org-between-regexps-p
22195 (concat "^[ \t]*#\\+begin_" n)
22196 (concat "^[ \t]*#\\+end_" n)
22197 lim-up lim-down)
22198 (throw 'exit n)))))
22199 nil)))
22201 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22202 "Call `multi-occur' with buffers for all agenda files."
22203 (interactive "sOrg-files matching: ")
22204 (let* ((files (org-agenda-files))
22205 (tnames (mapcar #'file-truename files))
22206 (extra org-agenda-text-search-extra-files))
22207 (when (eq (car extra) 'agenda-archives)
22208 (setq extra (cdr extra))
22209 (setq files (org-add-archive-files files)))
22210 (dolist (f extra)
22211 (unless (member (file-truename f) tnames)
22212 (unless (member f files) (setq files (append files (list f))))
22213 (setq tnames (append tnames (list (file-truename f))))))
22214 (multi-occur
22215 (mapcar (lambda (x)
22216 (with-current-buffer
22217 ;; FIXME: Why not just (find-file-noselect x)?
22218 ;; Is it to avoid the "revert buffer" prompt?
22219 (or (get-file-buffer x) (find-file-noselect x))
22220 (widen)
22221 (current-buffer)))
22222 files)
22223 regexp)))
22225 (add-hook 'occur-mode-find-occurrence-hook
22226 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22228 (defun org-occur-link-in-agenda-files ()
22229 "Create a link and search for it in the agendas.
22230 The link is not stored in `org-stored-links', it is just created
22231 for the search purpose."
22232 (interactive)
22233 (let ((link (condition-case nil
22234 (org-store-link nil)
22235 (error "Unable to create a link to here"))))
22236 (org-occur-in-agenda-files (regexp-quote link))))
22238 (defun org-reverse-string (string)
22239 "Return the reverse of STRING."
22240 (apply 'string (reverse (string-to-list string))))
22242 ;; defsubst org-uniquify must be defined before first use
22244 (defun org-uniquify-alist (alist)
22245 "Merge elements of ALIST with the same key.
22247 For example, in this alist:
22249 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22250 => \\='((a 1 3) (b 2))
22252 merge (a 1) and (a 3) into (a 1 3).
22254 The function returns the new ALIST."
22255 (let (rtn)
22256 (dolist (e alist rtn)
22257 (let (n)
22258 (if (not (assoc (car e) rtn))
22259 (push e rtn)
22260 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22261 (setq rtn (assq-delete-all (car e) rtn))
22262 (push n rtn))))))
22264 (defun org-delete-all (elts list)
22265 "Remove all elements in ELTS from LIST.
22266 Comparison is done with `equal'. It is a destructive operation
22267 that may remove elements by altering the list structure."
22268 (while elts
22269 (setq list (delete (pop elts) list)))
22270 list)
22272 (defun org-back-over-empty-lines ()
22273 "Move backwards over whitespace, to the beginning of the first empty line.
22274 Returns the number of empty lines passed."
22275 (let ((pos (point)))
22276 (if (cdr (assq 'heading org-blank-before-new-entry))
22277 (skip-chars-backward " \t\n\r")
22278 (unless (eobp)
22279 (forward-line -1)))
22280 (beginning-of-line 2)
22281 (goto-char (min (point) pos))
22282 (count-lines (point) pos)))
22284 (defun org-skip-whitespace ()
22285 (skip-chars-forward " \t\n\r"))
22287 (defun org-point-in-group (point group &optional context)
22288 "Check if POINT is in match-group GROUP.
22289 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22290 match. If the match group does not exist or point is not inside it,
22291 return nil."
22292 (and (match-beginning group)
22293 (>= point (match-beginning group))
22294 (<= point (match-end group))
22295 (if context
22296 (list context (match-beginning group) (match-end group))
22297 t)))
22299 (defun org-switch-to-buffer-other-window (&rest args)
22300 "Switch to buffer in a second window on the current frame.
22301 In particular, do not allow pop-up frames.
22302 Returns the newly created buffer."
22303 (org-no-popups
22304 (apply 'switch-to-buffer-other-window args)))
22306 (defun org-combine-plists (&rest plists)
22307 "Create a single property list from all plists in PLISTS.
22308 The process starts by copying the first list, and then setting properties
22309 from the other lists. Settings in the last list are the most significant
22310 ones and overrule settings in the other lists."
22311 (let ((rtn (copy-sequence (pop plists)))
22312 p v ls)
22313 (while plists
22314 (setq ls (pop plists))
22315 (while ls
22316 (setq p (pop ls) v (pop ls))
22317 (setq rtn (plist-put rtn p v))))
22318 rtn))
22320 (defun org-replace-escapes (string table)
22321 "Replace %-escapes in STRING with values in TABLE.
22322 TABLE is an association list with keys like \"%a\" and string values.
22323 The sequences in STRING may contain normal field width and padding information,
22324 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22325 so values can contain further %-escapes if they are define later in TABLE."
22326 (let ((tbl (copy-alist table))
22327 (case-fold-search nil)
22328 (pchg 0)
22329 re rpl)
22330 (dolist (e tbl)
22331 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22332 (when (and (cdr e) (string-match re (cdr e)))
22333 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22334 (safe "SREF"))
22335 (add-text-properties 0 3 (list 'sref sref) safe)
22336 (setcdr e (replace-match safe t t (cdr e)))))
22337 (while (string-match re string)
22338 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22339 (cdr e)))
22340 (setq string (replace-match rpl t t string))))
22341 (while (setq pchg (next-property-change pchg string))
22342 (let ((sref (get-text-property pchg 'sref string)))
22343 (when (and sref (string-match "SREF" string pchg))
22344 (setq string (replace-match sref t t string)))))
22345 string))
22347 (defun org-find-base-buffer-visiting (file)
22348 "Like `find-buffer-visiting' but always return the base buffer and
22349 not an indirect buffer."
22350 (let ((buf (or (get-file-buffer file)
22351 (find-buffer-visiting file))))
22352 (if buf
22353 (or (buffer-base-buffer buf) buf)
22354 nil)))
22356 ;;; TODO: Only called once, from ox-odt which should probably use
22357 ;;; org-export-inline-image-p or something.
22358 (defun org-file-image-p (file)
22359 "Return non-nil if FILE is an image."
22360 (save-match-data
22361 (string-match (image-file-name-regexp) file)))
22363 (defun org-get-cursor-date (&optional with-time)
22364 "Return the date at cursor in as a time.
22365 This works in the calendar and in the agenda, anywhere else it just
22366 returns the current time.
22367 If WITH-TIME is non-nil, returns the time of the event at point (in
22368 the agenda) or the current time of the day."
22369 (let (date day defd tp hod mod)
22370 (when with-time
22371 (setq tp (get-text-property (point) 'time))
22372 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22373 (setq hod (string-to-number (match-string 1 tp))
22374 mod (string-to-number (match-string 2 tp))))
22375 (or tp (let ((now (decode-time)))
22376 (setq hod (nth 2 now)
22377 mod (nth 1 now)))))
22378 (cond
22379 ((eq major-mode 'calendar-mode)
22380 (setq date (calendar-cursor-to-date)
22381 defd (encode-time 0 (or mod 0) (or hod 0)
22382 (nth 1 date) (nth 0 date) (nth 2 date))))
22383 ((eq major-mode 'org-agenda-mode)
22384 (setq day (get-text-property (point) 'day))
22385 (when day
22386 (setq date (calendar-gregorian-from-absolute day)
22387 defd (encode-time 0 (or mod 0) (or hod 0)
22388 (nth 1 date) (nth 0 date) (nth 2 date))))))
22389 (or defd (current-time))))
22391 (defun org-mark-subtree (&optional up)
22392 "Mark the current subtree.
22393 This puts point at the start of the current subtree, and mark at
22394 the end. If a numeric prefix UP is given, move up into the
22395 hierarchy of headlines by UP levels before marking the subtree."
22396 (interactive "P")
22397 (org-with-limited-levels
22398 (cond ((org-at-heading-p) (beginning-of-line))
22399 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22400 (t (outline-previous-visible-heading 1))))
22401 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22402 (if (called-interactively-p 'any)
22403 (call-interactively 'org-mark-element)
22404 (org-mark-element)))
22406 (defun org-file-newer-than-p (file time)
22407 "Non-nil if FILE is newer than TIME.
22408 FILE is a filename, as a string, TIME is a list of integers, as
22409 returned by, e.g., `current-time'."
22410 (and (file-exists-p file)
22411 ;; Only compare times up to whole seconds as some file-systems
22412 ;; (e.g. HFS+) do not retain any finer granularity. As
22413 ;; a consequence, make sure we return non-nil when the two
22414 ;; times are equal.
22415 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22416 (cl-subseq time 0 2)))))
22418 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22419 "Compile a SOURCE file using PROCESS.
22421 PROCESS is either a function or a list of shell commands, as
22422 strings. EXT is a file extension, without the leading dot, as
22423 a string. It is used to check if the process actually succeeded.
22425 PROCESS must create a file with the same base name and directory
22426 as SOURCE, but ending with EXT. The function then returns its
22427 filename. Otherwise, it raises an error. The error message can
22428 then be refined by providing string ERR-MSG, which is appended to
22429 the standard message.
22431 If PROCESS is a function, it is called with a single argument:
22432 the SOURCE file.
22434 If it is a list of commands, each of them is called using
22435 `shell-command'. By default, in each command, %b, %f, %F, %o and
22436 %O are replaced with, respectively, SOURCE base name, name, full
22437 name, directory and absolute output file name. It is possible,
22438 however, to use more place-holders by specifying them in optional
22439 argument SPEC, as an alist following the pattern
22441 (CHARACTER . REPLACEMENT-STRING).
22443 When PROCESS is a list of commands, optional argument LOG-BUF can
22444 be set to a buffer or a buffer name. `shell-command' then uses
22445 it for output."
22446 (let* ((base-name (file-name-base source))
22447 (full-name (file-truename source))
22448 (out-dir (or (file-name-directory source) "./"))
22449 (output (expand-file-name (concat base-name "." ext) out-dir))
22450 (time (current-time))
22451 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22452 (save-window-excursion
22453 (pcase process
22454 ((pred functionp) (funcall process (shell-quote-argument source)))
22455 ((pred consp)
22456 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22457 (spec (append spec
22458 `((?b . ,(shell-quote-argument base-name))
22459 (?f . ,(shell-quote-argument source))
22460 (?F . ,(shell-quote-argument full-name))
22461 (?o . ,(shell-quote-argument out-dir))
22462 (?O . ,(shell-quote-argument output))))))
22463 (dolist (command process)
22464 (shell-command (format-spec command spec) log-buf))
22465 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22466 (_ (error "No valid command to process %S%s" source err-msg))))
22467 ;; Check for process failure. Output file is expected to be
22468 ;; located in the same directory as SOURCE.
22469 (unless (org-file-newer-than-p output time)
22470 (error (format "File %S wasn't produced%s" output err-msg)))
22471 output))
22473 ;;; Indentation
22475 (defun org--get-expected-indentation (element contentsp)
22476 "Expected indentation column for current line, according to ELEMENT.
22477 ELEMENT is an element containing point. CONTENTSP is non-nil
22478 when indentation is to be computed according to contents of
22479 ELEMENT."
22480 (let ((type (org-element-type element))
22481 (start (org-element-property :begin element))
22482 (post-affiliated (org-element-property :post-affiliated element)))
22483 (org-with-wide-buffer
22484 (cond
22485 (contentsp
22486 (cl-case type
22487 ((diary-sexp footnote-definition) 0)
22488 ((headline inlinetask nil)
22489 (if (not org-adapt-indentation) 0
22490 (let ((level (org-current-level)))
22491 (if level (1+ level) 0))))
22492 ((item plain-list) (org-list-item-body-column post-affiliated))
22494 (goto-char start)
22495 (org-get-indentation))))
22496 ((memq type '(headline inlinetask nil))
22497 (if (org-match-line "[ \t]*$")
22498 (org--get-expected-indentation element t)
22500 ((memq type '(diary-sexp footnote-definition)) 0)
22501 ;; First paragraph of a footnote definition or an item.
22502 ;; Indent like parent.
22503 ((< (line-beginning-position) start)
22504 (org--get-expected-indentation
22505 (org-element-property :parent element) t))
22506 ;; At first line: indent according to previous sibling, if any,
22507 ;; ignoring footnote definitions and inline tasks, or parent's
22508 ;; contents.
22509 ((= (line-beginning-position) start)
22510 (catch 'exit
22511 (while t
22512 (if (= (point-min) start) (throw 'exit 0)
22513 (goto-char (1- start))
22514 (let* ((previous (org-element-at-point))
22515 (parent previous))
22516 (while (and parent (<= (org-element-property :end parent) start))
22517 (setq previous parent
22518 parent (org-element-property :parent parent)))
22519 (cond
22520 ((not previous) (throw 'exit 0))
22521 ((> (org-element-property :end previous) start)
22522 (throw 'exit (org--get-expected-indentation previous t)))
22523 ((memq (org-element-type previous)
22524 '(footnote-definition inlinetask))
22525 (setq start (org-element-property :begin previous)))
22526 (t (goto-char (org-element-property :begin previous))
22527 (throw 'exit
22528 (if (bolp) (org-get-indentation)
22529 ;; At first paragraph in an item or
22530 ;; a footnote definition.
22531 (org--get-expected-indentation
22532 (org-element-property :parent previous) t))))))))))
22533 ;; Otherwise, move to the first non-blank line above.
22535 (beginning-of-line)
22536 (let ((pos (point)))
22537 (skip-chars-backward " \r\t\n")
22538 (cond
22539 ;; Two blank lines end a footnote definition or a plain
22540 ;; list. When we indent an empty line after them, the
22541 ;; containing list or footnote definition is over, so it
22542 ;; qualifies as a previous sibling. Therefore, we indent
22543 ;; like its first line.
22544 ((and (memq type '(footnote-definition plain-list))
22545 (> (count-lines (point) pos) 2))
22546 (goto-char start)
22547 (org-get-indentation))
22548 ;; Line above is the first one of a paragraph at the
22549 ;; beginning of an item or a footnote definition. Indent
22550 ;; like parent.
22551 ((< (line-beginning-position) start)
22552 (org--get-expected-indentation
22553 (org-element-property :parent element) t))
22554 ;; Line above is the beginning of an element, i.e., point
22555 ;; was originally on the blank lines between element's start
22556 ;; and contents.
22557 ((= (line-beginning-position) post-affiliated)
22558 (org--get-expected-indentation element t))
22559 ;; POS is after contents in a greater element. Indent like
22560 ;; the beginning of the element.
22562 ;; As a special case, if point is at the end of a footnote
22563 ;; definition or an item, indent like the very last element
22564 ;; within. If that last element is an item, indent like its
22565 ;; contents.
22566 ((and (not (eq type 'paragraph))
22567 (let ((cend (org-element-property :contents-end element)))
22568 (and cend (<= cend pos))))
22569 (if (memq type '(footnote-definition item plain-list))
22570 (let ((last (org-element-at-point)))
22571 (org--get-expected-indentation
22572 last (eq (org-element-type last) 'item)))
22573 (goto-char start)
22574 (org-get-indentation)))
22575 ;; In any other case, indent like the current line.
22576 (t (org-get-indentation)))))))))
22578 (defun org--align-node-property ()
22579 "Align node property at point.
22580 Alignment is done according to `org-property-format', which see."
22581 (when (save-excursion
22582 (beginning-of-line)
22583 (looking-at org-property-re))
22584 (replace-match
22585 (concat (match-string 4)
22586 (org-trim
22587 (format org-property-format (match-string 1) (match-string 3))))
22588 t t)))
22590 (defun org-indent-line ()
22591 "Indent line depending on context.
22593 Indentation is done according to the following rules:
22595 - Footnote definitions, diary sexps, headlines and inline tasks
22596 have to start at column 0.
22598 - On the very first line of an element, consider, in order, the
22599 next rules until one matches:
22601 1. If there's a sibling element before, ignoring footnote
22602 definitions and inline tasks, indent like its first line.
22604 2. If element has a parent, indent like its contents. More
22605 precisely, if parent is an item, indent after the
22606 description part, if any, or the bullet (see
22607 `org-list-description-max-indent'). Else, indent like
22608 parent's first line.
22610 3. Otherwise, indent relatively to current level, if
22611 `org-adapt-indentation' is non-nil, or to left margin.
22613 - On a blank line at the end of an element, indent according to
22614 the type of the element. More precisely
22616 1. If element is a plain list, an item, or a footnote
22617 definition, indent like the very last element within.
22619 2. If element is a paragraph, indent like its last non blank
22620 line.
22622 3. Otherwise, indent like its very first line.
22624 - In the code part of a source block, use language major mode
22625 to indent current line if `org-src-tab-acts-natively' is
22626 non-nil. If it is nil, do nothing.
22628 - Otherwise, indent like the first non-blank line above.
22630 The function doesn't indent an item as it could break the whole
22631 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22632 `\\[org-shiftmetaright]'.
22634 Also align node properties according to `org-property-format'."
22635 (interactive)
22636 (cond
22637 (orgstruct-is-++
22638 (let ((indent-line-function
22639 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22640 (indent-according-to-mode)))
22641 ((org-at-heading-p) 'noindent)
22643 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22644 (type (org-element-type element)))
22645 (cond ((and (memq type '(plain-list item))
22646 (= (line-beginning-position)
22647 (org-element-property :post-affiliated element)))
22648 'noindent)
22649 ((and (eq type 'latex-environment)
22650 (>= (point) (org-element-property :post-affiliated element))
22651 (< (point) (org-with-wide-buffer
22652 (goto-char (org-element-property :end element))
22653 (skip-chars-backward " \r\t\n")
22654 (line-beginning-position 2))))
22655 'noindent)
22656 ((and (eq type 'src-block)
22657 org-src-tab-acts-natively
22658 (> (line-beginning-position)
22659 (org-element-property :post-affiliated element))
22660 (< (line-beginning-position)
22661 (org-with-wide-buffer
22662 (goto-char (org-element-property :end element))
22663 (skip-chars-backward " \r\t\n")
22664 (line-beginning-position))))
22665 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22667 (let ((column (org--get-expected-indentation element nil)))
22668 ;; Preserve current column.
22669 (if (<= (current-column) (current-indentation))
22670 (indent-line-to column)
22671 (save-excursion (indent-line-to column))))
22672 ;; Align node property. Also preserve current column.
22673 (when (eq type 'node-property)
22674 (let ((column (current-column)))
22675 (org--align-node-property)
22676 (org-move-to-column column)))))))))
22678 (defun org-indent-region (start end)
22679 "Indent each non-blank line in the region.
22680 Called from a program, START and END specify the region to
22681 indent. The function will not indent contents of example blocks,
22682 verse blocks and export blocks as leading white spaces are
22683 assumed to be significant there."
22684 (interactive "r")
22685 (save-excursion
22686 (goto-char start)
22687 (skip-chars-forward " \r\t\n")
22688 (unless (eobp) (beginning-of-line))
22689 (let ((indent-to
22690 (lambda (ind pos)
22691 ;; Set IND as indentation for all lines between point and
22692 ;; POS. Blank lines are ignored. Leave point after POS
22693 ;; once done.
22694 (let ((limit (copy-marker pos)))
22695 (while (< (point) limit)
22696 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22697 (forward-line))
22698 (set-marker limit nil))))
22699 (end (copy-marker end)))
22700 (while (< (point) end)
22701 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22702 (let* ((element (org-element-at-point))
22703 (type (org-element-type element))
22704 (element-end (copy-marker (org-element-property :end element)))
22705 (ind (org--get-expected-indentation element nil)))
22706 (cond
22707 ;; Element indented as a single block. Example blocks
22708 ;; preserving indentation are a special case since the
22709 ;; "contents" must not be indented whereas the block
22710 ;; boundaries can.
22711 ((or (memq type '(export-block latex-environment))
22712 (and (eq type 'example-block)
22713 (not
22714 (or org-src-preserve-indentation
22715 (org-element-property :preserve-indent element)))))
22716 (let ((offset (- ind (org-get-indentation))))
22717 (unless (zerop offset)
22718 (indent-rigidly (org-element-property :begin element)
22719 (org-element-property :end element)
22720 offset)))
22721 (goto-char element-end))
22722 ;; Elements indented line wise. Be sure to exclude
22723 ;; example blocks (preserving indentation) and source
22724 ;; blocks from this category as they are treated
22725 ;; specially later.
22726 ((or (memq type '(paragraph table table-row))
22727 (not (or (org-element-property :contents-begin element)
22728 (memq type '(example-block src-block)))))
22729 (when (eq type 'node-property)
22730 (org--align-node-property)
22731 (beginning-of-line))
22732 (funcall indent-to ind (min element-end end)))
22733 ;; Elements consisting of three parts: before the
22734 ;; contents, the contents, and after the contents. The
22735 ;; contents are treated specially, according to the
22736 ;; element type, or not indented at all. Other parts are
22737 ;; indented as a single block.
22739 (let* ((post (copy-marker
22740 (org-element-property :post-affiliated element)))
22741 (cbeg
22742 (copy-marker
22743 (cond
22744 ((not (org-element-property :contents-begin element))
22745 ;; Fake contents for source blocks.
22746 (org-with-wide-buffer
22747 (goto-char post)
22748 (line-beginning-position 2)))
22749 ((memq type '(footnote-definition item plain-list))
22750 ;; Contents in these elements could start on
22751 ;; the same line as the beginning of the
22752 ;; element. Make sure we start indenting
22753 ;; from the second line.
22754 (org-with-wide-buffer
22755 (goto-char post)
22756 (end-of-line)
22757 (skip-chars-forward " \r\t\n")
22758 (if (eobp) (point) (line-beginning-position))))
22759 (t (org-element-property :contents-begin element)))))
22760 (cend (copy-marker
22761 (or (org-element-property :contents-end element)
22762 ;; Fake contents for source blocks.
22763 (org-with-wide-buffer
22764 (goto-char element-end)
22765 (skip-chars-backward " \r\t\n")
22766 (line-beginning-position)))
22767 t)))
22768 ;; Do not change items indentation individually as it
22769 ;; might break the list as a whole. On the other
22770 ;; hand, when at a plain list, indent it as a whole.
22771 (cond ((eq type 'plain-list)
22772 (let ((offset (- ind (org-get-indentation))))
22773 (unless (zerop offset)
22774 (indent-rigidly (org-element-property :begin element)
22775 (org-element-property :end element)
22776 offset))
22777 (goto-char cbeg)))
22778 ((eq type 'item) (goto-char cbeg))
22779 (t (funcall indent-to ind (min cbeg end))))
22780 (when (< (point) end)
22781 (cl-case type
22782 ((example-block verse-block))
22783 (src-block
22784 ;; In a source block, indent source code
22785 ;; according to language major mode, but only if
22786 ;; `org-src-tab-acts-natively' is non-nil.
22787 (when (and (< (point) end) org-src-tab-acts-natively)
22788 (ignore-errors
22789 (org-babel-do-in-edit-buffer
22790 (indent-region (point-min) (point-max))))))
22791 (t (org-indent-region (point) (min cend end))))
22792 (goto-char (min cend end))
22793 (when (< (point) end)
22794 (funcall indent-to ind (min element-end end))))
22795 (set-marker post nil)
22796 (set-marker cbeg nil)
22797 (set-marker cend nil))))
22798 (set-marker element-end nil))))
22799 (set-marker end nil))))
22801 (defun org-indent-drawer ()
22802 "Indent the drawer at point."
22803 (interactive)
22804 (unless (save-excursion
22805 (beginning-of-line)
22806 (looking-at-p org-drawer-regexp))
22807 (user-error "Not at a drawer"))
22808 (let ((element (org-element-at-point)))
22809 (unless (memq (org-element-type element) '(drawer property-drawer))
22810 (user-error "Not at a drawer"))
22811 (org-with-wide-buffer
22812 (org-indent-region (org-element-property :begin element)
22813 (org-element-property :end element))))
22814 (message "Drawer at point indented"))
22816 (defun org-indent-block ()
22817 "Indent the block at point."
22818 (interactive)
22819 (unless (save-excursion
22820 (beginning-of-line)
22821 (let ((case-fold-search t))
22822 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22823 (user-error "Not at a block"))
22824 (let ((element (org-element-at-point)))
22825 (unless (memq (org-element-type element)
22826 '(comment-block center-block dynamic-block example-block
22827 export-block quote-block special-block
22828 src-block verse-block))
22829 (user-error "Not at a block"))
22830 (org-with-wide-buffer
22831 (org-indent-region (org-element-property :begin element)
22832 (org-element-property :end element))))
22833 (message "Block at point indented"))
22836 ;;; Filling
22838 ;; We use our own fill-paragraph and auto-fill functions.
22840 ;; `org-fill-paragraph' relies on adaptive filling and context
22841 ;; checking. Appropriate `fill-prefix' is computed with
22842 ;; `org-adaptive-fill-function'.
22844 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22845 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22846 ;; `org-adaptive-fill-function' value. Internally,
22847 ;; `org-comment-line-break-function' breaks the line.
22849 ;; `org-setup-filling' installs filling and auto-filling related
22850 ;; variables during `org-mode' initialization.
22852 (defvar org-element-paragraph-separate) ; org-element.el
22853 (defun org-setup-filling ()
22854 (require 'org-element)
22855 ;; Prevent auto-fill from inserting unwanted new items.
22856 (when (boundp 'fill-nobreak-predicate)
22857 (setq-local
22858 fill-nobreak-predicate
22859 (org-uniquify
22860 (append fill-nobreak-predicate
22861 '(org-fill-line-break-nobreak-p
22862 org-fill-paragraph-with-timestamp-nobreak-p)))))
22863 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22864 (setq-local paragraph-start paragraph-ending)
22865 (setq-local paragraph-separate paragraph-ending))
22866 (setq-local fill-paragraph-function 'org-fill-paragraph)
22867 (setq-local auto-fill-inhibit-regexp nil)
22868 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22869 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22870 (setq-local comment-line-break-function 'org-comment-line-break-function))
22872 (defun org-fill-line-break-nobreak-p ()
22873 "Non-nil when a new line at point would create an Org line break."
22874 (save-excursion
22875 (skip-chars-backward "[ \t]")
22876 (skip-chars-backward "\\\\")
22877 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22879 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22880 "Non-nil when a new line at point would split a timestamp."
22881 (and (org-at-timestamp-p t)
22882 (not (looking-at org-ts-regexp-both))))
22884 (declare-function message-in-body-p "message" ())
22885 (defvar orgtbl-line-start-regexp) ; From org-table.el
22886 (defun org-adaptive-fill-function ()
22887 "Compute a fill prefix for the current line.
22888 Return fill prefix, as a string, or nil if current line isn't
22889 meant to be filled. For convenience, if `adaptive-fill-regexp'
22890 matches in paragraphs or comments, use it."
22891 (catch 'exit
22892 (when (derived-mode-p 'message-mode)
22893 (save-excursion
22894 (beginning-of-line)
22895 (cond ((not (message-in-body-p)) (throw 'exit nil))
22896 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22897 ((looking-at message-cite-prefix-regexp)
22898 (throw 'exit (match-string-no-properties 0)))
22899 ((looking-at org-outline-regexp)
22900 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22901 (org-with-wide-buffer
22902 (unless (org-at-heading-p)
22903 (let* ((p (line-beginning-position))
22904 (element (save-excursion
22905 (beginning-of-line)
22906 (org-element-at-point)))
22907 (type (org-element-type element))
22908 (post-affiliated (org-element-property :post-affiliated element)))
22909 (unless (< p post-affiliated)
22910 (cl-case type
22911 (comment
22912 (save-excursion
22913 (beginning-of-line)
22914 (looking-at "[ \t]*")
22915 (concat (match-string 0) "# ")))
22916 (footnote-definition "")
22917 ((item plain-list)
22918 (make-string (org-list-item-body-column post-affiliated) ?\s))
22919 (paragraph
22920 ;; Fill prefix is usually the same as the current line,
22921 ;; unless the paragraph is at the beginning of an item.
22922 (let ((parent (org-element-property :parent element)))
22923 (save-excursion
22924 (beginning-of-line)
22925 (cond ((eq (org-element-type parent) 'item)
22926 (make-string (org-list-item-body-column
22927 (org-element-property :begin parent))
22928 ?\s))
22929 ((and adaptive-fill-regexp
22930 ;; Locally disable
22931 ;; `adaptive-fill-function' to let
22932 ;; `fill-context-prefix' handle
22933 ;; `adaptive-fill-regexp' variable.
22934 (let (adaptive-fill-function)
22935 (fill-context-prefix
22936 post-affiliated
22937 (org-element-property :end element)))))
22938 ((looking-at "[ \t]+") (match-string 0))
22939 (t "")))))
22940 (comment-block
22941 ;; Only fill contents if P is within block boundaries.
22942 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22943 (forward-line)
22944 (point)))
22945 (cend (save-excursion
22946 (goto-char (org-element-property :end element))
22947 (skip-chars-backward " \r\t\n")
22948 (line-beginning-position))))
22949 (when (and (>= p cbeg) (< p cend))
22950 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22951 (match-string 0)
22952 "")))))))))))
22954 (declare-function message-goto-body "message" ())
22955 (defvar message-cite-prefix-regexp) ; From message.el
22956 (defun org-fill-paragraph (&optional justify)
22957 "Fill element at point, when applicable.
22959 This function only applies to comment blocks, comments, example
22960 blocks and paragraphs. Also, as a special case, re-align table
22961 when point is at one.
22963 If JUSTIFY is non-nil (interactively, with prefix argument),
22964 justify as well. If `sentence-end-double-space' is non-nil, then
22965 period followed by one space does not end a sentence, so don't
22966 break a line there. The variable `fill-column' controls the
22967 width for filling.
22969 For convenience, when point is at a plain list, an item or
22970 a footnote definition, try to fill the first paragraph within."
22971 (interactive)
22972 (if (and (derived-mode-p 'message-mode)
22973 (or (not (message-in-body-p))
22974 (save-excursion (move-beginning-of-line 1)
22975 (looking-at message-cite-prefix-regexp))))
22976 ;; First ensure filling is correct in message-mode.
22977 (let ((fill-paragraph-function
22978 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
22979 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
22980 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
22981 (paragraph-separate
22982 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
22983 (fill-paragraph nil))
22984 (with-syntax-table org-mode-transpose-word-syntax-table
22985 ;; Move to end of line in order to get the first paragraph
22986 ;; within a plain list or a footnote definition.
22987 (let ((element (save-excursion
22988 (end-of-line)
22989 (or (ignore-errors (org-element-at-point))
22990 (user-error "An element cannot be parsed line %d"
22991 (line-number-at-pos (point)))))))
22992 ;; First check if point is in a blank line at the beginning of
22993 ;; the buffer. In that case, ignore filling.
22994 (cl-case (org-element-type element)
22995 ;; Use major mode filling function is src blocks.
22996 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22997 ;; Align Org tables, leave table.el tables as-is.
22998 (table-row (org-table-align) t)
22999 (table
23000 (when (eq (org-element-property :type element) 'org)
23001 (save-excursion
23002 (goto-char (org-element-property :post-affiliated element))
23003 (org-table-align)))
23005 (paragraph
23006 ;; Paragraphs may contain `line-break' type objects.
23007 (let ((beg (max (point-min)
23008 (org-element-property :contents-begin element)))
23009 (end (min (point-max)
23010 (org-element-property :contents-end element))))
23011 ;; Do nothing if point is at an affiliated keyword.
23012 (if (< (line-end-position) beg) t
23013 (when (derived-mode-p 'message-mode)
23014 ;; In `message-mode', do not fill following citation
23015 ;; in current paragraph nor text before message body.
23016 (let ((body-start (save-excursion (message-goto-body))))
23017 (when body-start (setq beg (max body-start beg))))
23018 (when (save-excursion
23019 (re-search-forward
23020 (concat "^" message-cite-prefix-regexp) end t))
23021 (setq end (match-beginning 0))))
23022 ;; Fill paragraph, taking line breaks into account.
23023 (save-excursion
23024 (goto-char beg)
23025 (let ((cuts (list beg)))
23026 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23027 (when (eq 'line-break
23028 (org-element-type
23029 (save-excursion (backward-char)
23030 (org-element-context))))
23031 (push (point) cuts)))
23032 (dolist (c (delq end cuts))
23033 (fill-region-as-paragraph c end justify)
23034 (setq end c))))
23035 t)))
23036 ;; Contents of `comment-block' type elements should be
23037 ;; filled as plain text, but only if point is within block
23038 ;; markers.
23039 (comment-block
23040 (let* ((case-fold-search t)
23041 (beg (save-excursion
23042 (goto-char (org-element-property :begin element))
23043 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23044 (forward-line)
23045 (point)))
23046 (end (save-excursion
23047 (goto-char (org-element-property :end element))
23048 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23049 (line-beginning-position))))
23050 (if (or (< (point) beg) (> (point) end)) t
23051 (fill-region-as-paragraph
23052 (save-excursion (end-of-line)
23053 (re-search-backward "^[ \t]*$" beg 'move)
23054 (line-beginning-position))
23055 (save-excursion (beginning-of-line)
23056 (re-search-forward "^[ \t]*$" end 'move)
23057 (line-beginning-position))
23058 justify))))
23059 ;; Fill comments.
23060 (comment
23061 (let ((begin (org-element-property :post-affiliated element))
23062 (end (org-element-property :end element)))
23063 (when (and (>= (point) begin) (<= (point) end))
23064 (let ((begin (save-excursion
23065 (end-of-line)
23066 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23067 (progn (forward-line) (point))
23068 begin)))
23069 (end (save-excursion
23070 (end-of-line)
23071 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23072 (1- (line-beginning-position))
23073 (skip-chars-backward " \r\t\n")
23074 (line-end-position)))))
23075 ;; Do not fill comments when at a blank line.
23076 (when (> end begin)
23077 (let ((fill-prefix
23078 (save-excursion
23079 (beginning-of-line)
23080 (looking-at "[ \t]*#")
23081 (let ((comment-prefix (match-string 0)))
23082 (goto-char (match-end 0))
23083 (if (looking-at adaptive-fill-regexp)
23084 (concat comment-prefix (match-string 0))
23085 (concat comment-prefix " "))))))
23086 (save-excursion
23087 (fill-region-as-paragraph begin end justify))))))
23089 ;; Ignore every other element.
23090 (otherwise t))))))
23092 (defun org-auto-fill-function ()
23093 "Auto-fill function."
23094 ;; Check if auto-filling is meaningful.
23095 (let ((fc (current-fill-column)))
23096 (when (and fc (> (current-column) fc))
23097 (let* ((fill-prefix (org-adaptive-fill-function))
23098 ;; Enforce empty fill prefix, if required. Otherwise, it
23099 ;; will be computed again.
23100 (adaptive-fill-mode (not (equal fill-prefix ""))))
23101 (when fill-prefix (do-auto-fill))))))
23103 (defun org-comment-line-break-function (&optional soft)
23104 "Break line at point and indent, continuing comment if within one.
23105 The inserted newline is marked hard if variable
23106 `use-hard-newlines' is true, unless optional argument SOFT is
23107 non-nil."
23108 (if soft (insert-and-inherit ?\n) (newline 1))
23109 (save-excursion (forward-char -1) (delete-horizontal-space))
23110 (delete-horizontal-space)
23111 (indent-to-left-margin)
23112 (insert-before-markers-and-inherit fill-prefix))
23115 ;;; Fixed Width Areas
23117 (defun org-toggle-fixed-width ()
23118 "Toggle fixed-width markup.
23120 Add or remove fixed-width markup on current line, whenever it
23121 makes sense. Return an error otherwise.
23123 If a region is active and if it contains only fixed-width areas
23124 or blank lines, remove all fixed-width markup in it. If the
23125 region contains anything else, convert all non-fixed-width lines
23126 to fixed-width ones.
23128 Blank lines at the end of the region are ignored unless the
23129 region only contains such lines."
23130 (interactive)
23131 (if (not (org-region-active-p))
23132 ;; No region:
23134 ;; Remove fixed width marker only in a fixed-with element.
23136 ;; Add fixed width maker in paragraphs, in blank lines after
23137 ;; elements or at the beginning of a headline or an inlinetask,
23138 ;; and before any one-line elements (e.g., a clock).
23139 (progn
23140 (beginning-of-line)
23141 (let* ((element (org-element-at-point))
23142 (type (org-element-type element)))
23143 (cond
23144 ((and (eq type 'fixed-width)
23145 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23146 (replace-match
23147 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23148 ((and (memq type '(babel-call clock comment diary-sexp headline
23149 horizontal-rule keyword paragraph
23150 planning))
23151 (<= (org-element-property :post-affiliated element) (point)))
23152 (skip-chars-forward " \t")
23153 (insert ": "))
23154 ((and (looking-at-p "[ \t]*$")
23155 (or (eq type 'inlinetask)
23156 (save-excursion
23157 (skip-chars-forward " \r\t\n")
23158 (<= (org-element-property :end element) (point)))))
23159 (delete-region (point) (line-end-position))
23160 (org-indent-line)
23161 (insert ": "))
23162 (t (user-error "Cannot insert a fixed-width line here")))))
23163 ;; Region active.
23164 (let* ((begin (save-excursion
23165 (goto-char (region-beginning))
23166 (line-beginning-position)))
23167 (end (copy-marker
23168 (save-excursion
23169 (goto-char (region-end))
23170 (unless (eolp) (beginning-of-line))
23171 (if (save-excursion (re-search-backward "\\S-" begin t))
23172 (progn (skip-chars-backward " \r\t\n") (point))
23173 (point)))))
23174 (all-fixed-width-p
23175 (catch 'not-all-p
23176 (save-excursion
23177 (goto-char begin)
23178 (skip-chars-forward " \r\t\n")
23179 (when (eobp) (throw 'not-all-p nil))
23180 (while (< (point) end)
23181 (let ((element (org-element-at-point)))
23182 (if (eq (org-element-type element) 'fixed-width)
23183 (goto-char (org-element-property :end element))
23184 (throw 'not-all-p nil))))
23185 t))))
23186 (if all-fixed-width-p
23187 (save-excursion
23188 (goto-char begin)
23189 (while (< (point) end)
23190 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23191 (replace-match
23192 "" nil nil nil
23193 (if (= (line-end-position) (match-end 0)) 0 1)))
23194 (forward-line)))
23195 (let ((min-ind (point-max)))
23196 ;; Find minimum indentation across all lines.
23197 (save-excursion
23198 (goto-char begin)
23199 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23200 (setq min-ind 0)
23201 (catch 'zerop
23202 (while (< (point) end)
23203 (unless (looking-at-p "[ \t]*$")
23204 (let ((ind (org-get-indentation)))
23205 (setq min-ind (min min-ind ind))
23206 (when (zerop ind) (throw 'zerop t))))
23207 (forward-line)))))
23208 ;; Loop over all lines and add fixed-width markup everywhere
23209 ;; but in fixed-width lines.
23210 (save-excursion
23211 (goto-char begin)
23212 (while (< (point) end)
23213 (cond
23214 ((org-at-heading-p)
23215 (insert ": ")
23216 (forward-line)
23217 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23218 (insert ":")
23219 (forward-line)))
23220 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23221 (let* ((element (org-element-at-point))
23222 (element-end (org-element-property :end element)))
23223 (if (eq (org-element-type element) 'fixed-width)
23224 (progn (goto-char element-end)
23225 (skip-chars-backward " \r\t\n")
23226 (forward-line))
23227 (let ((limit (min end element-end)))
23228 (while (< (point) limit)
23229 (org-move-to-column min-ind t)
23230 (insert ": ")
23231 (forward-line))))))
23233 (org-move-to-column min-ind t)
23234 (insert ": ")
23235 (forward-line)))))))
23236 (set-marker end nil))))
23239 ;;; Comments
23241 ;; Org comments syntax is quite complex. It requires the entire line
23242 ;; to be just a comment. Also, even with the right syntax at the
23243 ;; beginning of line, some some elements (i.e. verse-block or
23244 ;; example-block) don't accept comments. Usual Emacs comment commands
23245 ;; cannot cope with those requirements. Therefore, Org replaces them.
23247 ;; Org still relies on `comment-dwim', but cannot trust
23248 ;; `comment-only-p'. So, `comment-region-function' and
23249 ;; `uncomment-region-function' both point
23250 ;; to`org-comment-or-uncomment-region'. Eventually,
23251 ;; `org-insert-comment' takes care of insertion of comments at the
23252 ;; beginning of line.
23254 ;; `org-setup-comments-handling' install comments related variables
23255 ;; during `org-mode' initialization.
23257 (defun org-setup-comments-handling ()
23258 (interactive)
23259 (setq-local comment-use-syntax nil)
23260 (setq-local comment-start "# ")
23261 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23262 (setq-local comment-insert-comment-function 'org-insert-comment)
23263 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23264 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23266 (defun org-insert-comment ()
23267 "Insert an empty comment above current line.
23268 If the line is empty, insert comment at its beginning. When
23269 point is within a source block, comment according to the related
23270 major mode."
23271 (if (let ((element (org-element-at-point)))
23272 (and (eq (org-element-type element) 'src-block)
23273 (< (save-excursion
23274 (goto-char (org-element-property :post-affiliated element))
23275 (line-end-position))
23276 (point))
23277 (> (save-excursion
23278 (goto-char (org-element-property :end element))
23279 (skip-chars-backward " \r\t\n")
23280 (line-beginning-position))
23281 (point))))
23282 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23283 (beginning-of-line)
23284 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23285 (open-line 1))
23286 (org-indent-line)
23287 (insert "# ")))
23289 (defvar comment-empty-lines) ; From newcomment.el.
23290 (defun org-comment-or-uncomment-region (beg end &rest _)
23291 "Comment or uncomment each non-blank line in the region.
23292 Uncomment each non-blank line between BEG and END if it only
23293 contains commented lines. Otherwise, comment them. If region is
23294 strictly within a source block, use appropriate comment syntax."
23295 (if (let ((element (org-element-at-point)))
23296 (and (eq (org-element-type element) 'src-block)
23297 (< (save-excursion
23298 (goto-char (org-element-property :post-affiliated element))
23299 (line-end-position))
23300 beg)
23301 (>= (save-excursion
23302 (goto-char (org-element-property :end element))
23303 (skip-chars-backward " \r\t\n")
23304 (line-beginning-position))
23305 end)))
23306 ;; Translate region boundaries for the Org buffer to the source
23307 ;; buffer.
23308 (let ((offset (- end beg)))
23309 (save-excursion
23310 (goto-char beg)
23311 (org-babel-do-in-edit-buffer
23312 (comment-or-uncomment-region (point) (+ offset (point))))))
23313 (save-restriction
23314 ;; Restrict region
23315 (narrow-to-region (save-excursion (goto-char beg)
23316 (skip-chars-forward " \r\t\n" end)
23317 (line-beginning-position))
23318 (save-excursion (goto-char end)
23319 (skip-chars-backward " \r\t\n" beg)
23320 (line-end-position)))
23321 (let ((uncommentp
23322 ;; UNCOMMENTP is non-nil when every non blank line between
23323 ;; BEG and END is a comment.
23324 (save-excursion
23325 (goto-char (point-min))
23326 (while (and (not (eobp))
23327 (let ((element (org-element-at-point)))
23328 (and (eq (org-element-type element) 'comment)
23329 (goto-char (min (point-max)
23330 (org-element-property
23331 :end element)))))))
23332 (eobp))))
23333 (if uncommentp
23334 ;; Only blank lines and comments in region: uncomment it.
23335 (save-excursion
23336 (goto-char (point-min))
23337 (while (not (eobp))
23338 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23339 (replace-match "" nil nil nil 1))
23340 (forward-line)))
23341 ;; Comment each line in region.
23342 (let ((min-indent (point-max)))
23343 ;; First find the minimum indentation across all lines.
23344 (save-excursion
23345 (goto-char (point-min))
23346 (while (and (not (eobp)) (not (zerop min-indent)))
23347 (unless (looking-at "[ \t]*$")
23348 (setq min-indent (min min-indent (current-indentation))))
23349 (forward-line)))
23350 ;; Then loop over all lines.
23351 (save-excursion
23352 (goto-char (point-min))
23353 (while (not (eobp))
23354 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23355 ;; Don't get fooled by invisible text (e.g. link path)
23356 ;; when moving to column MIN-INDENT.
23357 (let ((buffer-invisibility-spec nil))
23358 (org-move-to-column min-indent t))
23359 (insert comment-start))
23360 (forward-line)))))))))
23362 (defun org-comment-dwim (_arg)
23363 "Call `comment-dwim' within a source edit buffer if needed."
23364 (interactive "*P")
23365 (if (org-in-src-block-p)
23366 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23367 (call-interactively 'comment-dwim)))
23370 ;;; Timestamps API
23372 ;; This section contains tools to operate on timestamp objects, as
23373 ;; returned by, e.g. `org-element-context'.
23375 (defun org-timestamp--to-internal-time (timestamp &optional end)
23376 "Encode TIMESTAMP object into Emacs internal time.
23377 Use end of date range or time range when END is non-nil."
23378 (apply #'encode-time
23379 (cons 0
23380 (mapcar
23381 (lambda (prop) (or (org-element-property prop timestamp) 0))
23382 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23383 '(:minute-start :hour-start :day-start :month-start
23384 :year-start))))))
23386 (defun org-timestamp-has-time-p (timestamp)
23387 "Non-nil when TIMESTAMP has a time specified."
23388 (org-element-property :hour-start timestamp))
23390 (defun org-timestamp-format (timestamp format &optional end utc)
23391 "Format a TIMESTAMP object into a string.
23393 FORMAT is a format specifier to be passed to
23394 `format-time-string'.
23396 When optional argument END is non-nil, use end of date-range or
23397 time-range, if possible.
23399 When optional argument UTC is non-nil, time will be expressed as
23400 Universal Time."
23401 (format-time-string
23402 format (org-timestamp--to-internal-time timestamp end)
23403 (and utc t)))
23405 (defun org-timestamp-split-range (timestamp &optional end)
23406 "Extract a TIMESTAMP object from a date or time range.
23408 END, when non-nil, means extract the end of the range.
23409 Otherwise, extract its start.
23411 Return a new timestamp object."
23412 (let ((type (org-element-property :type timestamp)))
23413 (if (memq type '(active inactive diary)) timestamp
23414 (let ((split-ts (org-element-copy timestamp)))
23415 ;; Set new type.
23416 (org-element-put-property
23417 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23418 ;; Copy start properties over end properties if END is
23419 ;; non-nil. Otherwise, copy end properties over `start' ones.
23420 (let ((p-alist '((:minute-start . :minute-end)
23421 (:hour-start . :hour-end)
23422 (:day-start . :day-end)
23423 (:month-start . :month-end)
23424 (:year-start . :year-end))))
23425 (dolist (p-cell p-alist)
23426 (org-element-put-property
23427 split-ts
23428 (funcall (if end #'car #'cdr) p-cell)
23429 (org-element-property
23430 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23431 ;; Eventually refresh `:raw-value'.
23432 (org-element-put-property split-ts :raw-value nil)
23433 (org-element-put-property
23434 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23436 (defun org-timestamp-translate (timestamp &optional boundary)
23437 "Translate TIMESTAMP object to custom format.
23439 Format string is defined in `org-time-stamp-custom-formats',
23440 which see.
23442 When optional argument BOUNDARY is non-nil, it is either the
23443 symbol `start' or `end'. In this case, only translate the
23444 starting or ending part of TIMESTAMP if it is a date or time
23445 range. Otherwise, translate both parts.
23447 Return timestamp as-is if `org-display-custom-times' is nil or if
23448 it has a `diary' type."
23449 (let ((type (org-element-property :type timestamp)))
23450 (if (or (not org-display-custom-times) (eq type 'diary))
23451 (org-element-interpret-data timestamp)
23452 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23453 org-time-stamp-custom-formats)))
23454 (if (and (not boundary) (memq type '(active-range inactive-range)))
23455 (concat (org-timestamp-format timestamp fmt)
23456 "--"
23457 (org-timestamp-format timestamp fmt t))
23458 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23462 ;;; Other stuff.
23464 (defvar reftex-docstruct-symbol)
23465 (defvar org--rds)
23467 (defun org-reftex-citation ()
23468 "Use reftex-citation to insert a citation into the buffer.
23469 This looks for a line like
23471 #+BIBLIOGRAPHY: foo plain option:-d
23473 and derives from it that foo.bib is the bibliography file relevant
23474 for this document. It then installs the necessary environment for RefTeX
23475 to work in this buffer and calls `reftex-citation' to insert a citation
23476 into the buffer.
23478 Export of such citations to both LaTeX and HTML is handled by the contributed
23479 package ox-bibtex by Taru Karttunen."
23480 (interactive)
23481 (let ((reftex-docstruct-symbol 'org--rds)
23482 org--rds bib)
23483 (org-with-wide-buffer
23484 (let ((case-fold-search t)
23485 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23486 (if (not (save-excursion
23487 (or (re-search-forward re nil t)
23488 (re-search-backward re nil t))))
23489 (user-error "No bibliography defined in file")
23490 (setq bib (concat (match-string 1) ".bib")
23491 org--rds (list (list 'bib bib))))))
23492 (call-interactively 'reftex-citation)))
23494 ;;;; Functions extending outline functionality
23496 (defun org-beginning-of-line (&optional n)
23497 "Go to the beginning of the current visible line.
23499 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23500 tags on the first attempt, and only move to after the tags when
23501 the cursor is already beyond the end of the headline.
23503 With argument N not nil or 1, move forward N - 1 lines first."
23504 (interactive "^p")
23505 (let ((origin (point))
23506 (special (pcase org-special-ctrl-a/e
23507 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23508 deactivate-mark)
23509 ;; First move to a visible line.
23510 (if (bound-and-true-p visual-line-mode)
23511 (beginning-of-visual-line n)
23512 (move-beginning-of-line n)
23513 ;; `move-beginning-of-line' may leave point after invisible
23514 ;; characters if line starts with such of these (e.g., with
23515 ;; a link at column 0). Really move to the beginning of the
23516 ;; current visible line.
23517 (beginning-of-line))
23518 (cond
23519 ;; No special behavior. Point is already at the beginning of
23520 ;; a line, logical or visual.
23521 ((not special))
23522 ;; `beginning-of-visual-line' left point before logical beginning
23523 ;; of line: point is at the beginning of a visual line. Bail
23524 ;; out.
23525 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23526 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23527 ;; At a headline, special position is before the title, but
23528 ;; after any TODO keyword or priority cookie.
23529 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23530 (line-end-position)))
23531 (bol (point)))
23532 (if (eq special 'reversed)
23533 (when (and (= origin bol) (eq last-command this-command))
23534 (goto-char refpos))
23535 (when (or (> origin refpos) (= origin bol))
23536 (goto-char refpos)))))
23537 ((and (looking-at org-list-full-item-re)
23538 (memq (org-element-type (save-match-data (org-element-at-point)))
23539 '(item plain-list)))
23540 ;; Set special position at first white space character after
23541 ;; bullet, and check-box, if any.
23542 (let ((after-bullet
23543 (let ((box (match-end 3)))
23544 (cond ((not box) (match-end 1))
23545 ((eq (char-after box) ?\s) (1+ box))
23546 (t box)))))
23547 (if (eq special 'reversed)
23548 (when (and (= (point) origin) (eq last-command this-command))
23549 (goto-char after-bullet))
23550 (when (or (> origin after-bullet) (= (point) origin))
23551 (goto-char after-bullet)))))
23552 ;; No special context. Point is already at beginning of line.
23553 (t nil))))
23555 (defun org-end-of-line (&optional n)
23556 "Go to the end of the line, but before ellipsis, if any.
23558 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23559 tags on the first attempt, and only move to after the tags when
23560 the cursor is already beyond the end of the headline.
23562 With argument N not nil or 1, move forward N - 1 lines first."
23563 (interactive "^p")
23564 (let ((origin (point))
23565 (special (pcase org-special-ctrl-a/e
23566 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23567 deactivate-mark)
23568 ;; First move to a visible line.
23569 (if (bound-and-true-p visual-line-mode)
23570 (beginning-of-visual-line n)
23571 (move-beginning-of-line n))
23572 (cond
23573 ;; At a headline, with tags.
23574 ((and special
23575 (save-excursion
23576 (beginning-of-line)
23577 (let ((case-fold-search nil))
23578 (looking-at org-complex-heading-regexp)))
23579 (match-end 5))
23580 (let ((tags (save-excursion
23581 (goto-char (match-beginning 5))
23582 (skip-chars-backward " \t")
23583 (point)))
23584 (visual-end (and (bound-and-true-p visual-line-mode)
23585 (save-excursion
23586 (end-of-visual-line)
23587 (point)))))
23588 ;; If `end-of-visual-line' brings us before end of line or
23589 ;; even tags, i.e., the headline spans over multiple visual
23590 ;; lines, move there.
23591 (cond ((and visual-end
23592 (< visual-end tags)
23593 (<= origin visual-end))
23594 (goto-char visual-end))
23595 ((eq special 'reversed)
23596 (if (and (= origin (line-end-position))
23597 (eq this-command last-command))
23598 (goto-char tags)
23599 (end-of-line)))
23601 (if (or (< origin tags) (= origin (line-end-position)))
23602 (goto-char tags)
23603 (end-of-line))))))
23604 ((bound-and-true-p visual-line-mode)
23605 (let ((bol (line-beginning-position)))
23606 (end-of-visual-line)
23607 ;; If `end-of-visual-line' gets us past the ellipsis at the
23608 ;; end of a line, backtrack and use `end-of-line' instead.
23609 (when (/= bol (line-beginning-position))
23610 (goto-char bol)
23611 (end-of-line))))
23612 (t (end-of-line)))))
23614 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23615 (define-key org-mode-map "\C-e" 'org-end-of-line)
23617 (defun org-backward-sentence (&optional _arg)
23618 "Go to beginning of sentence, or beginning of table field.
23619 This will call `backward-sentence' or `org-table-beginning-of-field',
23620 depending on context."
23621 (interactive)
23622 (let* ((element (org-element-at-point))
23623 (contents-begin (org-element-property :contents-begin element))
23624 (table (org-element-lineage element '(table) t)))
23625 (if (and table
23626 (> (point) contents-begin)
23627 (<= (point) (org-element-property :contents-end table)))
23628 (call-interactively #'org-table-beginning-of-field)
23629 (save-restriction
23630 (when (and contents-begin
23631 (< (point-min) contents-begin)
23632 (> (point) contents-begin))
23633 (narrow-to-region contents-begin
23634 (org-element-property :contents-end element)))
23635 (call-interactively #'backward-sentence)))))
23637 (defun org-forward-sentence (&optional _arg)
23638 "Go to end of sentence, or end of table field.
23639 This will call `forward-sentence' or `org-table-end-of-field',
23640 depending on context."
23641 (interactive)
23642 (let* ((element (org-element-at-point))
23643 (contents-end (org-element-property :contents-end element))
23644 (table (org-element-lineage element '(table) t)))
23645 (if (and table
23646 (>= (point) (org-element-property :contents-begin table))
23647 (< (point) contents-end))
23648 (call-interactively #'org-table-end-of-field)
23649 (save-restriction
23650 (when (and contents-end
23651 (> (point-max) contents-end)
23652 ;; Skip blank lines between elements.
23653 (< (org-element-property :end element)
23654 (save-excursion (goto-char contents-end)
23655 (skip-chars-forward " \r\t\n"))))
23656 (narrow-to-region (org-element-property :contents-begin element)
23657 contents-end))
23658 (call-interactively #'forward-sentence)))))
23660 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23661 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23663 (defun org-kill-line (&optional _arg)
23664 "Kill line, to tags or end of line."
23665 (interactive)
23666 (cond
23667 ((or (not org-special-ctrl-k)
23668 (bolp)
23669 (not (org-at-heading-p)))
23670 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23671 org-ctrl-k-protect-subtree
23672 (or (eq org-ctrl-k-protect-subtree 'error)
23673 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23674 (user-error "C-k aborted as it would kill a hidden subtree"))
23675 (call-interactively
23676 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23677 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23678 (kill-region (point) (match-beginning 1))
23679 (org-set-tags nil t))
23680 (t (kill-region (point) (point-at-eol)))))
23682 (define-key org-mode-map "\C-k" 'org-kill-line)
23684 (defun org-yank (&optional arg)
23685 "Yank. If the kill is a subtree, treat it specially.
23686 This command will look at the current kill and check if is a single
23687 subtree, or a series of subtrees[1]. If it passes the test, and if the
23688 cursor is at the beginning of a line or after the stars of a currently
23689 empty headline, then the yank is handled specially. How exactly depends
23690 on the value of the following variables.
23692 `org-yank-folded-subtrees'
23693 By default, this variable is non-nil, which results in
23694 subtree(s) being folded after insertion, except if doing so
23695 would swallow text after the yanked text.
23697 `org-yank-adjusted-subtrees'
23698 When non-nil (the default value is nil), the subtree will be
23699 promoted or demoted in order to fit into the local outline tree
23700 structure, which means that the level will be adjusted so that it
23701 becomes the smaller one of the two *visible* surrounding headings.
23703 Any prefix to this command will cause `yank' to be called directly with
23704 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23705 will just
23706 plainly yank the text as it is.
23708 \[1] The test checks if the first non-white line is a heading
23709 and if there are no other headings with fewer stars."
23710 (interactive "P")
23711 (org-yank-generic 'yank arg))
23713 (defun org-yank-generic (command arg)
23714 "Perform some yank-like command.
23716 This function implements the behavior described in the `org-yank'
23717 documentation. However, it has been generalized to work for any
23718 interactive command with similar behavior."
23720 ;; pretend to be command COMMAND
23721 (setq this-command command)
23723 (if arg
23724 (call-interactively command)
23726 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23727 (and (org-kill-is-subtree-p)
23728 (or (bolp)
23729 (and (looking-at "[ \t]*$")
23730 (string-match
23731 "\\`\\*+\\'"
23732 (buffer-substring (point-at-bol) (point)))))))
23733 swallowp)
23734 (cond
23735 ((and subtreep org-yank-folded-subtrees)
23736 (let ((beg (point))
23737 end)
23738 (if (and subtreep org-yank-adjusted-subtrees)
23739 (org-paste-subtree nil nil 'for-yank)
23740 (call-interactively command))
23742 (setq end (point))
23743 (goto-char beg)
23744 (when (and (bolp) subtreep
23745 (not (setq swallowp
23746 (org-yank-folding-would-swallow-text beg end))))
23747 (org-with-limited-levels
23748 (or (looking-at org-outline-regexp)
23749 (re-search-forward org-outline-regexp-bol end t))
23750 (while (and (< (point) end) (looking-at org-outline-regexp))
23751 (outline-hide-subtree)
23752 (org-cycle-show-empty-lines 'folded)
23753 (condition-case nil
23754 (outline-forward-same-level 1)
23755 (error (goto-char end))))))
23756 (when swallowp
23757 (message
23758 "Inserted text not folded because that would swallow text"))
23760 (goto-char end)
23761 (skip-chars-forward " \t\n\r")
23762 (beginning-of-line 1)
23763 (push-mark beg 'nomsg)))
23764 ((and subtreep org-yank-adjusted-subtrees)
23765 (let ((beg (point-at-bol)))
23766 (org-paste-subtree nil nil 'for-yank)
23767 (push-mark beg 'nomsg)))
23769 (call-interactively command))))))
23771 (defun org-yank-folding-would-swallow-text (beg end)
23772 "Would hide-subtree at BEG swallow any text after END?"
23773 (let (level)
23774 (org-with-limited-levels
23775 (save-excursion
23776 (goto-char beg)
23777 (when (or (looking-at org-outline-regexp)
23778 (re-search-forward org-outline-regexp-bol end t))
23779 (setq level (org-outline-level)))
23780 (goto-char end)
23781 (skip-chars-forward " \t\r\n\v\f")
23782 (not (or (eobp)
23783 (and (bolp) (looking-at-p org-outline-regexp)
23784 (<= (org-outline-level) level))))))))
23786 (define-key org-mode-map "\C-y" 'org-yank)
23788 (defun org-truely-invisible-p ()
23789 "Check if point is at a character currently not visible.
23790 This version does not only check the character property, but also
23791 `visible-mode'."
23792 ;; Early versions of noutline don't have `outline-invisible-p'.
23793 (unless (bound-and-true-p visible-mode)
23794 (outline-invisible-p)))
23796 (defun org-invisible-p2 ()
23797 "Check if point is at a character currently not visible."
23798 (save-excursion
23799 (when (and (eolp) (not (bobp))) (backward-char 1))
23800 ;; Early versions of noutline don't have `outline-invisible-p'.
23801 (outline-invisible-p)))
23803 (defun org-back-to-heading (&optional invisible-ok)
23804 "Call `outline-back-to-heading', but provide a better error message."
23805 (condition-case nil
23806 (outline-back-to-heading invisible-ok)
23807 (error (error "Before first headline at position %d in buffer %s"
23808 (point) (current-buffer)))))
23810 (defun org-before-first-heading-p ()
23811 "Before first heading?"
23812 (save-excursion
23813 (end-of-line)
23814 (null (re-search-backward org-outline-regexp-bol nil t))))
23816 (defun org-at-heading-p (&optional ignored)
23817 (outline-on-heading-p t))
23819 (defun org-in-commented-heading-p (&optional no-inheritance)
23820 "Non-nil if point is under a commented heading.
23821 This function also checks ancestors of the current headline,
23822 unless optional argument NO-INHERITANCE is non-nil."
23823 (cond
23824 ((org-before-first-heading-p) nil)
23825 ((let ((headline (nth 4 (org-heading-components))))
23826 (and headline
23827 (let ((case-fold-search nil))
23828 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23829 headline)))))
23830 (no-inheritance nil)
23832 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23834 (defun org-at-comment-p nil
23835 "Is cursor in a commented line?"
23836 (save-excursion
23837 (save-match-data
23838 (beginning-of-line)
23839 (looking-at "^[ \t]*# "))))
23841 (defun org-at-drawer-p nil
23842 "Is cursor at a drawer keyword?"
23843 (save-excursion
23844 (move-beginning-of-line 1)
23845 (looking-at org-drawer-regexp)))
23847 (defun org-at-block-p nil
23848 "Is cursor at a block keyword?"
23849 (save-excursion
23850 (move-beginning-of-line 1)
23851 (looking-at org-block-regexp)))
23853 (defun org-point-at-end-of-empty-headline ()
23854 "If point is at the end of an empty headline, return t, else nil.
23855 If the heading only contains a TODO keyword, it is still still considered
23856 empty."
23857 (let ((case-fold-search nil))
23858 (and (looking-at "[ \t]*$")
23859 org-todo-line-regexp
23860 (save-excursion
23861 (beginning-of-line)
23862 (looking-at org-todo-line-regexp)
23863 (string= (match-string 3) "")))))
23865 (defun org-at-heading-or-item-p ()
23866 (or (org-at-heading-p) (org-at-item-p)))
23868 (defun org-at-target-p ()
23869 (or (org-in-regexp org-radio-target-regexp)
23870 (org-in-regexp org-target-regexp)))
23871 ;; Compatibility alias with Org versions < 7.8.03
23872 (defalias 'org-on-target-p 'org-at-target-p)
23874 (defun org-up-heading-all (arg)
23875 "Move to the heading line of which the present line is a subheading.
23876 This function considers both visible and invisible heading lines.
23877 With argument, move up ARG levels."
23878 (outline-up-heading arg t))
23880 (defun org-up-heading-safe ()
23881 "Move to the heading line of which the present line is a subheading.
23882 This version will not throw an error. It will return the level of the
23883 headline found, or nil if no higher level is found.
23885 Also, this function will be a lot faster than `outline-up-heading',
23886 because it relies on stars being the outline starters. This can really
23887 make a significant difference in outlines with very many siblings."
23888 (when (ignore-errors (org-back-to-heading t))
23889 (let ((level-up (1- (funcall outline-level))))
23890 (and (> level-up 0)
23891 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23892 (funcall outline-level)))))
23894 (defun org-first-sibling-p ()
23895 "Is this heading the first child of its parents?"
23896 (interactive)
23897 (let ((re org-outline-regexp-bol)
23898 level l)
23899 (unless (org-at-heading-p t)
23900 (user-error "Not at a heading"))
23901 (setq level (funcall outline-level))
23902 (save-excursion
23903 (if (not (re-search-backward re nil t))
23905 (setq l (funcall outline-level))
23906 (< l level)))))
23908 (defun org-goto-sibling (&optional previous)
23909 "Goto the next sibling, even if it is invisible.
23910 When PREVIOUS is set, go to the previous sibling instead. Returns t
23911 when a sibling was found. When none is found, return nil and don't
23912 move point."
23913 (let ((fun (if previous 're-search-backward 're-search-forward))
23914 (pos (point))
23915 (re org-outline-regexp-bol)
23916 level l)
23917 (when (ignore-errors (org-back-to-heading t))
23918 (setq level (funcall outline-level))
23919 (catch 'exit
23920 (or previous (forward-char 1))
23921 (while (funcall fun re nil t)
23922 (setq l (funcall outline-level))
23923 (when (< l level) (goto-char pos) (throw 'exit nil))
23924 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23925 (goto-char pos)
23926 nil))))
23928 (defun org-show-siblings ()
23929 "Show all siblings of the current headline."
23930 (save-excursion
23931 (while (org-goto-sibling) (org-flag-heading nil)))
23932 (save-excursion
23933 (while (org-goto-sibling 'previous)
23934 (org-flag-heading nil))))
23936 (defun org-goto-first-child ()
23937 "Goto the first child, even if it is invisible.
23938 Return t when a child was found. Otherwise don't move point and
23939 return nil."
23940 (let (level (pos (point)) (re org-outline-regexp-bol))
23941 (when (ignore-errors (org-back-to-heading t))
23942 (setq level (outline-level))
23943 (forward-char 1)
23944 (if (and (re-search-forward re nil t) (> (outline-level) level))
23945 (progn (goto-char (match-beginning 0)) t)
23946 (goto-char pos) nil))))
23948 (defun org-show-hidden-entry ()
23949 "Show an entry where even the heading is hidden."
23950 (save-excursion
23951 (org-show-entry)))
23953 (defun org-flag-heading (flag &optional entry)
23954 "Flag the current heading. FLAG non-nil means make invisible.
23955 When ENTRY is non-nil, show the entire entry."
23956 (save-excursion
23957 (org-back-to-heading t)
23958 ;; Check if we should show the entire entry
23959 (if entry
23960 (progn
23961 (org-show-entry)
23962 (save-excursion
23963 (and (outline-next-heading)
23964 (org-flag-heading nil))))
23965 (outline-flag-region (max (point-min) (1- (point)))
23966 (save-excursion (outline-end-of-heading) (point))
23967 flag))))
23969 (defun org-get-next-sibling ()
23970 "Move to next heading of the same level, and return point.
23971 If there is no such heading, return nil.
23972 This is like outline-next-sibling, but invisible headings are ok."
23973 (let ((level (funcall outline-level)))
23974 (outline-next-heading)
23975 (while (and (not (eobp)) (> (funcall outline-level) level))
23976 (outline-next-heading))
23977 (unless (or (eobp) (< (funcall outline-level) level))
23978 (point))))
23980 (defun org-get-last-sibling ()
23981 "Move to previous heading of the same level, and return point.
23982 If there is no such heading, return nil."
23983 (let ((opoint (point))
23984 (level (funcall outline-level)))
23985 (outline-previous-heading)
23986 (when (and (/= (point) opoint) (outline-on-heading-p t))
23987 (while (and (> (funcall outline-level) level)
23988 (not (bobp)))
23989 (outline-previous-heading))
23990 (unless (< (funcall outline-level) level)
23991 (point)))))
23993 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23994 "Goto to the end of a subtree."
23995 ;; This contains an exact copy of the original function, but it uses
23996 ;; `org-back-to-heading', to make it work also in invisible
23997 ;; trees. And is uses an invisible-ok argument.
23998 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23999 ;; Furthermore, when used inside Org, finding the end of a large subtree
24000 ;; with many children and grandchildren etc, this can be much faster
24001 ;; than the outline version.
24002 (org-back-to-heading invisible-ok)
24003 (let ((first t)
24004 (level (funcall outline-level)))
24005 (if (and (derived-mode-p 'org-mode) (< level 1000))
24006 ;; A true heading (not a plain list item), in Org
24007 ;; This means we can easily find the end by looking
24008 ;; only for the right number of stars. Using a regexp to do
24009 ;; this is so much faster than using a Lisp loop.
24010 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24011 (forward-char 1)
24012 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24013 ;; something else, do it the slow way
24014 (while (and (not (eobp))
24015 (or first (> (funcall outline-level) level)))
24016 (setq first nil)
24017 (outline-next-heading)))
24018 (unless to-heading
24019 (when (memq (preceding-char) '(?\n ?\^M))
24020 ;; Go to end of line before heading
24021 (forward-char -1)
24022 (when (memq (preceding-char) '(?\n ?\^M))
24023 ;; leave blank line before heading
24024 (forward-char -1)))))
24025 (point))
24027 (defun org-end-of-meta-data (&optional full)
24028 "Skip planning line and properties drawer in current entry.
24029 When optional argument FULL is non-nil, also skip empty lines,
24030 clocking lines and regular drawers at the beginning of the
24031 entry."
24032 (org-back-to-heading t)
24033 (forward-line)
24034 (when (looking-at-p org-planning-line-re) (forward-line))
24035 (when (looking-at org-property-drawer-re)
24036 (goto-char (match-end 0))
24037 (forward-line))
24038 (when (and full (not (org-at-heading-p)))
24039 (catch 'exit
24040 (let ((end (save-excursion (outline-next-heading) (point)))
24041 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24042 (while (not (eobp))
24043 (cond ((looking-at-p org-drawer-regexp)
24044 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24045 (forward-line)
24046 (throw 'exit t)))
24047 ((looking-at-p re) (forward-line))
24048 (t (throw 'exit t))))))))
24050 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24051 "Move forward to the ARG'th subheading at same level as this one.
24052 Stop at the first and last subheadings of a superior heading.
24053 Normally this only looks at visible headings, but when INVISIBLE-OK is
24054 non-nil it will also look at invisible ones."
24055 (interactive "p")
24056 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24057 (if (and arg (< arg 0))
24058 (goto-char (point-min))
24059 (outline-next-heading))
24060 (org-at-heading-p)
24061 (let ((level (- (match-end 0) (match-beginning 0) 1))
24062 (f (if (and arg (< arg 0))
24063 're-search-backward
24064 're-search-forward))
24065 (count (if arg (abs arg) 1))
24066 (result (point)))
24067 (while (and (prog1 (> count 0)
24068 (forward-char (if (and arg (< arg 0)) -1 1)))
24069 (funcall f org-outline-regexp-bol nil 'move))
24070 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24071 (cond ((< l level) (setq count 0))
24072 ((and (= l level)
24073 (or invisible-ok
24074 (progn
24075 (goto-char (line-beginning-position))
24076 (not (outline-invisible-p)))))
24077 (setq count (1- count))
24078 (when (eq l level)
24079 (setq result (point)))))))
24080 (goto-char result))
24081 (beginning-of-line 1)))
24083 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24084 "Move backward to the ARG'th subheading at same level as this one.
24085 Stop at the first and last subheadings of a superior heading."
24086 (interactive "p")
24087 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24089 (defun org-next-visible-heading (arg)
24090 "Move to the next visible heading.
24092 This function wraps `outline-next-visible-heading' with
24093 `org-with-limited-levels' in order to skip over inline tasks and
24094 respect customization of `org-odd-levels-only'."
24095 (interactive "p")
24096 (org-with-limited-levels
24097 (outline-next-visible-heading arg)))
24099 (defun org-previous-visible-heading (arg)
24100 "Move to the previous visible heading.
24102 This function wraps `outline-previous-visible-heading' with
24103 `org-with-limited-levels' in order to skip over inline tasks and
24104 respect customization of `org-odd-levels-only'."
24105 (interactive "p")
24106 (org-with-limited-levels
24107 (outline-previous-visible-heading arg)))
24109 (defun org-next-block (arg &optional backward block-regexp)
24110 "Jump to the next block.
24112 With a prefix argument ARG, jump forward ARG many blocks.
24114 When BACKWARD is non-nil, jump to the previous block.
24116 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24117 Match data is set according to this regexp when the function
24118 returns.
24120 Return point at beginning of the opening line of found block.
24121 Throw an error if no block is found."
24122 (interactive "p")
24123 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24124 (case-fold-search t)
24125 (search-fn (if backward #'re-search-backward #'re-search-forward))
24126 (count (or arg 1))
24127 (origin (point))
24128 last-element)
24129 (if backward (beginning-of-line) (end-of-line))
24130 (while (and (> count 0) (funcall search-fn re nil t))
24131 (let ((element (save-excursion
24132 (goto-char (match-beginning 0))
24133 (save-match-data (org-element-at-point)))))
24134 (when (and (memq (org-element-type element)
24135 '(center-block comment-block dynamic-block
24136 example-block export-block quote-block
24137 special-block src-block verse-block))
24138 (<= (match-beginning 0)
24139 (org-element-property :post-affiliated element)))
24140 (setq last-element element)
24141 (cl-decf count))))
24142 (if (= count 0)
24143 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24144 (save-match-data (org-show-context)))
24145 (goto-char origin)
24146 (user-error "No %s code blocks" (if backward "previous" "further")))))
24148 (defun org-previous-block (arg &optional block-regexp)
24149 "Jump to the previous block.
24150 With a prefix argument ARG, jump backward ARG many source blocks.
24151 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24152 (interactive "p")
24153 (org-next-block arg t block-regexp))
24155 (defun org-forward-paragraph ()
24156 "Move forward to beginning of next paragraph or equivalent.
24158 The function moves point to the beginning of the next visible
24159 structural element, which can be a paragraph, a table, a list
24160 item, etc. It also provides some special moves for convenience:
24162 - On an affiliated keyword, jump to the beginning of the
24163 relative element.
24164 - On an item or a footnote definition, move to the second
24165 element inside, if any.
24166 - On a table or a property drawer, jump after it.
24167 - On a verse or source block, stop after blank lines."
24168 (interactive)
24169 (when (eobp) (user-error "Cannot move further down"))
24170 (let* ((deactivate-mark nil)
24171 (element (org-element-at-point))
24172 (type (org-element-type element))
24173 (post-affiliated (org-element-property :post-affiliated element))
24174 (contents-begin (org-element-property :contents-begin element))
24175 (contents-end (org-element-property :contents-end element))
24176 (end (let ((end (org-element-property :end element)) (parent element))
24177 (while (and (setq parent (org-element-property :parent parent))
24178 (= (org-element-property :contents-end parent) end))
24179 (setq end (org-element-property :end parent)))
24180 end)))
24181 (cond ((not element)
24182 (skip-chars-forward " \r\t\n")
24183 (or (eobp) (beginning-of-line)))
24184 ;; On affiliated keywords, move to element's beginning.
24185 ((< (point) post-affiliated)
24186 (goto-char post-affiliated))
24187 ;; At a table row, move to the end of the table. Similarly,
24188 ;; at a node property, move to the end of the property
24189 ;; drawer.
24190 ((memq type '(node-property table-row))
24191 (goto-char (org-element-property
24192 :end (org-element-property :parent element))))
24193 ((memq type '(property-drawer table)) (goto-char end))
24194 ;; Consider blank lines as separators in verse and source
24195 ;; blocks to ease editing.
24196 ((memq type '(src-block verse-block))
24197 (when (eq type 'src-block)
24198 (setq contents-end
24199 (save-excursion (goto-char end)
24200 (skip-chars-backward " \r\t\n")
24201 (line-beginning-position))))
24202 (beginning-of-line)
24203 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24204 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24205 (goto-char end)
24206 (skip-chars-forward " \r\t\n")
24207 (if (= (point) contents-end) (goto-char end)
24208 (beginning-of-line))))
24209 ;; With no contents, just skip element.
24210 ((not contents-begin) (goto-char end))
24211 ;; If contents are invisible, skip the element altogether.
24212 ((outline-invisible-p (line-end-position))
24213 (cl-case type
24214 (headline
24215 (org-with-limited-levels (outline-next-visible-heading 1)))
24216 ;; At a plain list, make sure we move to the next item
24217 ;; instead of skipping the whole list.
24218 (plain-list (forward-char)
24219 (org-forward-paragraph))
24220 (otherwise (goto-char end))))
24221 ((>= (point) contents-end) (goto-char end))
24222 ((>= (point) contents-begin)
24223 ;; This can only happen on paragraphs and plain lists.
24224 (cl-case type
24225 (paragraph (goto-char end))
24226 ;; At a plain list, try to move to second element in
24227 ;; first item, if possible.
24228 (plain-list (end-of-line)
24229 (org-forward-paragraph))))
24230 ;; When contents start on the middle of a line (e.g. in
24231 ;; items and footnote definitions), try to reach first
24232 ;; element starting after current line.
24233 ((> (line-end-position) contents-begin)
24234 (end-of-line)
24235 (org-forward-paragraph))
24236 (t (goto-char contents-begin)))))
24238 (defun org-backward-paragraph ()
24239 "Move backward to start of previous paragraph or equivalent.
24241 The function moves point to the beginning of the current
24242 structural element, which can be a paragraph, a table, a list
24243 item, etc., or to the beginning of the previous visible one if
24244 point is already there. It also provides some special moves for
24245 convenience:
24247 - On an affiliated keyword, jump to the first one.
24248 - On a table or a property drawer, move to its beginning.
24249 - On a verse or source block, stop before blank lines."
24250 (interactive)
24251 (when (bobp) (user-error "Cannot move further up"))
24252 (let* ((deactivate-mark nil)
24253 (element (org-element-at-point))
24254 (type (org-element-type element))
24255 (contents-begin (org-element-property :contents-begin element))
24256 (contents-end (org-element-property :contents-end element))
24257 (post-affiliated (org-element-property :post-affiliated element))
24258 (begin (org-element-property :begin element)))
24259 (cond
24260 ((not element) (goto-char (point-min)))
24261 ((= (point) begin)
24262 (backward-char)
24263 (org-backward-paragraph))
24264 ((<= (point) post-affiliated) (goto-char begin))
24265 ((memq type '(node-property table-row))
24266 (goto-char (org-element-property
24267 :post-affiliated (org-element-property :parent element))))
24268 ((memq type '(property-drawer table)) (goto-char begin))
24269 ((memq type '(src-block verse-block))
24270 (when (eq type 'src-block)
24271 (setq contents-begin
24272 (save-excursion (goto-char begin) (forward-line) (point))))
24273 (if (= (point) contents-begin) (goto-char post-affiliated)
24274 ;; Inside a verse block, see blank lines as paragraph
24275 ;; separators.
24276 (let ((origin (point)))
24277 (skip-chars-backward " \r\t\n" contents-begin)
24278 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24279 (skip-chars-forward " \r\t\n" origin)
24280 (if (= (point) origin) (goto-char contents-begin)
24281 (beginning-of-line))))))
24282 ((not contents-begin) (goto-char (or post-affiliated begin)))
24283 ((eq type 'paragraph)
24284 (goto-char contents-begin)
24285 ;; When at first paragraph in an item or a footnote definition,
24286 ;; move directly to beginning of line.
24287 (let ((parent-contents
24288 (org-element-property
24289 :contents-begin (org-element-property :parent element))))
24290 (when (and parent-contents (= parent-contents contents-begin))
24291 (beginning-of-line))))
24292 ;; At the end of a greater element, move to the beginning of the
24293 ;; last element within.
24294 ((>= (point) contents-end)
24295 (goto-char (1- contents-end))
24296 (org-backward-paragraph))
24297 (t (goto-char (or post-affiliated begin))))
24298 ;; Ensure we never leave point invisible.
24299 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24301 (defun org-forward-element ()
24302 "Move forward by one element.
24303 Move to the next element at the same level, when possible."
24304 (interactive)
24305 (cond ((eobp) (user-error "Cannot move further down"))
24306 ((org-with-limited-levels (org-at-heading-p))
24307 (let ((origin (point)))
24308 (goto-char (org-end-of-subtree nil t))
24309 (unless (org-with-limited-levels (org-at-heading-p))
24310 (goto-char origin)
24311 (user-error "Cannot move further down"))))
24313 (let* ((elem (org-element-at-point))
24314 (end (org-element-property :end elem))
24315 (parent (org-element-property :parent elem)))
24316 (cond ((and parent (= (org-element-property :contents-end parent) end))
24317 (goto-char (org-element-property :end parent)))
24318 ((integer-or-marker-p end) (goto-char end))
24319 (t (message "No element at point")))))))
24321 (defun org-backward-element ()
24322 "Move backward by one element.
24323 Move to the previous element at the same level, when possible."
24324 (interactive)
24325 (cond ((bobp) (user-error "Cannot move further up"))
24326 ((org-with-limited-levels (org-at-heading-p))
24327 ;; At a headline, move to the previous one, if any, or stay
24328 ;; here.
24329 (let ((origin (point)))
24330 (org-with-limited-levels (org-backward-heading-same-level 1))
24331 ;; When current headline has no sibling above, move to its
24332 ;; parent.
24333 (when (= (point) origin)
24334 (or (org-with-limited-levels (org-up-heading-safe))
24335 (progn (goto-char origin)
24336 (user-error "Cannot move further up"))))))
24338 (let* ((elem (org-element-at-point))
24339 (beg (org-element-property :begin elem)))
24340 (cond
24341 ;; Move to beginning of current element if point isn't
24342 ;; there already.
24343 ((null beg) (message "No element at point"))
24344 ((/= (point) beg) (goto-char beg))
24345 (t (goto-char beg)
24346 (skip-chars-backward " \r\t\n")
24347 (unless (bobp)
24348 (let ((prev (org-element-at-point)))
24349 (goto-char (org-element-property :begin prev))
24350 (while (and (setq prev (org-element-property :parent prev))
24351 (<= (org-element-property :end prev) beg))
24352 (goto-char (org-element-property :begin prev)))))))))))
24354 (defun org-up-element ()
24355 "Move to upper element."
24356 (interactive)
24357 (if (org-with-limited-levels (org-at-heading-p))
24358 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24359 (let* ((elem (org-element-at-point))
24360 (parent (org-element-property :parent elem)))
24361 (if parent (goto-char (org-element-property :begin parent))
24362 (if (org-with-limited-levels (org-before-first-heading-p))
24363 (user-error "No surrounding element")
24364 (org-with-limited-levels (org-back-to-heading)))))))
24366 (defvar org-element-greater-elements)
24367 (defun org-down-element ()
24368 "Move to inner element."
24369 (interactive)
24370 (let ((element (org-element-at-point)))
24371 (cond
24372 ((memq (org-element-type element) '(plain-list table))
24373 (goto-char (org-element-property :contents-begin element))
24374 (forward-char))
24375 ((memq (org-element-type element) org-element-greater-elements)
24376 ;; If contents are hidden, first disclose them.
24377 (when (outline-invisible-p (line-end-position)) (org-cycle))
24378 (goto-char (or (org-element-property :contents-begin element)
24379 (user-error "No content for this element"))))
24380 (t (user-error "No inner element")))))
24382 (defun org-drag-element-backward ()
24383 "Move backward element at point."
24384 (interactive)
24385 (let ((elem (or (org-element-at-point)
24386 (user-error "No element at point"))))
24387 (if (eq (org-element-type elem) 'headline)
24388 ;; Preserve point when moving a whole tree, even if point was
24389 ;; on blank lines below the headline.
24390 (let ((offset (skip-chars-backward " \t\n")))
24391 (unwind-protect (org-move-subtree-up)
24392 (forward-char (- offset))))
24393 (let ((prev-elem
24394 (save-excursion
24395 (goto-char (org-element-property :begin elem))
24396 (skip-chars-backward " \r\t\n")
24397 (unless (bobp)
24398 (let* ((beg (org-element-property :begin elem))
24399 (prev (org-element-at-point))
24400 (up prev))
24401 (while (and (setq up (org-element-property :parent up))
24402 (<= (org-element-property :end up) beg))
24403 (setq prev up))
24404 prev)))))
24405 ;; Error out if no previous element or previous element is
24406 ;; a parent of the current one.
24407 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24408 (user-error "Cannot drag element backward")
24409 (let ((pos (point)))
24410 (org-element-swap-A-B prev-elem elem)
24411 (goto-char (+ (org-element-property :begin prev-elem)
24412 (- pos (org-element-property :begin elem))))))))))
24414 (defun org-drag-element-forward ()
24415 "Move forward element at point."
24416 (interactive)
24417 (let* ((pos (point))
24418 (elem (or (org-element-at-point)
24419 (user-error "No element at point"))))
24420 (when (= (point-max) (org-element-property :end elem))
24421 (user-error "Cannot drag element forward"))
24422 (goto-char (org-element-property :end elem))
24423 (let ((next-elem (org-element-at-point)))
24424 (when (or (org-element-nested-p elem next-elem)
24425 (and (eq (org-element-type next-elem) 'headline)
24426 (not (eq (org-element-type elem) 'headline))))
24427 (goto-char pos)
24428 (user-error "Cannot drag element forward"))
24429 ;; Compute new position of point: it's shifted by NEXT-ELEM
24430 ;; body's length (without final blanks) and by the length of
24431 ;; blanks between ELEM and NEXT-ELEM.
24432 (let ((size-next (- (save-excursion
24433 (goto-char (org-element-property :end next-elem))
24434 (skip-chars-backward " \r\t\n")
24435 (forward-line)
24436 ;; Small correction if buffer doesn't end
24437 ;; with a newline character.
24438 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24439 (org-element-property :begin next-elem)))
24440 (size-blank (- (org-element-property :end elem)
24441 (save-excursion
24442 (goto-char (org-element-property :end elem))
24443 (skip-chars-backward " \r\t\n")
24444 (forward-line)
24445 (point)))))
24446 (org-element-swap-A-B elem next-elem)
24447 (goto-char (+ pos size-next size-blank))))))
24449 (defun org-drag-line-forward (arg)
24450 "Drag the line at point ARG lines forward."
24451 (interactive "p")
24452 (dotimes (_ (abs arg))
24453 (let ((c (current-column)))
24454 (if (< 0 arg)
24455 (progn
24456 (beginning-of-line 2)
24457 (transpose-lines 1)
24458 (beginning-of-line 0))
24459 (transpose-lines 1)
24460 (beginning-of-line -1))
24461 (org-move-to-column c))))
24463 (defun org-drag-line-backward (arg)
24464 "Drag the line at point ARG lines backward."
24465 (interactive "p")
24466 (org-drag-line-forward (- arg)))
24468 (defun org-mark-element ()
24469 "Put point at beginning of this element, mark at end.
24471 Interactively, if this command is repeated or (in Transient Mark
24472 mode) if the mark is active, it marks the next element after the
24473 ones already marked."
24474 (interactive)
24475 (let (deactivate-mark)
24476 (if (and (called-interactively-p 'any)
24477 (or (and (eq last-command this-command) (mark t))
24478 (and transient-mark-mode mark-active)))
24479 (set-mark
24480 (save-excursion
24481 (goto-char (mark))
24482 (goto-char (org-element-property :end (org-element-at-point)))))
24483 (let ((element (org-element-at-point)))
24484 (end-of-line)
24485 (push-mark (org-element-property :end element) t t)
24486 (goto-char (org-element-property :begin element))))))
24488 (defun org-narrow-to-element ()
24489 "Narrow buffer to current element."
24490 (interactive)
24491 (let ((elem (org-element-at-point)))
24492 (cond
24493 ((eq (car elem) 'headline)
24494 (narrow-to-region
24495 (org-element-property :begin elem)
24496 (org-element-property :end elem)))
24497 ((memq (car elem) org-element-greater-elements)
24498 (narrow-to-region
24499 (org-element-property :contents-begin elem)
24500 (org-element-property :contents-end elem)))
24502 (narrow-to-region
24503 (org-element-property :begin elem)
24504 (org-element-property :end elem))))))
24506 (defun org-transpose-element ()
24507 "Transpose current and previous elements, keeping blank lines between.
24508 Point is moved after both elements."
24509 (interactive)
24510 (org-skip-whitespace)
24511 (let ((end (org-element-property :end (org-element-at-point))))
24512 (org-drag-element-backward)
24513 (goto-char end)))
24515 (defun org-unindent-buffer ()
24516 "Un-indent the visible part of the buffer.
24517 Relative indentation (between items, inside blocks, etc.) isn't
24518 modified."
24519 (interactive)
24520 (unless (eq major-mode 'org-mode)
24521 (user-error "Cannot un-indent a buffer not in Org mode"))
24522 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24523 (unindent-tree
24524 (lambda (contents)
24525 (dolist (element (reverse contents))
24526 (if (memq (org-element-type element) '(headline section))
24527 (funcall unindent-tree (org-element-contents element))
24528 (save-excursion
24529 (save-restriction
24530 (narrow-to-region
24531 (org-element-property :begin element)
24532 (org-element-property :end element))
24533 (org-do-remove-indentation))))))))
24534 (funcall unindent-tree (org-element-contents parse-tree))))
24536 (defun org-show-children (&optional level)
24537 "Show all direct subheadings of this heading.
24538 Prefix arg LEVEL is how many levels below the current level
24539 should be shown. Default is enough to cause the following
24540 heading to appear."
24541 (interactive "p")
24542 ;; If `orgstruct-mode' is active, use the slower version.
24543 (if orgstruct-mode (call-interactively #'outline-show-children)
24544 (save-excursion
24545 (org-back-to-heading t)
24546 (let* ((current-level (funcall outline-level))
24547 (max-level (org-get-valid-level
24548 current-level
24549 (if level (prefix-numeric-value level) 1)))
24550 (end (save-excursion (org-end-of-subtree t t)))
24551 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24552 (past-first-child nil)
24553 ;; Make sure to skip inlinetasks.
24554 (re (format regexp-fmt
24555 current-level
24556 (cond
24557 ((not (featurep 'org-inlinetask)) "")
24558 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24560 (t (1- org-inlinetask-min-level))))))
24561 ;; Display parent heading.
24562 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24563 (forward-line)
24564 ;; Display children. First child may be deeper than expected
24565 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24566 ;; MAX-LEVEL accordingly.
24567 (while (re-search-forward re end t)
24568 (unless past-first-child
24569 (setq re (format regexp-fmt
24570 current-level
24571 (max (funcall outline-level) max-level)))
24572 (setq past-first-child t))
24573 (outline-flag-region
24574 (line-end-position 0) (line-end-position) nil))))))
24576 (defun org-show-subtree ()
24577 "Show everything after this heading at deeper levels."
24578 (interactive)
24579 (outline-flag-region
24580 (point)
24581 (save-excursion
24582 (org-end-of-subtree t t))
24583 nil))
24585 (defun org-show-entry ()
24586 "Show the body directly following this heading.
24587 Show the heading too, if it is currently invisible."
24588 (interactive)
24589 (save-excursion
24590 (ignore-errors
24591 (org-back-to-heading t)
24592 (outline-flag-region
24593 (max (point-min) (1- (point)))
24594 (save-excursion
24595 (if (re-search-forward
24596 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24597 (match-beginning 1)
24598 (point-max)))
24599 nil)
24600 (org-cycle-hide-drawers 'children))))
24602 (defun org-make-options-regexp (kwds &optional extra)
24603 "Make a regular expression for keyword lines.
24604 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24605 when non-nil, is a regexp matching keywords names."
24606 (concat "^[ \t]*#\\+\\("
24607 (regexp-opt kwds)
24608 (and extra (concat (and kwds "\\|") extra))
24609 "\\):[ \t]*\\(.*\\)"))
24611 ;;;; Integration with and fixes for other packages
24613 ;;; Imenu support
24615 (defvar-local org-imenu-markers nil
24616 "All markers currently used by Imenu.")
24618 (defun org-imenu-new-marker (&optional pos)
24619 "Return a new marker for use by Imenu, and remember the marker."
24620 (let ((m (make-marker)))
24621 (move-marker m (or pos (point)))
24622 (push m org-imenu-markers)
24625 (defun org-imenu-get-tree ()
24626 "Produce the index for Imenu."
24627 (dolist (x org-imenu-markers) (move-marker x nil))
24628 (setq org-imenu-markers nil)
24629 (let* ((case-fold-search nil)
24630 (n org-imenu-depth)
24631 (re (concat "^" (org-get-limited-outline-regexp)))
24632 (subs (make-vector (1+ n) nil))
24633 (last-level 0)
24634 m level head0 head)
24635 (org-with-wide-buffer
24636 (goto-char (point-max))
24637 (while (re-search-backward re nil t)
24638 (setq level (org-reduced-level (funcall outline-level)))
24639 (when (and (<= level n)
24640 (looking-at org-complex-heading-regexp)
24641 (setq head0 (match-string-no-properties 4)))
24642 (setq head (org-link-display-format head0)
24643 m (org-imenu-new-marker))
24644 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24645 (if (>= level last-level)
24646 (push (cons head m) (aref subs level))
24647 (push (cons head (aref subs (1+ level))) (aref subs level))
24648 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24649 (setq last-level level))))
24650 (aref subs 1)))
24652 (eval-after-load "imenu"
24653 '(progn
24654 (add-hook 'imenu-after-jump-hook
24655 (lambda ()
24656 (when (derived-mode-p 'org-mode)
24657 (org-show-context 'org-goto))))))
24659 (defun org-link-display-format (s)
24660 "Replace links in string S with their description.
24661 If there is no description, use the link target."
24662 (save-match-data
24663 (replace-regexp-in-string
24664 org-bracket-link-analytic-regexp
24665 (lambda (m)
24666 (if (match-end 5) (match-string 5 m)
24667 (concat (match-string 1 m) (match-string 3 m))))
24668 s nil t)))
24670 (defun org-toggle-link-display ()
24671 "Toggle the literal or descriptive display of links."
24672 (interactive)
24673 (if org-descriptive-links
24674 (progn (org-remove-from-invisibility-spec '(org-link))
24675 (org-restart-font-lock)
24676 (setq org-descriptive-links nil))
24677 (progn (add-to-invisibility-spec '(org-link))
24678 (org-restart-font-lock)
24679 (setq org-descriptive-links t))))
24681 ;; Speedbar support
24683 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24684 "Overlay marking the agenda restriction line in speedbar.")
24685 (overlay-put org-speedbar-restriction-lock-overlay
24686 'face 'org-agenda-restriction-lock)
24687 (overlay-put org-speedbar-restriction-lock-overlay
24688 'help-echo "Agendas are currently limited to this item.")
24689 (delete-overlay org-speedbar-restriction-lock-overlay)
24691 (defun org-speedbar-set-agenda-restriction ()
24692 "Restrict future agenda commands to the location at point in speedbar.
24693 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24694 (interactive)
24695 (require 'org-agenda)
24696 (let (p m tp np dir txt)
24697 (cond
24698 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24699 'org-imenu t))
24700 (setq m (get-text-property p 'org-imenu-marker))
24701 (with-current-buffer (marker-buffer m)
24702 (goto-char m)
24703 (org-agenda-set-restriction-lock 'subtree)))
24704 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24705 'speedbar-function 'speedbar-find-file))
24706 (setq tp (previous-single-property-change
24707 (1+ p) 'speedbar-function)
24708 np (next-single-property-change
24709 tp 'speedbar-function)
24710 dir (speedbar-line-directory)
24711 txt (buffer-substring-no-properties (or tp (point-min))
24712 (or np (point-max))))
24713 (with-current-buffer (find-file-noselect
24714 (let ((default-directory dir))
24715 (expand-file-name txt)))
24716 (unless (derived-mode-p 'org-mode)
24717 (user-error "Cannot restrict to non-Org mode file"))
24718 (org-agenda-set-restriction-lock 'file)))
24719 (t (user-error "Don't know how to restrict Org mode agenda")))
24720 (move-overlay org-speedbar-restriction-lock-overlay
24721 (point-at-bol) (point-at-eol))
24722 (setq current-prefix-arg nil)
24723 (org-agenda-maybe-redo)))
24725 (defvar speedbar-file-key-map)
24726 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24727 (eval-after-load "speedbar"
24728 '(progn
24729 (speedbar-add-supported-extension ".org")
24730 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24731 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24732 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24733 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24734 (add-hook 'speedbar-visiting-tag-hook
24735 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24737 ;;; Fixes and Hacks for problems with other packages
24739 (defun org--flyspell-object-check-p (element)
24740 "Non-nil when Flyspell can check object at point.
24741 ELEMENT is the element at point."
24742 (let ((object (save-excursion
24743 (when (looking-at-p "\\>") (backward-char))
24744 (org-element-context element))))
24745 (cl-case (org-element-type object)
24746 ;; Prevent checks in links due to keybinding conflict with
24747 ;; Flyspell.
24748 ((code entity export-snippet inline-babel-call
24749 inline-src-block line-break latex-fragment link macro
24750 statistics-cookie target timestamp verbatim)
24751 nil)
24752 (footnote-reference
24753 ;; Only in inline footnotes, within the definition.
24754 (and (eq (org-element-property :type object) 'inline)
24755 (< (save-excursion
24756 (goto-char (org-element-property :begin object))
24757 (search-forward ":" nil t 2))
24758 (point))))
24759 (otherwise t))))
24761 (defun org-mode-flyspell-verify ()
24762 "Function used for `flyspell-generic-check-word-predicate'."
24763 (if (org-at-heading-p)
24764 ;; At a headline or an inlinetask, check title only. This is
24765 ;; faster than relying on `org-element-at-point'.
24766 (and (save-excursion (beginning-of-line)
24767 (and (let ((case-fold-search t))
24768 (not (looking-at-p "\\*+ END[ \t]*$")))
24769 (let ((case-fold-search nil))
24770 (looking-at org-complex-heading-regexp))))
24771 (match-beginning 4)
24772 (>= (point) (match-beginning 4))
24773 (or (not (match-beginning 5))
24774 (< (point) (match-beginning 5))))
24775 (let* ((element (org-element-at-point))
24776 (post-affiliated (org-element-property :post-affiliated element)))
24777 (cond
24778 ;; Ignore checks in all affiliated keywords but captions.
24779 ((< (point) post-affiliated)
24780 (and (save-excursion
24781 (beginning-of-line)
24782 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24783 (> (point) (match-end 0))
24784 (org--flyspell-object-check-p element)))
24785 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24786 ((let ((log (org-log-into-drawer)))
24787 (and log
24788 (let ((drawer (org-element-lineage element '(drawer))))
24789 (and drawer
24790 (eq (compare-strings
24791 log nil nil
24792 (org-element-property :drawer-name drawer) nil nil t)
24793 t)))))
24794 nil)
24796 (cl-case (org-element-type element)
24797 ((comment quote-section) t)
24798 (comment-block
24799 ;; Allow checks between block markers, not on them.
24800 (and (> (line-beginning-position) post-affiliated)
24801 (save-excursion
24802 (end-of-line)
24803 (skip-chars-forward " \r\t\n")
24804 (< (point) (org-element-property :end element)))))
24805 ;; Arbitrary list of keywords where checks are meaningful.
24806 ;; Make sure point is on the value part of the element.
24807 (keyword
24808 (and (member (org-element-property :key element)
24809 '("DESCRIPTION" "TITLE"))
24810 (save-excursion
24811 (search-backward ":" (line-beginning-position) t))))
24812 ;; Check is globally allowed in paragraphs verse blocks and
24813 ;; table rows (after affiliated keywords) but some objects
24814 ;; must not be affected.
24815 ((paragraph table-row verse-block)
24816 (let ((cbeg (org-element-property :contents-begin element))
24817 (cend (org-element-property :contents-end element)))
24818 (and cbeg (>= (point) cbeg) (< (point) cend)
24819 (org--flyspell-object-check-p element))))))))))
24820 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24822 (defun org-remove-flyspell-overlays-in (beg end)
24823 "Remove flyspell overlays in region."
24824 (and (bound-and-true-p flyspell-mode)
24825 (fboundp 'flyspell-delete-region-overlays)
24826 (flyspell-delete-region-overlays beg end)))
24828 (defvar flyspell-delayed-commands)
24829 (eval-after-load "flyspell"
24830 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24832 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24833 (eval-after-load "bookmark"
24834 '(if (boundp 'bookmark-after-jump-hook)
24835 ;; We can use the hook
24836 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24837 ;; Hook not available, use advice
24838 (defadvice bookmark-jump (after org-make-visible activate)
24839 "Make the position visible."
24840 (org-bookmark-jump-unhide))))
24842 ;; Make sure saveplace shows the location if it was hidden
24843 (eval-after-load "saveplace"
24844 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24845 "Make the position visible."
24846 (org-bookmark-jump-unhide)))
24848 ;; Make sure ecb shows the location if it was hidden
24849 (eval-after-load "ecb"
24850 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24851 "Make hierarchy visible when jumping into location from ECB tree buffer."
24852 (when (derived-mode-p 'org-mode)
24853 (org-show-context))))
24855 (defun org-bookmark-jump-unhide ()
24856 "Unhide the current position, to show the bookmark location."
24857 (and (derived-mode-p 'org-mode)
24858 (or (outline-invisible-p)
24859 (save-excursion (goto-char (max (point-min) (1- (point))))
24860 (outline-invisible-p)))
24861 (org-show-context 'bookmark-jump)))
24863 (defun org-mark-jump-unhide ()
24864 "Make the point visible with `org-show-context' after jumping to the mark."
24865 (when (and (derived-mode-p 'org-mode)
24866 (outline-invisible-p))
24867 (org-show-context 'mark-goto)))
24869 (eval-after-load "simple"
24870 '(defadvice pop-to-mark-command (after org-make-visible activate)
24871 "Make the point visible with `org-show-context'."
24872 (org-mark-jump-unhide)))
24874 (eval-after-load "simple"
24875 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24876 "Make the point visible with `org-show-context'."
24877 (org-mark-jump-unhide)))
24879 (eval-after-load "simple"
24880 '(defadvice pop-global-mark (after org-make-visible activate)
24881 "Make the point visible with `org-show-context'."
24882 (org-mark-jump-unhide)))
24884 ;; Make session.el ignore our circular variable
24885 (defvar session-globals-exclude)
24886 (eval-after-load "session"
24887 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24889 ;;;; Finish up
24891 (provide 'org)
24893 (run-hooks 'org-load-hook)
24895 ;;; org.el ends here