Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blob6df065294a1a66184edd016f194d39ae7c1057cb
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 "hledger" hledger)
272 (const :tag "IO" io)
273 (const :tag "J" J)
274 (const :tag "Java" java)
275 (const :tag "Javascript" js)
276 (const :tag "LaTeX" latex)
277 (const :tag "Ledger" ledger)
278 (const :tag "Lilypond" lilypond)
279 (const :tag "Lisp" lisp)
280 (const :tag "Makefile" makefile)
281 (const :tag "Maxima" maxima)
282 (const :tag "Matlab" matlab)
283 (const :tag "Mscgen" mscgen)
284 (const :tag "Ocaml" ocaml)
285 (const :tag "Octave" octave)
286 (const :tag "Org" org)
287 (const :tag "Perl" perl)
288 (const :tag "Pico Lisp" picolisp)
289 (const :tag "PlantUML" plantuml)
290 (const :tag "Python" python)
291 (const :tag "Ruby" ruby)
292 (const :tag "Sass" sass)
293 (const :tag "Scala" scala)
294 (const :tag "Scheme" scheme)
295 (const :tag "Screen" screen)
296 (const :tag "Shell Script" shell)
297 (const :tag "Shen" shen)
298 (const :tag "Sql" sql)
299 (const :tag "Sqlite" sqlite)
300 (const :tag "Stan" stan)
301 (const :tag "ebnf2ps" ebnf2ps))
302 :value-type (boolean :tag "Activate" :value t)))
304 ;;;; Customization variables
305 (defcustom org-clone-delete-id nil
306 "Remove ID property of clones of a subtree.
307 When non-nil, clones of a subtree don't inherit the ID property.
308 Otherwise they inherit the ID property with a new unique
309 identifier."
310 :type 'boolean
311 :version "24.1"
312 :group 'org-id)
314 ;;; Version
315 (org-check-version)
317 ;;;###autoload
318 (defun org-version (&optional here full message)
319 "Show the Org version.
320 Interactively, or when MESSAGE is non-nil, show it in echo area.
321 With prefix argument, or when HERE is non-nil, insert it at point.
322 In non-interactive uses, a reduced version string is output unless
323 FULL is given."
324 (interactive (list current-prefix-arg t (not current-prefix-arg)))
325 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
326 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
327 (load-suffixes (list ".el"))
328 (org-install-dir
329 (ignore-errors (org-find-library-dir "org-loaddefs"))))
330 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
331 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
332 (let* ((load-suffixes save-load-suffixes)
333 (release (org-release))
334 (git-version (org-git-version))
335 (version (format "Org mode version %s (%s @ %s)"
336 release
337 git-version
338 (if org-install-dir
339 (if (string= org-dir org-install-dir)
340 org-install-dir
341 (concat "mixed installation! "
342 org-install-dir
343 " and "
344 org-dir))
345 "org-loaddefs.el can not be found!")))
346 (version1 (if full version release)))
347 (when here (insert version1))
348 (when message (message "%s" version1))
349 version1)))
351 (defconst org-version (org-version))
354 ;;; Syntax Constants
356 ;;;; Block
358 (defconst org-block-regexp
359 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
360 "Regular expression for hiding blocks.")
362 (defconst org-dblock-start-re
363 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
364 "Matches the start line of a dynamic block, with parameters.")
366 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
367 "Matches the end of a dynamic block.")
369 ;;;; Clock and Planning
371 (defconst org-clock-string "CLOCK:"
372 "String used as prefix for timestamps clocking work hours on an item.")
374 (defvar org-closed-string "CLOSED:"
375 "String used as the prefix for timestamps logging closing a TODO entry.")
377 (defvar org-deadline-string "DEADLINE:"
378 "String to mark deadline entries.
379 \\<org-mode-map>
380 A deadline is this string, followed by a time stamp. It must be
381 a word, terminated by a colon. You can insert a schedule keyword
382 and a timestamp with `\\[org-deadline]'.")
384 (defvar org-scheduled-string "SCHEDULED:"
385 "String to mark scheduled TODO entries.
386 \\<org-mode-map>
387 A schedule is this string, followed by a time stamp. It must be
388 a word, terminated by a colon. You can insert a schedule keyword
389 and a timestamp with `\\[org-schedule]'.")
391 (defconst org-ds-keyword-length
392 (+ 2
393 (apply #'max
394 (mapcar #'length
395 (list org-deadline-string org-scheduled-string
396 org-clock-string org-closed-string))))
397 "Maximum length of the DEADLINE and SCHEDULED keywords.")
399 (defconst org-planning-line-re
400 (concat "^[ \t]*"
401 (regexp-opt
402 (list org-closed-string org-deadline-string org-scheduled-string)
404 "Matches a line with planning info.
405 Matched keyword is in group 1.")
407 (defconst org-clock-line-re
408 (concat "^[ \t]*" org-clock-string)
409 "Matches a line with clock info.")
411 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
412 "Matches the DEADLINE keyword.")
414 (defconst org-deadline-time-regexp
415 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
416 "Matches the DEADLINE keyword together with a time stamp.")
418 (defconst org-deadline-time-hour-regexp
419 (concat "\\<" org-deadline-string
420 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
421 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
423 (defconst org-deadline-line-regexp
424 (concat "\\<\\(" org-deadline-string "\\).*")
425 "Matches the DEADLINE keyword and the rest of the line.")
427 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
428 "Matches the SCHEDULED keyword.")
430 (defconst org-scheduled-time-regexp
431 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
432 "Matches the SCHEDULED keyword together with a time stamp.")
434 (defconst org-scheduled-time-hour-regexp
435 (concat "\\<" org-scheduled-string
436 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
437 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
439 (defconst org-closed-time-regexp
440 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
441 "Matches the CLOSED keyword together with a time stamp.")
443 (defconst org-keyword-time-regexp
444 (concat "\\<"
445 (regexp-opt
446 (list org-scheduled-string org-deadline-string org-closed-string
447 org-clock-string)
449 " *[[<]\\([^]>]+\\)[]>]")
450 "Matches any of the 4 keywords, together with the time stamp.")
452 (defconst org-keyword-time-not-clock-regexp
453 (concat
454 "\\<"
455 (regexp-opt
456 (list org-scheduled-string org-deadline-string org-closed-string) t)
457 " *[[<]\\([^]>]+\\)[]>]")
458 "Matches any of the 3 keywords, together with the time stamp.")
460 (defconst org-maybe-keyword-time-regexp
461 (concat "\\(\\<"
462 (regexp-opt
463 (list org-scheduled-string org-deadline-string org-closed-string
464 org-clock-string)
466 "\\)?"
467 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
468 "\\|"
469 "<%%([^\r\n>]*>\\)")
470 "Matches a timestamp, possibly preceded by a keyword.")
472 (defconst org-all-time-keywords
473 (mapcar (lambda (w) (substring w 0 -1))
474 (list org-scheduled-string org-deadline-string
475 org-clock-string org-closed-string))
476 "List of time keywords.")
478 ;;;; Drawer
480 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
481 "Matches first or last line of a hidden block.
482 Group 1 contains drawer's name or \"END\".")
484 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
485 "Regular expression matching the first line of a property drawer.")
487 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
488 "Regular expression matching the last line of a property drawer.")
490 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
491 "Regular expression matching the first line of a clock drawer.")
493 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
494 "Regular expression matching the last line of a clock drawer.")
496 (defconst org-property-drawer-re
497 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
498 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
499 "[ \t]*:END:[ \t]*$")
500 "Matches an entire property drawer.")
502 (defconst org-clock-drawer-re
503 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
504 org-clock-drawer-end-re "\\)\n?")
505 "Matches an entire clock drawer.")
507 ;;;; Headline
509 (defconst org-heading-keyword-regexp-format
510 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
511 "Printf format for a regexp matching a headline with some keyword.
512 This regexp will match the headline of any node which has the
513 exact keyword that is put into the format. The keyword isn't in
514 any group by default, but the stars and the body are.")
516 (defconst org-heading-keyword-maybe-regexp-format
517 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
518 "Printf format for a regexp matching a headline, possibly with some keyword.
519 This regexp can match any headline with the specified keyword, or
520 without a keyword. The keyword isn't in any group by default,
521 but the stars and the body are.")
523 (defconst org-archive-tag "ARCHIVE"
524 "The tag that marks a subtree as archived.
525 An archived subtree does not open during visibility cycling, and does
526 not contribute to the agenda listings.")
528 (defconst org-comment-string "COMMENT"
529 "Entries starting with this keyword will never be exported.
530 \\<org-mode-map>
531 An entry can be toggled between COMMENT and normal with
532 `\\[org-toggle-comment]'.")
535 ;;;; LaTeX Environments and Fragments
537 (defconst org-latex-regexps
538 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
539 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
540 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
541 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
542 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
543 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
544 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
545 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
546 "Regular expressions for matching embedded LaTeX.")
548 ;;;; Node Property
550 (defconst org-effort-property "Effort"
551 "The property that is being used to keep track of effort estimates.
552 Effort estimates given in this property need to have the format H:MM.")
554 ;;;; Table
556 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
557 "Detect an org-type or table-type table.")
559 (defconst org-table-line-regexp "^[ \t]*|"
560 "Detect an org-type table line.")
562 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
563 "Detect an org-type table line.")
565 (defconst org-table-hline-regexp "^[ \t]*|-"
566 "Detect an org-type table hline.")
568 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
569 "Detect a table-type table hline.")
571 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
572 "Detect the first line outside a table when searching from within it.
573 This works for both table types.")
575 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
576 "Detect a #+TBLFM line.")
578 ;;;; Timestamp
580 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
581 "Regular expression for fast time stamp matching.")
583 (defconst org-ts-regexp-inactive
584 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
585 "Regular expression for fast inactive time stamp matching.")
587 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
588 "Regular expression for fast time stamp matching.")
590 (defconst org-ts-regexp0
591 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
592 "Regular expression matching time strings for analysis.
593 This one does not require the space after the date, so it can be used
594 on a string that terminates immediately after the date.")
596 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
597 "Regular expression matching time strings for analysis.")
599 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
600 "Regular expression matching time stamps, with groups.")
602 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
603 "Regular expression matching time stamps (also [..]), with groups.")
605 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
606 "Regular expression matching a time stamp range.")
608 (defconst org-tr-regexp-both
609 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
610 "Regular expression matching a time stamp range.")
612 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
613 org-ts-regexp "\\)?")
614 "Regular expression matching a time stamp or time stamp range.")
616 (defconst org-tsr-regexp-both
617 (concat org-ts-regexp-both "\\(--?-?"
618 org-ts-regexp-both "\\)?")
619 "Regular expression matching a time stamp or time stamp range.
620 The time stamps may be either active or inactive.")
622 (defconst org-repeat-re
623 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
624 "Regular expression for specifying repeated events.
625 After a match, group 1 contains the repeat expression.")
627 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
628 "Formats for `format-time-string' which are used for time stamps.")
631 ;;; The custom variables
633 (defgroup org nil
634 "Outline-based notes management and organizer."
635 :tag "Org"
636 :group 'outlines
637 :group 'calendar)
639 (defcustom org-mode-hook nil
640 "Mode hook for Org mode, run after the mode was turned on."
641 :group 'org
642 :type 'hook)
644 (defcustom org-load-hook nil
645 "Hook that is run after org.el has been loaded."
646 :group 'org
647 :type 'hook)
649 (defcustom org-log-buffer-setup-hook nil
650 "Hook that is run after an Org log buffer is created."
651 :group 'org
652 :version "24.1"
653 :type 'hook)
655 (defvar org-modules) ; defined below
656 (defvar org-modules-loaded nil
657 "Have the modules been loaded already?")
659 (defun org-load-modules-maybe (&optional force)
660 "Load all extensions listed in `org-modules'."
661 (when (or force (not org-modules-loaded))
662 (dolist (ext org-modules)
663 (condition-case nil (require ext)
664 (error (message "Problems while trying to load feature `%s'" ext))))
665 (setq org-modules-loaded t)))
667 (defun org-set-modules (var value)
668 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
669 (set var value)
670 (when (featurep 'org)
671 (org-load-modules-maybe 'force)
672 (org-element-cache-reset 'all)))
674 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
675 "Modules that should always be loaded together with org.el.
677 If a description starts with <C>, the file is not part of Emacs
678 and loading it will require that you have downloaded and properly
679 installed the Org mode distribution.
681 You can also use this system to load external packages (i.e. neither Org
682 core modules, nor modules from the CONTRIB directory). Just add symbols
683 to the end of the list. If the package is called org-xyz.el, then you need
684 to add the symbol `xyz', and the package must have a call to:
686 (provide \\='org-xyz)
688 For export specific modules, see also `org-export-backends'."
689 :group 'org
690 :set 'org-set-modules
691 :version "24.4"
692 :package-version '(Org . "8.0")
693 :type
694 '(set :greedy t
695 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
696 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
697 (const :tag " crypt: Encryption of subtrees" org-crypt)
698 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
699 (const :tag " docview: Links to doc-view buffers" org-docview)
700 (const :tag " eww: Store link to url of eww" org-eww)
701 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
702 (const :tag " habit: Track your consistency with habits" org-habit)
703 (const :tag " id: Global IDs for identifying entries" org-id)
704 (const :tag " info: Links to Info nodes" org-info)
705 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
706 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
707 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
708 (const :tag " mouse: Additional mouse support" org-mouse)
709 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
710 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
711 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
713 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
714 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
715 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
716 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
717 (const :tag "C collector: Collect properties into tables" org-collector)
718 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
719 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
720 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
721 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
722 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
723 (const :tag "C eval: Include command output as text" org-eval)
724 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
725 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
726 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
727 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
728 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
729 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
730 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
731 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
732 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
733 (const :tag "C man: Support for links to manpages in Org mode" org-man)
734 (const :tag "C mew: Links to Mew folders/messages" org-mew)
735 (const :tag "C mtags: Support for muse-like tags" org-mtags)
736 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
737 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
738 (const :tag "C registry: A registry for Org links" org-registry)
739 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
740 (const :tag "C secretary: Team management with org-mode" org-secretary)
741 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
742 (const :tag "C toc: Table of contents for Org buffer" org-toc)
743 (const :tag "C track: Keep up with Org mode development" org-track)
744 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
745 (const :tag "C vm: Links to VM folders/messages" org-vm)
746 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
747 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
748 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
750 (defvar org-export-registered-backends) ; From ox.el.
751 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
752 (declare-function org-export-backend-name "ox" (backend) t)
753 (defcustom org-export-backends '(ascii html icalendar latex odt)
754 "List of export back-ends that should be always available.
756 If a description starts with <C>, the file is not part of Emacs
757 and loading it will require that you have downloaded and properly
758 installed the Org mode distribution.
760 Unlike to `org-modules', libraries in this list will not be
761 loaded along with Org, but only once the export framework is
762 needed.
764 This variable needs to be set before org.el is loaded. If you
765 need to make a change while Emacs is running, use the customize
766 interface or run the following code, where VAL stands for the new
767 value of the variable, after updating it:
769 (progn
770 (setq org-export-registered-backends
771 (cl-remove-if-not
772 (lambda (backend)
773 (let ((name (org-export-backend-name backend)))
774 (or (memq name val)
775 (catch \\='parentp
776 (dolist (b val)
777 (and (org-export-derived-backend-p b name)
778 (throw \\='parentp t)))))))
779 org-export-registered-backends))
780 (let ((new-list (mapcar #\\='org-export-backend-name
781 org-export-registered-backends)))
782 (dolist (backend val)
783 (cond
784 ((not (load (format \"ox-%s\" backend) t t))
785 (message \"Problems while trying to load export back-end \\=`%s\\='\"
786 backend))
787 ((not (memq backend new-list)) (push backend new-list))))
788 (set-default \\='org-export-backends new-list)))
790 Adding a back-end to this list will also pull the back-end it
791 depends on, if any."
792 :group 'org
793 :group 'org-export
794 :version "26.1"
795 :package-version '(Org . "9.0")
796 :initialize 'custom-initialize-set
797 :set (lambda (var val)
798 (if (not (featurep 'ox)) (set-default var val)
799 ;; Any back-end not required anymore (not present in VAL and not
800 ;; a parent of any back-end in the new value) is removed from the
801 ;; list of registered back-ends.
802 (setq org-export-registered-backends
803 (cl-remove-if-not
804 (lambda (backend)
805 (let ((name (org-export-backend-name backend)))
806 (or (memq name val)
807 (catch 'parentp
808 (dolist (b val)
809 (and (org-export-derived-backend-p b name)
810 (throw 'parentp t)))))))
811 org-export-registered-backends))
812 ;; Now build NEW-LIST of both new back-ends and required
813 ;; parents.
814 (let ((new-list (mapcar #'org-export-backend-name
815 org-export-registered-backends)))
816 (dolist (backend val)
817 (cond
818 ((not (load (format "ox-%s" backend) t t))
819 (message "Problems while trying to load export back-end `%s'"
820 backend))
821 ((not (memq backend new-list)) (push backend new-list))))
822 ;; Set VAR to that list with fixed dependencies.
823 (set-default var new-list))))
824 :type '(set :greedy t
825 (const :tag " ascii Export buffer to ASCII format" ascii)
826 (const :tag " beamer Export buffer to Beamer presentation" beamer)
827 (const :tag " html Export buffer to HTML format" html)
828 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
829 (const :tag " latex Export buffer to LaTeX format" latex)
830 (const :tag " man Export buffer to MAN format" man)
831 (const :tag " md Export buffer to Markdown format" md)
832 (const :tag " odt Export buffer to ODT format" odt)
833 (const :tag " org Export buffer to Org format" org)
834 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
835 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
836 (const :tag "C deck Export buffer to deck.js presentations" deck)
837 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
838 (const :tag "C groff Export buffer to Groff format" groff)
839 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
840 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
841 (const :tag "C s5 Export buffer to s5 presentations" s5)
842 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
844 (eval-after-load 'ox
845 '(dolist (backend org-export-backends)
846 (condition-case nil (require (intern (format "ox-%s" backend)))
847 (error (message "Problems while trying to load export back-end `%s'"
848 backend)))))
850 (defcustom org-support-shift-select nil
851 "Non-nil means make shift-cursor commands select text when possible.
852 \\<org-mode-map>\
854 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
855 start selecting a region, or enlarge regions started in this way.
856 In Org mode, in special contexts, these same keys are used for
857 other purposes, important enough to compete with shift selection.
858 Org tries to balance these needs by supporting `shift-select-mode'
859 outside these special contexts, under control of this variable.
861 The default of this variable is nil, to avoid confusing behavior. Shifted
862 cursor keys will then execute Org commands in the following contexts:
863 - on a headline, changing TODO state (left/right) and priority (up/down)
864 - on a time stamp, changing the time
865 - in a plain list item, changing the bullet type
866 - in a property definition line, switching between allowed values
867 - in the BEGIN line of a clock table (changing the time block).
868 Outside these contexts, the commands will throw an error.
870 When this variable is t and the cursor is not in a special
871 context, Org mode will support shift-selection for making and
872 enlarging regions. To make this more effective, the bullet
873 cycling will no longer happen anywhere in an item line, but only
874 if the cursor is exactly on the bullet.
876 If you set this variable to the symbol `always', then the keys
877 will not be special in headlines, property lines, and item lines,
878 to make shift selection work there as well. If this is what you
879 want, you can use the following alternative commands:
880 `\\[org-todo]' and `\\[org-priority]' \
881 to change TODO state and priority,
882 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
883 can be used to switch TODO sets,
884 `\\[org-ctrl-c-minus]' to cycle item bullet types,
885 and properties can be edited by hand or in column view.
887 However, when the cursor is on a timestamp, shift-cursor commands
888 will still edit the time stamp - this is just too good to give up."
889 :group 'org
890 :type '(choice
891 (const :tag "Never" nil)
892 (const :tag "When outside special context" t)
893 (const :tag "Everywhere except timestamps" always)))
895 (defcustom org-loop-over-headlines-in-active-region nil
896 "Shall some commands act upon headlines in the active region?
898 When set to t, some commands will be performed in all headlines
899 within the active region.
901 When set to `start-level', some commands will be performed in all
902 headlines within the active region, provided that these headlines
903 are of the same level than the first one.
905 When set to a string, those commands will be performed on the
906 matching headlines within the active region. Such string must be
907 a tags/property/todo match as it is used in the agenda tags view.
909 The list of commands is: `org-schedule', `org-deadline',
910 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
911 `org-archive-to-archive-sibling'. The archiving commands skip
912 already archived entries."
913 :type '(choice (const :tag "Don't loop" nil)
914 (const :tag "All headlines in active region" t)
915 (const :tag "In active region, headlines at the same level than the first one" start-level)
916 (string :tag "Tags/Property/Todo matcher"))
917 :version "24.1"
918 :group 'org-todo
919 :group 'org-archive)
921 (defgroup org-startup nil
922 "Options concerning startup of Org mode."
923 :tag "Org Startup"
924 :group 'org)
926 (defcustom org-startup-folded t
927 "Non-nil means entering Org mode will switch to OVERVIEW.
929 This can also be configured on a per-file basis by adding one of
930 the following lines anywhere in the buffer:
932 #+STARTUP: fold (or `overview', this is equivalent)
933 #+STARTUP: nofold (or `showall', this is equivalent)
934 #+STARTUP: content
935 #+STARTUP: showeverything
937 Set `org-agenda-inhibit-startup' to a non-nil value if you want
938 to ignore this option when Org opens agenda files for the first
939 time."
940 :group 'org-startup
941 :type '(choice
942 (const :tag "nofold: show all" nil)
943 (const :tag "fold: overview" t)
944 (const :tag "content: all headlines" content)
945 (const :tag "show everything, even drawers" showeverything)))
947 (defcustom org-startup-truncated t
948 "Non-nil means entering Org mode will set `truncate-lines'.
949 This is useful since some lines containing links can be very long and
950 uninteresting. Also tables look terrible when wrapped.
952 The variable `org-startup-truncated' allows to configure
953 truncation for Org mode different to the other modes that use the
954 variable `truncate-lines' and as a shortcut instead of putting
955 the variable `truncate-lines' into the `org-mode-hook'. If one
956 wants to configure truncation for Org mode not statically but
957 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
958 the variable `truncate-lines' has to be used because in such a
959 case it is too late to set the variable `org-startup-truncated'."
960 :group 'org-startup
961 :type 'boolean)
963 (defcustom org-startup-indented nil
964 "Non-nil means turn on `org-indent-mode' on startup.
965 This can also be configured on a per-file basis by adding one of
966 the following lines anywhere in the buffer:
968 #+STARTUP: indent
969 #+STARTUP: noindent"
970 :group 'org-structure
971 :type '(choice
972 (const :tag "Not" nil)
973 (const :tag "Globally (slow on startup in large files)" t)))
975 (defcustom org-use-sub-superscripts t
976 "Non-nil means interpret \"_\" and \"^\" for display.
978 If you want to control how Org exports those characters, see
979 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
980 used to be an alias for `org-export-with-sub-superscripts' in
981 Org <8.0, it is not anymore.
983 When this option is turned on, you can use TeX-like syntax for
984 sub- and superscripts within the buffer. Several characters after
985 \"_\" or \"^\" will be considered as a single item - so grouping
986 with {} is normally not needed. For example, the following things
987 will be parsed as single sub- or superscripts:
989 10^24 or 10^tau several digits will be considered 1 item.
990 10^-12 or 10^-tau a leading sign with digits or a word
991 x^2-y^3 will be read as x^2 - y^3, because items are
992 terminated by almost any nonword/nondigit char.
993 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
995 Still, ambiguity is possible. So when in doubt, use {} to enclose
996 the sub/superscript. If you set this variable to the symbol `{}',
997 the braces are *required* in order to trigger interpretations as
998 sub/superscript. This can be helpful in documents that need \"_\"
999 frequently in plain text."
1000 :group 'org-startup
1001 :version "24.4"
1002 :package-version '(Org . "8.0")
1003 :type '(choice
1004 (const :tag "Always interpret" t)
1005 (const :tag "Only with braces" {})
1006 (const :tag "Never interpret" nil)))
1008 (defcustom org-startup-with-beamer-mode nil
1009 "Non-nil means turn on `org-beamer-mode' on startup.
1010 This can also be configured on a per-file basis by adding one of
1011 the following lines anywhere in the buffer:
1013 #+STARTUP: beamer"
1014 :group 'org-startup
1015 :version "24.1"
1016 :type 'boolean)
1018 (defcustom org-startup-align-all-tables nil
1019 "Non-nil means align all tables when visiting a file.
1020 This is useful when the column width in tables is forced with <N> cookies
1021 in table fields. Such tables will look correct only after the first re-align.
1022 This can also be configured on a per-file basis by adding one of
1023 the following lines anywhere in the buffer:
1024 #+STARTUP: align
1025 #+STARTUP: noalign"
1026 :group 'org-startup
1027 :type 'boolean)
1029 (defcustom org-startup-with-inline-images nil
1030 "Non-nil means show inline images when loading a new Org file.
1031 This can also be configured on a per-file basis by adding one of
1032 the following lines anywhere in the buffer:
1033 #+STARTUP: inlineimages
1034 #+STARTUP: noinlineimages"
1035 :group 'org-startup
1036 :version "24.1"
1037 :type 'boolean)
1039 (defcustom org-startup-with-latex-preview nil
1040 "Non-nil means preview LaTeX fragments when loading a new Org file.
1042 This can also be configured on a per-file basis by adding one of
1043 the following lines anywhere in the buffer:
1044 #+STARTUP: latexpreview
1045 #+STARTUP: nolatexpreview"
1046 :group 'org-startup
1047 :version "24.4"
1048 :package-version '(Org . "8.0")
1049 :type 'boolean)
1051 (defcustom org-insert-mode-line-in-empty-file nil
1052 "Non-nil means insert the first line setting Org mode in empty files.
1053 When the function `org-mode' is called interactively in an empty file, this
1054 normally means that the file name does not automatically trigger Org mode.
1055 To ensure that the file will always be in Org mode in the future, a
1056 line enforcing Org mode will be inserted into the buffer, if this option
1057 has been set."
1058 :group 'org-startup
1059 :type 'boolean)
1061 (defcustom org-replace-disputed-keys nil
1062 "Non-nil means use alternative key bindings for some keys.
1063 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1064 These keys are also used by other packages like shift-selection-mode'
1065 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1066 If you want to use Org mode together with one of these other modes,
1067 or more generally if you would like to move some Org mode commands to
1068 other keys, set this variable and configure the keys with the variable
1069 `org-disputed-keys'.
1071 This option is only relevant at load-time of Org mode, and must be set
1072 *before* org.el is loaded. Changing it requires a restart of Emacs to
1073 become effective."
1074 :group 'org-startup
1075 :type 'boolean)
1077 (defcustom org-use-extra-keys nil
1078 "Non-nil means use extra key sequence definitions for certain commands.
1079 This happens automatically if `window-system' is nil. This
1080 variable lets you do the same manually. You must set it before
1081 loading Org."
1082 :group 'org-startup
1083 :type 'boolean)
1085 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1087 (defcustom org-disputed-keys
1088 '(([(shift up)] . [(meta p)])
1089 ([(shift down)] . [(meta n)])
1090 ([(shift left)] . [(meta -)])
1091 ([(shift right)] . [(meta +)])
1092 ([(control shift right)] . [(meta shift +)])
1093 ([(control shift left)] . [(meta shift -)]))
1094 "Keys for which Org mode and other modes compete.
1095 This is an alist, cars are the default keys, second element specifies
1096 the alternative to use when `org-replace-disputed-keys' is t.
1098 Keys can be specified in any syntax supported by `define-key'.
1099 The value of this option takes effect only at Org mode startup,
1100 therefore you'll have to restart Emacs to apply it after changing."
1101 :group 'org-startup
1102 :type 'alist)
1104 (defun org-key (key)
1105 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1106 Or return the original if not disputed."
1107 (when org-replace-disputed-keys
1108 (let* ((nkey (key-description key))
1109 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1110 org-disputed-keys)))
1111 (setq key (if x (cdr x) key))))
1112 key)
1114 (defun org-defkey (keymap key def)
1115 "Define a key, possibly translated, as returned by `org-key'."
1116 (define-key keymap (org-key key) def))
1118 (defcustom org-ellipsis nil
1119 "The ellipsis to use in the Org mode outline.
1121 When nil, just use the standard three dots.
1122 When a string, use that string instead.
1124 The change affects only Org mode (which will then use its own display table).
1125 Changing this requires executing `\\[org-mode]' in a buffer to become
1126 effective."
1127 :group 'org-startup
1128 :type '(choice (const :tag "Default" nil)
1129 (string :tag "String" :value "...#"))
1130 :safe #'string-or-null-p)
1132 (defvar org-display-table nil
1133 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1135 (defgroup org-keywords nil
1136 "Keywords in Org mode."
1137 :tag "Org Keywords"
1138 :group 'org)
1140 (defcustom org-closed-keep-when-no-todo nil
1141 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1142 :group 'org-todo
1143 :group 'org-keywords
1144 :version "24.4"
1145 :package-version '(Org . "8.0")
1146 :type 'boolean)
1148 (defgroup org-structure nil
1149 "Options concerning the general structure of Org files."
1150 :tag "Org Structure"
1151 :group 'org)
1153 (defgroup org-reveal-location nil
1154 "Options about how to make context of a location visible."
1155 :tag "Org Reveal Location"
1156 :group 'org-structure)
1158 (defcustom org-show-context-detail '((agenda . local)
1159 (bookmark-jump . lineage)
1160 (isearch . lineage)
1161 (default . ancestors))
1162 "Alist between context and visibility span when revealing a location.
1164 \\<org-mode-map>Some actions may move point into invisible
1165 locations. As a consequence, Org always expose a neighborhood
1166 around point. How much is shown depends on the initial action,
1167 or context. Valid contexts are
1169 agenda when exposing an entry from the agenda
1170 org-goto when using the command `org-goto' (`\\[org-goto]')
1171 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1172 tags-tree when constructing a sparse tree based on tags matches
1173 link-search when exposing search matches associated with a link
1174 mark-goto when exposing the jump goal of a mark
1175 bookmark-jump when exposing a bookmark location
1176 isearch when exiting from an incremental search
1177 default default for all contexts not set explicitly
1179 Allowed visibility spans are
1181 minimal show current headline; if point is not on headline,
1182 also show entry
1184 local show current headline, entry and next headline
1186 ancestors show current headline and its direct ancestors; if
1187 point is not on headline, also show entry
1189 lineage show current headline, its direct ancestors and all
1190 their children; if point is not on headline, also show
1191 entry and first child
1193 tree show current headline, its direct ancestors and all
1194 their children; if point is not on headline, also show
1195 entry and all children
1197 canonical show current headline, its direct ancestors along with
1198 their entries and children; if point is not located on
1199 the headline, also show current entry and all children
1201 As special cases, a nil or t value means show all contexts in
1202 `minimal' or `canonical' view, respectively.
1204 Some views can make displayed information very compact, but also
1205 make it harder to edit the location of the match. In such
1206 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1207 more context."
1208 :group 'org-reveal-location
1209 :version "26.1"
1210 :package-version '(Org . "9.0")
1211 :type '(choice
1212 (const :tag "Canonical" t)
1213 (const :tag "Minimal" nil)
1214 (repeat :greedy t :tag "Individual contexts"
1215 (cons
1216 (choice :tag "Context"
1217 (const agenda)
1218 (const org-goto)
1219 (const occur-tree)
1220 (const tags-tree)
1221 (const link-search)
1222 (const mark-goto)
1223 (const bookmark-jump)
1224 (const isearch)
1225 (const default))
1226 (choice :tag "Detail level"
1227 (const minimal)
1228 (const local)
1229 (const ancestors)
1230 (const lineage)
1231 (const tree)
1232 (const canonical))))))
1234 (defcustom org-indirect-buffer-display 'other-window
1235 "How should indirect tree buffers be displayed?
1237 This applies to indirect buffers created with the commands
1238 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1240 Valid values are:
1241 current-window Display in the current window
1242 other-window Just display in another window.
1243 dedicated-frame Create one new frame, and re-use it each time.
1244 new-frame Make a new frame each time. Note that in this case
1245 previously-made indirect buffers are kept, and you need to
1246 kill these buffers yourself."
1247 :group 'org-structure
1248 :group 'org-agenda-windows
1249 :type '(choice
1250 (const :tag "In current window" current-window)
1251 (const :tag "In current frame, other window" other-window)
1252 (const :tag "Each time a new frame" new-frame)
1253 (const :tag "One dedicated frame" dedicated-frame)))
1255 (defcustom org-use-speed-commands nil
1256 "Non-nil means activate single letter commands at beginning of a headline.
1257 This may also be a function to test for appropriate locations where speed
1258 commands should be active.
1260 For example, to activate speed commands when the point is on any
1261 star at the beginning of the headline, you can do this:
1263 (setq org-use-speed-commands
1264 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1265 :group 'org-structure
1266 :type '(choice
1267 (const :tag "Never" nil)
1268 (const :tag "At beginning of headline stars" t)
1269 (function)))
1271 (defcustom org-speed-commands-user nil
1272 "Alist of additional speed commands.
1273 This list will be checked before `org-speed-commands-default'
1274 when the variable `org-use-speed-commands' is non-nil
1275 and when the cursor is at the beginning of a headline.
1276 The car if each entry is a string with a single letter, which must
1277 be assigned to `self-insert-command' in the global map.
1278 The cdr is either a command to be called interactively, a function
1279 to be called, or a form to be evaluated.
1280 An entry that is just a list with a single string will be interpreted
1281 as a descriptive headline that will be added when listing the speed
1282 commands in the Help buffer using the `?' speed command."
1283 :group 'org-structure
1284 :type '(repeat :value ("k" . ignore)
1285 (choice :value ("k" . ignore)
1286 (list :tag "Descriptive Headline" (string :tag "Headline"))
1287 (cons :tag "Letter and Command"
1288 (string :tag "Command letter")
1289 (choice
1290 (function)
1291 (sexp))))))
1293 (defcustom org-bookmark-names-plist
1294 '(:last-capture "org-capture-last-stored"
1295 :last-refile "org-refile-last-stored"
1296 :last-capture-marker "org-capture-last-stored-marker")
1297 "Names for bookmarks automatically set by some Org commands.
1298 This can provide strings as names for a number of bookmarks Org sets
1299 automatically. The following keys are currently implemented:
1300 :last-capture
1301 :last-capture-marker
1302 :last-refile
1303 When a key does not show up in the property list, the corresponding bookmark
1304 is not set."
1305 :group 'org-structure
1306 :type 'plist)
1308 (defgroup org-cycle nil
1309 "Options concerning visibility cycling in Org mode."
1310 :tag "Org Cycle"
1311 :group 'org-structure)
1313 (defcustom org-cycle-skip-children-state-if-no-children t
1314 "Non-nil means skip CHILDREN state in entries that don't have any."
1315 :group 'org-cycle
1316 :type 'boolean)
1318 (defcustom org-cycle-max-level nil
1319 "Maximum level which should still be subject to visibility cycling.
1320 Levels higher than this will, for cycling, be treated as text, not a headline.
1321 When `org-odd-levels-only' is set, a value of N in this variable actually
1322 means 2N-1 stars as the limiting headline.
1323 When nil, cycle all levels.
1324 Note that the limiting level of cycling is also influenced by
1325 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1326 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1327 than its value."
1328 :group 'org-cycle
1329 :type '(choice
1330 (const :tag "No limit" nil)
1331 (integer :tag "Maximum level")))
1333 (defcustom org-hide-block-startup nil
1334 "Non-nil means entering Org mode will fold all blocks.
1335 This can also be set in on a per-file basis with
1337 #+STARTUP: hideblocks
1338 #+STARTUP: showblocks"
1339 :group 'org-startup
1340 :group 'org-cycle
1341 :type 'boolean)
1343 (defcustom org-cycle-global-at-bob nil
1344 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1346 This makes it possible to do global cycling without having to use `S-TAB'
1347 or `\\[universal-argument] TAB'. For this special case to work, the first \
1348 line of the buffer
1349 must not be a headline -- it may be empty or some other text.
1351 When used in this way, `org-cycle-hook' is disabled temporarily to make
1352 sure the cursor stays at the beginning of the buffer.
1354 When this option is nil, don't do anything special at the beginning of
1355 the buffer."
1356 :group 'org-cycle
1357 :type 'boolean)
1359 (defcustom org-cycle-level-after-item/entry-creation t
1360 "Non-nil means cycle entry level or item indentation in new empty entries.
1362 When the cursor is at the end of an empty headline, i.e., with only stars
1363 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1364 and then all possible ancestor states, before returning to the original state.
1365 This makes data entry extremely fast: M-RET to create a new headline,
1366 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1368 When the cursor is at the end of an empty plain list item, one TAB will
1369 make it a subitem, two or more tabs will back up to make this an item
1370 higher up in the item hierarchy."
1371 :group 'org-cycle
1372 :type 'boolean)
1374 (defcustom org-cycle-emulate-tab t
1375 "Where should `org-cycle' emulate TAB.
1376 nil Never
1377 white Only in completely white lines
1378 whitestart Only at the beginning of lines, before the first non-white char
1379 t Everywhere except in headlines
1380 exc-hl-bol Everywhere except at the start of a headline
1381 If TAB is used in a place where it does not emulate TAB, the current subtree
1382 visibility is cycled."
1383 :group 'org-cycle
1384 :type '(choice (const :tag "Never" nil)
1385 (const :tag "Only in completely white lines" white)
1386 (const :tag "Before first char in a line" whitestart)
1387 (const :tag "Everywhere except in headlines" t)
1388 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1390 (defcustom org-cycle-separator-lines 2
1391 "Number of empty lines needed to keep an empty line between collapsed trees.
1392 If you leave an empty line between the end of a subtree and the following
1393 headline, this empty line is hidden when the subtree is folded.
1394 Org mode will leave (exactly) one empty line visible if the number of
1395 empty lines is equal or larger to the number given in this variable.
1396 So the default 2 means at least 2 empty lines after the end of a subtree
1397 are needed to produce free space between a collapsed subtree and the
1398 following headline.
1400 If the number is negative, and the number of empty lines is at least -N,
1401 all empty lines are shown.
1403 Special case: when 0, never leave empty lines in collapsed view."
1404 :group 'org-cycle
1405 :type 'integer)
1406 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1408 (defcustom org-pre-cycle-hook nil
1409 "Hook that is run before visibility cycling is happening.
1410 The function(s) in this hook must accept a single argument which indicates
1411 the new state that will be set right after running this hook. The
1412 argument is a symbol. Before a global state change, it can have the values
1413 `overview', `content', or `all'. Before a local state change, it can have
1414 the values `folded', `children', or `subtree'."
1415 :group 'org-cycle
1416 :type 'hook)
1418 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1419 org-cycle-hide-drawers
1420 org-cycle-show-empty-lines
1421 org-optimize-window-after-visibility-change)
1422 "Hook that is run after `org-cycle' has changed the buffer visibility.
1423 The function(s) in this hook must accept a single argument which indicates
1424 the new state that was set by the most recent `org-cycle' command. The
1425 argument is a symbol. After a global state change, it can have the values
1426 `overview', `contents', or `all'. After a local state change, it can have
1427 the values `folded', `children', or `subtree'."
1428 :group 'org-cycle
1429 :type 'hook
1430 :version "26.1"
1431 :package-version '(Org . "8.3"))
1433 (defgroup org-edit-structure nil
1434 "Options concerning structure editing in Org mode."
1435 :tag "Org Edit Structure"
1436 :group 'org-structure)
1438 (defcustom org-odd-levels-only nil
1439 "Non-nil means skip even levels and only use odd levels for the outline.
1440 This has the effect that two stars are being added/taken away in
1441 promotion/demotion commands. It also influences how levels are
1442 handled by the exporters.
1443 Changing it requires restart of `font-lock-mode' to become effective
1444 for fontification also in regions already fontified.
1445 You may also set this on a per-file basis by adding one of the following
1446 lines to the buffer:
1448 #+STARTUP: odd
1449 #+STARTUP: oddeven"
1450 :group 'org-edit-structure
1451 :group 'org-appearance
1452 :type 'boolean)
1454 (defcustom org-adapt-indentation t
1455 "Non-nil means adapt indentation to outline node level.
1457 When this variable is set, Org assumes that you write outlines by
1458 indenting text in each node to align with the headline (after the
1459 stars). The following issues are influenced by this variable:
1461 - The indentation is increased by one space in a demotion
1462 command, and decreased by one in a promotion command. However,
1463 in the latter case, if shifting some line in the entry body
1464 would alter document structure (e.g., insert a new headline),
1465 indentation is not changed at all.
1467 - Property drawers and planning information is inserted indented
1468 when this variable is set. When nil, they will not be indented.
1470 - TAB indents a line relative to current level. The lines below
1471 a headline will be indented when this variable is set.
1473 Note that this is all about true indentation, by adding and
1474 removing space characters. See also `org-indent.el' which does
1475 level-dependent indentation in a virtual way, i.e. at display
1476 time in Emacs."
1477 :group 'org-edit-structure
1478 :type 'boolean)
1480 (defcustom org-special-ctrl-a/e nil
1481 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1483 When t, `C-a' will bring back the cursor to the beginning of the
1484 headline text, i.e. after the stars and after a possible TODO
1485 keyword. In an item, this will be the position after bullet and
1486 check-box, if any. When the cursor is already at that position,
1487 another `C-a' will bring it to the beginning of the line.
1489 `C-e' will jump to the end of the headline, ignoring the presence
1490 of tags in the headline. A second `C-e' will then jump to the
1491 true end of the line, after any tags. This also means that, when
1492 this variable is non-nil, `C-e' also will never jump beyond the
1493 end of the heading of a folded section, i.e. not after the
1494 ellipses.
1496 When set to the symbol `reversed', the first `C-a' or `C-e' works
1497 normally, going to the true line boundary first. Only a directly
1498 following, identical keypress will bring the cursor to the
1499 special positions.
1501 This may also be a cons cell where the behavior for `C-a' and
1502 `C-e' is set separately."
1503 :group 'org-edit-structure
1504 :type '(choice
1505 (const :tag "off" nil)
1506 (const :tag "on: after stars/bullet and before tags first" t)
1507 (const :tag "reversed: true line boundary first" reversed)
1508 (cons :tag "Set C-a and C-e separately"
1509 (choice :tag "Special C-a"
1510 (const :tag "off" nil)
1511 (const :tag "on: after stars/bullet first" t)
1512 (const :tag "reversed: before stars/bullet first" reversed))
1513 (choice :tag "Special C-e"
1514 (const :tag "off" nil)
1515 (const :tag "on: before tags first" t)
1516 (const :tag "reversed: after tags first" reversed)))))
1517 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1519 (defcustom org-special-ctrl-k nil
1520 "Non-nil means `C-k' will behave specially in headlines.
1521 When nil, `C-k' will call the default `kill-line' command.
1522 When t, the following will happen while the cursor is in the headline:
1524 - When the cursor is at the beginning of a headline, kill the entire
1525 line and possible the folded subtree below the line.
1526 - When in the middle of the headline text, kill the headline up to the tags.
1527 - When after the headline text, kill the tags."
1528 :group 'org-edit-structure
1529 :type 'boolean)
1531 (defcustom org-ctrl-k-protect-subtree nil
1532 "Non-nil means, do not delete a hidden subtree with C-k.
1533 When set to the symbol `error', simply throw an error when C-k is
1534 used to kill (part-of) a headline that has hidden text behind it.
1535 Any other non-nil value will result in a query to the user, if it is
1536 OK to kill that hidden subtree. When nil, kill without remorse."
1537 :group 'org-edit-structure
1538 :version "24.1"
1539 :type '(choice
1540 (const :tag "Do not protect hidden subtrees" nil)
1541 (const :tag "Protect hidden subtrees with a security query" t)
1542 (const :tag "Never kill a hidden subtree with C-k" error)))
1544 (defcustom org-special-ctrl-o t
1545 "Non-nil means, make `C-o' insert a row in tables."
1546 :group 'org-edit-structure
1547 :type 'boolean)
1549 (defcustom org-catch-invisible-edits nil
1550 "Check if in invisible region before inserting or deleting a character.
1551 Valid values are:
1553 nil Do not check, so just do invisible edits.
1554 error Throw an error and do nothing.
1555 show Make point visible, and do the requested edit.
1556 show-and-error Make point visible, then throw an error and abort the edit.
1557 smart Make point visible, and do insertion/deletion if it is
1558 adjacent to visible text and the change feels predictable.
1559 Never delete a previously invisible character or add in the
1560 middle or right after an invisible region. Basically, this
1561 allows insertion and backward-delete right before ellipses.
1562 FIXME: maybe in this case we should not even show?"
1563 :group 'org-edit-structure
1564 :version "24.1"
1565 :type '(choice
1566 (const :tag "Do not check" nil)
1567 (const :tag "Throw error when trying to edit" error)
1568 (const :tag "Unhide, but do not do the edit" show-and-error)
1569 (const :tag "Show invisible part and do the edit" show)
1570 (const :tag "Be smart and do the right thing" smart)))
1572 (defcustom org-yank-folded-subtrees t
1573 "Non-nil means when yanking subtrees, fold them.
1574 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1575 it starts with a heading and all other headings in it are either children
1576 or siblings, then fold all the subtrees. However, do this only if no
1577 text after the yank would be swallowed into a folded tree by this action."
1578 :group 'org-edit-structure
1579 :type 'boolean)
1581 (defcustom org-yank-adjusted-subtrees nil
1582 "Non-nil means when yanking subtrees, adjust the level.
1583 With this setting, `org-paste-subtree' is used to insert the subtree, see
1584 this function for details."
1585 :group 'org-edit-structure
1586 :type 'boolean)
1588 (defcustom org-M-RET-may-split-line '((default . t))
1589 "Non-nil means M-RET will split the line at the cursor position.
1590 When nil, it will go to the end of the line before making a
1591 new line.
1592 You may also set this option in a different way for different
1593 contexts. Valid contexts are:
1595 headline when creating a new headline
1596 item when creating a new item
1597 table in a table field
1598 default the value to be used for all contexts not explicitly
1599 customized"
1600 :group 'org-structure
1601 :group 'org-table
1602 :type '(choice
1603 (const :tag "Always" t)
1604 (const :tag "Never" nil)
1605 (repeat :greedy t :tag "Individual contexts"
1606 (cons
1607 (choice :tag "Context"
1608 (const headline)
1609 (const item)
1610 (const table)
1611 (const default))
1612 (boolean)))))
1615 (defcustom org-insert-heading-respect-content nil
1616 "Non-nil means insert new headings after the current subtree.
1617 \\<org-mode-map>
1618 When nil, the new heading is created directly after the current line.
1619 The commands `\\[org-insert-heading-respect-content]' and \
1620 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1621 for the duration of the command."
1622 :group 'org-structure
1623 :type 'boolean)
1625 (defcustom org-blank-before-new-entry '((heading . auto)
1626 (plain-list-item . auto))
1627 "Should `org-insert-heading' leave a blank line before new heading/item?
1628 The value is an alist, with `heading' and `plain-list-item' as CAR,
1629 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1630 which case Org will look at the surrounding headings/items and try to
1631 make an intelligent decision whether to insert a blank line or not."
1632 :group 'org-edit-structure
1633 :type '(list
1634 (cons (const heading)
1635 (choice (const :tag "Never" nil)
1636 (const :tag "Always" t)
1637 (const :tag "Auto" auto)))
1638 (cons (const plain-list-item)
1639 (choice (const :tag "Never" nil)
1640 (const :tag "Always" t)
1641 (const :tag "Auto" auto)))))
1643 (defcustom org-insert-heading-hook nil
1644 "Hook being run after inserting a new heading."
1645 :group 'org-edit-structure
1646 :type 'hook)
1648 (defcustom org-enable-fixed-width-editor t
1649 "Non-nil means lines starting with \":\" are treated as fixed-width.
1650 This currently only means they are never auto-wrapped.
1651 When nil, such lines will be treated like ordinary lines."
1652 :group 'org-edit-structure
1653 :type 'boolean)
1655 (defcustom org-goto-auto-isearch t
1656 "Non-nil means typing characters in `org-goto' starts incremental search.
1657 When nil, you can use these keybindings to navigate the buffer:
1659 q Quit the org-goto interface
1660 n Go to the next visible heading
1661 p Go to the previous visible heading
1662 f Go one heading forward on same level
1663 b Go one heading backward on same level
1664 u Go one heading up"
1665 :group 'org-edit-structure
1666 :type 'boolean)
1668 (defgroup org-sparse-trees nil
1669 "Options concerning sparse trees in Org mode."
1670 :tag "Org Sparse Trees"
1671 :group 'org-structure)
1673 (defcustom org-highlight-sparse-tree-matches t
1674 "Non-nil means highlight all matches that define a sparse tree.
1675 The highlights will automatically disappear the next time the buffer is
1676 changed by an edit command."
1677 :group 'org-sparse-trees
1678 :type 'boolean)
1680 (defcustom org-remove-highlights-with-change t
1681 "Non-nil means any change to the buffer will remove temporary highlights.
1682 \\<org-mode-map>\
1683 Such highlights are created by `org-occur' and `org-clock-display'.
1684 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1685 to get rid of the highlights.
1686 The highlights created by `org-toggle-latex-fragment' always need
1687 `\\[org-toggle-latex-fragment]' to be removed."
1688 :group 'org-sparse-trees
1689 :group 'org-time
1690 :type 'boolean)
1692 (defcustom org-occur-case-fold-search t
1693 "Non-nil means `org-occur' should be case-insensitive.
1694 If set to `smart' the search will be case-insensitive only if it
1695 doesn't specify any upper case character."
1696 :group 'org-sparse-trees
1697 :version "26.1"
1698 :type '(choice
1699 (const :tag "Case-sensitive" nil)
1700 (const :tag "Case-insensitive" t)
1701 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1703 (defcustom org-occur-hook '(org-first-headline-recenter)
1704 "Hook that is run after `org-occur' has constructed a sparse tree.
1705 This can be used to recenter the window to show as much of the structure
1706 as possible."
1707 :group 'org-sparse-trees
1708 :type 'hook)
1710 (defgroup org-imenu-and-speedbar nil
1711 "Options concerning imenu and speedbar in Org mode."
1712 :tag "Org Imenu and Speedbar"
1713 :group 'org-structure)
1715 (defcustom org-imenu-depth 2
1716 "The maximum level for Imenu access to Org headlines.
1717 This also applied for speedbar access."
1718 :group 'org-imenu-and-speedbar
1719 :type 'integer)
1721 (defgroup org-table nil
1722 "Options concerning tables in Org mode."
1723 :tag "Org Table"
1724 :group 'org)
1726 (defcustom org-enable-table-editor 'optimized
1727 "Non-nil means lines starting with \"|\" are handled by the table editor.
1728 When nil, such lines will be treated like ordinary lines.
1730 When equal to the symbol `optimized', the table editor will be optimized to
1731 do the following:
1732 - Automatic overwrite mode in front of whitespace in table fields.
1733 This makes the structure of the table stay in tact as long as the edited
1734 field does not exceed the column width.
1735 - Minimize the number of realigns. Normally, the table is aligned each time
1736 TAB or RET are pressed to move to another field. With optimization this
1737 happens only if changes to a field might have changed the column width.
1738 Optimization requires replacing the functions `self-insert-command',
1739 `delete-char', and `backward-delete-char' in Org buffers, with a
1740 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1741 good at guessing when a re-align will be necessary, but you can always
1742 force one with `\\[org-ctrl-c-ctrl-c]'.
1744 If you would like to use the optimized version in Org mode, but the
1745 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1747 This variable can be used to turn on and off the table editor during a session,
1748 but in order to toggle optimization, a restart is required.
1750 See also the variable `org-table-auto-blank-field'."
1751 :group 'org-table
1752 :type '(choice
1753 (const :tag "off" nil)
1754 (const :tag "on" t)
1755 (const :tag "on, optimized" optimized)))
1757 (defcustom org-self-insert-cluster-for-undo nil
1758 "Non-nil means cluster self-insert commands for undo when possible.
1759 If this is set, then, like in the Emacs command loop, 20 consecutive
1760 characters will be undone together.
1761 This is configurable, because there is some impact on typing performance."
1762 :group 'org-table
1763 :type 'boolean)
1765 (defcustom org-table-tab-recognizes-table.el t
1766 "Non-nil means TAB will automatically notice a table.el table.
1767 When it sees such a table, it moves point into it and - if necessary -
1768 calls `table-recognize-table'."
1769 :group 'org-table-editing
1770 :type 'boolean)
1772 (defgroup org-link nil
1773 "Options concerning links in Org mode."
1774 :tag "Org Link"
1775 :group 'org)
1777 (defvar-local org-link-abbrev-alist-local nil
1778 "Buffer-local version of `org-link-abbrev-alist', which see.
1779 The value of this is taken from the #+LINK lines.")
1781 (defcustom org-link-parameters
1782 '(("doi" :follow org--open-doi-link)
1783 ("elisp" :follow org--open-elisp-link)
1784 ("file" :complete org-file-complete-link)
1785 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1786 ("help" :follow org--open-help-link)
1787 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1788 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1789 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1790 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1791 ("shell" :follow org--open-shell-link))
1792 "An alist of properties that defines all the links in Org mode.
1793 The key in each association is a string of the link type.
1794 Subsequent optional elements make up a p-list of link properties.
1796 :follow - A function that takes the link path as an argument.
1798 :export - A function that takes the link path, description and
1799 export-backend as arguments.
1801 :store - A function responsible for storing the link. See the
1802 function `org-store-link-functions'.
1804 :complete - A function that inserts a link with completion. The
1805 function takes one optional prefix arg.
1807 :face - A face for the link, or a function that returns a face.
1808 The function takes one argument which is the link path. The
1809 default face is `org-link'.
1811 :mouse-face - The mouse-face. The default is `highlight'.
1813 :display - `full' will not fold the link in descriptive
1814 display. Default is `org-link'.
1816 :help-echo - A string or function that takes (window object position)
1817 as arguments and returns a string.
1819 :keymap - A keymap that is active on the link. The default is
1820 `org-mouse-map'.
1822 :htmlize-link - A function for the htmlize-link. Defaults
1823 to (list :uri \"type:path\")
1825 :activate-func - A function to run at the end of font-lock
1826 activation. The function must accept (link-start link-end path bracketp)
1827 as arguments."
1828 :group 'org-link
1829 :type '(alist :tag "Link display parameters"
1830 :value-type plist)
1831 :version "26.1"
1832 :package-version '(Org . "9.1"))
1834 (defun org-link-get-parameter (type key)
1835 "Get TYPE link property for KEY.
1836 TYPE is a string and KEY is a plist keyword."
1837 (plist-get
1838 (cdr (assoc type org-link-parameters))
1839 key))
1841 (defun org-link-set-parameters (type &rest parameters)
1842 "Set link TYPE properties to PARAMETERS.
1843 PARAMETERS should be :key val pairs."
1844 (let ((data (assoc type org-link-parameters)))
1845 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1846 (push (cons type parameters) org-link-parameters)
1847 (org-make-link-regexps)
1848 (org-element-update-syntax))))
1850 (defun org-link-types ()
1851 "Return a list of known link types."
1852 (mapcar #'car org-link-parameters))
1854 (defcustom org-link-abbrev-alist nil
1855 "Alist of link abbreviations.
1856 The car of each element is a string, to be replaced at the start of a link.
1857 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1858 links in Org buffers can have an optional tag after a double colon, e.g.,
1860 [[linkkey:tag][description]]
1862 The `linkkey' must be a single word, starting with a letter, followed
1863 by letters, numbers, `-' or `_'.
1865 If REPLACE is a string, the tag will simply be appended to create the link.
1866 If the string contains \"%s\", the tag will be inserted there. If the string
1867 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1868 at that point (see the function `url-hexify-string'). If the string contains
1869 the specifier \"%(my-function)\", then the custom function `my-function' will
1870 be invoked: this function takes the tag as its only argument and must return
1871 a string.
1873 REPLACE may also be a function that will be called with the tag as the
1874 only argument to create the link, which should be returned as a string.
1876 See the manual for examples."
1877 :group 'org-link
1878 :type '(repeat
1879 (cons
1880 (string :tag "Protocol")
1881 (choice
1882 (string :tag "Format")
1883 (function)))))
1885 (defcustom org-descriptive-links t
1886 "Non-nil means Org will display descriptive links.
1887 E.g. [[http://orgmode.org][Org website]] will be displayed as
1888 \"Org Website\", hiding the link itself and just displaying its
1889 description. When set to nil, Org will display the full links
1890 literally.
1892 You can interactively set the value of this variable by calling
1893 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1894 :group 'org-link
1895 :type 'boolean)
1897 (defcustom org-link-file-path-type 'adaptive
1898 "How the path name in file links should be stored.
1899 Valid values are:
1901 relative Relative to the current directory, i.e. the directory of the file
1902 into which the link is being inserted.
1903 absolute Absolute path, if possible with ~ for home directory.
1904 noabbrev Absolute path, no abbreviation of home directory.
1905 adaptive Use relative path for files in the current directory and sub-
1906 directories of it. For other files, use an absolute path."
1907 :group 'org-link
1908 :type '(choice
1909 (const relative)
1910 (const absolute)
1911 (const noabbrev)
1912 (const adaptive)))
1914 (defvaralias 'org-activate-links 'org-highlight-links)
1915 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1916 "Types of links that should be highlighted in Org files.
1918 This is a list of symbols, each one of them leading to the
1919 highlighting of a certain link type.
1921 You can still open links that are not highlighted.
1923 In principle, it does not hurt to turn on highlighting for all
1924 link types. There may be a small gain when turning off unused
1925 link types. The types are:
1927 bracket The recommended [[link][description]] or [[link]] links with hiding.
1928 angle Links in angular brackets that may contain whitespace like
1929 <bbdb:Carsten Dominik>.
1930 plain Plain links in normal text, no whitespace, like http://google.com.
1931 radio Text that is matched by a radio target, see manual for details.
1932 tag Tag settings in a headline (link to tag search).
1933 date Time stamps (link to calendar).
1934 footnote Footnote labels.
1936 If you set this variable during an Emacs session, use `org-mode-restart'
1937 in the Org buffer so that the change takes effect."
1938 :group 'org-link
1939 :group 'org-appearance
1940 :type '(set :greedy t
1941 (const :tag "Double bracket links" bracket)
1942 (const :tag "Angular bracket links" angle)
1943 (const :tag "Plain text links" plain)
1944 (const :tag "Radio target matches" radio)
1945 (const :tag "Tags" tag)
1946 (const :tag "Timestamps" date)
1947 (const :tag "Footnotes" footnote)))
1949 (defcustom org-make-link-description-function nil
1950 "Function to use for generating link descriptions from links.
1951 When nil, the link location will be used. This function must take
1952 two parameters: the first one is the link, the second one is the
1953 description generated by `org-insert-link'. The function should
1954 return the description to use."
1955 :group 'org-link
1956 :type '(choice (const nil) (function)))
1958 (defgroup org-link-store nil
1959 "Options concerning storing links in Org mode."
1960 :tag "Org Store Link"
1961 :group 'org-link)
1963 (defcustom org-url-hexify-p t
1964 "When non-nil, hexify URL when creating a link."
1965 :type 'boolean
1966 :version "24.3"
1967 :group 'org-link-store)
1969 (defcustom org-email-link-description-format "Email %c: %.30s"
1970 "Format of the description part of a link to an email or usenet message.
1971 The following %-escapes will be replaced by corresponding information:
1973 %F full \"From\" field
1974 %f name, taken from \"From\" field, address if no name
1975 %T full \"To\" field
1976 %t first name in \"To\" field, address if no name
1977 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1978 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1979 %s subject
1980 %d date
1981 %m message-id.
1983 You may use normal field width specification between the % and the letter.
1984 This is for example useful to limit the length of the subject.
1986 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1987 :group 'org-link-store
1988 :type 'string)
1990 (defcustom org-from-is-user-regexp
1991 (let (r1 r2)
1992 (when (and user-mail-address (not (string= user-mail-address "")))
1993 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1994 (when (and user-full-name (not (string= user-full-name "")))
1995 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1996 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1997 "Regexp matched against the \"From:\" header of an email or usenet message.
1998 It should match if the message is from the user him/herself."
1999 :group 'org-link-store
2000 :type 'regexp)
2002 (defcustom org-context-in-file-links t
2003 "Non-nil means file links from `org-store-link' contain context.
2004 \\<org-mode-map>
2005 A search string will be added to the file name with :: as separator
2006 and used to find the context when the link is activated by the command
2007 `org-open-at-point'. When this option is t, the entire active region
2008 will be placed in the search string of the file link. If set to a
2009 positive integer, only the first n lines of context will be stored.
2011 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2012 \\[org-store-link]')
2013 negates this setting for the duration of the command."
2014 :group 'org-link-store
2015 :type '(choice boolean integer))
2017 (defcustom org-keep-stored-link-after-insertion nil
2018 "Non-nil means keep link in list for entire session.
2019 \\<org-mode-map>
2020 The command `org-store-link' adds a link pointing to the current
2021 location to an internal list. These links accumulate during a session.
2022 The command `org-insert-link' can be used to insert links into any
2023 Org file (offering completion for all stored links).
2025 When this option is nil, every link which has been inserted once using
2026 `\\[org-insert-link]' will be removed from the list, to make completing the \
2027 unused
2028 links more efficient."
2029 :group 'org-link-store
2030 :type 'boolean)
2032 (defgroup org-link-follow nil
2033 "Options concerning following links in Org mode."
2034 :tag "Org Follow Link"
2035 :group 'org-link)
2037 (defcustom org-link-translation-function nil
2038 "Function to translate links with different syntax to Org syntax.
2039 This can be used to translate links created for example by the Planner
2040 or emacs-wiki packages to Org syntax.
2041 The function must accept two parameters, a TYPE containing the link
2042 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2043 which is everything after the link protocol. It should return a cons
2044 with possibly modified values of type and path.
2045 Org contains a function for this, so if you set this variable to
2046 `org-translate-link-from-planner', you should be able follow many
2047 links created by planner."
2048 :group 'org-link-follow
2049 :type '(choice (const nil) (function)))
2051 (defcustom org-follow-link-hook nil
2052 "Hook that is run after a link has been followed."
2053 :group 'org-link-follow
2054 :type 'hook)
2056 (defcustom org-tab-follows-link nil
2057 "Non-nil means on links TAB will follow the link.
2058 Needs to be set before org.el is loaded.
2059 This really should not be used, it does not make sense, and the
2060 implementation is bad."
2061 :group 'org-link-follow
2062 :type 'boolean)
2064 (defcustom org-return-follows-link nil
2065 "Non-nil means on links RET will follow the link.
2066 In tables, the special behavior of RET has precedence."
2067 :group 'org-link-follow
2068 :type 'boolean)
2070 (defcustom org-mouse-1-follows-link
2071 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2072 "Non-nil means mouse-1 on a link will follow the link.
2073 A longer mouse click will still set point. Needs to be set
2074 before org.el is loaded."
2075 :group 'org-link-follow
2076 :version "24.4"
2077 :package-version '(Org . "8.3")
2078 :type '(choice
2079 (const :tag "A double click follows the link" double)
2080 (const :tag "Unconditionally follow the link with mouse-1" t)
2081 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2083 (defcustom org-mark-ring-length 4
2084 "Number of different positions to be recorded in the ring.
2085 Changing this requires a restart of Emacs to work correctly."
2086 :group 'org-link-follow
2087 :type 'integer)
2089 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2090 "Non-nil means internal fuzzy links can only match headlines.
2092 When nil, the a fuzzy link may point to a target or a named
2093 construct in the document. When set to the special value
2094 `query-to-create', offer to create a new headline when none
2095 matched.
2097 Spaces and statistics cookies are ignored during heading searches."
2098 :group 'org-link-follow
2099 :version "24.1"
2100 :type '(choice
2101 (const :tag "Use fuzzy text search" nil)
2102 (const :tag "Match only exact headline" t)
2103 (const :tag "Match exact headline or query to create it"
2104 query-to-create))
2105 :safe #'symbolp)
2107 (defcustom org-link-frame-setup
2108 '((vm . vm-visit-folder-other-frame)
2109 (vm-imap . vm-visit-imap-folder-other-frame)
2110 (gnus . org-gnus-no-new-news)
2111 (file . find-file-other-window)
2112 (wl . wl-other-frame))
2113 "Setup the frame configuration for following links.
2114 When following a link with Emacs, it may often be useful to display
2115 this link in another window or frame. This variable can be used to
2116 set this up for the different types of links.
2117 For VM, use any of
2118 `vm-visit-folder'
2119 `vm-visit-folder-other-window'
2120 `vm-visit-folder-other-frame'
2121 For Gnus, use any of
2122 `gnus'
2123 `gnus-other-frame'
2124 `org-gnus-no-new-news'
2125 For FILE, use any of
2126 `find-file'
2127 `find-file-other-window'
2128 `find-file-other-frame'
2129 For Wanderlust use any of
2130 `wl'
2131 `wl-other-frame'
2132 For the calendar, use the variable `calendar-setup'.
2133 For BBDB, it is currently only possible to display the matches in
2134 another window."
2135 :group 'org-link-follow
2136 :type '(list
2137 (cons (const vm)
2138 (choice
2139 (const vm-visit-folder)
2140 (const vm-visit-folder-other-window)
2141 (const vm-visit-folder-other-frame)))
2142 (cons (const vm-imap)
2143 (choice
2144 (const vm-visit-imap-folder)
2145 (const vm-visit-imap-folder-other-window)
2146 (const vm-visit-imap-folder-other-frame)))
2147 (cons (const gnus)
2148 (choice
2149 (const gnus)
2150 (const gnus-other-frame)
2151 (const org-gnus-no-new-news)))
2152 (cons (const file)
2153 (choice
2154 (const find-file)
2155 (const find-file-other-window)
2156 (const find-file-other-frame)))
2157 (cons (const wl)
2158 (choice
2159 (const wl)
2160 (const wl-other-frame)))))
2162 (defcustom org-display-internal-link-with-indirect-buffer nil
2163 "Non-nil means use indirect buffer to display infile links.
2164 Activating internal links (from one location in a file to another location
2165 in the same file) normally just jumps to the location. When the link is
2166 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2167 is displayed in
2168 another window. When this option is set, the other window actually displays
2169 an indirect buffer clone of the current buffer, to avoid any visibility
2170 changes to the current buffer."
2171 :group 'org-link-follow
2172 :type 'boolean)
2174 (defcustom org-open-non-existing-files nil
2175 "Non-nil means `org-open-file' will open non-existing files.
2176 When nil, an error will be generated.
2177 This variable applies only to external applications because they
2178 might choke on non-existing files. If the link is to a file that
2179 will be opened in Emacs, the variable is ignored."
2180 :group 'org-link-follow
2181 :type 'boolean)
2183 (defcustom org-open-directory-means-index-dot-org nil
2184 "Non-nil means a link to a directory really means to index.org.
2185 When nil, following a directory link will run dired or open a finder/explorer
2186 window on that directory."
2187 :group 'org-link-follow
2188 :type 'boolean)
2190 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2191 "Non-nil means ask for confirmation before executing shell links.
2192 Shell links can be dangerous: just think about a link
2194 [[shell:rm -rf ~/*][Google Search]]
2196 This link would show up in your Org document as \"Google Search\",
2197 but really it would remove your entire home directory.
2198 Therefore we advise against setting this variable to nil.
2199 Just change it to `y-or-n-p' if you want to confirm with a
2200 single keystroke rather than having to type \"yes\"."
2201 :group 'org-link-follow
2202 :type '(choice
2203 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2204 (const :tag "with y-or-n (faster)" y-or-n-p)
2205 (const :tag "no confirmation (dangerous)" nil)))
2206 (put 'org-confirm-shell-link-function
2207 'safe-local-variable
2208 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2210 (defcustom org-confirm-shell-link-not-regexp ""
2211 "A regexp to skip confirmation for shell links."
2212 :group 'org-link-follow
2213 :version "24.1"
2214 :type 'regexp)
2216 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2217 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2218 Elisp links can be dangerous: just think about a link
2220 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2222 This link would show up in your Org document as \"Google Search\",
2223 but really it would remove your entire home directory.
2224 Therefore we advise against setting this variable to nil.
2225 Just change it to `y-or-n-p' if you want to confirm with a
2226 single keystroke rather than having to type \"yes\"."
2227 :group 'org-link-follow
2228 :type '(choice
2229 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2230 (const :tag "with y-or-n (faster)" y-or-n-p)
2231 (const :tag "no confirmation (dangerous)" nil)))
2232 (put 'org-confirm-shell-link-function
2233 'safe-local-variable
2234 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2236 (defcustom org-confirm-elisp-link-not-regexp ""
2237 "A regexp to skip confirmation for Elisp links."
2238 :group 'org-link-follow
2239 :version "24.1"
2240 :type 'regexp)
2242 (defconst org-file-apps-defaults-gnu
2243 '((remote . emacs)
2244 (system . mailcap)
2245 (t . mailcap))
2246 "Default file applications on a UNIX or GNU/Linux system.
2247 See `org-file-apps'.")
2249 (defconst org-file-apps-defaults-macosx
2250 '((remote . emacs)
2251 (system . "open %s")
2252 ("ps.gz" . "gv %s")
2253 ("eps.gz" . "gv %s")
2254 ("dvi" . "xdvi %s")
2255 ("fig" . "xfig %s")
2256 (t . "open %s"))
2257 "Default file applications on a macOS system.
2258 The system \"open\" is known as a default, but we use X11 applications
2259 for some files for which the OS does not have a good default.
2260 See `org-file-apps'.")
2262 (defconst org-file-apps-defaults-windowsnt
2263 (list '(remote . emacs)
2264 (cons 'system (lambda (file _path)
2265 (with-no-warnings (w32-shell-execute "open" file))))
2266 (cons t (lambda (file _path)
2267 (with-no-warnings (w32-shell-execute "open" file)))))
2268 "Default file applications on a Windows NT system.
2269 The system \"open\" is used for most files.
2270 See `org-file-apps'.")
2272 (defcustom org-file-apps
2273 '((auto-mode . emacs)
2274 ("\\.mm\\'" . default)
2275 ("\\.x?html?\\'" . default)
2276 ("\\.pdf\\'" . default))
2277 "External applications for opening `file:path' items in a document.
2278 \\<org-mode-map>\
2280 Org mode uses system defaults for different file types, but
2281 you can use this variable to set the application for a given file
2282 extension. The entries in this list are cons cells where the car identifies
2283 files and the cdr the corresponding command.
2285 Possible values for the file identifier are:
2287 \"string\" A string as a file identifier can be interpreted in different
2288 ways, depending on its contents:
2290 - Alphanumeric characters only:
2291 Match links with this file extension.
2292 Example: (\"pdf\" . \"evince %s\")
2293 to open PDFs with evince.
2295 - Regular expression: Match links where the
2296 filename matches the regexp. If you want to
2297 use groups here, use shy groups.
2299 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2300 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2301 to open *.html and *.xhtml with firefox.
2303 - Regular expression which contains (non-shy) groups:
2304 Match links where the whole link, including \"::\", and
2305 anything after that, matches the regexp.
2306 In a custom command string, %1, %2, etc. are replaced with
2307 the parts of the link that were matched by the groups.
2308 For backwards compatibility, if a command string is given
2309 that does not use any of the group matches, this case is
2310 handled identically to the second one (i.e. match against
2311 file name only).
2312 In a custom function, you can access the group matches with
2313 (match-string n link).
2315 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2316 \"evince -p %1 %s\")
2317 to open [[file:document.pdf::5]] with evince at page 5.
2319 `directory' Matches a directory
2320 `remote' Matches a remote file, accessible through tramp or efs.
2321 Remote files most likely should be visited through Emacs
2322 because external applications cannot handle such paths.
2323 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2324 so all files Emacs knows how to handle. Using this with
2325 command `emacs' will open most files in Emacs. Beware that this
2326 will also open html files inside Emacs, unless you add
2327 (\"html\" . default) to the list as well.
2328 `system' The system command to open files, like `open' on Windows
2329 and macOS, and mailcap under GNU/Linux. This is the command
2330 that will be selected if you call `org-open-at-point' with a
2331 double prefix argument (`\\[universal-argument] \
2332 \\[universal-argument] \\[org-open-at-point]').
2333 t Default for files not matched by any of the other options.
2335 Possible values for the command are:
2337 `emacs' The file will be visited by the current Emacs process.
2338 `default' Use the default application for this file type, which is the
2339 association for t in the list, most likely in the system-specific
2340 part. This can be used to overrule an unwanted setting in the
2341 system-specific variable.
2342 `system' Use the system command for opening files, like \"open\".
2343 This command is specified by the entry whose car is `system'.
2344 Most likely, the system-specific version of this variable
2345 does define this command, but you can overrule/replace it
2346 here.
2347 `mailcap' Use command specified in the mailcaps.
2348 string A command to be executed by a shell; %s will be replaced
2349 by the path to the file.
2350 function A Lisp function, which will be called with two arguments:
2351 the file path and the original link string, without the
2352 \"file:\" prefix.
2354 For more examples, see the system specific constants
2355 `org-file-apps-defaults-macosx'
2356 `org-file-apps-defaults-windowsnt'
2357 `org-file-apps-defaults-gnu'."
2358 :group 'org-link-follow
2359 :type '(repeat
2360 (cons (choice :value ""
2361 (string :tag "Extension")
2362 (const :tag "System command to open files" system)
2363 (const :tag "Default for unrecognized files" t)
2364 (const :tag "Remote file" remote)
2365 (const :tag "Links to a directory" directory)
2366 (const :tag "Any files that have Emacs modes"
2367 auto-mode))
2368 (choice :value ""
2369 (const :tag "Visit with Emacs" emacs)
2370 (const :tag "Use default" default)
2371 (const :tag "Use the system command" system)
2372 (string :tag "Command")
2373 (function :tag "Function")))))
2375 (defcustom org-doi-server-url "http://dx.doi.org/"
2376 "The URL of the DOI server."
2377 :type 'string
2378 :version "24.3"
2379 :group 'org-link-follow)
2381 (defgroup org-refile nil
2382 "Options concerning refiling entries in Org mode."
2383 :tag "Org Refile"
2384 :group 'org)
2386 (defcustom org-directory "~/org"
2387 "Directory with Org files.
2388 This is just a default location to look for Org files. There is no need
2389 at all to put your files into this directory. It is used in the
2390 following situations:
2392 1. When a capture template specifies a target file that is not an
2393 absolute path. The path will then be interpreted relative to
2394 `org-directory'
2395 2. When the value of variable `org-agenda-files' is a single file, any
2396 relative paths in this file will be taken as relative to
2397 `org-directory'."
2398 :group 'org-refile
2399 :group 'org-capture
2400 :type 'directory)
2402 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2403 "Default target for storing notes.
2404 Used as a fall back file for org-capture.el, for templates that
2405 do not specify a target file."
2406 :group 'org-refile
2407 :group 'org-capture
2408 :type 'file)
2410 (defcustom org-goto-interface 'outline
2411 "The default interface to be used for `org-goto'.
2412 Allowed values are:
2413 outline The interface shows an outline of the relevant file
2414 and the correct heading is found by moving through
2415 the outline or by searching with incremental search.
2416 outline-path-completion Headlines in the current buffer are offered via
2417 completion. This is the interface also used by
2418 the refile command."
2419 :group 'org-refile
2420 :type '(choice
2421 (const :tag "Outline" outline)
2422 (const :tag "Outline-path-completion" outline-path-completion)))
2424 (defcustom org-goto-max-level 5
2425 "Maximum target level when running `org-goto' with refile interface."
2426 :group 'org-refile
2427 :type 'integer)
2429 (defcustom org-reverse-note-order nil
2430 "Non-nil means store new notes at the beginning of a file or entry.
2431 When nil, new notes will be filed to the end of a file or entry.
2432 This can also be a list with cons cells of regular expressions that
2433 are matched against file names, and values."
2434 :group 'org-capture
2435 :group 'org-refile
2436 :type '(choice
2437 (const :tag "Reverse always" t)
2438 (const :tag "Reverse never" nil)
2439 (repeat :tag "By file name regexp"
2440 (cons regexp boolean))))
2442 (defcustom org-log-refile nil
2443 "Information to record when a task is refiled.
2445 Possible values are:
2447 nil Don't add anything
2448 time Add a time stamp to the task
2449 note Prompt for a note and add it with template `org-log-note-headings'
2451 This option can also be set with on a per-file-basis with
2453 #+STARTUP: nologrefile
2454 #+STARTUP: logrefile
2455 #+STARTUP: lognoterefile
2457 You can have local logging settings for a subtree by setting the LOGGING
2458 property to one or more of these keywords.
2460 When bulk-refiling from the agenda, the value `note' is forbidden and
2461 will temporarily be changed to `time'."
2462 :group 'org-refile
2463 :group 'org-progress
2464 :version "24.1"
2465 :type '(choice
2466 (const :tag "No logging" nil)
2467 (const :tag "Record timestamp" time)
2468 (const :tag "Record timestamp with note." note)))
2470 (defcustom org-refile-targets nil
2471 "Targets for refiling entries with `\\[org-refile]'.
2472 This is a list of cons cells. Each cell contains:
2473 - a specification of the files to be considered, either a list of files,
2474 or a symbol whose function or variable value will be used to retrieve
2475 a file name or a list of file names. If you use `org-agenda-files' for
2476 that, all agenda files will be scanned for targets. Nil means consider
2477 headings in the current buffer.
2478 - A specification of how to find candidate refile targets. This may be
2479 any of:
2480 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2481 This tag has to be present in all target headlines, inheritance will
2482 not be considered.
2483 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2484 todo keyword.
2485 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2486 headlines that are refiling targets.
2487 - a cons cell (:level . N). Any headline of level N is considered a target.
2488 Note that, when `org-odd-levels-only' is set, level corresponds to
2489 order in hierarchy, not to the number of stars.
2490 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2491 Note that, when `org-odd-levels-only' is set, level corresponds to
2492 order in hierarchy, not to the number of stars.
2494 Each element of this list generates a set of possible targets.
2495 The union of these sets is presented (with completion) to
2496 the user by `org-refile'.
2498 You can set the variable `org-refile-target-verify-function' to a function
2499 to verify each headline found by the simple criteria above.
2501 When this variable is nil, all top-level headlines in the current buffer
2502 are used, equivalent to the value `((nil . (:level . 1))'."
2503 :group 'org-refile
2504 :type '(repeat
2505 (cons
2506 (choice :value org-agenda-files
2507 (const :tag "All agenda files" org-agenda-files)
2508 (const :tag "Current buffer" nil)
2509 (function) (variable) (file))
2510 (choice :tag "Identify target headline by"
2511 (cons :tag "Specific tag" (const :value :tag) (string))
2512 (cons :tag "TODO keyword" (const :value :todo) (string))
2513 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2514 (cons :tag "Level number" (const :value :level) (integer))
2515 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2517 (defcustom org-refile-target-verify-function nil
2518 "Function to verify if the headline at point should be a refile target.
2519 The function will be called without arguments, with point at the
2520 beginning of the headline. It should return t and leave point
2521 where it is if the headline is a valid target for refiling.
2523 If the target should not be selected, the function must return nil.
2524 In addition to this, it may move point to a place from where the search
2525 should be continued. For example, the function may decide that the entire
2526 subtree of the current entry should be excluded and move point to the end
2527 of the subtree."
2528 :group 'org-refile
2529 :type '(choice
2530 (const nil)
2531 (function)))
2533 (defcustom org-refile-use-cache nil
2534 "Non-nil means cache refile targets to speed up the process.
2535 \\<org-mode-map>\
2536 The cache for a particular file will be updated automatically when
2537 the buffer has been killed, or when any of the marker used for flagging
2538 refile targets no longer points at a live buffer.
2539 If you have added new entries to a buffer that might themselves be targets,
2540 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2541 if you find that easier, \
2542 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2543 \\[org-refile]'."
2544 :group 'org-refile
2545 :version "24.1"
2546 :type 'boolean)
2548 (defcustom org-refile-use-outline-path nil
2549 "Non-nil means provide refile targets as paths.
2550 So a level 3 headline will be available as level1/level2/level3.
2552 When the value is `file', also include the file name (without directory)
2553 into the path. In this case, you can also stop the completion after
2554 the file name, to get entries inserted as top level in the file.
2556 When `full-file-path', include the full file path.
2558 When `buffer-name', use the buffer name."
2559 :group 'org-refile
2560 :type '(choice
2561 (const :tag "Not" nil)
2562 (const :tag "Yes" t)
2563 (const :tag "Start with file name" file)
2564 (const :tag "Start with full file path" full-file-path)
2565 (const :tag "Start with buffer name" buffer-name)))
2567 (defcustom org-outline-path-complete-in-steps t
2568 "Non-nil means complete the outline path in hierarchical steps.
2569 When Org uses the refile interface to select an outline path (see
2570 `org-refile-use-outline-path'), the completion of the path can be
2571 done in a single go, or it can be done in steps down the headline
2572 hierarchy. Going in steps is probably the best if you do not use
2573 a special completion package like `ido' or `icicles'. However,
2574 when using these packages, going in one step can be very fast,
2575 while still showing the whole path to the entry."
2576 :group 'org-refile
2577 :type 'boolean)
2579 (defcustom org-refile-allow-creating-parent-nodes nil
2580 "Non-nil means allow the creation of new nodes as refile targets.
2581 New nodes are then created by adding \"/new node name\" to the completion
2582 of an existing node. When the value of this variable is `confirm',
2583 new node creation must be confirmed by the user (recommended).
2584 When nil, the completion must match an existing entry.
2586 Note that, if the new heading is not seen by the criteria
2587 listed in `org-refile-targets', multiple instances of the same
2588 heading would be created by trying again to file under the new
2589 heading."
2590 :group 'org-refile
2591 :type '(choice
2592 (const :tag "Never" nil)
2593 (const :tag "Always" t)
2594 (const :tag "Prompt for confirmation" confirm)))
2596 (defcustom org-refile-active-region-within-subtree nil
2597 "Non-nil means also refile active region within a subtree.
2599 By default `org-refile' doesn't allow refiling regions if they
2600 don't contain a set of subtrees, but it might be convenient to
2601 do so sometimes: in that case, the first line of the region is
2602 converted to a headline before refiling."
2603 :group 'org-refile
2604 :version "24.1"
2605 :type 'boolean)
2607 (defgroup org-todo nil
2608 "Options concerning TODO items in Org mode."
2609 :tag "Org TODO"
2610 :group 'org)
2612 (defgroup org-progress nil
2613 "Options concerning Progress logging in Org mode."
2614 :tag "Org Progress"
2615 :group 'org-time)
2617 (defvar org-todo-interpretation-widgets
2618 '((:tag "Sequence (cycling hits every state)" sequence)
2619 (:tag "Type (cycling directly to DONE)" type))
2620 "The available interpretation symbols for customizing `org-todo-keywords'.
2621 Interested libraries should add to this list.")
2623 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2624 "List of TODO entry keyword sequences and their interpretation.
2625 \\<org-mode-map>This is a list of sequences.
2627 Each sequence starts with a symbol, either `sequence' or `type',
2628 indicating if the keywords should be interpreted as a sequence of
2629 action steps, or as different types of TODO items. The first
2630 keywords are states requiring action - these states will select a headline
2631 for inclusion into the global TODO list Org produces. If one of the
2632 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2633 signify that no further action is necessary. If \"|\" is not found,
2634 the last keyword is treated as the only DONE state of the sequence.
2636 The command `\\[org-todo]' cycles an entry through these states, and one
2637 additional state where no keyword is present. For details about this
2638 cycling, see the manual.
2640 TODO keywords and interpretation can also be set on a per-file basis with
2641 the special #+SEQ_TODO and #+TYP_TODO lines.
2643 Each keyword can optionally specify a character for fast state selection
2644 \(in combination with the variable `org-use-fast-todo-selection')
2645 and specifiers for state change logging, using the same syntax that
2646 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2647 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2648 indicates to record a time stamp each time this state is selected.
2650 Each keyword may also specify if a timestamp or a note should be
2651 recorded when entering or leaving the state, by adding additional
2652 characters in the parenthesis after the keyword. This looks like this:
2653 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2654 record only the time of the state change. With X and Y being either
2655 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2656 Y when leaving the state if and only if the *target* state does not
2657 define X. You may omit any of the fast-selection key or X or /Y,
2658 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2660 For backward compatibility, this variable may also be just a list
2661 of keywords. In this case the interpretation (sequence or type) will be
2662 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2663 :group 'org-todo
2664 :group 'org-keywords
2665 :type '(choice
2666 (repeat :tag "Old syntax, just keywords"
2667 (string :tag "Keyword"))
2668 (repeat :tag "New syntax"
2669 (cons
2670 (choice
2671 :tag "Interpretation"
2672 ;;Quick and dirty way to see
2673 ;;`org-todo-interpretations'. This takes the
2674 ;;place of item arguments
2675 :convert-widget
2676 (lambda (widget)
2677 (widget-put widget
2678 :args (mapcar
2679 (lambda (x)
2680 (widget-convert
2681 (cons 'const x)))
2682 org-todo-interpretation-widgets))
2683 widget))
2684 (repeat
2685 (string :tag "Keyword"))))))
2687 (defvar-local org-todo-keywords-1 nil
2688 "All TODO and DONE keywords active in a buffer.")
2689 (defvar org-todo-keywords-for-agenda nil)
2690 (defvar org-done-keywords-for-agenda nil)
2691 (defvar org-todo-keyword-alist-for-agenda nil)
2692 (defvar org-tag-alist-for-agenda nil
2693 "Alist of all tags from all agenda files.")
2694 (defvar org-tag-groups-alist-for-agenda nil
2695 "Alist of all groups tags from all current agenda files.")
2696 (defvar-local org-tag-groups-alist nil)
2697 (defvar org-agenda-contributing-files nil)
2698 (defvar-local org-current-tag-alist nil
2699 "Alist of all tag groups in current buffer.
2700 This variable takes into consideration `org-tag-alist',
2701 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2702 (defvar-local org-not-done-keywords nil)
2703 (defvar-local org-done-keywords nil)
2704 (defvar-local org-todo-heads nil)
2705 (defvar-local org-todo-sets nil)
2706 (defvar-local org-todo-log-states nil)
2707 (defvar-local org-todo-kwd-alist nil)
2708 (defvar-local org-todo-key-alist nil)
2709 (defvar-local org-todo-key-trigger nil)
2711 (defcustom org-todo-interpretation 'sequence
2712 "Controls how TODO keywords are interpreted.
2713 This variable is in principle obsolete and is only used for
2714 backward compatibility, if the interpretation of todo keywords is
2715 not given already in `org-todo-keywords'. See that variable for
2716 more information."
2717 :group 'org-todo
2718 :group 'org-keywords
2719 :type '(choice (const sequence)
2720 (const type)))
2722 (defcustom org-use-fast-todo-selection t
2723 "\\<org-mode-map>\
2724 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2725 This variable describes if and under what circumstances the cycling
2726 mechanism for TODO keywords will be replaced by a single-key, direct
2727 selection scheme.
2729 When nil, fast selection is never used.
2731 When the symbol `prefix', it will be used when `org-todo' is called
2732 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2733 in an Org buffer, and
2734 `\\[universal-argument] t' in an agenda buffer.
2736 When t, fast selection is used by default. In this case, the prefix
2737 argument forces cycling instead.
2739 In all cases, the special interface is only used if access keys have
2740 actually been assigned by the user, i.e. if keywords in the configuration
2741 are followed by a letter in parenthesis, like TODO(t)."
2742 :group 'org-todo
2743 :type '(choice
2744 (const :tag "Never" nil)
2745 (const :tag "By default" t)
2746 (const :tag "Only with C-u C-c C-t" prefix)))
2748 (defcustom org-provide-todo-statistics t
2749 "Non-nil means update todo statistics after insert and toggle.
2750 ALL-HEADLINES means update todo statistics by including headlines
2751 with no TODO keyword as well, counting them as not done.
2752 A list of TODO keywords means the same, but skip keywords that are
2753 not in this list.
2754 When set to a list of two lists, the first list contains keywords
2755 to consider as TODO keywords, the second list contains keywords
2756 to consider as DONE keywords.
2758 When this is set, todo statistics is updated in the parent of the
2759 current entry each time a todo state is changed."
2760 :group 'org-todo
2761 :type '(choice
2762 (const :tag "Yes, only for TODO entries" t)
2763 (const :tag "Yes, including all entries" all-headlines)
2764 (repeat :tag "Yes, for TODOs in this list"
2765 (string :tag "TODO keyword"))
2766 (list :tag "Yes, for TODOs and DONEs in these lists"
2767 (repeat (string :tag "TODO keyword"))
2768 (repeat (string :tag "DONE keyword")))
2769 (other :tag "No TODO statistics" nil)))
2771 (defcustom org-hierarchical-todo-statistics t
2772 "Non-nil means TODO statistics covers just direct children.
2773 When nil, all entries in the subtree are considered.
2774 This has only an effect if `org-provide-todo-statistics' is set.
2775 To set this to nil for only a single subtree, use a COOKIE_DATA
2776 property and include the word \"recursive\" into the value."
2777 :group 'org-todo
2778 :type 'boolean)
2780 (defcustom org-after-todo-state-change-hook nil
2781 "Hook which is run after the state of a TODO item was changed.
2782 The new state (a string with a TODO keyword, or nil) is available in the
2783 Lisp variable `org-state'."
2784 :group 'org-todo
2785 :type 'hook)
2787 (defvar org-blocker-hook nil
2788 "Hook for functions that are allowed to block a state change.
2790 Functions in this hook should not modify the buffer.
2791 Each function gets as its single argument a property list,
2792 see `org-trigger-hook' for more information about this list.
2794 If any of the functions in this hook returns nil, the state change
2795 is blocked.")
2797 (defvar org-trigger-hook nil
2798 "Hook for functions that are triggered by a state change.
2800 Each function gets as its single argument a property list with at
2801 least the following elements:
2803 (:type type-of-change :position pos-at-entry-start
2804 :from old-state :to new-state)
2806 Depending on the type, more properties may be present.
2808 This mechanism is currently implemented for:
2810 TODO state changes
2811 ------------------
2812 :type todo-state-change
2813 :from previous state (keyword as a string), or nil, or a symbol
2814 `todo' or `done', to indicate the general type of state.
2815 :to new state, like in :from")
2817 (defcustom org-enforce-todo-dependencies nil
2818 "Non-nil means undone TODO entries will block switching the parent to DONE.
2819 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2820 be blocked if any prior sibling is not yet done.
2821 Finally, if the parent is blocked because of ordered siblings of its own,
2822 the child will also be blocked."
2823 :set (lambda (var val)
2824 (set var val)
2825 (if val
2826 (add-hook 'org-blocker-hook
2827 'org-block-todo-from-children-or-siblings-or-parent)
2828 (remove-hook 'org-blocker-hook
2829 'org-block-todo-from-children-or-siblings-or-parent)))
2830 :group 'org-todo
2831 :type 'boolean)
2833 (defcustom org-enforce-todo-checkbox-dependencies nil
2834 "Non-nil means unchecked boxes will block switching the parent to DONE.
2835 When this is nil, checkboxes have no influence on switching TODO states.
2836 When non-nil, you first need to check off all check boxes before the TODO
2837 entry can be switched to DONE.
2838 This variable needs to be set before org.el is loaded, and you need to
2839 restart Emacs after a change to make the change effective. The only way
2840 to change is while Emacs is running is through the customize interface."
2841 :set (lambda (var val)
2842 (set var val)
2843 (if val
2844 (add-hook 'org-blocker-hook
2845 'org-block-todo-from-checkboxes)
2846 (remove-hook 'org-blocker-hook
2847 'org-block-todo-from-checkboxes)))
2848 :group 'org-todo
2849 :type 'boolean)
2851 (defcustom org-treat-insert-todo-heading-as-state-change nil
2852 "Non-nil means inserting a TODO heading is treated as state change.
2853 So when the command `\\[org-insert-todo-heading]' is used, state change
2854 logging will apply if appropriate. When nil, the new TODO item will
2855 be inserted directly, and no logging will take place."
2856 :group 'org-todo
2857 :type 'boolean)
2859 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2860 "Non-nil means switching TODO states with S-cursor counts as state change.
2861 This is the default behavior. However, setting this to nil allows a
2862 convenient way to select a TODO state and bypass any logging associated
2863 with that."
2864 :group 'org-todo
2865 :type 'boolean)
2867 (defcustom org-todo-state-tags-triggers nil
2868 "Tag changes that should be triggered by TODO state changes.
2869 This is a list. Each entry is
2871 (state-change (tag . flag) .......)
2873 State-change can be a string with a state, and empty string to indicate the
2874 state that has no TODO keyword, or it can be one of the symbols `todo'
2875 or `done', meaning any not-done or done state, respectively."
2876 :group 'org-todo
2877 :group 'org-tags
2878 :type '(repeat
2879 (cons (choice :tag "When changing to"
2880 (const :tag "Not-done state" todo)
2881 (const :tag "Done state" done)
2882 (string :tag "State"))
2883 (repeat
2884 (cons :tag "Tag action"
2885 (string :tag "Tag")
2886 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2888 (defcustom org-log-done nil
2889 "Information to record when a task moves to the DONE state.
2891 Possible values are:
2893 nil Don't add anything, just change the keyword
2894 time Add a time stamp to the task
2895 note Prompt for a note and add it with template `org-log-note-headings'
2897 This option can also be set with on a per-file-basis with
2899 #+STARTUP: nologdone
2900 #+STARTUP: logdone
2901 #+STARTUP: lognotedone
2903 You can have local logging settings for a subtree by setting the LOGGING
2904 property to one or more of these keywords."
2905 :group 'org-todo
2906 :group 'org-progress
2907 :type '(choice
2908 (const :tag "No logging" nil)
2909 (const :tag "Record CLOSED timestamp" time)
2910 (const :tag "Record CLOSED timestamp with note." note)))
2912 ;; Normalize old uses of org-log-done.
2913 (cond
2914 ((eq org-log-done t) (setq org-log-done 'time))
2915 ((and (listp org-log-done) (memq 'done org-log-done))
2916 (setq org-log-done 'note)))
2918 (defcustom org-log-reschedule nil
2919 "Information to record when the scheduling date of a tasks is modified.
2921 Possible values are:
2923 nil Don't add anything, just change the date
2924 time Add a time stamp to the task
2925 note Prompt for a note and add it with template `org-log-note-headings'
2927 This option can also be set with on a per-file-basis with
2929 #+STARTUP: nologreschedule
2930 #+STARTUP: logreschedule
2931 #+STARTUP: lognotereschedule"
2932 :group 'org-todo
2933 :group 'org-progress
2934 :type '(choice
2935 (const :tag "No logging" nil)
2936 (const :tag "Record timestamp" time)
2937 (const :tag "Record timestamp with note." note)))
2939 (defcustom org-log-redeadline nil
2940 "Information to record when the deadline date of a tasks is modified.
2942 Possible values are:
2944 nil Don't add anything, just change the date
2945 time Add a time stamp to the task
2946 note Prompt for a note and add it with template `org-log-note-headings'
2948 This option can also be set with on a per-file-basis with
2950 #+STARTUP: nologredeadline
2951 #+STARTUP: logredeadline
2952 #+STARTUP: lognoteredeadline
2954 You can have local logging settings for a subtree by setting the LOGGING
2955 property to one or more of these keywords."
2956 :group 'org-todo
2957 :group 'org-progress
2958 :type '(choice
2959 (const :tag "No logging" nil)
2960 (const :tag "Record timestamp" time)
2961 (const :tag "Record timestamp with note." note)))
2963 (defcustom org-log-note-clock-out nil
2964 "Non-nil means record a note when clocking out of an item.
2965 This can also be configured on a per-file basis by adding one of
2966 the following lines anywhere in the buffer:
2968 #+STARTUP: lognoteclock-out
2969 #+STARTUP: nolognoteclock-out"
2970 :group 'org-todo
2971 :group 'org-progress
2972 :type 'boolean)
2974 (defcustom org-log-done-with-time t
2975 "Non-nil means the CLOSED time stamp will contain date and time.
2976 When nil, only the date will be recorded."
2977 :group 'org-progress
2978 :type 'boolean)
2980 (defcustom org-log-note-headings
2981 '((done . "CLOSING NOTE %t")
2982 (state . "State %-12s from %-12S %t")
2983 (note . "Note taken on %t")
2984 (reschedule . "Rescheduled from %S on %t")
2985 (delschedule . "Not scheduled, was %S on %t")
2986 (redeadline . "New deadline from %S on %t")
2987 (deldeadline . "Removed deadline, was %S on %t")
2988 (refile . "Refiled on %t")
2989 (clock-out . ""))
2990 "Headings for notes added to entries.
2992 The value is an alist, with the car being a symbol indicating the
2993 note context, and the cdr is the heading to be used. The heading
2994 may also be the empty string. The following placeholders can be
2995 used:
2997 %t a time stamp.
2998 %T an active time stamp instead the default inactive one
2999 %d a short-format time stamp.
3000 %D an active short-format time stamp.
3001 %s the new TODO state or time stamp (inactive), in double quotes.
3002 %S the old TODO state or time stamp (inactive), in double quotes.
3003 %u the user name.
3004 %U full user name.
3006 In fact, it is not a good idea to change the `state' entry,
3007 because Agenda Log mode depends on the format of these entries."
3008 :group 'org-todo
3009 :group 'org-progress
3010 :type '(list :greedy t
3011 (cons (const :tag "Heading when closing an item" done) string)
3012 (cons (const :tag
3013 "Heading when changing todo state (todo sequence only)"
3014 state) string)
3015 (cons (const :tag "Heading when just taking a note" note) string)
3016 (cons (const :tag "Heading when rescheduling" reschedule) string)
3017 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3018 (cons (const :tag "Heading when changing deadline" redeadline) string)
3019 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3020 (cons (const :tag "Heading when refiling" refile) string)
3021 (cons (const :tag "Heading when clocking out" clock-out) string)))
3023 (unless (assq 'note org-log-note-headings)
3024 (push '(note . "%t") org-log-note-headings))
3026 (defcustom org-log-into-drawer nil
3027 "Non-nil means insert state change notes and time stamps into a drawer.
3028 When nil, state changes notes will be inserted after the headline and
3029 any scheduling and clock lines, but not inside a drawer.
3031 The value of this variable should be the name of the drawer to use.
3032 LOGBOOK is proposed as the default drawer for this purpose, you can
3033 also set this to a string to define the drawer of your choice.
3035 A value of t is also allowed, representing \"LOGBOOK\".
3037 A value of t or nil can also be set with on a per-file-basis with
3039 #+STARTUP: logdrawer
3040 #+STARTUP: nologdrawer
3042 If this variable is set, `org-log-state-notes-insert-after-drawers'
3043 will be ignored.
3045 You can set the property LOG_INTO_DRAWER to overrule this setting for
3046 a subtree.
3048 Do not check directly this variable in a Lisp program. Call
3049 function `org-log-into-drawer' instead."
3050 :group 'org-todo
3051 :group 'org-progress
3052 :type '(choice
3053 (const :tag "Not into a drawer" nil)
3054 (const :tag "LOGBOOK" t)
3055 (string :tag "Other")))
3057 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3059 (defun org-log-into-drawer ()
3060 "Name of the log drawer, as a string, or nil.
3061 This is the value of `org-log-into-drawer'. However, if the
3062 current entry has or inherits a LOG_INTO_DRAWER property, it will
3063 be used instead of the default value."
3064 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3065 (cond ((equal p "nil") nil)
3066 ((equal p "t") "LOGBOOK")
3067 ((stringp p) p)
3068 (p "LOGBOOK")
3069 ((stringp org-log-into-drawer) org-log-into-drawer)
3070 (org-log-into-drawer "LOGBOOK"))))
3072 (defcustom org-log-state-notes-insert-after-drawers nil
3073 "Non-nil means insert state change notes after any drawers in entry.
3074 Only the drawers that *immediately* follow the headline and the
3075 deadline/scheduled line are skipped.
3076 When nil, insert notes right after the heading and perhaps the line
3077 with deadline/scheduling if present.
3079 This variable will have no effect if `org-log-into-drawer' is
3080 set."
3081 :group 'org-todo
3082 :group 'org-progress
3083 :type 'boolean)
3085 (defcustom org-log-states-order-reversed t
3086 "Non-nil means the latest state note will be directly after heading.
3087 When nil, the state change notes will be ordered according to time.
3089 This option can also be set with on a per-file-basis with
3091 #+STARTUP: logstatesreversed
3092 #+STARTUP: nologstatesreversed"
3093 :group 'org-todo
3094 :group 'org-progress
3095 :type 'boolean)
3097 (defcustom org-todo-repeat-to-state nil
3098 "The TODO state to which a repeater should return the repeating task.
3099 By default this is the first task in a TODO sequence, or the previous state
3100 in a TODO_TYP set. But you can specify another task here.
3101 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3102 :group 'org-todo
3103 :version "24.1"
3104 :type '(choice (const :tag "Head of sequence" nil)
3105 (string :tag "Specific state")))
3107 (defcustom org-log-repeat 'time
3108 "Non-nil means record moving through the DONE state when triggering repeat.
3109 An auto-repeating task is immediately switched back to TODO when
3110 marked DONE. If you are not logging state changes (by adding \"@\"
3111 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3112 record a closing note, there will be no record of the task moving
3113 through DONE. This variable forces taking a note anyway.
3115 nil Don't force a record
3116 time Record a time stamp
3117 note Prompt for a note and add it with template `org-log-note-headings'
3119 This option can also be set with on a per-file-basis with
3121 #+STARTUP: nologrepeat
3122 #+STARTUP: logrepeat
3123 #+STARTUP: lognoterepeat
3125 You can have local logging settings for a subtree by setting the LOGGING
3126 property to one or more of these keywords."
3127 :group 'org-todo
3128 :group 'org-progress
3129 :type '(choice
3130 (const :tag "Don't force a record" nil)
3131 (const :tag "Force recording the DONE state" time)
3132 (const :tag "Force recording a note with the DONE state" note)))
3135 (defgroup org-priorities nil
3136 "Priorities in Org mode."
3137 :tag "Org Priorities"
3138 :group 'org-todo)
3140 (defcustom org-enable-priority-commands t
3141 "Non-nil means priority commands are active.
3142 When nil, these commands will be disabled, so that you never accidentally
3143 set a priority."
3144 :group 'org-priorities
3145 :type 'boolean)
3147 (defcustom org-highest-priority ?A
3148 "The highest priority of TODO items. A character like ?A, ?B etc.
3149 Must have a smaller ASCII number than `org-lowest-priority'."
3150 :group 'org-priorities
3151 :type 'character)
3153 (defcustom org-lowest-priority ?C
3154 "The lowest priority of TODO items. A character like ?A, ?B etc.
3155 Must have a larger ASCII number than `org-highest-priority'."
3156 :group 'org-priorities
3157 :type 'character)
3159 (defcustom org-default-priority ?B
3160 "The default priority of TODO items.
3161 This is the priority an item gets if no explicit priority is given.
3162 When starting to cycle on an empty priority the first step in the cycle
3163 depends on `org-priority-start-cycle-with-default'. The resulting first
3164 step priority must not exceed the range from `org-highest-priority' to
3165 `org-lowest-priority' which means that `org-default-priority' has to be
3166 in this range exclusive or inclusive the range boundaries. Else the
3167 first step refuses to set the default and the second will fall back
3168 to (depending on the command used) the highest or lowest priority."
3169 :group 'org-priorities
3170 :type 'character)
3172 (defcustom org-priority-start-cycle-with-default t
3173 "Non-nil means start with default priority when starting to cycle.
3174 When this is nil, the first step in the cycle will be (depending on the
3175 command used) one higher or lower than the default priority.
3176 See also `org-default-priority'."
3177 :group 'org-priorities
3178 :type 'boolean)
3180 (defcustom org-get-priority-function nil
3181 "Function to extract the priority from a string.
3182 The string is normally the headline. If this is nil Org computes the
3183 priority from the priority cookie like [#A] in the headline. It returns
3184 an integer, increasing by 1000 for each priority level.
3185 The user can set a different function here, which should take a string
3186 as an argument and return the numeric priority."
3187 :group 'org-priorities
3188 :version "24.1"
3189 :type '(choice
3190 (const nil)
3191 (function)))
3193 (defgroup org-time nil
3194 "Options concerning time stamps and deadlines in Org mode."
3195 :tag "Org Time"
3196 :group 'org)
3198 (defcustom org-time-stamp-rounding-minutes '(0 5)
3199 "Number of minutes to round time stamps to.
3200 \\<org-mode-map>\
3201 These are two values, the first applies when first creating a time stamp.
3202 The second applies when changing it with the commands `S-up' and `S-down'.
3203 When changing the time stamp, this means that it will change in steps
3204 of N minutes, as given by the second value.
3206 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3207 numbers should be factors of 60, so for example 5, 10, 15.
3209 When this is larger than 1, you can still force an exact time stamp by using
3210 a double prefix argument to a time stamp command like \
3211 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3212 and by using a prefix arg to `S-up/down' to specify the exact number
3213 of minutes to shift."
3214 :group 'org-time
3215 :get (lambda (var) ; Make sure both elements are there
3216 (if (integerp (default-value var))
3217 (list (default-value var) 5)
3218 (default-value var)))
3219 :type '(list
3220 (integer :tag "when inserting times")
3221 (integer :tag "when modifying times")))
3223 ;; Normalize old customizations of this variable.
3224 (when (integerp org-time-stamp-rounding-minutes)
3225 (setq org-time-stamp-rounding-minutes
3226 (list org-time-stamp-rounding-minutes
3227 org-time-stamp-rounding-minutes)))
3229 (defcustom org-display-custom-times nil
3230 "Non-nil means overlay custom formats over all time stamps.
3231 The formats are defined through the variable `org-time-stamp-custom-formats'.
3232 To turn this on on a per-file basis, insert anywhere in the file:
3233 #+STARTUP: customtime"
3234 :group 'org-time
3235 :set 'set-default
3236 :type 'sexp)
3237 (make-variable-buffer-local 'org-display-custom-times)
3239 (defcustom org-time-stamp-custom-formats
3240 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3241 "Custom formats for time stamps. See `format-time-string' for the syntax.
3242 These are overlaid over the default ISO format if the variable
3243 `org-display-custom-times' is set. Time like %H:%M should be at the
3244 end of the second format. The custom formats are also honored by export
3245 commands, if custom time display is turned on at the time of export."
3246 :group 'org-time
3247 :type 'sexp)
3249 (defun org-time-stamp-format (&optional long inactive)
3250 "Get the right format for a time string."
3251 (let ((f (if long (cdr org-time-stamp-formats)
3252 (car org-time-stamp-formats))))
3253 (if inactive
3254 (concat "[" (substring f 1 -1) "]")
3255 f)))
3257 (defcustom org-deadline-warning-days 14
3258 "Number of days before expiration during which a deadline becomes active.
3259 This variable governs the display in sparse trees and in the agenda.
3260 When 0 or negative, it means use this number (the absolute value of it)
3261 even if a deadline has a different individual lead time specified.
3263 Custom commands can set this variable in the options section."
3264 :group 'org-time
3265 :group 'org-agenda-daily/weekly
3266 :type 'integer)
3268 (defcustom org-scheduled-delay-days 0
3269 "Number of days before a scheduled item becomes active.
3270 This variable governs the display in sparse trees and in the agenda.
3271 The default value (i.e. 0) means: don't delay scheduled item.
3272 When negative, it means use this number (the absolute value of it)
3273 even if a scheduled item has a different individual delay time
3274 specified.
3276 Custom commands can set this variable in the options section."
3277 :group 'org-time
3278 :group 'org-agenda-daily/weekly
3279 :version "24.4"
3280 :package-version '(Org . "8.0")
3281 :type 'integer)
3283 (defcustom org-read-date-prefer-future t
3284 "Non-nil means assume future for incomplete date input from user.
3285 This affects the following situations:
3286 1. The user gives a month but not a year.
3287 For example, if it is April and you enter \"feb 2\", this will be read
3288 as Feb 2, *next* year. \"May 5\", however, will be this year.
3289 2. The user gives a day, but no month.
3290 For example, if today is the 15th, and you enter \"3\", Org will read
3291 this as the third of *next* month. However, if you enter \"17\",
3292 it will be considered as *this* month.
3294 If you set this variable to the symbol `time', then also the following
3295 will work:
3297 3. If the user gives a time.
3298 If the time is before now, it will be interpreted as tomorrow.
3300 Currently none of this works for ISO week specifications.
3302 When this option is nil, the current day, month and year will always be
3303 used as defaults.
3305 See also `org-agenda-jump-prefer-future'."
3306 :group 'org-time
3307 :type '(choice
3308 (const :tag "Never" nil)
3309 (const :tag "Check month and day" t)
3310 (const :tag "Check month, day, and time" time)))
3312 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3313 "Should the agenda jump command prefer the future for incomplete dates?
3314 The default is to do the same as configured in `org-read-date-prefer-future'.
3315 But you can also set a deviating value here.
3316 This may t or nil, or the symbol `org-read-date-prefer-future'."
3317 :group 'org-agenda
3318 :group 'org-time
3319 :version "24.1"
3320 :type '(choice
3321 (const :tag "Use org-read-date-prefer-future"
3322 org-read-date-prefer-future)
3323 (const :tag "Never" nil)
3324 (const :tag "Always" t)))
3326 (defcustom org-read-date-force-compatible-dates t
3327 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3329 Depending on the system Emacs is running on, certain dates cannot
3330 be represented with the type used internally to represent time.
3331 Dates between 1970-1-1 and 2038-1-1 can always be represented
3332 correctly. Some systems allow for earlier dates, some for later,
3333 some for both. One way to find out it to insert any date into an
3334 Org buffer, putting the cursor on the year and hitting S-up and
3335 S-down to test the range.
3337 When this variable is set to t, the date/time prompt will not let
3338 you specify dates outside the 1970-2037 range, so it is certain that
3339 these dates will work in whatever version of Emacs you are
3340 running, and also that you can move a file from one Emacs implementation
3341 to another. WHenever Org is forcing the year for you, it will display
3342 a message and beep.
3344 When this variable is nil, Org will check if the date is
3345 representable in the specific Emacs implementation you are using.
3346 If not, it will force a year, usually the current year, and beep
3347 to remind you. Currently this setting is not recommended because
3348 the likelihood that you will open your Org files in an Emacs that
3349 has limited date range is not negligible.
3351 A workaround for this problem is to use diary sexp dates for time
3352 stamps outside of this range."
3353 :group 'org-time
3354 :version "24.1"
3355 :type 'boolean)
3357 (defcustom org-read-date-display-live t
3358 "Non-nil means display current interpretation of date prompt live.
3359 This display will be in an overlay, in the minibuffer."
3360 :group 'org-time
3361 :type 'boolean)
3363 (defcustom org-read-date-popup-calendar t
3364 "Non-nil means pop up a calendar when prompting for a date.
3365 In the calendar, the date can be selected with mouse-1. However, the
3366 minibuffer will also be active, and you can simply enter the date as well.
3367 When nil, only the minibuffer will be available."
3368 :group 'org-time
3369 :type 'boolean)
3370 (defvaralias 'org-popup-calendar-for-date-prompt
3371 'org-read-date-popup-calendar)
3373 (defcustom org-extend-today-until 0
3374 "The hour when your day really ends. Must be an integer.
3375 This has influence for the following applications:
3376 - When switching the agenda to \"today\". It it is still earlier than
3377 the time given here, the day recognized as TODAY is actually yesterday.
3378 - When a date is read from the user and it is still before the time given
3379 here, the current date and time will be assumed to be yesterday, 23:59.
3380 Also, timestamps inserted in capture templates follow this rule.
3382 IMPORTANT: This is a feature whose implementation is and likely will
3383 remain incomplete. Really, it is only here because past midnight seems to
3384 be the favorite working time of John Wiegley :-)"
3385 :group 'org-time
3386 :type 'integer)
3388 (defcustom org-use-effective-time nil
3389 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3390 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3391 \"effective time\" of any timestamps between midnight and 8am will be
3392 23:59 of the previous day."
3393 :group 'org-time
3394 :version "24.1"
3395 :type 'boolean)
3397 (defcustom org-use-last-clock-out-time-as-effective-time nil
3398 "When non-nil, use the last clock out time for `org-todo'.
3399 Note that this option has precedence over the combined use of
3400 `org-use-effective-time' and `org-extend-today-until'."
3401 :group 'org-time
3402 :version "24.4"
3403 :package-version '(Org . "8.0")
3404 :type 'boolean)
3406 (defcustom org-edit-timestamp-down-means-later nil
3407 "Non-nil means S-down will increase the time in a time stamp.
3408 When nil, S-up will increase."
3409 :group 'org-time
3410 :type 'boolean)
3412 (defcustom org-calendar-follow-timestamp-change t
3413 "Non-nil means make the calendar window follow timestamp changes.
3414 When a timestamp is modified and the calendar window is visible, it will be
3415 moved to the new date."
3416 :group 'org-time
3417 :type 'boolean)
3419 (defgroup org-tags nil
3420 "Options concerning tags in Org mode."
3421 :tag "Org Tags"
3422 :group 'org)
3424 (defcustom org-tag-alist nil
3425 "Default tags available in Org files.
3427 The value of this variable is an alist. Associations either:
3429 (TAG)
3430 (TAG . SELECT)
3431 (SPECIAL)
3433 where TAG is a tag as a string, SELECT is character, used to
3434 select that tag through the fast tag selection interface, and
3435 SPECIAL is one of the following keywords: `:startgroup',
3436 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3437 `:newline'. These keywords are used to define a hierarchy of
3438 tags. See manual for details.
3440 When this variable is nil, Org mode bases tag input on what is
3441 already in the buffer. The value can be overridden locally by
3442 using a TAGS keyword, e.g.,
3444 #+TAGS: tag1 tag2
3446 See also `org-tag-persistent-alist' to sidestep this behavior."
3447 :group 'org-tags
3448 :type '(repeat
3449 (choice
3450 (cons (string :tag "Tag name")
3451 (character :tag "Access char"))
3452 (const :tag "Start radio group" (:startgroup))
3453 (const :tag "Start tag group, non distinct" (:startgrouptag))
3454 (const :tag "Group tags delimiter" (:grouptags))
3455 (const :tag "End radio group" (:endgroup))
3456 (const :tag "End tag group, non distinct" (:endgrouptag))
3457 (const :tag "New line" (:newline)))))
3459 (defcustom org-tag-persistent-alist nil
3460 "Tags always available in Org files.
3462 The value of this variable is an alist. Associations either:
3464 (TAG)
3465 (TAG . SELECT)
3466 (SPECIAL)
3468 where TAG is a tag as a string, SELECT is a character, used to
3469 select that tag through the fast tag selection interface, and
3470 SPECIAL is one of the following keywords: `:startgroup',
3471 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3472 `:newline'. These keywords are used to define a hierarchy of
3473 tags. See manual for details.
3475 Unlike to `org-tag-alist', tags defined in this variable do not
3476 depend on a local TAGS keyword. Instead, to disable these tags
3477 on a per-file basis, insert anywhere in the file:
3479 #+STARTUP: noptag"
3480 :group 'org-tags
3481 :type '(repeat
3482 (choice
3483 (cons (string :tag "Tag name")
3484 (character :tag "Access char"))
3485 (const :tag "Start radio group" (:startgroup))
3486 (const :tag "Start tag group, non distinct" (:startgrouptag))
3487 (const :tag "Group tags delimiter" (:grouptags))
3488 (const :tag "End radio group" (:endgroup))
3489 (const :tag "End tag group, non distinct" (:endgrouptag))
3490 (const :tag "New line" (:newline)))))
3492 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3493 "If non-nil, always offer completion for all tags of all agenda files.
3494 Instead of customizing this variable directly, you might want to
3495 set it locally for capture buffers, because there no list of
3496 tags in that file can be created dynamically (there are none).
3498 (add-hook \\='org-capture-mode-hook
3499 (lambda ()
3500 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3501 :group 'org-tags
3502 :version "24.1"
3503 :type 'boolean)
3505 (defvar org-file-tags nil
3506 "List of tags that can be inherited by all entries in the file.
3507 The tags will be inherited if the variable `org-use-tag-inheritance'
3508 says they should be.
3509 This variable is populated from #+FILETAGS lines.")
3511 (defcustom org-use-fast-tag-selection 'auto
3512 "Non-nil means use fast tag selection scheme.
3513 This is a special interface to select and deselect tags with single keys.
3514 When nil, fast selection is never used.
3515 When the symbol `auto', fast selection is used if and only if selection
3516 characters for tags have been configured, either through the variable
3517 `org-tag-alist' or through a #+TAGS line in the buffer.
3518 When t, fast selection is always used and selection keys are assigned
3519 automatically if necessary."
3520 :group 'org-tags
3521 :type '(choice
3522 (const :tag "Always" t)
3523 (const :tag "Never" nil)
3524 (const :tag "When selection characters are configured" auto)))
3526 (defcustom org-fast-tag-selection-single-key nil
3527 "Non-nil means fast tag selection exits after first change.
3528 When nil, you have to press RET to exit it.
3529 During fast tag selection, you can toggle this flag with `C-c'.
3530 This variable can also have the value `expert'. In this case, the window
3531 displaying the tags menu is not even shown, until you press C-c again."
3532 :group 'org-tags
3533 :type '(choice
3534 (const :tag "No" nil)
3535 (const :tag "Yes" t)
3536 (const :tag "Expert" expert)))
3538 (defvar org-fast-tag-selection-include-todo nil
3539 "Non-nil means fast tags selection interface will also offer TODO states.
3540 This is an undocumented feature, you should not rely on it.")
3542 (defcustom org-tags-column -77
3543 "The column to which tags should be indented in a headline.
3544 If this number is positive, it specifies the column. If it is negative,
3545 it means that the tags should be flushright to that column. For example,
3546 -80 works well for a normal 80 character screen.
3547 When 0, place tags directly after headline text, with only one space in
3548 between."
3549 :group 'org-tags
3550 :type 'integer)
3552 (defcustom org-auto-align-tags t
3553 "Non-nil keeps tags aligned when modifying headlines.
3554 Some operations (i.e. demoting) change the length of a headline and
3555 therefore shift the tags around. With this option turned on, after
3556 each such operation the tags are again aligned to `org-tags-column'."
3557 :group 'org-tags
3558 :type 'boolean)
3560 (defcustom org-use-tag-inheritance t
3561 "Non-nil means tags in levels apply also for sublevels.
3562 When nil, only the tags directly given in a specific line apply there.
3563 This may also be a list of tags that should be inherited, or a regexp that
3564 matches tags that should be inherited. Additional control is possible
3565 with the variable `org-tags-exclude-from-inheritance' which gives an
3566 explicit list of tags to be excluded from inheritance, even if the value of
3567 `org-use-tag-inheritance' would select it for inheritance.
3569 If this option is t, a match early-on in a tree can lead to a large
3570 number of matches in the subtree when constructing the agenda or creating
3571 a sparse tree. If you only want to see the first match in a tree during
3572 a search, check out the variable `org-tags-match-list-sublevels'."
3573 :group 'org-tags
3574 :type '(choice
3575 (const :tag "Not" nil)
3576 (const :tag "Always" t)
3577 (repeat :tag "Specific tags" (string :tag "Tag"))
3578 (regexp :tag "Tags matched by regexp")))
3580 (defcustom org-tags-exclude-from-inheritance nil
3581 "List of tags that should never be inherited.
3582 This is a way to exclude a few tags from inheritance. For way to do
3583 the opposite, to actively allow inheritance for selected tags,
3584 see the variable `org-use-tag-inheritance'."
3585 :group 'org-tags
3586 :type '(repeat (string :tag "Tag")))
3588 (defun org-tag-inherit-p (tag)
3589 "Check if TAG is one that should be inherited."
3590 (cond
3591 ((member tag org-tags-exclude-from-inheritance) nil)
3592 ((eq org-use-tag-inheritance t) t)
3593 ((not org-use-tag-inheritance) nil)
3594 ((stringp org-use-tag-inheritance)
3595 (string-match org-use-tag-inheritance tag))
3596 ((listp org-use-tag-inheritance)
3597 (member tag org-use-tag-inheritance))
3598 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3600 (defcustom org-tags-match-list-sublevels t
3601 "Non-nil means list also sublevels of headlines matching a search.
3602 This variable applies to tags/property searches, and also to stuck
3603 projects because this search is based on a tags match as well.
3605 When set to the symbol `indented', sublevels are indented with
3606 leading dots.
3608 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3609 the sublevels of a headline matching a tag search often also match
3610 the same search. Listing all of them can create very long lists.
3611 Setting this variable to nil causes subtrees of a match to be skipped.
3613 This variable is semi-obsolete and probably should always be true. It
3614 is better to limit inheritance to certain tags using the variables
3615 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3616 :group 'org-tags
3617 :type '(choice
3618 (const :tag "No, don't list them" nil)
3619 (const :tag "Yes, do list them" t)
3620 (const :tag "List them, indented with leading dots" indented)))
3622 (defcustom org-tags-sort-function nil
3623 "When set, tags are sorted using this function as a comparator."
3624 :group 'org-tags
3625 :type '(choice
3626 (const :tag "No sorting" nil)
3627 (const :tag "Alphabetical" string<)
3628 (const :tag "Reverse alphabetical" string>)
3629 (function :tag "Custom function" nil)))
3631 (defvar org-tags-history nil
3632 "History of minibuffer reads for tags.")
3633 (defvar org-last-tags-completion-table nil
3634 "The last used completion table for tags.")
3635 (defvar org-after-tags-change-hook nil
3636 "Hook that is run after the tags in a line have changed.")
3638 (defgroup org-properties nil
3639 "Options concerning properties in Org mode."
3640 :tag "Org Properties"
3641 :group 'org)
3643 (defcustom org-property-format "%-10s %s"
3644 "How property key/value pairs should be formatted by `indent-line'.
3645 When `indent-line' hits a property definition, it will format the line
3646 according to this format, mainly to make sure that the values are
3647 lined-up with respect to each other."
3648 :group 'org-properties
3649 :type 'string)
3651 (defcustom org-properties-postprocess-alist nil
3652 "Alist of properties and functions to adjust inserted values.
3653 Elements of this alist must be of the form
3655 ([string] [function])
3657 where [string] must be a property name and [function] must be a
3658 lambda expression: this lambda expression must take one argument,
3659 the value to adjust, and return the new value as a string.
3661 For example, this element will allow the property \"Remaining\"
3662 to be updated wrt the relation between the \"Effort\" property
3663 and the clock summary:
3665 ((\"Remaining\" (lambda(value)
3666 (let ((clocksum (org-clock-sum-current-item))
3667 (effort (org-duration-to-minutes
3668 (org-entry-get (point) \"Effort\"))))
3669 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3670 :group 'org-properties
3671 :version "24.1"
3672 :type '(alist :key-type (string :tag "Property")
3673 :value-type (function :tag "Function")))
3675 (defcustom org-use-property-inheritance nil
3676 "Non-nil means properties apply also for sublevels.
3678 This setting is chiefly used during property searches. Turning it on can
3679 cause significant overhead when doing a search, which is why it is not
3680 on by default.
3682 When nil, only the properties directly given in the current entry count.
3683 When t, every property is inherited. The value may also be a list of
3684 properties that should have inheritance, or a regular expression matching
3685 properties that should be inherited.
3687 However, note that some special properties use inheritance under special
3688 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3689 and the properties ending in \"_ALL\" when they are used as descriptor
3690 for valid values of a property.
3692 Note for programmers:
3693 When querying an entry with `org-entry-get', you can control if inheritance
3694 should be used. By default, `org-entry-get' looks only at the local
3695 properties. You can request inheritance by setting the inherit argument
3696 to t (to force inheritance) or to `selective' (to respect the setting
3697 in this variable)."
3698 :group 'org-properties
3699 :type '(choice
3700 (const :tag "Not" nil)
3701 (const :tag "Always" t)
3702 (repeat :tag "Specific properties" (string :tag "Property"))
3703 (regexp :tag "Properties matched by regexp")))
3705 (defun org-property-inherit-p (property)
3706 "Return a non-nil value if PROPERTY should be inherited."
3707 (cond
3708 ((eq org-use-property-inheritance t) t)
3709 ((not org-use-property-inheritance) nil)
3710 ((stringp org-use-property-inheritance)
3711 (string-match org-use-property-inheritance property))
3712 ((listp org-use-property-inheritance)
3713 (member-ignore-case property org-use-property-inheritance))
3714 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3716 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3717 "The default column format, if no other format has been defined.
3718 This variable can be set on the per-file basis by inserting a line
3720 #+COLUMNS: %25ITEM ....."
3721 :group 'org-properties
3722 :type 'string)
3724 (defcustom org-columns-ellipses ".."
3725 "The ellipses to be used when a field in column view is truncated.
3726 When this is the empty string, as many characters as possible are shown,
3727 but then there will be no visual indication that the field has been truncated.
3728 When this is a string of length N, the last N characters of a truncated
3729 field are replaced by this string. If the column is narrower than the
3730 ellipses string, only part of the ellipses string will be shown."
3731 :group 'org-properties
3732 :type 'string)
3734 (defconst org-global-properties-fixed
3735 '(("VISIBILITY_ALL" . "folded children content all")
3736 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3737 "List of property/value pairs that can be inherited by any entry.
3739 These are fixed values, for the preset properties. The user variable
3740 that can be used to add to this list is `org-global-properties'.
3742 The entries in this list are cons cells where the car is a property
3743 name and cdr is a string with the value. If the value represents
3744 multiple items like an \"_ALL\" property, separate the items by
3745 spaces.")
3747 (defcustom org-global-properties nil
3748 "List of property/value pairs that can be inherited by any entry.
3750 This list will be combined with the constant `org-global-properties-fixed'.
3752 The entries in this list are cons cells where the car is a property
3753 name and cdr is a string with the value.
3755 You can set buffer-local values for the same purpose in the variable
3756 `org-file-properties' this by adding lines like
3758 #+PROPERTY: NAME VALUE"
3759 :group 'org-properties
3760 :type '(repeat
3761 (cons (string :tag "Property")
3762 (string :tag "Value"))))
3764 (defvar-local org-file-properties nil
3765 "List of property/value pairs that can be inherited by any entry.
3766 Valid for the current buffer.
3767 This variable is populated from #+PROPERTY lines.")
3769 (defgroup org-agenda nil
3770 "Options concerning agenda views in Org mode."
3771 :tag "Org Agenda"
3772 :group 'org)
3774 (defvar-local org-category nil
3775 "Variable used by org files to set a category for agenda display.
3776 Such files should use a file variable to set it, for example
3778 # -*- mode: org; org-category: \"ELisp\"
3780 or contain a special line
3782 #+CATEGORY: ELisp
3784 If the file does not specify a category, then file's base name
3785 is used instead.")
3786 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3788 (defcustom org-agenda-files nil
3789 "The files to be used for agenda display.
3791 If an entry is a directory, all files in that directory that are matched
3792 by `org-agenda-file-regexp' will be part of the file list.
3794 If the value of the variable is not a list but a single file name, then
3795 the list of agenda files is actually stored and maintained in that file,
3796 one agenda file per line. In this file paths can be given relative to
3797 `org-directory'. Tilde expansion and environment variable substitution
3798 are also made.
3800 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3801 and removed with `\\[org-remove-file]'."
3802 :group 'org-agenda
3803 :type '(choice
3804 (repeat :tag "List of files and directories" file)
3805 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3807 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3808 "Regular expression to match files for `org-agenda-files'.
3809 If any element in the list in that variable contains a directory instead
3810 of a normal file, all files in that directory that are matched by this
3811 regular expression will be included."
3812 :group 'org-agenda
3813 :type 'regexp)
3815 (defcustom org-agenda-text-search-extra-files nil
3816 "List of extra files to be searched by text search commands.
3817 These files will be searched in addition to the agenda files by the
3818 commands `org-search-view' (`\\[org-agenda] s') \
3819 and `org-occur-in-agenda-files'.
3820 Note that these files will only be searched for text search commands,
3821 not for the other agenda views like todo lists, tag searches or the weekly
3822 agenda. This variable is intended to list notes and possibly archive files
3823 that should also be searched by these two commands.
3824 In fact, if the first element in the list is the symbol `agenda-archives',
3825 then all archive files of all agenda files will be added to the search
3826 scope."
3827 :group 'org-agenda
3828 :type '(set :greedy t
3829 (const :tag "Agenda Archives" agenda-archives)
3830 (repeat :inline t (file))))
3832 (defvaralias 'org-agenda-multi-occur-extra-files
3833 'org-agenda-text-search-extra-files)
3835 (defcustom org-agenda-skip-unavailable-files nil
3836 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3837 A nil value means to remove them, after a query, from the list."
3838 :group 'org-agenda
3839 :type 'boolean)
3841 (defcustom org-calendar-to-agenda-key [?c]
3842 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3843 The command `org-calendar-goto-agenda' will be bound to this key. The
3844 default is the character `c' because then `c' can be used to switch back and
3845 forth between agenda and calendar."
3846 :group 'org-agenda
3847 :type 'sexp)
3849 (defcustom org-calendar-insert-diary-entry-key [?i]
3850 "The key to be installed in `calendar-mode-map' for adding diary entries.
3851 This option is irrelevant until `org-agenda-diary-file' has been configured
3852 to point to an Org file. When that is the case, the command
3853 `org-agenda-diary-entry' will be bound to the key given here, by default
3854 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3855 if you want to continue doing this, you need to change this to a different
3856 key."
3857 :group 'org-agenda
3858 :type 'sexp)
3860 (defcustom org-agenda-diary-file 'diary-file
3861 "File to which to add new entries with the `i' key in agenda and calendar.
3862 When this is the symbol `diary-file', the functionality in the Emacs
3863 calendar will be used to add entries to the `diary-file'. But when this
3864 points to a file, `org-agenda-diary-entry' will be used instead."
3865 :group 'org-agenda
3866 :type '(choice
3867 (const :tag "The standard Emacs diary file" diary-file)
3868 (file :tag "Special Org file diary entries")))
3870 (eval-after-load "calendar"
3871 '(progn
3872 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3873 'org-calendar-goto-agenda)
3874 (add-hook 'calendar-mode-hook
3875 (lambda ()
3876 (unless (eq org-agenda-diary-file 'diary-file)
3877 (define-key calendar-mode-map
3878 org-calendar-insert-diary-entry-key
3879 'org-agenda-diary-entry))))))
3881 (defgroup org-latex nil
3882 "Options for embedding LaTeX code into Org mode."
3883 :tag "Org LaTeX"
3884 :group 'org)
3886 (defcustom org-format-latex-options
3887 '(:foreground default :background default :scale 1.0
3888 :html-foreground "Black" :html-background "Transparent"
3889 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3890 "Options for creating images from LaTeX fragments.
3891 This is a property list with the following properties:
3892 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3893 `default' means use the foreground of the default face.
3894 `auto' means use the foreground from the text face.
3895 :background the background color, or \"Transparent\".
3896 `default' means use the background of the default face.
3897 `auto' means use the background from the text face.
3898 :scale a scaling factor for the size of the images, to get more pixels
3899 :html-foreground, :html-background, :html-scale
3900 the same numbers for HTML export.
3901 :matchers a list indicating which matchers should be used to
3902 find LaTeX fragments. Valid members of this list are:
3903 \"begin\" find environments
3904 \"$1\" find single characters surrounded by $.$
3905 \"$\" find math expressions surrounded by $...$
3906 \"$$\" find math expressions surrounded by $$....$$
3907 \"\\(\" find math expressions surrounded by \\(...\\)
3908 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3909 :group 'org-latex
3910 :type 'plist)
3912 (defcustom org-format-latex-signal-error t
3913 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3914 When nil, just push out a message."
3915 :group 'org-latex
3916 :version "24.1"
3917 :type 'boolean)
3919 (defcustom org-latex-to-mathml-jar-file nil
3920 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3921 Use this to specify additional executable file say a jar file.
3923 When using MathToWeb as the converter, specify the full-path to
3924 your mathtoweb.jar file."
3925 :group 'org-latex
3926 :version "24.1"
3927 :type '(choice
3928 (const :tag "None" nil)
3929 (file :tag "JAR file" :must-match t)))
3931 (defcustom org-latex-to-mathml-convert-command nil
3932 "Command to convert LaTeX fragments to MathML.
3933 Replace format-specifiers in the command as noted below and use
3934 `shell-command' to convert LaTeX to MathML.
3935 %j: Executable file in fully expanded form as specified by
3936 `org-latex-to-mathml-jar-file'.
3937 %I: Input LaTeX file in fully expanded form.
3938 %i: The latex fragment to be converted.
3939 %o: Output MathML file.
3941 This command is used by `org-create-math-formula'.
3943 When using MathToWeb as the converter, set this option to
3944 \"java -jar %j -unicode -force -df %o %I\".
3946 When using LaTeXML set this option to
3947 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3948 :group 'org-latex
3949 :version "24.1"
3950 :type '(choice
3951 (const :tag "None" nil)
3952 (string :tag "\nShell command")))
3954 (defcustom org-preview-latex-default-process 'dvipng
3955 "The default process to convert LaTeX fragments to image files.
3956 All available processes and theirs documents can be found in
3957 `org-preview-latex-process-alist', which see."
3958 :group 'org-latex
3959 :version "26.1"
3960 :package-version '(Org . "9.0")
3961 :type 'symbol)
3963 (defcustom org-preview-latex-process-alist
3964 '((dvipng
3965 :programs ("latex" "dvipng")
3966 :description "dvi > png"
3967 :message "you need to install the programs: latex and dvipng."
3968 :image-input-type "dvi"
3969 :image-output-type "png"
3970 :image-size-adjust (1.0 . 1.0)
3971 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3972 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3973 (dvisvgm
3974 :programs ("latex" "dvisvgm")
3975 :description "dvi > svg"
3976 :message "you need to install the programs: latex and dvisvgm."
3977 :use-xcolor t
3978 :image-input-type "dvi"
3979 :image-output-type "svg"
3980 :image-size-adjust (1.7 . 1.5)
3981 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3982 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3983 (imagemagick
3984 :programs ("latex" "convert")
3985 :description "pdf > png"
3986 :message "you need to install the programs: latex and imagemagick."
3987 :use-xcolor t
3988 :image-input-type "pdf"
3989 :image-output-type "png"
3990 :image-size-adjust (1.0 . 1.0)
3991 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3992 :image-converter
3993 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3994 "Definitions of external processes for LaTeX previewing.
3995 Org mode can use some external commands to generate TeX snippet's images for
3996 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3997 `org-create-formula-image' how to call them.
3999 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4000 PROPERTIES accepts the following attributes:
4002 :programs list of strings, required programs.
4003 :description string, describe the process.
4004 :message string, message it when required programs cannot be found.
4005 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4006 :image-output-type string, output file type of image converter (e.g., \"png\").
4007 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4008 deal with background and foreground color of image.
4009 Otherwise, dvipng style background and foregroud color
4010 format are generated. You may then refer to them in
4011 command options with \"%F\" and \"%B\".
4012 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4013 image size showed in buffer and the cdr element is for
4014 HTML file. This option is only useful for process
4015 developers, users should use variable
4016 `org-format-latex-options' instead.
4017 :post-clean list of strings, files matched are to be cleaned up once
4018 the image is generated. When nil, the files with \".dvi\",
4019 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4020 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4021 be cleaned up.
4022 :latex-header list of strings, the LaTeX header of the snippet file.
4023 When nil, the fallback value is used instead, which is
4024 controlled by `org-format-latex-header',
4025 `org-latex-default-packages-alist' and
4026 `org-latex-packages-alist', which see.
4027 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4028 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4029 replaced with values defined below.
4030 :image-converter list of image converter commands strings. Each of them is
4031 given to the shell and supports any of the following
4032 place-holders defined below.
4034 Place-holders used by `:image-converter' and `:latex-compiler':
4036 %f input file name
4037 %b base name of input file
4038 %o base directory of input file
4039 %O absolute output file name
4041 Place-holders only used by `:image-converter':
4043 %F foreground of image
4044 %B background of image
4045 %D dpi, which is used to adjust image size by some processing commands.
4046 %S the image size scale ratio, which is used to adjust image size by some
4047 processing commands."
4048 :group 'org-latex
4049 :version "26.1"
4050 :package-version '(Org . "9.0")
4051 :type '(alist :tag "LaTeX to image backends"
4052 :value-type (plist)))
4054 (defcustom org-preview-latex-image-directory "ltximg/"
4055 "Path to store latex preview images.
4056 A relative path here creates many directories relative to the
4057 processed org files paths. An absolute path puts all preview
4058 images at the same place."
4059 :group 'org-latex
4060 :version "26.1"
4061 :package-version '(Org . "9.0")
4062 :type 'string)
4064 (defun org-format-latex-mathml-available-p ()
4065 "Return t if `org-latex-to-mathml-convert-command' is usable."
4066 (save-match-data
4067 (when (and (boundp 'org-latex-to-mathml-convert-command)
4068 org-latex-to-mathml-convert-command)
4069 (let ((executable (car (split-string
4070 org-latex-to-mathml-convert-command))))
4071 (when (executable-find executable)
4072 (if (string-match
4073 "%j" org-latex-to-mathml-convert-command)
4074 (file-readable-p org-latex-to-mathml-jar-file)
4075 t))))))
4077 (defcustom org-format-latex-header "\\documentclass{article}
4078 \\usepackage[usenames]{color}
4079 \[PACKAGES]
4080 \[DEFAULT-PACKAGES]
4081 \\pagestyle{empty} % do not remove
4082 % The settings below are copied from fullpage.sty
4083 \\setlength{\\textwidth}{\\paperwidth}
4084 \\addtolength{\\textwidth}{-3cm}
4085 \\setlength{\\oddsidemargin}{1.5cm}
4086 \\addtolength{\\oddsidemargin}{-2.54cm}
4087 \\setlength{\\evensidemargin}{\\oddsidemargin}
4088 \\setlength{\\textheight}{\\paperheight}
4089 \\addtolength{\\textheight}{-\\headheight}
4090 \\addtolength{\\textheight}{-\\headsep}
4091 \\addtolength{\\textheight}{-\\footskip}
4092 \\addtolength{\\textheight}{-3cm}
4093 \\setlength{\\topmargin}{1.5cm}
4094 \\addtolength{\\topmargin}{-2.54cm}"
4095 "The document header used for processing LaTeX fragments.
4096 It is imperative that this header make sure that no page number
4097 appears on the page. The package defined in the variables
4098 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4099 will either replace the placeholder \"[PACKAGES]\" in this
4100 header, or they will be appended."
4101 :group 'org-latex
4102 :type 'string)
4104 (defun org-set-packages-alist (var val)
4105 "Set the packages alist and make sure it has 3 elements per entry."
4106 (set var (mapcar (lambda (x)
4107 (if (and (consp x) (= (length x) 2))
4108 (list (car x) (nth 1 x) t)
4110 val)))
4112 (defun org-get-packages-alist (var)
4113 "Get the packages alist and make sure it has 3 elements per entry."
4114 (mapcar (lambda (x)
4115 (if (and (consp x) (= (length x) 2))
4116 (list (car x) (nth 1 x) t)
4118 (default-value var)))
4120 (defcustom org-latex-default-packages-alist
4121 '(("AUTO" "inputenc" t ("pdflatex"))
4122 ("T1" "fontenc" t ("pdflatex"))
4123 ("" "graphicx" t)
4124 ("" "grffile" t)
4125 ("" "longtable" nil)
4126 ("" "wrapfig" nil)
4127 ("" "rotating" nil)
4128 ("normalem" "ulem" t)
4129 ("" "amsmath" t)
4130 ("" "textcomp" t)
4131 ("" "amssymb" t)
4132 ("" "capt-of" nil)
4133 ("" "hyperref" nil))
4134 "Alist of default packages to be inserted in the header.
4136 Change this only if one of the packages here causes an
4137 incompatibility with another package you are using.
4139 The packages in this list are needed by one part or another of
4140 Org mode to function properly:
4142 - inputenc, fontenc: for basic font and character selection
4143 - graphicx: for including images
4144 - grffile: allow periods and spaces in graphics file names
4145 - longtable: For multipage tables
4146 - wrapfig: for figure placement
4147 - rotating: for sideways figures and tables
4148 - ulem: for underline and strike-through
4149 - amsmath: for subscript and superscript and math environments
4150 - textcomp, amssymb: for various symbols used
4151 for interpreting the entities in `org-entities'. You can skip
4152 some of these packages if you don't use any of their symbols.
4153 - capt-of: for captions outside of floats
4154 - hyperref: for cross references
4156 Therefore you should not modify this variable unless you know
4157 what you are doing. The one reason to change it anyway is that
4158 you might be loading some other package that conflicts with one
4159 of the default packages. Each element is either a cell or
4160 a string.
4162 A cell is of the format
4164 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4166 If SNIPPET-FLAG is non-nil, the package also needs to be included
4167 when compiling LaTeX snippets into images for inclusion into
4168 non-LaTeX output. COMPILERS is a list of compilers that should
4169 include the package, see `org-latex-compiler'. If the document
4170 compiler is not in the list, and the list is non-nil, the package
4171 will not be inserted in the final document.
4173 A string will be inserted as-is in the header of the document."
4174 :group 'org-latex
4175 :group 'org-export-latex
4176 :set 'org-set-packages-alist
4177 :get 'org-get-packages-alist
4178 :version "26.1"
4179 :package-version '(Org . "8.3")
4180 :type '(repeat
4181 (choice
4182 (list :tag "options/package pair"
4183 (string :tag "options")
4184 (string :tag "package")
4185 (boolean :tag "Snippet"))
4186 (string :tag "A line of LaTeX"))))
4188 (defcustom org-latex-packages-alist nil
4189 "Alist of packages to be inserted in every LaTeX header.
4191 These will be inserted after `org-latex-default-packages-alist'.
4192 Each element is either a cell or a string.
4194 A cell is of the format:
4196 (\"options\" \"package\" SNIPPET-FLAG)
4198 SNIPPET-FLAG, when non-nil, indicates that this package is also
4199 needed when turning LaTeX snippets into images for inclusion into
4200 non-LaTeX output.
4202 A string will be inserted as-is in the header of the document.
4204 Make sure that you only list packages here which:
4206 - you want in every file;
4207 - do not conflict with the setup in `org-format-latex-header';
4208 - do not conflict with the default packages in
4209 `org-latex-default-packages-alist'."
4210 :group 'org-latex
4211 :group 'org-export-latex
4212 :set 'org-set-packages-alist
4213 :get 'org-get-packages-alist
4214 :type '(repeat
4215 (choice
4216 (list :tag "options/package pair"
4217 (string :tag "options")
4218 (string :tag "package")
4219 (boolean :tag "Snippet"))
4220 (string :tag "A line of LaTeX"))))
4222 (defgroup org-appearance nil
4223 "Settings for Org mode appearance."
4224 :tag "Org Appearance"
4225 :group 'org)
4227 (defcustom org-level-color-stars-only nil
4228 "Non-nil means fontify only the stars in each headline.
4229 When nil, the entire headline is fontified.
4230 Changing it requires restart of `font-lock-mode' to become effective
4231 also in regions already fontified."
4232 :group 'org-appearance
4233 :type 'boolean)
4235 (defcustom org-hide-leading-stars nil
4236 "Non-nil means hide the first N-1 stars in a headline.
4237 This works by using the face `org-hide' for these stars. This
4238 face is white for a light background, and black for a dark
4239 background. You may have to customize the face `org-hide' to
4240 make this work.
4241 Changing it requires restart of `font-lock-mode' to become effective
4242 also in regions already fontified.
4243 You may also set this on a per-file basis by adding one of the following
4244 lines to the buffer:
4246 #+STARTUP: hidestars
4247 #+STARTUP: showstars"
4248 :group 'org-appearance
4249 :type 'boolean)
4251 (defcustom org-hidden-keywords nil
4252 "List of symbols corresponding to keywords to be hidden the org buffer.
4253 For example, a value \\='(title) for this list will make the document's title
4254 appear in the buffer without the initial #+TITLE: keyword."
4255 :group 'org-appearance
4256 :version "24.1"
4257 :type '(set (const :tag "#+AUTHOR" author)
4258 (const :tag "#+DATE" date)
4259 (const :tag "#+EMAIL" email)
4260 (const :tag "#+TITLE" title)))
4262 (defcustom org-custom-properties nil
4263 "List of properties (as strings) with a special meaning.
4264 The default use of these custom properties is to let the user
4265 hide them with `org-toggle-custom-properties-visibility'."
4266 :group 'org-properties
4267 :group 'org-appearance
4268 :version "24.3"
4269 :type '(repeat (string :tag "Property Name")))
4271 (defcustom org-fontify-done-headline nil
4272 "Non-nil means change the face of a headline if it is marked DONE.
4273 Normally, only the TODO/DONE keyword indicates the state of a headline.
4274 When this is non-nil, the headline after the keyword is set to the
4275 `org-headline-done' as an additional indication."
4276 :group 'org-appearance
4277 :type 'boolean)
4279 (defcustom org-fontify-emphasized-text t
4280 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4281 Changing this variable requires a restart of Emacs to take effect."
4282 :group 'org-appearance
4283 :type 'boolean)
4285 (defcustom org-fontify-whole-heading-line nil
4286 "Non-nil means fontify the whole line for headings.
4287 This is useful when setting a background color for the
4288 org-level-* faces."
4289 :group 'org-appearance
4290 :type 'boolean)
4292 (defcustom org-highlight-latex-and-related nil
4293 "Non-nil means highlight LaTeX related syntax in the buffer.
4294 When non nil, the value should be a list containing any of the
4295 following symbols:
4296 `latex' Highlight LaTeX snippets and environments.
4297 `script' Highlight subscript and superscript.
4298 `entities' Highlight entities."
4299 :group 'org-appearance
4300 :version "24.4"
4301 :package-version '(Org . "8.0")
4302 :type '(choice
4303 (const :tag "No highlighting" nil)
4304 (set :greedy t :tag "Highlight"
4305 (const :tag "LaTeX snippets and environments" latex)
4306 (const :tag "Subscript and superscript" script)
4307 (const :tag "Entities" entities))))
4309 (defcustom org-hide-emphasis-markers nil
4310 "Non-nil mean font-lock should hide the emphasis marker characters."
4311 :group 'org-appearance
4312 :type 'boolean)
4314 (defcustom org-hide-macro-markers nil
4315 "Non-nil mean font-lock should hide the brackets marking macro calls."
4316 :group 'org-appearance
4317 :type 'boolean)
4319 (defcustom org-pretty-entities nil
4320 "Non-nil means show entities as UTF8 characters.
4321 When nil, the \\name form remains in the buffer."
4322 :group 'org-appearance
4323 :version "24.1"
4324 :type 'boolean)
4326 (defcustom org-pretty-entities-include-sub-superscripts t
4327 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4328 :group 'org-appearance
4329 :version "24.1"
4330 :type 'boolean)
4332 (defvar org-emph-re nil
4333 "Regular expression for matching emphasis.
4334 After a match, the match groups contain these elements:
4335 0 The match of the full regular expression, including the characters
4336 before and after the proper match
4337 1 The character before the proper match, or empty at beginning of line
4338 2 The proper match, including the leading and trailing markers
4339 3 The leading marker like * or /, indicating the type of highlighting
4340 4 The text between the emphasis markers, not including the markers
4341 5 The character after the match, empty at the end of a line")
4343 (defvar org-verbatim-re nil
4344 "Regular expression for matching verbatim text.")
4346 (defvar org-emphasis-regexp-components) ; defined just below
4347 (defvar org-emphasis-alist) ; defined just below
4348 (defun org-set-emph-re (var val)
4349 "Set variable and compute the emphasis regular expression."
4350 (set var val)
4351 (when (and (boundp 'org-emphasis-alist)
4352 (boundp 'org-emphasis-regexp-components)
4353 org-emphasis-alist org-emphasis-regexp-components)
4354 (pcase-let*
4355 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4356 (body (if (<= nl 0) body
4357 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4358 (template
4359 (format (concat "\\([%s]\\|^\\)" ;before markers
4360 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4361 "\\([%s]\\|$\\)") ;after markers
4362 pre border border body border post)))
4363 (setq org-emph-re (format template "*/_+"))
4364 (setq org-verbatim-re (format template "=~")))))
4366 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4367 ;; set this option proved cumbersome. See this message/thread:
4368 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4369 (defvar org-emphasis-regexp-components
4370 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4371 "Components used to build the regular expression for emphasis.
4372 This is a list with five entries. Terminology: In an emphasis string
4373 like \" *strong word* \", we call the initial space PREMATCH, the final
4374 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4375 and \"trong wor\" is the body. The different components in this variable
4376 specify what is allowed/forbidden in each part:
4378 pre Chars allowed as prematch. Beginning of line will be allowed too.
4379 post Chars allowed as postmatch. End of line will be allowed too.
4380 border The chars *forbidden* as border characters.
4381 body-regexp A regexp like \".\" to match a body character. Don't use
4382 non-shy groups here, and don't allow newline here.
4383 newline The maximum number of newlines allowed in an emphasis exp.
4385 You need to reload Org or to restart Emacs after customizing this.")
4387 (defcustom org-emphasis-alist
4388 '(("*" bold)
4389 ("/" italic)
4390 ("_" underline)
4391 ("=" org-verbatim verbatim)
4392 ("~" org-code verbatim)
4393 ("+" (:strike-through t)))
4394 "Alist of characters and faces to emphasize text.
4395 Text starting and ending with a special character will be emphasized,
4396 for example *bold*, _underlined_ and /italic/. This variable sets the
4397 marker characters and the face to be used by font-lock for highlighting
4398 in Org buffers.
4400 You need to reload Org or to restart Emacs after customizing this."
4401 :group 'org-appearance
4402 :set 'org-set-emph-re
4403 :version "24.4"
4404 :package-version '(Org . "8.0")
4405 :type '(repeat
4406 (list
4407 (string :tag "Marker character")
4408 (choice
4409 (face :tag "Font-lock-face")
4410 (plist :tag "Face property list"))
4411 (option (const verbatim)))))
4413 (defvar org-protecting-blocks '("src" "example" "export")
4414 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4415 This is needed for font-lock setup.")
4417 ;;; Functions and variables from their packages
4418 ;; Declared here to avoid compiler warnings
4419 (defvar mark-active)
4421 ;; Various packages
4422 (declare-function calc-eval "calc" (str &optional separator &rest args))
4423 (declare-function calendar-forward-day "cal-move" (arg))
4424 (declare-function calendar-goto-date "cal-move" (date))
4425 (declare-function calendar-goto-today "cal-move" ())
4426 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4427 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4428 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4429 (declare-function cdlatex-tab "ext:cdlatex" ())
4430 (declare-function dired-get-filename
4431 "dired"
4432 (&optional localp no-error-if-not-filep))
4433 (declare-function iswitchb-read-buffer
4434 "iswitchb"
4435 (prompt &optional
4436 default require-match _predicate start matches-set))
4437 (declare-function org-agenda-change-all-lines
4438 "org-agenda"
4439 (newhead hdmarker &optional fixface just-this))
4440 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4441 "org-agenda"
4442 (&optional end))
4443 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4444 (declare-function org-agenda-format-item
4445 "org-agenda"
4446 (extra txt &optional level category tags dotime
4447 remove-re habitp))
4448 (declare-function org-agenda-maybe-redo "org-agenda" ())
4449 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4450 (declare-function org-agenda-save-markers-for-cut-and-paste
4451 "org-agenda"
4452 (beg end))
4453 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4454 (declare-function org-agenda-skip "org-agenda" ())
4455 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4456 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4457 (declare-function org-indent-mode "org-indent" (&optional arg))
4458 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4459 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4460 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4461 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4462 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4463 (declare-function parse-time-string "parse-time" (string))
4464 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4466 (defvar align-mode-rules-list)
4467 (defvar calc-embedded-close-formula)
4468 (defvar calc-embedded-open-formula)
4469 (defvar calc-embedded-open-mode)
4470 (defvar font-lock-unfontify-region-function)
4471 (defvar iswitchb-temp-buflist)
4472 (defvar org-agenda-tags-todo-honor-ignore-options)
4473 (defvar remember-data-file)
4474 (defvar texmathp-why)
4476 ;;;###autoload
4477 (defun turn-on-orgtbl ()
4478 "Unconditionally turn on `orgtbl-mode'."
4479 (require 'org-table)
4480 (orgtbl-mode 1))
4482 (defun org-at-table-p (&optional table-type)
4483 "Non-nil if the cursor is inside an Org table.
4484 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4485 If `org-enable-table-editor' is nil, return nil unconditionally."
4486 (and
4487 org-enable-table-editor
4488 (save-excursion
4489 (beginning-of-line)
4490 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4491 (or (not (derived-mode-p 'org-mode))
4492 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4493 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4495 (defun org-at-table.el-p ()
4496 "Non-nil when point is at a table.el table."
4497 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4498 (let ((element (org-element-at-point)))
4499 (and (eq (org-element-type element) 'table)
4500 (eq (org-element-property :type element) 'table.el)))))
4502 (defun org-at-table-hline-p ()
4503 "Non-nil when point is inside a hline in a table.
4504 Assume point is already in a table. If `org-enable-table-editor'
4505 is nil, return nil unconditionally."
4506 (and org-enable-table-editor
4507 (save-excursion
4508 (beginning-of-line)
4509 (looking-at org-table-hline-regexp))))
4511 (defun org-table-map-tables (function &optional quietly)
4512 "Apply FUNCTION to the start of all tables in the buffer."
4513 (org-with-wide-buffer
4514 (goto-char (point-min))
4515 (while (re-search-forward org-table-any-line-regexp nil t)
4516 (unless quietly
4517 (message "Mapping tables: %d%%"
4518 (floor (* 100.0 (point)) (buffer-size))))
4519 (beginning-of-line 1)
4520 (when (and (looking-at org-table-line-regexp)
4521 ;; Exclude tables in src/example/verbatim/clocktable blocks
4522 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4523 (save-excursion (funcall function))
4524 (or (looking-at org-table-line-regexp)
4525 (forward-char 1)))
4526 (re-search-forward org-table-any-border-regexp nil 1)))
4527 (unless quietly (message "Mapping tables: done")))
4529 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4530 (declare-function org-clock-update-mode-line "org-clock" ())
4531 (declare-function org-resolve-clocks "org-clock"
4532 (&optional also-non-dangling-p prompt last-valid))
4534 (defun org-at-TBLFM-p (&optional pos)
4535 "Non-nil when point (or POS) is in #+TBLFM line."
4536 (save-excursion
4537 (goto-char (or pos (point)))
4538 (beginning-of-line)
4539 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4540 (eq (org-element-type (org-element-at-point)) 'table))))
4542 (defvar org-clock-start-time)
4543 (defvar org-clock-marker (make-marker)
4544 "Marker recording the last clock-in.")
4545 (defvar org-clock-hd-marker (make-marker)
4546 "Marker recording the last clock-in, but the headline position.")
4547 (defvar org-clock-heading ""
4548 "The heading of the current clock entry.")
4549 (defun org-clock-is-active ()
4550 "Return the buffer where the clock is currently running.
4551 Return nil if no clock is running."
4552 (marker-buffer org-clock-marker))
4554 (defun org-check-running-clock ()
4555 "Check if the current buffer contains the running clock.
4556 If yes, offer to stop it and to save the buffer with the changes."
4557 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4558 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4559 (buffer-name))))
4560 (org-clock-out)
4561 (when (y-or-n-p "Save changed buffer?")
4562 (save-buffer))))
4564 (defun org-clocktable-try-shift (dir n)
4565 "Check if this line starts a clock table, if yes, shift the time block."
4566 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4567 (org-clocktable-shift dir n)))
4569 ;;;###autoload
4570 (defun org-clock-persistence-insinuate ()
4571 "Set up hooks for clock persistence."
4572 (require 'org-clock)
4573 (add-hook 'org-mode-hook 'org-clock-load)
4574 (add-hook 'kill-emacs-hook 'org-clock-save))
4576 (defgroup org-archive nil
4577 "Options concerning archiving in Org mode."
4578 :tag "Org Archive"
4579 :group 'org-structure)
4581 (defcustom org-archive-location "%s_archive::"
4582 "The location where subtrees should be archived.
4584 The value of this variable is a string, consisting of two parts,
4585 separated by a double-colon. The first part is a filename and
4586 the second part is a headline.
4588 When the filename is omitted, archiving happens in the same file.
4589 %s in the filename will be replaced by the current file
4590 name (without the directory part). Archiving to a different file
4591 is useful to keep archived entries from contributing to the
4592 Org Agenda.
4594 The archived entries will be filed as subtrees of the specified
4595 headline. When the headline is omitted, the subtrees are simply
4596 filed away at the end of the file, as top-level entries. Also in
4597 the heading you can use %s to represent the file name, this can be
4598 useful when using the same archive for a number of different files.
4600 Here are a few examples:
4601 \"%s_archive::\"
4602 If the current file is Projects.org, archive in file
4603 Projects.org_archive, as top-level trees. This is the default.
4605 \"::* Archived Tasks\"
4606 Archive in the current file, under the top-level headline
4607 \"* Archived Tasks\".
4609 \"~/org/archive.org::\"
4610 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4612 \"~/org/archive.org::* From %s\"
4613 Archive in file ~/org/archive.org (absolute path), under headlines
4614 \"From FILENAME\" where file name is the current file name.
4616 \"~/org/datetree.org::datetree/* Finished Tasks\"
4617 The \"datetree/\" string is special, signifying to archive
4618 items to the datetree. Items are placed in either the CLOSED
4619 date of the item, or the current date if there is no CLOSED date.
4620 The heading will be a subentry to the current date. There doesn't
4621 need to be a heading, but there always needs to be a slash after
4622 datetree. For example, to store archived items directly in the
4623 datetree, use \"~/org/datetree.org::datetree/\".
4625 \"basement::** Finished Tasks\"
4626 Archive in file ./basement (relative path), as level 3 trees
4627 below the level 2 heading \"** Finished Tasks\".
4629 You may set this option on a per-file basis by adding to the buffer a
4630 line like
4632 #+ARCHIVE: basement::** Finished Tasks
4634 You may also define it locally for a subtree by setting an ARCHIVE property
4635 in the entry. If such a property is found in an entry, or anywhere up
4636 the hierarchy, it will be used."
4637 :group 'org-archive
4638 :type 'string)
4640 (defcustom org-agenda-skip-archived-trees t
4641 "Non-nil means the agenda will skip any items located in archived trees.
4642 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4643 variable is no longer recommended, you should leave it at the value t.
4644 Instead, use the key `v' to cycle the archives-mode in the agenda."
4645 :group 'org-archive
4646 :group 'org-agenda-skip
4647 :type 'boolean)
4649 (defcustom org-columns-skip-archived-trees t
4650 "Non-nil means ignore archived trees when creating column view."
4651 :group 'org-archive
4652 :group 'org-properties
4653 :type 'boolean)
4655 (defcustom org-cycle-open-archived-trees nil
4656 "Non-nil means `org-cycle' will open archived trees.
4657 An archived tree is a tree marked with the tag ARCHIVE.
4658 When nil, archived trees will stay folded. You can still open them with
4659 normal outline commands like `show-all', but not with the cycling commands."
4660 :group 'org-archive
4661 :group 'org-cycle
4662 :type 'boolean)
4664 (defcustom org-sparse-tree-open-archived-trees nil
4665 "Non-nil means sparse tree construction shows matches in archived trees.
4666 When nil, matches in these trees are highlighted, but the trees are kept in
4667 collapsed state."
4668 :group 'org-archive
4669 :group 'org-sparse-trees
4670 :type 'boolean)
4672 (defcustom org-sparse-tree-default-date-type nil
4673 "The default date type when building a sparse tree.
4674 When this is nil, a date is a scheduled or a deadline timestamp.
4675 Otherwise, these types are allowed:
4677 all: all timestamps
4678 active: only active timestamps (<...>)
4679 inactive: only inactive timestamps ([...])
4680 scheduled: only scheduled timestamps
4681 deadline: only deadline timestamps"
4682 :type '(choice (const :tag "Scheduled or deadline" nil)
4683 (const :tag "All timestamps" all)
4684 (const :tag "Only active timestamps" active)
4685 (const :tag "Only inactive timestamps" inactive)
4686 (const :tag "Only scheduled timestamps" scheduled)
4687 (const :tag "Only deadline timestamps" deadline)
4688 (const :tag "Only closed timestamps" closed))
4689 :version "26.1"
4690 :package-version '(Org . "8.3")
4691 :group 'org-sparse-trees)
4693 (defun org-cycle-hide-archived-subtrees (state)
4694 "Re-hide all archived subtrees after a visibility state change."
4695 (when (and (not org-cycle-open-archived-trees)
4696 (not (memq state '(overview folded))))
4697 (save-excursion
4698 (let* ((globalp (memq state '(contents all)))
4699 (beg (if globalp (point-min) (point)))
4700 (end (if globalp (point-max) (org-end-of-subtree t))))
4701 (org-hide-archived-subtrees beg end)
4702 (goto-char beg)
4703 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4704 (message "%s" (substitute-command-keys
4705 "Subtree is archived and stays closed. Use \
4706 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4708 (defun org-force-cycle-archived ()
4709 "Cycle subtree even if it is archived."
4710 (interactive)
4711 (setq this-command 'org-cycle)
4712 (let ((org-cycle-open-archived-trees t))
4713 (call-interactively 'org-cycle)))
4715 (defun org-hide-archived-subtrees (beg end)
4716 "Re-hide all archived subtrees after a visibility state change."
4717 (org-with-wide-buffer
4718 (let ((case-fold-search nil)
4719 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4720 (goto-char beg)
4721 ;; Include headline point is currently on.
4722 (beginning-of-line)
4723 (while (and (< (point) end) (re-search-forward re end t))
4724 (when (member org-archive-tag (org-get-tags))
4725 (org-flag-subtree t)
4726 (org-end-of-subtree t))))))
4728 (declare-function outline-end-of-heading "outline" ())
4729 (declare-function outline-flag-region "outline" (from to flag))
4730 (defun org-flag-subtree (flag)
4731 (save-excursion
4732 (org-back-to-heading t)
4733 (outline-end-of-heading)
4734 (outline-flag-region (point)
4735 (progn (org-end-of-subtree t) (point))
4736 flag)))
4738 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4740 ;; Declare Column View Code
4742 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4743 (declare-function org-columns-compute "org-colview" (property))
4745 ;; Declare ID code
4747 (declare-function org-id-store-link "org-id")
4748 (declare-function org-id-locations-load "org-id")
4749 (declare-function org-id-locations-save "org-id")
4750 (defvar org-id-track-globally)
4752 ;;; Variables for pre-computed regular expressions, all buffer local
4754 (defvar-local org-todo-regexp nil
4755 "Matches any of the TODO state keywords.
4756 Since TODO keywords are case-sensitive, `case-fold-search' is
4757 expected to be bound to nil when matching against this regexp.")
4759 (defvar-local org-not-done-regexp nil
4760 "Matches any of the TODO state keywords except the last one.
4761 Since TODO keywords are case-sensitive, `case-fold-search' is
4762 expected to be bound to nil when matching against this regexp.")
4764 (defvar-local org-not-done-heading-regexp nil
4765 "Matches a TODO headline that is not done.
4766 Since TODO keywords are case-sensitive, `case-fold-search' is
4767 expected to be bound to nil when matching against this regexp.")
4769 (defvar-local org-todo-line-regexp nil
4770 "Matches a headline and puts TODO state into group 2 if present.
4771 Since TODO keywords are case-sensitive, `case-fold-search' is
4772 expected to be bound to nil when matching against this regexp.")
4774 (defvar-local org-complex-heading-regexp nil
4775 "Matches a headline and puts everything into groups:
4777 group 1: Stars
4778 group 2: The TODO keyword, maybe
4779 group 3: Priority cookie
4780 group 4: True headline
4781 group 5: Tags
4783 Since TODO keywords are case-sensitive, `case-fold-search' is
4784 expected to be bound to nil when matching against this regexp.")
4786 (defvar-local org-complex-heading-regexp-format nil
4787 "Printf format to make regexp to match an exact headline.
4788 This regexp will match the headline of any node which has the
4789 exact headline text that is put into the format, but may have any
4790 TODO state, priority and tags.")
4792 (defvar-local org-todo-line-tags-regexp nil
4793 "Matches a headline and puts TODO state into group 2 if present.
4794 Also put tags into group 4 if tags are present.")
4796 (defconst org-plain-time-of-day-regexp
4797 (concat
4798 "\\(\\<[012]?[0-9]"
4799 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4800 "\\(--?"
4801 "\\(\\<[012]?[0-9]"
4802 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4803 "\\)?")
4804 "Regular expression to match a plain time or time range.
4805 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4806 groups carry important information:
4807 0 the full match
4808 1 the first time, range or not
4809 8 the second time, if it is a range.")
4811 (defconst org-plain-time-extension-regexp
4812 (concat
4813 "\\(\\<[012]?[0-9]"
4814 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4815 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4816 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4817 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4818 groups carry important information:
4819 0 the full match
4820 7 hours of duration
4821 9 minutes of duration")
4823 (defconst org-stamp-time-of-day-regexp
4824 (concat
4825 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4826 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4827 "\\(--?"
4828 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4829 "Regular expression to match a timestamp time or time range.
4830 After a match, the following groups carry important information:
4831 0 the full match
4832 1 date plus weekday, for back referencing to make sure both times are on the same day
4833 2 the first time, range or not
4834 4 the second time, if it is a range.")
4836 (defconst org-startup-options
4837 '(("fold" org-startup-folded t)
4838 ("overview" org-startup-folded t)
4839 ("nofold" org-startup-folded nil)
4840 ("showall" org-startup-folded nil)
4841 ("showeverything" org-startup-folded showeverything)
4842 ("content" org-startup-folded content)
4843 ("indent" org-startup-indented t)
4844 ("noindent" org-startup-indented nil)
4845 ("hidestars" org-hide-leading-stars t)
4846 ("showstars" org-hide-leading-stars nil)
4847 ("odd" org-odd-levels-only t)
4848 ("oddeven" org-odd-levels-only nil)
4849 ("align" org-startup-align-all-tables t)
4850 ("noalign" org-startup-align-all-tables nil)
4851 ("inlineimages" org-startup-with-inline-images t)
4852 ("noinlineimages" org-startup-with-inline-images nil)
4853 ("latexpreview" org-startup-with-latex-preview t)
4854 ("nolatexpreview" org-startup-with-latex-preview nil)
4855 ("customtime" org-display-custom-times t)
4856 ("logdone" org-log-done time)
4857 ("lognotedone" org-log-done note)
4858 ("nologdone" org-log-done nil)
4859 ("lognoteclock-out" org-log-note-clock-out t)
4860 ("nolognoteclock-out" org-log-note-clock-out nil)
4861 ("logrepeat" org-log-repeat state)
4862 ("lognoterepeat" org-log-repeat note)
4863 ("logdrawer" org-log-into-drawer t)
4864 ("nologdrawer" org-log-into-drawer nil)
4865 ("logstatesreversed" org-log-states-order-reversed t)
4866 ("nologstatesreversed" org-log-states-order-reversed nil)
4867 ("nologrepeat" org-log-repeat nil)
4868 ("logreschedule" org-log-reschedule time)
4869 ("lognotereschedule" org-log-reschedule note)
4870 ("nologreschedule" org-log-reschedule nil)
4871 ("logredeadline" org-log-redeadline time)
4872 ("lognoteredeadline" org-log-redeadline note)
4873 ("nologredeadline" org-log-redeadline nil)
4874 ("logrefile" org-log-refile time)
4875 ("lognoterefile" org-log-refile note)
4876 ("nologrefile" org-log-refile nil)
4877 ("fninline" org-footnote-define-inline t)
4878 ("nofninline" org-footnote-define-inline nil)
4879 ("fnlocal" org-footnote-section nil)
4880 ("fnauto" org-footnote-auto-label t)
4881 ("fnprompt" org-footnote-auto-label nil)
4882 ("fnconfirm" org-footnote-auto-label confirm)
4883 ("fnplain" org-footnote-auto-label plain)
4884 ("fnadjust" org-footnote-auto-adjust t)
4885 ("nofnadjust" org-footnote-auto-adjust nil)
4886 ("constcgs" constants-unit-system cgs)
4887 ("constSI" constants-unit-system SI)
4888 ("noptag" org-tag-persistent-alist nil)
4889 ("hideblocks" org-hide-block-startup t)
4890 ("nohideblocks" org-hide-block-startup nil)
4891 ("beamer" org-startup-with-beamer-mode t)
4892 ("entitiespretty" org-pretty-entities t)
4893 ("entitiesplain" org-pretty-entities nil))
4894 "Variable associated with STARTUP options for org-mode.
4895 Each element is a list of three items: the startup options (as written
4896 in the #+STARTUP line), the corresponding variable, and the value to set
4897 this variable to if the option is found. An optional forth element PUSH
4898 means to push this value onto the list in the variable.")
4900 (defcustom org-group-tags t
4901 "When non-nil (the default), use group tags.
4902 This can be turned on/off through `org-toggle-tags-groups'."
4903 :group 'org-tags
4904 :group 'org-startup
4905 :type 'boolean)
4907 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4909 (defun org-toggle-tags-groups ()
4910 "Toggle support for group tags.
4911 Support for group tags is controlled by the option
4912 `org-group-tags', which is non-nil by default."
4913 (interactive)
4914 (setq org-group-tags (not org-group-tags))
4915 (cond ((and (derived-mode-p 'org-agenda-mode)
4916 org-group-tags)
4917 (org-agenda-redo))
4918 ((derived-mode-p 'org-mode)
4919 (let ((org-inhibit-startup t)) (org-mode))))
4920 (message "Groups tags support has been turned %s"
4921 (if org-group-tags "on" "off")))
4923 (defun org-set-regexps-and-options (&optional tags-only)
4924 "Precompute regular expressions used in the current buffer.
4925 When optional argument TAGS-ONLY is non-nil, only compute tags
4926 related expressions."
4927 (when (derived-mode-p 'org-mode)
4928 (let ((alist (org--setup-collect-keywords
4929 (org-make-options-regexp
4930 (append '("FILETAGS" "TAGS" "SETUPFILE")
4931 (and (not tags-only)
4932 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4933 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4934 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4935 ;; Startup options. Get this early since it does change
4936 ;; behavior for other options (e.g., tags).
4937 (let ((startup (cdr (assq 'startup alist))))
4938 (dolist (option startup)
4939 (let ((entry (assoc-string option org-startup-options t)))
4940 (when entry
4941 (let ((var (nth 1 entry))
4942 (val (nth 2 entry)))
4943 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4944 (unless (listp (symbol-value var))
4945 (set (make-local-variable var) nil))
4946 (add-to-list var val)))))))
4947 (setq-local org-file-tags
4948 (mapcar #'org-add-prop-inherited
4949 (cdr (assq 'filetags alist))))
4950 (setq org-current-tag-alist
4951 (append org-tag-persistent-alist
4952 (let ((tags (cdr (assq 'tags alist))))
4953 (if tags (org-tag-string-to-alist tags)
4954 org-tag-alist))))
4955 (setq org-tag-groups-alist
4956 (org-tag-alist-to-groups org-current-tag-alist))
4957 (unless tags-only
4958 ;; File properties.
4959 (setq-local org-file-properties (cdr (assq 'property alist)))
4960 ;; Archive location.
4961 (let ((archive (cdr (assq 'archive alist))))
4962 (when archive (setq-local org-archive-location archive)))
4963 ;; Category.
4964 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4965 (when cat
4966 (setq-local org-category (intern cat))
4967 (setq-local org-file-properties
4968 (org--update-property-plist
4969 "CATEGORY" cat org-file-properties))))
4970 ;; Columns.
4971 (let ((column (cdr (assq 'columns alist))))
4972 (when column (setq-local org-columns-default-format column)))
4973 ;; Constants.
4974 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4975 ;; Link abbreviations.
4976 (let ((links (cdr (assq 'link alist))))
4977 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4978 ;; Priorities.
4979 (let ((priorities (cdr (assq 'priorities alist))))
4980 (when priorities
4981 (setq-local org-highest-priority (nth 0 priorities))
4982 (setq-local org-lowest-priority (nth 1 priorities))
4983 (setq-local org-default-priority (nth 2 priorities))))
4984 ;; Scripts.
4985 (let ((scripts (assq 'scripts alist)))
4986 (when scripts
4987 (setq-local org-use-sub-superscripts (cdr scripts))))
4988 ;; TODO keywords.
4989 (setq-local org-todo-kwd-alist nil)
4990 (setq-local org-todo-key-alist nil)
4991 (setq-local org-todo-key-trigger nil)
4992 (setq-local org-todo-keywords-1 nil)
4993 (setq-local org-done-keywords nil)
4994 (setq-local org-todo-heads nil)
4995 (setq-local org-todo-sets nil)
4996 (setq-local org-todo-log-states nil)
4997 (let ((todo-sequences
4998 (or (nreverse (cdr (assq 'todo alist)))
4999 (let ((d (default-value 'org-todo-keywords)))
5000 (if (not (stringp (car d))) d
5001 ;; XXX: Backward compatibility code.
5002 (list (cons org-todo-interpretation d)))))))
5003 (dolist (sequence todo-sequences)
5004 (let* ((sequence (or (run-hook-with-args-until-success
5005 'org-todo-setup-filter-hook sequence)
5006 sequence))
5007 (sequence-type (car sequence))
5008 (keywords (cdr sequence))
5009 (sep (member "|" keywords))
5010 names alist)
5011 (dolist (k (remove "|" keywords))
5012 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5014 (error "Invalid TODO keyword %s" k))
5015 (let ((name (match-string 1 k))
5016 (key (match-string 2 k))
5017 (log (org-extract-log-state-settings k)))
5018 (push name names)
5019 (push (cons name (and key (string-to-char key))) alist)
5020 (when log (push log org-todo-log-states))))
5021 (let* ((names (nreverse names))
5022 (done (if sep (org-remove-keyword-keys (cdr sep))
5023 (last names)))
5024 (head (car names))
5025 (tail (list sequence-type head (car done) (org-last done))))
5026 (add-to-list 'org-todo-heads head 'append)
5027 (push names org-todo-sets)
5028 (setq org-done-keywords (append org-done-keywords done nil))
5029 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5030 (setq org-todo-key-alist
5031 (append org-todo-key-alist
5032 (and alist
5033 (append '((:startgroup))
5034 (nreverse alist)
5035 '((:endgroup))))))
5036 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5037 (setq org-todo-sets (nreverse org-todo-sets)
5038 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5039 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5040 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5041 ;; Compute the regular expressions and other local variables.
5042 ;; Using `org-outline-regexp-bol' would complicate them much,
5043 ;; because of the fixed white space at the end of that string.
5044 (unless org-done-keywords
5045 (setq org-done-keywords
5046 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5047 (setq org-not-done-keywords
5048 (org-delete-all org-done-keywords
5049 (copy-sequence org-todo-keywords-1))
5050 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5051 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5052 org-not-done-heading-regexp
5053 (format org-heading-keyword-regexp-format org-not-done-regexp)
5054 org-todo-line-regexp
5055 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5056 org-complex-heading-regexp
5057 (concat "^\\(\\*+\\)"
5058 "\\(?: +" org-todo-regexp "\\)?"
5059 "\\(?: +\\(\\[#.\\]\\)\\)?"
5060 "\\(?: +\\(.*?\\)\\)??"
5061 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5062 "[ \t]*$")
5063 org-complex-heading-regexp-format
5064 (concat "^\\(\\*+\\)"
5065 "\\(?: +" org-todo-regexp "\\)?"
5066 "\\(?: +\\(\\[#.\\]\\)\\)?"
5067 "\\(?: +"
5068 ;; Stats cookies can be stuck to body.
5069 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5070 "\\(%s\\)"
5071 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5072 "\\)"
5073 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5074 "[ \t]*$")
5075 org-todo-line-tags-regexp
5076 (concat "^\\(\\*+\\)"
5077 "\\(?: +" org-todo-regexp "\\)?"
5078 "\\(?: +\\(.*?\\)\\)??"
5079 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5080 "[ \t]*$"))
5081 (org-compute-latex-and-related-regexp)))))
5083 (defun org--setup-collect-keywords (regexp &optional files alist)
5084 "Return setup keywords values as an alist.
5086 REGEXP matches a subset of setup keywords. FILES is a list of
5087 file names already visited. It is used to avoid circular setup
5088 files. ALIST, when non-nil, is the alist computed so far.
5090 Return value contains the following keys: `archive', `category',
5091 `columns', `constants', `filetags', `link', `priorities',
5092 `property', `scripts', `startup', `tags' and `todo'."
5093 (org-with-wide-buffer
5094 (goto-char (point-min))
5095 (let ((case-fold-search t))
5096 (while (re-search-forward regexp nil t)
5097 (let ((element (org-element-at-point)))
5098 (when (eq (org-element-type element) 'keyword)
5099 (let ((key (org-element-property :key element))
5100 (value (org-element-property :value element)))
5101 (cond
5102 ((equal key "ARCHIVE")
5103 (when (org-string-nw-p value)
5104 (push (cons 'archive value) alist)))
5105 ((equal key "CATEGORY") (push (cons 'category value) alist))
5106 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5107 ((equal key "CONSTANTS")
5108 (let* ((constants (assq 'constants alist))
5109 (store (cdr constants)))
5110 (dolist (pair (org-split-string value))
5111 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5112 pair)
5113 (let* ((name (match-string 1 pair))
5114 (value (match-string 2 pair))
5115 (old (assoc name store)))
5116 (if old (setcdr old value)
5117 (push (cons name value) store)))))
5118 (if constants (setcdr constants store)
5119 (push (cons 'constants store) alist))))
5120 ((equal key "FILETAGS")
5121 (when (org-string-nw-p value)
5122 (let ((old (assq 'filetags alist))
5123 (new (apply #'nconc
5124 (mapcar (lambda (x) (org-split-string x ":"))
5125 (org-split-string value)))))
5126 (if old (setcdr old (append new (cdr old)))
5127 (push (cons 'filetags new) alist)))))
5128 ((equal key "LINK")
5129 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5130 (let ((links (assq 'link alist))
5131 (pair (cons (match-string-no-properties 1 value)
5132 (match-string-no-properties 2 value))))
5133 (if links (push pair (cdr links))
5134 (push (list 'link pair) alist)))))
5135 ((equal key "OPTIONS")
5136 (when (and (org-string-nw-p value)
5137 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5138 (push (cons 'scripts (read (match-string 1 value))) alist)))
5139 ((equal key "PRIORITIES")
5140 (push (cons 'priorities
5141 (let ((prio (org-split-string value)))
5142 (if (< (length prio) 3) '(?A ?C ?B)
5143 (mapcar #'string-to-char prio))))
5144 alist))
5145 ((equal key "PROPERTY")
5146 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5147 (let* ((property (assq 'property alist))
5148 (value (org--update-property-plist
5149 (match-string-no-properties 1 value)
5150 (match-string-no-properties 2 value)
5151 (cdr property))))
5152 (if property (setcdr property value)
5153 (push (cons 'property value) alist)))))
5154 ((equal key "STARTUP")
5155 (let ((startup (assq 'startup alist)))
5156 (if startup
5157 (setcdr startup
5158 (append (cdr startup) (org-split-string value)))
5159 (push (cons 'startup (org-split-string value)) alist))))
5160 ((equal key "TAGS")
5161 (let ((tag-cell (assq 'tags alist)))
5162 (if tag-cell
5163 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5164 (push (cons 'tags value) alist))))
5165 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5166 (let ((todo (assq 'todo alist))
5167 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5168 (org-split-string value))))
5169 (if todo (push value (cdr todo))
5170 (push (list 'todo value) alist))))
5171 ((equal key "SETUPFILE")
5172 (unless buffer-read-only ; Do not check in Gnus messages.
5173 (let ((f (and (org-string-nw-p value)
5174 (expand-file-name
5175 (org-unbracket-string "\"" "\"" value)))))
5176 (when (and f (file-readable-p f) (not (member f files)))
5177 (with-temp-buffer
5178 (setq default-directory (file-name-directory f))
5179 (insert-file-contents f)
5180 (setq alist
5181 ;; Fake Org mode to benefit from cache
5182 ;; without recurring needlessly.
5183 (let ((major-mode 'org-mode))
5184 (org--setup-collect-keywords
5185 regexp (cons f files) alist)))))))))))))))
5186 alist)
5188 (defun org-tag-string-to-alist (s)
5189 "Return tag alist associated to string S.
5190 S is a value for TAGS keyword or produced with
5191 `org-tag-alist-to-string'. Return value is an alist suitable for
5192 `org-tag-alist' or `org-tag-persistent-alist'."
5193 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5194 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5195 "\\|{.+?}\\)" ; regular expression
5196 "\\(?:(\\(.\\))\\)?\\'"))
5197 alist group-flag)
5198 (dolist (tokens lines (cdr (nreverse alist)))
5199 (push '(:newline) alist)
5200 (while tokens
5201 (let ((token (pop tokens)))
5202 (pcase token
5203 ("{"
5204 (push '(:startgroup) alist)
5205 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5206 ("}"
5207 (push '(:endgroup) alist)
5208 (setq group-flag nil))
5209 ("["
5210 (push '(:startgrouptag) alist)
5211 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5212 ("]"
5213 (push '(:endgrouptag) alist)
5214 (setq group-flag nil))
5215 (":"
5216 (push '(:grouptags) alist))
5217 ((guard (string-match tag-re token))
5218 (let ((tag (match-string 1 token))
5219 (key (and (match-beginning 2)
5220 (string-to-char (match-string 2 token)))))
5221 ;; Push all tags in groups, no matter if they already
5222 ;; appear somewhere else in the list.
5223 (when (or group-flag (not (assoc tag alist)))
5224 (push (cons tag key) alist))))))))))
5226 (defun org-tag-alist-to-string (alist &optional skip-key)
5227 "Return tag string associated to ALIST.
5229 ALIST is an alist, as defined in `org-tag-alist' or
5230 `org-tag-persistent-alist', or produced with
5231 `org-tag-string-to-alist'.
5233 Return value is a string suitable as a value for \"TAGS\"
5234 keyword.
5236 When optional argument SKIP-KEY is non-nil, skip selection keys
5237 next to tags."
5238 (mapconcat (lambda (token)
5239 (pcase token
5240 (`(:startgroup) "{")
5241 (`(:endgroup) "}")
5242 (`(:startgrouptag) "[")
5243 (`(:endgrouptag) "]")
5244 (`(:grouptags) ":")
5245 (`(:newline) "\\n")
5246 ((and
5247 (guard (not skip-key))
5248 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5249 (format "%s(%c)" tag key))
5250 (`(,(and tag (pred stringp)) . ,_) tag)
5251 (_ (user-error "Invalid tag token: %S" token))))
5252 alist
5253 " "))
5255 (defun org-tag-alist-to-groups (alist)
5256 "Return group alist from tag ALIST.
5257 ALIST is an alist, as defined in `org-tag-alist' or
5258 `org-tag-persistent-alist', or produced with
5259 `org-tag-string-to-alist'. Return value is an alist following
5260 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5261 a string, summarizing TAGS, as a list of strings."
5262 (let (groups group-status current-group)
5263 (dolist (token alist (nreverse groups))
5264 (pcase token
5265 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5266 (`(,(or :endgroup :endgrouptag))
5267 (when (eq group-status 'append)
5268 (push (nreverse current-group) groups))
5269 (setq group-status nil))
5270 (`(:grouptags) (setq group-status 'append))
5271 ((and `(,tag . ,_) (guard group-status))
5272 (if (eq group-status 'append) (push tag current-group)
5273 (setq current-group (list tag))))
5274 (_ nil)))))
5276 (defun org-file-contents (file &optional noerror)
5277 "Return the contents of FILE, as a string."
5278 (if (and file (file-readable-p file))
5279 (with-temp-buffer
5280 (insert-file-contents file)
5281 (buffer-string))
5282 (funcall (if noerror 'message 'error)
5283 "Cannot read file \"%s\"%s"
5284 file
5285 (let ((from (buffer-file-name (buffer-base-buffer))))
5286 (if from (concat " (referenced in file \"" from "\")") "")))))
5288 (defun org-extract-log-state-settings (x)
5289 "Extract the log state setting from a TODO keyword string.
5290 This will extract info from a string like \"WAIT(w@/!)\"."
5291 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5292 (let ((kw (match-string 1 x))
5293 (log1 (and (match-end 3) (match-string 3 x)))
5294 (log2 (and (match-end 4) (match-string 4 x))))
5295 (and (or log1 log2)
5296 (list kw
5297 (and log1 (if (equal log1 "!") 'time 'note))
5298 (and log2 (if (equal log2 "!") 'time 'note)))))))
5300 (defun org-remove-keyword-keys (list)
5301 "Remove a pair of parenthesis at the end of each string in LIST."
5302 (mapcar (lambda (x)
5303 (if (string-match "(.*)$" x)
5304 (substring x 0 (match-beginning 0))
5306 list))
5308 (defun org-assign-fast-keys (alist)
5309 "Assign fast keys to a keyword-key alist.
5310 Respect keys that are already there."
5311 (let (new e (alt ?0))
5312 (while (setq e (pop alist))
5313 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5314 (cdr e)) ;; Key already assigned.
5315 (push e new)
5316 (let ((clist (string-to-list (downcase (car e))))
5317 (used (append new alist)))
5318 (when (= (car clist) ?@)
5319 (pop clist))
5320 (while (and clist (rassoc (car clist) used))
5321 (pop clist))
5322 (unless clist
5323 (while (rassoc alt used)
5324 (cl-incf alt)))
5325 (push (cons (car e) (or (car clist) alt)) new))))
5326 (nreverse new)))
5328 ;;; Some variables used in various places
5330 (defvar org-window-configuration nil
5331 "Used in various places to store a window configuration.")
5332 (defvar org-selected-window nil
5333 "Used in various places to store a window configuration.")
5334 (defvar org-finish-function nil
5335 "Function to be called when `C-c C-c' is used.
5336 This is for getting out of special buffers like capture.")
5337 (defvar org-last-state)
5339 ;; Defined somewhere in this file, but used before definition.
5340 (defvar org-entities) ;; defined in org-entities.el
5341 (defvar org-struct-menu)
5342 (defvar org-org-menu)
5343 (defvar org-tbl-menu)
5345 ;;;; Define the Org mode
5347 ;; We use a before-change function to check if a table might need
5348 ;; an update.
5349 (defvar org-table-may-need-update t
5350 "Indicates that a table might need an update.
5351 This variable is set by `org-before-change-function'.
5352 `org-table-align' sets it back to nil.")
5353 (defun org-before-change-function (_beg _end)
5354 "Every change indicates that a table might need an update."
5355 (setq org-table-may-need-update t))
5356 (defvar org-mode-map)
5357 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5358 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5359 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5360 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5361 (defvar org-table-buffer-is-an nil)
5363 (defvar bidi-paragraph-direction)
5364 (defvar buffer-face-mode-face)
5366 (require 'outline)
5368 ;; Other stuff we need.
5369 (require 'time-date)
5370 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5371 (require 'easymenu)
5372 (autoload 'easy-menu-add "easymenu")
5373 (require 'overlay)
5375 ;; (require 'org-macs) moved higher up in the file before it is first used
5376 (require 'org-entities)
5377 ;; (require 'org-compat) moved higher up in the file before it is first used
5378 (require 'org-faces)
5379 (require 'org-list)
5380 (require 'org-pcomplete)
5381 (require 'org-src)
5382 (require 'org-footnote)
5383 (require 'org-macro)
5385 ;; babel
5386 (require 'ob)
5388 ;;;###autoload
5389 (define-derived-mode org-mode outline-mode "Org"
5390 "Outline-based notes management and organizer, alias
5391 \"Carsten's outline-mode for keeping track of everything.\"
5393 Org mode develops organizational tasks around a NOTES file which
5394 contains information about projects as plain text. Org mode is
5395 implemented on top of Outline mode, which is ideal to keep the content
5396 of large files well structured. It supports ToDo items, deadlines and
5397 time stamps, which magically appear in the diary listing of the Emacs
5398 calendar. Tables are easily created with a built-in table editor.
5399 Plain text URL-like links connect to websites, emails (VM), Usenet
5400 messages (Gnus), BBDB entries, and any files related to the project.
5401 For printing and sharing of notes, an Org file (or a part of it)
5402 can be exported as a structured ASCII or HTML file.
5404 The following commands are available:
5406 \\{org-mode-map}"
5408 ;; Get rid of Outline menus, they are not needed
5409 ;; Need to do this here because define-derived-mode sets up
5410 ;; the keymap so late. Still, it is a waste to call this each time
5411 ;; we switch another buffer into Org mode.
5412 (define-key org-mode-map [menu-bar headings] 'undefined)
5413 (define-key org-mode-map [menu-bar hide] 'undefined)
5414 (define-key org-mode-map [menu-bar show] 'undefined)
5416 (org-load-modules-maybe)
5417 (org-install-agenda-files-menu)
5418 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5419 (add-to-invisibility-spec '(org-cwidth))
5420 (add-to-invisibility-spec '(org-hide-block . t))
5421 (setq-local outline-regexp org-outline-regexp)
5422 (setq-local outline-level 'org-outline-level)
5423 (setq bidi-paragraph-direction 'left-to-right)
5424 (when (and org-ellipsis
5425 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5426 (fboundp 'make-glyph-code))
5427 (unless org-display-table
5428 (setq org-display-table (make-display-table)))
5429 (set-display-table-slot
5430 org-display-table 4
5431 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5432 (if (stringp org-ellipsis) org-ellipsis "..."))))
5433 (setq buffer-display-table org-display-table))
5434 (org-set-regexps-and-options)
5435 (org-set-font-lock-defaults)
5436 (when (and org-tag-faces (not org-tags-special-faces-re))
5437 ;; tag faces set outside customize.... force initialization.
5438 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5439 ;; Calc embedded
5440 (setq-local calc-embedded-open-mode "# ")
5441 ;; Modify a few syntax entries
5442 (modify-syntax-entry ?@ "w")
5443 (modify-syntax-entry ?\" "\"")
5444 (modify-syntax-entry ?\\ "_")
5445 (modify-syntax-entry ?~ "_")
5446 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5447 ;; Activate before-change-function
5448 (setq-local org-table-may-need-update t)
5449 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5450 ;; Check for running clock before killing a buffer
5451 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5452 ;; Initialize macros templates.
5453 (org-macro-initialize-templates)
5454 ;; Initialize radio targets.
5455 (org-update-radio-target-regexp)
5456 ;; Indentation.
5457 (setq-local indent-line-function 'org-indent-line)
5458 (setq-local indent-region-function 'org-indent-region)
5459 ;; Filling and auto-filling.
5460 (org-setup-filling)
5461 ;; Comments.
5462 (org-setup-comments-handling)
5463 ;; Initialize cache.
5464 (org-element-cache-reset)
5465 ;; Beginning/end of defun
5466 (setq-local beginning-of-defun-function 'org-backward-element)
5467 (setq-local end-of-defun-function
5468 (lambda ()
5469 (if (not (org-at-heading-p))
5470 (org-forward-element)
5471 (org-forward-element)
5472 (forward-char -1))))
5473 ;; Next error for sparse trees
5474 (setq-local next-error-function 'org-occur-next-match)
5475 ;; Make sure dependence stuff works reliably, even for users who set it
5476 ;; too late :-(
5477 (if org-enforce-todo-dependencies
5478 (add-hook 'org-blocker-hook
5479 'org-block-todo-from-children-or-siblings-or-parent)
5480 (remove-hook 'org-blocker-hook
5481 'org-block-todo-from-children-or-siblings-or-parent))
5482 (if org-enforce-todo-checkbox-dependencies
5483 (add-hook 'org-blocker-hook
5484 'org-block-todo-from-checkboxes)
5485 (remove-hook 'org-blocker-hook
5486 'org-block-todo-from-checkboxes))
5488 ;; Align options lines
5489 (setq-local
5490 align-mode-rules-list
5491 '((org-in-buffer-settings
5492 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5493 (modes . '(org-mode)))))
5495 ;; Imenu
5496 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5498 ;; Make isearch reveal context
5499 (setq-local outline-isearch-open-invisible-function
5500 (lambda (&rest _) (org-show-context 'isearch)))
5502 ;; Setup the pcomplete hooks
5503 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5504 (setq-local pcomplete-command-name-function 'org-command-at-point)
5505 (setq-local pcomplete-default-completion-function 'ignore)
5506 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5507 (setq-local pcomplete-termination-string "")
5508 (setq-local buffer-face-mode-face 'org-default)
5510 ;; If empty file that did not turn on Org mode automatically, make
5511 ;; it to.
5512 (when (and org-insert-mode-line-in-empty-file
5513 (called-interactively-p 'any)
5514 (= (point-min) (point-max)))
5515 (insert "# -*- mode: org -*-\n\n"))
5516 (unless org-inhibit-startup
5517 (org-unmodified
5518 (when org-startup-with-beamer-mode (org-beamer-mode))
5519 (when org-startup-align-all-tables
5520 (org-table-map-tables #'org-table-align t))
5521 (when org-startup-with-inline-images (org-display-inline-images))
5522 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5523 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5524 (when org-startup-truncated (setq truncate-lines t))
5525 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5526 (org-refresh-effort-properties)))
5527 ;; Try to set `org-hide' face correctly.
5528 (let ((foreground (org-find-invisible-foreground)))
5529 (when foreground
5530 (set-face-foreground 'org-hide foreground))))
5532 ;; Update `customize-package-emacs-version-alist'
5533 (add-to-list 'customize-package-emacs-version-alist
5534 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5535 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5536 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5537 ("9.0" . "26.1")))
5539 (defvar org-mode-transpose-word-syntax-table
5540 (let ((st (make-syntax-table text-mode-syntax-table)))
5541 (dolist (c org-emphasis-alist st)
5542 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5544 (when (fboundp 'abbrev-table-put)
5545 (abbrev-table-put org-mode-abbrev-table
5546 :parents (list text-mode-abbrev-table)))
5548 (defun org-find-invisible-foreground ()
5549 (let ((candidates (remove
5550 "unspecified-bg"
5551 (nconc
5552 (list (face-background 'default)
5553 (face-background 'org-default))
5554 (mapcar
5555 (lambda (alist)
5556 (when (boundp alist)
5557 (cdr (assq 'background-color (symbol-value alist)))))
5558 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5559 (list (face-foreground 'org-hide))))))
5560 (car (remove nil candidates))))
5562 (defun org-current-time (&optional rounding-minutes past)
5563 "Current time, possibly rounded to ROUNDING-MINUTES.
5564 When ROUNDING-MINUTES is not an integer, fall back on the car of
5565 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5566 the rounding returns a past time."
5567 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5568 (car org-time-stamp-rounding-minutes)))
5569 (time (decode-time)) res)
5570 (if (< r 1)
5571 (current-time)
5572 (setq res
5573 (apply 'encode-time
5574 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5575 (nthcdr 2 time))))
5576 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5577 (seconds-to-time (- (float-time res) (* r 60)))
5578 res))))
5580 (defun org-today ()
5581 "Return today date, considering `org-extend-today-until'."
5582 (time-to-days
5583 (time-subtract (current-time)
5584 (list 0 (* 3600 org-extend-today-until) 0))))
5586 ;;;; Font-Lock stuff, including the activators
5588 (defvar org-mouse-map (make-sparse-keymap))
5589 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5590 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5591 (when org-mouse-1-follows-link
5592 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5593 (when org-tab-follows-link
5594 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5595 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5597 (require 'font-lock)
5599 (defconst org-non-link-chars "]\t\n\r<>")
5600 (defvar org-link-types-re nil
5601 "Matches a link that has a url-like prefix like \"http:\"")
5602 (defvar org-link-re-with-space nil
5603 "Matches a link with spaces, optional angular brackets around it.")
5604 (defvar org-link-re-with-space2 nil
5605 "Matches a link with spaces, optional angular brackets around it.")
5606 (defvar org-link-re-with-space3 nil
5607 "Matches a link with spaces, only for internal part in bracket links.")
5608 (defvar org-angle-link-re nil
5609 "Matches link with angular brackets, spaces are allowed.")
5610 (defvar org-plain-link-re nil
5611 "Matches plain link, without spaces.")
5612 (defvar org-bracket-link-regexp nil
5613 "Matches a link in double brackets.")
5614 (defvar org-bracket-link-analytic-regexp nil
5615 "Regular expression used to analyze links.
5616 Here is what the match groups contain after a match:
5617 1: http:
5618 2: http
5619 3: path
5620 4: [desc]
5621 5: desc")
5622 (defvar org-bracket-link-analytic-regexp++ nil
5623 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5624 (defvar org-any-link-re nil
5625 "Regular expression matching any link.")
5627 (defconst org-match-sexp-depth 3
5628 "Number of stacked braces for sub/superscript matching.")
5630 (defun org-create-multibrace-regexp (left right n)
5631 "Create a regular expression which will match a balanced sexp.
5632 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5633 as single character strings.
5634 The regexp returned will match the entire expression including the
5635 delimiters. It will also define a single group which contains the
5636 match except for the outermost delimiters. The maximum depth of
5637 stacked delimiters is N. Escaping delimiters is not possible."
5638 (let* ((nothing (concat "[^" left right "]*?"))
5639 (or "\\|")
5640 (re nothing)
5641 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5642 (while (> n 1)
5643 (setq n (1- n)
5644 re (concat re or next)
5645 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5646 (concat left "\\(" re "\\)" right)))
5648 (defconst org-match-substring-regexp
5649 (concat
5650 "\\(\\S-\\)\\([_^]\\)\\("
5651 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5652 "\\|"
5653 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5654 "\\|"
5655 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5656 "The regular expression matching a sub- or superscript.")
5658 (defconst org-match-substring-with-braces-regexp
5659 (concat
5660 "\\(\\S-\\)\\([_^]\\)"
5661 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5662 "The regular expression matching a sub- or superscript, forcing braces.")
5664 (defun org-make-link-regexps ()
5665 "Update the link regular expressions.
5666 This should be called after the variable `org-link-parameters' has changed."
5667 (let ((types-re (regexp-opt (org-link-types) t)))
5668 (setq org-link-types-re
5669 (concat "\\`" types-re ":")
5670 org-link-re-with-space
5671 (concat "<?" types-re ":"
5672 "\\([^" org-non-link-chars " ]"
5673 "[^" org-non-link-chars "]*"
5674 "[^" org-non-link-chars " ]\\)>?")
5675 org-link-re-with-space2
5676 (concat "<?" types-re ":"
5677 "\\([^" org-non-link-chars " ]"
5678 "[^\t\n\r]*"
5679 "[^" org-non-link-chars " ]\\)>?")
5680 org-link-re-with-space3
5681 (concat "<?" types-re ":"
5682 "\\([^" org-non-link-chars " ]"
5683 "[^\t\n\r]*\\)")
5684 org-angle-link-re
5685 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5686 types-re)
5687 org-plain-link-re
5688 (concat
5689 "\\<" types-re ":"
5690 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5691 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5692 org-bracket-link-regexp
5693 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5694 org-bracket-link-analytic-regexp
5695 (concat
5696 "\\[\\["
5697 "\\(" types-re ":\\)?"
5698 "\\([^]]+\\)"
5699 "\\]"
5700 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5701 "\\]")
5702 org-bracket-link-analytic-regexp++
5703 (concat
5704 "\\[\\["
5705 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5706 "\\([^]]+\\)"
5707 "\\]"
5708 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5709 "\\]")
5710 org-any-link-re
5711 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5712 org-angle-link-re "\\)\\|\\("
5713 org-plain-link-re "\\)"))))
5715 (org-make-link-regexps)
5717 (defvar org-emph-face nil)
5719 (defun org-do-emphasis-faces (limit)
5720 "Run through the buffer and emphasize strings."
5721 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5722 (car org-emphasis-regexp-components))))
5723 (catch :exit
5724 (while (re-search-forward quick-re limit t)
5725 (let* ((marker (match-string 2))
5726 (verbatim? (member marker '("~" "="))))
5727 (when (save-excursion
5728 (goto-char (match-beginning 0))
5729 ;; Do not match headline stars. Do not consider
5730 ;; stars of a headline as closing marker for bold
5731 ;; markup either.
5732 (and (not (looking-at-p org-outline-regexp-bol))
5733 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5734 (not (string-match-p
5735 (concat org-outline-regexp-bol "\\'")
5736 (match-string 0)))))
5737 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5738 (font-lock-prepend-text-property
5739 (match-beginning 2) (match-end 2) 'face face)
5740 (when verbatim?
5741 (org-remove-flyspell-overlays-in
5742 (match-beginning 0) (match-end 0)))
5743 (add-text-properties (match-beginning 2) (match-end 2)
5744 '(font-lock-multiline t org-emphasis t))
5745 (when org-hide-emphasis-markers
5746 (add-text-properties (match-end 4) (match-beginning 5)
5747 '(invisible org-link))
5748 (add-text-properties (match-beginning 3) (match-end 3)
5749 '(invisible org-link)))
5750 (throw :exit t))))))))
5752 (defun org-emphasize (&optional char)
5753 "Insert or change an emphasis, i.e. a font like bold or italic.
5754 If there is an active region, change that region to a new emphasis.
5755 If there is no region, just insert the marker characters and position
5756 the cursor between them.
5757 CHAR should be the marker character. If it is a space, it means to
5758 remove the emphasis of the selected region.
5759 If CHAR is not given (for example in an interactive call) it will be
5760 prompted for."
5761 (interactive)
5762 (let ((erc org-emphasis-regexp-components)
5763 (string "") beg end move s)
5764 (if (org-region-active-p)
5765 (setq beg (region-beginning)
5766 end (region-end)
5767 string (buffer-substring beg end))
5768 (setq move t))
5770 (unless char
5771 (message "Emphasis marker or tag: [%s]"
5772 (mapconcat #'car org-emphasis-alist ""))
5773 (setq char (read-char-exclusive)))
5774 (if (equal char ?\s)
5775 (setq s ""
5776 move nil)
5777 (unless (assoc (char-to-string char) org-emphasis-alist)
5778 (user-error "No such emphasis marker: \"%c\"" char))
5779 (setq s (char-to-string char)))
5780 (while (and (> (length string) 1)
5781 (equal (substring string 0 1) (substring string -1))
5782 (assoc (substring string 0 1) org-emphasis-alist))
5783 (setq string (substring string 1 -1)))
5784 (setq string (concat s string s))
5785 (when beg (delete-region beg end))
5786 (unless (or (bolp)
5787 (string-match (concat "[" (nth 0 erc) "\n]")
5788 (char-to-string (char-before (point)))))
5789 (insert " "))
5790 (unless (or (eobp)
5791 (string-match (concat "[" (nth 1 erc) "\n]")
5792 (char-to-string (char-after (point)))))
5793 (insert " ") (backward-char 1))
5794 (insert string)
5795 (and move (backward-char 1))))
5797 (defconst org-nonsticky-props
5798 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5800 (defsubst org-rear-nonsticky-at (pos)
5801 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5803 (defun org-activate-plain-links (limit)
5804 "Add link properties for plain links."
5805 (when (and (re-search-forward org-plain-link-re limit t)
5806 (not (org-in-src-block-p)))
5808 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5809 'face))
5810 (link (match-string-no-properties 0))
5811 (type (match-string-no-properties 1))
5812 (path (match-string-no-properties 2))
5813 (link-start (match-beginning 0))
5814 (link-end (match-end 0))
5815 (link-face (org-link-get-parameter type :face))
5816 (help-echo (org-link-get-parameter type :help-echo))
5817 (htmlize-link (org-link-get-parameter type :htmlize-link))
5818 (activate-func (org-link-get-parameter type :activate-func)))
5819 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5820 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5821 (add-text-properties (match-beginning 0) (match-end 0)
5822 (list
5823 'mouse-face (or (org-link-get-parameter type :mouse-face)
5824 'highlight)
5825 'face (cond
5826 ;; A function that returns a face
5827 ((functionp link-face)
5828 (funcall link-face path))
5829 ;; a face
5830 ((facep link-face)
5831 link-face)
5832 ;; An anonymous face
5833 ((consp link-face)
5834 link-face)
5835 ;; default
5837 'org-link))
5838 'help-echo (cond
5839 ((stringp help-echo)
5840 help-echo)
5841 ((functionp help-echo)
5842 help-echo)
5844 (concat "LINK: "
5845 (save-match-data
5846 (org-link-unescape link)))))
5847 'htmlize-link (cond
5848 ((functionp htmlize-link)
5849 (funcall htmlize-link path))
5851 `(:uri ,link)))
5852 'keymap (or (org-link-get-parameter type :keymap)
5853 org-mouse-map)
5854 'org-link-start (match-beginning 0)))
5855 (org-rear-nonsticky-at (match-end 0))
5856 (when activate-func
5857 (funcall activate-func link-start link-end path nil))
5858 t))))
5860 (defun org-activate-code (limit)
5861 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5862 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5863 (remove-text-properties (match-beginning 0) (match-end 0)
5864 '(display t invisible t intangible t))
5867 (defcustom org-src-fontify-natively t
5868 "When non-nil, fontify code in code blocks.
5869 See also the `org-block' face."
5870 :type 'boolean
5871 :version "24.4"
5872 :package-version '(Org . "8.3")
5873 :group 'org-appearance
5874 :group 'org-babel)
5876 (defcustom org-allow-promoting-top-level-subtree nil
5877 "When non-nil, allow promoting a top level subtree.
5878 The leading star of the top level headline will be replaced
5879 by a #."
5880 :type 'boolean
5881 :version "24.1"
5882 :group 'org-appearance)
5884 (defun org-fontify-meta-lines-and-blocks (limit)
5885 (condition-case nil
5886 (org-fontify-meta-lines-and-blocks-1 limit)
5887 (error (message "org-mode fontification error in %S at %d"
5888 (current-buffer)
5889 (line-number-at-pos)))))
5891 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5892 "Fontify #+ lines and blocks."
5893 (let ((case-fold-search t))
5894 (when (re-search-forward
5895 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5896 limit t)
5897 (let ((beg (match-beginning 0))
5898 (block-start (match-end 0))
5899 (block-end nil)
5900 (lang (match-string 7))
5901 (beg1 (line-beginning-position 2))
5902 (dc1 (downcase (match-string 2)))
5903 (dc3 (downcase (match-string 3)))
5904 end end1 quoting block-type)
5905 (cond
5906 ((and (match-end 4) (equal dc3 "+begin"))
5907 ;; Truly a block
5908 (setq block-type (downcase (match-string 5))
5909 quoting (member block-type org-protecting-blocks))
5910 (when (re-search-forward
5911 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5912 nil t) ;; on purpose, we look further than LIMIT
5913 (setq end (min (point-max) (match-end 0))
5914 end1 (min (point-max) (1- (match-beginning 0))))
5915 (setq block-end (match-beginning 0))
5916 (when quoting
5917 (org-remove-flyspell-overlays-in beg1 end1)
5918 (remove-text-properties beg end
5919 '(display t invisible t intangible t)))
5920 (add-text-properties
5921 beg end '(font-lock-fontified t font-lock-multiline t))
5922 (add-text-properties beg beg1 '(face org-meta-line))
5923 (org-remove-flyspell-overlays-in beg beg1)
5924 (add-text-properties ; For end_src
5925 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5926 (org-remove-flyspell-overlays-in end1 end)
5927 (cond
5928 ((and lang (not (string= lang "")) org-src-fontify-natively)
5929 (org-src-font-lock-fontify-block lang block-start block-end)
5930 (add-text-properties beg1 block-end '(src-block t)))
5931 (quoting
5932 (add-text-properties beg1 (min (point-max) (1+ end1))
5933 (list 'face
5934 (list :inherit
5935 (let ((face-name
5936 (intern (format "org-block-%s" lang))))
5937 (append (and (facep face-name) (list face-name))
5938 '(org-block))))))) ; end of source block
5939 ((not org-fontify-quote-and-verse-blocks))
5940 ((string= block-type "quote")
5941 (add-face-text-property
5942 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5943 ((string= block-type "verse")
5944 (add-face-text-property
5945 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5946 (add-text-properties beg beg1 '(face org-block-begin-line))
5947 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5948 '(face org-block-end-line))
5950 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5951 (org-remove-flyspell-overlays-in
5952 (match-beginning 0)
5953 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5954 (add-text-properties
5955 beg (match-end 3)
5956 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5957 '(font-lock-fontified t invisible t)
5958 '(font-lock-fontified t face org-document-info-keyword)))
5959 (add-text-properties
5960 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5961 (if (string-equal dc1 "+title:")
5962 '(font-lock-fontified t face org-document-title)
5963 '(font-lock-fontified t face org-document-info))))
5964 ((string-prefix-p "+caption" dc1)
5965 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5966 (remove-text-properties (match-beginning 0) (match-end 0)
5967 '(display t invisible t intangible t))
5968 ;; Handle short captions.
5969 (save-excursion
5970 (beginning-of-line)
5971 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5972 (add-text-properties (line-beginning-position) (match-end 1)
5973 '(font-lock-fontified t face org-meta-line))
5974 (add-text-properties (match-end 0) (line-end-position)
5975 '(font-lock-fontified t face org-block))
5977 ((member dc3 '(" " ""))
5978 (org-remove-flyspell-overlays-in beg (match-end 0))
5979 (add-text-properties
5980 beg (match-end 0)
5981 '(font-lock-fontified t face font-lock-comment-face)))
5982 (t ;; just any other in-buffer setting, but not indented
5983 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5984 (remove-text-properties (match-beginning 0) (match-end 0)
5985 '(display t invisible t intangible t))
5986 (add-text-properties beg (match-end 0)
5987 '(font-lock-fontified t face org-meta-line))
5988 t))))))
5990 (defun org-fontify-drawers (limit)
5991 "Fontify drawers."
5992 (when (re-search-forward org-drawer-regexp limit t)
5993 (add-text-properties
5994 (match-beginning 0) (match-end 0)
5995 '(font-lock-fontified t face org-special-keyword))
5996 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5999 (defun org-fontify-macros (limit)
6000 "Fontify macros."
6001 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6002 (add-text-properties
6003 (match-beginning 0) (match-end 0)
6004 '(font-lock-fontified t face org-macro))
6005 (when org-hide-macro-markers
6006 (add-text-properties (match-end 2) (match-beginning 2)
6007 '(invisible t))
6008 (add-text-properties (match-beginning 1) (match-end 1)
6009 '(invisible t)))
6010 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6013 (defun org-activate-angle-links (limit)
6014 "Add text properties for angle links."
6015 (when (and (re-search-forward org-angle-link-re limit t)
6016 (not (org-in-src-block-p)))
6017 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6018 (add-text-properties (match-beginning 0) (match-end 0)
6019 (list 'mouse-face 'highlight
6020 'keymap org-mouse-map
6021 'font-lock-multiline t))
6022 (org-rear-nonsticky-at (match-end 0))
6025 (defun org-activate-footnote-links (limit)
6026 "Add text properties for footnotes."
6027 (let ((fn (org-footnote-next-reference-or-definition limit)))
6028 (when fn
6029 (let* ((beg (nth 1 fn))
6030 (end (nth 2 fn))
6031 (label (car fn))
6032 (referencep (/= (line-beginning-position) beg)))
6033 (when (and referencep (nth 3 fn))
6034 (save-excursion
6035 (goto-char beg)
6036 (search-forward (or label "fn:"))
6037 (org-remove-flyspell-overlays-in beg (match-end 0))))
6038 (add-text-properties beg end
6039 (list 'mouse-face 'highlight
6040 'keymap org-mouse-map
6041 'help-echo
6042 (if referencep "Footnote reference"
6043 "Footnote definition")
6044 'font-lock-fontified t
6045 'font-lock-multiline t
6046 'face 'org-footnote))))))
6048 (defun org-activate-bracket-links (limit)
6049 "Add text properties for bracketed links."
6050 (when (and (re-search-forward org-bracket-link-regexp limit t)
6051 (not (org-in-src-block-p)))
6052 (let* ((hl (save-match-data
6053 (org-link-expand-abbrev (match-string-no-properties 1))))
6054 (type (save-match-data
6055 (and (string-match org-plain-link-re hl)
6056 (match-string-no-properties 1 hl))))
6057 (path (save-match-data
6058 (and (string-match org-plain-link-re hl)
6059 (match-string-no-properties 2 hl))))
6060 (link-start (match-beginning 0))
6061 (link-end (match-end 0))
6062 (bracketp t)
6063 (help-echo (org-link-get-parameter type :help-echo))
6064 (help (cond
6065 ((stringp help-echo)
6066 help-echo)
6067 ((functionp help-echo)
6068 help-echo)
6070 (concat "LINK: "
6071 (save-match-data
6072 (org-link-unescape hl))))))
6073 (link-face (org-link-get-parameter type :face))
6074 (face (cond
6075 ;; A function that returns a face
6076 ((functionp link-face)
6077 (funcall link-face path))
6078 ;; a face
6079 ((facep link-face)
6080 link-face)
6081 ;; An anonymous face
6082 ((consp link-face)
6083 link-face)
6084 ;; default
6086 'org-link)))
6087 (keymap (or (org-link-get-parameter type :keymap)
6088 org-mouse-map))
6089 (mouse-face (or (org-link-get-parameter type :mouse-face)
6090 'highlight))
6091 (htmlize (org-link-get-parameter type :htmlize-link))
6092 (htmlize-link (cond
6093 ((functionp htmlize)
6094 (funcall htmlize))
6096 `(:uri ,(format "%s:%s" type path)))))
6097 (activate-func (org-link-get-parameter type :activate-func))
6098 ;; invisible part
6099 (ip (list 'invisible (or
6100 (org-link-get-parameter type :display)
6101 'org-link)
6102 'face face
6103 'keymap keymap
6104 'mouse-face mouse-face
6105 'font-lock-multiline t
6106 'help-echo help
6107 'htmlize-link htmlize-link))
6108 ;; visible part
6109 (vp (list 'keymap keymap
6110 'face face
6111 'mouse-face mouse-face
6112 'font-lock-multiline t
6113 'help-echo help
6114 'htmlize-link htmlize-link)))
6115 ;; We need to remove the invisible property here. Table narrowing
6116 ;; may have made some of this invisible.
6117 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6118 (remove-text-properties (match-beginning 0) (match-end 0)
6119 '(invisible nil))
6120 (if (match-end 3)
6121 (progn
6122 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6123 (org-rear-nonsticky-at (match-beginning 3))
6124 (add-text-properties (match-beginning 3) (match-end 3) vp)
6125 (org-rear-nonsticky-at (match-end 3))
6126 (add-text-properties (match-end 3) (match-end 0) ip)
6127 (org-rear-nonsticky-at (match-end 0)))
6128 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6129 (org-rear-nonsticky-at (match-beginning 1))
6130 (add-text-properties (match-beginning 1) (match-end 1) vp)
6131 (org-rear-nonsticky-at (match-end 1))
6132 (add-text-properties (match-end 1) (match-end 0) ip)
6133 (org-rear-nonsticky-at (match-end 0)))
6134 (when activate-func
6135 (funcall activate-func link-start link-end path bracketp))
6136 t)))
6138 (defun org-activate-dates (limit)
6139 "Add text properties for dates."
6140 (when (and (re-search-forward org-tsr-regexp-both limit t)
6141 (not (equal (char-before (match-beginning 0)) 91)))
6142 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6143 (add-text-properties (match-beginning 0) (match-end 0)
6144 (list 'mouse-face 'highlight
6145 'keymap org-mouse-map))
6146 (org-rear-nonsticky-at (match-end 0))
6147 (when org-display-custom-times
6148 (if (match-end 3)
6149 (org-display-custom-time (match-beginning 3) (match-end 3))
6150 (org-display-custom-time (match-beginning 1) (match-end 1))))
6153 (defvar-local org-target-link-regexp nil
6154 "Regular expression matching radio targets in plain text.")
6156 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6157 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6158 border border border))
6159 "Regular expression matching a link target.")
6161 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6162 "Regular expression matching a radio target.")
6164 (defconst org-any-target-regexp
6165 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6166 "Regular expression matching any target.")
6168 (defun org-activate-target-links (limit)
6169 "Add text properties for target matches."
6170 (when org-target-link-regexp
6171 (let ((case-fold-search t))
6172 (when (re-search-forward org-target-link-regexp limit t)
6173 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6174 (add-text-properties (match-beginning 1) (match-end 1)
6175 (list 'mouse-face 'highlight
6176 'keymap org-mouse-map
6177 'help-echo "Radio target link"
6178 'org-linked-text t))
6179 (org-rear-nonsticky-at (match-end 1))
6180 t))))
6182 (defun org-update-radio-target-regexp ()
6183 "Find all radio targets in this file and update the regular expression.
6184 Also refresh fontification if needed."
6185 (interactive)
6186 (let ((old-regexp org-target-link-regexp)
6187 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6188 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6189 (targets
6190 (org-with-wide-buffer
6191 (goto-char (point-min))
6192 (let (rtn)
6193 (while (re-search-forward org-radio-target-regexp nil t)
6194 ;; Make sure point is really within the object.
6195 (backward-char)
6196 (let ((obj (org-element-context)))
6197 (when (eq (org-element-type obj) 'radio-target)
6198 (cl-pushnew (org-element-property :value obj) rtn
6199 :test #'equal))))
6200 rtn))))
6201 (setq org-target-link-regexp
6202 (and targets
6203 (concat before-re
6204 (mapconcat
6205 (lambda (x)
6206 (replace-regexp-in-string
6207 " +" "\\s-+" (regexp-quote x) t t))
6208 targets
6209 "\\|")
6210 after-re)))
6211 (unless (equal old-regexp org-target-link-regexp)
6212 ;; Clean-up cache.
6213 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6214 ((not org-target-link-regexp) old-regexp)
6216 (concat before-re
6217 (mapconcat
6218 (lambda (re)
6219 (substring re (length before-re)
6220 (- (length after-re))))
6221 (list old-regexp org-target-link-regexp)
6222 "\\|")
6223 after-re)))))
6224 (org-with-wide-buffer
6225 (goto-char (point-min))
6226 (while (re-search-forward regexp nil t)
6227 (org-element-cache-refresh (match-beginning 1)))))
6228 ;; Re fontify buffer.
6229 (when (memq 'radio org-highlight-links)
6230 (org-restart-font-lock)))))
6232 (defun org-hide-wide-columns (limit)
6233 (let (s e)
6234 (setq s (text-property-any (point) (or limit (point-max))
6235 'org-cwidth t))
6236 (when s
6237 (setq e (next-single-property-change s 'org-cwidth))
6238 (add-text-properties s e '(invisible org-cwidth))
6239 (goto-char e)
6240 t)))
6242 (defvar org-latex-and-related-regexp nil
6243 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6245 (defun org-compute-latex-and-related-regexp ()
6246 "Compute regular expression for LaTeX, entities and sub/superscript.
6247 Result depends on variable `org-highlight-latex-and-related'."
6248 (setq-local
6249 org-latex-and-related-regexp
6250 (let* ((re-sub
6251 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6252 ((eq org-use-sub-superscripts '{})
6253 (list org-match-substring-with-braces-regexp))
6254 (org-use-sub-superscripts (list org-match-substring-regexp))))
6255 (re-latex
6256 (when (memq 'latex org-highlight-latex-and-related)
6257 (let ((matchers (plist-get org-format-latex-options :matchers)))
6258 (delq nil
6259 (mapcar (lambda (x)
6260 (and (member (car x) matchers) (nth 1 x)))
6261 org-latex-regexps)))))
6262 (re-entities
6263 (when (memq 'entities org-highlight-latex-and-related)
6264 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6265 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6267 (defun org-do-latex-and-related (limit)
6268 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6269 LIMIT bounds the search for syntax to highlight. Stop at first
6270 highlighted object, if any. Return t if some highlighting was
6271 done, nil otherwise."
6272 (when (org-string-nw-p org-latex-and-related-regexp)
6273 (catch 'found
6274 (while (re-search-forward org-latex-and-related-regexp limit t)
6275 (unless
6276 (cl-some
6277 (lambda (f)
6278 (memq f '(org-code org-verbatim underline org-special-keyword)))
6279 (save-excursion
6280 (goto-char (1+ (match-beginning 0)))
6281 (face-at-point nil t)))
6282 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6283 '(?_ ?^))
6285 0)))
6286 (font-lock-prepend-text-property
6287 (+ offset (match-beginning 0)) (match-end 0)
6288 'face 'org-latex-and-related)
6289 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6290 '(font-lock-multiline t)))
6291 (throw 'found t)))
6292 nil)))
6294 (defun org-restart-font-lock ()
6295 "Restart `font-lock-mode', to force refontification."
6296 (when (and (boundp 'font-lock-mode) font-lock-mode)
6297 (font-lock-mode -1)
6298 (font-lock-mode 1)))
6300 (defun org-activate-tags (limit)
6301 (when (re-search-forward
6302 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6303 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6304 (add-text-properties (match-beginning 1) (match-end 1)
6305 (list 'mouse-face 'highlight
6306 'keymap org-mouse-map))
6307 (org-rear-nonsticky-at (match-end 1))
6310 (defun org-outline-level ()
6311 "Compute the outline level of the heading at point.
6313 If this is called at a normal headline, the level is the number
6314 of stars. Use `org-reduced-level' to remove the effect of
6315 `org-odd-levels'. Unlike to `org-current-level', this function
6316 takes into consideration inlinetasks."
6317 (org-with-wide-buffer
6318 (end-of-line)
6319 (if (re-search-backward org-outline-regexp-bol nil t)
6320 (1- (- (match-end 0) (match-beginning 0)))
6321 0)))
6323 (defvar org-font-lock-keywords nil)
6325 (defsubst org-re-property (property &optional literal allow-null value)
6326 "Return a regexp matching a PROPERTY line.
6328 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6329 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6330 non-nil, match properties even without a value.
6332 Match group 3 is set to the value when it exists. If there is no
6333 value and ALLOW-NULL is non-nil, it is set to the empty string.
6335 With optional argument VALUE, match only property lines with
6336 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6337 unless LITERAL is non-nil."
6338 (concat
6339 "^\\(?4:[ \t]*\\)"
6340 (format "\\(?1::\\(?2:%s\\):\\)"
6341 (if literal property (regexp-quote property)))
6342 (cond (value
6343 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6344 (if literal value (regexp-quote value))))
6345 (allow-null
6346 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6348 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6350 (defconst org-property-re
6351 (org-re-property "\\S-+" 'literal t)
6352 "Regular expression matching a property line.
6353 There are four matching groups:
6354 1: :PROPKEY: including the leading and trailing colon,
6355 2: PROPKEY without the leading and trailing colon,
6356 3: PROPVAL without leading or trailing spaces,
6357 4: the indentation of the current line,
6358 5: trailing whitespace.")
6360 (defvar org-font-lock-hook nil
6361 "Functions to be called for special font lock stuff.")
6363 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6365 (defvar org-font-lock-set-keywords-hook nil
6366 "Functions that can manipulate `org-font-lock-extra-keywords'.
6367 This is called after `org-font-lock-extra-keywords' is defined, but before
6368 it is installed to be used by font lock. This can be useful if something
6369 needs to be inserted at a specific position in the font-lock sequence.")
6371 (defun org-font-lock-hook (limit)
6372 "Run `org-font-lock-hook' within LIMIT."
6373 (run-hook-with-args 'org-font-lock-hook limit))
6375 (defun org-set-font-lock-defaults ()
6376 "Set font lock defaults for the current buffer."
6377 (let* ((em org-fontify-emphasized-text)
6378 (lk org-highlight-links)
6379 (org-font-lock-extra-keywords
6380 (list
6381 ;; Call the hook
6382 '(org-font-lock-hook)
6383 ;; Headlines
6384 `(,(if org-fontify-whole-heading-line
6385 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6386 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6387 (1 (org-get-level-face 1))
6388 (2 (org-get-level-face 2))
6389 (3 (org-get-level-face 3)))
6390 ;; Table lines
6391 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6392 (1 'org-table t))
6393 ;; Table internals
6394 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6395 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6396 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6397 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6398 ;; Drawers
6399 '(org-fontify-drawers)
6400 ;; Properties
6401 (list org-property-re
6402 '(1 'org-special-keyword t)
6403 '(3 'org-property-value t))
6404 ;; Links
6405 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6406 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6407 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6408 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6409 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6410 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6411 (when (memq 'footnote lk) '(org-activate-footnote-links))
6412 ;; Targets.
6413 (list org-any-target-regexp '(0 'org-target t))
6414 ;; Diary sexps.
6415 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6416 ;; Macro
6417 '(org-fontify-macros)
6418 '(org-hide-wide-columns (0 nil append))
6419 ;; TODO keyword
6420 (list (format org-heading-keyword-regexp-format
6421 org-todo-regexp)
6422 '(2 (org-get-todo-face 2) t))
6423 ;; DONE
6424 (if org-fontify-done-headline
6425 (list (format org-heading-keyword-regexp-format
6426 (concat
6427 "\\(?:"
6428 (mapconcat 'regexp-quote org-done-keywords "\\|")
6429 "\\)"))
6430 '(2 'org-headline-done t))
6431 nil)
6432 ;; Priorities
6433 '(org-font-lock-add-priority-faces)
6434 ;; Tags
6435 '(org-font-lock-add-tag-faces)
6436 ;; Tags groups
6437 (when (and org-group-tags org-tag-groups-alist)
6438 (list (concat org-outline-regexp-bol ".+\\(:"
6439 (regexp-opt (mapcar 'car org-tag-groups-alist))
6440 ":\\).*$")
6441 '(1 'org-tag-group prepend)))
6442 ;; Special keywords
6443 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6444 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6445 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6446 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6447 ;; Emphasis
6448 (when em '(org-do-emphasis-faces))
6449 ;; Checkboxes
6450 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6451 1 'org-checkbox prepend)
6452 (when (cdr (assq 'checkbox org-list-automatic-rules))
6453 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6454 (0 (org-get-checkbox-statistics-face) t)))
6455 ;; Description list items
6456 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6457 1 'org-list-dt prepend)
6458 ;; ARCHIVEd headings
6459 (list (concat
6460 org-outline-regexp-bol
6461 "\\(.*:" org-archive-tag ":.*\\)")
6462 '(1 'org-archived prepend))
6463 ;; Specials
6464 '(org-do-latex-and-related)
6465 '(org-fontify-entities)
6466 '(org-raise-scripts)
6467 ;; Code
6468 '(org-activate-code (1 'org-code t))
6469 ;; COMMENT
6470 (list (format
6471 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6472 org-todo-regexp
6473 org-comment-string)
6474 '(9 'org-special-keyword t))
6475 ;; Blocks and meta lines
6476 '(org-fontify-meta-lines-and-blocks))))
6477 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6478 (run-hooks 'org-font-lock-set-keywords-hook)
6479 ;; Now set the full font-lock-keywords
6480 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6481 (setq-local font-lock-defaults
6482 '(org-font-lock-keywords t nil nil backward-paragraph))
6483 (kill-local-variable 'font-lock-keywords)
6484 nil))
6486 (defun org-toggle-pretty-entities ()
6487 "Toggle the composition display of entities as UTF8 characters."
6488 (interactive)
6489 (setq-local org-pretty-entities (not org-pretty-entities))
6490 (org-restart-font-lock)
6491 (if org-pretty-entities
6492 (message "Entities are now displayed as UTF8 characters")
6493 (save-restriction
6494 (widen)
6495 (decompose-region (point-min) (point-max))
6496 (message "Entities are now displayed as plain text"))))
6498 (defvar-local org-custom-properties-overlays nil
6499 "List of overlays used for custom properties.")
6501 (defun org-toggle-custom-properties-visibility ()
6502 "Display or hide properties in `org-custom-properties'."
6503 (interactive)
6504 (if org-custom-properties-overlays
6505 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6506 (setq org-custom-properties-overlays nil))
6507 (when org-custom-properties
6508 (org-with-wide-buffer
6509 (goto-char (point-min))
6510 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6511 (while (re-search-forward regexp nil t)
6512 (let ((end (cdr (save-match-data (org-get-property-block)))))
6513 (when (and end (< (point) end))
6514 ;; Hide first custom property in current drawer.
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 ;; Hide additional custom properties in the same drawer.
6520 (while (re-search-forward regexp end t)
6521 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6522 (overlay-put o 'invisible t)
6523 (overlay-put o 'org-custom-property t)
6524 (push o org-custom-properties-overlays)))))
6525 ;; Each entry is limited to a single property drawer.
6526 (outline-next-heading)))))))
6528 (defun org-fontify-entities (limit)
6529 "Find an entity to fontify."
6530 (let (ee)
6531 (when org-pretty-entities
6532 (catch 'match
6533 ;; "\_ "-family is left out on purpose. Only the first one,
6534 ;; i.e., "\_ ", could be fontified anyway, and it would be
6535 ;; confusing when adding a second white space character.
6536 (while (re-search-forward
6537 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6538 limit t)
6539 (when (and (not (org-at-comment-p))
6540 (setq ee (org-entity-get (match-string 1)))
6541 (= (length (nth 6 ee)) 1))
6542 (let* ((end (if (equal (match-string 2) "{}")
6543 (match-end 2)
6544 (match-end 1))))
6545 (add-text-properties
6546 (match-beginning 0) end
6547 (list 'font-lock-fontified t))
6548 (compose-region (match-beginning 0) end
6549 (nth 6 ee) nil)
6550 (backward-char 1)
6551 (throw 'match t))))
6552 nil))))
6554 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6555 "Fontify string S like in Org mode."
6556 (with-temp-buffer
6557 (insert s)
6558 (let ((org-odd-levels-only odd-levels))
6559 (org-mode)
6560 (org-font-lock-ensure)
6561 (buffer-string))))
6563 (defvar org-m nil)
6564 (defvar org-l nil)
6565 (defvar org-f nil)
6566 (defun org-get-level-face (n)
6567 "Get the right face for match N in font-lock matching of headlines."
6568 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6569 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6570 (if org-cycle-level-faces
6571 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6572 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6573 (cond
6574 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6575 ((eq n 2) org-f)
6576 (t (unless org-level-color-stars-only org-f))))
6578 (defun org-face-from-face-or-color (context inherit face-or-color)
6579 "Create a face list that inherits INHERIT, but sets the foreground color.
6580 When FACE-OR-COLOR is not a string, just return it."
6581 (if (stringp face-or-color)
6582 (list :inherit inherit
6583 (cdr (assoc context org-faces-easy-properties))
6584 face-or-color)
6585 face-or-color))
6587 (defun org-get-todo-face (kwd)
6588 "Get the right face for a TODO keyword KWD.
6589 If KWD is a number, get the corresponding match group."
6590 (when (numberp kwd) (setq kwd (match-string kwd)))
6591 (or (org-face-from-face-or-color
6592 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6593 (and (member kwd org-done-keywords) 'org-done)
6594 'org-todo))
6596 (defun org-get-priority-face (priority)
6597 "Get the right face for PRIORITY.
6598 PRIORITY is a character."
6599 (or (org-face-from-face-or-color
6600 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6601 'org-priority))
6603 (defun org-get-tag-face (tag)
6604 "Get the right face for TAG.
6605 If TAG is a number, get the corresponding match group."
6606 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6607 (or (org-face-from-face-or-color
6608 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6609 'org-tag)))
6611 (defun org-font-lock-add-priority-faces (limit)
6612 "Add the special priority faces."
6613 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6614 (add-text-properties
6615 (match-beginning 1) (match-end 1)
6616 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6617 'font-lock-fontified t))))
6619 (defun org-font-lock-add-tag-faces (limit)
6620 "Add the special tag faces."
6621 (when (and org-tag-faces org-tags-special-faces-re)
6622 (while (re-search-forward org-tags-special-faces-re limit t)
6623 (add-text-properties (match-beginning 1) (match-end 1)
6624 (list 'face (org-get-tag-face 1)
6625 'font-lock-fontified t))
6626 (backward-char 1))))
6628 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6629 "Remove fontification and activation overlays from links."
6630 (font-lock-default-unfontify-region beg end)
6631 (let* ((buffer-undo-list t)
6632 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6633 (inhibit-modification-hooks t)
6634 deactivate-mark buffer-file-name buffer-file-truename)
6635 (decompose-region beg end)
6636 (remove-text-properties beg end
6637 '(mouse-face t keymap t org-linked-text t
6638 invisible t intangible t
6639 org-emphasis t))
6640 (org-remove-font-lock-display-properties beg end)))
6642 (defconst org-script-display '(((raise -0.3) (height 0.7))
6643 ((raise 0.3) (height 0.7))
6644 ((raise -0.5))
6645 ((raise 0.5)))
6646 "Display properties for showing superscripts and subscripts.")
6648 (defun org-remove-font-lock-display-properties (beg end)
6649 "Remove specific display properties that have been added by font lock.
6650 The will remove the raise properties that are used to show superscripts
6651 and subscripts."
6652 (let (next prop)
6653 (while (< beg end)
6654 (setq next (next-single-property-change beg 'display nil end)
6655 prop (get-text-property beg 'display))
6656 (when (member prop org-script-display)
6657 (put-text-property beg next 'display nil))
6658 (setq beg next))))
6660 (defun org-raise-scripts (limit)
6661 "Add raise properties to sub/superscripts."
6662 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6663 (re-search-forward
6664 (if (eq org-use-sub-superscripts t)
6665 org-match-substring-regexp
6666 org-match-substring-with-braces-regexp)
6667 limit t))
6668 (let* ((pos (point)) table-p comment-p
6669 (mpos (match-beginning 3))
6670 (emph-p (get-text-property mpos 'org-emphasis))
6671 (link-p (get-text-property mpos 'mouse-face))
6672 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6673 (goto-char (point-at-bol))
6674 (setq table-p (looking-at-p org-table-dataline-regexp)
6675 comment-p (looking-at-p "^[ \t]*#[ +]"))
6676 (goto-char pos)
6677 ;; Handle a_b^c
6678 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6679 (unless (or comment-p emph-p link-p keyw-p)
6680 (put-text-property (match-beginning 3) (match-end 0)
6681 'display
6682 (if (equal (char-after (match-beginning 2)) ?^)
6683 (nth (if table-p 3 1) org-script-display)
6684 (nth (if table-p 2 0) org-script-display)))
6685 (add-text-properties (match-beginning 2) (match-end 2)
6686 (list 'invisible t
6687 'org-dwidth t 'org-dwidth-n 1))
6688 (if (and (eq (char-after (match-beginning 3)) ?{)
6689 (eq (char-before (match-end 3)) ?}))
6690 (progn
6691 (add-text-properties
6692 (match-beginning 3) (1+ (match-beginning 3))
6693 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6694 (add-text-properties
6695 (1- (match-end 3)) (match-end 3)
6696 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6697 t)))
6699 ;;;; Visibility cycling, including org-goto and indirect buffer
6701 ;;; Cycling
6703 (defvar-local org-cycle-global-status nil)
6704 (put 'org-cycle-global-status 'org-state t)
6705 (defvar-local org-cycle-subtree-status nil)
6706 (put 'org-cycle-subtree-status 'org-state t)
6708 (defvar org-inlinetask-min-level)
6710 (defun org-unlogged-message (&rest args)
6711 "Display a message, but avoid logging it in the *Messages* buffer."
6712 (let ((message-log-max nil))
6713 (apply 'message args)))
6715 ;;;###autoload
6716 (defun org-cycle (&optional arg)
6717 "TAB-action and visibility cycling for Org mode.
6719 This is the command invoked in Org mode by the `TAB' key. Its main
6720 purpose is outline visibility cycling, but it also invokes other actions
6721 in special contexts.
6723 When this function is called with a `\\[universal-argument]' prefix, rotate \
6724 the entire
6725 buffer through 3 states (global cycling)
6726 1. OVERVIEW: Show only top-level headlines.
6727 2. CONTENTS: Show all headlines of all levels, but no body text.
6728 3. SHOW ALL: Show everything.
6730 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6731 switch to the startup visibility,
6732 determined by the variable `org-startup-folded', and by any VISIBILITY
6733 properties in the buffer.
6735 With a `\\[universal-argument] \\[universal-argument] \
6736 \\[universal-argument]' prefix argument, show the entire buffer, including
6737 any drawers.
6739 When inside a table, re-align the table and move to the next field.
6741 When point is at the beginning of a headline, rotate the subtree started
6742 by this line through 3 different states (local cycling)
6743 1. FOLDED: Only the main headline is shown.
6744 2. CHILDREN: The main headline and the direct children are shown.
6745 From this state, you can move to one of the children
6746 and zoom in further.
6747 3. SUBTREE: Show the entire subtree, including body text.
6748 If there is no subtree, switch directly from CHILDREN to FOLDED.
6750 When point is at the beginning of an empty headline and the variable
6751 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6752 of the headline by demoting and promoting it to likely levels. This
6753 speeds up creation document structure by pressing `TAB' once or several
6754 times right after creating a new headline.
6756 When there is a numeric prefix, go up to a heading with level ARG, do
6757 a `show-subtree' and return to the previous cursor position. If ARG
6758 is negative, go up that many levels.
6760 When point is not at the beginning of a headline, execute the global
6761 binding for `TAB', which is re-indenting the line. See the option
6762 `org-cycle-emulate-tab' for details.
6764 As a special case, if point is at the beginning of the buffer and there is
6765 no headline in line 1, this function will act as if called with prefix arg
6766 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6767 prefix arg, but only
6768 if the variable `org-cycle-global-at-bob' is t."
6769 (interactive "P")
6770 (org-load-modules-maybe)
6771 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6772 (and org-cycle-level-after-item/entry-creation
6773 (or (org-cycle-level)
6774 (org-cycle-item-indentation))))
6775 (let* ((limit-level
6776 (or org-cycle-max-level
6777 (and (boundp 'org-inlinetask-min-level)
6778 org-inlinetask-min-level
6779 (1- org-inlinetask-min-level))))
6780 (nstars (and limit-level
6781 (if org-odd-levels-only
6782 (and limit-level (1- (* limit-level 2)))
6783 limit-level)))
6784 (org-outline-regexp
6785 (if (not (derived-mode-p 'org-mode))
6786 outline-regexp
6787 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6788 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6789 (not (looking-at org-outline-regexp))))
6790 (org-cycle-hook
6791 (if bob-special
6792 (delq 'org-optimize-window-after-visibility-change
6793 (copy-sequence org-cycle-hook))
6794 org-cycle-hook))
6795 (pos (point)))
6797 (cond
6799 ((equal arg '(16))
6800 (setq last-command 'dummy)
6801 (org-set-startup-visibility)
6802 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6804 ((equal arg '(64))
6805 (outline-show-all)
6806 (org-unlogged-message "Entire buffer visible, including drawers"))
6808 ((equal arg '(4)) (org-cycle-internal-global))
6810 ;; Try hiding block at point.
6811 ((org-hide-block-toggle-maybe))
6813 ;; Try cdlatex TAB completion
6814 ((org-try-cdlatex-tab))
6816 ;; Table: enter it or move to the next field.
6817 ((org-at-table-p 'any)
6818 (if (org-at-table.el-p)
6819 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6820 Use `\\[org-edit-special]' to edit table.el tables"))
6821 (if arg (org-table-edit-field t)
6822 (org-table-justify-field-maybe)
6823 (call-interactively 'org-table-next-field))))
6825 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6827 ;; Global cycling: delegate to `org-cycle-internal-global'.
6828 (bob-special (org-cycle-internal-global))
6830 ;; Drawers: delegate to `org-flag-drawer'.
6831 ((save-excursion
6832 (beginning-of-line 1)
6833 (looking-at org-drawer-regexp))
6834 (org-flag-drawer ; toggle block visibility
6835 (not (get-char-property (match-end 0) 'invisible))))
6837 ;; Show-subtree, ARG levels up from here.
6838 ((integerp arg)
6839 (save-excursion
6840 (org-back-to-heading)
6841 (outline-up-heading (if (< arg 0) (- arg)
6842 (- (funcall outline-level) arg)))
6843 (org-show-subtree)))
6845 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6846 ((and (featurep 'org-inlinetask)
6847 (org-inlinetask-at-task-p)
6848 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6849 (org-inlinetask-toggle-visibility))
6851 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6852 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6853 (save-excursion (move-beginning-of-line 1)
6854 (looking-at org-outline-regexp)))
6855 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6856 (org-cycle-internal-local))
6858 ;; From there: TAB emulation and template completion.
6859 (buffer-read-only (org-back-to-heading))
6861 ((run-hook-with-args-until-success
6862 'org-tab-after-check-for-cycling-hook))
6864 ((org-try-structure-completion))
6866 ((run-hook-with-args-until-success
6867 'org-tab-before-tab-emulation-hook))
6869 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6870 (or (not (bolp))
6871 (not (looking-at org-outline-regexp))))
6872 (call-interactively (global-key-binding "\t")))
6874 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6875 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6876 (or (and (eq org-cycle-emulate-tab 'white)
6877 (= (match-end 0) (point-at-eol)))
6878 (and (eq org-cycle-emulate-tab 'whitestart)
6879 (>= (match-end 0) pos))))
6881 (eq org-cycle-emulate-tab t))
6882 (call-interactively (global-key-binding "\t")))
6884 (t (save-excursion
6885 (org-back-to-heading)
6886 (org-cycle)))))))
6888 (defun org-cycle-internal-global ()
6889 "Do the global cycling action."
6890 ;; Hack to avoid display of messages for .org attachments in Gnus
6891 (let ((ga (string-match "\\*fontification" (buffer-name))))
6892 (cond
6893 ((and (eq last-command this-command)
6894 (eq org-cycle-global-status 'overview))
6895 ;; We just created the overview - now do table of contents
6896 ;; This can be slow in very large buffers, so indicate action
6897 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6898 (unless ga (org-unlogged-message "CONTENTS..."))
6899 (org-content)
6900 (unless ga (org-unlogged-message "CONTENTS...done"))
6901 (setq org-cycle-global-status 'contents)
6902 (run-hook-with-args 'org-cycle-hook 'contents))
6904 ((and (eq last-command this-command)
6905 (eq org-cycle-global-status 'contents))
6906 ;; We just showed the table of contents - now show everything
6907 (run-hook-with-args 'org-pre-cycle-hook 'all)
6908 (outline-show-all)
6909 (unless ga (org-unlogged-message "SHOW ALL"))
6910 (setq org-cycle-global-status 'all)
6911 (run-hook-with-args 'org-cycle-hook 'all))
6914 ;; Default action: go to overview
6915 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6916 (org-overview)
6917 (unless ga (org-unlogged-message "OVERVIEW"))
6918 (setq org-cycle-global-status 'overview)
6919 (run-hook-with-args 'org-cycle-hook 'overview)))))
6921 (defvar org-called-with-limited-levels nil
6922 "Non-nil when `org-with-limited-levels' is currently active.")
6924 (defun org-cycle-internal-local ()
6925 "Do the local cycling action."
6926 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6927 ;; First, determine end of headline (EOH), end of subtree or item
6928 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6929 (save-excursion
6930 (if (org-at-item-p)
6931 (progn
6932 (beginning-of-line)
6933 (setq struct (org-list-struct))
6934 (setq eoh (point-at-eol))
6935 (setq eos (org-list-get-item-end-before-blank (point) struct))
6936 (setq has-children (org-list-has-child-p (point) struct)))
6937 (org-back-to-heading)
6938 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6939 (setq eos (save-excursion (org-end-of-subtree t t)
6940 (when (bolp) (backward-char)) (point)))
6941 (setq has-children
6942 (or (save-excursion
6943 (let ((level (funcall outline-level)))
6944 (outline-next-heading)
6945 (and (org-at-heading-p t)
6946 (> (funcall outline-level) level))))
6947 (save-excursion
6948 (org-list-search-forward (org-item-beginning-re) eos t)))))
6949 ;; Determine end invisible part of buffer (EOL)
6950 (beginning-of-line 2)
6951 (while (and (not (eobp)) ;This is like `next-line'.
6952 (get-char-property (1- (point)) 'invisible))
6953 (goto-char (next-single-char-property-change (point) 'invisible))
6954 (and (eolp) (beginning-of-line 2)))
6955 (setq eol (point)))
6956 ;; Find out what to do next and set `this-command'
6957 (cond
6958 ((= eos eoh)
6959 ;; Nothing is hidden behind this heading
6960 (unless (org-before-first-heading-p)
6961 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6962 (org-unlogged-message "EMPTY ENTRY")
6963 (setq org-cycle-subtree-status nil)
6964 (save-excursion
6965 (goto-char eos)
6966 (outline-next-heading)
6967 (when (outline-invisible-p) (org-flag-heading nil))))
6968 ((and (or (>= eol eos)
6969 (not (string-match "\\S-" (buffer-substring eol eos))))
6970 (or has-children
6971 (not (setq children-skipped
6972 org-cycle-skip-children-state-if-no-children))))
6973 ;; Entire subtree is hidden in one line: children view
6974 (unless (org-before-first-heading-p)
6975 (run-hook-with-args 'org-pre-cycle-hook 'children))
6976 (if (org-at-item-p)
6977 (org-list-set-item-visibility (point-at-bol) struct 'children)
6978 (org-show-entry)
6979 (org-with-limited-levels (org-show-children))
6980 ;; FIXME: This slows down the func way too much.
6981 ;; How keep drawers hidden in subtree anyway?
6982 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6983 ;; (org-cycle-hide-drawers 'subtree))
6985 ;; Fold every list in subtree to top-level items.
6986 (when (eq org-cycle-include-plain-lists 'integrate)
6987 (save-excursion
6988 (org-back-to-heading)
6989 (while (org-list-search-forward (org-item-beginning-re) eos t)
6990 (beginning-of-line 1)
6991 (let* ((struct (org-list-struct))
6992 (prevs (org-list-prevs-alist struct))
6993 (end (org-list-get-bottom-point struct)))
6994 (dolist (e (org-list-get-all-items (point) struct prevs))
6995 (org-list-set-item-visibility e struct 'folded))
6996 (goto-char (if (< end eos) end eos)))))))
6997 (org-unlogged-message "CHILDREN")
6998 (save-excursion
6999 (goto-char eos)
7000 (outline-next-heading)
7001 (when (outline-invisible-p) (org-flag-heading nil)))
7002 (setq org-cycle-subtree-status 'children)
7003 (unless (org-before-first-heading-p)
7004 (run-hook-with-args 'org-cycle-hook 'children)))
7005 ((or children-skipped
7006 (and (eq last-command this-command)
7007 (eq org-cycle-subtree-status 'children)))
7008 ;; We just showed the children, or no children are there,
7009 ;; now show everything.
7010 (unless (org-before-first-heading-p)
7011 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7012 (outline-flag-region eoh eos nil)
7013 (org-unlogged-message
7014 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7015 (setq org-cycle-subtree-status 'subtree)
7016 (unless (org-before-first-heading-p)
7017 (run-hook-with-args 'org-cycle-hook 'subtree)))
7019 ;; Default action: hide the subtree.
7020 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7021 (outline-flag-region eoh eos t)
7022 (org-unlogged-message "FOLDED")
7023 (setq org-cycle-subtree-status 'folded)
7024 (unless (org-before-first-heading-p)
7025 (run-hook-with-args 'org-cycle-hook 'folded))))))
7027 ;;;###autoload
7028 (defun org-global-cycle (&optional arg)
7029 "Cycle the global visibility. For details see `org-cycle'.
7030 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7031 With a numeric prefix, show all headlines up to that level."
7032 (interactive "P")
7033 (let ((org-cycle-include-plain-lists
7034 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7035 (cond
7036 ((integerp arg)
7037 (outline-show-all)
7038 (outline-hide-sublevels arg)
7039 (setq org-cycle-global-status 'contents))
7040 ((equal arg '(4))
7041 (org-set-startup-visibility)
7042 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7044 (org-cycle '(4))))))
7046 (defun org-set-startup-visibility ()
7047 "Set the visibility required by startup options and properties."
7048 (cond
7049 ((eq org-startup-folded t)
7050 (org-overview))
7051 ((eq org-startup-folded 'content)
7052 (org-content))
7053 ((or (eq org-startup-folded 'showeverything)
7054 (eq org-startup-folded nil))
7055 (outline-show-all)))
7056 (unless (eq org-startup-folded 'showeverything)
7057 (when org-hide-block-startup (org-hide-block-all))
7058 (org-set-visibility-according-to-property 'no-cleanup)
7059 (org-cycle-hide-archived-subtrees 'all)
7060 (org-cycle-hide-drawers 'all)
7061 (org-cycle-show-empty-lines t)))
7063 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7064 "Switch subtree visibilities according to :VISIBILITY: property."
7065 (interactive)
7066 (org-with-wide-buffer
7067 (goto-char (point-min))
7068 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7069 (if (not (org-at-property-p)) (outline-next-heading)
7070 (let ((state (match-string 3)))
7071 (save-excursion
7072 (org-back-to-heading t)
7073 (outline-hide-subtree)
7074 (org-reveal)
7075 (cond
7076 ((equal state "folded")
7077 (outline-hide-subtree))
7078 ((equal state "children")
7079 (org-show-hidden-entry)
7080 (org-show-children))
7081 ((equal state "content")
7082 (save-excursion
7083 (save-restriction
7084 (org-narrow-to-subtree)
7085 (org-content))))
7086 ((member state '("all" "showall"))
7087 (outline-show-subtree)))))))
7088 (unless no-cleanup
7089 (org-cycle-hide-archived-subtrees 'all)
7090 (org-cycle-hide-drawers 'all)
7091 (org-cycle-show-empty-lines 'all))))
7093 ;; This function uses outline-regexp instead of the more fundamental
7094 ;; org-outline-regexp so that org-cycle-global works outside of Org
7095 ;; buffers, where outline-regexp is needed.
7096 (defun org-overview ()
7097 "Switch to overview mode, showing only top-level headlines.
7098 This shows all headlines with a level equal or greater than the level
7099 of the first headline in the buffer. This is important, because if the
7100 first headline is not level one, then (hide-sublevels 1) gives confusing
7101 results."
7102 (interactive)
7103 (save-excursion
7104 (let ((level
7105 (save-excursion
7106 (goto-char (point-min))
7107 (when (re-search-forward (concat "^" outline-regexp) nil t)
7108 (goto-char (match-beginning 0))
7109 (funcall outline-level)))))
7110 (and level (outline-hide-sublevels level)))))
7112 (defun org-content (&optional arg)
7113 "Show all headlines in the buffer, like a table of contents.
7114 With numerical argument N, show content up to level N."
7115 (interactive "P")
7116 (org-overview)
7117 (save-excursion
7118 ;; Visit all headings and show their offspring
7119 (and (integerp arg) (org-overview))
7120 (goto-char (point-max))
7121 (catch 'exit
7122 (while (and (progn (condition-case nil
7123 (outline-previous-visible-heading 1)
7124 (error (goto-char (point-min))))
7126 (looking-at org-outline-regexp))
7127 (if (integerp arg)
7128 (org-show-children (1- arg))
7129 (outline-show-branches))
7130 (when (bobp) (throw 'exit nil))))))
7132 (defun org-optimize-window-after-visibility-change (state)
7133 "Adjust the window after a change in outline visibility.
7134 This function is the default value of the hook `org-cycle-hook'."
7135 (when (get-buffer-window (current-buffer))
7136 (cond
7137 ((eq state 'content) nil)
7138 ((eq state 'all) nil)
7139 ((eq state 'folded) nil)
7140 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7141 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7143 (defun org-remove-empty-overlays-at (pos)
7144 "Remove outline overlays that do not contain non-white stuff."
7145 (dolist (o (overlays-at pos))
7146 (and (eq 'outline (overlay-get o 'invisible))
7147 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7148 (overlay-end o))))
7149 (delete-overlay o))))
7151 (defun org-clean-visibility-after-subtree-move ()
7152 "Fix visibility issues after moving a subtree."
7153 ;; First, find a reasonable region to look at:
7154 ;; Start two siblings above, end three below
7155 (let* ((beg (save-excursion
7156 (and (org-get-last-sibling)
7157 (org-get-last-sibling))
7158 (point)))
7159 (end (save-excursion
7160 (and (org-get-next-sibling)
7161 (org-get-next-sibling)
7162 (org-get-next-sibling))
7163 (if (org-at-heading-p)
7164 (point-at-eol)
7165 (point))))
7166 (level (looking-at "\\*+"))
7167 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7168 (save-excursion
7169 (save-restriction
7170 (narrow-to-region beg end)
7171 (when re
7172 ;; Properly fold already folded siblings
7173 (goto-char (point-min))
7174 (while (re-search-forward re nil t)
7175 (when (and (not (outline-invisible-p))
7176 (save-excursion
7177 (goto-char (point-at-eol)) (outline-invisible-p)))
7178 (outline-hide-entry))))
7179 (org-cycle-show-empty-lines 'overview)
7180 (org-cycle-hide-drawers 'overview)))))
7182 (defun org-cycle-show-empty-lines (state)
7183 "Show empty lines above all visible headlines.
7184 The region to be covered depends on STATE when called through
7185 `org-cycle-hook'. Lisp program can use t for STATE to get the
7186 entire buffer covered. Note that an empty line is only shown if there
7187 are at least `org-cycle-separator-lines' empty lines before the headline."
7188 (when (/= org-cycle-separator-lines 0)
7189 (save-excursion
7190 (let* ((n (abs org-cycle-separator-lines))
7191 (re (cond
7192 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7193 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7194 (t (let ((ns (number-to-string (- n 2))))
7195 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7196 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7197 beg end)
7198 (cond
7199 ((memq state '(overview contents t))
7200 (setq beg (point-min) end (point-max)))
7201 ((memq state '(children folded))
7202 (setq beg (point)
7203 end (progn (org-end-of-subtree t t)
7204 (line-beginning-position 2)))))
7205 (when beg
7206 (goto-char beg)
7207 (while (re-search-forward re end t)
7208 (unless (get-char-property (match-end 1) 'invisible)
7209 (let ((e (match-end 1))
7210 (b (if (>= org-cycle-separator-lines 0)
7211 (match-beginning 1)
7212 (save-excursion
7213 (goto-char (match-beginning 0))
7214 (skip-chars-backward " \t\n")
7215 (line-end-position)))))
7216 (outline-flag-region b e nil))))))))
7217 ;; Never hide empty lines at the end of the file.
7218 (save-excursion
7219 (goto-char (point-max))
7220 (outline-previous-heading)
7221 (outline-end-of-heading)
7222 (when (and (looking-at "[ \t\n]+")
7223 (= (match-end 0) (point-max)))
7224 (outline-flag-region (point) (match-end 0) nil))))
7226 (defun org-show-empty-lines-in-parent ()
7227 "Move to the parent and re-show empty lines before visible headlines."
7228 (save-excursion
7229 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7230 (org-cycle-show-empty-lines context))))
7232 (defun org-files-list ()
7233 "Return `org-agenda-files' list, plus all open Org files.
7234 This is useful for operations that need to scan all of a user's
7235 open and agenda-wise Org files."
7236 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7237 (dolist (buf (buffer-list))
7238 (with-current-buffer buf
7239 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7240 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7241 files))
7243 (defsubst org-entry-beginning-position ()
7244 "Return the beginning position of the current entry."
7245 (save-excursion (org-back-to-heading t) (point)))
7247 (defsubst org-entry-end-position ()
7248 "Return the end position of the current entry."
7249 (save-excursion (outline-next-heading) (point)))
7251 (defun org-cycle-hide-drawers (state &optional exceptions)
7252 "Re-hide all drawers after a visibility state change.
7253 When non-nil, optional argument EXCEPTIONS is a list of strings
7254 specifying which drawers should not be hidden."
7255 (when (and (derived-mode-p 'org-mode)
7256 (not (memq state '(overview folded contents))))
7257 (save-excursion
7258 (let* ((globalp (memq state '(contents all)))
7259 (beg (if globalp (point-min) (point)))
7260 (end (if globalp (point-max)
7261 (if (eq state 'children)
7262 (save-excursion (outline-next-heading) (point))
7263 (org-end-of-subtree t)))))
7264 (goto-char beg)
7265 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7266 (unless (member-ignore-case (match-string 1) exceptions)
7267 (let ((drawer (org-element-at-point)))
7268 (when (memq (org-element-type drawer) '(drawer property-drawer))
7269 (org-flag-drawer t drawer)
7270 ;; Make sure to skip drawer entirely or we might flag
7271 ;; it another time when matching its ending line with
7272 ;; `org-drawer-regexp'.
7273 (goto-char (org-element-property :end drawer))))))))))
7275 (defun org-flag-drawer (flag &optional element)
7276 "When FLAG is non-nil, hide the drawer we are at.
7277 Otherwise make it visible. When optional argument ELEMENT is
7278 a parsed drawer, as returned by `org-element-at-point', hide or
7279 show that drawer instead."
7280 (let ((drawer (or element
7281 (and (save-excursion
7282 (beginning-of-line)
7283 (looking-at-p org-drawer-regexp))
7284 (org-element-at-point)))))
7285 (when (memq (org-element-type drawer) '(drawer property-drawer))
7286 (let ((post (org-element-property :post-affiliated drawer)))
7287 (save-excursion
7288 (outline-flag-region
7289 (progn (goto-char post) (line-end-position))
7290 (progn (goto-char (org-element-property :end drawer))
7291 (skip-chars-backward " \r\t\n")
7292 (line-end-position))
7293 flag))
7294 ;; When the drawer is hidden away, make sure point lies in
7295 ;; a visible part of the buffer.
7296 (when (and flag (> (line-beginning-position) post))
7297 (goto-char post))))))
7299 (defun org-subtree-end-visible-p ()
7300 "Is the end of the current subtree visible?"
7301 (pos-visible-in-window-p
7302 (save-excursion (org-end-of-subtree t) (point))))
7304 (defun org-first-headline-recenter ()
7305 "Move cursor to the first headline and recenter the headline."
7306 (let ((window (get-buffer-window)))
7307 (when window
7308 (goto-char (point-min))
7309 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7310 (set-window-start window (line-beginning-position))))))
7312 ;;; Saving and restoring visibility
7314 (defun org-outline-overlay-data (&optional use-markers)
7315 "Return a list of the locations of all outline overlays.
7316 These are overlays with the `invisible' property value `outline'.
7317 The return value is a list of cons cells, with start and stop
7318 positions for each overlay.
7319 If USE-MARKERS is set, return the positions as markers."
7320 (let (beg end)
7321 (org-with-wide-buffer
7322 (delq nil
7323 (mapcar (lambda (o)
7324 (when (eq (overlay-get o 'invisible) 'outline)
7325 (setq beg (overlay-start o)
7326 end (overlay-end o))
7327 (and beg end (> end beg)
7328 (if use-markers
7329 (cons (copy-marker beg)
7330 (copy-marker end t))
7331 (cons beg end)))))
7332 (overlays-in (point-min) (point-max)))))))
7334 (defun org-set-outline-overlay-data (data)
7335 "Create visibility overlays for all positions in DATA.
7336 DATA should have been made by `org-outline-overlay-data'."
7337 (org-with-wide-buffer
7338 (outline-show-all)
7339 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7341 ;;; Folding of blocks
7343 (defvar-local org-hide-block-overlays nil
7344 "Overlays hiding blocks.")
7346 (defun org-block-map (function &optional start end)
7347 "Call FUNCTION at the head of all source blocks in the current buffer.
7348 Optional arguments START and END can be used to limit the range."
7349 (let ((start (or start (point-min)))
7350 (end (or end (point-max))))
7351 (save-excursion
7352 (goto-char start)
7353 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7354 (save-excursion
7355 (save-match-data
7356 (goto-char (match-beginning 0))
7357 (funcall function)))))))
7359 (defun org-hide-block-toggle-all ()
7360 "Toggle the visibility of all blocks in the current buffer."
7361 (org-block-map 'org-hide-block-toggle))
7363 (defun org-hide-block-all ()
7364 "Fold all blocks in the current buffer."
7365 (interactive)
7366 (org-show-block-all)
7367 (org-block-map 'org-hide-block-toggle-maybe))
7369 (defun org-show-block-all ()
7370 "Unfold all blocks in the current buffer."
7371 (interactive)
7372 (mapc #'delete-overlay org-hide-block-overlays)
7373 (setq org-hide-block-overlays nil))
7375 (defun org-hide-block-toggle-maybe ()
7376 "Toggle visibility of block at point.
7377 Unlike to `org-hide-block-toggle', this function does not throw
7378 an error. Return a non-nil value when toggling is successful."
7379 (interactive)
7380 (ignore-errors (org-hide-block-toggle)))
7382 (defun org-hide-block-toggle (&optional force)
7383 "Toggle the visibility of the current block.
7384 When optional argument FORCE is `off', make block visible. If it
7385 is non-nil, hide it unconditionally. Throw an error when not at
7386 a block. Return a non-nil value when toggling is successful."
7387 (interactive)
7388 (let ((element (org-element-at-point)))
7389 (unless (memq (org-element-type element)
7390 '(center-block comment-block dynamic-block example-block
7391 export-block quote-block special-block
7392 src-block verse-block))
7393 (user-error "Not at a block"))
7394 (let* ((start (save-excursion
7395 (goto-char (org-element-property :post-affiliated element))
7396 (line-end-position)))
7397 (end (save-excursion
7398 (goto-char (org-element-property :end element))
7399 (skip-chars-backward " \r\t\n")
7400 (line-end-position)))
7401 (overlays (overlays-at start)))
7402 (cond
7403 ;; Do nothing when not before or at the block opening line or
7404 ;; at the block closing line.
7405 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7406 ((and (not (eq force 'off))
7407 (not (memq t (mapcar
7408 (lambda (o)
7409 (eq (overlay-get o 'invisible) 'org-hide-block))
7410 overlays))))
7411 (let ((ov (make-overlay start end)))
7412 (overlay-put ov 'invisible 'org-hide-block)
7413 ;; Make the block accessible to `isearch'.
7414 (overlay-put
7415 ov 'isearch-open-invisible
7416 (lambda (ov)
7417 (when (memq ov org-hide-block-overlays)
7418 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7419 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7420 (delete-overlay ov))))
7421 (push ov org-hide-block-overlays)
7422 ;; When the block is hidden away, make sure point is left in
7423 ;; a visible part of the buffer.
7424 (when (> (line-beginning-position) start)
7425 (goto-char start)
7426 (beginning-of-line))
7427 ;; Signal successful toggling.
7429 ((or (not force) (eq force 'off))
7430 (dolist (ov overlays t)
7431 (when (memq ov org-hide-block-overlays)
7432 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7433 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7434 (delete-overlay ov))))))))
7436 ;; Remove overlays when changing major mode
7437 (add-hook 'org-mode-hook
7438 (lambda () (add-hook 'change-major-mode-hook
7439 'org-show-block-all 'append 'local)))
7441 ;;; Org-goto
7443 (defvar org-goto-window-configuration nil)
7444 (defvar org-goto-marker nil)
7445 (defvar org-goto-map)
7446 (defun org-goto-map ()
7447 "Set the keymap `org-goto'."
7448 (setq org-goto-map
7449 (let ((map (make-sparse-keymap)))
7450 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7451 mouse-drag-region universal-argument org-occur)))
7452 (dolist (cmd cmds)
7453 (substitute-key-definition cmd cmd map global-map)))
7454 (suppress-keymap map)
7455 (org-defkey map "\C-m" 'org-goto-ret)
7456 (org-defkey map [(return)] 'org-goto-ret)
7457 (org-defkey map [(left)] 'org-goto-left)
7458 (org-defkey map [(right)] 'org-goto-right)
7459 (org-defkey map [(control ?g)] 'org-goto-quit)
7460 (org-defkey map "\C-i" 'org-cycle)
7461 (org-defkey map [(tab)] 'org-cycle)
7462 (org-defkey map [(down)] 'outline-next-visible-heading)
7463 (org-defkey map [(up)] 'outline-previous-visible-heading)
7464 (if org-goto-auto-isearch
7465 (if (fboundp 'define-key-after)
7466 (define-key-after map [t] 'org-goto-local-auto-isearch)
7467 nil)
7468 (org-defkey map "q" 'org-goto-quit)
7469 (org-defkey map "n" 'outline-next-visible-heading)
7470 (org-defkey map "p" 'outline-previous-visible-heading)
7471 (org-defkey map "f" 'outline-forward-same-level)
7472 (org-defkey map "b" 'outline-backward-same-level)
7473 (org-defkey map "u" 'outline-up-heading))
7474 (org-defkey map "/" 'org-occur)
7475 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7476 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7477 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7478 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7479 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7480 map)))
7482 (defconst org-goto-help
7483 "Browse buffer copy, to find location or copy text.%s
7484 RET=jump to location C-g=quit and return to previous location
7485 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7487 (defvar org-goto-start-pos) ; dynamically scoped parameter
7489 (defun org-goto (&optional alternative-interface)
7490 "Look up a different location in the current file, keeping current visibility.
7492 When you want look-up or go to a different location in a
7493 document, the fastest way is often to fold the entire buffer and
7494 then dive into the tree. This method has the disadvantage, that
7495 the previous location will be folded, which may not be what you
7496 want.
7498 This command works around this by showing a copy of the current
7499 buffer in an indirect buffer, in overview mode. You can dive
7500 into the tree in that copy, use org-occur and incremental search
7501 to find a location. When pressing RET or `Q', the command
7502 returns to the original buffer in which the visibility is still
7503 unchanged. After RET it will also jump to the location selected
7504 in the indirect buffer and expose the headline hierarchy above.
7506 With a prefix argument, use the alternative interface: e.g., if
7507 `org-goto-interface' is `outline' use `outline-path-completion'."
7508 (interactive "P")
7509 (org-goto-map)
7510 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7511 (org-refile-use-outline-path t)
7512 (org-refile-target-verify-function nil)
7513 (interface
7514 (if (not alternative-interface)
7515 org-goto-interface
7516 (if (eq org-goto-interface 'outline)
7517 'outline-path-completion
7518 'outline)))
7519 (org-goto-start-pos (point))
7520 (selected-point
7521 (if (eq interface 'outline)
7522 (car (org-get-location (current-buffer) org-goto-help))
7523 (let ((pa (org-refile-get-location "Goto")))
7524 (org-refile-check-position pa)
7525 (nth 3 pa)))))
7526 (if selected-point
7527 (progn
7528 (org-mark-ring-push org-goto-start-pos)
7529 (goto-char selected-point)
7530 (when (or (outline-invisible-p) (org-invisible-p2))
7531 (org-show-context 'org-goto)))
7532 (message "Quit"))))
7534 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7535 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7536 (defvar org-goto-local-auto-isearch-map) ; defined below
7538 (defun org-get-location (_buf help)
7539 "Let the user select a location in current buffer.
7540 This function uses a recursive edit. It returns the selected position
7541 or nil."
7542 (org-no-popups
7543 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7544 (isearch-hide-immediately nil)
7545 (isearch-search-fun-function
7546 (lambda () 'org-goto-local-search-headings))
7547 (org-goto-selected-point org-goto-exit-command))
7548 (save-excursion
7549 (save-window-excursion
7550 (delete-other-windows)
7551 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7552 (pop-to-buffer-same-window
7553 (condition-case nil
7554 (make-indirect-buffer (current-buffer) "*org-goto*")
7555 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7556 (with-output-to-temp-buffer "*Org Help*"
7557 (princ (format help (if org-goto-auto-isearch
7558 " Just type for auto-isearch."
7559 " n/p/f/b/u to navigate, q to quit."))))
7560 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7561 (setq buffer-read-only nil)
7562 (let ((org-startup-truncated t)
7563 (org-startup-folded nil)
7564 (org-startup-align-all-tables nil))
7565 (org-mode)
7566 (org-overview))
7567 (setq buffer-read-only t)
7568 (if (and (boundp 'org-goto-start-pos)
7569 (integer-or-marker-p org-goto-start-pos))
7570 (progn (goto-char org-goto-start-pos)
7571 (when (outline-invisible-p)
7572 (org-show-set-visibility 'lineage)))
7573 (goto-char (point-min)))
7574 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7575 (message "Select location and press RET")
7576 (use-local-map org-goto-map)
7577 (recursive-edit)))
7578 (kill-buffer "*org-goto*")
7579 (cons org-goto-selected-point org-goto-exit-command))))
7581 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7582 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7583 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7584 (if (fboundp 'isearch-other-control-char)
7585 (progn
7586 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7587 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7588 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7589 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7590 (define-key org-goto-local-auto-isearch-map [return] nil))
7592 (defun org-goto-local-search-headings (string bound noerror)
7593 "Search and make sure that any matches are in headlines."
7594 (catch 'return
7595 (while (if isearch-forward
7596 (search-forward string bound noerror)
7597 (search-backward string bound noerror))
7598 (when (save-match-data
7599 (and (save-excursion
7600 (beginning-of-line)
7601 (looking-at org-complex-heading-regexp))
7602 (or (not (match-beginning 5))
7603 (< (point) (match-beginning 5)))))
7604 (throw 'return (point))))))
7606 (defun org-goto-local-auto-isearch ()
7607 "Start isearch."
7608 (interactive)
7609 (goto-char (point-min))
7610 (let ((keys (this-command-keys)))
7611 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7612 (isearch-mode t)
7613 (isearch-process-search-char (string-to-char keys)))))
7615 (defun org-goto-ret (&optional _arg)
7616 "Finish `org-goto' by going to the new location."
7617 (interactive "P")
7618 (setq org-goto-selected-point (point))
7619 (setq org-goto-exit-command 'return)
7620 (throw 'exit nil))
7622 (defun org-goto-left ()
7623 "Finish `org-goto' by going to the new location."
7624 (interactive)
7625 (if (org-at-heading-p)
7626 (progn
7627 (beginning-of-line 1)
7628 (setq org-goto-selected-point (point)
7629 org-goto-exit-command 'left)
7630 (throw 'exit nil))
7631 (user-error "Not on a heading")))
7633 (defun org-goto-right ()
7634 "Finish `org-goto' by going to the new location."
7635 (interactive)
7636 (if (org-at-heading-p)
7637 (progn
7638 (setq org-goto-selected-point (point)
7639 org-goto-exit-command 'right)
7640 (throw 'exit nil))
7641 (user-error "Not on a heading")))
7643 (defun org-goto-quit ()
7644 "Finish `org-goto' without cursor motion."
7645 (interactive)
7646 (setq org-goto-selected-point nil)
7647 (setq org-goto-exit-command 'quit)
7648 (throw 'exit nil))
7650 ;;; Indirect buffer display of subtrees
7652 (defvar org-indirect-dedicated-frame nil
7653 "This is the frame being used for indirect tree display.")
7654 (defvar org-last-indirect-buffer nil)
7656 (defun org-tree-to-indirect-buffer (&optional arg)
7657 "Create indirect buffer and narrow it to current subtree.
7659 With a numerical prefix ARG, go up to this level and then take that tree.
7660 If ARG is negative, go up that many levels.
7662 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7663 indirect buffer previously made with this command, to avoid proliferation of
7664 indirect buffers. However, when you call the command with a \
7665 `\\[universal-argument]' prefix, or
7666 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7667 so that you can work with several indirect buffers at the same time. If
7668 `org-indirect-buffer-display' is `dedicated-frame', the \
7669 `\\[universal-argument]' prefix also
7670 requests that a new frame be made for the new buffer, so that the dedicated
7671 frame is not changed."
7672 (interactive "P")
7673 (let ((cbuf (current-buffer))
7674 (cwin (selected-window))
7675 (pos (point))
7676 beg end level heading ibuf)
7677 (save-excursion
7678 (org-back-to-heading t)
7679 (when (numberp arg)
7680 (setq level (org-outline-level))
7681 (when (< arg 0) (setq arg (+ level arg)))
7682 (while (> (setq level (org-outline-level)) arg)
7683 (org-up-heading-safe)))
7684 (setq beg (point)
7685 heading (org-get-heading 'no-tags))
7686 (org-end-of-subtree t t)
7687 (when (org-at-heading-p) (backward-char 1))
7688 (setq end (point)))
7689 (when (and (buffer-live-p org-last-indirect-buffer)
7690 (not (eq org-indirect-buffer-display 'new-frame))
7691 (not arg))
7692 (kill-buffer org-last-indirect-buffer))
7693 (setq ibuf (org-get-indirect-buffer cbuf heading)
7694 org-last-indirect-buffer ibuf)
7695 (cond
7696 ((or (eq org-indirect-buffer-display 'new-frame)
7697 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7698 (select-frame (make-frame))
7699 (delete-other-windows)
7700 (pop-to-buffer-same-window ibuf)
7701 (org-set-frame-title heading))
7702 ((eq org-indirect-buffer-display 'dedicated-frame)
7703 (raise-frame
7704 (select-frame (or (and org-indirect-dedicated-frame
7705 (frame-live-p org-indirect-dedicated-frame)
7706 org-indirect-dedicated-frame)
7707 (setq org-indirect-dedicated-frame (make-frame)))))
7708 (delete-other-windows)
7709 (pop-to-buffer-same-window ibuf)
7710 (org-set-frame-title (concat "Indirect: " heading)))
7711 ((eq org-indirect-buffer-display 'current-window)
7712 (pop-to-buffer-same-window ibuf))
7713 ((eq org-indirect-buffer-display 'other-window)
7714 (pop-to-buffer ibuf))
7715 (t (error "Invalid value")))
7716 (narrow-to-region beg end)
7717 (outline-show-all)
7718 (goto-char pos)
7719 (run-hook-with-args 'org-cycle-hook 'all)
7720 (and (window-live-p cwin) (select-window cwin))))
7722 (defun org-get-indirect-buffer (&optional buffer heading)
7723 (setq buffer (or buffer (current-buffer)))
7724 (let ((n 1) (base (buffer-name buffer)) bname)
7725 (while (buffer-live-p
7726 (get-buffer
7727 (setq bname
7728 (concat base "-"
7729 (if heading (concat heading "-" (number-to-string n))
7730 (number-to-string n))))))
7731 (setq n (1+ n)))
7732 (condition-case nil
7733 (make-indirect-buffer buffer bname 'clone)
7734 (error (make-indirect-buffer buffer bname)))))
7736 (defun org-set-frame-title (title)
7737 "Set the title of the current frame to the string TITLE."
7738 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7740 ;;;; Structure editing
7742 ;;; Inserting headlines
7744 (defun org--line-empty-p (n)
7745 "Is the Nth next line empty?
7747 Counts the current line as N = 1 and the previous line as N = 0;
7748 see `beginning-of-line'."
7749 (save-excursion
7750 (and (not (bobp))
7751 (or (beginning-of-line n) t)
7752 (save-match-data
7753 (looking-at "[ \t]*$")))))
7755 (defun org-previous-line-empty-p ()
7756 "Is the previous line a blank line?
7757 When NEXT is non-nil, check the next line instead."
7758 (org--line-empty-p 0))
7760 (defun org-next-line-empty-p ()
7761 "Is the previous line a blank line?
7762 When NEXT is non-nil, check the next line instead."
7763 (org--line-empty-p 2))
7765 (defun org--blank-before-heading-p (&optional parent)
7766 "Non-nil when an empty line should precede a new heading here.
7767 When optional argument PARENT is non-nil, consider parent
7768 headline instead of current one."
7769 (pcase (assq 'heading org-blank-before-new-entry)
7770 (`(heading . auto)
7771 (save-excursion
7772 (org-with-limited-levels
7773 (unless (and (org-before-first-heading-p)
7774 (not (outline-next-heading)))
7775 (org-back-to-heading t)
7776 (when parent (org-up-heading-safe))
7777 (cond ((not (bobp))
7778 (org-previous-line-empty-p))
7779 ((outline-next-heading)
7780 (org-previous-line-empty-p))
7781 ;; Ignore trailing spaces on last buffer line.
7782 ((progn (skip-chars-backward " \t") (bolp))
7783 (org-previous-line-empty-p))
7784 (t nil))))))
7785 (`(heading . ,value) value)
7786 (_ nil)))
7788 (defun org-insert-heading (&optional arg invisible-ok top)
7789 "Insert a new heading or an item with the same depth at point.
7791 If point is at the beginning of a heading, insert a new heading
7792 or a new headline above the current one. When at the beginning
7793 of a regular line of text, turn it into a heading.
7795 If point is in the middle of a line, split it and create a new
7796 headline with the text in the current line after point (see
7797 `org-M-RET-may-split-line' on how to modify this behavior). As
7798 a special case, on a headline, splitting can only happen on the
7799 title itself. E.g., this excludes breaking stars or tags.
7801 With a `\\[universal-argument]' prefix, set \
7802 `org-insert-heading-respect-content' to
7803 a non-nil value for the duration of the command. This forces the
7804 insertion of a heading after the current subtree, independently
7805 on the location of point.
7807 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7808 insert the heading at the end of the tree
7809 above the current heading. For example, if point is within a
7810 2nd-level heading, then it will insert a 2nd-level heading at
7811 the end of the 1st-level parent subtree.
7813 When INVISIBLE-OK is set, stop at invisible headlines when going
7814 back. This is important for non-interactive uses of the
7815 command.
7817 When optional argument TOP is non-nil, insert a level 1 heading,
7818 unconditionally."
7819 (interactive "P")
7820 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7821 (level (org-current-level))
7822 (stars (make-string (if (and level (not top)) level 1) ?*)))
7823 (cond
7824 ((or org-insert-heading-respect-content
7825 (member arg '((4) (16)))
7826 (and (not invisible-ok)
7827 (invisible-p (max (1- (point)) (point-min)))))
7828 ;; Position point at the location of insertion.
7829 (if (not level) ;before first headline
7830 (org-with-limited-levels (outline-next-heading))
7831 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7832 ;; is nil.
7833 (org-with-limited-levels (org-back-to-heading invisible-ok))
7834 (cond ((equal arg '(16))
7835 (org-up-heading-safe)
7836 (org-end-of-subtree t t))
7838 (org-end-of-subtree t t))))
7839 (unless (bolp) (insert "\n")) ;ensure final newline
7840 (unless (and blank? (org-previous-line-empty-p))
7841 (org-N-empty-lines-before-current (if blank? 1 0)))
7842 (insert stars " \n")
7843 (forward-char -1))
7844 ;; At a headline...
7845 ((org-at-heading-p)
7846 (cond ((bolp)
7847 (when blank? (save-excursion (insert "\n")))
7848 (save-excursion (insert stars " \n"))
7849 (unless (and blank? (org-previous-line-empty-p))
7850 (org-N-empty-lines-before-current (if blank? 1 0)))
7851 (end-of-line))
7852 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7853 (org-match-line org-complex-heading-regexp)
7854 (org-pos-in-match-range (point) 4))
7855 ;; Grab the text that should moved to the new headline.
7856 ;; Preserve tags.
7857 (let ((split (delete-and-extract-region (point) (match-end 4))))
7858 (if (looking-at "[ \t]*$") (replace-match "")
7859 (org-set-tags nil t))
7860 (end-of-line)
7861 (when blank? (insert "\n"))
7862 (insert "\n" stars " ")
7863 (when (org-string-nw-p split) (insert split))
7864 (when (eobp) (save-excursion (insert "\n")))))
7866 (end-of-line)
7867 (when blank? (insert "\n"))
7868 (insert "\n" stars " ")
7869 (when (eobp) (save-excursion (insert "\n"))))))
7870 ;; On regular text, turn line into a headline or split, if
7871 ;; appropriate.
7872 ((bolp)
7873 (insert stars " ")
7874 (unless (and blank? (org-previous-line-empty-p))
7875 (org-N-empty-lines-before-current (if blank? 1 0))))
7877 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7878 (end-of-line))
7879 (insert "\n" stars " ")
7880 (unless (and blank? (org-previous-line-empty-p))
7881 (org-N-empty-lines-before-current (if blank? 1 0))))))
7882 (run-hooks 'org-insert-heading-hook))
7884 (defun org-N-empty-lines-before-current (n)
7885 "Make the number of empty lines before current exactly N.
7886 So this will delete or add empty lines."
7887 (let ((column (current-column)))
7888 (beginning-of-line)
7889 (unless (bobp)
7890 (let ((start (save-excursion
7891 (skip-chars-backward " \r\t\n")
7892 (line-end-position))))
7893 (delete-region start (line-end-position 0))))
7894 (insert (make-string n ?\n))
7895 (move-to-column column)))
7897 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7898 "Return the heading of the current entry, without the stars.
7899 When NO-TAGS is non-nil, don't include tags.
7900 When NO-TODO is non-nil, don't include TODO keywords.
7901 When NO-PRIORITY is non-nil, don't include priority cookie.
7902 When NO-COMMENT is non-nil, don't include COMMENT string."
7903 (save-excursion
7904 (org-back-to-heading t)
7905 (let ((case-fold-search nil))
7906 (looking-at org-complex-heading-regexp)
7907 (let ((todo (and (not no-todo) (match-string 2)))
7908 (priority (and (not no-priority) (match-string 3)))
7909 (headline (pcase (match-string 4)
7910 (`nil "")
7911 ((and (guard no-comment) h)
7912 (replace-regexp-in-string
7913 (eval-when-compile
7914 (format "\\`%s[ \t]+" org-comment-string))
7915 "" h))
7916 (h h)))
7917 (tags (and (not no-tags) (match-string 5))))
7918 (mapconcat #'identity
7919 (delq nil (list todo priority headline tags))
7920 " ")))))
7922 (defvar orgstruct-mode) ; defined below
7924 (defun org-heading-components ()
7925 "Return the components of the current heading.
7926 This is a list with the following elements:
7927 - the level as an integer
7928 - the reduced level, different if `org-odd-levels-only' is set.
7929 - the TODO keyword, or nil
7930 - the priority character, like ?A, or nil if no priority is given
7931 - the headline text itself, or the tags string if no headline text
7932 - the tags string, or nil."
7933 (save-excursion
7934 (org-back-to-heading t)
7935 (when (let (case-fold-search)
7936 (looking-at
7937 (if orgstruct-mode
7938 org-heading-regexp
7939 org-complex-heading-regexp)))
7940 (if orgstruct-mode
7941 (list (length (match-string 1))
7942 (org-reduced-level (length (match-string 1)))
7945 (match-string 2)
7946 nil)
7947 (list (length (match-string 1))
7948 (org-reduced-level (length (match-string 1)))
7949 (match-string-no-properties 2)
7950 (and (match-end 3) (aref (match-string 3) 2))
7951 (match-string-no-properties 4)
7952 (match-string-no-properties 5))))))
7954 (defun org-get-entry ()
7955 "Get the entry text, after heading, entire subtree."
7956 (save-excursion
7957 (org-back-to-heading t)
7958 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7960 (defun org-edit-headline (&optional heading)
7961 "Edit the current headline.
7962 Set it to HEADING when provided."
7963 (interactive)
7964 (org-with-wide-buffer
7965 (org-back-to-heading t)
7966 (let ((case-fold-search nil))
7967 (when (looking-at org-complex-heading-regexp)
7968 (let* ((old (match-string-no-properties 4))
7969 (new (save-match-data
7970 (org-trim (or heading (read-string "Edit: " old))))))
7971 (unless (equal old new)
7972 (if old (replace-match new t t nil 4)
7973 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7974 (insert " " new))
7975 (org-set-tags nil t)
7976 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7978 (defun org-insert-heading-after-current ()
7979 "Insert a new heading with same level as current, after current subtree."
7980 (interactive)
7981 (org-back-to-heading)
7982 (org-insert-heading)
7983 (org-move-subtree-down)
7984 (end-of-line 1))
7986 (defun org-insert-heading-respect-content (&optional invisible-ok)
7987 "Insert heading with `org-insert-heading-respect-content' set to t."
7988 (interactive)
7989 (org-insert-heading '(4) invisible-ok))
7991 (defun org-insert-todo-heading-respect-content (&optional force-state)
7992 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7993 (interactive)
7994 (org-insert-todo-heading force-state '(4)))
7996 (defun org-insert-todo-heading (arg &optional force-heading)
7997 "Insert a new heading with the same level and TODO state as current heading.
7999 If the heading has no TODO state, or if the state is DONE, use
8000 the first state (TODO by default). Also with one prefix arg,
8001 force first state. With two prefix args, force inserting at the
8002 end of the parent subtree.
8004 When called at a plain list item, insert a new item with an
8005 unchecked check box."
8006 (interactive "P")
8007 (when (or force-heading (not (org-insert-item 'checkbox)))
8008 (org-insert-heading (or (and (equal arg '(16)) '(16))
8009 force-heading))
8010 (save-excursion
8011 (org-back-to-heading)
8012 (outline-previous-heading)
8013 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
8014 (let* ((new-mark-x
8015 (if (or (equal arg '(4))
8016 (not (match-beginning 2))
8017 (member (match-string 2) org-done-keywords))
8018 (car org-todo-keywords-1)
8019 (match-string 2)))
8020 (new-mark
8022 (run-hook-with-args-until-success
8023 'org-todo-get-default-hook new-mark-x nil)
8024 new-mark-x)))
8025 (beginning-of-line 1)
8026 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8027 (if org-treat-insert-todo-heading-as-state-change
8028 (org-todo new-mark)
8029 (insert new-mark " "))))
8030 (when org-provide-todo-statistics
8031 (org-update-parent-todo-statistics))))
8033 (defun org-insert-subheading (arg)
8034 "Insert a new subheading and demote it.
8035 Works for outline headings and for plain lists alike."
8036 (interactive "P")
8037 (org-insert-heading arg)
8038 (cond
8039 ((org-at-heading-p) (org-do-demote))
8040 ((org-at-item-p) (org-indent-item))))
8042 (defun org-insert-todo-subheading (arg)
8043 "Insert a new subheading with TODO keyword or checkbox and demote it.
8044 Works for outline headings and for plain lists alike."
8045 (interactive "P")
8046 (org-insert-todo-heading arg)
8047 (cond
8048 ((org-at-heading-p) (org-do-demote))
8049 ((org-at-item-p) (org-indent-item))))
8051 ;;; Promotion and Demotion
8053 (defvar org-after-demote-entry-hook nil
8054 "Hook run after an entry has been demoted.
8055 The cursor will be at the beginning of the entry.
8056 When a subtree is being demoted, the hook will be called for each node.")
8058 (defvar org-after-promote-entry-hook nil
8059 "Hook run after an entry has been promoted.
8060 The cursor will be at the beginning of the entry.
8061 When a subtree is being promoted, the hook will be called for each node.")
8063 (defun org-promote-subtree ()
8064 "Promote the entire subtree.
8065 See also `org-promote'."
8066 (interactive)
8067 (save-excursion
8068 (org-with-limited-levels (org-map-tree 'org-promote)))
8069 (org-fix-position-after-promote))
8071 (defun org-demote-subtree ()
8072 "Demote the entire subtree.
8073 See `org-demote' and `org-promote'."
8074 (interactive)
8075 (save-excursion
8076 (org-with-limited-levels (org-map-tree 'org-demote)))
8077 (org-fix-position-after-promote))
8079 (defun org-do-promote ()
8080 "Promote the current heading higher up the tree.
8081 If the region is active in `transient-mark-mode', promote all
8082 headings in the region."
8083 (interactive)
8084 (save-excursion
8085 (if (org-region-active-p)
8086 (org-map-region 'org-promote (region-beginning) (region-end))
8087 (org-promote)))
8088 (org-fix-position-after-promote))
8090 (defun org-do-demote ()
8091 "Demote the current heading lower down the tree.
8092 If the region is active in `transient-mark-mode', demote all
8093 headings in the region."
8094 (interactive)
8095 (save-excursion
8096 (if (org-region-active-p)
8097 (org-map-region 'org-demote (region-beginning) (region-end))
8098 (org-demote)))
8099 (org-fix-position-after-promote))
8101 (defun org-fix-position-after-promote ()
8102 "Fix cursor position and indentation after demoting/promoting."
8103 (let ((pos (point)))
8104 (when (save-excursion
8105 (beginning-of-line)
8106 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8107 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8108 (cond ((eobp) (insert " "))
8109 ((eolp) (insert " "))
8110 ((equal (char-after) ?\s) (forward-char 1))))))
8112 (defun org-current-level ()
8113 "Return the level of the current entry, or nil if before the first headline.
8114 The level is the number of stars at the beginning of the
8115 headline. Use `org-reduced-level' to remove the effect of
8116 `org-odd-levels'. Unlike to `org-outline-level', this function
8117 ignores inlinetasks."
8118 (let ((level (org-with-limited-levels (org-outline-level))))
8119 (and (> level 0) level)))
8121 (defun org-get-previous-line-level ()
8122 "Return the outline depth of the last headline before the current line.
8123 Returns 0 for the first headline in the buffer, and nil if before the
8124 first headline."
8125 (and (org-current-level)
8126 (or (and (/= (line-beginning-position) (point-min))
8127 (save-excursion (beginning-of-line 0) (org-current-level)))
8128 0)))
8130 (defun org-reduced-level (l)
8131 "Compute the effective level of a heading.
8132 This takes into account the setting of `org-odd-levels-only'."
8133 (cond
8134 ((zerop l) 0)
8135 (org-odd-levels-only (1+ (floor (/ l 2))))
8136 (t l)))
8138 (defun org-level-increment ()
8139 "Return the number of stars that will be added or removed at a
8140 time to headlines when structure editing, based on the value of
8141 `org-odd-levels-only'."
8142 (if org-odd-levels-only 2 1))
8144 (defun org-get-valid-level (level &optional change)
8145 "Rectify a level change under the influence of `org-odd-levels-only'.
8146 LEVEL is a current level, CHANGE is by how much the level should
8147 be modified. Even if CHANGE is nil, LEVEL may be returned
8148 modified because even level numbers will become the next higher
8149 odd number. Returns values greater than 0."
8150 (if org-odd-levels-only
8151 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8152 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8153 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8154 (max 1 (+ level (or change 0)))))
8156 (defun org-promote ()
8157 "Promote the current heading higher up the tree."
8158 (org-with-wide-buffer
8159 (org-back-to-heading t)
8160 (let* ((after-change-functions (remq 'flyspell-after-change-function
8161 after-change-functions))
8162 (level (save-match-data (funcall outline-level)))
8163 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8164 (diff (abs (- level (length up-head) -1))))
8165 (cond
8166 ((and (= level 1) org-allow-promoting-top-level-subtree)
8167 (replace-match "# " nil t))
8168 ((= level 1)
8169 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8170 (t (replace-match up-head nil t)))
8171 (unless (= level 1)
8172 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8173 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8174 (run-hooks 'org-after-promote-entry-hook))))
8176 (defun org-demote ()
8177 "Demote the current heading lower down the tree."
8178 (org-with-wide-buffer
8179 (org-back-to-heading t)
8180 (let* ((after-change-functions (remq 'flyspell-after-change-function
8181 after-change-functions))
8182 (level (save-match-data (funcall outline-level)))
8183 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8184 (diff (abs (- level (length down-head) -1))))
8185 (replace-match down-head nil t)
8186 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8187 (when org-adapt-indentation (org-fixup-indentation diff))
8188 (run-hooks 'org-after-demote-entry-hook))))
8190 (defun org-cycle-level ()
8191 "Cycle the level of an empty headline through possible states.
8192 This goes first to child, then to parent, level, then up the hierarchy.
8193 After top level, it switches back to sibling level."
8194 (interactive)
8195 (let ((org-adapt-indentation nil))
8196 (when (org-point-at-end-of-empty-headline)
8197 (setq this-command 'org-cycle-level) ; Only needed for caching
8198 (let ((cur-level (org-current-level))
8199 (prev-level (org-get-previous-line-level)))
8200 (cond
8201 ;; If first headline in file, promote to top-level.
8202 ((= prev-level 0)
8203 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8204 do (org-do-promote)))
8205 ;; If same level as prev, demote one.
8206 ((= prev-level cur-level)
8207 (org-do-demote))
8208 ;; If parent is top-level, promote to top level if not already.
8209 ((= prev-level 1)
8210 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8211 do (org-do-promote)))
8212 ;; If top-level, return to prev-level.
8213 ((= cur-level 1)
8214 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8215 do (org-do-demote)))
8216 ;; If less than prev-level, promote one.
8217 ((< cur-level prev-level)
8218 (org-do-promote))
8219 ;; If deeper than prev-level, promote until higher than
8220 ;; prev-level.
8221 ((> cur-level prev-level)
8222 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8223 do (org-do-promote))))
8224 t))))
8226 (defun org-map-tree (fun)
8227 "Call FUN for every heading underneath the current one."
8228 (org-back-to-heading t)
8229 (let ((level (funcall outline-level)))
8230 (save-excursion
8231 (funcall fun)
8232 (while (and (progn
8233 (outline-next-heading)
8234 (> (funcall outline-level) level))
8235 (not (eobp)))
8236 (funcall fun)))))
8238 (defun org-map-region (fun beg end)
8239 "Call FUN for every heading between BEG and END."
8240 (let ((org-ignore-region t))
8241 (save-excursion
8242 (setq end (copy-marker end))
8243 (goto-char beg)
8244 (when (and (re-search-forward org-outline-regexp-bol nil t)
8245 (< (point) end))
8246 (funcall fun))
8247 (while (and (progn
8248 (outline-next-heading)
8249 (< (point) end))
8250 (not (eobp)))
8251 (funcall fun)))))
8253 (defun org-fixup-indentation (diff)
8254 "Change the indentation in the current entry by DIFF.
8256 DIFF is an integer. Indentation is done according to the
8257 following rules:
8259 - Planning information and property drawers are always indented
8260 according to the new level of the headline;
8262 - Footnote definitions and their contents are ignored;
8264 - Inlinetasks' boundaries are not shifted;
8266 - Empty lines are ignored;
8268 - Other lines' indentation are shifted by DIFF columns, unless
8269 it would introduce a structural change in the document, in
8270 which case no shifting is done at all.
8272 Assume point is at a heading or an inlinetask beginning."
8273 (org-with-wide-buffer
8274 (narrow-to-region (line-beginning-position)
8275 (save-excursion
8276 (if (org-with-limited-levels (org-at-heading-p))
8277 (org-with-limited-levels (outline-next-heading))
8278 (org-inlinetask-goto-end))
8279 (point)))
8280 (forward-line)
8281 ;; Indent properly planning info and property drawer.
8282 (when (looking-at-p org-planning-line-re)
8283 (org-indent-line)
8284 (forward-line))
8285 (when (looking-at org-property-drawer-re)
8286 (goto-char (match-end 0))
8287 (forward-line)
8288 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8289 (catch 'no-shift
8290 (when (zerop diff) (throw 'no-shift nil))
8291 ;; If DIFF is negative, first check if a shift is possible at all
8292 ;; (e.g., it doesn't break structure). This can only happen if
8293 ;; some contents are not properly indented.
8294 (let ((case-fold-search t))
8295 (when (< diff 0)
8296 (let ((diff (- diff))
8297 (forbidden-re (concat org-outline-regexp
8298 "\\|"
8299 (substring org-footnote-definition-re 1))))
8300 (save-excursion
8301 (while (not (eobp))
8302 (cond
8303 ((looking-at-p "[ \t]*$") (forward-line))
8304 ((and (looking-at-p org-footnote-definition-re)
8305 (let ((e (org-element-at-point)))
8306 (and (eq (org-element-type e) 'footnote-definition)
8307 (goto-char (org-element-property :end e))))))
8308 ((looking-at-p org-outline-regexp) (forward-line))
8309 ;; Give up if shifting would move before column 0 or
8310 ;; if it would introduce a headline or a footnote
8311 ;; definition.
8313 (skip-chars-forward " \t")
8314 (let ((ind (current-column)))
8315 (when (or (< ind diff)
8316 (and (= ind diff) (looking-at-p forbidden-re)))
8317 (throw 'no-shift nil)))
8318 ;; Ignore contents of example blocks and source
8319 ;; blocks if their indentation is meant to be
8320 ;; preserved. Jump to block's closing line.
8321 (beginning-of-line)
8322 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8323 (let ((e (org-element-at-point)))
8324 (and (memq (org-element-type e)
8325 '(example-block src-block))
8326 (or org-src-preserve-indentation
8327 (org-element-property :preserve-indent e))
8328 (goto-char (org-element-property :end e))
8329 (progn (skip-chars-backward " \r\t\n")
8330 (beginning-of-line)
8331 t))))
8332 (forward-line))))))))
8333 ;; Shift lines but footnote definitions, inlinetasks boundaries
8334 ;; by DIFF. Also skip contents of source or example blocks
8335 ;; when indentation is meant to be preserved.
8336 (while (not (eobp))
8337 (cond
8338 ((and (looking-at-p org-footnote-definition-re)
8339 (let ((e (org-element-at-point)))
8340 (and (eq (org-element-type e) 'footnote-definition)
8341 (goto-char (org-element-property :end e))))))
8342 ((looking-at-p org-outline-regexp) (forward-line))
8343 ((looking-at-p "[ \t]*$") (forward-line))
8345 (indent-line-to (+ (org-get-indentation) diff))
8346 (beginning-of-line)
8347 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8348 (let ((e (org-element-at-point)))
8349 (and (memq (org-element-type e)
8350 '(example-block src-block))
8351 (or org-src-preserve-indentation
8352 (org-element-property :preserve-indent e))
8353 (goto-char (org-element-property :end e))
8354 (progn (skip-chars-backward " \r\t\n")
8355 (beginning-of-line)
8356 t))))
8357 (forward-line)))))))))
8359 (defun org-convert-to-odd-levels ()
8360 "Convert an Org file with all levels allowed to one with odd levels.
8361 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8362 level 5 etc."
8363 (interactive)
8364 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8365 (let ((outline-level 'org-outline-level)
8366 (org-odd-levels-only nil) n)
8367 (save-excursion
8368 (goto-char (point-min))
8369 (while (re-search-forward "^\\*\\*+ " nil t)
8370 (setq n (- (length (match-string 0)) 2))
8371 (while (>= (setq n (1- n)) 0)
8372 (org-demote))
8373 (end-of-line 1))))))
8375 (defun org-convert-to-oddeven-levels ()
8376 "Convert an Org file with only odd levels to one with odd/even levels.
8377 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8378 file contains a section with an even level, conversion would
8379 destroy the structure of the file. An error is signaled in this
8380 case."
8381 (interactive)
8382 (goto-char (point-min))
8383 ;; First check if there are no even levels
8384 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8385 (org-show-set-visibility 'canonical)
8386 (error "Not all levels are odd in this file. Conversion not possible"))
8387 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8388 (let ((outline-regexp org-outline-regexp)
8389 (outline-level 'org-outline-level)
8390 (org-odd-levels-only nil) n)
8391 (save-excursion
8392 (goto-char (point-min))
8393 (while (re-search-forward "^\\*\\*+ " nil t)
8394 (setq n (/ (1- (length (match-string 0))) 2))
8395 (while (>= (setq n (1- n)) 0)
8396 (org-promote))
8397 (end-of-line 1))))))
8399 (defun org-tr-level (n)
8400 "Make N odd if required."
8401 (if org-odd-levels-only (1+ (/ n 2)) n))
8403 ;;; Vertical tree motion, cutting and pasting of subtrees
8405 (defun org-move-subtree-up (&optional arg)
8406 "Move the current subtree up past ARG headlines of the same level."
8407 (interactive "p")
8408 (org-move-subtree-down (- (prefix-numeric-value arg))))
8410 (defun org-move-subtree-down (&optional arg)
8411 "Move the current subtree down past ARG headlines of the same level."
8412 (interactive "p")
8413 (setq arg (prefix-numeric-value arg))
8414 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8415 'org-get-last-sibling))
8416 (ins-point (make-marker))
8417 (cnt (abs arg))
8418 (col (current-column))
8419 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8420 ;; Select the tree
8421 (org-back-to-heading)
8422 (setq beg0 (point))
8423 (save-excursion
8424 (setq ne-beg (org-back-over-empty-lines))
8425 (setq beg (point)))
8426 (save-match-data
8427 (save-excursion (outline-end-of-heading)
8428 (setq folded (outline-invisible-p)))
8429 (progn (org-end-of-subtree nil t)
8430 (unless (eobp) (backward-char))))
8431 (outline-next-heading)
8432 (setq ne-end (org-back-over-empty-lines))
8433 (setq end (point))
8434 (goto-char beg0)
8435 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8436 ;; include less whitespace
8437 (save-excursion
8438 (goto-char beg)
8439 (forward-line (- ne-beg ne-end))
8440 (setq beg (point))))
8441 ;; Find insertion point, with error handling
8442 (while (> cnt 0)
8443 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8444 (progn (goto-char beg0)
8445 (user-error "Cannot move past superior level or buffer limit")))
8446 (setq cnt (1- cnt)))
8447 (when (> arg 0)
8448 ;; Moving forward - still need to move over subtree
8449 (org-end-of-subtree t t)
8450 (save-excursion
8451 (org-back-over-empty-lines)
8452 (or (bolp) (newline))))
8453 (setq ne-ins (org-back-over-empty-lines))
8454 (move-marker ins-point (point))
8455 (setq txt (buffer-substring beg end))
8456 (org-save-markers-in-region beg end)
8457 (delete-region beg end)
8458 (org-remove-empty-overlays-at beg)
8459 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8460 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8461 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8462 (let ((bbb (point)))
8463 (insert-before-markers txt)
8464 (org-reinstall-markers-in-region bbb)
8465 (move-marker ins-point bbb))
8466 (or (bolp) (insert "\n"))
8467 (setq ins-end (point))
8468 (goto-char ins-point)
8469 (org-skip-whitespace)
8470 (when (and (< arg 0)
8471 (org-first-sibling-p)
8472 (> ne-ins ne-beg))
8473 ;; Move whitespace back to beginning
8474 (save-excursion
8475 (goto-char ins-end)
8476 (let ((kill-whole-line t))
8477 (kill-line (- ne-ins ne-beg)) (point)))
8478 (insert (make-string (- ne-ins ne-beg) ?\n)))
8479 (move-marker ins-point nil)
8480 (if folded
8481 (outline-hide-subtree)
8482 (org-show-entry)
8483 (org-show-children)
8484 (org-cycle-hide-drawers 'children))
8485 (org-clean-visibility-after-subtree-move)
8486 ;; move back to the initial column we were at
8487 (move-to-column col)))
8489 (defvar org-subtree-clip ""
8490 "Clipboard for cut and paste of subtrees.
8491 This is actually only a copy of the kill, because we use the normal kill
8492 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8494 (defvar org-subtree-clip-folded nil
8495 "Was the last copied subtree folded?
8496 This is used to fold the tree back after pasting.")
8498 (defun org-cut-subtree (&optional n)
8499 "Cut the current subtree into the clipboard.
8500 With prefix arg N, cut this many sequential subtrees.
8501 This is a short-hand for marking the subtree and then cutting it."
8502 (interactive "p")
8503 (org-copy-subtree n 'cut))
8505 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8506 "Copy the current subtree it in the clipboard.
8507 With prefix arg N, copy this many sequential subtrees.
8508 This is a short-hand for marking the subtree and then copying it.
8509 If CUT is non-nil, actually cut the subtree.
8510 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8511 of some markers in the region, even if CUT is non-nil. This is
8512 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8513 (interactive "p")
8514 (let (beg end folded (beg0 (point)))
8515 (if (called-interactively-p 'any)
8516 (org-back-to-heading nil) ; take what looks like a subtree
8517 (org-back-to-heading t)) ; take what is really there
8518 (setq beg (point))
8519 (skip-chars-forward " \t\r\n")
8520 (save-match-data
8521 (if nosubtrees
8522 (outline-next-heading)
8523 (save-excursion (outline-end-of-heading)
8524 (setq folded (outline-invisible-p)))
8525 (ignore-errors (org-forward-heading-same-level (1- n) t))
8526 (org-end-of-subtree t t)))
8527 ;; Include the end of an inlinetask
8528 (when (and (featurep 'org-inlinetask)
8529 (looking-at-p (concat (org-inlinetask-outline-regexp)
8530 "END[ \t]*$")))
8531 (end-of-line))
8532 (setq end (point))
8533 (goto-char beg0)
8534 (when (> end beg)
8535 (setq org-subtree-clip-folded folded)
8536 (when (or cut force-store-markers)
8537 (org-save-markers-in-region beg end))
8538 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8539 (setq org-subtree-clip (current-kill 0))
8540 (message "%s: Subtree(s) with %d characters"
8541 (if cut "Cut" "Copied")
8542 (length org-subtree-clip)))))
8544 (defun org-paste-subtree (&optional level tree for-yank remove)
8545 "Paste the clipboard as a subtree, with modification of headline level.
8546 The entire subtree is promoted or demoted in order to match a new headline
8547 level.
8549 If the cursor is at the beginning of a headline, the same level as
8550 that headline is used to paste the tree.
8552 If not, the new level is derived from the *visible* headings
8553 before and after the insertion point, and taken to be the inferior headline
8554 level of the two. So if the previous visible heading is level 3 and the
8555 next is level 4 (or vice versa), level 4 will be used for insertion.
8556 This makes sure that the subtree remains an independent subtree and does
8557 not swallow low level entries.
8559 You can also force a different level, either by using a numeric prefix
8560 argument, or by inserting the heading marker by hand. For example, if the
8561 cursor is after \"*****\", then the tree will be shifted to level 5.
8563 If optional TREE is given, use this text instead of the kill ring.
8565 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8566 move back over whitespace before inserting, and move point to the end of
8567 the inserted text when done.
8569 When REMOVE is non-nil, remove the subtree from the clipboard."
8570 (interactive "P")
8571 (setq tree (or tree (and kill-ring (current-kill 0))))
8572 (unless (org-kill-is-subtree-p tree)
8573 (user-error "%s"
8574 (substitute-command-keys
8575 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8576 (org-with-limited-levels
8577 (let* ((visp (not (outline-invisible-p)))
8578 (txt tree)
8579 (^re_ "\\(\\*+\\)[ \t]*")
8580 (old-level (if (string-match org-outline-regexp-bol txt)
8581 (- (match-end 0) (match-beginning 0) 1)
8582 -1))
8583 (force-level (cond (level (prefix-numeric-value level))
8584 ((and (looking-at "[ \t]*$")
8585 (string-match
8586 "^\\*+$" (buffer-substring
8587 (point-at-bol) (point))))
8588 (- (match-end 0) (match-beginning 0)))
8589 ((and (bolp)
8590 (looking-at org-outline-regexp))
8591 (- (match-end 0) (point) 1))))
8592 (previous-level (save-excursion
8593 (condition-case nil
8594 (progn
8595 (outline-previous-visible-heading 1)
8596 (if (looking-at ^re_)
8597 (- (match-end 0) (match-beginning 0) 1)
8599 (error 1))))
8600 (next-level (save-excursion
8601 (condition-case nil
8602 (progn
8603 (or (looking-at org-outline-regexp)
8604 (outline-next-visible-heading 1))
8605 (if (looking-at ^re_)
8606 (- (match-end 0) (match-beginning 0) 1)
8608 (error 1))))
8609 (new-level (or force-level (max previous-level next-level)))
8610 (shift (if (or (= old-level -1)
8611 (= new-level -1)
8612 (= old-level new-level))
8614 (- new-level old-level)))
8615 (delta (if (> shift 0) -1 1))
8616 (func (if (> shift 0) 'org-demote 'org-promote))
8617 (org-odd-levels-only nil)
8618 beg end newend)
8619 ;; Remove the forced level indicator
8620 (when force-level
8621 (delete-region (point-at-bol) (point)))
8622 ;; Paste
8623 (beginning-of-line (if (bolp) 1 2))
8624 (setq beg (point))
8625 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8626 (insert-before-markers txt)
8627 (unless (string-suffix-p "\n" txt) (insert "\n"))
8628 (setq newend (point))
8629 (org-reinstall-markers-in-region beg)
8630 (setq end (point))
8631 (goto-char beg)
8632 (skip-chars-forward " \t\n\r")
8633 (setq beg (point))
8634 (when (and (outline-invisible-p) visp)
8635 (save-excursion (outline-show-heading)))
8636 ;; Shift if necessary
8637 (unless (= shift 0)
8638 (save-restriction
8639 (narrow-to-region beg end)
8640 (while (not (= shift 0))
8641 (org-map-region func (point-min) (point-max))
8642 (setq shift (+ delta shift)))
8643 (goto-char (point-min))
8644 (setq newend (point-max))))
8645 (when (or (called-interactively-p 'interactive) for-yank)
8646 (message "Clipboard pasted as level %d subtree" new-level))
8647 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8648 kill-ring
8649 (eq org-subtree-clip (current-kill 0))
8650 org-subtree-clip-folded)
8651 ;; The tree was folded before it was killed/copied
8652 (outline-hide-subtree))
8653 (and for-yank (goto-char newend))
8654 (and remove (setq kill-ring (cdr kill-ring))))))
8656 (defun org-kill-is-subtree-p (&optional txt)
8657 "Check if the current kill is an outline subtree, or a set of trees.
8658 Returns nil if kill does not start with a headline, or if the first
8659 headline level is not the largest headline level in the tree.
8660 So this will actually accept several entries of equal levels as well,
8661 which is OK for `org-paste-subtree'.
8662 If optional TXT is given, check this string instead of the current kill."
8663 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8664 (re (org-get-limited-outline-regexp))
8665 (^re (concat "^" re))
8666 (start-level (and kill
8667 (string-match
8668 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8669 kill)
8670 (- (match-end 2) (match-beginning 2) 1)))
8671 (start (1+ (or (match-beginning 2) -1))))
8672 (if (not start-level)
8673 (progn
8674 nil) ;; does not even start with a heading
8675 (catch 'exit
8676 (while (setq start (string-match ^re kill (1+ start)))
8677 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8678 (throw 'exit nil)))
8679 t))))
8681 (defvar org-markers-to-move nil
8682 "Markers that should be moved with a cut-and-paste operation.
8683 Those markers are stored together with their positions relative to
8684 the start of the region.")
8686 (defun org-save-markers-in-region (beg end)
8687 "Check markers in region.
8688 If these markers are between BEG and END, record their position relative
8689 to BEG, so that after moving the block of text, we can put the markers back
8690 into place.
8691 This function gets called just before an entry or tree gets cut from the
8692 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8693 called immediately, to move the markers with the entries."
8694 (setq org-markers-to-move nil)
8695 (when (featurep 'org-clock)
8696 (org-clock-save-markers-for-cut-and-paste beg end))
8697 (when (featurep 'org-agenda)
8698 (org-agenda-save-markers-for-cut-and-paste beg end)))
8700 (defun org-check-and-save-marker (marker beg end)
8701 "Check if MARKER is between BEG and END.
8702 If yes, remember the marker and the distance to BEG."
8703 (when (and (marker-buffer marker)
8704 (equal (marker-buffer marker) (current-buffer))
8705 (>= marker beg) (< marker end))
8706 (push (cons marker (- marker beg)) org-markers-to-move)))
8708 (defun org-reinstall-markers-in-region (beg)
8709 "Move all remembered markers to their position relative to BEG."
8710 (dolist (x org-markers-to-move)
8711 (move-marker (car x) (+ beg (cdr x))))
8712 (setq org-markers-to-move nil))
8714 (defun org-narrow-to-subtree ()
8715 "Narrow buffer to the current subtree."
8716 (interactive)
8717 (save-excursion
8718 (save-match-data
8719 (org-with-limited-levels
8720 (narrow-to-region
8721 (progn (org-back-to-heading t) (point))
8722 (progn (org-end-of-subtree t t)
8723 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8724 (point)))))))
8726 (defun org-narrow-to-block ()
8727 "Narrow buffer to the current block."
8728 (interactive)
8729 (let* ((case-fold-search t)
8730 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8731 "^[ \t]*#\\+end_.*")))
8732 (if blockp
8733 (narrow-to-region (car blockp) (cdr blockp))
8734 (user-error "Not in a block"))))
8736 (defun org-clone-subtree-with-time-shift (n &optional shift)
8737 "Clone the task (subtree) at point N times.
8738 The clones will be inserted as siblings.
8740 In interactive use, the user will be prompted for the number of
8741 clones to be produced. If the entry has a timestamp, the user
8742 will also be prompted for a time shift, which may be a repeater
8743 as used in time stamps, for example `+3d'. To disable this,
8744 you can call the function with a universal prefix argument.
8746 When a valid repeater is given and the entry contains any time
8747 stamps, the clones will become a sequence in time, with time
8748 stamps in the subtree shifted for each clone produced. If SHIFT
8749 is nil or the empty string, time stamps will be left alone. The
8750 ID property of the original subtree is removed.
8752 In each clone, all the CLOCK entries will be removed. This
8753 prevents Org from considering that the clocked times overlap.
8755 If the original subtree did contain time stamps with a repeater,
8756 the following will happen:
8757 - the repeater will be removed in each clone
8758 - an additional clone will be produced, with the current, unshifted
8759 date(s) in the entry.
8760 - the original entry will be placed *after* all the clones, with
8761 repeater intact.
8762 - the start days in the repeater in the original entry will be shifted
8763 to past the last clone.
8764 In this way you can spell out a number of instances of a repeating task,
8765 and still retain the repeater to cover future instances of the task.
8767 As described above, N+1 clones are produced when the original
8768 subtree has a repeater. Setting N to 0, then, can be used to
8769 remove the repeater from a subtree and create a shifted clone
8770 with the original repeater."
8771 (interactive "nNumber of clones to produce: ")
8772 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8773 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8774 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8775 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8776 (shift
8777 (or shift
8778 (if (and (not (equal current-prefix-arg '(4)))
8779 (save-excursion
8780 (goto-char beg)
8781 (re-search-forward org-ts-regexp-both end-of-tree t)))
8782 (read-from-minibuffer
8783 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8784 ""))) ;No time shift
8785 (doshift
8786 (and (org-string-nw-p shift)
8787 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8788 shift)
8789 (user-error "Invalid shift specification %s" shift)))))
8790 (goto-char end-of-tree)
8791 (unless (bolp) (insert "\n"))
8792 (let* ((end (point))
8793 (template (buffer-substring beg end))
8794 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8795 (shift-what (pcase (and doshift (match-string 2 shift))
8796 (`nil nil)
8797 ("d" 'day)
8798 ("w" (setq shift-n (* 7 shift-n)) 'day)
8799 ("m" 'month)
8800 ("y" 'year)
8801 (_ (error "Unsupported time unit"))))
8802 (nmin 1)
8803 (nmax n)
8804 (n-no-remove -1)
8805 (idprop (org-entry-get nil "ID")))
8806 (when (and doshift
8807 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8808 template))
8809 (delete-region beg end)
8810 (setq end beg)
8811 (setq nmin 0)
8812 (setq nmax (1+ nmax))
8813 (setq n-no-remove nmax))
8814 (goto-char end)
8815 (cl-loop for n from nmin to nmax do
8816 (insert
8817 ;; Prepare clone.
8818 (with-temp-buffer
8819 (insert template)
8820 (org-mode)
8821 (goto-char (point-min))
8822 (org-show-subtree)
8823 (and idprop (if org-clone-delete-id
8824 (org-entry-delete nil "ID")
8825 (org-id-get-create t)))
8826 (unless (= n 0)
8827 (while (re-search-forward org-clock-line-re nil t)
8828 (delete-region (line-beginning-position)
8829 (line-beginning-position 2)))
8830 (goto-char (point-min))
8831 (while (re-search-forward org-drawer-regexp nil t)
8832 (org-remove-empty-drawer-at (point))))
8833 (goto-char (point-min))
8834 (when doshift
8835 (while (re-search-forward org-ts-regexp-both nil t)
8836 (org-timestamp-change (* n shift-n) shift-what))
8837 (unless (= n n-no-remove)
8838 (goto-char (point-min))
8839 (while (re-search-forward org-ts-regexp nil t)
8840 (save-excursion
8841 (goto-char (match-beginning 0))
8842 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8843 (delete-region (match-beginning 1) (match-end 1)))))))
8844 (buffer-string)))))
8845 (goto-char beg)))
8847 ;;; Outline Sorting
8849 (defun org-sort (&optional with-case)
8850 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8851 Optional argument WITH-CASE means sort case-sensitively."
8852 (interactive "P")
8853 (org-call-with-arg
8854 (cond ((org-at-table-p) #'org-table-sort-lines)
8855 ((org-at-item-p) #'org-sort-list)
8856 (t #'org-sort-entries))
8857 with-case))
8859 (defun org-sort-remove-invisible (s)
8860 "Remove invisible part of links and emphasis markers from string S."
8861 (remove-text-properties 0 (length s) org-rm-props s)
8862 (replace-regexp-in-string
8863 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8864 (replace-regexp-in-string
8865 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8866 (org-link-display-format s)
8867 t t) t t))
8869 (defvar org-priority-regexp) ; defined later in the file
8871 (defvar org-after-sorting-entries-or-items-hook nil
8872 "Hook that is run after a bunch of entries or items have been sorted.
8873 When children are sorted, the cursor is in the parent line when this
8874 hook gets called. When a region or a plain list is sorted, the cursor
8875 will be in the first entry of the sorted region/list.")
8877 (defun org-sort-entries
8878 (&optional with-case sorting-type getkey-func compare-func property
8879 interactive?)
8880 "Sort entries on a certain level of an outline tree.
8881 If there is an active region, the entries in the region are sorted.
8882 Else, if the cursor is before the first entry, sort the top-level items.
8883 Else, the children of the entry at point are sorted.
8885 Sorting can be alphabetically, numerically, by date/time as given by
8886 a time stamp, by a property, by priority order, or by a custom function.
8888 The command prompts for the sorting type unless it has been given to the
8889 function through the SORTING-TYPE argument, which needs to be a character,
8890 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8891 the precise meaning of each character:
8893 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8894 c By creation time, which is assumed to be the first inactive time stamp
8895 at the beginning of a line.
8896 d By deadline date/time.
8897 k By clocking time.
8898 n Numerically, by converting the beginning of the entry/item to a number.
8899 o By order of TODO keywords.
8900 p By priority according to the cookie.
8901 r By the value of a property.
8902 s By scheduled date/time.
8903 t By date/time, either the first active time stamp in the entry, or, if
8904 none exist, by the first inactive one.
8906 Capital letters will reverse the sort order.
8908 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8909 called with point at the beginning of the record. It must return a
8910 value that is compatible with COMPARE-FUNC, the function used to
8911 compare entries.
8913 Comparing entries ignores case by default. However, with an optional argument
8914 WITH-CASE, the sorting considers case as well.
8916 Sorting is done against the visible part of the headlines, it ignores hidden
8917 links.
8919 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8921 A non-nil value for INTERACTIVE? is used to signal that this
8922 function is being called interactively."
8923 (interactive (list current-prefix-arg nil nil nil nil t))
8924 (let ((case-func (if with-case 'identity 'downcase))
8925 (cmstr
8926 ;; The clock marker is lost when using `sort-subr', let's
8927 ;; store the clocking string.
8928 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8929 (save-excursion
8930 (goto-char org-clock-marker)
8931 (buffer-substring-no-properties (line-beginning-position)
8932 (point)))))
8933 start beg end stars re re2
8934 txt what tmp)
8935 ;; Find beginning and end of region to sort
8936 (cond
8937 ((org-region-active-p)
8938 ;; we will sort the region
8939 (setq end (region-end)
8940 what "region")
8941 (goto-char (region-beginning))
8942 (unless (org-at-heading-p) (outline-next-heading))
8943 (setq start (point)))
8944 ((or (org-at-heading-p)
8945 (ignore-errors (progn (org-back-to-heading) t)))
8946 ;; we will sort the children of the current headline
8947 (org-back-to-heading)
8948 (setq start (point)
8949 end (progn (org-end-of-subtree t t)
8950 (or (bolp) (insert "\n"))
8951 (when (>= (org-back-over-empty-lines) 1)
8952 (forward-line 1))
8953 (point))
8954 what "children")
8955 (goto-char start)
8956 (outline-show-subtree)
8957 (outline-next-heading))
8959 ;; we will sort the top-level entries in this file
8960 (goto-char (point-min))
8961 (or (org-at-heading-p) (outline-next-heading))
8962 (setq start (point))
8963 (goto-char (point-max))
8964 (beginning-of-line 1)
8965 (when (looking-at ".*?\\S-")
8966 ;; File ends in a non-white line
8967 (end-of-line 1)
8968 (insert "\n"))
8969 (setq end (point-max))
8970 (setq what "top-level")
8971 (goto-char start)
8972 (outline-show-all)))
8974 (setq beg (point))
8975 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8977 (looking-at "\\(\\*+\\)")
8978 (setq stars (match-string 1)
8979 re (concat "^" (regexp-quote stars) " +")
8980 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8981 txt (buffer-substring beg end))
8982 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8983 (when (and (not (equal stars "*")) (string-match re2 txt))
8984 (user-error "Region to sort contains a level above the first entry"))
8986 (unless sorting-type
8987 (message
8988 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8989 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8990 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8991 what)
8992 (setq sorting-type (read-char-exclusive)))
8994 (unless getkey-func
8995 (and (= (downcase sorting-type) ?f)
8996 (setq getkey-func
8997 (or (and interactive?
8998 (org-read-function
8999 "Function for extracting keys: "))
9000 (error "Missing key extractor")))))
9002 (and (= (downcase sorting-type) ?r)
9003 (not property)
9004 (setq property
9005 (completing-read "Property: "
9006 (mapcar #'list (org-buffer-property-keys t))
9007 nil t)))
9009 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9010 (message "Sorting entries...")
9012 (save-restriction
9013 (narrow-to-region start end)
9014 (let ((dcst (downcase sorting-type))
9015 (case-fold-search nil)
9016 (now (current-time)))
9017 (sort-subr
9018 (/= dcst sorting-type)
9019 ;; This function moves to the beginning character of the "record" to
9020 ;; be sorted.
9021 (lambda nil
9022 (if (re-search-forward re nil t)
9023 (goto-char (match-beginning 0))
9024 (goto-char (point-max))))
9025 ;; This function moves to the last character of the "record" being
9026 ;; sorted.
9027 (lambda nil
9028 (save-match-data
9029 (condition-case nil
9030 (outline-forward-same-level 1)
9031 (error
9032 (goto-char (point-max))))))
9033 ;; This function returns the value that gets sorted against.
9034 (lambda nil
9035 (cond
9036 ((= dcst ?n)
9037 (if (looking-at org-complex-heading-regexp)
9038 (string-to-number (org-sort-remove-invisible (match-string 4)))
9039 nil))
9040 ((= dcst ?a)
9041 (if (looking-at org-complex-heading-regexp)
9042 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9043 nil))
9044 ((= dcst ?k)
9045 (or (get-text-property (point) :org-clock-minutes) 0))
9046 ((= dcst ?t)
9047 (let ((end (save-excursion (outline-next-heading) (point))))
9048 (if (or (re-search-forward org-ts-regexp end t)
9049 (re-search-forward org-ts-regexp-both end t))
9050 (org-time-string-to-seconds (match-string 0))
9051 (float-time now))))
9052 ((= dcst ?c)
9053 (let ((end (save-excursion (outline-next-heading) (point))))
9054 (if (re-search-forward
9055 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9056 end t)
9057 (org-time-string-to-seconds (match-string 0))
9058 (float-time now))))
9059 ((= dcst ?s)
9060 (let ((end (save-excursion (outline-next-heading) (point))))
9061 (if (re-search-forward org-scheduled-time-regexp end t)
9062 (org-time-string-to-seconds (match-string 1))
9063 (float-time now))))
9064 ((= dcst ?d)
9065 (let ((end (save-excursion (outline-next-heading) (point))))
9066 (if (re-search-forward org-deadline-time-regexp end t)
9067 (org-time-string-to-seconds (match-string 1))
9068 (float-time now))))
9069 ((= dcst ?p)
9070 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9071 (string-to-char (match-string 2))
9072 org-default-priority))
9073 ((= dcst ?r)
9074 (or (org-entry-get nil property) ""))
9075 ((= dcst ?o)
9076 (when (looking-at org-complex-heading-regexp)
9077 (let* ((m (match-string 2))
9078 (s (if (member m org-done-keywords) '- '+)))
9079 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9080 ((= dcst ?f)
9081 (if getkey-func
9082 (progn
9083 (setq tmp (funcall getkey-func))
9084 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9085 tmp)
9086 (error "Invalid key function `%s'" getkey-func)))
9087 (t (error "Invalid sorting type `%c'" sorting-type))))
9089 (cond
9090 ((= dcst ?a) 'string<)
9091 ((= dcst ?f)
9092 (or compare-func
9093 (and interactive?
9094 (org-read-function
9095 (concat "Function for comparing keys "
9096 "(empty for default `sort-subr' predicate): ")
9097 'allow-empty))))
9098 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9099 (run-hooks 'org-after-sorting-entries-or-items-hook)
9100 ;; Reset the clock marker if needed
9101 (when cmstr
9102 (save-excursion
9103 (goto-char start)
9104 (search-forward cmstr nil t)
9105 (move-marker org-clock-marker (point))))
9106 (message "Sorting entries...done")))
9108 ;;; The orgstruct minor mode
9110 ;; Define a minor mode which can be used in other modes in order to
9111 ;; integrate the Org mode structure editing commands.
9113 ;; This is really a hack, because the Org mode structure commands use
9114 ;; keys which normally belong to the major mode. Here is how it
9115 ;; works: The minor mode defines all the keys necessary to operate the
9116 ;; structure commands, but wraps the commands into a function which
9117 ;; tests if the cursor is currently at a headline or a plain list
9118 ;; item. If that is the case, the structure command is used,
9119 ;; temporarily setting many Org mode variables like regular
9120 ;; expressions for filling etc. However, when any of those keys is
9121 ;; used at a different location, function uses `key-binding' to look
9122 ;; up if the key has an associated command in another currently active
9123 ;; keymap (minor modes, major mode, global), and executes that
9124 ;; command. There might be problems if any of the keys is otherwise
9125 ;; used as a prefix key.
9127 (defcustom orgstruct-heading-prefix-regexp ""
9128 "Regexp that matches the custom prefix of Org headlines in
9129 orgstruct(++)-mode."
9130 :group 'org
9131 :version "24.4"
9132 :package-version '(Org . "8.3")
9133 :type 'regexp)
9134 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9136 (defcustom orgstruct-setup-hook nil
9137 "Hook run after orgstruct-mode-map is filled."
9138 :group 'org
9139 :version "24.4"
9140 :package-version '(Org . "8.0")
9141 :type 'hook)
9143 (defvar orgstruct-initialized nil)
9145 (defvar org-local-vars nil
9146 "List of local variables, for use by `orgstruct-mode'.")
9148 ;;;###autoload
9149 (define-minor-mode orgstruct-mode
9150 "Toggle the minor mode `orgstruct-mode'.
9151 This mode is for using Org mode structure commands in other
9152 modes. The following keys behave as if Org mode were active, if
9153 the cursor is on a headline, or on a plain list item (both as
9154 defined by Org mode)."
9155 nil " OrgStruct" (make-sparse-keymap)
9156 (funcall (if orgstruct-mode
9157 'add-to-invisibility-spec
9158 'remove-from-invisibility-spec)
9159 '(outline . t))
9160 (when orgstruct-mode
9161 (org-load-modules-maybe)
9162 (unless orgstruct-initialized
9163 (orgstruct-setup)
9164 (setq orgstruct-initialized t))))
9166 ;;;###autoload
9167 (defun turn-on-orgstruct ()
9168 "Unconditionally turn on `orgstruct-mode'."
9169 (orgstruct-mode 1))
9171 (defvar-local orgstruct-is-++ nil
9172 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9173 (defvar-local org-fb-vars nil)
9174 (defun orgstruct++-mode (&optional arg)
9175 "Toggle `orgstruct-mode', the enhanced version of it.
9176 In addition to setting orgstruct-mode, this also exports all
9177 indentation and autofilling variables from Org mode into the
9178 buffer. It will also recognize item context in multiline items."
9179 (interactive "P")
9180 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9181 (if (< arg 1)
9182 (progn (orgstruct-mode -1)
9183 (dolist (v org-fb-vars)
9184 (set (make-local-variable (car v))
9185 (if (eq (car-safe (cadr v)) 'quote)
9186 (cl-cadadr v)
9187 (nth 1 v)))))
9188 (orgstruct-mode 1)
9189 (setq org-fb-vars nil)
9190 (unless org-local-vars
9191 (setq org-local-vars (org-get-local-variables)))
9192 (let (var val)
9193 (dolist (x org-local-vars)
9194 (when (string-match
9195 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9196 \\|fill-prefix\\|indent-\\)"
9197 (symbol-name (car x)))
9198 (setq var (car x) val (nth 1 x))
9199 (push (list var `(quote ,(eval var))) org-fb-vars)
9200 (set (make-local-variable var)
9201 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9202 (setq-local orgstruct-is-++ t))))
9204 ;;;###autoload
9205 (defun turn-on-orgstruct++ ()
9206 "Unconditionally turn on `orgstruct++-mode'."
9207 (orgstruct++-mode 1))
9209 (defun orgstruct-error ()
9210 "Error when there is no default binding for a structure key."
9211 (interactive)
9212 (funcall (if (fboundp 'user-error)
9213 'user-error
9214 'error)
9215 "This key has no function outside structure elements"))
9217 (defun orgstruct-setup ()
9218 "Setup orgstruct keymap."
9219 (dolist (cell '((org-demote . t)
9220 (org-metaleft . t)
9221 (org-metaright . t)
9222 (org-promote . t)
9223 (org-shiftmetaleft . t)
9224 (org-shiftmetaright . t)
9225 org-backward-element
9226 org-backward-heading-same-level
9227 org-ctrl-c-ret
9228 org-ctrl-c-minus
9229 org-ctrl-c-star
9230 org-cycle
9231 org-force-cycle-archived
9232 org-forward-heading-same-level
9233 org-insert-heading
9234 org-insert-heading-respect-content
9235 org-kill-note-or-show-branches
9236 org-mark-subtree
9237 org-meta-return
9238 org-metadown
9239 org-metaup
9240 org-narrow-to-subtree
9241 org-promote-subtree
9242 org-reveal
9243 org-shiftdown
9244 org-shiftleft
9245 org-shiftmetadown
9246 org-shiftmetaup
9247 org-shiftright
9248 org-shifttab
9249 org-shifttab
9250 org-shiftup
9251 org-show-children
9252 org-show-subtree
9253 org-sort
9254 org-up-element
9255 outline-demote
9256 outline-next-visible-heading
9257 outline-previous-visible-heading
9258 outline-promote
9259 outline-up-heading))
9260 (let ((f (or (car-safe cell) cell))
9261 (disable-when-heading-prefix (cdr-safe cell)))
9262 (when (fboundp f)
9263 (let ((new-bindings))
9264 (dolist (binding (nconc (where-is-internal f org-mode-map)
9265 (where-is-internal f outline-mode-map)))
9266 (push binding new-bindings)
9267 ;; TODO use local-function-key-map
9268 (dolist (rep '(("<tab>" . "TAB")
9269 ("<return>" . "RET")
9270 ("<escape>" . "ESC")
9271 ("<delete>" . "DEL")))
9272 (setq binding (read-kbd-macro
9273 (let ((case-fold-search))
9274 (replace-regexp-in-string
9275 (regexp-quote (cdr rep))
9276 (car rep)
9277 (key-description binding)))))
9278 (cl-pushnew binding new-bindings :test 'equal)))
9279 (dolist (binding new-bindings)
9280 (let ((key (lookup-key orgstruct-mode-map binding)))
9281 (when (or (not key) (numberp key))
9282 (ignore-errors
9283 (org-defkey orgstruct-mode-map
9284 binding
9285 (orgstruct-make-binding
9286 f binding disable-when-heading-prefix))))))))))
9287 (run-hooks 'orgstruct-setup-hook))
9289 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9290 "Create a function for binding in the structure minor mode.
9291 FUN is the command to call inside a table. KEY is the key that
9292 should be checked in for a command to execute outside of tables.
9293 Non-nil `disable-when-heading-prefix' means to disable the command
9294 if `orgstruct-heading-prefix-regexp' is not empty."
9295 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9296 (let ((nname name)
9297 (i 0))
9298 (while (fboundp (intern nname))
9299 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9300 (setq name (intern nname)))
9301 (eval
9302 (let ((bindings '((org-heading-regexp
9303 (concat "^"
9304 orgstruct-heading-prefix-regexp
9305 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9306 (org-outline-regexp
9307 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9308 (org-outline-regexp-bol
9309 (concat "^" org-outline-regexp))
9310 (outline-regexp org-outline-regexp)
9311 (outline-heading-end-regexp "\n")
9312 (outline-level 'org-outline-level)
9313 (outline-heading-alist))))
9314 `(defun ,name (arg)
9315 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9316 "Outside of structure, run the binding of `"
9317 (key-description key) "'."
9318 (when disable-when-heading-prefix
9319 (concat
9320 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9321 "back to the default binding due to limitations of Org's implementation of\n"
9322 "`" (symbol-name fun) "'.")))
9323 (interactive "p")
9324 (let* ((disable
9325 ,(and disable-when-heading-prefix
9326 '(not (string= orgstruct-heading-prefix-regexp ""))))
9327 (fallback
9328 (or disable
9329 (not
9330 (let* ,bindings
9331 (org-context-p 'headline 'item
9332 ,(when (memq fun
9333 '(org-insert-heading
9334 org-insert-heading-respect-content
9335 org-meta-return))
9336 '(when orgstruct-is-++
9337 'item-body))))))))
9338 (if fallback
9339 (let* ((orgstruct-mode)
9340 (binding
9341 (let ((key ,key))
9342 (catch 'exit
9343 (dolist
9344 (rep
9345 '(nil
9346 ("<\\([^>]*\\)tab>" . "\\1TAB")
9347 ("<\\([^>]*\\)return>" . "\\1RET")
9348 ("<\\([^>]*\\)escape>" . "\\1ESC")
9349 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9350 nil)
9351 (when rep
9352 (setq key (read-kbd-macro
9353 (let ((case-fold-search))
9354 (replace-regexp-in-string
9355 (car rep)
9356 (cdr rep)
9357 (key-description key))))))
9358 (when (key-binding key)
9359 (throw 'exit (key-binding key))))))))
9360 (if (keymapp binding)
9361 (org-set-transient-map binding)
9362 (let ((func (or binding
9363 (unless disable
9364 'orgstruct-error))))
9365 (when func
9366 (call-interactively func)))))
9367 (org-run-like-in-org-mode
9368 (lambda ()
9369 (interactive)
9370 (let* ,bindings
9371 (call-interactively ',fun)))))))))
9372 name))
9374 (defun org-contextualize-keys (alist contexts)
9375 "Return valid elements in ALIST depending on CONTEXTS.
9377 `org-agenda-custom-commands' or `org-capture-templates' are the
9378 values used for ALIST, and `org-agenda-custom-commands-contexts'
9379 or `org-capture-templates-contexts' are the associated contexts
9380 definitions."
9381 (let ((contexts
9382 ;; normalize contexts
9383 (mapcar
9384 (lambda(c) (cond ((listp (cadr c))
9385 (list (car c) (car c) (nth 1 c)))
9386 ((string= "" (cadr c))
9387 (list (car c) (car c) (nth 2 c)))
9388 (t c)))
9389 contexts))
9390 (a alist) r s)
9391 ;; loop over all commands or templates
9392 (dolist (c a)
9393 (let (vrules repl)
9394 (cond
9395 ((not (assoc (car c) contexts))
9396 (push c r))
9397 ((and (assoc (car c) contexts)
9398 (setq vrules (org-contextualize-validate-key
9399 (car c) contexts)))
9400 (mapc (lambda (vr)
9401 (unless (equal (car vr) (cadr vr))
9402 (setq repl vr)))
9403 vrules)
9404 (if (not repl) (push c r)
9405 (push (cadr repl) s)
9406 (push
9407 (cons (car c)
9408 (cdr (or (assoc (cadr repl) alist)
9409 (error "Undefined key `%s' as contextual replacement for `%s'"
9410 (cadr repl) (car c)))))
9411 r))))))
9412 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9413 (delq
9415 (delete-dups
9416 (mapcar (lambda (x)
9417 (let ((tpl (car x)))
9418 (unless (delq
9420 (mapcar (lambda (y)
9421 (equal y tpl))
9423 x)))
9424 (reverse r))))))
9426 (defun org-contextualize-validate-key (key contexts)
9427 "Check CONTEXTS for agenda or capture KEY."
9428 (let (res)
9429 (dolist (r contexts)
9430 (dolist (rr (car (last r)))
9431 (when
9432 (and (equal key (car r))
9433 (if (functionp rr) (funcall rr)
9434 (or (and (eq (car rr) 'in-file)
9435 (buffer-file-name)
9436 (string-match (cdr rr) (buffer-file-name)))
9437 (and (eq (car rr) 'in-mode)
9438 (string-match (cdr rr) (symbol-name major-mode)))
9439 (and (eq (car rr) 'in-buffer)
9440 (string-match (cdr rr) (buffer-name)))
9441 (when (and (eq (car rr) 'not-in-file)
9442 (buffer-file-name))
9443 (not (string-match (cdr rr) (buffer-file-name))))
9444 (when (eq (car rr) 'not-in-mode)
9445 (not (string-match (cdr rr) (symbol-name major-mode))))
9446 (when (eq (car rr) 'not-in-buffer)
9447 (not (string-match (cdr rr) (buffer-name)))))))
9448 (push r res))))
9449 (delete-dups (delq nil res))))
9451 (defun org-context-p (&rest contexts)
9452 "Check if local context is any of CONTEXTS.
9453 Possible values in the list of contexts are `table', `headline', and `item'."
9454 (let ((pos (point)))
9455 (goto-char (point-at-bol))
9456 (prog1 (or (and (memq 'table contexts)
9457 (looking-at "[ \t]*|"))
9458 (and (memq 'headline contexts)
9459 (looking-at org-outline-regexp))
9460 (and (memq 'item contexts)
9461 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9462 (and (memq 'item-body contexts)
9463 (org-in-item-p)))
9464 (goto-char pos))))
9466 (defconst org-unique-local-variables
9467 '(org-element--cache
9468 org-element--cache-objects
9469 org-element--cache-sync-keys
9470 org-element--cache-sync-requests
9471 org-element--cache-sync-timer)
9472 "List of local variables that cannot be transferred to another buffer.")
9474 (defun org-get-local-variables ()
9475 "Return a list of all local variables in an Org mode buffer."
9476 (delq nil
9477 (mapcar
9478 (lambda (x)
9479 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9480 (name (car binding)))
9481 (and (not (get name 'org-state))
9482 (not (memq name org-unique-local-variables))
9483 (string-match-p
9484 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9485 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9486 (symbol-name name))
9487 binding)))
9488 (with-temp-buffer
9489 (org-mode)
9490 (buffer-local-variables)))))
9492 (defun org-clone-local-variables (from-buffer &optional regexp)
9493 "Clone local variables from FROM-BUFFER.
9494 Optional argument REGEXP selects variables to clone."
9495 (dolist (pair (buffer-local-variables from-buffer))
9496 (let ((name (car pair)))
9497 (when (and (symbolp name)
9498 (not (memq name org-unique-local-variables))
9499 (or (null regexp) (string-match regexp (symbol-name name))))
9500 (set (make-local-variable name) (cdr pair))))))
9502 ;;;###autoload
9503 (defun org-run-like-in-org-mode (cmd)
9504 "Run a command, pretending that the current buffer is in Org mode.
9505 This will temporarily bind local variables that are typically bound in
9506 Org mode to the values they have in Org mode, and then interactively
9507 call CMD."
9508 (org-load-modules-maybe)
9509 (unless org-local-vars
9510 (setq org-local-vars (org-get-local-variables)))
9511 (let (binds)
9512 (dolist (var org-local-vars)
9513 (when (or (not (boundp (car var)))
9514 (eq (symbol-value (car var))
9515 (default-value (car var))))
9516 (push (list (car var) `(quote ,(cadr var))) binds)))
9517 (eval `(let ,binds
9518 (call-interactively (quote ,cmd))))))
9520 (defun org-get-category (&optional pos force-refresh)
9521 "Get the category applying to position POS."
9522 (save-match-data
9523 (when force-refresh (org-refresh-category-properties))
9524 (let ((pos (or pos (point))))
9525 (or (get-text-property pos 'org-category)
9526 (progn (org-refresh-category-properties)
9527 (get-text-property pos 'org-category))))))
9529 ;;; Refresh properties
9531 (defun org-refresh-properties (dprop tprop)
9532 "Refresh buffer text properties.
9533 DPROP is the drawer property and TPROP is either the
9534 corresponding text property to set, or an alist with each element
9535 being a text property (as a symbol) and a function to apply to
9536 the value of the drawer property."
9537 (let* ((case-fold-search t)
9538 (inhibit-read-only t)
9539 (inherit? (org-property-inherit-p dprop))
9540 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9541 (global (and inherit? (org--property-global-value dprop nil))))
9542 (org-with-silent-modifications
9543 (org-with-point-at 1
9544 ;; Set global values (e.g., values defined through
9545 ;; "#+PROPERTY:" keywords) to the whole buffer.
9546 (when global (put-text-property (point-min) (point-max) tprop global))
9547 ;; Set local values.
9548 (while (re-search-forward property-re nil t)
9549 (when (org-at-property-p)
9550 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9551 (outline-next-heading))))))
9553 (defun org-refresh-property (tprop p &optional inherit)
9554 "Refresh the buffer text property TPROP from the drawer property P.
9555 The refresh happens only for the current headline, or the whole
9556 sub-tree if optional argument INHERIT is non-nil."
9557 (unless (org-before-first-heading-p)
9558 (save-excursion
9559 (org-back-to-heading t)
9560 (let ((start (point))
9561 (end (save-excursion
9562 (if inherit (org-end-of-subtree t t)
9563 (or (outline-next-heading) (point-max))))))
9564 (if (symbolp tprop)
9565 ;; TPROP is a text property symbol.
9566 (put-text-property start end tprop p)
9567 ;; TPROP is an alist with (property . function) elements.
9568 (pcase-dolist (`(,prop . ,f) tprop)
9569 (put-text-property start end prop (funcall f p))))))))
9571 (defun org-refresh-category-properties ()
9572 "Refresh category text properties in the buffer."
9573 (let ((case-fold-search t)
9574 (inhibit-read-only t)
9575 (default-category
9576 (cond ((null org-category)
9577 (if buffer-file-name
9578 (file-name-sans-extension
9579 (file-name-nondirectory buffer-file-name))
9580 "???"))
9581 ((symbolp org-category) (symbol-name org-category))
9582 (t org-category))))
9583 (org-with-silent-modifications
9584 (org-with-wide-buffer
9585 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9586 ;; This is the default category for the buffer. If none is
9587 ;; found, fall-back to `org-category' or buffer file name.
9588 (put-text-property
9589 (point-min) (point-max)
9590 'org-category
9591 (catch 'buffer-category
9592 (goto-char (point-max))
9593 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9594 (let ((element (org-element-at-point)))
9595 (when (eq (org-element-type element) 'keyword)
9596 (throw 'buffer-category
9597 (org-element-property :value element)))))
9598 default-category))
9599 ;; Set sub-tree specific categories.
9600 (goto-char (point-min))
9601 (let ((regexp (org-re-property "CATEGORY")))
9602 (while (re-search-forward regexp nil t)
9603 (let ((value (match-string-no-properties 3)))
9604 (when (org-at-property-p)
9605 (put-text-property
9606 (save-excursion (org-back-to-heading t) (point))
9607 (save-excursion (org-end-of-subtree t t) (point))
9608 'org-category
9609 value)))))))))
9611 (defun org-refresh-stats-properties ()
9612 "Refresh stats text properties in the buffer."
9613 (org-with-silent-modifications
9614 (org-with-point-at 1
9615 (let ((regexp (concat org-outline-regexp-bol
9616 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9617 (while (re-search-forward regexp nil t)
9618 (let* ((numerator (string-to-number (match-string 1)))
9619 (denominator (and (match-end 2)
9620 (string-to-number (match-string 2))))
9621 (stats (cond ((not denominator) numerator) ;percent
9622 ((= denominator 0) 0)
9623 (t (/ (* numerator 100) denominator)))))
9624 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9625 'org-stats stats)))))))
9627 (defun org-refresh-effort-properties ()
9628 "Refresh effort properties"
9629 (org-refresh-properties
9630 org-effort-property
9631 '((effort . identity)
9632 (effort-minutes . org-duration-to-minutes))))
9634 ;;;; Link Stuff
9636 ;;; Link abbreviations
9638 (defun org-link-expand-abbrev (link)
9639 "Apply replacements as defined in `org-link-abbrev-alist'."
9640 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9641 (let* ((key (match-string 1 link))
9642 (as (or (assoc key org-link-abbrev-alist-local)
9643 (assoc key org-link-abbrev-alist)))
9644 (tag (and (match-end 2) (match-string 3 link)))
9645 rpl)
9646 (if (not as)
9647 link
9648 (setq rpl (cdr as))
9649 (cond
9650 ((symbolp rpl) (funcall rpl tag))
9651 ((string-match "%(\\([^)]+\\))" rpl)
9652 (replace-match
9653 (save-match-data
9654 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9655 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9656 ((string-match "%h" rpl)
9657 (replace-match (url-hexify-string (or tag "")) t t rpl))
9658 (t (concat rpl tag)))))
9659 link))
9661 ;;; Storing and inserting links
9663 (defvar org-insert-link-history nil
9664 "Minibuffer history for links inserted with `org-insert-link'.")
9666 (defvar org-stored-links nil
9667 "Contains the links stored with `org-store-link'.")
9669 (defvar org-store-link-plist nil
9670 "Plist with info about the most recently link created with `org-store-link'.")
9672 (defun org-store-link-functions ()
9673 "Return a list of functions that are called to create and store a link.
9674 The functions defined in the :store property of
9675 `org-link-parameters'.
9677 Each function will be called in turn until one returns a non-nil
9678 value. Each function should check if it is responsible for
9679 creating this link (for example by looking at the major mode).
9680 If not, it must exit and return nil. If yes, it should return
9681 a non-nil value after calling `org-store-link-props' with a list
9682 of properties and values. Special properties are:
9684 :type The link prefix, like \"http\". This must be given.
9685 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9686 This is obligatory as well.
9687 :description Optional default description for the second pair
9688 of brackets in an Org mode link. The user can still change
9689 this when inserting this link into an Org mode buffer.
9691 In addition to these, any additional properties can be specified
9692 and then used in capture templates."
9693 (cl-loop for link in org-link-parameters
9694 with store-func
9695 do (setq store-func (org-link-get-parameter (car link) :store))
9696 if store-func
9697 collect store-func))
9699 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9700 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9702 ;;;###autoload
9703 (defun org-store-link (arg)
9704 "Store an org-link to the current location.
9705 \\<org-mode-map>
9706 This link is added to `org-stored-links' and can later be inserted
9707 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9709 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9710 A single
9711 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9712 `org-gnus-prefer-web-links' for links to Usenet articles.
9714 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9715 skipping storing functions that are not
9716 part of Org core.
9718 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9719 prefix ARG forces storing a link for each line in the
9720 active region."
9721 (interactive "P")
9722 (org-load-modules-maybe)
9723 (if (and (equal arg '(64)) (org-region-active-p))
9724 (save-excursion
9725 (let ((end (region-end)))
9726 (goto-char (region-beginning))
9727 (set-mark (point))
9728 (while (< (point-at-eol) end)
9729 (move-end-of-line 1) (activate-mark)
9730 (let (current-prefix-arg)
9731 (call-interactively 'org-store-link))
9732 (move-beginning-of-line 2)
9733 (set-mark (point)))))
9734 (setq org-store-link-plist nil)
9735 (let (link cpltxt desc description search
9736 txt custom-id agenda-link sfuns sfunsn)
9737 (cond
9739 ;; Store a link using an external link type
9740 ((and (not (equal arg '(16)))
9741 (setq sfuns
9742 (delq
9743 nil (mapcar (lambda (f)
9744 (let (fs) (if (funcall f) (push f fs))))
9745 (org-store-link-functions)))
9746 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9747 (or (and (cdr sfuns)
9748 (funcall (intern
9749 (completing-read
9750 "Which function for creating the link? "
9751 sfunsn nil t (car sfunsn)))))
9752 (funcall (caar sfuns)))
9753 (setq link (plist-get org-store-link-plist :link)
9754 desc (or (plist-get org-store-link-plist
9755 :description)
9756 link))))
9758 ;; Store a link from a source code buffer.
9759 ((org-src-edit-buffer-p)
9760 (let ((coderef-format (org-src-coderef-format)))
9761 (cond ((save-excursion
9762 (beginning-of-line)
9763 (looking-at (org-src-coderef-regexp coderef-format)))
9764 (setq link (format "(%s)" (match-string-no-properties 3))))
9765 ((called-interactively-p 'any)
9766 (let ((label (read-string "Code line label: ")))
9767 (end-of-line)
9768 (setq link (format coderef-format label))
9769 (let ((gc (- 79 (length link))))
9770 (if (< (current-column) gc)
9771 (org-move-to-column gc t)
9772 (insert " ")))
9773 (insert link)
9774 (setq link (concat "(" label ")"))
9775 (setq desc nil)))
9776 (t (setq link nil)))))
9778 ;; We are in the agenda, link to referenced location
9779 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9780 (let ((m (or (get-text-property (point) 'org-hd-marker)
9781 (get-text-property (point) 'org-marker))))
9782 (when m
9783 (org-with-point-at m
9784 (setq agenda-link
9785 (if (called-interactively-p 'any)
9786 (call-interactively 'org-store-link)
9787 (org-store-link nil)))))))
9789 ((eq major-mode 'calendar-mode)
9790 (let ((cd (calendar-cursor-to-date)))
9791 (setq link
9792 (format-time-string
9793 (car org-time-stamp-formats)
9794 (apply 'encode-time
9795 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9796 nil nil nil))))
9797 (org-store-link-props :type "calendar" :date cd)))
9799 ((eq major-mode 'help-mode)
9800 (setq link (concat "help:" (save-excursion
9801 (goto-char (point-min))
9802 (looking-at "^[^ ]+")
9803 (match-string 0))))
9804 (org-store-link-props :type "help"))
9806 ((eq major-mode 'w3-mode)
9807 (setq cpltxt (if (and (buffer-name)
9808 (not (string-match "Untitled" (buffer-name))))
9809 (buffer-name)
9810 (url-view-url t))
9811 link (url-view-url t))
9812 (org-store-link-props :type "w3" :url (url-view-url t)))
9814 ((eq major-mode 'image-mode)
9815 (setq cpltxt (concat "file:"
9816 (abbreviate-file-name buffer-file-name))
9817 link cpltxt)
9818 (org-store-link-props :type "image" :file buffer-file-name))
9820 ;; In dired, store a link to the file of the current line
9821 ((derived-mode-p 'dired-mode)
9822 (let ((file (dired-get-filename nil t)))
9823 (setq file (if file
9824 (abbreviate-file-name
9825 (expand-file-name (dired-get-filename nil t)))
9826 ;; otherwise, no file so use current directory.
9827 default-directory))
9828 (setq cpltxt (concat "file:" file)
9829 link cpltxt)))
9831 ((setq search (run-hook-with-args-until-success
9832 'org-create-file-search-functions))
9833 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9834 "::" search))
9835 (setq cpltxt (or description link)))
9837 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9838 (org-with-limited-levels
9839 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9840 (cond
9841 ;; Store a link using the target at point
9842 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9843 (setq cpltxt
9844 (concat "file:"
9845 (abbreviate-file-name
9846 (buffer-file-name (buffer-base-buffer)))
9847 "::" (match-string 1))
9848 link cpltxt))
9849 ((and (featurep 'org-id)
9850 (or (eq org-id-link-to-org-use-id t)
9851 (and (called-interactively-p 'any)
9852 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9853 (and (eq org-id-link-to-org-use-id
9854 'create-if-interactive-and-no-custom-id)
9855 (not custom-id))))
9856 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9857 ;; Store a link using the ID at point
9858 (setq link (condition-case nil
9859 (prog1 (org-id-store-link)
9860 (setq desc (or (plist-get org-store-link-plist
9861 :description)
9862 "")))
9863 (error
9864 ;; Probably before first headline, link only to file
9865 (concat "file:"
9866 (abbreviate-file-name
9867 (buffer-file-name (buffer-base-buffer))))))))
9869 ;; Just link to current headline
9870 (setq cpltxt (concat "file:"
9871 (abbreviate-file-name
9872 (buffer-file-name (buffer-base-buffer)))))
9873 ;; Add a context search string
9874 (when (org-xor org-context-in-file-links
9875 (equal arg '(4)))
9876 (let* ((element (org-element-at-point))
9877 (name (org-element-property :name element)))
9878 (setq txt (cond
9879 ((org-at-heading-p) nil)
9880 (name)
9881 ((org-region-active-p)
9882 (buffer-substring (region-beginning) (region-end)))))
9883 (when (or (null txt) (string-match "\\S-" txt))
9884 (setq cpltxt
9885 (concat cpltxt "::"
9886 (condition-case nil
9887 (org-make-org-heading-search-string txt)
9888 (error "")))
9889 desc (or name
9890 (nth 4 (ignore-errors (org-heading-components)))
9891 "NONE")))))
9892 (when (string-match "::\\'" cpltxt)
9893 (setq cpltxt (substring cpltxt 0 -2)))
9894 (setq link cpltxt)))))
9896 ((buffer-file-name (buffer-base-buffer))
9897 ;; Just link to this file here.
9898 (setq cpltxt (concat "file:"
9899 (abbreviate-file-name
9900 (buffer-file-name (buffer-base-buffer)))))
9901 ;; Add a context string.
9902 (when (org-xor org-context-in-file-links
9903 (equal arg '(4)))
9904 (setq txt (if (org-region-active-p)
9905 (buffer-substring (region-beginning) (region-end))
9906 (buffer-substring (point-at-bol) (point-at-eol))))
9907 ;; Only use search option if there is some text.
9908 (when (string-match "\\S-" txt)
9909 (setq cpltxt
9910 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9911 desc "NONE")))
9912 (setq link cpltxt))
9914 ((called-interactively-p 'interactive)
9915 (user-error "No method for storing a link from this buffer"))
9917 (t (setq link nil)))
9919 ;; We're done setting link and desc, clean up
9920 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9921 (setq link (or link cpltxt)
9922 desc (or desc cpltxt))
9923 (cond ((not desc))
9924 ((equal desc "NONE") (setq desc nil))
9925 (t (setq desc
9926 (replace-regexp-in-string
9927 org-bracket-link-analytic-regexp
9928 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9929 desc))))
9930 ;; Return the link
9931 (if (not (and (or (called-interactively-p 'any)
9932 executing-kbd-macro)
9933 link))
9934 (or agenda-link (and link (org-make-link-string link desc)))
9935 (push (list link desc) org-stored-links)
9936 (message "Stored: %s" (or desc link))
9937 (when custom-id
9938 (setq link (concat "file:" (abbreviate-file-name
9939 (buffer-file-name)) "::#" custom-id))
9940 (push (list link desc) org-stored-links))
9941 (car org-stored-links)))))
9943 (defun org-store-link-props (&rest plist)
9944 "Store link properties, extract names, addresses and dates."
9945 (let ((x (plist-get plist :from)))
9946 (when x
9947 (let ((adr (mail-extract-address-components x)))
9948 (setq plist (plist-put plist :fromname (car adr)))
9949 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9950 (let ((x (plist-get plist :to)))
9951 (when x
9952 (let ((adr (mail-extract-address-components x)))
9953 (setq plist (plist-put plist :toname (car adr)))
9954 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9955 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9956 (when x
9957 (setq plist (plist-put plist :date-timestamp
9958 (format-time-string
9959 (org-time-stamp-format t) x)))
9960 (setq plist (plist-put plist :date-timestamp-inactive
9961 (format-time-string
9962 (org-time-stamp-format t t) x)))))
9963 (let ((from (plist-get plist :from))
9964 (to (plist-get plist :to)))
9965 (when (and from to org-from-is-user-regexp)
9966 (setq plist
9967 (plist-put plist :fromto
9968 (if (string-match org-from-is-user-regexp from)
9969 (concat "to %t")
9970 (concat "from %f"))))))
9971 (setq org-store-link-plist plist))
9973 (defun org-add-link-props (&rest plist)
9974 "Add these properties to the link property list."
9975 (let (key value)
9976 (while plist
9977 (setq key (pop plist) value (pop plist))
9978 (setq org-store-link-plist
9979 (plist-put org-store-link-plist key value)))))
9981 (defun org-email-link-description (&optional fmt)
9982 "Return the description part of an email link.
9983 This takes information from `org-store-link-plist' and formats it
9984 according to FMT (default from `org-email-link-description-format')."
9985 (setq fmt (or fmt org-email-link-description-format))
9986 (let* ((p org-store-link-plist)
9987 (to (plist-get p :toaddress))
9988 (from (plist-get p :fromaddress))
9989 (table
9990 (list
9991 (cons "%c" (plist-get p :fromto))
9992 (cons "%F" (plist-get p :from))
9993 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9994 (cons "%T" (plist-get p :to))
9995 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9996 (cons "%s" (plist-get p :subject))
9997 (cons "%d" (plist-get p :date))
9998 (cons "%m" (plist-get p :message-id)))))
9999 (when (string-match "%c" fmt)
10000 ;; Check if the user wrote this message
10001 (if (and org-from-is-user-regexp from to
10002 (save-match-data (string-match org-from-is-user-regexp from)))
10003 (setq fmt (replace-match "to %t" t t fmt))
10004 (setq fmt (replace-match "from %f" t t fmt))))
10005 (org-replace-escapes fmt table)))
10007 (defun org-make-org-heading-search-string (&optional string)
10008 "Make search string for the current headline or STRING."
10009 (let ((s (or string
10010 (and (derived-mode-p 'org-mode)
10011 (save-excursion
10012 (org-back-to-heading t)
10013 (org-element-property :raw-value (org-element-at-point))))))
10014 (lines org-context-in-file-links))
10015 (or string (setq s (concat "*" s))) ; Add * for headlines
10016 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10017 (when (and string (integerp lines) (> lines 0))
10018 (let ((slines (org-split-string s "\n")))
10019 (when (< lines (length slines))
10020 (setq s (mapconcat
10021 'identity
10022 (reverse (nthcdr (- (length slines) lines)
10023 (reverse slines))) "\n")))))
10024 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10026 (defun org-make-link-string (link &optional description)
10027 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10028 (unless (org-string-nw-p link) (error "Empty link"))
10029 (let ((uri (cond ((string-match org-link-types-re link)
10030 (concat (match-string 1 link)
10031 (org-link-escape (substring link (match-end 1)))))
10032 ;; For readability, url-encode internal links only
10033 ;; when absolutely needed (i.e, when they contain
10034 ;; square brackets). File links however, are
10035 ;; encoded since, e.g., spaces are significant.
10036 ((or (file-name-absolute-p link)
10037 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10038 (org-link-escape link))
10039 (t link)))
10040 (description
10041 (and (org-string-nw-p description)
10042 ;; Remove brackets from description, as they are fatal.
10043 (replace-regexp-in-string
10044 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10045 (org-trim description)))))
10046 (format "[[%s]%s]"
10048 (if description (format "[%s]" description) ""))))
10050 (defconst org-link-escape-chars
10051 ;;%20 %5B %5D %25
10052 '(?\s ?\[ ?\] ?%)
10053 "List of characters that should be escaped in a link when stored to Org.
10054 This is the list that is used for internal purposes.")
10056 (defun org-link-escape (text &optional table merge)
10057 "Return percent escaped representation of TEXT.
10058 TEXT is a string with the text to escape.
10059 Optional argument TABLE is a list with characters that should be
10060 escaped. When nil, `org-link-escape-chars' is used.
10061 If optional argument MERGE is set, merge TABLE into
10062 `org-link-escape-chars'."
10063 (let ((characters-to-encode
10064 (cond ((null table) org-link-escape-chars)
10065 (merge (append org-link-escape-chars table))
10066 (t table))))
10067 (mapconcat
10068 (lambda (c)
10069 (if (or (memq c characters-to-encode)
10070 (and org-url-hexify-p (or (< c 32) (> c 126))))
10071 (mapconcat (lambda (e) (format "%%%.2X" e))
10072 (or (encode-coding-char c 'utf-8)
10073 (error "Unable to percent escape character: %c" c))
10075 (char-to-string c)))
10076 text "")))
10078 (defun org-link-unescape (str)
10079 "Unhex hexified Unicode parts in string STR.
10080 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10081 reciprocal of `org-link-escape', which see."
10082 (if (org-string-nw-p str)
10083 (replace-regexp-in-string
10084 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10085 str))
10087 (defun org-link-unescape-compound (hex)
10088 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10089 Note: this function also decodes single byte encodings like
10090 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10091 (save-match-data
10092 (let* ((bytes (cdr (split-string hex "%")))
10093 (ret "")
10094 (eat 0)
10095 (sum 0))
10096 (while bytes
10097 (let* ((val (string-to-number (pop bytes) 16))
10098 (shift-xor
10099 (if (= 0 eat)
10100 (cond
10101 ((>= val 252) (cons 6 252))
10102 ((>= val 248) (cons 5 248))
10103 ((>= val 240) (cons 4 240))
10104 ((>= val 224) (cons 3 224))
10105 ((>= val 192) (cons 2 192))
10106 (t (cons 0 0)))
10107 (cons 6 128))))
10108 (when (>= val 192) (setq eat (car shift-xor)))
10109 (setq val (logxor val (cdr shift-xor)))
10110 (setq sum (+ (lsh sum (car shift-xor)) val))
10111 (when (> eat 0) (setq eat (- eat 1)))
10112 (cond
10113 ((= 0 eat) ;multi byte
10114 (setq ret (concat ret (char-to-string sum)))
10115 (setq sum 0))
10116 ((not bytes) ; single byte(s)
10117 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10118 ret)))
10120 (defun org-link-unescape-single-byte-sequence (hex)
10121 "Unhexify hex-encoded single byte character sequences."
10122 (mapconcat (lambda (byte)
10123 (char-to-string (string-to-number byte 16)))
10124 (cdr (split-string hex "%")) ""))
10126 (defun org-xor (a b)
10127 "Exclusive or."
10128 (if a (not b) b))
10130 (defun org-fixup-message-id-for-http (s)
10131 "Replace special characters in a message id, so it can be used in an http query."
10132 (when (string-match "%" s)
10133 (setq s (mapconcat (lambda (c)
10134 (if (eq c ?%)
10135 "%25"
10136 (char-to-string c)))
10137 s "")))
10138 (while (string-match "<" s)
10139 (setq s (replace-match "%3C" t t s)))
10140 (while (string-match ">" s)
10141 (setq s (replace-match "%3E" t t s)))
10142 (while (string-match "@" s)
10143 (setq s (replace-match "%40" t t s)))
10146 (defun org-link-prettify (link)
10147 "Return a human-readable representation of LINK.
10148 The car of LINK must be a raw link.
10149 The cdr of LINK must be either a link description or nil."
10150 (let ((desc (or (cadr link) "<no description>")))
10151 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10152 "<" (car link) ">")))
10154 ;;;###autoload
10155 (defun org-insert-link-global ()
10156 "Insert a link like Org mode does.
10157 This command can be called in any mode to insert a link in Org syntax."
10158 (interactive)
10159 (org-load-modules-maybe)
10160 (org-run-like-in-org-mode 'org-insert-link))
10162 (defun org-insert-all-links (arg &optional pre post)
10163 "Insert all links in `org-stored-links'.
10164 When a universal prefix, do not delete the links from `org-stored-links'.
10165 When `ARG' is a number, insert the last N link(s).
10166 `PRE' and `POST' are optional arguments to define a string to
10167 prepend or to append."
10168 (interactive "P")
10169 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10170 (links (copy-sequence org-stored-links))
10171 (pr (or pre "- "))
10172 (po (or post "\n"))
10173 (cnt 1) l)
10174 (if (null org-stored-links)
10175 (message "No link to insert")
10176 (while (and (or (listp arg) (>= arg cnt))
10177 (setq l (if (listp arg)
10178 (pop links)
10179 (pop org-stored-links))))
10180 (setq cnt (1+ cnt))
10181 (insert pr)
10182 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10183 (insert po)))))
10185 (defun org-insert-last-stored-link (arg)
10186 "Insert the last link stored in `org-stored-links'."
10187 (interactive "p")
10188 (org-insert-all-links arg "" "\n"))
10190 (defun org-link-fontify-links-to-this-file ()
10191 "Fontify links to the current file in `org-stored-links'."
10192 (let ((f (buffer-file-name)) a b)
10193 (setq a (mapcar (lambda(l)
10194 (let ((ll (car l)))
10195 (when (and (string-match "^file:\\(.+\\)::" ll)
10196 (equal f (expand-file-name (match-string 1 ll))))
10197 ll)))
10198 org-stored-links))
10199 (when (featurep 'org-id)
10200 (setq b (mapcar (lambda(l)
10201 (let ((ll (car l)))
10202 (when (and (string-match "^id:\\(.+\\)$" ll)
10203 (equal f (expand-file-name
10204 (or (org-id-find-id-file
10205 (match-string 1 ll)) ""))))
10206 ll)))
10207 org-stored-links)))
10208 (mapcar (lambda(l)
10209 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10210 (delq nil (append a b)))))
10212 (defvar org--links-history nil)
10213 (defun org-insert-link (&optional complete-file link-location default-description)
10214 "Insert a link. At the prompt, enter the link.
10216 Completion can be used to insert any of the link protocol prefixes in use.
10218 The history can be used to select a link previously stored with
10219 `org-store-link'. When the empty string is entered (i.e. if you just
10220 press `RET' at the prompt), the link defaults to the most recently
10221 stored link. As `SPC' triggers completion in the minibuffer, you need to
10222 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10224 You will also be prompted for a description, and if one is given, it will
10225 be displayed in the buffer instead of the link.
10227 If there is already a link at point, this command will allow you to edit
10228 link and description parts.
10230 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10231 file name can be
10232 selected using completion. The path to the file will be relative to the
10233 current directory if the file is in the current directory or a subdirectory.
10234 Otherwise, the link will be the absolute path as completed in the minibuffer
10235 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10236 option `org-link-file-path-type'.
10238 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10239 absolute path even if the file is in
10240 the current directory or below.
10242 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10243 prefix negates `org-keep-stored-link-after-insertion'.
10245 If `org-make-link-description-function' is non-nil, this function will be
10246 called with the link target, and the result will be the default
10247 link description.
10249 If the LINK-LOCATION parameter is non-nil, this value will be used as
10250 the link location instead of reading one interactively.
10252 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10253 as the default description."
10254 (interactive "P")
10255 (let* ((wcf (current-window-configuration))
10256 (origbuf (current-buffer))
10257 (region (when (org-region-active-p)
10258 (buffer-substring (region-beginning) (region-end))))
10259 (remove (and region (list (region-beginning) (region-end))))
10260 (desc region)
10261 (link link-location)
10262 (abbrevs org-link-abbrev-alist-local)
10263 entry all-prefixes auto-desc)
10264 (cond
10265 (link-location) ; specified by arg, just use it.
10266 ((org-in-regexp org-bracket-link-regexp 1)
10267 ;; We do have a link at point, and we are going to edit it.
10268 (setq remove (list (match-beginning 0) (match-end 0)))
10269 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10270 (setq link (read-string "Link: "
10271 (org-link-unescape
10272 (match-string-no-properties 1)))))
10273 ((or (org-in-regexp org-angle-link-re)
10274 (org-in-regexp org-plain-link-re))
10275 ;; Convert to bracket link
10276 (setq remove (list (match-beginning 0) (match-end 0))
10277 link (read-string "Link: "
10278 (org-unbracket-string "<" ">" (match-string 0)))))
10279 ((member complete-file '((4) (16)))
10280 ;; Completing read for file names.
10281 (setq link (org-file-complete-link complete-file)))
10283 ;; Read link, with completion for stored links.
10284 (org-link-fontify-links-to-this-file)
10285 (org-switch-to-buffer-other-window "*Org Links*")
10286 (with-current-buffer "*Org Links*"
10287 (erase-buffer)
10288 (insert "Insert a link.
10289 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10290 (when org-stored-links
10291 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10292 (insert (mapconcat 'org-link-prettify
10293 (reverse org-stored-links) "\n")))
10294 (goto-char (point-min)))
10295 (let ((cw (selected-window)))
10296 (select-window (get-buffer-window "*Org Links*" 'visible))
10297 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10298 (unless (pos-visible-in-window-p (point-max))
10299 (org-fit-window-to-buffer))
10300 (and (window-live-p cw) (select-window cw)))
10301 (setq all-prefixes (append (mapcar 'car abbrevs)
10302 (mapcar 'car org-link-abbrev-alist)
10303 (org-link-types)))
10304 (unwind-protect
10305 ;; Fake a link history, containing the stored links.
10306 (let ((org--links-history
10307 (append (mapcar #'car org-stored-links)
10308 org-insert-link-history)))
10309 (setq link
10310 (org-completing-read
10311 "Link: "
10312 (append
10313 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10314 (mapcar #'car org-stored-links))
10315 nil nil nil
10316 'org--links-history
10317 (caar org-stored-links)))
10318 (unless (org-string-nw-p link) (user-error "No link selected"))
10319 (dolist (l org-stored-links)
10320 (when (equal link (cadr l))
10321 (setq link (car l))
10322 (setq auto-desc t)))
10323 (when (or (member link all-prefixes)
10324 (and (equal ":" (substring link -1))
10325 (member (substring link 0 -1) all-prefixes)
10326 (setq link (substring link 0 -1))))
10327 (setq link (with-current-buffer origbuf
10328 (org-link-try-special-completion link)))))
10329 (set-window-configuration wcf)
10330 (kill-buffer "*Org Links*"))
10331 (setq entry (assoc link org-stored-links))
10332 (or entry (push link org-insert-link-history))
10333 (setq desc (or desc (nth 1 entry)))))
10335 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10336 (not org-keep-stored-link-after-insertion))
10337 (setq org-stored-links (delq (assoc link org-stored-links)
10338 org-stored-links)))
10340 (when (and (string-match org-plain-link-re link)
10341 (not (string-match org-ts-regexp link)))
10342 ;; URL-like link, normalize the use of angular brackets.
10343 (setq link (org-unbracket-string "<" ">" link)))
10345 ;; Check if we are linking to the current file with a search
10346 ;; option If yes, simplify the link by using only the search
10347 ;; option.
10348 (when (and buffer-file-name
10349 (let ((case-fold-search nil))
10350 (string-match "\\`file:\\(.+?\\)::" link)))
10351 (let ((path (match-string-no-properties 1 link))
10352 (search (substring-no-properties link (match-end 0))))
10353 (save-match-data
10354 (when (equal (file-truename buffer-file-name) (file-truename path))
10355 ;; We are linking to this same file, with a search option
10356 (setq link search)))))
10358 ;; Check if we can/should use a relative path. If yes, simplify the link
10359 (let ((case-fold-search nil))
10360 (when (string-match "\\`\\(file\\|docview\\):" link)
10361 (let* ((type (match-string-no-properties 0 link))
10362 (path (substring-no-properties link (match-end 0)))
10363 (origpath path))
10364 (cond
10365 ((or (eq org-link-file-path-type 'absolute)
10366 (equal complete-file '(16)))
10367 (setq path (abbreviate-file-name (expand-file-name path))))
10368 ((eq org-link-file-path-type 'noabbrev)
10369 (setq path (expand-file-name path)))
10370 ((eq org-link-file-path-type 'relative)
10371 (setq path (file-relative-name path)))
10373 (save-match-data
10374 (if (string-match (concat "^" (regexp-quote
10375 (expand-file-name
10376 (file-name-as-directory
10377 default-directory))))
10378 (expand-file-name path))
10379 ;; We are linking a file with relative path name.
10380 (setq path (substring (expand-file-name path)
10381 (match-end 0)))
10382 (setq path (abbreviate-file-name (expand-file-name path)))))))
10383 (setq link (concat type path))
10384 (when (equal desc origpath)
10385 (setq desc path)))))
10387 (if org-make-link-description-function
10388 (setq desc
10389 (or (condition-case nil
10390 (funcall org-make-link-description-function link desc)
10391 (error (progn (message "Can't get link description from `%s'"
10392 (symbol-name org-make-link-description-function))
10393 (sit-for 2) nil)))
10394 (read-string "Description: " default-description)))
10395 (if default-description (setq desc default-description)
10396 (setq desc (or (and auto-desc desc)
10397 (read-string "Description: " desc)))))
10399 (unless (string-match "\\S-" desc) (setq desc nil))
10400 (when remove (apply 'delete-region remove))
10401 (insert (org-make-link-string link desc))
10402 ;; Redisplay so as the new link has proper invisible characters.
10403 (sit-for 0)))
10405 (defun org-link-try-special-completion (type)
10406 "If there is completion support for link type TYPE, offer it."
10407 (let ((fun (org-link-get-parameter type :complete)))
10408 (if (functionp fun)
10409 (funcall fun)
10410 (read-string "Link (no completion support): " (concat type ":")))))
10412 (defun org-file-complete-link (&optional arg)
10413 "Create a file link using completion."
10414 (let ((file (read-file-name "File: "))
10415 (pwd (file-name-as-directory (expand-file-name ".")))
10416 (pwd1 (file-name-as-directory (abbreviate-file-name
10417 (expand-file-name ".")))))
10418 (cond ((equal arg '(16))
10419 (concat "file:"
10420 (abbreviate-file-name (expand-file-name file))))
10421 ((string-match
10422 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10423 (concat "file:" (match-string 1 file)))
10424 ((string-match
10425 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10426 (expand-file-name file))
10427 (concat "file:"
10428 (match-string 1 (expand-file-name file))))
10429 (t (concat "file:" file)))))
10431 (defun org-completing-read (&rest args)
10432 "Completing-read with SPACE being a normal character."
10433 (let ((enable-recursive-minibuffers t)
10434 (minibuffer-local-completion-map
10435 (copy-keymap minibuffer-local-completion-map)))
10436 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10437 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10438 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10439 'org-time-stamp-inactive)
10440 (apply #'completing-read args)))
10442 ;;; Opening/following a link
10444 (defvar org-link-search-failed nil)
10446 (defvar org-open-link-functions nil
10447 "Hook for functions finding a plain text link.
10448 These functions must take a single argument, the link content.
10449 They will be called for links that look like [[link text][description]]
10450 when LINK TEXT does not have a protocol like \"http:\" and does not look
10451 like a filename (e.g. \"./blue.png\").
10453 These functions will be called *before* Org attempts to resolve the
10454 link by doing text searches in the current buffer - so if you want a
10455 link \"[[target]]\" to still find \"<<target>>\", your function should
10456 handle this as a special case.
10458 When the function does handle the link, it must return a non-nil value.
10459 If it decides that it is not responsible for this link, it must return
10460 nil to indicate that that Org can continue with other options like
10461 exact and fuzzy text search.")
10463 (defun org-next-link (&optional search-backward)
10464 "Move forward to the next link.
10465 If the link is in hidden text, expose it."
10466 (interactive "P")
10467 (when (and org-link-search-failed (eq this-command last-command))
10468 (goto-char (point-min))
10469 (message "Link search wrapped back to beginning of buffer"))
10470 (setq org-link-search-failed nil)
10471 (let* ((pos (point))
10472 (ct (org-context))
10473 (a (assq :link ct))
10474 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10475 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10476 ((looking-at org-any-link-re)
10477 ;; Don't stay stuck at link without an org-link face
10478 (forward-char (if search-backward -1 1))))
10479 (if (funcall srch-fun org-any-link-re nil t)
10480 (progn
10481 (goto-char (match-beginning 0))
10482 (when (outline-invisible-p) (org-show-context)))
10483 (goto-char pos)
10484 (setq org-link-search-failed t)
10485 (message "No further link found"))))
10487 (defun org-previous-link ()
10488 "Move backward to the previous link.
10489 If the link is in hidden text, expose it."
10490 (interactive)
10491 (funcall 'org-next-link t))
10493 (defun org-translate-link (s)
10494 "Translate a link string if a translation function has been defined."
10495 (with-temp-buffer
10496 (insert (org-trim s))
10497 (org-trim (org-element-interpret-data (org-element-context)))))
10499 (defun org-translate-link-from-planner (type path)
10500 "Translate a link from Emacs Planner syntax so that Org can follow it.
10501 This is still an experimental function, your mileage may vary."
10502 (cond
10503 ((member type '("http" "https" "news" "ftp"))
10504 ;; standard Internet links are the same.
10505 nil)
10506 ((and (equal type "irc") (string-match "^//" path))
10507 ;; Planner has two / at the beginning of an irc link, we have 1.
10508 ;; We should have zero, actually....
10509 (setq path (substring path 1)))
10510 ((and (equal type "lisp") (string-match "^/" path))
10511 ;; Planner has a slash, we do not.
10512 (setq type "elisp" path (substring path 1)))
10513 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10514 ;; A typical message link. Planner has the id after the final slash,
10515 ;; we separate it with a hash mark
10516 (setq path (concat (match-string 1 path) "#"
10517 (org-unbracket-string "<" ">" (match-string 2 path))))))
10518 (cons type path))
10520 (defun org-find-file-at-mouse (ev)
10521 "Open file link or URL at mouse."
10522 (interactive "e")
10523 (mouse-set-point ev)
10524 (org-open-at-point 'in-emacs))
10526 (defun org-open-at-mouse (ev)
10527 "Open file link or URL at mouse.
10528 See the docstring of `org-open-file' for details."
10529 (interactive "e")
10530 (mouse-set-point ev)
10531 (when (eq major-mode 'org-agenda-mode)
10532 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10533 (org-open-at-point))
10535 (defvar org-window-config-before-follow-link nil
10536 "The window configuration before following a link.
10537 This is saved in case the need arises to restore it.")
10539 ;;;###autoload
10540 (defun org-open-at-point-global ()
10541 "Follow a link or time-stamp like Org mode does.
10542 This command can be called in any mode to follow an external link
10543 or a time-stamp that has Org mode syntax. Its behavior is
10544 undefined when called on internal links (e.g., fuzzy links).
10545 Raise an error when there is nothing to follow. "
10546 (interactive)
10547 (cond ((org-in-regexp org-any-link-re)
10548 (org-open-link-from-string (match-string-no-properties 0)))
10549 ((or (org-in-regexp org-ts-regexp-both nil t)
10550 (org-in-regexp org-tsr-regexp-both nil t))
10551 (org-follow-timestamp-link))
10552 (t (user-error "No link found"))))
10554 ;;;###autoload
10555 (defun org-open-link-from-string (s &optional arg reference-buffer)
10556 "Open a link in the string S, as if it was in Org mode."
10557 (interactive "sLink: \nP")
10558 (let ((reference-buffer (or reference-buffer (current-buffer))))
10559 (with-temp-buffer
10560 (let ((org-inhibit-startup (not reference-buffer)))
10561 (org-mode)
10562 (insert s)
10563 (goto-char (point-min))
10564 (when reference-buffer
10565 (setq org-link-abbrev-alist-local
10566 (with-current-buffer reference-buffer
10567 org-link-abbrev-alist-local)))
10568 (org-open-at-point arg reference-buffer)))))
10570 (defvar org-open-at-point-functions nil
10571 "Hook that is run when following a link at point.
10573 Functions in this hook must return t if they identify and follow
10574 a link at point. If they don't find anything interesting at point,
10575 they must return nil.")
10577 (defvar org-link-search-inhibit-query nil)
10578 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10579 (defun org--open-doi-link (path)
10580 "Open a \"doi\" type link.
10581 PATH is a the path to search for, as a string."
10582 (browse-url (url-encode-url (concat org-doi-server-url path))))
10584 (defun org--open-elisp-link (path)
10585 "Open a \"elisp\" type link.
10586 PATH is the sexp to evaluate, as a string."
10587 (let ((cmd path))
10588 (if (or (and (org-string-nw-p
10589 org-confirm-elisp-link-not-regexp)
10590 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10591 (not org-confirm-elisp-link-function)
10592 (funcall org-confirm-elisp-link-function
10593 (format "Execute \"%s\" as elisp? "
10594 (org-add-props cmd nil 'face 'org-warning))))
10595 (message "%s => %s" cmd
10596 (if (eq (string-to-char cmd) ?\()
10597 (eval (read cmd))
10598 (call-interactively (read cmd))))
10599 (user-error "Abort"))))
10601 (defun org--open-help-link (path)
10602 "Open a \"help\" type link.
10603 PATH is a symbol name, as a string."
10604 (pcase (intern path)
10605 ((and (pred fboundp) variable) (describe-function variable))
10606 ((and (pred boundp) function) (describe-variable function))
10607 (name (user-error "Unknown function or variable: %s" name))))
10609 (defun org--open-shell-link (path)
10610 "Open a \"shell\" type link.
10611 PATH is the command to execute, as a string."
10612 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10613 (cmd path))
10614 (if (or (and (org-string-nw-p
10615 org-confirm-shell-link-not-regexp)
10616 (string-match
10617 org-confirm-shell-link-not-regexp cmd))
10618 (not org-confirm-shell-link-function)
10619 (funcall org-confirm-shell-link-function
10620 (format "Execute \"%s\" in shell? "
10621 (org-add-props cmd nil
10622 'face 'org-warning))))
10623 (progn
10624 (message "Executing %s" cmd)
10625 (shell-command cmd buf)
10626 (when (featurep 'midnight)
10627 (setq clean-buffer-list-kill-buffer-names
10628 (cons (buffer-name buf)
10629 clean-buffer-list-kill-buffer-names))))
10630 (user-error "Abort"))))
10632 (defun org-open-at-point (&optional arg reference-buffer)
10633 "Open link, timestamp, footnote or tags at point.
10635 When point is on a link, follow it. Normally, files will be
10636 opened by an appropriate application. If the optional prefix
10637 argument ARG is non-nil, Emacs will visit the file. With
10638 a double prefix argument, try to open outside of Emacs, in the
10639 application the system uses for this file type.
10641 When point is on a timestamp, open the agenda at the day
10642 specified.
10644 When point is a footnote definition, move to the first reference
10645 found. If it is on a reference, move to the associated
10646 definition.
10648 When point is on a headline, display a list of every link in the
10649 entry, so it is possible to pick one, or all, of them. If point
10650 is on a tag, call `org-tags-view' instead.
10652 When optional argument REFERENCE-BUFFER is non-nil, it should
10653 specify a buffer from where the link search should happen. This
10654 is used internally by `org-open-link-from-string'.
10656 On top of syntactically correct links, this function will open
10657 the link at point in comments or comment blocks and the first
10658 link in a property drawer line."
10659 (interactive "P")
10660 ;; On a code block, open block's results.
10661 (unless (call-interactively 'org-babel-open-src-block-result)
10662 (org-load-modules-maybe)
10663 (setq org-window-config-before-follow-link (current-window-configuration))
10664 (org-remove-occur-highlights nil nil t)
10665 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10666 (let* ((context
10667 ;; Only consider supported types, even if they are not
10668 ;; the closest one.
10669 (org-element-lineage
10670 (org-element-context)
10671 '(clock comment comment-block footnote-definition
10672 footnote-reference headline inlinetask keyword link
10673 node-property timestamp)
10675 (type (org-element-type context))
10676 (value (org-element-property :value context)))
10677 (cond
10678 ((not context) (user-error "No link found"))
10679 ;; Exception: open timestamps and links in properties
10680 ;; drawers, keywords and comments.
10681 ((memq type '(comment comment-block keyword node-property))
10682 (call-interactively #'org-open-at-point-global))
10683 ;; On a headline or an inlinetask, but not on a timestamp,
10684 ;; a link, a footnote reference or on tags.
10685 ((and (memq type '(headline inlinetask))
10686 ;; Not on tags.
10687 (let ((case-fold-search nil))
10688 (save-excursion
10689 (beginning-of-line)
10690 (looking-at org-complex-heading-regexp))
10691 (or (not (match-beginning 5))
10692 (< (point) (match-beginning 5)))))
10693 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10694 (links (car data))
10695 (links-end (cdr data)))
10696 (if links
10697 (dolist (link (if (stringp links) (list links) links))
10698 (search-forward link nil links-end)
10699 (goto-char (match-beginning 0))
10700 (org-open-at-point))
10701 (require 'org-attach)
10702 (org-attach-reveal 'if-exists))))
10703 ;; On a clock line, make sure point is on the timestamp
10704 ;; before opening it.
10705 ((and (eq type 'clock)
10706 value
10707 (>= (point) (org-element-property :begin value))
10708 (<= (point) (org-element-property :end value)))
10709 (org-follow-timestamp-link))
10710 ;; Do nothing on white spaces after an object.
10711 ((>= (point)
10712 (save-excursion
10713 (goto-char (org-element-property :end context))
10714 (skip-chars-backward " \t")
10715 (point)))
10716 (user-error "No link found"))
10717 ((eq type 'timestamp) (org-follow-timestamp-link))
10718 ;; On tags within a headline or an inlinetask.
10719 ((and (memq type '(headline inlinetask))
10720 (let ((case-fold-search nil))
10721 (save-excursion (beginning-of-line)
10722 (looking-at org-complex-heading-regexp))
10723 (and (match-beginning 5)
10724 (>= (point) (match-beginning 5)))))
10725 (org-tags-view arg (substring (match-string 5) 0 -1)))
10726 ((eq type 'link)
10727 (let ((type (org-element-property :type context))
10728 (path (org-link-unescape (org-element-property :path context))))
10729 ;; Switch back to REFERENCE-BUFFER needed when called in
10730 ;; a temporary buffer through `org-open-link-from-string'.
10731 (with-current-buffer (or reference-buffer (current-buffer))
10732 (cond
10733 ((equal type "file")
10734 (if (string-match "[*?{]" (file-name-nondirectory path))
10735 (dired path)
10736 ;; Look into `org-link-parameters' in order to find
10737 ;; a DEDICATED-FUNCTION to open file. The function
10738 ;; will be applied on raw link instead of parsed
10739 ;; link due to the limitation in `org-add-link-type'
10740 ;; ("open" function called with a single argument).
10741 ;; If no such function is found, fallback to
10742 ;; `org-open-file'.
10743 (let* ((option (org-element-property :search-option context))
10744 (app (org-element-property :application context))
10745 (dedicated-function
10746 (org-link-get-parameter
10747 (if app (concat type "+" app) type)
10748 :follow)))
10749 (if dedicated-function
10750 (funcall dedicated-function
10751 (concat path
10752 (and option (concat "::" option))))
10753 (apply #'org-open-file
10754 path
10755 (cond (arg)
10756 ((equal app "emacs") 'emacs)
10757 ((equal app "sys") 'system))
10758 (cond ((not option) nil)
10759 ((string-match-p "\\`[0-9]+\\'" option)
10760 (list (string-to-number option)))
10761 (t (list nil
10762 (org-link-unescape option)))))))))
10763 ((functionp (org-link-get-parameter type :follow))
10764 (funcall (org-link-get-parameter type :follow) path))
10765 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10766 (unless (run-hook-with-args-until-success
10767 'org-open-link-functions path)
10768 (if (not arg) (org-mark-ring-push)
10769 (switch-to-buffer-other-window
10770 (org-get-buffer-for-internal-link (current-buffer))))
10771 (let ((destination
10772 (org-with-wide-buffer
10773 (if (equal type "radio")
10774 (org-search-radio-target
10775 (org-element-property :path context))
10776 (org-link-search
10777 (if (member type '("custom-id" "coderef"))
10778 (org-element-property :raw-link context)
10779 path)
10780 ;; Prevent fuzzy links from matching
10781 ;; themselves.
10782 (and (equal type "fuzzy")
10783 (+ 2 (org-element-property :begin context)))))
10784 (point))))
10785 (unless (and (<= (point-min) destination)
10786 (>= (point-max) destination))
10787 (widen))
10788 (goto-char destination))))
10789 (t (browse-url-at-point))))))
10790 ;; On a footnote reference or at a footnote definition's label.
10791 ((or (eq type 'footnote-reference)
10792 (and (eq type 'footnote-definition)
10793 (save-excursion
10794 ;; Do not validate action when point is on the
10795 ;; spaces right after the footnote label, in
10796 ;; order to be on par with behaviour on links.
10797 (skip-chars-forward " \t")
10798 (let ((begin
10799 (org-element-property :contents-begin context)))
10800 (if begin (< (point) begin)
10801 (= (org-element-property :post-affiliated context)
10802 (line-beginning-position)))))))
10803 (org-footnote-action))
10804 (t (user-error "No link found")))))
10805 (run-hook-with-args 'org-follow-link-hook)))
10807 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10808 "Offer links in the current entry and return the selected link.
10809 If there is only one link, return it.
10810 If NTH is an integer, return the NTH link found.
10811 If ZERO is a string, check also this string for a link, and if
10812 there is one, return it."
10813 (with-current-buffer buffer
10814 (org-with-wide-buffer
10815 (goto-char marker)
10816 (let ((cnt ?0)
10817 have-zero end links link c)
10818 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10819 (push (match-string 0 zero) links)
10820 (setq cnt (1- cnt) have-zero t))
10821 (save-excursion
10822 (org-back-to-heading t)
10823 (setq end (save-excursion (outline-next-heading) (point)))
10824 (while (re-search-forward org-any-link-re end t)
10825 (push (match-string 0) links))
10826 (setq links (org-uniquify (reverse links))))
10827 (cond
10828 ((null links)
10829 (message "No links"))
10830 ((equal (length links) 1)
10831 (setq link (car links)))
10832 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10833 (setq link (nth (if have-zero nth (1- nth)) links)))
10834 (t ; we have to select a link
10835 (save-excursion
10836 (save-window-excursion
10837 (delete-other-windows)
10838 (with-output-to-temp-buffer "*Select Link*"
10839 (dolist (l links)
10840 (cond
10841 ((not (string-match org-bracket-link-regexp l))
10842 (princ (format "[%c] %s\n" (cl-incf cnt)
10843 (org-unbracket-string "<" ">" l))))
10844 ((match-end 3)
10845 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10846 (match-string 3 l) (match-string 1 l))))
10847 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10848 (match-string 1 l)))))))
10849 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10850 (message "Select link to open, RET to open all:")
10851 (setq c (read-char-exclusive))
10852 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10853 (when (equal c ?q) (user-error "Abort"))
10854 (if (equal c ?\C-m)
10855 (setq link links)
10856 (setq nth (- c ?0))
10857 (when have-zero (setq nth (1+ nth)))
10858 (unless (and (integerp nth) (>= (length links) nth))
10859 (user-error "Invalid link selection"))
10860 (setq link (nth (1- nth) links)))))
10861 (cons link end)))))
10863 ;; TODO: These functions are deprecated since `org-open-at-point'
10864 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10865 (defun org-open-file-with-system (path)
10866 "Open file at PATH using the system way of opening it."
10867 (org-open-file path 'system))
10868 (defun org-open-file-with-emacs (path)
10869 "Open file at PATH in Emacs."
10870 (org-open-file path 'emacs))
10873 ;;; File search
10875 (defvar org-create-file-search-functions nil
10876 "List of functions to construct the right search string for a file link.
10877 These functions are called in turn with point at the location to
10878 which the link should point.
10880 A function in the hook should first test if it would like to
10881 handle this file type, for example by checking the `major-mode'
10882 or the file extension. If it decides not to handle this file, it
10883 should just return nil to give other functions a chance. If it
10884 does handle the file, it must return the search string to be used
10885 when following the link. The search string will be part of the
10886 file link, given after a double colon, and `org-open-at-point'
10887 will automatically search for it. If special measures must be
10888 taken to make the search successful, another function should be
10889 added to the companion hook `org-execute-file-search-functions',
10890 which see.
10892 A function in this hook may also use `setq' to set the variable
10893 `description' to provide a suggestion for the descriptive text to
10894 be used for this link when it gets inserted into an Org buffer
10895 with \\[org-insert-link].")
10897 (defvar org-execute-file-search-functions nil
10898 "List of functions to execute a file search triggered by a link.
10900 Functions added to this hook must accept a single argument, the
10901 search string that was part of the file link, the part after the
10902 double colon. The function must first check if it would like to
10903 handle this search, for example by checking the `major-mode' or
10904 the file extension. If it decides not to handle this search, it
10905 should just return nil to give other functions a chance. If it
10906 does handle the search, it must return a non-nil value to keep
10907 other functions from trying.
10909 Each function can access the current prefix argument through the
10910 variable `current-prefix-arg'. Note that a single prefix is used
10911 to force opening a link in Emacs, so it may be good to only use a
10912 numeric or double prefix to guide the search function.
10914 In case this is needed, a function in this hook can also restore
10915 the window configuration before `org-open-at-point' was called using:
10917 (set-window-configuration org-window-config-before-follow-link)")
10919 (defun org-search-radio-target (target)
10920 "Search a radio target matching TARGET in current buffer.
10921 White spaces are not significant."
10922 (let ((re (format "<<<%s>>>"
10923 (mapconcat #'regexp-quote
10924 (org-split-string target "[ \t\n]+")
10925 "[ \t]+\\(?:\n[ \t]*\\)?")))
10926 (origin (point)))
10927 (goto-char (point-min))
10928 (catch :radio-match
10929 (while (re-search-forward re nil t)
10930 (backward-char)
10931 (let ((object (org-element-context)))
10932 (when (eq (org-element-type object) 'radio-target)
10933 (goto-char (org-element-property :begin object))
10934 (org-show-context 'link-search)
10935 (throw :radio-match nil))))
10936 (goto-char origin)
10937 (user-error "No match for radio target: %s" target))))
10939 (defun org-link-search (s &optional avoid-pos stealth)
10940 "Search for a search string S.
10942 If S starts with \"#\", it triggers a custom ID search.
10944 If S is enclosed within parenthesis, it initiates a coderef
10945 search.
10947 If S is surrounded by forward slashes, it is interpreted as
10948 a regular expression. In Org mode files, this will create an
10949 `org-occur' sparse tree. In ordinary files, `occur' will be used
10950 to list matches. If the current buffer is in `dired-mode', grep
10951 will be used to search in all files.
10953 When AVOID-POS is given, ignore matches near that position.
10955 When optional argument STEALTH is non-nil, do not modify
10956 visibility around point, thus ignoring `org-show-context-detail'
10957 variable.
10959 Search is case-insensitive and ignores white spaces. Return type
10960 of matched result, which is either `dedicated' or `fuzzy'."
10961 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10962 (let* ((case-fold-search t)
10963 (origin (point))
10964 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10965 (starred (eq (string-to-char normalized) ?*))
10966 (words (split-string (if starred (substring s 1) s)))
10967 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10968 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10969 type)
10970 (cond
10971 ;; Check if there are any special search functions.
10972 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10973 ((eq (string-to-char s) ?#)
10974 ;; Look for a custom ID S if S starts with "#".
10975 (let* ((id (substring normalized 1))
10976 (match (org-find-property "CUSTOM_ID" id)))
10977 (if match (progn (goto-char match) (setf type 'dedicated))
10978 (error "No match for custom ID: %s" id))))
10979 ((string-match "\\`(\\(.*\\))\\'" normalized)
10980 ;; Look for coderef targets if S is enclosed within parenthesis.
10981 (let ((coderef (match-string-no-properties 1 normalized))
10982 (re (substring s-single-re 1 -1)))
10983 (goto-char (point-min))
10984 (catch :coderef-match
10985 (while (re-search-forward re nil t)
10986 (let ((element (org-element-at-point)))
10987 (when (and (memq (org-element-type element)
10988 '(example-block src-block))
10989 ;; Build proper regexp according to current
10990 ;; block's label format.
10991 (let ((label-fmt
10992 (regexp-quote
10993 (or (org-element-property :label-fmt element)
10994 org-coderef-label-format))))
10995 (save-excursion
10996 (beginning-of-line)
10997 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10998 (format label-fmt coderef))))))
10999 (setq type 'dedicated)
11000 (goto-char (match-beginning 1))
11001 (throw :coderef-match nil))))
11002 (goto-char origin)
11003 (error "No match for coderef: %s" coderef))))
11004 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11005 ;; Look for a regular expression.
11006 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11007 (match-string 1 s)))
11008 ;; From here, we handle fuzzy links.
11010 ;; Look for targets, only if not in a headline search.
11011 ((and (not starred)
11012 (let ((target (format "<<%s>>" s-multi-re)))
11013 (catch :target-match
11014 (goto-char (point-min))
11015 (while (re-search-forward target nil t)
11016 (backward-char)
11017 (let ((context (org-element-context)))
11018 (when (eq (org-element-type context) 'target)
11019 (setq type 'dedicated)
11020 (goto-char (org-element-property :begin context))
11021 (throw :target-match t))))
11022 nil))))
11023 ;; Look for elements named after S, only if not in a headline
11024 ;; search.
11025 ((and (not starred)
11026 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11027 (catch :name-match
11028 (goto-char (point-min))
11029 (while (re-search-forward name nil t)
11030 (let ((element (org-element-at-point)))
11031 (when (equal words
11032 (split-string
11033 (org-element-property :name element)))
11034 (setq type 'dedicated)
11035 (beginning-of-line)
11036 (throw :name-match t))))
11037 nil))))
11038 ;; Regular text search. Prefer headlines in Org mode buffers.
11039 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11040 ;; statistics cookies and tags.
11041 ((and (derived-mode-p 'org-mode)
11042 (let ((title-re
11043 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11044 org-outline-regexp-bol
11045 org-comment-string
11046 (mapconcat #'regexp-quote words ".+")))
11047 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11048 (comment-re (eval-when-compile
11049 (format "\\`%s[ \t]+" org-comment-string))))
11050 (goto-char (point-min))
11051 (catch :found
11052 (while (re-search-forward title-re nil t)
11053 (when (equal words
11054 (split-string
11055 (replace-regexp-in-string
11056 cookie-re ""
11057 (replace-regexp-in-string
11058 comment-re "" (org-get-heading t t t)))))
11059 (throw :found t)))
11060 nil)))
11061 (beginning-of-line)
11062 (setq type 'dedicated))
11063 ;; Offer to create non-existent headline depending on
11064 ;; `org-link-search-must-match-exact-headline'.
11065 ((and (derived-mode-p 'org-mode)
11066 (not org-link-search-inhibit-query)
11067 (eq org-link-search-must-match-exact-headline 'query-to-create)
11068 (yes-or-no-p "No match - create this as a new heading? "))
11069 (goto-char (point-max))
11070 (unless (bolp) (newline))
11071 (org-insert-heading nil t t)
11072 (insert s "\n")
11073 (beginning-of-line 0))
11074 ;; Only headlines are looked after. No need to process
11075 ;; further: throw an error.
11076 ((and (derived-mode-p 'org-mode)
11077 (or starred org-link-search-must-match-exact-headline))
11078 (goto-char origin)
11079 (error "No match for fuzzy expression: %s" normalized))
11080 ;; Regular text search.
11081 ((catch :fuzzy-match
11082 (goto-char (point-min))
11083 (while (re-search-forward s-multi-re nil t)
11084 ;; Skip match if it contains AVOID-POS or it is included in
11085 ;; a link with a description but outside the description.
11086 (unless (or (and avoid-pos
11087 (<= (match-beginning 0) avoid-pos)
11088 (> (match-end 0) avoid-pos))
11089 (and (save-match-data
11090 (org-in-regexp org-bracket-link-regexp))
11091 (match-beginning 3)
11092 (or (> (match-beginning 3) (point))
11093 (<= (match-end 3) (point)))
11094 (org-element-lineage
11095 (save-match-data (org-element-context))
11096 '(link) t)))
11097 (goto-char (match-beginning 0))
11098 (setq type 'fuzzy)
11099 (throw :fuzzy-match t)))
11100 nil))
11101 ;; All failed. Throw an error.
11102 (t (goto-char origin)
11103 (error "No match for fuzzy expression: %s" normalized)))
11104 ;; Disclose surroundings of match, if appropriate.
11105 (when (and (derived-mode-p 'org-mode) (not stealth))
11106 (org-show-context 'link-search))
11107 type))
11109 (defun org-get-buffer-for-internal-link (buffer)
11110 "Return a buffer to be used for displaying the link target of internal links."
11111 (cond
11112 ((not org-display-internal-link-with-indirect-buffer)
11113 buffer)
11114 ((string-suffix-p "(Clone)" (buffer-name buffer))
11115 (message "Buffer is already a clone, not making another one")
11116 ;; we also do not modify visibility in this case
11117 buffer)
11118 (t ; make a new indirect buffer for displaying the link
11119 (let* ((bn (buffer-name buffer))
11120 (ibn (concat bn "(Clone)"))
11121 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11122 (with-current-buffer ib (org-overview))
11123 ib))))
11125 (defun org-do-occur (regexp &optional cleanup)
11126 "Call the Emacs command `occur'.
11127 If CLEANUP is non-nil, remove the printout of the regular expression
11128 in the *Occur* buffer. This is useful if the regex is long and not useful
11129 to read."
11130 (occur regexp)
11131 (when cleanup
11132 (let ((cwin (selected-window)) win beg end)
11133 (when (setq win (get-buffer-window "*Occur*"))
11134 (select-window win))
11135 (goto-char (point-min))
11136 (when (re-search-forward "match[a-z]+" nil t)
11137 (setq beg (match-end 0))
11138 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11139 (setq end (1- (match-beginning 0)))))
11140 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11141 (goto-char (point-min))
11142 (select-window cwin))))
11144 ;;; The mark ring for links jumps
11146 (defvar org-mark-ring nil
11147 "Mark ring for positions before jumps in Org mode.")
11148 (defvar org-mark-ring-last-goto nil
11149 "Last position in the mark ring used to go back.")
11150 ;; Fill and close the ring
11151 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11152 (dotimes (_ org-mark-ring-length)
11153 (push (make-marker) org-mark-ring))
11154 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11155 org-mark-ring)
11157 (defun org-mark-ring-push (&optional pos buffer)
11158 "Put the current position or POS into the mark ring and rotate it."
11159 (interactive)
11160 (setq pos (or pos (point)))
11161 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11162 (move-marker (car org-mark-ring)
11163 (or pos (point))
11164 (or buffer (current-buffer)))
11165 (message "%s"
11166 (substitute-command-keys
11167 "Position saved to mark ring, go back with \
11168 `\\[org-mark-ring-goto]'.")))
11170 (defun org-mark-ring-goto (&optional n)
11171 "Jump to the previous position in the mark ring.
11172 With prefix arg N, jump back that many stored positions. When
11173 called several times in succession, walk through the entire ring.
11174 Org mode commands jumping to a different position in the current file,
11175 or to another Org file, automatically push the old position onto the ring."
11176 (interactive "p")
11177 (let (p m)
11178 (if (eq last-command this-command)
11179 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11180 (setq p org-mark-ring))
11181 (setq org-mark-ring-last-goto p)
11182 (setq m (car p))
11183 (pop-to-buffer-same-window (marker-buffer m))
11184 (goto-char m)
11185 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11187 (defun org-add-angle-brackets (s)
11188 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11189 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11192 ;;; Following specific links
11194 (defvar org-agenda-buffer-tmp-name)
11195 (defvar org-agenda-start-on-weekday)
11196 (defun org-follow-timestamp-link ()
11197 "Open an agenda view for the time-stamp date/range at point."
11198 (cond
11199 ((org-at-date-range-p t)
11200 (let ((org-agenda-start-on-weekday)
11201 (t1 (match-string 1))
11202 (t2 (match-string 2)) tt1 tt2)
11203 (setq tt1 (time-to-days (org-time-string-to-time t1))
11204 tt2 (time-to-days (org-time-string-to-time t2)))
11205 (let ((org-agenda-buffer-tmp-name
11206 (format "*Org Agenda(a:%s)"
11207 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11208 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11209 ((org-at-timestamp-p 'lax)
11210 (let ((org-agenda-buffer-tmp-name
11211 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11212 (org-agenda-list nil (time-to-days (org-time-string-to-time
11213 (substring (match-string 1) 0 10)))
11214 1)))
11215 (t (error "This should not happen"))))
11218 ;;; Following file links
11219 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11220 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11221 (declare-function mailcap-mime-info
11222 "mailcap" (string &optional request no-decode))
11223 (defvar org-wait nil)
11224 (defun org-open-file (path &optional in-emacs line search)
11225 "Open the file at PATH.
11226 First, this expands any special file name abbreviations. Then the
11227 configuration variable `org-file-apps' is checked if it contains an
11228 entry for this file type, and if yes, the corresponding command is launched.
11230 If no application is found, Emacs simply visits the file.
11232 With optional prefix argument IN-EMACS, Emacs will visit the file.
11233 With a double \\[universal-argument] \\[universal-argument] \
11234 prefix arg, Org tries to avoid opening in Emacs
11235 and to use an external application to visit the file.
11237 Optional LINE specifies a line to go to, optional SEARCH a string
11238 to search for. If LINE or SEARCH is given, the file will be
11239 opened in Emacs, unless an entry from org-file-apps that makes
11240 use of groups in a regexp matches.
11242 If you want to change the way frames are used when following a
11243 link, please customize `org-link-frame-setup'.
11245 If the file does not exist, an error is thrown."
11246 (let* ((file (if (equal path "")
11247 buffer-file-name
11248 (substitute-in-file-name (expand-file-name path))))
11249 (file-apps (append org-file-apps (org-default-apps)))
11250 (apps (cl-remove-if
11251 'org-file-apps-entry-match-against-dlink-p file-apps))
11252 (apps-dlink (cl-remove-if-not
11253 'org-file-apps-entry-match-against-dlink-p file-apps))
11254 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11255 (dirp (unless remp (file-directory-p file)))
11256 (file (if (and dirp org-open-directory-means-index-dot-org)
11257 (concat (file-name-as-directory file) "index.org")
11258 file))
11259 (a-m-a-p (assq 'auto-mode apps))
11260 (dfile (downcase file))
11261 ;; Reconstruct the original link from the PATH, LINE and
11262 ;; SEARCH args.
11263 (link (cond (line (concat file "::" (number-to-string line)))
11264 (search (concat file "::" search))
11265 (t file)))
11266 (dlink (downcase link))
11267 (ext
11268 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11269 (match-string 1 dfile)))
11270 (save-position-maybe
11271 (let ((old-buffer (current-buffer))
11272 (old-pos (point))
11273 (old-mode major-mode))
11274 (lambda ()
11275 (and (derived-mode-p 'org-mode)
11276 (eq old-mode 'org-mode)
11277 (or (not (eq old-buffer (current-buffer)))
11278 (not (eq old-pos (point))))
11279 (org-mark-ring-push old-pos old-buffer)))))
11280 cmd link-match-data)
11281 (cond
11282 ((member in-emacs '((16) system))
11283 (setq cmd (cdr (assq 'system apps))))
11284 (in-emacs (setq cmd 'emacs))
11286 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11287 (and dirp (cdr (assq 'directory apps)))
11288 ;; First, try matching against apps-dlink if we
11289 ;; get a match here, store the match data for
11290 ;; later.
11291 (let ((match (assoc-default dlink apps-dlink
11292 'string-match)))
11293 (if match
11294 (progn (setq link-match-data (match-data))
11295 match)
11296 (progn (setq in-emacs (or in-emacs line search))
11297 nil))) ; if we have no match in apps-dlink,
11298 ; always open the file in emacs if line or search
11299 ; is given (for backwards compatibility)
11300 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11301 'string-match)
11302 (cdr (assoc ext apps))
11303 (cdr (assq t apps))))))
11304 (when (eq cmd 'system)
11305 (setq cmd (cdr (assq 'system apps))))
11306 (when (eq cmd 'default)
11307 (setq cmd (cdr (assoc t apps))))
11308 (when (eq cmd 'mailcap)
11309 (require 'mailcap)
11310 (mailcap-parse-mailcaps)
11311 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11312 (command (mailcap-mime-info mime-type)))
11313 (if (stringp command)
11314 (setq cmd command)
11315 (setq cmd 'emacs))))
11316 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11317 (not (file-exists-p file))
11318 (not org-open-non-existing-files))
11319 (user-error "No such file: %s" file))
11320 (cond
11321 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11322 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11323 (while (string-match "['\"]%s['\"]" cmd)
11324 (setq cmd (replace-match "%s" t t cmd)))
11325 (setq cmd (replace-regexp-in-string
11326 "%s"
11327 (shell-quote-argument (convert-standard-filename file))
11329 nil t))
11331 ;; Replace "%1", "%2" etc. in command with group matches from regex
11332 (save-match-data
11333 (let ((match-index 1)
11334 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11335 (set-match-data link-match-data)
11336 (while (<= match-index number-of-groups)
11337 (let ((regex (concat "%" (number-to-string match-index)))
11338 (replace-with (match-string match-index dlink)))
11339 (while (string-match regex cmd)
11340 (setq cmd (replace-match replace-with t t cmd))))
11341 (setq match-index (+ match-index 1)))))
11343 (save-window-excursion
11344 (message "Running %s...done" cmd)
11345 (start-process-shell-command cmd nil cmd)
11346 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11347 ((or (stringp cmd)
11348 (eq cmd 'emacs))
11349 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11350 (widen)
11351 (cond (line (org-goto-line line)
11352 (when (derived-mode-p 'org-mode) (org-reveal)))
11353 (search (condition-case err
11354 (org-link-search search)
11355 ;; Save position before error-ing out so user
11356 ;; can easily move back to the original buffer.
11357 (error (funcall save-position-maybe)
11358 (error (nth 1 err)))))))
11359 ((functionp cmd)
11360 (save-match-data
11361 (set-match-data link-match-data)
11362 (condition-case nil
11363 (funcall cmd file link)
11364 ;; FIXME: Remove this check when most default installations
11365 ;; of Emacs have at least Org 9.0.
11366 ((debug wrong-number-of-arguments wrong-type-argument
11367 invalid-function)
11368 (user-error "Please see Org News for version 9.0 about \
11369 `org-file-apps'--Lisp error: %S" cmd)))))
11370 ((consp cmd)
11371 ;; FIXME: Remove this check when most default installations of
11372 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11373 ;; fall back to `org-link-frame-setup' for an old usage of
11374 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11375 (user-error "Please see Org News for version 9.0 about \
11376 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11377 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11378 (funcall save-position-maybe)))
11380 (defun org-file-apps-entry-match-against-dlink-p (entry)
11381 "This function returns non-nil if `entry' uses a regular
11382 expression which should be matched against the whole link by
11383 org-open-file.
11385 It assumes that is the case when the entry uses a regular
11386 expression which has at least one grouping construct and the
11387 action is either a lisp form or a command string containing
11388 `%1', i.e. using at least one subexpression match as a
11389 parameter."
11390 (let ((selector (car entry))
11391 (action (cdr entry)))
11392 (if (stringp selector)
11393 (and (> (regexp-opt-depth selector) 0)
11394 (or (and (stringp action)
11395 (string-match "%[0-9]" action))
11396 (consp action)))
11397 nil)))
11399 (defun org-default-apps ()
11400 "Return the default applications for this operating system."
11401 (cond
11402 ((eq system-type 'darwin)
11403 org-file-apps-defaults-macosx)
11404 ((eq system-type 'windows-nt)
11405 org-file-apps-defaults-windowsnt)
11406 (t org-file-apps-defaults-gnu)))
11408 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11409 "Convert extensions to regular expressions in the cars of LIST.
11410 Also, weed out any non-string entries, because the return value is used
11411 only for regexp matching.
11412 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11413 point to the symbol `emacs', indicating that the file should
11414 be opened in Emacs."
11415 (append
11416 (delq nil
11417 (mapcar (lambda (x)
11418 (unless (not (stringp (car x)))
11419 (if (string-match "\\W" (car x))
11421 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11422 list))
11423 (when add-auto-mode
11424 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11426 (defvar ange-ftp-name-format)
11427 (defun org-file-remote-p (file)
11428 "Test whether FILE specifies a location on a remote system.
11429 Return non-nil if the location is indeed remote.
11431 For example, the filename \"/user@host:/foo\" specifies a location
11432 on the system \"/user@host:\"."
11433 (cond ((fboundp 'file-remote-p)
11434 (file-remote-p file))
11435 ((fboundp 'tramp-handle-file-remote-p)
11436 (tramp-handle-file-remote-p file))
11437 ((and (boundp 'ange-ftp-name-format)
11438 (string-match (car ange-ftp-name-format) file))
11439 t)))
11442 ;;;; Refiling
11444 (defun org-get-org-file ()
11445 "Read a filename, with default directory `org-directory'."
11446 (let ((default (or org-default-notes-file remember-data-file)))
11447 (read-file-name (format "File name [%s]: " default)
11448 (file-name-as-directory org-directory)
11449 default)))
11451 (defun org-notes-order-reversed-p ()
11452 "Check if the current file should receive notes in reversed order."
11453 (cond
11454 ((not org-reverse-note-order) nil)
11455 ((eq t org-reverse-note-order) t)
11456 ((not (listp org-reverse-note-order)) nil)
11457 (t (catch 'exit
11458 (dolist (entry org-reverse-note-order)
11459 (when (string-match (car entry) buffer-file-name)
11460 (throw 'exit (cdr entry))))))))
11462 (defvar org-refile-target-table nil
11463 "The list of refile targets, created by `org-refile'.")
11465 (defvar org-agenda-new-buffers nil
11466 "Buffers created to visit agenda files.")
11468 (defvar org-refile-cache nil
11469 "Cache for refile targets.")
11471 (defvar org-refile-markers nil
11472 "All the markers used for caching refile locations.")
11474 (defun org-refile-marker (pos)
11475 "Get a new refile marker, but only if caching is in use."
11476 (if (not org-refile-use-cache)
11478 (let ((m (make-marker)))
11479 (move-marker m pos)
11480 (push m org-refile-markers)
11481 m)))
11483 (defun org-refile-cache-clear ()
11484 "Clear the refile cache and disable all the markers."
11485 (dolist (m org-refile-markers) (move-marker m nil))
11486 (setq org-refile-markers nil)
11487 (setq org-refile-cache nil)
11488 (message "Refile cache has been cleared"))
11490 (defun org-refile-cache-check-set (set)
11491 "Check if all the markers in the cache still have live buffers."
11492 (let (marker)
11493 (catch 'exit
11494 (while (and set (setq marker (nth 3 (pop set))))
11495 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11496 (when (and marker (null (marker-buffer marker)))
11497 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11498 (sit-for 3)
11499 (throw 'exit nil)))
11500 t)))
11502 (defun org-refile-cache-put (set &rest identifiers)
11503 "Push the refile targets SET into the cache, under IDENTIFIERS."
11504 (let* ((key (sha1 (prin1-to-string identifiers)))
11505 (entry (assoc key org-refile-cache)))
11506 (if entry
11507 (setcdr entry set)
11508 (push (cons key set) org-refile-cache))))
11510 (defun org-refile-cache-get (&rest identifiers)
11511 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11512 (cond
11513 ((not org-refile-cache) nil)
11514 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11516 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11517 org-refile-cache))))
11518 (and set (org-refile-cache-check-set set) set)))))
11520 (defvar org-outline-path-cache nil
11521 "Alist between buffer positions and outline paths.
11522 It value is an alist (POSITION . PATH) where POSITION is the
11523 buffer position at the beginning of an entry and PATH is a list
11524 of strings describing the outline path for that entry, in reverse
11525 order.")
11527 (defun org-refile-get-targets (&optional default-buffer)
11528 "Produce a table with refile targets."
11529 (let ((case-fold-search nil)
11530 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11531 (entries (or org-refile-targets '((nil . (:level . 1)))))
11532 targets tgs files desc descre)
11533 (message "Getting targets...")
11534 (with-current-buffer (or default-buffer (current-buffer))
11535 (dolist (entry entries)
11536 (setq files (car entry) desc (cdr entry))
11537 (cond
11538 ((null files) (setq files (list (current-buffer))))
11539 ((eq files 'org-agenda-files)
11540 (setq files (org-agenda-files 'unrestricted)))
11541 ((and (symbolp files) (fboundp files))
11542 (setq files (funcall files)))
11543 ((and (symbolp files) (boundp files))
11544 (setq files (symbol-value files))))
11545 (when (stringp files) (setq files (list files)))
11546 (cond
11547 ((eq (car desc) :tag)
11548 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11549 ((eq (car desc) :todo)
11550 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11551 ((eq (car desc) :regexp)
11552 (setq descre (cdr desc)))
11553 ((eq (car desc) :level)
11554 (setq descre (concat "^\\*\\{" (number-to-string
11555 (if org-odd-levels-only
11556 (1- (* 2 (cdr desc)))
11557 (cdr desc)))
11558 "\\}[ \t]")))
11559 ((eq (car desc) :maxlevel)
11560 (setq descre (concat "^\\*\\{1," (number-to-string
11561 (if org-odd-levels-only
11562 (1- (* 2 (cdr desc)))
11563 (cdr desc)))
11564 "\\}[ \t]")))
11565 (t (error "Bad refiling target description %s" desc)))
11566 (dolist (f files)
11567 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11569 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11570 (progn
11571 (when (bufferp f)
11572 (setq f (buffer-file-name (buffer-base-buffer f))))
11573 (setq f (and f (expand-file-name f)))
11574 (when (eq org-refile-use-outline-path 'file)
11575 (push (list (file-name-nondirectory f) f nil nil) tgs))
11576 (when (eq org-refile-use-outline-path 'buffer-name)
11577 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11578 (when (eq org-refile-use-outline-path 'full-file-path)
11579 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11580 (org-with-wide-buffer
11581 (goto-char (point-min))
11582 (setq org-outline-path-cache nil)
11583 (while (re-search-forward descre nil t)
11584 (beginning-of-line)
11585 (let ((case-fold-search nil))
11586 (looking-at org-complex-heading-regexp))
11587 (let ((begin (point))
11588 (heading (match-string-no-properties 4)))
11589 (unless (or (and
11590 org-refile-target-verify-function
11591 (not
11592 (funcall org-refile-target-verify-function)))
11593 (not heading))
11594 (let ((re (format org-complex-heading-regexp-format
11595 (regexp-quote heading)))
11596 (target
11597 (if (not org-refile-use-outline-path) heading
11598 (mapconcat
11599 #'identity
11600 (append
11601 (pcase org-refile-use-outline-path
11602 (`file (list (file-name-nondirectory
11603 (buffer-file-name
11604 (buffer-base-buffer)))))
11605 (`full-file-path
11606 (list (buffer-file-name
11607 (buffer-base-buffer))))
11608 (`buffer-name
11609 (list (buffer-name
11610 (buffer-base-buffer))))
11611 (_ nil))
11612 (mapcar #'org-protect-slash
11613 (org-get-outline-path t t)))
11614 "/"))))
11615 (push (list target f re (org-refile-marker (point)))
11616 tgs)))
11617 (when (= (point) begin)
11618 ;; Verification function has not moved point.
11619 (end-of-line)))))))
11620 (when org-refile-use-cache
11621 (org-refile-cache-put tgs (buffer-file-name) descre))
11622 (setq targets (append tgs targets))))))
11623 (message "Getting targets...done")
11624 (nreverse (delete-dups targets))))
11626 (defun org-protect-slash (s)
11627 (replace-regexp-in-string "/" "\\/" s nil t))
11629 (defun org--get-outline-path-1 (&optional use-cache)
11630 "Return outline path to current headline.
11632 Outline path is a list of strings, in reverse order. When
11633 optional argument USE-CACHE is non-nil, make use of a cache. See
11634 `org-get-outline-path' for details.
11636 Assume buffer is widened and point is on a headline."
11637 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11638 (let ((p (point))
11639 (heading (let ((case-fold-search nil))
11640 (looking-at org-complex-heading-regexp)
11641 (if (not (match-end 4)) ""
11642 ;; Remove statistics cookies.
11643 (org-trim
11644 (org-link-display-format
11645 (replace-regexp-in-string
11646 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11647 (match-string-no-properties 4))))))))
11648 (if (org-up-heading-safe)
11649 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11650 (when use-cache
11651 (push (cons p path) org-outline-path-cache))
11652 path)
11653 ;; This is a new root node. Since we assume we are moving
11654 ;; forward, we can drop previous cache so as to limit number
11655 ;; of associations there.
11656 (let ((path (list heading)))
11657 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11658 path)))))
11660 (defun org-get-outline-path (&optional with-self use-cache)
11661 "Return the outline path to the current entry.
11663 An outline path is a list of ancestors for current headline, as
11664 a list of strings. Statistics cookies are removed and links are
11665 replaced with their description, if any, or their path otherwise.
11667 When optional argument WITH-SELF is non-nil, the path also
11668 includes the current headline.
11670 When optional argument USE-CACHE is non-nil, cache outline paths
11671 between calls to this function so as to avoid backtracking. This
11672 argument is useful when planning to find more than one outline
11673 path in the same document. In that case, there are two
11674 conditions to satisfy:
11675 - `org-outline-path-cache' is set to nil before starting the
11676 process;
11677 - outline paths are computed by increasing buffer positions."
11678 (org-with-wide-buffer
11679 (and (or (and with-self (org-back-to-heading t))
11680 (org-up-heading-safe))
11681 (reverse (org--get-outline-path-1 use-cache)))))
11683 (defun org-format-outline-path (path &optional width prefix separator)
11684 "Format the outline path PATH for display.
11685 WIDTH is the maximum number of characters that is available.
11686 PREFIX is a prefix to be included in the returned string,
11687 such as the file name.
11688 SEPARATOR is inserted between the different parts of the path,
11689 the default is \"/\"."
11690 (setq width (or width 79))
11691 (setq path (delq nil path))
11692 (unless (> width 0)
11693 (user-error "Argument `width' must be positive"))
11694 (setq separator (or separator "/"))
11695 (let* ((org-odd-levels-only nil)
11696 (fpath (concat
11697 prefix (and prefix path separator)
11698 (mapconcat
11699 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11700 (cl-loop for head in path
11701 for n from 0
11702 collect (org-add-props
11703 head nil 'face
11704 (nth (% n org-n-level-faces) org-level-faces)))
11705 separator))))
11706 (when (> (length fpath) width)
11707 (if (< width 7)
11708 ;; It's unlikely that `width' will be this small, but don't
11709 ;; waste characters by adding ".." if it is.
11710 (setq fpath (substring fpath 0 width))
11711 (setf (substring fpath (- width 2)) "..")))
11712 fpath))
11714 (defun org-display-outline-path (&optional file current separator just-return-string)
11715 "Display the current outline path in the echo area.
11717 If FILE is non-nil, prepend the output with the file name.
11718 If CURRENT is non-nil, append the current heading to the output.
11719 SEPARATOR is passed through to `org-format-outline-path'. It separates
11720 the different parts of the path and defaults to \"/\".
11721 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11722 (interactive "P")
11723 (let* (case-fold-search
11724 (bfn (buffer-file-name (buffer-base-buffer)))
11725 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11726 res)
11727 (when current (setq path (append path
11728 (save-excursion
11729 (org-back-to-heading t)
11730 (when (looking-at org-complex-heading-regexp)
11731 (list (match-string 4)))))))
11732 (setq res
11733 (org-format-outline-path
11734 path
11735 (1- (frame-width))
11736 (and file bfn (concat (file-name-nondirectory bfn) separator))
11737 separator))
11738 (if just-return-string
11739 (org-no-properties res)
11740 (org-unlogged-message "%s" res))))
11742 (defvar org-refile-history nil
11743 "History for refiling operations.")
11745 (defvar org-after-refile-insert-hook nil
11746 "Hook run after `org-refile' has inserted its stuff at the new location.
11747 Note that this is still *before* the stuff will be removed from
11748 the *old* location.")
11750 (defvar org-capture-last-stored-marker)
11751 (defvar org-refile-keep nil
11752 "Non-nil means `org-refile' will copy instead of refile.")
11754 (defun org-copy ()
11755 "Like `org-refile', but copy."
11756 (interactive)
11757 (let ((org-refile-keep t))
11758 (funcall 'org-refile nil nil nil "Copy")))
11760 (defun org-refile (&optional arg default-buffer rfloc msg)
11761 "Move the entry or entries at point to another heading.
11763 The list of target headings is compiled using the information in
11764 `org-refile-targets', which see.
11766 At the target location, the entry is filed as a subitem of the
11767 target heading. Depending on `org-reverse-note-order', the new
11768 subitem will either be the first or the last subitem.
11770 If there is an active region, all entries in that region will be
11771 refiled. However, the region must fulfill the requirement that
11772 the first heading sets the top-level of the moved text.
11774 With a `\\[universal-argument]' ARG, the command will only visit the target \
11775 location
11776 and not actually move anything.
11778 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11779 location where the last
11780 refiling operation has put the subtree.
11782 With a numeric prefix argument of `2', refile to the running clock.
11784 With a numeric prefix argument of `3', emulate `org-refile-keep'
11785 being set to t and copy to the target location, don't move it.
11786 Beware that keeping refiled entries may result in duplicated ID
11787 properties.
11789 RFLOC can be a refile location obtained in a different way.
11791 MSG is a string to replace \"Refile\" in the default prompt with
11792 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11794 See also `org-refile-use-outline-path'.
11796 If you are using target caching (see `org-refile-use-cache'), you
11797 have to clear the target cache in order to find new targets.
11798 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11799 prefix argument (`C-u C-u C-u C-c C-w')."
11800 (interactive "P")
11801 (if (member arg '(0 (64)))
11802 (org-refile-cache-clear)
11803 (let* ((actionmsg (cond (msg msg)
11804 ((equal arg 3) "Refile (and keep)")
11805 (t "Refile")))
11806 (regionp (org-region-active-p))
11807 (region-start (and regionp (region-beginning)))
11808 (region-end (and regionp (region-end)))
11809 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11810 pos it nbuf file level reversed)
11811 (setq last-command nil)
11812 (when regionp
11813 (goto-char region-start)
11814 (or (bolp) (goto-char (point-at-bol)))
11815 (setq region-start (point))
11816 (unless (or (org-kill-is-subtree-p
11817 (buffer-substring region-start region-end))
11818 (prog1 org-refile-active-region-within-subtree
11819 (let ((s (point-at-eol)))
11820 (org-toggle-heading)
11821 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11822 (user-error "The region is not a (sequence of) subtree(s)")))
11823 (if (equal arg '(16))
11824 (org-refile-goto-last-stored)
11825 (when (or
11826 (and (equal arg 2)
11827 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11828 (prog1
11829 (setq it (list (or org-clock-heading "running clock")
11830 (buffer-file-name
11831 (marker-buffer org-clock-hd-marker))
11833 (marker-position org-clock-hd-marker)))
11834 (setq arg nil)))
11835 (setq it
11836 (or rfloc
11837 (let (heading-text)
11838 (save-excursion
11839 (unless (and arg (listp arg))
11840 (org-back-to-heading t)
11841 (setq heading-text
11842 (replace-regexp-in-string
11843 org-bracket-link-regexp
11844 "\\3"
11845 (or (nth 4 (org-heading-components))
11846 ""))))
11847 (org-refile-get-location
11848 (cond ((and arg (listp arg)) "Goto")
11849 (regionp (concat actionmsg " region to"))
11850 (t (concat actionmsg " subtree \""
11851 heading-text "\" to")))
11852 default-buffer
11853 (and (not (equal '(4) arg))
11854 org-refile-allow-creating-parent-nodes)))))))
11855 (setq file (nth 1 it)
11856 pos (nth 3 it))
11857 (when (and (not arg)
11859 (equal (buffer-file-name) file)
11860 (if regionp
11861 (and (>= pos region-start)
11862 (<= pos region-end))
11863 (and (>= pos (point))
11864 (< pos (save-excursion
11865 (org-end-of-subtree t t))))))
11866 (error "Cannot refile to position inside the tree or region"))
11867 (setq nbuf (or (find-buffer-visiting file)
11868 (find-file-noselect file)))
11869 (if (and arg (not (equal arg 3)))
11870 (progn
11871 (pop-to-buffer-same-window nbuf)
11872 (goto-char pos)
11873 (org-show-context 'org-goto))
11874 (if regionp
11875 (progn
11876 (org-kill-new (buffer-substring region-start region-end))
11877 (org-save-markers-in-region region-start region-end))
11878 (org-copy-subtree 1 nil t))
11879 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11880 (find-file-noselect file)))
11881 (setq reversed (org-notes-order-reversed-p))
11882 (org-with-wide-buffer
11883 (if pos
11884 (progn
11885 (goto-char pos)
11886 (setq level (org-get-valid-level (funcall outline-level) 1))
11887 (goto-char
11888 (if reversed
11889 (or (outline-next-heading) (point-max))
11890 (or (save-excursion (org-get-next-sibling))
11891 (org-end-of-subtree t t)
11892 (point-max)))))
11893 (setq level 1)
11894 (if (not reversed)
11895 (goto-char (point-max))
11896 (goto-char (point-min))
11897 (or (outline-next-heading) (goto-char (point-max)))))
11898 (unless (bolp) (newline))
11899 (org-paste-subtree level nil nil t)
11900 (when org-log-refile
11901 (org-add-log-setup 'refile nil nil org-log-refile)
11902 (unless (eq org-log-refile 'note)
11903 (save-excursion (org-add-log-note))))
11904 (and org-auto-align-tags
11905 (let ((org-loop-over-headlines-in-active-region nil))
11906 (org-set-tags nil t)))
11907 (let ((bookmark-name (plist-get org-bookmark-names-plist
11908 :last-refile)))
11909 (when bookmark-name
11910 (with-demoted-errors
11911 (bookmark-set bookmark-name))))
11912 ;; If we are refiling for capture, make sure that the
11913 ;; last-capture pointers point here
11914 (when (bound-and-true-p org-capture-is-refiling)
11915 (let ((bookmark-name (plist-get org-bookmark-names-plist
11916 :last-capture-marker)))
11917 (when bookmark-name
11918 (with-demoted-errors
11919 (bookmark-set bookmark-name))))
11920 (move-marker org-capture-last-stored-marker (point)))
11921 (when (fboundp 'deactivate-mark) (deactivate-mark))
11922 (run-hooks 'org-after-refile-insert-hook)))
11923 (unless org-refile-keep
11924 (if regionp
11925 (delete-region (point) (+ (point) (- region-end region-start)))
11926 (delete-region
11927 (and (org-back-to-heading t) (point))
11928 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11929 (when (featurep 'org-inlinetask)
11930 (org-inlinetask-remove-END-maybe))
11931 (setq org-markers-to-move nil)
11932 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11934 (defun org-refile-goto-last-stored ()
11935 "Go to the location where the last refile was stored."
11936 (interactive)
11937 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11938 (message "This is the location of the last refile"))
11940 (defun org-refile--get-location (refloc tbl)
11941 "When user refile to REFLOC, find the associated target in TBL.
11942 Also check `org-refile-target-table'."
11943 (car (delq
11945 (mapcar
11946 (lambda (r) (or (assoc r tbl)
11947 (assoc r org-refile-target-table)))
11948 (list (replace-regexp-in-string "/$" "" refloc)
11949 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11951 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11952 "Prompt the user for a refile location, using PROMPT.
11953 PROMPT should not be suffixed with a colon and a space, because
11954 this function appends the default value from
11955 `org-refile-history' automatically, if that is not empty."
11956 (let ((org-refile-targets org-refile-targets)
11957 (org-refile-use-outline-path org-refile-use-outline-path))
11958 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11959 (unless org-refile-target-table
11960 (user-error "No refile targets"))
11961 (let* ((cbuf (current-buffer))
11962 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11963 (cfunc (if (and org-refile-use-outline-path
11964 org-outline-path-complete-in-steps)
11965 #'org-olpath-completing-read
11966 #'completing-read))
11967 (extra (if org-refile-use-outline-path "/" ""))
11968 (cbnex (concat (buffer-name) extra))
11969 (filename (and cfn (expand-file-name cfn)))
11970 (tbl (mapcar
11971 (lambda (x)
11972 (if (and (not (member org-refile-use-outline-path
11973 '(file full-file-path)))
11974 (not (equal filename (nth 1 x))))
11975 (cons (concat (car x) extra " ("
11976 (file-name-nondirectory (nth 1 x)) ")")
11977 (cdr x))
11978 (cons (concat (car x) extra) (cdr x))))
11979 org-refile-target-table))
11980 (completion-ignore-case t)
11981 cdef
11982 (prompt (concat prompt
11983 (or (and (car org-refile-history)
11984 (concat " (default " (car org-refile-history) ")"))
11985 (and (assoc cbnex tbl) (setq cdef cbnex)
11986 (concat " (default " cbnex ")"))) ": "))
11987 pa answ parent-target child parent old-hist)
11988 (setq old-hist org-refile-history)
11989 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11990 nil 'org-refile-history (or cdef (car org-refile-history))))
11991 (if (setq pa (org-refile--get-location answ tbl))
11992 (progn
11993 (org-refile-check-position pa)
11994 (when (or (not org-refile-history)
11995 (not (eq old-hist org-refile-history))
11996 (not (equal (car pa) (car org-refile-history))))
11997 (setq org-refile-history
11998 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11999 org-refile-history
12000 (cdr org-refile-history))))
12001 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12002 (pop org-refile-history)))
12004 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12005 (progn
12006 (setq parent (match-string 1 answ)
12007 child (match-string 2 answ))
12008 (setq parent-target (org-refile--get-location parent tbl))
12009 (when (and parent-target
12010 (or (eq new-nodes t)
12011 (and (eq new-nodes 'confirm)
12012 (y-or-n-p (format "Create new node \"%s\"? "
12013 child)))))
12014 (org-refile-new-child parent-target child)))
12015 (user-error "Invalid target location")))))
12017 (declare-function org-string-nw-p "org-macs" (s))
12018 (defun org-refile-check-position (refile-pointer)
12019 "Check if the refile pointer matches the headline to which it points."
12020 (let* ((file (nth 1 refile-pointer))
12021 (re (nth 2 refile-pointer))
12022 (pos (nth 3 refile-pointer))
12023 buffer)
12024 (if (and (not (markerp pos)) (not file))
12025 (user-error "Please indicate a target file in the refile path")
12026 (when (org-string-nw-p re)
12027 (setq buffer (if (markerp pos)
12028 (marker-buffer pos)
12029 (or (find-buffer-visiting file)
12030 (find-file-noselect file))))
12031 (with-current-buffer buffer
12032 (org-with-wide-buffer
12033 (goto-char pos)
12034 (beginning-of-line 1)
12035 (unless (looking-at-p re)
12036 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12038 (defun org-refile-new-child (parent-target child)
12039 "Use refile target PARENT-TARGET to add new CHILD below it."
12040 (unless parent-target
12041 (error "Cannot find parent for new node"))
12042 (let ((file (nth 1 parent-target))
12043 (pos (nth 3 parent-target))
12044 level)
12045 (with-current-buffer (or (find-buffer-visiting file)
12046 (find-file-noselect file))
12047 (org-with-wide-buffer
12048 (if pos
12049 (goto-char pos)
12050 (goto-char (point-max))
12051 (unless (bolp) (newline)))
12052 (when (looking-at org-outline-regexp)
12053 (setq level (funcall outline-level))
12054 (org-end-of-subtree t t))
12055 (org-back-over-empty-lines)
12056 (insert "\n" (make-string
12057 (if pos (org-get-valid-level level 1) 1) ?*)
12058 " " child "\n")
12059 (beginning-of-line 0)
12060 (list (concat (car parent-target) "/" child) file "" (point))))))
12062 (defun org-olpath-completing-read (prompt collection &rest args)
12063 "Read an outline path like a file name."
12064 (let ((thetable collection))
12065 (apply #'completing-read
12066 prompt
12067 (lambda (string predicate &optional flag)
12068 (cond
12069 ((eq flag nil) (try-completion string thetable))
12070 ((eq flag t)
12071 (let ((l (length string)))
12072 (mapcar (lambda (x)
12073 (let ((r (substring x l))
12074 (f (if (string-match " ([^)]*)$" x)
12075 (match-string 0 x)
12076 "")))
12077 (if (string-match "/" r)
12078 (concat string (substring r 0 (match-end 0)) f)
12079 x)))
12080 (all-completions string thetable predicate))))
12081 ;; Exact match?
12082 ((eq flag 'lambda) (assoc string thetable))))
12083 args)))
12085 ;;;; Dynamic blocks
12087 (defun org-find-dblock (name)
12088 "Find the first dynamic block with name NAME in the buffer.
12089 If not found, stay at current position and return nil."
12090 (let ((case-fold-search t) pos)
12091 (save-excursion
12092 (goto-char (point-min))
12093 (setq pos (and (re-search-forward
12094 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12095 (match-beginning 0))))
12096 (when pos (goto-char pos))
12097 pos))
12099 (defun org-create-dblock (plist)
12100 "Create a dynamic block section, with parameters taken from PLIST.
12101 PLIST must contain a :name entry which is used as the name of the block."
12102 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12103 (end-of-line 1)
12104 (newline))
12105 (let ((col (current-column))
12106 (name (plist-get plist :name)))
12107 (insert "#+BEGIN: " name)
12108 (while plist
12109 (if (eq (car plist) :name)
12110 (setq plist (cddr plist))
12111 (insert " " (prin1-to-string (pop plist)))))
12112 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12113 (beginning-of-line -2)))
12115 (defun org-prepare-dblock ()
12116 "Prepare dynamic block for refresh.
12117 This empties the block, puts the cursor at the insert position and returns
12118 the property list including an extra property :name with the block name."
12119 (unless (looking-at org-dblock-start-re)
12120 (user-error "Not at a dynamic block"))
12121 (let* ((begdel (1+ (match-end 0)))
12122 (name (org-no-properties (match-string 1)))
12123 (params (append (list :name name)
12124 (read (concat "(" (match-string 3) ")")))))
12125 (save-excursion
12126 (beginning-of-line 1)
12127 (skip-chars-forward " \t")
12128 (setq params (plist-put params :indentation-column (current-column))))
12129 (unless (re-search-forward org-dblock-end-re nil t)
12130 (error "Dynamic block not terminated"))
12131 (setq params
12132 (append params
12133 (list :content (buffer-substring
12134 begdel (match-beginning 0)))))
12135 (delete-region begdel (match-beginning 0))
12136 (goto-char begdel)
12137 (open-line 1)
12138 params))
12140 (defun org-map-dblocks (&optional command)
12141 "Apply COMMAND to all dynamic blocks in the current buffer.
12142 If COMMAND is not given, use `org-update-dblock'."
12143 (let ((cmd (or command 'org-update-dblock)))
12144 (save-excursion
12145 (goto-char (point-min))
12146 (while (re-search-forward org-dblock-start-re nil t)
12147 (goto-char (match-beginning 0))
12148 (save-excursion
12149 (condition-case nil
12150 (funcall cmd)
12151 (error (message "Error during update of dynamic block"))))
12152 (unless (re-search-forward org-dblock-end-re nil t)
12153 (error "Dynamic block not terminated"))))))
12155 (defun org-dblock-update (&optional arg)
12156 "User command for updating dynamic blocks.
12157 Update the dynamic block at point. With prefix ARG, update all dynamic
12158 blocks in the buffer."
12159 (interactive "P")
12160 (if arg
12161 (org-update-all-dblocks)
12162 (or (looking-at org-dblock-start-re)
12163 (org-beginning-of-dblock))
12164 (org-update-dblock)))
12166 (defun org-update-dblock ()
12167 "Update the dynamic block at point.
12168 This means to empty the block, parse for parameters and then call
12169 the correct writing function."
12170 (interactive)
12171 (save-excursion
12172 (let* ((win (selected-window))
12173 (pos (point))
12174 (line (org-current-line))
12175 (params (org-prepare-dblock))
12176 (name (plist-get params :name))
12177 (indent (plist-get params :indentation-column))
12178 (cmd (intern (concat "org-dblock-write:" name))))
12179 (message "Updating dynamic block `%s' at line %d..." name line)
12180 (funcall cmd params)
12181 (message "Updating dynamic block `%s' at line %d...done" name line)
12182 (goto-char pos)
12183 (when (and indent (> indent 0))
12184 (setq indent (make-string indent ?\ ))
12185 (save-excursion
12186 (select-window win)
12187 (org-beginning-of-dblock)
12188 (forward-line 1)
12189 (while (not (looking-at org-dblock-end-re))
12190 (insert indent)
12191 (beginning-of-line 2))
12192 (when (looking-at org-dblock-end-re)
12193 (and (looking-at "[ \t]+")
12194 (replace-match ""))
12195 (insert indent)))))))
12197 (defun org-beginning-of-dblock ()
12198 "Find the beginning of the dynamic block at point.
12199 Error if there is no such block at point."
12200 (let ((pos (point))
12201 beg)
12202 (end-of-line 1)
12203 (if (and (re-search-backward org-dblock-start-re nil t)
12204 (setq beg (match-beginning 0))
12205 (re-search-forward org-dblock-end-re nil t)
12206 (> (match-end 0) pos))
12207 (goto-char beg)
12208 (goto-char pos)
12209 (error "Not in a dynamic block"))))
12211 (defun org-update-all-dblocks ()
12212 "Update all dynamic blocks in the buffer.
12213 This function can be used in a hook."
12214 (interactive)
12215 (when (derived-mode-p 'org-mode)
12216 (org-map-dblocks 'org-update-dblock)))
12219 ;;;; Completion
12221 (declare-function org-export-backend-options "ox" (cl-x) t)
12222 (defun org-get-export-keywords ()
12223 "Return a list of all currently understood export keywords.
12224 Export keywords include options, block names, attributes and
12225 keywords relative to each registered export back-end."
12226 (let (keywords)
12227 (dolist (backend
12228 (bound-and-true-p org-export-registered-backends)
12229 (delq nil keywords))
12230 ;; Back-end name (for keywords, like #+LATEX:)
12231 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12232 (dolist (option-entry (org-export-backend-options backend))
12233 ;; Back-end options.
12234 (push (nth 1 option-entry) keywords)))))
12236 (defconst org-options-keywords
12237 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12238 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12239 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12240 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12241 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12243 (defcustom org-structure-template-alist
12244 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12245 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12246 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12247 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12248 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12249 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12250 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12251 ("L" "#+LaTeX: ")
12252 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12253 ("H" "#+HTML: ")
12254 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12255 ("A" "#+ASCII: ")
12256 ("i" "#+INDEX: ?")
12257 ("I" "#+INCLUDE: %file ?"))
12258 "Structure completion elements.
12259 This is a list of abbreviation keys and values. The value gets inserted
12260 if you type `<' followed by the key and then press the completion key,
12261 usually `TAB'. %file will be replaced by a file name after prompting
12262 for the file using completion. The cursor will be placed at the position
12263 of the `?' in the template.
12264 There are two templates for each key, the first uses the original Org syntax,
12265 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12266 the default when the /org-mtags.el/ module has been loaded. See also the
12267 variable `org-mtags-prefer-muse-templates'."
12268 :group 'org-completion
12269 :type '(repeat
12270 (list
12271 (string :tag "Key")
12272 (string :tag "Template")))
12273 :version "26.1"
12274 :package-version '(Org . "8.3"))
12276 (defun org-try-structure-completion ()
12277 "Try to complete a structure template before point.
12278 This looks for strings like \"<e\" on an otherwise empty line and
12279 expands them."
12280 (let ((l (buffer-substring (point-at-bol) (point)))
12282 (when (and (looking-at "[ \t]*$")
12283 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12284 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12285 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12286 (match-beginning 1)) a)
12287 t)))
12289 (defun org-complete-expand-structure-template (start cell)
12290 "Expand a structure template."
12291 (let ((rpl (nth 1 cell))
12292 (ind ""))
12293 (delete-region start (point))
12294 (when (string-match "\\`[ \t]*#\\+" rpl)
12295 (cond
12296 ((bolp))
12297 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12298 (setq ind (buffer-substring (point-at-bol) (point))))
12299 (t (newline))))
12300 (setq start (point))
12301 (when (string-match "%file" rpl)
12302 (setq rpl (replace-match
12303 (concat
12304 "\""
12305 (save-match-data
12306 (abbreviate-file-name (read-file-name "Include file: ")))
12307 "\"")
12308 t t rpl)))
12309 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12310 (concat "\n" ind)))
12311 (insert rpl)
12312 (when (re-search-backward "\\?" start t) (delete-char 1))))
12314 ;;;; TODO, DEADLINE, Comments
12316 (defun org-toggle-comment ()
12317 "Change the COMMENT state of an entry."
12318 (interactive)
12319 (save-excursion
12320 (org-back-to-heading)
12321 (let ((case-fold-search nil))
12322 (looking-at org-complex-heading-regexp))
12323 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12324 (skip-chars-forward " \t")
12325 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12326 (if (org-in-commented-heading-p t)
12327 (delete-region (point)
12328 (progn (search-forward " " (line-end-position) 'move)
12329 (skip-chars-forward " \t")
12330 (point)))
12331 (insert org-comment-string)
12332 (unless (eolp) (insert " ")))))
12334 (defvar org-last-todo-state-is-todo nil
12335 "This is non-nil when the last TODO state change led to a TODO state.
12336 If the last change removed the TODO tag or switched to DONE, then
12337 this is nil.")
12339 (defvar org-setting-tags nil) ; dynamically skipped
12341 (defvar org-todo-setup-filter-hook nil
12342 "Hook for functions that pre-filter todo specs.
12343 Each function takes a todo spec and returns either nil or the spec
12344 transformed into canonical form." )
12346 (defvar org-todo-get-default-hook nil
12347 "Hook for functions that get a default item for todo.
12348 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12349 nil or a string to be used for the todo mark." )
12351 (defvar org-agenda-headline-snapshot-before-repeat)
12353 (defun org-current-effective-time ()
12354 "Return current time adjusted for `org-extend-today-until' variable."
12355 (let* ((ct (org-current-time))
12356 (dct (decode-time ct))
12357 (ct1
12358 (cond
12359 (org-use-last-clock-out-time-as-effective-time
12360 (or (org-clock-get-last-clock-out-time) ct))
12361 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12362 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12363 (t ct))))
12364 ct1))
12366 (defun org-todo-yesterday (&optional arg)
12367 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12368 (interactive "P")
12369 (if (eq major-mode 'org-agenda-mode)
12370 (apply 'org-agenda-todo-yesterday arg)
12371 (let* ((org-use-effective-time t)
12372 (hour (nth 2 (decode-time (org-current-time))))
12373 (org-extend-today-until (1+ hour)))
12374 (org-todo arg))))
12376 (defvar org-block-entry-blocking ""
12377 "First entry preventing the TODO state change.")
12379 (defun org-cancel-repeater ()
12380 "Cancel a repeater by setting its numeric value to zero."
12381 (interactive)
12382 (save-excursion
12383 (org-back-to-heading t)
12384 (let ((bound1 (point))
12385 (bound0 (save-excursion (outline-next-heading) (point))))
12386 (when (and (re-search-forward
12387 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12388 org-deadline-time-regexp "\\)\\|\\("
12389 org-ts-regexp "\\)")
12390 bound0 t)
12391 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12392 bound1 t))
12393 (replace-match "0" t nil nil 1)))))
12395 (defvar org-state)
12396 (defvar org-blocked-by-checkboxes)
12397 (defun org-todo (&optional arg)
12398 "Change the TODO state of an item.
12400 The state of an item is given by a keyword at the start of the heading,
12401 like
12402 *** TODO Write paper
12403 *** DONE Call mom
12405 The different keywords are specified in the variable `org-todo-keywords'.
12406 By default the available states are \"TODO\" and \"DONE\". So, for this
12407 example: when the item starts with TODO, it is changed to DONE.
12408 When it starts with DONE, the DONE is removed. And when neither TODO nor
12409 DONE are present, add TODO at the beginning of the heading.
12411 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12412 state.
12413 With numeric prefix ARG, switch to that state.
12414 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12415 next set of TODO \
12416 keywords (nextset).
12417 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12418 prefix, circumvent any state blocking.
12419 With a numeric prefix arg of 0, inhibit note taking for the change.
12420 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12422 When called through ELisp, arg is also interpreted in the following way:
12423 `none' -> empty state
12424 \"\" -> switch to empty state
12425 `done' -> switch to DONE
12426 `nextset' -> switch to the next set of keywords
12427 `previousset' -> switch to the previous set of keywords
12428 \"WAITING\" -> switch to the specified keyword, but only if it
12429 really is a member of `org-todo-keywords'."
12430 (interactive "P")
12431 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12432 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12433 'region-start-level 'region))
12434 org-loop-over-headlines-in-active-region)
12435 (org-map-entries
12436 `(org-todo ,arg)
12437 org-loop-over-headlines-in-active-region
12438 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12439 (when (equal arg '(16)) (setq arg 'nextset))
12440 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12441 (let ((org-blocker-hook org-blocker-hook)
12442 commentp
12443 case-fold-search)
12444 (when (equal arg '(64))
12445 (setq arg nil org-blocker-hook nil))
12446 (when (and org-blocker-hook
12447 (or org-inhibit-blocking
12448 (org-entry-get nil "NOBLOCKING")))
12449 (setq org-blocker-hook nil))
12450 (save-excursion
12451 (catch 'exit
12452 (org-back-to-heading t)
12453 (when (org-in-commented-heading-p t)
12454 (org-toggle-comment)
12455 (setq commentp t))
12456 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12457 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12458 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12459 (let* ((match-data (match-data))
12460 (startpos (point-at-bol))
12461 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12462 (org-log-done org-log-done)
12463 (org-log-repeat org-log-repeat)
12464 (org-todo-log-states org-todo-log-states)
12465 (org-inhibit-logging
12466 (if (equal arg 0)
12467 (progn (setq arg nil) 'note) org-inhibit-logging))
12468 (this (match-string 1))
12469 (hl-pos (match-beginning 0))
12470 (head (org-get-todo-sequence-head this))
12471 (ass (assoc head org-todo-kwd-alist))
12472 (interpret (nth 1 ass))
12473 (done-word (nth 3 ass))
12474 (final-done-word (nth 4 ass))
12475 (org-last-state (or this ""))
12476 (completion-ignore-case t)
12477 (member (member this org-todo-keywords-1))
12478 (tail (cdr member))
12479 (org-state (cond
12480 ((and org-todo-key-trigger
12481 (or (and (equal arg '(4))
12482 (eq org-use-fast-todo-selection 'prefix))
12483 (and (not arg) org-use-fast-todo-selection
12484 (not (eq org-use-fast-todo-selection
12485 'prefix)))))
12486 ;; Use fast selection.
12487 (org-fast-todo-selection))
12488 ((and (equal arg '(4))
12489 (or (not org-use-fast-todo-selection)
12490 (not org-todo-key-trigger)))
12491 ;; Read a state with completion.
12492 (completing-read
12493 "State: " (mapcar #'list org-todo-keywords-1)
12494 nil t))
12495 ((eq arg 'right)
12496 (if this
12497 (if tail (car tail) nil)
12498 (car org-todo-keywords-1)))
12499 ((eq arg 'left)
12500 (unless (equal member org-todo-keywords-1)
12501 (if this
12502 (nth (- (length org-todo-keywords-1)
12503 (length tail) 2)
12504 org-todo-keywords-1)
12505 (org-last org-todo-keywords-1))))
12506 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12507 (setq arg nil))) ;hack to fall back to cycling
12508 (arg
12509 ;; User or caller requests a specific state.
12510 (cond
12511 ((equal arg "") nil)
12512 ((eq arg 'none) nil)
12513 ((eq arg 'done) (or done-word (car org-done-keywords)))
12514 ((eq arg 'nextset)
12515 (or (car (cdr (member head org-todo-heads)))
12516 (car org-todo-heads)))
12517 ((eq arg 'previousset)
12518 (let ((org-todo-heads (reverse org-todo-heads)))
12519 (or (car (cdr (member head org-todo-heads)))
12520 (car org-todo-heads))))
12521 ((car (member arg org-todo-keywords-1)))
12522 ((stringp arg)
12523 (user-error "State `%s' not valid in this file" arg))
12524 ((nth (1- (prefix-numeric-value arg))
12525 org-todo-keywords-1))))
12526 ((null member) (or head (car org-todo-keywords-1)))
12527 ((equal this final-done-word) nil) ;-> make empty
12528 ((null tail) nil) ;-> first entry
12529 ((memq interpret '(type priority))
12530 (if (eq this-command last-command)
12531 (car tail)
12532 (if (> (length tail) 0)
12533 (or done-word (car org-done-keywords))
12534 nil)))
12536 (car tail))))
12537 (org-state (or
12538 (run-hook-with-args-until-success
12539 'org-todo-get-default-hook org-state org-last-state)
12540 org-state))
12541 (next (if org-state (concat " " org-state " ") " "))
12542 (change-plist (list :type 'todo-state-change :from this :to org-state
12543 :position startpos))
12544 dolog now-done-p)
12545 (when org-blocker-hook
12546 (let (org-blocked-by-checkboxes block-reason)
12547 (setq org-last-todo-state-is-todo
12548 (not (member this org-done-keywords)))
12549 (unless (save-excursion
12550 (save-match-data
12551 (org-with-wide-buffer
12552 (run-hook-with-args-until-failure
12553 'org-blocker-hook change-plist))))
12554 (setq block-reason (if org-blocked-by-checkboxes
12555 "contained checkboxes"
12556 (format "\"%s\"" org-block-entry-blocking)))
12557 (if (called-interactively-p 'interactive)
12558 (user-error "TODO state change from %s to %s blocked (by %s)"
12559 this org-state block-reason)
12560 ;; Fail silently.
12561 (message "TODO state change from %s to %s blocked (by %s)"
12562 this org-state block-reason)
12563 (throw 'exit nil)))))
12564 (store-match-data match-data)
12565 (replace-match next t t)
12566 (cond ((equal this org-state)
12567 (message "TODO state was already %s" (org-trim next)))
12568 ((pos-visible-in-window-p hl-pos)
12569 (message "TODO state changed to %s" (org-trim next))))
12570 (unless head
12571 (setq head (org-get-todo-sequence-head org-state)
12572 ass (assoc head org-todo-kwd-alist)
12573 interpret (nth 1 ass)
12574 done-word (nth 3 ass)
12575 final-done-word (nth 4 ass)))
12576 (when (memq arg '(nextset previousset))
12577 (message "Keyword-Set %d/%d: %s"
12578 (- (length org-todo-sets) -1
12579 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12580 (length org-todo-sets)
12581 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12582 (setq org-last-todo-state-is-todo
12583 (not (member org-state org-done-keywords)))
12584 (setq now-done-p (and (member org-state org-done-keywords)
12585 (not (member this org-done-keywords))))
12586 (and logging (org-local-logging logging))
12587 (when (and (or org-todo-log-states org-log-done)
12588 (not (eq org-inhibit-logging t))
12589 (not (memq arg '(nextset previousset))))
12590 ;; We need to look at recording a time and note.
12591 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12592 (nth 2 (assoc this org-todo-log-states))))
12593 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12594 (setq dolog 'time))
12595 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12596 (and org-state
12597 (member org-state org-not-done-keywords)
12598 (not (member this org-not-done-keywords))))
12599 ;; This is now a todo state and was not one before
12600 ;; If there was a CLOSED time stamp, get rid of it.
12601 (org-add-planning-info nil nil 'closed))
12602 (when (and now-done-p org-log-done)
12603 ;; It is now done, and it was not done before.
12604 (org-add-planning-info 'closed (org-current-effective-time))
12605 (when (and (not dolog) (eq 'note org-log-done))
12606 (org-add-log-setup 'done org-state this 'note)))
12607 (when (and org-state dolog)
12608 ;; This is a non-nil state, and we need to log it.
12609 (org-add-log-setup 'state org-state this dolog)))
12610 ;; Fixup tag positioning.
12611 (org-todo-trigger-tag-changes org-state)
12612 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12613 (when org-provide-todo-statistics
12614 (org-update-parent-todo-statistics))
12615 (run-hooks 'org-after-todo-state-change-hook)
12616 (when (and arg (not (member org-state org-done-keywords)))
12617 (setq head (org-get-todo-sequence-head org-state)))
12618 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12619 ;; Do we need to trigger a repeat?
12620 (when now-done-p
12621 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12622 ;; This is for the agenda, take a snapshot of the headline.
12623 (save-match-data
12624 (setq org-agenda-headline-snapshot-before-repeat
12625 (org-get-heading))))
12626 (org-auto-repeat-maybe org-state))
12627 ;; Fixup cursor location if close to the keyword.
12628 (when (and (outline-on-heading-p)
12629 (not (bolp))
12630 (save-excursion (beginning-of-line 1)
12631 (looking-at org-todo-line-regexp))
12632 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12633 (goto-char (or (match-end 2) (match-end 1)))
12634 (and (looking-at " ") (just-one-space)))
12635 (when org-trigger-hook
12636 (save-excursion
12637 (run-hook-with-args 'org-trigger-hook change-plist)))
12638 (when commentp (org-toggle-comment))))))))
12640 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12641 "Block turning an entry into a TODO, using the hierarchy.
12642 This checks whether the current task should be blocked from state
12643 changes. Such blocking occurs when:
12645 1. The task has children which are not all in a completed state.
12647 2. A task has a parent with the property :ORDERED:, and there
12648 are siblings prior to the current task with incomplete
12649 status.
12651 3. The parent of the task is blocked because it has siblings that should
12652 be done first, or is child of a block grandparent TODO entry."
12654 (if (not org-enforce-todo-dependencies)
12655 t ; if locally turned off don't block
12656 (catch 'dont-block
12657 ;; If this is not a todo state change, or if this entry is already DONE,
12658 ;; do not block
12659 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12660 (member (plist-get change-plist :from)
12661 (cons 'done org-done-keywords))
12662 (member (plist-get change-plist :to)
12663 (cons 'todo org-not-done-keywords))
12664 (not (plist-get change-plist :to)))
12665 (throw 'dont-block t))
12666 ;; If this task has children, and any are undone, it's blocked
12667 (save-excursion
12668 (org-back-to-heading t)
12669 (let ((this-level (funcall outline-level)))
12670 (outline-next-heading)
12671 (let ((child-level (funcall outline-level)))
12672 (while (and (not (eobp))
12673 (> child-level this-level))
12674 ;; this todo has children, check whether they are all
12675 ;; completed
12676 (when (and (not (org-entry-is-done-p))
12677 (org-entry-is-todo-p))
12678 (setq org-block-entry-blocking (org-get-heading))
12679 (throw 'dont-block nil))
12680 (outline-next-heading)
12681 (setq child-level (funcall outline-level))))))
12682 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12683 ;; any previous siblings are undone, it's blocked
12684 (save-excursion
12685 (org-back-to-heading t)
12686 (let* ((pos (point))
12687 (parent-pos (and (org-up-heading-safe) (point)))
12688 (case-fold-search nil))
12689 (unless parent-pos (throw 'dont-block t)) ; no parent
12690 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12691 (forward-line 1)
12692 (re-search-forward org-not-done-heading-regexp pos t))
12693 (setq org-block-entry-blocking (match-string 0))
12694 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12695 ;; Search further up the hierarchy, to see if an ancestor is blocked
12696 (while t
12697 (goto-char parent-pos)
12698 (unless (looking-at org-not-done-heading-regexp)
12699 (throw 'dont-block t)) ; do not block, parent is not a TODO
12700 (setq pos (point))
12701 (setq parent-pos (and (org-up-heading-safe) (point)))
12702 (unless parent-pos (throw 'dont-block t)) ; no parent
12703 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12704 (forward-line 1)
12705 (re-search-forward org-not-done-heading-regexp pos t)
12706 (setq org-block-entry-blocking (org-get-heading)))
12707 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12709 (defcustom org-track-ordered-property-with-tag nil
12710 "Should the ORDERED property also be shown as a tag?
12711 The ORDERED property decides if an entry should require subtasks to be
12712 completed in sequence. Since a property is not very visible, setting
12713 this option means that toggling the ORDERED property with the command
12714 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12715 not relevant for the behavior, but it makes things more visible.
12717 Note that toggling the tag with tags commands will not change the property
12718 and therefore not influence behavior!
12720 This can be t, meaning the tag ORDERED should be used, It can also be a
12721 string to select a different tag for this task."
12722 :group 'org-todo
12723 :type '(choice
12724 (const :tag "No tracking" nil)
12725 (const :tag "Track with ORDERED tag" t)
12726 (string :tag "Use other tag")))
12728 (defun org-toggle-ordered-property ()
12729 "Toggle the ORDERED property of the current entry.
12730 For better visibility, you can track the value of this property with a tag.
12731 See variable `org-track-ordered-property-with-tag'."
12732 (interactive)
12733 (let* ((t1 org-track-ordered-property-with-tag)
12734 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12735 (save-excursion
12736 (org-back-to-heading)
12737 (if (org-entry-get nil "ORDERED")
12738 (progn
12739 (org-delete-property "ORDERED")
12740 (and tag (org-toggle-tag tag 'off))
12741 (message "Subtasks can be completed in arbitrary order"))
12742 (org-entry-put nil "ORDERED" "t")
12743 (and tag (org-toggle-tag tag 'on))
12744 (message "Subtasks must be completed in sequence")))))
12746 (defun org-block-todo-from-checkboxes (change-plist)
12747 "Block turning an entry into a TODO, using checkboxes.
12748 This checks whether the current task should be blocked from state
12749 changes because there are unchecked boxes in this entry."
12750 (if (not org-enforce-todo-checkbox-dependencies)
12751 t ; if locally turned off don't block
12752 (catch 'dont-block
12753 ;; If this is not a todo state change, or if this entry is already DONE,
12754 ;; do not block
12755 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12756 (member (plist-get change-plist :from)
12757 (cons 'done org-done-keywords))
12758 (member (plist-get change-plist :to)
12759 (cons 'todo org-not-done-keywords))
12760 (not (plist-get change-plist :to)))
12761 (throw 'dont-block t))
12762 ;; If this task has checkboxes that are not checked, it's blocked
12763 (save-excursion
12764 (org-back-to-heading t)
12765 (let ((beg (point)) end)
12766 (outline-next-heading)
12767 (setq end (point))
12768 (goto-char beg)
12769 (when (org-list-search-forward
12770 (concat (org-item-beginning-re)
12771 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12772 "\\[[- ]\\]")
12773 end t)
12774 (when (boundp 'org-blocked-by-checkboxes)
12775 (setq org-blocked-by-checkboxes t))
12776 (throw 'dont-block nil))))
12777 t))) ; do not block
12779 (defun org-entry-blocked-p ()
12780 "Non-nil if entry at point is blocked."
12781 (and (not (org-entry-get nil "NOBLOCKING"))
12782 (member (org-entry-get nil "TODO") org-not-done-keywords)
12783 (not (run-hook-with-args-until-failure
12784 'org-blocker-hook
12785 (list :type 'todo-state-change
12786 :position (point)
12787 :from 'todo
12788 :to 'done)))))
12790 (defun org-update-statistics-cookies (all)
12791 "Update the statistics cookie, either from TODO or from checkboxes.
12792 This should be called with the cursor in a line with a statistics
12793 cookie. When called with a \\[universal-argument] prefix, update
12794 all statistics cookies in the buffer."
12795 (interactive "P")
12796 (if all
12797 (progn
12798 (org-update-checkbox-count 'all)
12799 (org-map-entries 'org-update-parent-todo-statistics))
12800 (if (not (org-at-heading-p))
12801 (org-update-checkbox-count)
12802 (let ((pos (point-marker))
12803 end l1 l2)
12804 (ignore-errors (org-back-to-heading t))
12805 (if (not (org-at-heading-p))
12806 (org-update-checkbox-count)
12807 (setq l1 (org-outline-level))
12808 (setq end (save-excursion
12809 (outline-next-heading)
12810 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12811 (point)))
12812 (if (and (save-excursion
12813 (re-search-forward
12814 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12815 (not (save-excursion (re-search-forward
12816 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12817 (org-update-checkbox-count)
12818 (if (and l2 (> l2 l1))
12819 (progn
12820 (goto-char end)
12821 (org-update-parent-todo-statistics))
12822 (goto-char pos)
12823 (beginning-of-line 1)
12824 (while (re-search-forward
12825 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12826 (point-at-eol) t)
12827 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12828 (goto-char pos)
12829 (move-marker pos nil)))))
12831 (defvar org-entry-property-inherited-from) ;; defined below
12832 (defun org-update-parent-todo-statistics ()
12833 "Update any statistics cookie in the parent of the current headline.
12834 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12835 the entire subtree and this will travel up the hierarchy and update
12836 statistics everywhere."
12837 (let* ((prop (save-excursion (org-up-heading-safe)
12838 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12839 (recursive (or (not org-hierarchical-todo-statistics)
12840 (and prop (string-match "\\<recursive\\>" prop))))
12841 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12843 (first t)
12844 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12845 level ltoggle l1 new ndel
12846 (cnt-all 0) (cnt-done 0) is-percent kwd
12847 checkbox-beg cookie-present)
12848 (catch 'exit
12849 (save-excursion
12850 (beginning-of-line 1)
12851 (setq ltoggle (funcall outline-level))
12852 ;; Three situations are to consider:
12854 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12855 ;; to the top-level ancestor on the headline;
12857 ;; 2. If parent has "recursive" property, repeat up to the
12858 ;; headline setting that property, taking inheritance into
12859 ;; account;
12861 ;; 3. Else, move up to direct parent and proceed only once.
12862 (while (and (setq level (org-up-heading-safe))
12863 (or recursive first)
12864 (>= (point) lim))
12865 (setq first nil cookie-present nil)
12866 (unless (and level
12867 (not (string-match
12868 "\\<checkbox\\>"
12869 (downcase (or (org-entry-get nil "COOKIE_DATA")
12870 "")))))
12871 (throw 'exit nil))
12872 (while (re-search-forward box-re (point-at-eol) t)
12873 (setq cnt-all 0 cnt-done 0 cookie-present t)
12874 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12875 (save-match-data
12876 (unless (outline-next-heading) (throw 'exit nil))
12877 (while (and (looking-at org-complex-heading-regexp)
12878 (> (setq l1 (length (match-string 1))) level))
12879 (setq kwd (and (or recursive (= l1 ltoggle))
12880 (match-string 2)))
12881 (if (or (eq org-provide-todo-statistics 'all-headlines)
12882 (and (eq org-provide-todo-statistics t)
12883 (or (member kwd org-done-keywords)))
12884 (and (listp org-provide-todo-statistics)
12885 (stringp (car org-provide-todo-statistics))
12886 (or (member kwd org-provide-todo-statistics)
12887 (member kwd org-done-keywords)))
12888 (and (listp org-provide-todo-statistics)
12889 (listp (car org-provide-todo-statistics))
12890 (or (member kwd (car org-provide-todo-statistics))
12891 (and (member kwd org-done-keywords)
12892 (member kwd (cadr org-provide-todo-statistics))))))
12893 (setq cnt-all (1+ cnt-all))
12894 (and (eq org-provide-todo-statistics t)
12896 (setq cnt-all (1+ cnt-all))))
12897 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12898 (member kwd org-done-keywords))
12899 (and (listp org-provide-todo-statistics)
12900 (listp (car org-provide-todo-statistics))
12901 (member kwd org-done-keywords)
12902 (member kwd (cadr org-provide-todo-statistics)))
12903 (and (listp org-provide-todo-statistics)
12904 (stringp (car org-provide-todo-statistics))
12905 (member kwd org-done-keywords)))
12906 (setq cnt-done (1+ cnt-done)))
12907 (outline-next-heading)))
12908 (setq new
12909 (if is-percent
12910 (format "[%d%%]" (floor (* 100.0 cnt-done)
12911 (max 1 cnt-all)))
12912 (format "[%d/%d]" cnt-done cnt-all))
12913 ndel (- (match-end 0) checkbox-beg))
12914 (goto-char checkbox-beg)
12915 (insert new)
12916 (delete-region (point) (+ (point) ndel))
12917 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12918 (when cookie-present
12919 (run-hook-with-args 'org-after-todo-statistics-hook
12920 cnt-done (- cnt-all cnt-done))))))
12921 (run-hooks 'org-todo-statistics-hook)))
12923 (defvar org-after-todo-statistics-hook nil
12924 "Hook that is called after a TODO statistics cookie has been updated.
12925 Each function is called with two arguments: the number of not-done entries
12926 and the number of done entries.
12928 For example, the following function, when added to this hook, will switch
12929 an entry to DONE when all children are done, and back to TODO when new
12930 entries are set to a TODO status. Note that this hook is only called
12931 when there is a statistics cookie in the headline!
12933 (defun org-summary-todo (n-done n-not-done)
12934 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12935 (let (org-log-done org-log-states) ; turn off logging
12936 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12939 (defvar org-todo-statistics-hook nil
12940 "Hook that is run whenever Org thinks TODO statistics should be updated.
12941 This hook runs even if there is no statistics cookie present, in which case
12942 `org-after-todo-statistics-hook' would not run.")
12944 (defun org-todo-trigger-tag-changes (state)
12945 "Apply the changes defined in `org-todo-state-tags-triggers'."
12946 (let ((l org-todo-state-tags-triggers)
12947 changes)
12948 (when (or (not state) (equal state ""))
12949 (setq changes (append changes (cdr (assoc "" l)))))
12950 (when (and (stringp state) (> (length state) 0))
12951 (setq changes (append changes (cdr (assoc state l)))))
12952 (when (member state org-not-done-keywords)
12953 (setq changes (append changes (cdr (assq 'todo l)))))
12954 (when (member state org-done-keywords)
12955 (setq changes (append changes (cdr (assq 'done l)))))
12956 (dolist (c changes)
12957 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12959 (defun org-local-logging (value)
12960 "Get logging settings from a property VALUE."
12961 ;; Directly set the variables, they are already local.
12962 (setq org-log-done nil
12963 org-log-repeat nil
12964 org-todo-log-states nil)
12965 (dolist (w (org-split-string value))
12966 (let (a)
12967 (cond
12968 ((setq a (assoc w org-startup-options))
12969 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12970 (set (nth 1 a) (nth 2 a))))
12971 ((setq a (org-extract-log-state-settings w))
12972 (and (member (car a) org-todo-keywords-1)
12973 (push a org-todo-log-states)))))))
12975 (defun org-get-todo-sequence-head (kwd)
12976 "Return the head of the TODO sequence to which KWD belongs.
12977 If KWD is not set, check if there is a text property remembering the
12978 right sequence."
12979 (let (p)
12980 (cond
12981 ((not kwd)
12982 (or (get-text-property (point-at-bol) 'org-todo-head)
12983 (progn
12984 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12985 nil (point-at-eol)))
12986 (get-text-property p 'org-todo-head))))
12987 ((not (member kwd org-todo-keywords-1))
12988 (car org-todo-keywords-1))
12989 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12991 (defun org-fast-todo-selection ()
12992 "Fast TODO keyword selection with single keys.
12993 Returns the new TODO keyword, or nil if no state change should occur."
12994 (let* ((fulltable org-todo-key-alist)
12995 (done-keywords org-done-keywords) ;; needed for the faces.
12996 (maxlen (apply 'max (mapcar
12997 (lambda (x)
12998 (if (stringp (car x)) (string-width (car x)) 0))
12999 fulltable)))
13000 (expert nil)
13001 (fwidth (+ maxlen 3 1 3))
13002 (ncol (/ (- (window-width) 4) fwidth))
13003 tg cnt e c tbl
13004 groups ingroup)
13005 (save-excursion
13006 (save-window-excursion
13007 (if expert
13008 (set-buffer (get-buffer-create " *Org todo*"))
13009 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13010 (erase-buffer)
13011 (setq-local org-done-keywords done-keywords)
13012 (setq tbl fulltable cnt 0)
13013 (while (setq e (pop tbl))
13014 (cond
13015 ((equal e '(:startgroup))
13016 (push '() groups) (setq ingroup t)
13017 (unless (= cnt 0)
13018 (setq cnt 0)
13019 (insert "\n"))
13020 (insert "{ "))
13021 ((equal e '(:endgroup))
13022 (setq ingroup nil cnt 0)
13023 (insert "}\n"))
13024 ((equal e '(:newline))
13025 (unless (= cnt 0)
13026 (setq cnt 0)
13027 (insert "\n")
13028 (setq e (car tbl))
13029 (while (equal (car tbl) '(:newline))
13030 (insert "\n")
13031 (setq tbl (cdr tbl)))))
13033 (setq tg (car e) c (cdr e))
13034 (when ingroup (push tg (car groups)))
13035 (setq tg (org-add-props tg nil 'face
13036 (org-get-todo-face tg)))
13037 (when (and (= cnt 0) (not ingroup)) (insert " "))
13038 (insert "[" c "] " tg (make-string
13039 (- fwidth 4 (length tg)) ?\ ))
13040 (when (= (setq cnt (1+ cnt)) ncol)
13041 (insert "\n")
13042 (when ingroup (insert " "))
13043 (setq cnt 0)))))
13044 (insert "\n")
13045 (goto-char (point-min))
13046 (unless expert (org-fit-window-to-buffer))
13047 (message "[a-z..]:Set [SPC]:clear")
13048 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13049 (cond
13050 ((or (= c ?\C-g)
13051 (and (= c ?q) (not (rassoc c fulltable))))
13052 (setq quit-flag t))
13053 ((= c ?\ ) nil)
13054 ((setq e (rassoc c fulltable) tg (car e))
13056 (t (setq quit-flag t)))))))
13058 (defun org-entry-is-todo-p ()
13059 (member (org-get-todo-state) org-not-done-keywords))
13061 (defun org-entry-is-done-p ()
13062 (member (org-get-todo-state) org-done-keywords))
13064 (defun org-get-todo-state ()
13065 "Return the TODO keyword of the current subtree."
13066 (save-excursion
13067 (org-back-to-heading t)
13068 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13069 (match-end 2)
13070 (match-string 2))))
13072 (defun org-at-date-range-p (&optional inactive-ok)
13073 "Non-nil if point is inside a date range.
13075 When optional argument INACTIVE-OK is non-nil, also consider
13076 inactive time ranges.
13078 When this function returns a non-nil value, match data is set
13079 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13080 on INACTIVE-OK."
13081 (interactive)
13082 (save-excursion
13083 (catch 'exit
13084 (let ((pos (point)))
13085 (skip-chars-backward "^[<\r\n")
13086 (skip-chars-backward "<[")
13087 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13088 (>= (match-end 0) pos)
13089 (throw 'exit t))
13090 (skip-chars-backward "^<[\r\n")
13091 (skip-chars-backward "<[")
13092 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13093 (>= (match-end 0) pos)
13094 (throw 'exit t)))
13095 nil)))
13097 (defun org-get-repeat (&optional timestamp)
13098 "Check if there is a time-stamp with repeater in this entry.
13100 Return the repeater, as a string, or nil. Also return nil when
13101 this function is called before first heading.
13103 When optional argument TIMESTAMP is a string, extract the
13104 repeater from there instead."
13105 (save-match-data
13106 (cond (timestamp
13107 (and (string-match org-repeat-re timestamp)
13108 (match-string-no-properties 1 timestamp)))
13109 ((org-before-first-heading-p) nil)
13111 (save-excursion
13112 (org-back-to-heading t)
13113 (let ((end (org-entry-end-position)))
13114 (catch :repeat
13115 (while (re-search-forward org-repeat-re end t)
13116 (when (save-match-data (org-at-timestamp-p 'agenda))
13117 (throw :repeat (match-string-no-properties 1)))))))))))
13119 (defvar org-last-changed-timestamp)
13120 (defvar org-last-inserted-timestamp)
13121 (defvar org-log-post-message)
13122 (defvar org-log-note-purpose)
13123 (defvar org-log-note-how nil)
13124 (defvar org-log-note-extra)
13125 (defun org-auto-repeat-maybe (done-word)
13126 "Check if the current headline contains a repeated time-stamp.
13128 If yes, set TODO state back to what it was and change the base date
13129 of repeating deadline/scheduled time stamps to new date.
13131 This function is run automatically after each state change to a DONE state."
13132 (let* ((repeat (org-get-repeat))
13133 (aa (assoc org-last-state org-todo-kwd-alist))
13134 (interpret (nth 1 aa))
13135 (head (nth 2 aa))
13136 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13137 (msg "Entry repeats: ")
13138 (org-log-done nil)
13139 (org-todo-log-states nil)
13140 (end (copy-marker (org-entry-end-position))))
13141 (unwind-protect
13142 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13143 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13144 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13145 org-todo-repeat-to-state)))
13146 (org-todo (cond
13147 ((and to-state (member to-state org-todo-keywords-1))
13148 to-state)
13149 ((eq interpret 'type) org-last-state)
13150 (head)
13151 (t 'none))))
13152 (org-back-to-heading t)
13153 (org-add-planning-info nil nil 'closed)
13154 ;; When `org-log-repeat' is non-nil or entry contains
13155 ;; a clock, set LAST_REPEAT property.
13156 (when (or org-log-repeat
13157 (catch :clock
13158 (while (re-search-forward org-clock-line-re end t)
13159 (when (org-at-clock-log-p) (throw :clock t)))))
13160 (org-entry-put nil "LAST_REPEAT" (format-time-string
13161 (org-time-stamp-format t t)
13162 (current-time))))
13163 (when org-log-repeat
13164 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13165 (memq 'org-add-log-note post-command-hook))
13166 ;; We are already setup for some record.
13167 (when (eq org-log-repeat 'note)
13168 ;; Make sure we take a note, not only a time stamp.
13169 (setq org-log-note-how 'note))
13170 ;; Set up for taking a record.
13171 (org-add-log-setup 'state
13172 (or done-word (car org-done-keywords))
13173 org-last-state
13174 org-log-repeat)))
13175 (let ((planning-re (regexp-opt
13176 (list org-scheduled-string org-deadline-string))))
13177 (while (re-search-forward org-ts-regexp end t)
13178 (let* ((ts (match-string 0))
13179 (planning? (org-at-planning-p))
13180 (type (if (not planning?) "Plain:"
13181 (save-excursion
13182 (re-search-backward
13183 planning-re (line-beginning-position) t)
13184 (match-string 0)))))
13185 (cond
13186 ;; Ignore fake time-stamps (e.g., within comments).
13187 ((not (org-at-timestamp-p 'agenda)))
13188 ;; Time-stamps without a repeater are usually
13189 ;; skipped. However, a SCHEDULED time-stamp without
13190 ;; one is removed, as they are no longer relevant.
13191 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13192 ts))
13193 (when (equal type org-scheduled-string)
13194 (org-remove-timestamp-with-keyword type)))
13196 (let ((n (string-to-number (match-string 2 ts)))
13197 (what (match-string 3 ts)))
13198 (when (equal what "w") (setq n (* n 7) what "d"))
13199 (when (and (equal what "h")
13200 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13201 ts)))
13202 (user-error
13203 "Cannot repeat in Repeat in %d hour(s) because no hour \
13204 has been set"
13206 ;; Preparation, see if we need to modify the start
13207 ;; date for the change.
13208 (when (match-end 1)
13209 (let ((time (save-match-data
13210 (org-time-string-to-time ts))))
13211 (cond
13212 ((equal (match-string 1 ts) ".")
13213 ;; Shift starting date to today
13214 (org-timestamp-change
13215 (- (org-today) (time-to-days time))
13216 'day))
13217 ((equal (match-string 1 ts) "+")
13218 (let ((nshiftmax 10)
13219 (nshift 0))
13220 (while (or (= nshift 0)
13221 (not (time-less-p (current-time) time)))
13222 (when (= (cl-incf nshift) nshiftmax)
13223 (or (y-or-n-p
13224 (format "%d repeater intervals were not \
13225 enough to shift date past today. Continue? "
13226 nshift))
13227 (user-error "Abort")))
13228 (org-timestamp-change n (cdr (assoc what whata)))
13229 (org-in-regexp org-ts-regexp3)
13230 (setq ts (match-string 1))
13231 (setq time
13232 (save-match-data
13233 (org-time-string-to-time ts)))))
13234 (org-timestamp-change (- n) (cdr (assoc what whata)))
13235 ;; Rematch, so that we have everything in place
13236 ;; for the real shift.
13237 (org-in-regexp org-ts-regexp3)
13238 (setq ts (match-string 1))
13239 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13240 ts)))))
13241 (save-excursion
13242 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13243 (setq msg
13244 (concat
13245 msg type " " org-last-changed-timestamp " "))))))))
13246 (setq org-log-post-message msg)
13247 (message "%s" msg))
13248 (set-marker end nil))))
13250 (defun org-show-todo-tree (arg)
13251 "Make a compact tree which shows all headlines marked with TODO.
13252 The tree will show the lines where the regexp matches, and all higher
13253 headlines above the match.
13254 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13255 With a numeric prefix N, construct a sparse tree for the Nth element
13256 of `org-todo-keywords-1'."
13257 (interactive "P")
13258 (let ((case-fold-search nil)
13259 (kwd-re
13260 (cond ((null arg) org-not-done-regexp)
13261 ((equal arg '(4))
13262 (let ((kwd
13263 (completing-read "Keyword (or KWD1|KWD2|...): "
13264 (mapcar #'list org-todo-keywords-1))))
13265 (concat "\\("
13266 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13267 "\\)\\>")))
13268 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13269 (regexp-quote (nth (1- (prefix-numeric-value arg))
13270 org-todo-keywords-1)))
13271 (t (user-error "Invalid prefix argument: %s" arg)))))
13272 (message "%d TODO entries found"
13273 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13275 (defun org--deadline-or-schedule (arg type time)
13276 "Insert DEADLINE or SCHEDULE information in current entry.
13277 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13278 `org-schedule' for information about ARG and TIME arguments."
13279 (let* ((deadline? (eq type 'deadline))
13280 (keyword (if deadline? org-deadline-string org-scheduled-string))
13281 (log (if deadline? org-log-redeadline org-log-reschedule))
13282 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13283 (old-date-time (and old-date (org-time-string-to-time old-date)))
13284 ;; Save repeater cookie from either TIME or current scheduled
13285 ;; time stamp. We are going to insert it back at the end of
13286 ;; the process.
13287 (repeater (or (and (org-string-nw-p time)
13288 ;; We use `org-repeat-re' because we need
13289 ;; to tell the difference between a real
13290 ;; repeater and a time delta, e.g. "+2d".
13291 (string-match org-repeat-re time)
13292 (match-string 1 time))
13293 (and (org-string-nw-p old-date)
13294 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13295 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13296 old-date)
13297 (match-string 1 old-date)))))
13298 (pcase arg
13299 (`(4)
13300 (when (and old-date log)
13301 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13302 nil old-date log))
13303 (org-remove-timestamp-with-keyword keyword)
13304 (message (if deadline? "Item no longer has a deadline."
13305 "Item is no longer scheduled.")))
13306 (`(16)
13307 (save-excursion
13308 (org-back-to-heading t)
13309 (let ((regexp (if deadline? org-deadline-time-regexp
13310 org-scheduled-time-regexp)))
13311 (if (not (re-search-forward regexp (line-end-position 2) t))
13312 (user-error (if deadline? "No deadline information to update"
13313 "No scheduled information to update"))
13314 (let* ((rpl0 (match-string 1))
13315 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13316 (msg (if deadline? "Warn starting from" "Delay until")))
13317 (replace-match
13318 (concat keyword
13319 " <" rpl
13320 (format " -%dd"
13321 (abs (- (time-to-days
13322 (save-match-data
13323 (org-read-date
13324 nil t nil msg old-date-time)))
13325 (time-to-days old-date-time))))
13326 ">") t t))))))
13328 (org-add-planning-info type time 'closed)
13329 (when (and old-date
13331 (not (equal old-date org-last-inserted-timestamp)))
13332 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13333 org-last-inserted-timestamp
13334 old-date
13335 log))
13336 (when repeater
13337 (save-excursion
13338 (org-back-to-heading t)
13339 (when (re-search-forward
13340 (concat keyword " " org-last-inserted-timestamp)
13341 (line-end-position 2)
13343 (goto-char (1- (match-end 0)))
13344 (insert " " repeater)
13345 (setq org-last-inserted-timestamp
13346 (concat (substring org-last-inserted-timestamp 0 -1)
13347 " " repeater
13348 (substring org-last-inserted-timestamp -1))))))
13349 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13350 org-last-inserted-timestamp)))))
13352 (defun org-deadline (arg &optional time)
13353 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13354 With one universal prefix argument, remove any deadline from the item.
13355 With two universal prefix arguments, prompt for a warning delay.
13356 With argument TIME, set the deadline at the corresponding date. TIME
13357 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13358 (interactive "P")
13359 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13360 (org-map-entries
13361 (lambda () (org--deadline-or-schedule arg 'deadline time))
13363 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13364 'region-start-level
13365 'region)
13366 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13367 (org--deadline-or-schedule arg 'deadline time)))
13369 (defun org-schedule (arg &optional time)
13370 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13371 With one universal prefix argument, remove any scheduling date from the item.
13372 With two universal prefix arguments, prompt for a delay cookie.
13373 With argument TIME, scheduled at the corresponding date. TIME can
13374 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13375 (interactive "P")
13376 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13377 (org-map-entries
13378 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13380 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13381 'region-start-level
13382 'region)
13383 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13384 (org--deadline-or-schedule arg 'scheduled time)))
13386 (defun org-get-scheduled-time (pom &optional inherit)
13387 "Get the scheduled time as a time tuple, of a format suitable
13388 for calling org-schedule with, or if there is no scheduling,
13389 returns nil."
13390 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13391 (when time
13392 (apply 'encode-time (org-parse-time-string time)))))
13394 (defun org-get-deadline-time (pom &optional inherit)
13395 "Get the deadline as a time tuple, of a format suitable for
13396 calling org-deadline with, or if there is no scheduling, returns
13397 nil."
13398 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13399 (when time
13400 (apply 'encode-time (org-parse-time-string time)))))
13402 (defun org-remove-timestamp-with-keyword (keyword)
13403 "Remove all time stamps with KEYWORD in the current entry."
13404 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13405 beg)
13406 (save-excursion
13407 (org-back-to-heading t)
13408 (setq beg (point))
13409 (outline-next-heading)
13410 (while (re-search-backward re beg t)
13411 (replace-match "")
13412 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13413 (equal (char-before) ?\ ))
13414 (backward-delete-char 1)
13415 (when (string-match "^[ \t]*$" (buffer-substring
13416 (point-at-bol) (point-at-eol)))
13417 (delete-region (point-at-bol)
13418 (min (point-max) (1+ (point-at-eol))))))))))
13420 (defvar org-time-was-given) ; dynamically scoped parameter
13421 (defvar org-end-time-was-given) ; dynamically scoped parameter
13423 (defun org-at-planning-p ()
13424 "Non-nil when point is on a planning info line."
13425 ;; This is as accurate and faster than `org-element-at-point' since
13426 ;; planning info location is fixed in the section.
13427 (org-with-wide-buffer
13428 (beginning-of-line)
13429 (and (looking-at-p org-planning-line-re)
13430 (eq (point)
13431 (ignore-errors
13432 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13433 (org-back-to-heading t)
13434 (org-with-limited-levels (org-back-to-heading t)))
13435 (line-beginning-position 2))))))
13437 (defun org-add-planning-info (what &optional time &rest remove)
13438 "Insert new timestamp with keyword in the planning line.
13439 WHAT indicates what kind of time stamp to add. It is a symbol
13440 among `closed', `deadline', `scheduled' and nil. TIME indicates
13441 the time to use. If none is given, the user is prompted for
13442 a date. REMOVE indicates what kind of entries to remove. An old
13443 WHAT entry will also be removed."
13444 (let (org-time-was-given org-end-time-was-given default-time default-input)
13445 (catch 'exit
13446 (when (and (memq what '(scheduled deadline))
13447 (or (not time)
13448 (and (stringp time)
13449 (string-match "^[-+]+[0-9]" time))))
13450 ;; Try to get a default date/time from existing timestamp
13451 (save-excursion
13452 (org-back-to-heading t)
13453 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13454 (when (re-search-forward (if (eq what 'scheduled)
13455 org-scheduled-time-regexp
13456 org-deadline-time-regexp)
13457 end t)
13458 (setq ts (match-string 1)
13459 default-time (apply 'encode-time (org-parse-time-string ts))
13460 default-input (and ts (org-get-compact-tod ts)))))))
13461 (when what
13462 (setq time
13463 (if (stringp time)
13464 ;; This is a string (relative or absolute), set
13465 ;; proper date.
13466 (apply #'encode-time
13467 (org-read-date-analyze
13468 time default-time (decode-time default-time)))
13469 ;; If necessary, get the time from the user
13470 (or time (org-read-date nil 'to-time nil nil
13471 default-time default-input)))))
13473 (org-with-wide-buffer
13474 (org-back-to-heading t)
13475 (forward-line)
13476 (unless (bolp) (insert "\n"))
13477 (cond ((looking-at-p org-planning-line-re)
13478 ;; Move to current indentation.
13479 (skip-chars-forward " \t")
13480 ;; Check if we have to remove something.
13481 (dolist (type (if what (cons what remove) remove))
13482 (save-excursion
13483 (when (re-search-forward
13484 (cl-case type
13485 (closed org-closed-time-regexp)
13486 (deadline org-deadline-time-regexp)
13487 (scheduled org-scheduled-time-regexp)
13488 (otherwise
13489 (error "Invalid planning type: %s" type)))
13490 (line-end-position) t)
13491 ;; Delete until next keyword or end of line.
13492 (delete-region
13493 (match-beginning 0)
13494 (if (re-search-forward org-keyword-time-not-clock-regexp
13495 (line-end-position)
13497 (match-beginning 0)
13498 (line-end-position))))))
13499 ;; If there is nothing more to add and no more keyword
13500 ;; is left, remove the line completely.
13501 (if (and (looking-at-p "[ \t]*$") (not what))
13502 (delete-region (line-beginning-position)
13503 (line-beginning-position 2))
13504 ;; If we removed last keyword, do not leave trailing
13505 ;; white space at the end of line.
13506 (let ((p (point)))
13507 (save-excursion
13508 (end-of-line)
13509 (unless (= (skip-chars-backward " \t" p) 0)
13510 (delete-region (point) (line-end-position)))))))
13511 ((not what) (throw 'exit nil)) ; Nothing to do.
13512 (t (insert-before-markers "\n")
13513 (backward-char 1)
13514 (when org-adapt-indentation
13515 (indent-to-column (1+ (org-outline-level))))))
13516 (when what
13517 ;; Insert planning keyword.
13518 (insert (cl-case what
13519 (closed org-closed-string)
13520 (deadline org-deadline-string)
13521 (scheduled org-scheduled-string)
13522 (otherwise (error "Invalid planning type: %s" what)))
13523 " ")
13524 ;; Insert associated timestamp.
13525 (let ((ts (org-insert-time-stamp
13526 time
13527 (or org-time-was-given
13528 (and (eq what 'closed) org-log-done-with-time))
13529 (eq what 'closed)
13530 nil nil (list org-end-time-was-given))))
13531 (unless (eolp) (insert " "))
13532 ts))))))
13534 (defvar org-log-note-marker (make-marker)
13535 "Marker pointing at the entry where the note is to be inserted.")
13536 (defvar org-log-note-purpose nil)
13537 (defvar org-log-note-state nil)
13538 (defvar org-log-note-previous-state nil)
13539 (defvar org-log-note-extra nil)
13540 (defvar org-log-note-window-configuration nil)
13541 (defvar org-log-note-return-to (make-marker))
13542 (defvar org-log-note-effective-time nil
13543 "Remembered current time so that dynamically scoped
13544 `org-extend-today-until' affects timestamps in state change log")
13546 (defvar org-log-post-message nil
13547 "Message to be displayed after a log note has been stored.
13548 The auto-repeater uses this.")
13550 (defun org-add-note ()
13551 "Add a note to the current entry.
13552 This is done in the same way as adding a state change note."
13553 (interactive)
13554 (org-add-log-setup 'note))
13556 (defun org-log-beginning (&optional create)
13557 "Return expected start of log notes in current entry.
13558 When optional argument CREATE is non-nil, the function creates
13559 a drawer to store notes, if necessary. Returned position ignores
13560 narrowing."
13561 (org-with-wide-buffer
13562 (let ((drawer (org-log-into-drawer)))
13563 (cond
13564 (drawer
13565 (org-end-of-meta-data)
13566 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13567 (end (if (org-at-heading-p) (point)
13568 (save-excursion (outline-next-heading) (point))))
13569 (case-fold-search t))
13570 (catch 'exit
13571 ;; Try to find existing drawer.
13572 (while (re-search-forward regexp end t)
13573 (let ((element (org-element-at-point)))
13574 (when (eq (org-element-type element) 'drawer)
13575 (let ((cend (org-element-property :contents-end element)))
13576 (when (and (not org-log-states-order-reversed) cend)
13577 (goto-char cend)))
13578 (throw 'exit nil))))
13579 ;; No drawer found. Create one, if permitted.
13580 (when create
13581 (unless (bolp) (insert "\n"))
13582 (let ((beg (point)))
13583 (insert ":" drawer ":\n:END:\n")
13584 (org-indent-region beg (point)))
13585 (end-of-line -1)))))
13587 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13588 (skip-chars-forward " \t\n")
13589 (beginning-of-line)
13590 (unless org-log-states-order-reversed
13591 (org-skip-over-state-notes)
13592 (skip-chars-backward " \t\n")
13593 (forward-line)))))
13594 (if (bolp) (point) (line-beginning-position 2))))
13596 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13597 "Set up the post command hook to take a note.
13598 If this is about to TODO state change, the new state is expected in STATE.
13599 HOW is an indicator what kind of note should be created.
13600 EXTRA is additional text that will be inserted into the notes buffer."
13601 (move-marker org-log-note-marker (point))
13602 (setq org-log-note-purpose purpose
13603 org-log-note-state state
13604 org-log-note-previous-state prev-state
13605 org-log-note-how how
13606 org-log-note-extra extra
13607 org-log-note-effective-time (org-current-effective-time))
13608 (add-hook 'post-command-hook 'org-add-log-note 'append))
13610 (defun org-skip-over-state-notes ()
13611 "Skip past the list of State notes in an entry."
13612 (when (ignore-errors (goto-char (org-in-item-p)))
13613 (let* ((struct (org-list-struct))
13614 (prevs (org-list-prevs-alist struct))
13615 (regexp
13616 (concat "[ \t]*- +"
13617 (replace-regexp-in-string
13618 " +" " +"
13619 (org-replace-escapes
13620 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13621 `(("%d" . ,org-ts-regexp-inactive)
13622 ("%D" . ,org-ts-regexp)
13623 ("%s" . "\"\\S-+\"")
13624 ("%S" . "\"\\S-+\"")
13625 ("%t" . ,org-ts-regexp-inactive)
13626 ("%T" . ,org-ts-regexp)
13627 ("%u" . ".*?")
13628 ("%U" . ".*?")))))))
13629 (while (looking-at-p regexp)
13630 (goto-char (or (org-list-get-next-item (point) struct prevs)
13631 (org-list-get-item-end (point) struct)))))))
13633 (defun org-add-log-note (&optional _purpose)
13634 "Pop up a window for taking a note, and add this note later."
13635 (remove-hook 'post-command-hook 'org-add-log-note)
13636 (setq org-log-note-window-configuration (current-window-configuration))
13637 (delete-other-windows)
13638 (move-marker org-log-note-return-to (point))
13639 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13640 (goto-char org-log-note-marker)
13641 (org-switch-to-buffer-other-window "*Org Note*")
13642 (erase-buffer)
13643 (if (memq org-log-note-how '(time state))
13644 (let (current-prefix-arg) (org-store-log-note))
13645 (let ((org-inhibit-startup t)) (org-mode))
13646 (insert (format "# Insert note for %s.
13647 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13648 (cond
13649 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13650 ((eq org-log-note-purpose 'done) "closed todo item")
13651 ((eq org-log-note-purpose 'state)
13652 (format "state change from \"%s\" to \"%s\""
13653 (or org-log-note-previous-state "")
13654 (or org-log-note-state "")))
13655 ((eq org-log-note-purpose 'reschedule)
13656 "rescheduling")
13657 ((eq org-log-note-purpose 'delschedule)
13658 "no longer scheduled")
13659 ((eq org-log-note-purpose 'redeadline)
13660 "changing deadline")
13661 ((eq org-log-note-purpose 'deldeadline)
13662 "removing deadline")
13663 ((eq org-log-note-purpose 'refile)
13664 "refiling")
13665 ((eq org-log-note-purpose 'note)
13666 "this entry")
13667 (t (error "This should not happen")))))
13668 (when org-log-note-extra (insert org-log-note-extra))
13669 (setq-local org-finish-function 'org-store-log-note)
13670 (run-hooks 'org-log-buffer-setup-hook)))
13672 (defvar org-note-abort nil) ; dynamically scoped
13673 (defun org-store-log-note ()
13674 "Finish taking a log note, and insert it to where it belongs."
13675 (let ((txt (prog1 (buffer-string)
13676 (kill-buffer)))
13677 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13678 lines)
13679 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13680 (setq txt (replace-match "" t t txt)))
13681 (when (string-match "\\s-+\\'" txt)
13682 (setq txt (replace-match "" t t txt)))
13683 (setq lines (org-split-string txt "\n"))
13684 (when (org-string-nw-p note)
13685 (setq note
13686 (org-replace-escapes
13687 note
13688 (list (cons "%u" (user-login-name))
13689 (cons "%U" user-full-name)
13690 (cons "%t" (format-time-string
13691 (org-time-stamp-format 'long 'inactive)
13692 org-log-note-effective-time))
13693 (cons "%T" (format-time-string
13694 (org-time-stamp-format 'long nil)
13695 org-log-note-effective-time))
13696 (cons "%d" (format-time-string
13697 (org-time-stamp-format nil 'inactive)
13698 org-log-note-effective-time))
13699 (cons "%D" (format-time-string
13700 (org-time-stamp-format nil nil)
13701 org-log-note-effective-time))
13702 (cons "%s" (cond
13703 ((not org-log-note-state) "")
13704 ((string-match-p org-ts-regexp
13705 org-log-note-state)
13706 (format "\"[%s]\""
13707 (substring org-log-note-state 1 -1)))
13708 (t (format "\"%s\"" org-log-note-state))))
13709 (cons "%S"
13710 (cond
13711 ((not org-log-note-previous-state) "")
13712 ((string-match-p org-ts-regexp
13713 org-log-note-previous-state)
13714 (format "\"[%s]\""
13715 (substring
13716 org-log-note-previous-state 1 -1)))
13717 (t (format "\"%s\""
13718 org-log-note-previous-state)))))))
13719 (when lines (setq note (concat note " \\\\")))
13720 (push note lines))
13721 (when (and lines (not (or current-prefix-arg org-note-abort)))
13722 (with-current-buffer (marker-buffer org-log-note-marker)
13723 (org-with-wide-buffer
13724 ;; Find location for the new note.
13725 (goto-char org-log-note-marker)
13726 (set-marker org-log-note-marker nil)
13727 ;; Note associated to a clock is to be located right after
13728 ;; the clock. Do not move point.
13729 (unless (eq org-log-note-purpose 'clock-out)
13730 (goto-char (org-log-beginning t)))
13731 ;; Make sure point is at the beginning of an empty line.
13732 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13733 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13734 ;; In an existing list, add a new item at the top level.
13735 ;; Otherwise, indent line like a regular one.
13736 (let ((itemp (org-in-item-p)))
13737 (if itemp
13738 (indent-line-to
13739 (let ((struct (save-excursion
13740 (goto-char itemp) (org-list-struct))))
13741 (org-list-get-ind (org-list-get-top-point struct) struct)))
13742 (org-indent-line)))
13743 (insert (org-list-bullet-string "-") (pop lines))
13744 (let ((ind (org-list-item-body-column (line-beginning-position))))
13745 (dolist (line lines)
13746 (insert "\n")
13747 (indent-line-to ind)
13748 (insert line)))
13749 (message "Note stored")
13750 (org-back-to-heading t)
13751 (org-cycle-hide-drawers 'children))
13752 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13753 ;; from within `org-add-log-note' because `buffer-undo-list'
13754 ;; is then modified outside of `org-with-remote-undo'.
13755 (when (eq this-command 'org-agenda-todo)
13756 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13757 ;; Don't add undo information when called from `org-agenda-todo'.
13758 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13759 (set-window-configuration org-log-note-window-configuration)
13760 (with-current-buffer (marker-buffer org-log-note-return-to)
13761 (goto-char org-log-note-return-to))
13762 (move-marker org-log-note-return-to nil)
13763 (when org-log-post-message (message "%s" org-log-post-message))))
13765 (defun org-remove-empty-drawer-at (pos)
13766 "Remove an empty drawer at position POS.
13767 POS may also be a marker."
13768 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13769 (org-with-wide-buffer
13770 (goto-char pos)
13771 (let ((drawer (org-element-at-point)))
13772 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13773 (not (org-element-property :contents-begin drawer)))
13774 (delete-region (org-element-property :begin drawer)
13775 (progn (goto-char (org-element-property :end drawer))
13776 (skip-chars-backward " \r\t\n")
13777 (forward-line)
13778 (point))))))))
13780 (defvar org-ts-type nil)
13781 (defun org-sparse-tree (&optional arg type)
13782 "Create a sparse tree, prompt for the details.
13783 This command can create sparse trees. You first need to select the type
13784 of match used to create the tree:
13786 t Show all TODO entries.
13787 T Show entries with a specific TODO keyword.
13788 m Show entries selected by a tags/property match.
13789 p Enter a property name and its value (both with completion on existing
13790 names/values) and show entries with that property.
13791 r Show entries matching a regular expression (`/' can be used as well).
13792 b Show deadlines and scheduled items before a date.
13793 a Show deadlines and scheduled items after a date.
13794 d Show deadlines due within `org-deadline-warning-days'.
13795 D Show deadlines and scheduled items between a date range."
13796 (interactive "P")
13797 (setq type (or type org-sparse-tree-default-date-type))
13798 (setq org-ts-type type)
13799 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13800 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13801 \[c]ycle through date types: %s"
13802 (cl-case type
13803 (all "all timestamps")
13804 (scheduled "only scheduled")
13805 (deadline "only deadline")
13806 (active "only active timestamps")
13807 (inactive "only inactive timestamps")
13808 (closed "with a closed time-stamp")
13809 (otherwise "scheduled/deadline")))
13810 (let ((answer (read-char-exclusive)))
13811 (cl-case answer
13813 (org-sparse-tree
13815 (cadr
13816 (memq type '(nil all scheduled deadline active inactive closed)))))
13817 (?d (call-interactively 'org-check-deadlines))
13818 (?b (call-interactively 'org-check-before-date))
13819 (?a (call-interactively 'org-check-after-date))
13820 (?D (call-interactively 'org-check-dates-range))
13821 (?t (call-interactively 'org-show-todo-tree))
13822 (?T (org-show-todo-tree '(4)))
13823 (?m (call-interactively 'org-match-sparse-tree))
13824 ((?p ?P)
13825 (let* ((kwd (completing-read
13826 "Property: " (mapcar #'list (org-buffer-property-keys))))
13827 (value (completing-read
13828 "Value: " (mapcar #'list (org-property-values kwd)))))
13829 (unless (string-match "\\`{.*}\\'" value)
13830 (setq value (concat "\"" value "\"")))
13831 (org-match-sparse-tree arg (concat kwd "=" value))))
13832 ((?r ?R ?/) (call-interactively 'org-occur))
13833 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13835 (defvar-local org-occur-highlights nil
13836 "List of overlays used for occur matches.")
13837 (defvar-local org-occur-parameters nil
13838 "Parameters of the active org-occur calls.
13839 This is a list, each call to org-occur pushes as cons cell,
13840 containing the regular expression and the callback, onto the list.
13841 The list can contain several entries if `org-occur' has been called
13842 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13843 will only contain one set of parameters. When the highlights are
13844 removed (for example with `C-c C-c', or with the next edit (depending
13845 on `org-remove-highlights-with-change'), this variable is emptied
13846 as well.")
13848 (defun org-occur (regexp &optional keep-previous callback)
13849 "Make a compact tree which shows all matches of REGEXP.
13851 The tree will show the lines where the regexp matches, and any other context
13852 defined in `org-show-context-detail', which see.
13854 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13855 done by a previous call to `org-occur' will be kept, to allow stacking of
13856 calls to this command.
13858 Optional argument CALLBACK can be a function of no argument. In this case,
13859 it is called with point at the end of the match, match data being set
13860 accordingly. Current match is shown only if the return value is non-nil.
13861 The function must neither move point nor alter narrowing."
13862 (interactive "sRegexp: \nP")
13863 (when (equal regexp "")
13864 (user-error "Regexp cannot be empty"))
13865 (unless keep-previous
13866 (org-remove-occur-highlights nil nil t))
13867 (push (cons regexp callback) org-occur-parameters)
13868 (let ((cnt 0))
13869 (save-excursion
13870 (goto-char (point-min))
13871 (when (or (not keep-previous) ; do not want to keep
13872 (not org-occur-highlights)) ; no previous matches
13873 ;; hide everything
13874 (org-overview))
13875 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13876 (isearch-no-upper-case-p regexp t)
13877 org-occur-case-fold-search)))
13878 (while (re-search-forward regexp nil t)
13879 (when (or (not callback)
13880 (save-match-data (funcall callback)))
13881 (setq cnt (1+ cnt))
13882 (when org-highlight-sparse-tree-matches
13883 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13884 (org-show-context 'occur-tree)))))
13885 (when org-remove-highlights-with-change
13886 (add-hook 'before-change-functions 'org-remove-occur-highlights
13887 nil 'local))
13888 (unless org-sparse-tree-open-archived-trees
13889 (org-hide-archived-subtrees (point-min) (point-max)))
13890 (run-hooks 'org-occur-hook)
13891 (when (called-interactively-p 'interactive)
13892 (message "%d match(es) for regexp %s" cnt regexp))
13893 cnt))
13895 (defun org-occur-next-match (&optional n _reset)
13896 "Function for `next-error-function' to find sparse tree matches.
13897 N is the number of matches to move, when negative move backwards.
13898 This function always goes back to the starting point when no
13899 match is found."
13900 (let* ((limit (if (< n 0) (point-min) (point-max)))
13901 (search-func (if (< n 0)
13902 'previous-single-char-property-change
13903 'next-single-char-property-change))
13904 (n (abs n))
13905 (pos (point))
13907 (catch 'exit
13908 (while (setq p1 (funcall search-func (point) 'org-type))
13909 (when (equal p1 limit)
13910 (goto-char pos)
13911 (user-error "No more matches"))
13912 (when (equal (get-char-property p1 'org-type) 'org-occur)
13913 (setq n (1- n))
13914 (when (= n 0)
13915 (goto-char p1)
13916 (throw 'exit (point))))
13917 (goto-char p1))
13918 (goto-char p1)
13919 (user-error "No more matches"))))
13921 (defun org-show-context (&optional key)
13922 "Make sure point and context are visible.
13923 Optional argument KEY, when non-nil, is a symbol. See
13924 `org-show-context-detail' for allowed values and how much is to
13925 be shown."
13926 (org-show-set-visibility
13927 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13928 ((cdr (assq key org-show-context-detail)))
13929 (t (cdr (assq 'default org-show-context-detail))))))
13931 (defun org-show-set-visibility (detail)
13932 "Set visibility around point according to DETAIL.
13933 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13934 `tree', `canonical' or t. See `org-show-context-detail' for more
13935 information."
13936 ;; Show current heading and possibly its entry, following headline
13937 ;; or all children.
13938 (if (and (org-at-heading-p) (not (eq detail 'local)))
13939 (org-flag-heading nil)
13940 (org-show-entry)
13941 ;; If point is hidden within a drawer or a block, make sure to
13942 ;; expose it.
13943 (dolist (o (overlays-at (point)))
13944 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13945 (delete-overlay o)))
13946 (unless (org-before-first-heading-p)
13947 (org-with-limited-levels
13948 (cl-case detail
13949 ((tree canonical t) (org-show-children))
13950 ((nil minimal ancestors))
13951 (t (save-excursion
13952 (outline-next-heading)
13953 (org-flag-heading nil)))))))
13954 ;; Show all siblings.
13955 (when (eq detail 'lineage) (org-show-siblings))
13956 ;; Show ancestors, possibly with their children.
13957 (when (memq detail '(ancestors lineage tree canonical t))
13958 (save-excursion
13959 (while (org-up-heading-safe)
13960 (org-flag-heading nil)
13961 (when (memq detail '(canonical t)) (org-show-entry))
13962 (when (memq detail '(tree canonical t)) (org-show-children))))))
13964 (defvar org-reveal-start-hook nil
13965 "Hook run before revealing a location.")
13967 (defun org-reveal (&optional siblings)
13968 "Show current entry, hierarchy above it, and the following headline.
13970 This can be used to show a consistent set of context around
13971 locations exposed with `org-show-context'.
13973 With optional argument SIBLINGS, on each level of the hierarchy all
13974 siblings are shown. This repairs the tree structure to what it would
13975 look like when opened with hierarchical calls to `org-cycle'.
13977 With a \\[universal-argument] \\[universal-argument] prefix, \
13978 go to the parent and show the entire tree."
13979 (interactive "P")
13980 (run-hooks 'org-reveal-start-hook)
13981 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13982 ((equal siblings '(16))
13983 (save-excursion
13984 (when (org-up-heading-safe)
13985 (org-show-subtree)
13986 (run-hook-with-args 'org-cycle-hook 'subtree))))
13987 (t (org-show-set-visibility 'lineage))))
13989 (defun org-highlight-new-match (beg end)
13990 "Highlight from BEG to END and mark the highlight is an occur headline."
13991 (let ((ov (make-overlay beg end)))
13992 (overlay-put ov 'face 'secondary-selection)
13993 (overlay-put ov 'org-type 'org-occur)
13994 (push ov org-occur-highlights)))
13996 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13997 "Remove the occur highlights from the buffer.
13998 BEG and END are ignored. If NOREMOVE is nil, remove this function
13999 from the `before-change-functions' in the current buffer."
14000 (interactive)
14001 (unless org-inhibit-highlight-removal
14002 (mapc #'delete-overlay org-occur-highlights)
14003 (setq org-occur-highlights nil)
14004 (setq org-occur-parameters nil)
14005 (unless noremove
14006 (remove-hook 'before-change-functions
14007 'org-remove-occur-highlights 'local))))
14009 ;;;; Priorities
14011 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14012 "Regular expression matching the priority indicator.")
14014 (defvar org-remove-priority-next-time nil)
14016 (defun org-priority-up ()
14017 "Increase the priority of the current item."
14018 (interactive)
14019 (org-priority 'up))
14021 (defun org-priority-down ()
14022 "Decrease the priority of the current item."
14023 (interactive)
14024 (org-priority 'down))
14026 (defun org-priority (&optional action _show)
14027 "Change the priority of an item.
14028 ACTION can be `set', `up', `down', or a character."
14029 (interactive "P")
14030 (if (equal action '(4))
14031 (org-show-priority)
14032 (unless org-enable-priority-commands
14033 (user-error "Priority commands are disabled"))
14034 (setq action (or action 'set))
14035 (let (current new news have remove)
14036 (save-excursion
14037 (org-back-to-heading t)
14038 (when (looking-at org-priority-regexp)
14039 (setq current (string-to-char (match-string 2))
14040 have t))
14041 (cond
14042 ((eq action 'remove)
14043 (setq remove t new ?\ ))
14044 ((or (eq action 'set)
14045 (integerp action))
14046 (if (not (eq action 'set))
14047 (setq new action)
14048 (message "Priority %c-%c, SPC to remove: "
14049 org-highest-priority org-lowest-priority)
14050 (save-match-data
14051 (setq new (read-char-exclusive))))
14052 (when (and (= (upcase org-highest-priority) org-highest-priority)
14053 (= (upcase org-lowest-priority) org-lowest-priority))
14054 (setq new (upcase new)))
14055 (cond ((equal new ?\ ) (setq remove t))
14056 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14057 (user-error "Priority must be between `%c' and `%c'"
14058 org-highest-priority org-lowest-priority))))
14059 ((eq action 'up)
14060 (setq new (if have
14061 (1- current) ; normal cycling
14062 ;; last priority was empty
14063 (if (eq last-command this-command)
14064 org-lowest-priority ; wrap around empty to lowest
14065 ;; default
14066 (if org-priority-start-cycle-with-default
14067 org-default-priority
14068 (1- org-default-priority))))))
14069 ((eq action 'down)
14070 (setq new (if have
14071 (1+ current) ; normal cycling
14072 ;; last priority was empty
14073 (if (eq last-command this-command)
14074 org-highest-priority ; wrap around empty to highest
14075 ;; default
14076 (if org-priority-start-cycle-with-default
14077 org-default-priority
14078 (1+ org-default-priority))))))
14079 (t (user-error "Invalid action")))
14080 (when (or (< (upcase new) org-highest-priority)
14081 (> (upcase new) org-lowest-priority))
14082 (if (and (memq action '(up down))
14083 (not have) (not (eq last-command this-command)))
14084 ;; `new' is from default priority
14085 (error
14086 "The default can not be set, see `org-default-priority' why")
14087 ;; normal cycling: `new' is beyond highest/lowest priority
14088 ;; and is wrapped around to the empty priority
14089 (setq remove t)))
14090 (setq news (format "%c" new))
14091 (if have
14092 (if remove
14093 (replace-match "" t t nil 1)
14094 (replace-match news t t nil 2))
14095 (if remove
14096 (user-error "No priority cookie found in line")
14097 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14098 (if (match-end 2)
14099 (progn
14100 (goto-char (match-end 2))
14101 (insert " [#" news "]"))
14102 (goto-char (match-beginning 3))
14103 (insert "[#" news "] "))))
14104 (org-set-tags nil 'align))
14105 (if remove
14106 (message "Priority removed")
14107 (message "Priority of current item set to %s" news)))))
14109 (defun org-show-priority ()
14110 "Show the priority of the current item.
14111 This priority is composed of the main priority given with the [#A] cookies,
14112 and by additional input from the age of a schedules or deadline entry."
14113 (interactive)
14114 (let ((pri (if (eq major-mode 'org-agenda-mode)
14115 (org-get-at-bol 'priority)
14116 (save-excursion
14117 (save-match-data
14118 (beginning-of-line)
14119 (and (looking-at org-heading-regexp)
14120 (org-get-priority (match-string 0))))))))
14121 (message "Priority is %d" (if pri pri -1000))))
14123 (defun org-get-priority (s)
14124 "Find priority cookie and return priority."
14125 (save-match-data
14126 (if (functionp org-get-priority-function)
14127 (funcall org-get-priority-function)
14128 (if (not (string-match org-priority-regexp s))
14129 (* 1000 (- org-lowest-priority org-default-priority))
14130 (* 1000 (- org-lowest-priority
14131 (string-to-char (match-string 2 s))))))))
14133 ;;;; Tags
14135 (defvar org-agenda-archives-mode)
14136 (defvar org-map-continue-from nil
14137 "Position from where mapping should continue.
14138 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14140 (defvar org-scanner-tags nil
14141 "The current tag list while the tags scanner is running.")
14143 (defvar org-trust-scanner-tags nil
14144 "Should `org-get-tags-at' use the tags for the scanner.
14145 This is for internal dynamical scoping only.
14146 When this is non-nil, the function `org-get-tags-at' will return the value
14147 of `org-scanner-tags' instead of building the list by itself. This
14148 can lead to large speed-ups when the tags scanner is used in a file with
14149 many entries, and when the list of tags is retrieved, for example to
14150 obtain a list of properties. Building the tags list for each entry in such
14151 a file becomes an N^2 operation - but with this variable set, it scales
14152 as N.")
14154 (defvar org--matcher-tags-todo-only nil)
14156 (defun org-scan-tags (action matcher todo-only &optional start-level)
14157 "Scan headline tags with inheritance and produce output ACTION.
14159 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14160 or `agenda' to produce an entry list for an agenda view. It can also be
14161 a Lisp form or a function that should be called at each matched headline, in
14162 this case the return value is a list of all return values from these calls.
14164 MATCHER is a function accepting three arguments, returning
14165 a non-nil value whenever a given set of tags qualifies a headline
14166 for inclusion. See `org-make-tags-matcher' for more information.
14167 As a special case, it can also be set to t (respectively nil) in
14168 order to match all (respectively none) headline.
14170 When TODO-ONLY is non-nil, only lines with a not-done TODO
14171 keyword are included in the output.
14173 START-LEVEL can be a string with asterisks, reducing the scope to
14174 headlines matching this string."
14175 (require 'org-agenda)
14176 (let* ((re (concat "^"
14177 (if start-level
14178 ;; Get the correct level to match
14179 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14180 org-outline-regexp)
14181 " *\\(\\<\\("
14182 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14183 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14184 (props (list 'face 'default
14185 'done-face 'org-agenda-done
14186 'undone-face 'default
14187 'mouse-face 'highlight
14188 'org-not-done-regexp org-not-done-regexp
14189 'org-todo-regexp org-todo-regexp
14190 'org-complex-heading-regexp org-complex-heading-regexp
14191 'help-echo
14192 (format "mouse-2 or RET jump to org file %s"
14193 (abbreviate-file-name
14194 (or (buffer-file-name (buffer-base-buffer))
14195 (buffer-name (buffer-base-buffer)))))))
14196 (org-map-continue-from nil)
14197 lspos tags tags-list
14198 (tags-alist (list (cons 0 org-file-tags)))
14199 (llast 0) rtn rtn1 level category i txt
14200 todo marker entry priority
14201 ts-date ts-date-type ts-date-pair)
14202 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14203 (setq action (list 'lambda nil action)))
14204 (save-excursion
14205 (goto-char (point-min))
14206 (when (eq action 'sparse-tree)
14207 (org-overview)
14208 (org-remove-occur-highlights))
14209 (while (let (case-fold-search)
14210 (re-search-forward re nil t))
14211 (setq org-map-continue-from nil)
14212 (catch :skip
14213 (setq todo
14214 ;; TODO: is the 1-2 difference a bug?
14215 (when (match-end 1) (match-string-no-properties 2))
14216 tags (when (match-end 4) (match-string-no-properties 4)))
14217 (goto-char (setq lspos (match-beginning 0)))
14218 (setq level (org-reduced-level (org-outline-level))
14219 category (org-get-category))
14220 (when (eq action 'agenda)
14221 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14222 ts-date (car ts-date-pair)
14223 ts-date-type (cdr ts-date-pair)))
14224 (setq i llast llast level)
14225 ;; remove tag lists from same and sublevels
14226 (while (>= i level)
14227 (when (setq entry (assoc i tags-alist))
14228 (setq tags-alist (delete entry tags-alist)))
14229 (setq i (1- i)))
14230 ;; add the next tags
14231 (when tags
14232 (setq tags (org-split-string tags ":")
14233 tags-alist
14234 (cons (cons level tags) tags-alist)))
14235 ;; compile tags for current headline
14236 (setq tags-list
14237 (if org-use-tag-inheritance
14238 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14239 tags)
14240 org-scanner-tags tags-list)
14241 (when org-use-tag-inheritance
14242 (setcdr (car tags-alist)
14243 (mapcar (lambda (x)
14244 (setq x (copy-sequence x))
14245 (org-add-prop-inherited x))
14246 (cdar tags-alist))))
14247 (when (and tags org-use-tag-inheritance
14248 (or (not (eq t org-use-tag-inheritance))
14249 org-tags-exclude-from-inheritance))
14250 ;; Selective inheritance, remove uninherited ones.
14251 (setcdr (car tags-alist)
14252 (org-remove-uninherited-tags (cdar tags-alist))))
14253 (when (and
14255 ;; eval matcher only when the todo condition is OK
14256 (and (or (not todo-only) (member todo org-not-done-keywords))
14257 (if (functionp matcher)
14258 (let ((case-fold-search t) (org-trust-scanner-tags t))
14259 (funcall matcher todo tags-list level))
14260 matcher))
14262 ;; Call the skipper, but return t if it does not
14263 ;; skip, so that the `and' form continues evaluating.
14264 (progn
14265 (unless (eq action 'sparse-tree) (org-agenda-skip))
14268 ;; Check if timestamps are deselecting this entry
14269 (or (not todo-only)
14270 (and (member todo org-not-done-keywords)
14271 (or (not org-agenda-tags-todo-honor-ignore-options)
14272 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14274 ;; select this headline
14275 (cond
14276 ((eq action 'sparse-tree)
14277 (and org-highlight-sparse-tree-matches
14278 (org-get-heading) (match-end 0)
14279 (org-highlight-new-match
14280 (match-beginning 1) (match-end 1)))
14281 (org-show-context 'tags-tree))
14282 ((eq action 'agenda)
14283 (setq txt (org-agenda-format-item
14285 (concat
14286 (if (eq org-tags-match-list-sublevels 'indented)
14287 (make-string (1- level) ?.) "")
14288 (org-get-heading))
14289 (make-string level ?\s)
14290 category
14291 tags-list)
14292 priority (org-get-priority txt))
14293 (goto-char lspos)
14294 (setq marker (org-agenda-new-marker))
14295 (org-add-props txt props
14296 'org-marker marker 'org-hd-marker marker 'org-category category
14297 'todo-state todo
14298 'ts-date ts-date
14299 'priority priority
14300 'type (concat "tagsmatch" ts-date-type))
14301 (push txt rtn))
14302 ((functionp action)
14303 (setq org-map-continue-from nil)
14304 (save-excursion
14305 (setq rtn1 (funcall action))
14306 (push rtn1 rtn)))
14307 (t (user-error "Invalid action")))
14309 ;; if we are to skip sublevels, jump to end of subtree
14310 (unless org-tags-match-list-sublevels
14311 (org-end-of-subtree t)
14312 (backward-char 1))))
14313 ;; Get the correct position from where to continue
14314 (if org-map-continue-from
14315 (goto-char org-map-continue-from)
14316 (and (= (point) lspos) (end-of-line 1)))))
14317 (when (and (eq action 'sparse-tree)
14318 (not org-sparse-tree-open-archived-trees))
14319 (org-hide-archived-subtrees (point-min) (point-max)))
14320 (nreverse rtn)))
14322 (defun org-remove-uninherited-tags (tags)
14323 "Remove all tags that are not inherited from the list TAGS."
14324 (cond
14325 ((eq org-use-tag-inheritance t)
14326 (if org-tags-exclude-from-inheritance
14327 (org-delete-all org-tags-exclude-from-inheritance tags)
14328 tags))
14329 ((not org-use-tag-inheritance) nil)
14330 ((stringp org-use-tag-inheritance)
14331 (delq nil (mapcar
14332 (lambda (x)
14333 (if (and (string-match org-use-tag-inheritance x)
14334 (not (member x org-tags-exclude-from-inheritance)))
14335 x nil))
14336 tags)))
14337 ((listp org-use-tag-inheritance)
14338 (delq nil (mapcar
14339 (lambda (x)
14340 (if (member x org-use-tag-inheritance) x nil))
14341 tags)))))
14343 (defun org-match-sparse-tree (&optional todo-only match)
14344 "Create a sparse tree according to tags string MATCH.
14346 MATCH is a string with match syntax. It can contain a selection
14347 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14348 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14349 those. See the manual for details.
14351 If optional argument TODO-ONLY is non-nil, only select lines that
14352 are also TODO tasks."
14353 (interactive "P")
14354 (org-agenda-prepare-buffers (list (current-buffer)))
14355 (let ((org--matcher-tags-todo-only todo-only))
14356 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14357 org--matcher-tags-todo-only)))
14359 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14361 (defvar org-cached-props nil)
14362 (defun org-cached-entry-get (pom property)
14363 (if (or (eq t org-use-property-inheritance)
14364 (and (stringp org-use-property-inheritance)
14365 (let ((case-fold-search t))
14366 (string-match-p org-use-property-inheritance property)))
14367 (and (listp org-use-property-inheritance)
14368 (member-ignore-case property org-use-property-inheritance)))
14369 ;; Caching is not possible, check it directly.
14370 (org-entry-get pom property 'inherit)
14371 ;; Get all properties, so we can do complicated checks easily.
14372 (cdr (assoc-string property
14373 (or org-cached-props
14374 (setq org-cached-props (org-entry-properties pom)))
14375 t))))
14377 (defun org-global-tags-completion-table (&optional files)
14378 "Return the list of all tags in all agenda buffer/files.
14379 Optional FILES argument is a list of files which can be used
14380 instead of the agenda files."
14381 (save-excursion
14382 (org-uniquify
14383 (delq nil
14384 (apply #'append
14385 (mapcar
14386 (lambda (file)
14387 (set-buffer (find-file-noselect file))
14388 (mapcar (lambda (x)
14389 (and (stringp (car-safe x))
14390 (list (car-safe x))))
14391 (or org-current-tag-alist (org-get-buffer-tags))))
14392 (if (car-safe files) files
14393 (org-agenda-files))))))))
14395 (defun org-make-tags-matcher (match)
14396 "Create the TAGS/TODO matcher form for the selection string MATCH.
14398 Returns a cons of the selection string MATCH and a function
14399 implementing the matcher.
14401 The matcher is to be called at an Org entry, with point on the
14402 headline, and returns non-nil if the entry matches the selection
14403 string MATCH. It must be called with three arguments: the TODO
14404 keyword at the entry (or nil if none), the list of all tags at
14405 the entry including inherited ones and the reduced level of the
14406 headline. Additionally, the category of the entry, if any, must
14407 be specified as the text property `org-category' on the headline.
14409 This function sets the variable `org--matcher-tags-todo-only' to
14410 a non-nil value if the matcher restricts matching to TODO
14411 entries, otherwise it is not touched.
14413 See also `org-scan-tags'."
14414 (unless match
14415 ;; Get a new match request, with completion against the global
14416 ;; tags table and the local tags in current buffer.
14417 (let ((org-last-tags-completion-table
14418 (org-uniquify
14419 (delq nil (append (org-get-buffer-tags)
14420 (org-global-tags-completion-table))))))
14421 (setq match
14422 (completing-read
14423 "Match: "
14424 'org-tags-completion-function nil nil nil 'org-tags-history))))
14426 (let ((match0 match)
14427 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14428 (start 0)
14429 tagsmatch todomatch tagsmatcher todomatcher)
14431 ;; Expand group tags.
14432 (setq match (org-tags-expand match))
14434 ;; Check if there is a TODO part of this match, which would be the
14435 ;; part after a "/". To make sure that this slash is not part of
14436 ;; a property value to be matched against, we also check that
14437 ;; there is no / after that slash. First, find the last slash.
14438 (let ((s 0))
14439 (while (string-match "/+" match s)
14440 (setq start (match-beginning 0))
14441 (setq s (match-end 0))))
14442 (if (and (string-match "/+" match start)
14443 (not (string-match-p "\"" match start)))
14444 ;; Match contains also a TODO-matching request.
14445 (progn
14446 (setq tagsmatch (substring match 0 (match-beginning 0)))
14447 (setq todomatch (substring match (match-end 0)))
14448 (when (string-prefix-p "!" todomatch)
14449 (setq org--matcher-tags-todo-only t)
14450 (setq todomatch (substring todomatch 1)))
14451 (when (string-match "\\`\\s-*\\'" todomatch)
14452 (setq todomatch nil)))
14453 ;; Only matching tags.
14454 (setq tagsmatch match)
14455 (setq todomatch nil))
14457 ;; Make the tags matcher.
14458 (when (org-string-nw-p tagsmatch)
14459 (let ((orlist nil)
14460 (orterms (org-split-string tagsmatch "|"))
14461 term)
14462 (while (setq term (pop orterms))
14463 (while (and (equal (substring term -1) "\\") orterms)
14464 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14465 (while (string-match re term)
14466 (let* ((rest (substring term (match-end 0)))
14467 (minus (and (match-end 1)
14468 (equal (match-string 1 term) "-")))
14469 (tag (save-match-data
14470 (replace-regexp-in-string
14471 "\\\\-" "-" (match-string 2 term))))
14472 (regexp (eq (string-to-char tag) ?{))
14473 (levelp (match-end 4))
14474 (propp (match-end 5))
14476 (cond
14477 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14478 (levelp
14479 `(,(org-op-to-function (match-string 3 term))
14480 level
14481 ,(string-to-number (match-string 4 term))))
14482 (propp
14483 (let* ((gv (pcase (upcase (match-string 5 term))
14484 ("CATEGORY"
14485 '(get-text-property (point) 'org-category))
14486 ("TODO" 'todo)
14487 (p `(org-cached-entry-get nil ,p))))
14488 (pv (match-string 7 term))
14489 (regexp (eq (string-to-char pv) ?{))
14490 (strp (eq (string-to-char pv) ?\"))
14491 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14492 (po (org-op-to-function (match-string 6 term)
14493 (if timep 'time strp))))
14494 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14495 (when timep (setq pv (org-matcher-time pv)))
14496 (cond ((and regexp (eq po 'org<>))
14497 `(not (string-match ,pv (or ,gv ""))))
14498 (regexp `(string-match ,pv (or ,gv "")))
14499 (strp `(,po (or ,gv "") ,pv))
14501 `(,po
14502 (string-to-number (or ,gv ""))
14503 ,(string-to-number pv))))))
14504 (t `(member ,tag tags-list)))))
14505 (push (if minus `(not ,mm) mm) tagsmatcher)
14506 (setq term rest)))
14507 (push `(and ,@tagsmatcher) orlist)
14508 (setq tagsmatcher nil))
14509 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14511 ;; Make the TODO matcher.
14512 (when (org-string-nw-p todomatch)
14513 (let ((orlist nil))
14514 (dolist (term (org-split-string todomatch "|"))
14515 (while (string-match re term)
14516 (let* ((minus (and (match-end 1)
14517 (equal (match-string 1 term) "-")))
14518 (kwd (match-string 2 term))
14519 (regexp (eq (string-to-char kwd) ?{))
14520 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14521 `(equal todo ,kwd))))
14522 (push (if minus `(not ,mm) mm) todomatcher))
14523 (setq term (substring term (match-end 0))))
14524 (push (if (> (length todomatcher) 1)
14525 (cons 'and todomatcher)
14526 (car todomatcher))
14527 orlist)
14528 (setq todomatcher nil))
14529 (setq todomatcher (cons 'or orlist))))
14531 ;; Return the string and function of the matcher. If no
14532 ;; tags-specific or todo-specific matcher exists, match
14533 ;; everything.
14534 (let ((matcher (if (and tagsmatcher todomatcher)
14535 `(and ,tagsmatcher ,todomatcher)
14536 (or tagsmatcher todomatcher t))))
14537 (when org--matcher-tags-todo-only
14538 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14539 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14541 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14542 "Expand group tags in MATCH.
14544 This replaces every group tag in MATCH with a regexp tag search.
14545 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14546 will be replaced like this:
14548 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14549 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14550 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14552 Replacing by a regexp preserves the structure of the match.
14553 E.g., this expansion
14555 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14557 will match anything tagged with \"Lab\" and \"Home\", or tagged
14558 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14560 A group tag in MATCH can contain regular expressions of its own.
14561 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14562 will be replaced like this:
14564 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14566 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14567 assumed to be a single group tag, and the function will return
14568 the list of tags in this group.
14570 When DOWNCASE is non-nil, expand downcased TAGS."
14571 (if org-group-tags
14572 (let* ((case-fold-search t)
14573 (stable org-mode-syntax-table)
14574 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14575 (taggroups (if downcased
14576 (mapcar (lambda (tg) (mapcar #'downcase tg))
14577 taggroups)
14578 taggroups))
14579 (taggroups-keys (mapcar #'car taggroups))
14580 (return-match (if downcased (downcase match) match))
14581 (count 0)
14582 (work-already-expanded tags-already-expanded)
14583 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14584 ;; @ and _ are allowed as word-components in tags.
14585 (modify-syntax-entry ?@ "w" stable)
14586 (modify-syntax-entry ?_ "w" stable)
14587 ;; Temporarily replace regexp-expressions in the match-expression.
14588 (while (string-match "{.+?}" return-match)
14589 (cl-incf count)
14590 (push (match-string 0 return-match) regexps-in-match)
14591 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14592 (while (and taggroups-keys
14593 (with-syntax-table stable
14594 (string-match
14595 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14596 (regexp-opt taggroups-keys) "\\>\\)")
14597 return-match)))
14598 (let* ((dir (match-string 1 return-match))
14599 (tag (match-string 2 return-match))
14600 (tag (if downcased (downcase tag) tag)))
14601 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14602 (member tag work-already-expanded))
14603 (setq tags-in-group (assoc tag taggroups))
14604 (push tag work-already-expanded)
14605 ;; Recursively expand each tag in the group, if the tag hasn't
14606 ;; already been expanded. Restore the match-data after all recursive calls.
14607 (save-match-data
14608 (let (tags-expanded)
14609 (dolist (x (cdr tags-in-group))
14610 (if (and (member x taggroups-keys)
14611 (not (member x work-already-expanded)))
14612 (setq tags-expanded
14613 (delete-dups
14614 (append
14615 (org-tags-expand x t downcased
14616 work-already-expanded)
14617 tags-expanded)))
14618 (setq tags-expanded
14619 (append (list x) tags-expanded)))
14620 (setq work-already-expanded
14621 (delete-dups
14622 (append tags-expanded
14623 work-already-expanded))))
14624 (setq tags-in-group
14625 (delete-dups (cons (car tags-in-group)
14626 tags-expanded)))))
14627 ;; Filter tag-regexps from tags.
14628 (setq regexp-in-group-escaped
14629 (delq nil (mapcar (lambda (x)
14630 (if (stringp x)
14631 (and (equal "{" (substring x 0 1))
14632 (equal "}" (substring x -1))
14635 tags-in-group))
14636 regexp-in-group
14637 (mapcar (lambda (x)
14638 (substring x 1 -1))
14639 regexp-in-group-escaped)
14640 tags-in-group
14641 (delq nil (mapcar (lambda (x)
14642 (if (stringp x)
14643 (and (not (equal "{" (substring x 0 1)))
14644 (not (equal "}" (substring x -1)))
14647 tags-in-group)))
14648 ;; If single-as-list, do no more in the while-loop.
14649 (if (not single-as-list)
14650 (progn
14651 (when regexp-in-group
14652 (setq regexp-in-group
14653 (concat "\\|"
14654 (mapconcat 'identity regexp-in-group
14655 "\\|"))))
14656 (setq tags-in-group
14657 (concat dir
14658 "{\\<"
14659 (regexp-opt tags-in-group)
14660 "\\>"
14661 regexp-in-group
14662 "}"))
14663 (when (stringp tags-in-group)
14664 (org-add-props tags-in-group '(grouptag t)))
14665 (setq return-match
14666 (replace-match tags-in-group t t return-match)))
14667 (setq tags-in-group
14668 (append regexp-in-group-escaped tags-in-group))))
14669 (setq taggroups-keys (delete tag taggroups-keys))))
14670 ;; Add the regular expressions back into the match-expression again.
14671 (while regexps-in-match
14672 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14673 (pop regexps-in-match)
14674 return-match t t))
14675 (cl-decf count))
14676 (if single-as-list
14677 (if tags-in-group tags-in-group (list return-match))
14678 return-match))
14679 (if single-as-list
14680 (list (if downcased (downcase match) match))
14681 match)))
14683 (defun org-op-to-function (op &optional stringp)
14684 "Turn an operator into the appropriate function."
14685 (setq op
14686 (cond
14687 ((equal op "<" ) '(< string< org-time<))
14688 ((equal op ">" ) '(> org-string> org-time>))
14689 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14690 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14691 ((member op '("=" "==")) '(= string= org-time=))
14692 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14693 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14695 (defun org<> (a b) (not (= a b)))
14696 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14697 (defun org-string>= (a b) (not (string< a b)))
14698 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14699 (defun org-string<> (a b) (not (string= a b)))
14700 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14701 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14702 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14703 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14704 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14705 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14706 (defun org-2ft (s)
14707 "Convert S to a floating point time.
14708 If S is already a number, just return it. If it is a string, parse
14709 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14710 (cond
14711 ((numberp s) s)
14712 ((stringp s)
14713 (condition-case nil
14714 (float-time (apply 'encode-time (org-parse-time-string s)))
14715 (error 0.)))
14716 (t 0.)))
14718 (defun org-time-today ()
14719 "Time in seconds today at 0:00.
14720 Returns the float number of seconds since the beginning of the
14721 epoch to the beginning of today (00:00)."
14722 (float-time (apply 'encode-time
14723 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14725 (defun org-matcher-time (s)
14726 "Interpret a time comparison value."
14727 (save-match-data
14728 (cond
14729 ((string= s "<now>") (float-time))
14730 ((string= s "<today>") (org-time-today))
14731 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14732 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14733 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14734 (+ (org-time-today)
14735 (* (string-to-number (match-string 1 s))
14736 (cdr (assoc (match-string 2 s)
14737 '(("d" . 86400.0) ("w" . 604800.0)
14738 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14739 (t (org-2ft s)))))
14741 (defun org-match-any-p (re list)
14742 "Does re match any element of list?"
14743 (setq list (mapcar (lambda (x) (string-match re x)) list))
14744 (delq nil list))
14746 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14747 (defvar org-tags-overlay (make-overlay 1 1))
14748 (delete-overlay org-tags-overlay)
14750 (defun org-get-local-tags-at (&optional pos)
14751 "Get a list of tags defined in the current headline."
14752 (org-get-tags-at pos 'local))
14754 (defun org-get-local-tags ()
14755 "Get a list of tags defined in the current headline."
14756 (org-get-tags-at nil 'local))
14758 (defun org-get-tags-at (&optional pos local)
14759 "Get a list of all headline tags applicable at POS.
14760 POS defaults to point. If tags are inherited, the list contains
14761 the targets in the same sequence as the headlines appear, i.e.
14762 the tags of the current headline come last.
14763 When LOCAL is non-nil, only return tags from the current headline,
14764 ignore inherited ones."
14765 (interactive)
14766 (if (and org-trust-scanner-tags
14767 (or (not pos) (equal pos (point)))
14768 (not local))
14769 org-scanner-tags
14770 (let (tags ltags lastpos parent)
14771 (save-excursion
14772 (save-restriction
14773 (widen)
14774 (goto-char (or pos (point)))
14775 (save-match-data
14776 (catch 'done
14777 (condition-case nil
14778 (progn
14779 (org-back-to-heading t)
14780 (while (not (equal lastpos (point)))
14781 (setq lastpos (point))
14782 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14783 (setq ltags (org-split-string
14784 (match-string-no-properties 1) ":"))
14785 (when parent
14786 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14787 (setq tags (append
14788 (if parent
14789 (org-remove-uninherited-tags ltags)
14790 ltags)
14791 tags)))
14792 (or org-use-tag-inheritance (throw 'done t))
14793 (when local (throw 'done t))
14794 (or (org-up-heading-safe) (error nil))
14795 (setq parent t)))
14796 (error nil)))))
14797 (if local
14798 tags
14799 (reverse (delete-dups
14800 (reverse (append
14801 (org-remove-uninherited-tags
14802 org-file-tags)
14803 tags)))))))))
14805 (defun org-add-prop-inherited (s)
14806 (add-text-properties 0 (length s) '(inherited t) s)
14809 (defun org-toggle-tag (tag &optional onoff)
14810 "Toggle the tag TAG for the current line.
14811 If ONOFF is `on' or `off', don't toggle but set to this state."
14812 (let (res current)
14813 (save-excursion
14814 (org-back-to-heading t)
14815 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14816 (point-at-eol) t)
14817 (progn
14818 (setq current (match-string 1))
14819 (replace-match ""))
14820 (setq current ""))
14821 (setq current (nreverse (org-split-string current ":")))
14822 (cond
14823 ((eq onoff 'on)
14824 (setq res t)
14825 (or (member tag current) (push tag current)))
14826 ((eq onoff 'off)
14827 (or (not (member tag current)) (setq current (delete tag current))))
14828 (t (if (member tag current)
14829 (setq current (delete tag current))
14830 (setq res t)
14831 (push tag current))))
14832 (end-of-line 1)
14833 (if current
14834 (progn
14835 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14836 (org-set-tags nil t))
14837 (delete-horizontal-space))
14838 (run-hooks 'org-after-tags-change-hook))
14839 res))
14841 (defun org--align-tags-here (to-col)
14842 "Align tags on the current headline to TO-COL.
14843 Assume point is on a headline."
14844 (let ((pos (point)))
14845 (beginning-of-line)
14846 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14847 (>= pos (match-beginning 2)))
14848 ;; No tags or point within tags: do not align.
14849 (goto-char pos)
14850 (goto-char (match-beginning 1))
14851 (let ((shift (max (- (if (>= to-col 0) to-col
14852 (- (abs to-col) (string-width (match-string 2))))
14853 (current-column))
14854 1)))
14855 (replace-match (make-string shift ?\s) nil nil nil 1)
14856 ;; Preserve initial position, if possible. In any case, stop
14857 ;; before tags.
14858 (when (< pos (point)) (goto-char pos))))))
14860 (defun org-set-tags-command (&optional arg just-align)
14861 "Call the set-tags command for the current entry."
14862 (interactive "P")
14863 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14864 (org-set-tags arg just-align)
14865 (save-excursion
14866 (unless (and (org-region-active-p)
14867 org-loop-over-headlines-in-active-region)
14868 (org-back-to-heading t))
14869 (org-set-tags arg just-align))))
14871 (defun org-set-tags-to (data)
14872 "Set the tags of the current entry to DATA, replacing the current tags.
14873 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14874 If DATA is nil or the empty string, any tags will be removed."
14875 (interactive "sTags: ")
14876 (setq data
14877 (cond
14878 ((eq data nil) "")
14879 ((equal data "") "")
14880 ((stringp data)
14881 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14882 ":"))
14883 ((listp data)
14884 (concat ":" (mapconcat 'identity data ":") ":"))))
14885 (when data
14886 (save-excursion
14887 (org-back-to-heading t)
14888 (when (let ((case-fold-search nil))
14889 (looking-at org-complex-heading-regexp))
14890 (if (match-end 5)
14891 (progn
14892 (goto-char (match-beginning 5))
14893 (insert data)
14894 (delete-region (point) (point-at-eol))
14895 (org-set-tags nil 'align))
14896 (goto-char (point-at-eol))
14897 (insert " " data)
14898 (org-set-tags nil 'align)))
14899 (beginning-of-line 1)
14900 (when (looking-at ".*?\\([ \t]+\\)$")
14901 (delete-region (match-beginning 1) (match-end 1))))))
14903 (defun org-align-all-tags ()
14904 "Align the tags in all headings."
14905 (interactive)
14906 (save-excursion
14907 (or (ignore-errors (org-back-to-heading t))
14908 (outline-next-heading))
14909 (if (org-at-heading-p)
14910 (org-set-tags t)
14911 (message "No headings"))))
14913 (defvar org-indent-indentation-per-level)
14914 (defun org-set-tags (&optional arg just-align)
14915 "Set the tags for the current headline.
14916 With prefix ARG, realign all tags in headings in the current buffer.
14917 When JUST-ALIGN is non-nil, only align tags."
14918 (interactive "P")
14919 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14920 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14921 'region-start-level
14922 'region))
14923 org-loop-over-headlines-in-active-region)
14924 (org-map-entries
14925 ;; We don't use ARG and JUST-ALIGN here because these args
14926 ;; are not useful when looping over headlines.
14927 #'org-set-tags
14928 org-loop-over-headlines-in-active-region
14930 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14931 (let ((org-setting-tags t))
14932 (if arg
14933 (save-excursion
14934 (goto-char (point-min))
14935 (while (re-search-forward org-outline-regexp-bol nil t)
14936 (org-set-tags nil t)
14937 (end-of-line))
14938 (message "All tags realigned to column %d" org-tags-column))
14939 (let* ((current (org-get-tags-string))
14940 (tags
14941 (if just-align current
14942 ;; Get a new set of tags from the user.
14943 (save-excursion
14944 (let* ((seen)
14945 (table
14946 (setq
14947 org-last-tags-completion-table
14948 ;; Uniquify tags in alists, yet preserve
14949 ;; structure (i.e., keywords).
14950 (delq nil
14951 (mapcar
14952 (lambda (pair)
14953 (let ((head (car pair)))
14954 (cond ((symbolp head) pair)
14955 ((member head seen) nil)
14956 (t (push head seen)
14957 pair))))
14958 (append
14959 (or org-current-tag-alist
14960 (org-get-buffer-tags))
14961 (and
14962 org-complete-tags-always-offer-all-agenda-tags
14963 (org-global-tags-completion-table
14964 (org-agenda-files))))))))
14965 (current-tags (org-split-string current ":"))
14966 (inherited-tags
14967 (nreverse (nthcdr (length current-tags)
14968 (nreverse (org-get-tags-at))))))
14969 (replace-regexp-in-string
14970 "\\([-+&]+\\|,\\)"
14972 (if (or (eq t org-use-fast-tag-selection)
14973 (and org-use-fast-tag-selection
14974 (delq nil (mapcar #'cdr table))))
14975 (org-fast-tag-selection
14976 current-tags inherited-tags table
14977 (and org-fast-tag-selection-include-todo
14978 org-todo-key-alist))
14979 (let ((org-add-colon-after-tag-completion
14980 (< 1 (length table))))
14981 (org-trim
14982 (completing-read
14983 "Tags: "
14984 #'org-tags-completion-function
14985 nil nil current 'org-tags-history))))))))))
14987 (when org-tags-sort-function
14988 (setq tags
14989 (mapconcat
14990 #'identity
14991 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14992 org-tags-sort-function)
14993 ":")))
14995 (if (or (string= ":" tags)
14996 (string= "::" tags))
14997 (setq tags ""))
14998 (if (not (org-string-nw-p tags)) (setq tags "")
14999 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15000 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15002 ;; Insert new tags at the correct column.
15003 (unless (equal current tags)
15004 (save-excursion
15005 (beginning-of-line)
15006 (let ((case-fold-search nil))
15007 (looking-at org-complex-heading-regexp))
15008 ;; Remove current tags, if any.
15009 (when (match-end 5) (replace-match "" nil nil nil 5))
15010 ;; Insert new tags, if any. Otherwise, remove trailing
15011 ;; white spaces.
15012 (end-of-line)
15013 (if (not (equal tags ""))
15014 ;; When text is being inserted on an invisible
15015 ;; region boundary, it can be inadvertently sucked
15016 ;; into invisibility.
15017 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
15018 (skip-chars-backward " \t")
15019 (delete-region (point) (line-end-position)))))
15020 ;; Align tags, if any. Fix tags column if `org-indent-mode'
15021 ;; is on.
15022 (unless (equal tags "")
15023 (let* ((level (save-excursion
15024 (beginning-of-line)
15025 (skip-chars-forward "\\*")))
15026 (offset (if (bound-and-true-p org-indent-mode)
15027 (* (1- org-indent-indentation-per-level)
15028 (1- level))
15030 (tags-column
15031 (+ org-tags-column
15032 (if (> org-tags-column 0) (- offset) offset))))
15033 (org--align-tags-here tags-column))))
15034 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15036 (defun org-change-tag-in-region (beg end tag off)
15037 "Add or remove TAG for each entry in the region.
15038 This works in the agenda, and also in an Org buffer."
15039 (interactive
15040 (list (region-beginning) (region-end)
15041 (let ((org-last-tags-completion-table
15042 (if (derived-mode-p 'org-mode)
15043 (org-uniquify
15044 (delq nil (append (org-get-buffer-tags)
15045 (org-global-tags-completion-table))))
15046 (org-global-tags-completion-table))))
15047 (completing-read
15048 "Tag: " 'org-tags-completion-function nil nil nil
15049 'org-tags-history))
15050 (progn
15051 (message "[s]et or [r]emove? ")
15052 (equal (read-char-exclusive) ?r))))
15053 (when (fboundp 'deactivate-mark) (deactivate-mark))
15054 (let ((agendap (equal major-mode 'org-agenda-mode))
15055 l1 l2 m buf pos newhead (cnt 0))
15056 (goto-char end)
15057 (setq l2 (1- (org-current-line)))
15058 (goto-char beg)
15059 (setq l1 (org-current-line))
15060 (cl-loop for l from l1 to l2 do
15061 (org-goto-line l)
15062 (setq m (get-text-property (point) 'org-hd-marker))
15063 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15064 (and agendap m))
15065 (setq buf (if agendap (marker-buffer m) (current-buffer))
15066 pos (if agendap m (point)))
15067 (with-current-buffer buf
15068 (save-excursion
15069 (save-restriction
15070 (goto-char pos)
15071 (setq cnt (1+ cnt))
15072 (org-toggle-tag tag (if off 'off 'on))
15073 (setq newhead (org-get-heading)))))
15074 (and agendap (org-agenda-change-all-lines newhead m))))
15075 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15077 (defun org-tags-completion-function (string _predicate &optional flag)
15078 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15079 (confirm (lambda (x) (stringp (car x)))))
15080 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15081 (setq s1 (match-string 1 string)
15082 s2 (match-string 2 string))
15083 (setq s1 "" s2 string))
15084 (cond
15085 ((eq flag nil)
15086 ;; try completion
15087 (setq rtn (try-completion s2 ctable confirm))
15088 (when (stringp rtn)
15089 (setq rtn
15090 (concat s1 s2 (substring rtn (length s2))
15091 (if (and org-add-colon-after-tag-completion
15092 (assoc rtn ctable))
15093 ":" ""))))
15094 rtn)
15095 ((eq flag t)
15096 ;; all-completions
15097 (all-completions s2 ctable confirm))
15098 ((eq flag 'lambda)
15099 ;; exact match?
15100 (assoc s2 ctable)))))
15102 (defun org-fast-tag-insert (kwd tags face &optional end)
15103 "Insert KDW, and the TAGS, the latter with face FACE.
15104 Also insert END."
15105 (insert (format "%-12s" (concat kwd ":"))
15106 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15107 (or end "")))
15109 (defun org-fast-tag-show-exit (flag)
15110 (save-excursion
15111 (org-goto-line 3)
15112 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15113 (replace-match ""))
15114 (when flag
15115 (end-of-line 1)
15116 (org-move-to-column (- (window-width) 19) t)
15117 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15119 (defun org-set-current-tags-overlay (current prefix)
15120 "Add an overlay to CURRENT tag with PREFIX."
15121 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15122 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15123 (org-overlay-display org-tags-overlay (concat prefix s))))
15125 (defvar org-last-tag-selection-key nil)
15126 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15127 "Fast tag selection with single keys.
15128 CURRENT is the current list of tags in the headline, INHERITED is the
15129 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15130 possibly with grouping information. TODO-TABLE is a similar table with
15131 TODO keywords, should these have keys assigned to them.
15132 If the keys are nil, a-z are automatically assigned.
15133 Returns the new tags string, or nil to not change the current settings."
15134 (let* ((fulltable (append table todo-table))
15135 (maxlen (apply 'max (mapcar
15136 (lambda (x)
15137 (if (stringp (car x)) (string-width (car x)) 0))
15138 fulltable)))
15139 (buf (current-buffer))
15140 (expert (eq org-fast-tag-selection-single-key 'expert))
15141 (buffer-tags nil)
15142 (fwidth (+ maxlen 3 1 3))
15143 (ncol (/ (- (window-width) 4) fwidth))
15144 (i-face 'org-done)
15145 (c-face 'org-todo)
15146 tg cnt e c char c1 c2 ntable tbl rtn
15147 ov-start ov-end ov-prefix
15148 (exit-after-next org-fast-tag-selection-single-key)
15149 (done-keywords org-done-keywords)
15150 groups ingroup intaggroup)
15151 (save-excursion
15152 (beginning-of-line 1)
15153 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15154 (setq ov-start (match-beginning 1)
15155 ov-end (match-end 1)
15156 ov-prefix "")
15157 (setq ov-start (1- (point-at-eol))
15158 ov-end (1+ ov-start))
15159 (skip-chars-forward "^\n\r")
15160 (setq ov-prefix
15161 (concat
15162 (buffer-substring (1- (point)) (point))
15163 (if (> (current-column) org-tags-column)
15165 (make-string (- org-tags-column (current-column)) ?\ ))))))
15166 (move-overlay org-tags-overlay ov-start ov-end)
15167 (save-window-excursion
15168 (if expert
15169 (set-buffer (get-buffer-create " *Org tags*"))
15170 (delete-other-windows)
15171 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15172 (org-switch-to-buffer-other-window " *Org tags*"))
15173 (erase-buffer)
15174 (setq-local org-done-keywords done-keywords)
15175 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15176 (org-fast-tag-insert "Current" current c-face "\n\n")
15177 (org-fast-tag-show-exit exit-after-next)
15178 (org-set-current-tags-overlay current ov-prefix)
15179 (setq tbl fulltable char ?a cnt 0)
15180 (while (setq e (pop tbl))
15181 (cond
15182 ((eq (car e) :startgroup)
15183 (push '() groups) (setq ingroup t)
15184 (unless (zerop cnt)
15185 (setq cnt 0)
15186 (insert "\n"))
15187 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15188 ((eq (car e) :endgroup)
15189 (setq ingroup nil cnt 0)
15190 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15191 ((eq (car e) :startgrouptag)
15192 (setq intaggroup t)
15193 (unless (zerop cnt)
15194 (setq cnt 0)
15195 (insert "\n"))
15196 (insert "[ "))
15197 ((eq (car e) :endgrouptag)
15198 (setq intaggroup nil cnt 0)
15199 (insert "]\n"))
15200 ((equal e '(:newline))
15201 (unless (zerop cnt)
15202 (setq cnt 0)
15203 (insert "\n")
15204 (setq e (car tbl))
15205 (while (equal (car tbl) '(:newline))
15206 (insert "\n")
15207 (setq tbl (cdr tbl)))))
15208 ((equal e '(:grouptags)) (insert " : "))
15210 (setq tg (copy-sequence (car e)) c2 nil)
15211 (if (cdr e)
15212 (setq c (cdr e))
15213 ;; automatically assign a character.
15214 (setq c1 (string-to-char
15215 (downcase (substring
15216 tg (if (= (string-to-char tg) ?@) 1 0)))))
15217 (if (or (rassoc c1 ntable) (rassoc c1 table))
15218 (while (or (rassoc char ntable) (rassoc char table))
15219 (setq char (1+ char)))
15220 (setq c2 c1))
15221 (setq c (or c2 char)))
15222 (when ingroup (push tg (car groups)))
15223 (setq tg (org-add-props tg nil 'face
15224 (cond
15225 ((not (assoc tg table))
15226 (org-get-todo-face tg))
15227 ((member tg current) c-face)
15228 ((member tg inherited) i-face))))
15229 (when (equal (caar tbl) :grouptags)
15230 (org-add-props tg nil 'face 'org-tag-group))
15231 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15232 (insert "[" c "] " tg (make-string
15233 (- fwidth 4 (length tg)) ?\ ))
15234 (push (cons tg c) ntable)
15235 (when (= (cl-incf cnt) ncol)
15236 (insert "\n")
15237 (when (or ingroup intaggroup) (insert " "))
15238 (setq cnt 0)))))
15239 (setq ntable (nreverse ntable))
15240 (insert "\n")
15241 (goto-char (point-min))
15242 (unless expert (org-fit-window-to-buffer))
15243 (setq rtn
15244 (catch 'exit
15245 (while t
15246 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15247 (if (not groups) "no " "")
15248 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15249 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15250 (setq org-last-tag-selection-key c)
15251 (cond
15252 ((= c ?\r) (throw 'exit t))
15253 ((= c ?!)
15254 (setq groups (not groups))
15255 (goto-char (point-min))
15256 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15257 ((= c ?\C-c)
15258 (if (not expert)
15259 (org-fast-tag-show-exit
15260 (setq exit-after-next (not exit-after-next)))
15261 (setq expert nil)
15262 (delete-other-windows)
15263 (set-window-buffer (split-window-vertically) " *Org tags*")
15264 (org-switch-to-buffer-other-window " *Org tags*")
15265 (org-fit-window-to-buffer)))
15266 ((or (= c ?\C-g)
15267 (and (= c ?q) (not (rassoc c ntable))))
15268 (delete-overlay org-tags-overlay)
15269 (setq quit-flag t))
15270 ((= c ?\ )
15271 (setq current nil)
15272 (when exit-after-next (setq exit-after-next 'now)))
15273 ((= c ?\t)
15274 (condition-case nil
15275 (setq tg (completing-read
15276 "Tag: "
15277 (or buffer-tags
15278 (with-current-buffer buf
15279 (setq buffer-tags
15280 (org-get-buffer-tags))))))
15281 (quit (setq tg "")))
15282 (when (string-match "\\S-" tg)
15283 (cl-pushnew (list tg) buffer-tags :test #'equal)
15284 (if (member tg current)
15285 (setq current (delete tg current))
15286 (push tg current)))
15287 (when exit-after-next (setq exit-after-next 'now)))
15288 ((setq e (rassoc c todo-table) tg (car e))
15289 (with-current-buffer buf
15290 (save-excursion (org-todo tg)))
15291 (when exit-after-next (setq exit-after-next 'now)))
15292 ((setq e (rassoc c ntable) tg (car e))
15293 (if (member tg current)
15294 (setq current (delete tg current))
15295 (cl-loop for g in groups do
15296 (when (member tg g)
15297 (dolist (x g) (setq current (delete x current)))))
15298 (push tg current))
15299 (when exit-after-next (setq exit-after-next 'now))))
15301 ;; Create a sorted list
15302 (setq current
15303 (sort current
15304 (lambda (a b)
15305 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15306 (when (eq exit-after-next 'now) (throw 'exit t))
15307 (goto-char (point-min))
15308 (beginning-of-line 2)
15309 (delete-region (point) (point-at-eol))
15310 (org-fast-tag-insert "Current" current c-face)
15311 (org-set-current-tags-overlay current ov-prefix)
15312 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15313 (setq tg (match-string 1))
15314 (add-text-properties
15315 (match-beginning 1) (match-end 1)
15316 (list 'face
15317 (cond
15318 ((member tg current) c-face)
15319 ((member tg inherited) i-face)
15320 (t (get-text-property (match-beginning 1) 'face))))))
15321 (goto-char (point-min)))))
15322 (delete-overlay org-tags-overlay)
15323 (if rtn
15324 (mapconcat 'identity current ":")
15325 nil))))
15327 (defun org-get-tags-string ()
15328 "Get the TAGS string in the current headline."
15329 (unless (org-at-heading-p t)
15330 (user-error "Not on a heading"))
15331 (save-excursion
15332 (beginning-of-line 1)
15333 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15334 (match-string-no-properties 1)
15335 "")))
15337 (defun org-get-tags ()
15338 "Get the list of tags specified in the current headline."
15339 (org-split-string (org-get-tags-string) ":"))
15341 (defun org-get-buffer-tags ()
15342 "Get a table of all tags used in the buffer, for completion."
15343 (org-with-wide-buffer
15344 (goto-char (point-min))
15345 (let ((tag-re (concat org-outline-regexp-bol
15346 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15347 tags)
15348 (while (re-search-forward tag-re nil t)
15349 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15350 (push tag tags)))
15351 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15353 ;;;; The mapping API
15355 (defvar org-agenda-skip-comment-trees)
15356 (defvar org-agenda-skip-function)
15357 (defun org-map-entries (func &optional match scope &rest skip)
15358 "Call FUNC at each headline selected by MATCH in SCOPE.
15360 FUNC is a function or a lisp form. The function will be called without
15361 arguments, with the cursor positioned at the beginning of the headline.
15362 The return values of all calls to the function will be collected and
15363 returned as a list.
15365 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15366 does not need to preserve point. After evaluation, the cursor will be
15367 moved to the end of the line (presumably of the headline of the
15368 processed entry) and search continues from there. Under some
15369 circumstances, this may not produce the wanted results. For example,
15370 if you have removed (e.g. archived) the current (sub)tree it could
15371 mean that the next entry will be skipped entirely. In such cases, you
15372 can specify the position from where search should continue by making
15373 FUNC set the variable `org-map-continue-from' to the desired buffer
15374 position.
15376 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15377 Only headlines that are matched by this query will be considered during
15378 the iteration. When MATCH is nil or t, all headlines will be
15379 visited by the iteration.
15381 SCOPE determines the scope of this command. It can be any of:
15383 nil The current buffer, respecting the restriction if any
15384 tree The subtree started with the entry at point
15385 region The entries within the active region, if any
15386 region-start-level
15387 The entries within the active region, but only those at
15388 the same level than the first one.
15389 file The current buffer, without restriction
15390 file-with-archives
15391 The current buffer, and any archives associated with it
15392 agenda All agenda files
15393 agenda-with-archives
15394 All agenda files with any archive files associated with them
15395 \(file1 file2 ...)
15396 If this is a list, all files in the list will be scanned
15398 The remaining args are treated as settings for the skipping facilities of
15399 the scanner. The following items can be given here:
15401 archive skip trees with the archive tag
15402 comment skip trees with the COMMENT keyword
15403 function or Emacs Lisp form:
15404 will be used as value for `org-agenda-skip-function', so
15405 whenever the function returns a position, FUNC will not be
15406 called for that entry and search will continue from the
15407 position returned
15409 If your function needs to retrieve the tags including inherited tags
15410 at the *current* entry, you can use the value of the variable
15411 `org-scanner-tags' which will be much faster than getting the value
15412 with `org-get-tags-at'. If your function gets properties with
15413 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15414 to t around the call to `org-entry-properties' to get the same speedup.
15415 Note that if your function moves around to retrieve tags and properties at
15416 a *different* entry, you cannot use these techniques."
15417 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15418 (not (org-region-active-p)))
15419 (let* ((org-agenda-archives-mode nil) ; just to make sure
15420 (org-agenda-skip-archived-trees (memq 'archive skip))
15421 (org-agenda-skip-comment-trees (memq 'comment skip))
15422 (org-agenda-skip-function
15423 (car (org-delete-all '(comment archive) skip)))
15424 (org-tags-match-list-sublevels t)
15425 (start-level (eq scope 'region-start-level))
15426 matcher res
15427 org-todo-keywords-for-agenda
15428 org-done-keywords-for-agenda
15429 org-todo-keyword-alist-for-agenda
15430 org-tag-alist-for-agenda
15431 org--matcher-tags-todo-only)
15433 (cond
15434 ((eq match t) (setq matcher t))
15435 ((eq match nil) (setq matcher t))
15436 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15438 (save-excursion
15439 (save-restriction
15440 (cond ((eq scope 'tree)
15441 (org-back-to-heading t)
15442 (org-narrow-to-subtree)
15443 (setq scope nil))
15444 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15445 (org-region-active-p))
15446 ;; If needed, set start-level to a string like "2"
15447 (when start-level
15448 (save-excursion
15449 (goto-char (region-beginning))
15450 (unless (org-at-heading-p) (outline-next-heading))
15451 (setq start-level (org-current-level))))
15452 (narrow-to-region (region-beginning)
15453 (save-excursion
15454 (goto-char (region-end))
15455 (unless (and (bolp) (org-at-heading-p))
15456 (outline-next-heading))
15457 (point)))
15458 (setq scope nil)))
15460 (if (not scope)
15461 (progn
15462 (org-agenda-prepare-buffers
15463 (and buffer-file-name (list buffer-file-name)))
15464 (setq res
15465 (org-scan-tags
15466 func matcher org--matcher-tags-todo-only start-level)))
15467 ;; Get the right scope
15468 (cond
15469 ((and scope (listp scope) (symbolp (car scope)))
15470 (setq scope (eval scope)))
15471 ((eq scope 'agenda)
15472 (setq scope (org-agenda-files t)))
15473 ((eq scope 'agenda-with-archives)
15474 (setq scope (org-agenda-files t))
15475 (setq scope (org-add-archive-files scope)))
15476 ((eq scope 'file)
15477 (setq scope (and buffer-file-name (list buffer-file-name))))
15478 ((eq scope 'file-with-archives)
15479 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15480 (org-agenda-prepare-buffers scope)
15481 (dolist (file scope)
15482 (with-current-buffer (org-find-base-buffer-visiting file)
15483 (org-with-wide-buffer
15484 (goto-char (point-min))
15485 (setq res
15486 (append
15488 (org-scan-tags
15489 func matcher org--matcher-tags-todo-only)))))))))
15490 res)))
15492 ;;; Properties API
15494 (defconst org-special-properties
15495 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15496 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15497 "The special properties valid in Org mode.
15498 These are properties that are not defined in the property drawer,
15499 but in some other way.")
15501 (defconst org-default-properties
15502 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15503 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15504 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15505 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15506 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15507 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15508 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15509 "Some properties that are used by Org mode for various purposes.
15510 Being in this list makes sure that they are offered for completion.")
15512 (defun org--valid-property-p (property)
15513 "Non nil when string PROPERTY is a valid property name."
15514 (not
15515 (or (equal property "")
15516 (string-match-p "\\s-" property))))
15518 (defun org--update-property-plist (key val props)
15519 "Associate KEY to VAL in alist PROPS.
15520 Modifications are made by side-effect. Return new alist."
15521 (let* ((appending (string= (substring key -1) "+"))
15522 (key (if appending (substring key 0 -1) key))
15523 (old (assoc-string key props t)))
15524 (if (not old) (cons (cons key val) props)
15525 (setcdr old (if appending (concat (cdr old) " " val) val))
15526 props)))
15528 (defun org-get-property-block (&optional beg force)
15529 "Return the (beg . end) range of the body of the property drawer.
15530 BEG is the beginning of the current subtree, or of the part
15531 before the first headline. If it is not given, it will be found.
15532 If the drawer does not exist, create it if FORCE is non-nil, or
15533 return nil."
15534 (org-with-wide-buffer
15535 (when beg (goto-char beg))
15536 (unless (org-before-first-heading-p)
15537 (let ((beg (cond (beg)
15538 ((or (not (featurep 'org-inlinetask))
15539 (org-inlinetask-in-task-p))
15540 (org-back-to-heading t))
15541 (t (org-with-limited-levels (org-back-to-heading t))))))
15542 (forward-line)
15543 (when (looking-at-p org-planning-line-re) (forward-line))
15544 (cond ((looking-at org-property-drawer-re)
15545 (forward-line)
15546 (cons (point) (progn (goto-char (match-end 0))
15547 (line-beginning-position))))
15548 (force
15549 (goto-char beg)
15550 (org-insert-property-drawer)
15551 (let ((pos (save-excursion (search-forward ":END:")
15552 (line-beginning-position))))
15553 (cons pos pos))))))))
15555 (defun org-at-property-p ()
15556 "Non-nil when point is inside a property drawer.
15557 See `org-property-re' for match data, if applicable."
15558 (save-excursion
15559 (beginning-of-line)
15560 (and (looking-at org-property-re)
15561 (let ((property-drawer (save-match-data (org-get-property-block))))
15562 (and property-drawer
15563 (>= (point) (car property-drawer))
15564 (< (point) (cdr property-drawer)))))))
15566 (defun org-property-action ()
15567 "Do an action on properties."
15568 (interactive)
15569 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15570 (let ((c (read-char-exclusive)))
15571 (cl-case c
15572 (?s (call-interactively #'org-set-property))
15573 (?d (call-interactively #'org-delete-property))
15574 (?D (call-interactively #'org-delete-property-globally))
15575 (?c (call-interactively #'org-compute-property-at-point))
15576 (otherwise (user-error "No such property action %c" c)))))
15578 (defun org-inc-effort ()
15579 "Increment the value of the effort property in the current entry."
15580 (interactive)
15581 (org-set-effort nil t))
15583 (defvar org-clock-effort) ; Defined in org-clock.el.
15584 (defvar org-clock-current-task) ; Defined in org-clock.el.
15585 (defun org-set-effort (&optional value increment)
15586 "Set the effort property of the current entry.
15587 With numerical prefix arg, use the nth allowed value, 0 stands for the
15588 10th allowed value.
15590 When INCREMENT is non-nil, set the property to the next allowed value."
15591 (interactive "P")
15592 (when (equal value 0) (setq value 10))
15593 (let* ((completion-ignore-case t)
15594 (prop org-effort-property)
15595 (cur (org-entry-get nil prop))
15596 (allowed (org-property-get-allowed-values nil prop 'table))
15597 (existing (mapcar 'list (org-property-values prop)))
15598 (heading (nth 4 (org-heading-components)))
15600 (val (cond
15601 ((stringp value) value)
15602 ((and allowed (integerp value))
15603 (or (car (nth (1- value) allowed))
15604 (car (org-last allowed))))
15605 ((and allowed increment)
15606 (or (cl-caadr (member (list cur) allowed))
15607 (user-error "Allowed effort values are not set")))
15608 (allowed
15609 (message "Select 1-9,0, [RET%s]: %s"
15610 (if cur (concat "=" cur) "")
15611 (mapconcat 'car allowed " "))
15612 (setq rpl (read-char-exclusive))
15613 (if (equal rpl ?\r)
15615 (setq rpl (- rpl ?0))
15616 (when (equal rpl 0) (setq rpl 10))
15617 (if (and (> rpl 0) (<= rpl (length allowed)))
15618 (car (nth (1- rpl) allowed))
15619 (org-completing-read "Effort: " allowed nil))))
15621 (org-completing-read
15622 (concat "Effort" (and cur (string-match "\\S-" cur)
15623 (concat " [" cur "]"))
15624 ": ")
15625 existing nil nil "" nil cur)))))
15626 (unless (equal (org-entry-get nil prop) val)
15627 (org-entry-put nil prop val))
15628 (org-refresh-property
15629 '((effort . identity)
15630 (effort-minutes . org-duration-to-minutes))
15631 val)
15632 (when (equal heading (bound-and-true-p org-clock-current-task))
15633 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15634 (org-clock-update-mode-line))
15635 (message "%s is now %s" prop val)))
15637 (defun org-entry-properties (&optional pom which)
15638 "Get all properties of the current entry.
15640 When POM is a buffer position, get all properties from the entry
15641 there instead.
15643 This includes the TODO keyword, the tags, time strings for
15644 deadline, scheduled, and clocking, and any additional properties
15645 defined in the entry.
15647 If WHICH is nil or `all', get all properties. If WHICH is
15648 `special' or `standard', only get that subclass. If WHICH is
15649 a string, only get that property.
15651 Return value is an alist. Keys are properties, as upcased
15652 strings."
15653 (org-with-point-at pom
15654 (when (and (derived-mode-p 'org-mode)
15655 (ignore-errors (org-back-to-heading t)))
15656 (catch 'exit
15657 (let* ((beg (point))
15658 (specific (and (stringp which) (upcase which)))
15659 (which (cond ((not specific) which)
15660 ((member specific org-special-properties) 'special)
15661 (t 'standard)))
15662 props)
15663 ;; Get the special properties, like TODO and TAGS.
15664 (when (memq which '(nil all special))
15665 (when (or (not specific) (string= specific "CLOCKSUM"))
15666 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15667 (when clocksum
15668 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15669 props)))
15670 (when specific (throw 'exit props)))
15671 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15672 (let ((clocksumt (get-text-property (point)
15673 :org-clock-minutes-today)))
15674 (when clocksumt
15675 (push (cons "CLOCKSUM_T"
15676 (org-duration-from-minutes clocksumt))
15677 props)))
15678 (when specific (throw 'exit props)))
15679 (when (or (not specific) (string= specific "ITEM"))
15680 (let ((case-fold-search nil))
15681 (when (looking-at org-complex-heading-regexp)
15682 (push (cons "ITEM"
15683 (let ((title (match-string-no-properties 4)))
15684 (if (org-string-nw-p title)
15685 (org-remove-tabs title)
15686 "")))
15687 props)))
15688 (when specific (throw 'exit props)))
15689 (when (or (not specific) (string= specific "TODO"))
15690 (let ((case-fold-search nil))
15691 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15692 (push (cons "TODO" (match-string-no-properties 2)) props)))
15693 (when specific (throw 'exit props)))
15694 (when (or (not specific) (string= specific "PRIORITY"))
15695 (push (cons "PRIORITY"
15696 (if (looking-at org-priority-regexp)
15697 (match-string-no-properties 2)
15698 (char-to-string org-default-priority)))
15699 props)
15700 (when specific (throw 'exit props)))
15701 (when (or (not specific) (string= specific "FILE"))
15702 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15703 props)
15704 (when specific (throw 'exit props)))
15705 (when (or (not specific) (string= specific "TAGS"))
15706 (let ((value (org-string-nw-p (org-get-tags-string))))
15707 (when value (push (cons "TAGS" value) props)))
15708 (when specific (throw 'exit props)))
15709 (when (or (not specific) (string= specific "ALLTAGS"))
15710 (let ((value (org-get-tags-at)))
15711 (when value
15712 (push (cons "ALLTAGS"
15713 (format ":%s:" (mapconcat #'identity value ":")))
15714 props)))
15715 (when specific (throw 'exit props)))
15716 (when (or (not specific) (string= specific "BLOCKED"))
15717 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15718 (when specific (throw 'exit props)))
15719 (when (or (not specific)
15720 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15721 (forward-line)
15722 (when (looking-at-p org-planning-line-re)
15723 (end-of-line)
15724 (let ((bol (line-beginning-position))
15725 ;; Backward compatibility: time keywords used to
15726 ;; be configurable (before 8.3). Make sure we
15727 ;; get the correct keyword.
15728 (key-assoc `(("CLOSED" . ,org-closed-string)
15729 ("DEADLINE" . ,org-deadline-string)
15730 ("SCHEDULED" . ,org-scheduled-string))))
15731 (dolist (pair (if specific (list (assoc specific key-assoc))
15732 key-assoc))
15733 (save-excursion
15734 (when (search-backward (cdr pair) bol t)
15735 (goto-char (match-end 0))
15736 (skip-chars-forward " \t")
15737 (and (looking-at org-ts-regexp-both)
15738 (push (cons (car pair)
15739 (match-string-no-properties 0))
15740 props)))))))
15741 (when specific (throw 'exit props)))
15742 (when (or (not specific)
15743 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15744 (let ((find-ts
15745 (lambda (end ts)
15746 ;; Fix next time-stamp before END. TS is the
15747 ;; list of time-stamps found so far.
15748 (let ((ts ts)
15749 (regexp (cond
15750 ((string= specific "TIMESTAMP")
15751 org-ts-regexp)
15752 ((string= specific "TIMESTAMP_IA")
15753 org-ts-regexp-inactive)
15754 ((assoc "TIMESTAMP_IA" ts)
15755 org-ts-regexp)
15756 ((assoc "TIMESTAMP" ts)
15757 org-ts-regexp-inactive)
15758 (t org-ts-regexp-both))))
15759 (catch 'next
15760 (while (re-search-forward regexp end t)
15761 (backward-char)
15762 (let ((object (org-element-context)))
15763 ;; Accept to match timestamps in node
15764 ;; properties, too.
15765 (when (memq (org-element-type object)
15766 '(node-property timestamp))
15767 (let ((type
15768 (org-element-property :type object)))
15769 (cond
15770 ((and (memq type '(active active-range))
15771 (not (equal specific "TIMESTAMP_IA")))
15772 (unless (assoc "TIMESTAMP" ts)
15773 (push (cons "TIMESTAMP"
15774 (org-element-property
15775 :raw-value object))
15777 (when specific (throw 'exit ts))))
15778 ((and (memq type '(inactive inactive-range))
15779 (not (string= specific "TIMESTAMP")))
15780 (unless (assoc "TIMESTAMP_IA" ts)
15781 (push (cons "TIMESTAMP_IA"
15782 (org-element-property
15783 :raw-value object))
15785 (when specific (throw 'exit ts))))))
15786 ;; Both timestamp types are found,
15787 ;; move to next part.
15788 (when (= (length ts) 2) (throw 'next ts)))))
15789 ts)))))
15790 (goto-char beg)
15791 ;; First look for timestamps within headline.
15792 (let ((ts (funcall find-ts (line-end-position) nil)))
15793 (if (= (length ts) 2) (setq props (nconc ts props))
15794 ;; Then find timestamps in the section, skipping
15795 ;; planning line.
15796 (let ((end (save-excursion (outline-next-heading))))
15797 (forward-line)
15798 (when (looking-at-p org-planning-line-re) (forward-line))
15799 (setq props (nconc (funcall find-ts end ts) props))))))))
15800 ;; Get the standard properties, like :PROP:.
15801 (when (memq which '(nil all standard))
15802 ;; If we are looking after a specific property, delegate
15803 ;; to `org-entry-get', which is faster. However, make an
15804 ;; exception for "CATEGORY", since it can be also set
15805 ;; through keywords (i.e. #+CATEGORY).
15806 (if (and specific (not (equal specific "CATEGORY")))
15807 (let ((value (org-entry-get beg specific nil t)))
15808 (throw 'exit (and value (list (cons specific value)))))
15809 (let ((range (org-get-property-block beg)))
15810 (when range
15811 (let ((end (cdr range)) seen-base)
15812 (goto-char (car range))
15813 ;; Unlike to `org--update-property-plist', we
15814 ;; handle the case where base values is found
15815 ;; after its extension. We also forbid standard
15816 ;; properties to be named as special properties.
15817 (while (re-search-forward org-property-re end t)
15818 (let* ((key (upcase (match-string-no-properties 2)))
15819 (extendp (string-match-p "\\+\\'" key))
15820 (key-base (if extendp (substring key 0 -1) key))
15821 (value (match-string-no-properties 3)))
15822 (cond
15823 ((member-ignore-case key-base org-special-properties))
15824 (extendp
15825 (setq props
15826 (org--update-property-plist key value props)))
15827 ((member key seen-base))
15828 (t (push key seen-base)
15829 (let ((p (assoc-string key props t)))
15830 (if p (setcdr p (concat value " " (cdr p)))
15831 (push (cons key value) props))))))))))))
15832 (unless (assoc "CATEGORY" props)
15833 (push (cons "CATEGORY" (org-get-category beg)) props)
15834 (when (string= specific "CATEGORY") (throw 'exit props)))
15835 ;; Return value.
15836 props)))))
15838 (defun org--property-local-values (property literal-nil)
15839 "Return value for PROPERTY in current entry.
15840 Value is a list whose car is the base value for PROPERTY and cdr
15841 a list of accumulated values. Return nil if neither is found in
15842 the entry. Also return nil when PROPERTY is set to \"nil\",
15843 unless LITERAL-NIL is non-nil."
15844 (let ((range (org-get-property-block)))
15845 (when range
15846 (goto-char (car range))
15847 (let* ((case-fold-search t)
15848 (end (cdr range))
15849 (value
15850 ;; Base value.
15851 (save-excursion
15852 (let ((v (and (re-search-forward
15853 (org-re-property property nil t) end t)
15854 (match-string-no-properties 3))))
15855 (list (if literal-nil v (org-not-nil v)))))))
15856 ;; Find additional values.
15857 (let* ((property+ (org-re-property (concat property "+") nil t)))
15858 (while (re-search-forward property+ end t)
15859 (push (match-string-no-properties 3) value)))
15860 ;; Return final values.
15861 (and (not (equal value '(nil))) (nreverse value))))))
15863 (defun org--property-global-value (property literal-nil)
15864 "Return value for PROPERTY in current buffer.
15865 Return value is a string. Return nil if property is not set
15866 globally. Also return nil when PROPERTY is set to \"nil\",
15867 unless LITERAL-NIL is non-nil."
15868 (let ((global
15869 (cdr (or (assoc-string property org-file-properties t)
15870 (assoc-string property org-global-properties t)
15871 (assoc-string property org-global-properties-fixed t)))))
15872 (if literal-nil global (org-not-nil global))))
15874 (defun org-entry-get (pom property &optional inherit literal-nil)
15875 "Get value of PROPERTY for entry or content at point-or-marker POM.
15877 If INHERIT is non-nil and the entry does not have the property,
15878 then also check higher levels of the hierarchy. If INHERIT is
15879 the symbol `selective', use inheritance only if the setting in
15880 `org-use-property-inheritance' selects PROPERTY for inheritance.
15882 If the property is present but empty, the return value is the
15883 empty string. If the property is not present at all, nil is
15884 returned. In any other case, return the value as a string.
15885 Search is case-insensitive.
15887 If LITERAL-NIL is set, return the string value \"nil\" as
15888 a string, do not interpret it as the list atom nil. This is used
15889 for inheritance when a \"nil\" value can supersede a non-nil
15890 value higher up the hierarchy."
15891 (org-with-point-at pom
15892 (cond
15893 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15894 ;; We need a special property. Use `org-entry-properties' to
15895 ;; retrieve it, but specify the wanted property.
15896 (cdr (assoc-string property (org-entry-properties nil property))))
15897 ((and inherit
15898 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15899 (org-entry-get-with-inheritance property literal-nil))
15901 (let* ((local (org--property-local-values property literal-nil))
15902 (value (and local (mapconcat #'identity (delq nil local) " "))))
15903 (if literal-nil value (org-not-nil value)))))))
15905 (defun org-property-or-variable-value (var &optional inherit)
15906 "Check if there is a property fixing the value of VAR.
15907 If yes, return this value. If not, return the current value of the variable."
15908 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15909 (if (and prop (stringp prop) (string-match "\\S-" prop))
15910 (read prop)
15911 (symbol-value var))))
15913 (defun org-entry-delete (pom property)
15914 "Delete PROPERTY from entry at point-or-marker POM.
15915 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15916 non-nil when a property was removed."
15917 (org-with-point-at pom
15918 (pcase (org-get-property-block)
15919 (`(,begin . ,origin)
15920 (let* ((end (copy-marker origin))
15921 (re (org-re-property
15922 (concat (regexp-quote property) "\\+?") t t)))
15923 (goto-char begin)
15924 (while (re-search-forward re end t)
15925 (delete-region (match-beginning 0) (line-beginning-position 2)))
15926 ;; If drawer is empty, remove it altogether.
15927 (when (= begin end)
15928 (delete-region (line-beginning-position 0)
15929 (line-beginning-position 2)))
15930 ;; Return non-nil if some property was removed.
15931 (prog1 (/= end origin) (set-marker end nil))))
15932 (_ nil))))
15934 ;; Multi-values properties are properties that contain multiple values
15935 ;; These values are assumed to be single words, separated by whitespace.
15936 (defun org-entry-add-to-multivalued-property (pom property value)
15937 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15938 (let* ((old (org-entry-get pom property))
15939 (values (and old (org-split-string old "[ \t]"))))
15940 (setq value (org-entry-protect-space value))
15941 (unless (member value values)
15942 (setq values (append values (list value)))
15943 (org-entry-put pom property
15944 (mapconcat 'identity values " ")))))
15946 (defun org-entry-remove-from-multivalued-property (pom property value)
15947 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15948 (let* ((old (org-entry-get pom property))
15949 (values (and old (org-split-string old "[ \t]"))))
15950 (setq value (org-entry-protect-space value))
15951 (when (member value values)
15952 (setq values (delete value values))
15953 (org-entry-put pom property
15954 (mapconcat 'identity values " ")))))
15956 (defun org-entry-member-in-multivalued-property (pom property value)
15957 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15958 (let* ((old (org-entry-get pom property))
15959 (values (and old (org-split-string old "[ \t]"))))
15960 (setq value (org-entry-protect-space value))
15961 (member value values)))
15963 (defun org-entry-get-multivalued-property (pom property)
15964 "Return a list of values in a multivalued property."
15965 (let* ((value (org-entry-get pom property))
15966 (values (and value (org-split-string value "[ \t]"))))
15967 (mapcar 'org-entry-restore-space values)))
15969 (defun org-entry-put-multivalued-property (pom property &rest values)
15970 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15971 VALUES should be a list of strings. Spaces will be protected."
15972 (org-entry-put pom property
15973 (mapconcat 'org-entry-protect-space values " "))
15974 (let* ((value (org-entry-get pom property))
15975 (values (and value (org-split-string value "[ \t]"))))
15976 (mapcar 'org-entry-restore-space values)))
15978 (defun org-entry-protect-space (s)
15979 "Protect spaces and newline in string S."
15980 (while (string-match " " s)
15981 (setq s (replace-match "%20" t t s)))
15982 (while (string-match "\n" s)
15983 (setq s (replace-match "%0A" t t s)))
15986 (defun org-entry-restore-space (s)
15987 "Restore spaces and newline in string S."
15988 (while (string-match "%20" s)
15989 (setq s (replace-match " " t t s)))
15990 (while (string-match "%0A" s)
15991 (setq s (replace-match "\n" t t s)))
15994 (defvar org-entry-property-inherited-from (make-marker)
15995 "Marker pointing to the entry from where a property was inherited.
15996 Each call to `org-entry-get-with-inheritance' will set this marker to the
15997 location of the entry where the inheritance search matched. If there was
15998 no match, the marker will point nowhere.
15999 Note that also `org-entry-get' calls this function, if the INHERIT flag
16000 is set.")
16002 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16003 "Get PROPERTY of entry or content at point, search higher levels if needed.
16004 The search will stop at the first ancestor which has the property defined.
16005 If the value found is \"nil\", return nil to show that the property
16006 should be considered as undefined (this is the meaning of nil here).
16007 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16008 (move-marker org-entry-property-inherited-from nil)
16009 (org-with-wide-buffer
16010 (let (value)
16011 (catch 'exit
16012 (while t
16013 (let ((v (org--property-local-values property literal-nil)))
16014 (when v
16015 (setq value
16016 (concat (mapconcat #'identity (delq nil v) " ")
16017 (and value " ")
16018 value)))
16019 (cond
16020 ((car v)
16021 (org-back-to-heading t)
16022 (move-marker org-entry-property-inherited-from (point))
16023 (throw 'exit nil))
16024 ((org-up-heading-safe))
16026 (let ((global (org--property-global-value property literal-nil)))
16027 (cond ((not global))
16028 (value (setq value (concat global " " value)))
16029 (t (setq value global))))
16030 (throw 'exit nil))))))
16031 (if literal-nil value (org-not-nil value)))))
16033 (defvar org-property-changed-functions nil
16034 "Hook called when the value of a property has changed.
16035 Each hook function should accept two arguments, the name of the property
16036 and the new value.")
16038 (defun org-entry-put (pom property value)
16039 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16041 If the value is nil, it is converted to the empty string. If it
16042 is not a string, an error is raised. Also raise an error on
16043 invalid property names.
16045 PROPERTY can be any regular property (see
16046 `org-special-properties'). It can also be \"TODO\",
16047 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16049 For the last two properties, VALUE may have any of the special
16050 values \"earlier\" and \"later\". The function then increases or
16051 decreases scheduled or deadline date by one day."
16052 (cond ((null value) (setq value ""))
16053 ((not (stringp value)) (error "Properties values should be strings"))
16054 ((not (org--valid-property-p property))
16055 (user-error "Invalid property name: \"%s\"" property)))
16056 (org-with-point-at pom
16057 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16058 (org-back-to-heading t)
16059 (org-with-limited-levels (org-back-to-heading t)))
16060 (let ((beg (point)))
16061 (cond
16062 ((equal property "TODO")
16063 (cond ((not (org-string-nw-p value)) (setq value 'none))
16064 ((not (member value org-todo-keywords-1))
16065 (user-error "\"%s\" is not a valid TODO state" value)))
16066 (org-todo value)
16067 (org-set-tags nil 'align))
16068 ((equal property "PRIORITY")
16069 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16070 (org-set-tags nil 'align))
16071 ((equal property "SCHEDULED")
16072 (forward-line)
16073 (if (and (looking-at-p org-planning-line-re)
16074 (re-search-forward
16075 org-scheduled-time-regexp (line-end-position) t))
16076 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16077 ((string= value "later") (org-timestamp-change 1 'day))
16078 ((string= value "") (org-schedule '(4)))
16079 (t (org-schedule nil value)))
16080 (if (member value '("earlier" "later" ""))
16081 (call-interactively #'org-schedule)
16082 (org-schedule nil value))))
16083 ((equal property "DEADLINE")
16084 (forward-line)
16085 (if (and (looking-at-p org-planning-line-re)
16086 (re-search-forward
16087 org-deadline-time-regexp (line-end-position) t))
16088 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16089 ((string= value "later") (org-timestamp-change 1 'day))
16090 ((string= value "") (org-deadline '(4)))
16091 (t (org-deadline nil value)))
16092 (if (member value '("earlier" "later" ""))
16093 (call-interactively #'org-deadline)
16094 (org-deadline nil value))))
16095 ((member property org-special-properties)
16096 (error "The %s property cannot be set with `org-entry-put'" property))
16098 (let* ((range (org-get-property-block beg 'force))
16099 (end (cdr range))
16100 (case-fold-search t))
16101 (goto-char (car range))
16102 (if (re-search-forward (org-re-property property nil t) end t)
16103 (progn (delete-region (match-beginning 0) (match-end 0))
16104 (goto-char (match-beginning 0)))
16105 (goto-char end)
16106 (insert "\n")
16107 (backward-char))
16108 (insert ":" property ":")
16109 (when value (insert " " value))
16110 (org-indent-line)))))
16111 (run-hook-with-args 'org-property-changed-functions property value)))
16113 (defun org-buffer-property-keys
16114 (&optional specials defaults columns ignore-malformed)
16115 "Get all property keys in the current buffer.
16117 When SPECIALS is non-nil, also list the special properties that
16118 reflect things like tags and TODO state.
16120 When DEFAULTS is non-nil, also include properties that has
16121 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16122 DESCRIPTION, LOCATION, and LOGGING and others.
16124 When COLUMNS in non-nil, also include property names given in
16125 COLUMN formats in the current buffer.
16127 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16128 automatically performed, such drawers will be silently ignored."
16129 (let ((case-fold-search t)
16130 (props (append
16131 (and specials org-special-properties)
16132 (and defaults (cons org-effort-property org-default-properties))
16133 nil)))
16134 (org-with-wide-buffer
16135 (goto-char (point-min))
16136 (while (re-search-forward org-property-start-re nil t)
16137 (let ((range (org-get-property-block)))
16138 (catch 'skip
16139 (unless range
16140 (when (and (not ignore-malformed)
16141 (not (org-before-first-heading-p))
16142 (y-or-n-p (format "Malformed drawer at %d, repair?"
16143 (line-beginning-position))))
16144 (org-get-property-block nil t))
16145 (throw 'skip nil))
16146 (goto-char (car range))
16147 (let ((begin (car range))
16148 (end (cdr range)))
16149 ;; Make sure that found property block is not located
16150 ;; before current point, as it would generate an infloop.
16151 ;; It can happen, for example, in the following
16152 ;; situation:
16154 ;; * Headline
16155 ;; :PROPERTIES:
16156 ;; ...
16157 ;; :END:
16158 ;; *************** Inlinetask
16159 ;; #+BEGIN_EXAMPLE
16160 ;; :PROPERTIES:
16161 ;; #+END_EXAMPLE
16163 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16164 (while (< (point) end)
16165 (let ((p (progn (looking-at org-property-re)
16166 (match-string-no-properties 2))))
16167 ;; Only add true property name, not extension symbol.
16168 (push (if (not (string-match-p "\\+\\'" p)) p
16169 (substring p 0 -1))
16170 props))
16171 (forward-line))))
16172 (outline-next-heading)))
16173 (when columns
16174 (goto-char (point-min))
16175 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16176 (let ((element (org-element-at-point)))
16177 (when (memq (org-element-type element) '(keyword node-property))
16178 (let ((value (org-element-property :value element))
16179 (start 0))
16180 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16181 (setq start (match-end 0))
16182 (let ((p (match-string-no-properties 1 value)))
16183 (unless (member-ignore-case p org-special-properties)
16184 (push p props))))))))))
16185 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16187 (defun org-property-values (key)
16188 "List all non-nil values of property KEY in current buffer."
16189 (org-with-wide-buffer
16190 (goto-char (point-min))
16191 (let ((case-fold-search t)
16192 (re (org-re-property key))
16193 values)
16194 (while (re-search-forward re nil t)
16195 (push (org-entry-get (point) key) values))
16196 (delete-dups values))))
16198 (defun org-insert-property-drawer ()
16199 "Insert a property drawer into the current entry."
16200 (org-with-wide-buffer
16201 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16202 (org-back-to-heading t)
16203 (org-with-limited-levels (org-back-to-heading t)))
16204 (forward-line)
16205 (when (looking-at-p org-planning-line-re) (forward-line))
16206 (unless (looking-at-p org-property-drawer-re)
16207 ;; Make sure we start editing a line from current entry, not from
16208 ;; next one. It prevents extending text properties or overlays
16209 ;; belonging to the latter.
16210 (when (bolp) (backward-char))
16211 (let ((begin (1+ (point)))
16212 (inhibit-read-only t))
16213 (insert "\n:PROPERTIES:\n:END:")
16214 (when (eobp) (insert "\n"))
16215 (org-indent-region begin (point))))))
16217 (defun org-insert-drawer (&optional arg drawer)
16218 "Insert a drawer at point.
16220 When optional argument ARG is non-nil, insert a property drawer.
16222 Optional argument DRAWER, when non-nil, is a string representing
16223 drawer's name. Otherwise, the user is prompted for a name.
16225 If a region is active, insert the drawer around that region
16226 instead.
16228 Point is left between drawer's boundaries."
16229 (interactive "P")
16230 (let* ((drawer (if arg "PROPERTIES"
16231 (or drawer (read-from-minibuffer "Drawer: ")))))
16232 (cond
16233 ;; With C-u, fall back on `org-insert-property-drawer'
16234 (arg (org-insert-property-drawer))
16235 ;; Check validity of suggested drawer's name.
16236 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16237 (user-error "Invalid drawer name"))
16238 ;; With an active region, insert a drawer at point.
16239 ((not (org-region-active-p))
16240 (progn
16241 (unless (bolp) (insert "\n"))
16242 (insert (format ":%s:\n\n:END:\n" drawer))
16243 (forward-line -2)))
16244 ;; Otherwise, insert the drawer at point
16246 (let ((rbeg (region-beginning))
16247 (rend (copy-marker (region-end))))
16248 (unwind-protect
16249 (progn
16250 (goto-char rbeg)
16251 (beginning-of-line)
16252 (when (save-excursion
16253 (re-search-forward org-outline-regexp-bol rend t))
16254 (user-error "Drawers cannot contain headlines"))
16255 ;; Position point at the beginning of the first
16256 ;; non-blank line in region. Insert drawer's opening
16257 ;; there, then indent it.
16258 (org-skip-whitespace)
16259 (beginning-of-line)
16260 (insert ":" drawer ":\n")
16261 (forward-line -1)
16262 (indent-for-tab-command)
16263 ;; Move point to the beginning of the first blank line
16264 ;; after the last non-blank line in region. Insert
16265 ;; drawer's closing, then indent it.
16266 (goto-char rend)
16267 (skip-chars-backward " \r\t\n")
16268 (insert "\n:END:")
16269 (deactivate-mark t)
16270 (indent-for-tab-command)
16271 (unless (eolp) (insert "\n")))
16272 ;; Clear marker, whatever the outcome of insertion is.
16273 (set-marker rend nil)))))))
16275 (defvar org-property-set-functions-alist nil
16276 "Property set function alist.
16277 Each entry should have the following format:
16279 (PROPERTY . READ-FUNCTION)
16281 The read function will be called with the same argument as
16282 `org-completing-read'.")
16284 (defun org-set-property-function (property)
16285 "Get the function that should be used to set PROPERTY.
16286 This is computed according to `org-property-set-functions-alist'."
16287 (or (cdr (assoc property org-property-set-functions-alist))
16288 'org-completing-read))
16290 (defun org-read-property-value (property)
16291 "Read PROPERTY value from user."
16292 (let* ((completion-ignore-case t)
16293 (allowed (org-property-get-allowed-values nil property 'table))
16294 (cur (org-entry-get nil property))
16295 (prompt (concat property " value"
16296 (if (and cur (string-match "\\S-" cur))
16297 (concat " [" cur "]") "") ": "))
16298 (set-function (org-set-property-function property))
16299 (val (if allowed
16300 (funcall set-function prompt allowed nil
16301 (not (get-text-property 0 'org-unrestricted
16302 (caar allowed))))
16303 (funcall set-function prompt
16304 (mapcar 'list (org-property-values property))
16305 nil nil "" nil cur))))
16306 (org-trim val)))
16308 (defvar org-last-set-property nil)
16309 (defvar org-last-set-property-value nil)
16310 (defun org-read-property-name ()
16311 "Read a property name."
16312 (let ((completion-ignore-case t)
16313 (default-prop (or (and (org-at-property-p)
16314 (match-string-no-properties 2))
16315 org-last-set-property)))
16316 (org-completing-read
16317 (concat "Property"
16318 (if default-prop (concat " [" default-prop "]") "")
16319 ": ")
16320 (mapcar #'list (org-buffer-property-keys nil t t))
16321 nil nil nil nil default-prop)))
16323 (defun org-set-property-and-value (use-last)
16324 "Allow to set [PROPERTY]: [value] direction from prompt.
16325 When use-default, don't even ask, just use the last
16326 \"[PROPERTY]: [value]\" string from the history."
16327 (interactive "P")
16328 (let* ((completion-ignore-case t)
16329 (pv (or (and use-last org-last-set-property-value)
16330 (org-completing-read
16331 "Enter a \"[Property]: [value]\" pair: "
16332 nil nil nil nil nil
16333 org-last-set-property-value)))
16334 prop val)
16335 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16336 (setq prop (match-string 1 pv)
16337 val (match-string 2 pv))
16338 (org-set-property prop val))))
16340 (defun org-set-property (property value)
16341 "In the current entry, set PROPERTY to VALUE.
16343 When called interactively, this will prompt for a property name, offering
16344 completion on existing and default properties. And then it will prompt
16345 for a value, offering completion either on allowed values (via an inherited
16346 xxx_ALL property) or on existing values in other instances of this property
16347 in the current file.
16349 Throw an error when trying to set a property with an invalid name."
16350 (interactive (list nil nil))
16351 (let ((property (or property (org-read-property-name))))
16352 ;; `org-entry-put' also makes the following check, but this one
16353 ;; avoids polluting `org-last-set-property' and
16354 ;; `org-last-set-property-value' needlessly.
16355 (unless (org--valid-property-p property)
16356 (user-error "Invalid property name: \"%s\"" property))
16357 (let ((value (or value (org-read-property-value property)))
16358 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16359 (setq org-last-set-property property)
16360 (setq org-last-set-property-value (concat property ": " value))
16361 ;; Possibly postprocess the inserted value:
16362 (when fn (setq value (funcall fn value)))
16363 (unless (equal (org-entry-get nil property) value)
16364 (org-entry-put nil property value)))))
16366 (defun org-find-property (property &optional value)
16367 "Find first entry in buffer that sets PROPERTY.
16369 When optional argument VALUE is non-nil, only consider an entry
16370 if it contains PROPERTY set to this value. If PROPERTY should be
16371 explicitly set to nil, use string \"nil\" for VALUE.
16373 Return position where the entry begins, or nil if there is no
16374 such entry. If narrowing is in effect, only search the visible
16375 part of the buffer."
16376 (save-excursion
16377 (goto-char (point-min))
16378 (let ((case-fold-search t)
16379 (re (org-re-property property nil (not value) value)))
16380 (catch 'exit
16381 (while (re-search-forward re nil t)
16382 (when (if value (org-at-property-p)
16383 (org-entry-get (point) property nil t))
16384 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16386 (defun org-delete-property (property)
16387 "In the current entry, delete PROPERTY."
16388 (interactive
16389 (let* ((completion-ignore-case t)
16390 (cat (org-entry-get (point) "CATEGORY"))
16391 (props0 (org-entry-properties nil 'standard))
16392 (props (if cat props0
16393 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16394 (prop (if (< 1 (length props))
16395 (completing-read "Property: " props nil t)
16396 (caar props))))
16397 (list prop)))
16398 (if (not property)
16399 (message "No property to delete in this entry")
16400 (org-entry-delete nil property)
16401 (message "Property \"%s\" deleted" property)))
16403 (defun org-delete-property-globally (property)
16404 "Remove PROPERTY globally, from all entries.
16405 This function ignores narrowing, if any."
16406 (interactive
16407 (let* ((completion-ignore-case t)
16408 (prop (completing-read
16409 "Globally remove property: "
16410 (mapcar #'list (org-buffer-property-keys)))))
16411 (list prop)))
16412 (org-with-wide-buffer
16413 (goto-char (point-min))
16414 (let ((count 0)
16415 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16416 (while (re-search-forward re nil t)
16417 (when (org-entry-delete (point) property) (cl-incf count)))
16418 (message "Property \"%s\" removed from %d entries" property count))))
16420 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16422 (defun org-compute-property-at-point ()
16423 "Compute the property at point.
16424 This looks for an enclosing column format, extracts the operator and
16425 then applies it to the property in the column format's scope."
16426 (interactive)
16427 (unless (org-at-property-p)
16428 (user-error "Not at a property"))
16429 (let ((prop (match-string-no-properties 2)))
16430 (org-columns-get-format-and-top-level)
16431 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16432 (user-error "No operator defined for property %s" prop))
16433 (org-columns-compute prop)))
16435 (defvar org-property-allowed-value-functions nil
16436 "Hook for functions supplying allowed values for a specific property.
16437 The functions must take a single argument, the name of the property, and
16438 return a flat list of allowed values. If \":ETC\" is one of
16439 the values, this means that these values are intended as defaults for
16440 completion, but that other values should be allowed too.
16441 The functions must return nil if they are not responsible for this
16442 property.")
16444 (defun org-property-get-allowed-values (pom property &optional table)
16445 "Get allowed values for the property PROPERTY.
16446 When TABLE is non-nil, return an alist that can directly be used for
16447 completion."
16448 (let (vals)
16449 (cond
16450 ((equal property "TODO")
16451 (setq vals (org-with-point-at pom
16452 (append org-todo-keywords-1 '("")))))
16453 ((equal property "PRIORITY")
16454 (let ((n org-lowest-priority))
16455 (while (>= n org-highest-priority)
16456 (push (char-to-string n) vals)
16457 (setq n (1- n)))))
16458 ((equal property "CATEGORY"))
16459 ((member property org-special-properties))
16460 ((setq vals (run-hook-with-args-until-success
16461 'org-property-allowed-value-functions property)))
16463 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16464 (when (and vals (string-match "\\S-" vals))
16465 (setq vals (car (read-from-string (concat "(" vals ")"))))
16466 (setq vals (mapcar (lambda (x)
16467 (cond ((stringp x) x)
16468 ((numberp x) (number-to-string x))
16469 ((symbolp x) (symbol-name x))
16470 (t "???")))
16471 vals)))))
16472 (when (member ":ETC" vals)
16473 (setq vals (remove ":ETC" vals))
16474 (org-add-props (car vals) '(org-unrestricted t)))
16475 (if table (mapcar 'list vals) vals)))
16477 (defun org-property-previous-allowed-value (&optional _previous)
16478 "Switch to the next allowed value for this property."
16479 (interactive)
16480 (org-property-next-allowed-value t))
16482 (defun org-property-next-allowed-value (&optional previous)
16483 "Switch to the next allowed value for this property."
16484 (interactive)
16485 (unless (org-at-property-p)
16486 (user-error "Not at a property"))
16487 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16488 (key (match-string 2))
16489 (value (match-string 3))
16490 (allowed (or (org-property-get-allowed-values (point) key)
16491 (and (member value '("[ ]" "[-]" "[X]"))
16492 '("[ ]" "[X]"))))
16493 (heading (save-match-data (nth 4 (org-heading-components))))
16494 nval)
16495 (unless allowed
16496 (user-error "Allowed values for this property have not been defined"))
16497 (when previous (setq allowed (reverse allowed)))
16498 (when (member value allowed)
16499 (setq nval (car (cdr (member value allowed)))))
16500 (setq nval (or nval (car allowed)))
16501 (when (equal nval value)
16502 (user-error "Only one allowed value for this property"))
16503 (org-at-property-p)
16504 (replace-match (concat " :" key ": " nval) t t)
16505 (org-indent-line)
16506 (beginning-of-line 1)
16507 (skip-chars-forward " \t")
16508 (when (equal prop org-effort-property)
16509 (org-refresh-property
16510 '((effort . identity)
16511 (effort-minutes . org-duration-to-minutes))
16512 nval)
16513 (when (string= org-clock-current-task heading)
16514 (setq org-clock-effort nval)
16515 (org-clock-update-mode-line)))
16516 (run-hook-with-args 'org-property-changed-functions key nval)))
16518 (defun org-find-olp (path &optional this-buffer)
16519 "Return a marker pointing to the entry at outline path OLP.
16520 If anything goes wrong, throw an error.
16521 You can wrap this call to catch the error like this:
16523 (condition-case msg
16524 (org-mobile-locate-entry (match-string 4))
16525 (error (nth 1 msg)))
16527 The return value will then be either a string with the error message,
16528 or a marker if everything is OK.
16530 If THIS-BUFFER is set, the outline path does not contain a file,
16531 only headings."
16532 (let* ((file (if this-buffer buffer-file-name (pop path)))
16533 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16534 (level 1)
16535 (lmin 1)
16536 (lmax 1)
16537 end found flevel)
16538 (unless buffer (error "File not found :%s" file))
16539 (with-current-buffer buffer
16540 (unless (derived-mode-p 'org-mode)
16541 (error "Buffer %s needs to be in Org mode" buffer))
16542 (org-with-wide-buffer
16543 (goto-char (point-min))
16544 (dolist (heading path)
16545 (let ((re (format org-complex-heading-regexp-format
16546 (regexp-quote heading)))
16547 (cnt 0))
16548 (while (re-search-forward re end t)
16549 (setq level (- (match-end 1) (match-beginning 1)))
16550 (when (and (>= level lmin) (<= level lmax))
16551 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16552 (when (= cnt 0)
16553 (error "Heading not found on level %d: %s" lmax heading))
16554 (when (> cnt 1)
16555 (error "Heading not unique on level %d: %s" lmax heading))
16556 (goto-char found)
16557 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16558 (setq end (save-excursion (org-end-of-subtree t t)))))
16559 (when (org-at-heading-p)
16560 (point-marker))))))
16562 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16563 "Find node HEADING in BUFFER.
16564 Return a marker to the heading if it was found, or nil if not.
16565 If POS-ONLY is set, return just the position instead of a marker.
16567 The heading text must match exact, but it may have a TODO keyword,
16568 a priority cookie and tags in the standard locations."
16569 (with-current-buffer (or buffer (current-buffer))
16570 (org-with-wide-buffer
16571 (goto-char (point-min))
16572 (let (case-fold-search)
16573 (when (re-search-forward
16574 (format org-complex-heading-regexp-format
16575 (regexp-quote heading)) nil t)
16576 (if pos-only
16577 (match-beginning 0)
16578 (move-marker (make-marker) (match-beginning 0))))))))
16580 (defun org-find-exact-heading-in-directory (heading &optional dir)
16581 "Find Org node headline HEADING in all .org files in directory DIR.
16582 When the target headline is found, return a marker to this location."
16583 (let ((files (directory-files (or dir default-directory)
16584 t "\\`[^.#].*\\.org\\'"))
16585 visiting m buffer)
16586 (catch 'found
16587 (dolist (file files)
16588 (message "trying %s" file)
16589 (setq visiting (org-find-base-buffer-visiting file))
16590 (setq buffer (or visiting (find-file-noselect file)))
16591 (setq m (org-find-exact-headline-in-buffer
16592 heading buffer))
16593 (when (and (not m) (not visiting)) (kill-buffer buffer))
16594 (and m (throw 'found m))))))
16596 (defun org-find-entry-with-id (ident)
16597 "Locate the entry that contains the ID property with exact value IDENT.
16598 IDENT can be a string, a symbol or a number, this function will search for
16599 the string representation of it.
16600 Return the position where this entry starts, or nil if there is no such entry."
16601 (interactive "sID: ")
16602 (let ((id (cond
16603 ((stringp ident) ident)
16604 ((symbolp ident) (symbol-name ident))
16605 ((numberp ident) (number-to-string ident))
16606 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16607 (org-with-wide-buffer (org-find-property "ID" id))))
16609 ;;;; Timestamps
16611 (defvar org-last-changed-timestamp nil)
16612 (defvar org-last-inserted-timestamp nil
16613 "The last time stamp inserted with `org-insert-time-stamp'.")
16615 (defun org-time-stamp (arg &optional inactive)
16616 "Prompt for a date/time and insert a time stamp.
16618 If the user specifies a time like HH:MM or if this command is
16619 called with at least one prefix argument, the time stamp contains
16620 the date and the time. Otherwise, only the date is included.
16622 All parts of a date not specified by the user are filled in from
16623 the timestamp at point, if any, or the current date/time
16624 otherwise.
16626 If there is already a timestamp at the cursor, it is replaced.
16628 With two universal prefix arguments, insert an active timestamp
16629 with the current time without prompting the user.
16631 When called from lisp, the timestamp is inactive if INACTIVE is
16632 non-nil."
16633 (interactive "P")
16634 (let* ((ts (cond
16635 ((org-at-date-range-p t)
16636 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16637 ((org-at-timestamp-p 'lax) (match-string 0))))
16638 ;; Default time is either the timestamp at point or today.
16639 ;; When entering a range, only the range start is considered.
16640 (default-time (if (not ts) (current-time)
16641 (apply #'encode-time (org-parse-time-string ts))))
16642 (default-input (and ts (org-get-compact-tod ts)))
16643 (repeater (and ts
16644 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16645 (match-string 0 ts)))
16646 org-time-was-given
16647 org-end-time-was-given
16648 (time
16649 (and (if (equal arg '(16)) (current-time)
16650 ;; Preserve `this-command' and `last-command'.
16651 (let ((this-command this-command)
16652 (last-command last-command))
16653 (org-read-date
16654 arg 'totime nil nil default-time default-input
16655 inactive))))))
16656 (cond
16657 ((and ts
16658 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16659 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16660 (insert "--")
16661 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16663 ;; Make sure we're on a timestamp. When in the middle of a date
16664 ;; range, move arbitrarily to range end.
16665 (unless (org-at-timestamp-p 'lax)
16666 (skip-chars-forward "-")
16667 (org-at-timestamp-p 'lax))
16668 (replace-match "")
16669 (setq org-last-changed-timestamp
16670 (org-insert-time-stamp
16671 time (or org-time-was-given arg)
16672 inactive nil nil (list org-end-time-was-given)))
16673 (when repeater
16674 (backward-char)
16675 (insert " " repeater)
16676 (setq org-last-changed-timestamp
16677 (concat (substring org-last-inserted-timestamp 0 -1)
16678 " " repeater ">")))
16679 (message "Timestamp updated"))
16680 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16681 (t (org-insert-time-stamp
16682 time (or org-time-was-given arg) inactive nil nil
16683 (list org-end-time-was-given))))))
16685 ;; FIXME: can we use this for something else, like computing time differences?
16686 (defun org-get-compact-tod (s)
16687 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16688 (let* ((t1 (match-string 1 s))
16689 (h1 (string-to-number (match-string 2 s)))
16690 (m1 (string-to-number (match-string 3 s)))
16691 (t2 (and (match-end 4) (match-string 5 s)))
16692 (h2 (and t2 (string-to-number (match-string 6 s))))
16693 (m2 (and t2 (string-to-number (match-string 7 s))))
16694 dh dm)
16695 (if (not t2)
16697 (setq dh (- h2 h1) dm (- m2 m1))
16698 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16699 (concat t1 "+" (number-to-string dh)
16700 (and (/= 0 dm) (format ":%02d" dm)))))))
16702 (defun org-time-stamp-inactive (&optional arg)
16703 "Insert an inactive time stamp.
16704 An inactive time stamp is enclosed in square brackets instead of angle
16705 brackets. It is inactive in the sense that it does not trigger agenda entries,
16706 does not link to the calendar and cannot be changed with the S-cursor keys.
16707 So these are more for recording a certain time/date."
16708 (interactive "P")
16709 (org-time-stamp arg 'inactive))
16711 (defvar org-date-ovl (make-overlay 1 1))
16712 (overlay-put org-date-ovl 'face 'org-date-selected)
16713 (delete-overlay org-date-ovl)
16715 (defvar org-ans1) ; dynamically scoped parameter
16716 (defvar org-ans2) ; dynamically scoped parameter
16718 (defvar org-plain-time-of-day-regexp) ; defined below
16720 (defvar org-overriding-default-time nil) ; dynamically scoped
16721 (defvar org-read-date-overlay nil)
16722 (defvar org-dcst nil) ; dynamically scoped
16723 (defvar org-read-date-history nil)
16724 (defvar org-read-date-final-answer nil)
16725 (defvar org-read-date-analyze-futurep nil)
16726 (defvar org-read-date-analyze-forced-year nil)
16727 (defvar org-read-date-inactive)
16729 (defvar org-read-date-minibuffer-local-map
16730 (let* ((map (make-sparse-keymap)))
16731 (set-keymap-parent map minibuffer-local-map)
16732 (org-defkey map (kbd ".")
16733 (lambda () (interactive)
16734 ;; Are we at the beginning of the prompt?
16735 (if (looking-back "^[^:]+: "
16736 (let ((inhibit-field-text-motion t))
16737 (line-beginning-position)))
16738 (org-eval-in-calendar '(calendar-goto-today))
16739 (insert "."))))
16740 (org-defkey map (kbd "C-.")
16741 (lambda () (interactive)
16742 (org-eval-in-calendar '(calendar-goto-today))))
16743 (org-defkey map [(meta shift left)]
16744 (lambda () (interactive)
16745 (org-eval-in-calendar '(calendar-backward-month 1))))
16746 (org-defkey map [(meta shift right)]
16747 (lambda () (interactive)
16748 (org-eval-in-calendar '(calendar-forward-month 1))))
16749 (org-defkey map [(meta shift up)]
16750 (lambda () (interactive)
16751 (org-eval-in-calendar '(calendar-backward-year 1))))
16752 (org-defkey map [(meta shift down)]
16753 (lambda () (interactive)
16754 (org-eval-in-calendar '(calendar-forward-year 1))))
16755 (org-defkey map [?\e (shift left)]
16756 (lambda () (interactive)
16757 (org-eval-in-calendar '(calendar-backward-month 1))))
16758 (org-defkey map [?\e (shift right)]
16759 (lambda () (interactive)
16760 (org-eval-in-calendar '(calendar-forward-month 1))))
16761 (org-defkey map [?\e (shift up)]
16762 (lambda () (interactive)
16763 (org-eval-in-calendar '(calendar-backward-year 1))))
16764 (org-defkey map [?\e (shift down)]
16765 (lambda () (interactive)
16766 (org-eval-in-calendar '(calendar-forward-year 1))))
16767 (org-defkey map [(shift up)]
16768 (lambda () (interactive)
16769 (org-eval-in-calendar '(calendar-backward-week 1))))
16770 (org-defkey map [(shift down)]
16771 (lambda () (interactive)
16772 (org-eval-in-calendar '(calendar-forward-week 1))))
16773 (org-defkey map [(shift left)]
16774 (lambda () (interactive)
16775 (org-eval-in-calendar '(calendar-backward-day 1))))
16776 (org-defkey map [(shift right)]
16777 (lambda () (interactive)
16778 (org-eval-in-calendar '(calendar-forward-day 1))))
16779 (org-defkey map "!"
16780 (lambda () (interactive)
16781 (org-eval-in-calendar '(diary-view-entries))
16782 (message "")))
16783 (org-defkey map ">"
16784 (lambda () (interactive)
16785 (org-eval-in-calendar '(calendar-scroll-left 1))))
16786 (org-defkey map "<"
16787 (lambda () (interactive)
16788 (org-eval-in-calendar '(calendar-scroll-right 1))))
16789 (org-defkey map "\C-v"
16790 (lambda () (interactive)
16791 (org-eval-in-calendar
16792 '(calendar-scroll-left-three-months 1))))
16793 (org-defkey map "\M-v"
16794 (lambda () (interactive)
16795 (org-eval-in-calendar
16796 '(calendar-scroll-right-three-months 1))))
16797 map)
16798 "Keymap for minibuffer commands when using `org-read-date'.")
16800 (defvar org-def)
16801 (defvar org-defdecode)
16802 (defvar org-with-time)
16804 (defvar calendar-setup) ; Dynamically scoped.
16805 (defun org-read-date (&optional with-time to-time from-string prompt
16806 default-time default-input inactive)
16807 "Read a date, possibly a time, and make things smooth for the user.
16808 The prompt will suggest to enter an ISO date, but you can also enter anything
16809 which will at least partially be understood by `parse-time-string'.
16810 Unrecognized parts of the date will default to the current day, month, year,
16811 hour and minute. If this command is called to replace a timestamp at point,
16812 or to enter the second timestamp of a range, the default time is taken
16813 from the existing stamp. Furthermore, the command prefers the future,
16814 so if you are giving a date where the year is not given, and the day-month
16815 combination is already past in the current year, it will assume you
16816 mean next year. For details, see the manual. A few examples:
16818 3-2-5 --> 2003-02-05
16819 feb 15 --> currentyear-02-15
16820 2/15 --> currentyear-02-15
16821 sep 12 9 --> 2009-09-12
16822 12:45 --> today 12:45
16823 22 sept 0:34 --> currentyear-09-22 0:34
16824 12 --> currentyear-currentmonth-12
16825 Fri --> nearest Friday after today
16826 -Tue --> last Tuesday
16827 etc.
16829 Furthermore you can specify a relative date by giving, as the *first* thing
16830 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16831 change in days weeks, months, years.
16832 With a single plus or minus, the date is relative to today. With a double
16833 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16834 +4d --> four days from today
16835 +4 --> same as above
16836 +2w --> two weeks from today
16837 ++5 --> five days from default date
16839 The function understands only English month and weekday abbreviations.
16841 While prompting, a calendar is popped up - you can also select the
16842 date with the mouse (button 1). The calendar shows a period of three
16843 months. To scroll it to other months, use the keys `>' and `<'.
16844 If you don't like the calendar, turn it off with
16845 (setq org-read-date-popup-calendar nil)
16847 With optional argument TO-TIME, the date will immediately be converted
16848 to an internal time.
16849 With an optional argument WITH-TIME, the prompt will suggest to
16850 also insert a time. Note that when WITH-TIME is not set, you can
16851 still enter a time, and this function will inform the calling routine
16852 about this change. The calling routine may then choose to change the
16853 format used to insert the time stamp into the buffer to include the time.
16854 With optional argument FROM-STRING, read from this string instead from
16855 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16856 the time/date that is used for everything that is not specified by the
16857 user."
16858 (require 'parse-time)
16859 (let* ((org-with-time with-time)
16860 (org-time-stamp-rounding-minutes
16861 (if (equal org-with-time '(16))
16862 '(0 0)
16863 org-time-stamp-rounding-minutes))
16864 (org-dcst org-display-custom-times)
16865 (ct (org-current-time))
16866 (org-def (or org-overriding-default-time default-time ct))
16867 (org-defdecode (decode-time org-def))
16868 (cur-frame (selected-frame))
16869 (mouse-autoselect-window nil) ; Don't let the mouse jump
16870 (calendar-setup
16871 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16872 (calendar-move-hook nil)
16873 (calendar-view-diary-initially-flag nil)
16874 (calendar-view-holidays-initially-flag nil)
16875 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16876 ;; Rationalize `org-def' and `org-defdecode', if required.
16877 (when (< (nth 2 org-defdecode) org-extend-today-until)
16878 (setf (nth 2 org-defdecode) -1)
16879 (setf (nth 1 org-defdecode) 59)
16880 (setq org-def (apply #'encode-time org-defdecode))
16881 (setq org-defdecode (decode-time org-def)))
16882 (let* ((timestr (format-time-string
16883 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16884 org-def))
16885 (prompt (concat (if prompt (concat prompt " ") "")
16886 (format "Date+time [%s]: " timestr))))
16887 (cond
16888 (from-string (setq ans from-string))
16889 (org-read-date-popup-calendar
16890 (save-excursion
16891 (save-window-excursion
16892 (calendar)
16893 (when (eq calendar-setup 'calendar-only)
16894 (setq cal-frame
16895 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16896 (select-frame cal-frame))
16897 (org-eval-in-calendar '(setq cursor-type nil) t)
16898 (unwind-protect
16899 (progn
16900 (calendar-forward-day (- (time-to-days org-def)
16901 (calendar-absolute-from-gregorian
16902 (calendar-current-date))))
16903 (org-eval-in-calendar nil t)
16904 (let* ((old-map (current-local-map))
16905 (map (copy-keymap calendar-mode-map))
16906 (minibuffer-local-map
16907 (copy-keymap org-read-date-minibuffer-local-map)))
16908 (org-defkey map (kbd "RET") 'org-calendar-select)
16909 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16910 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16911 (unwind-protect
16912 (progn
16913 (use-local-map map)
16914 (setq org-read-date-inactive inactive)
16915 (add-hook 'post-command-hook 'org-read-date-display)
16916 (setq org-ans0
16917 (read-string prompt
16918 default-input
16919 'org-read-date-history
16920 nil))
16921 ;; org-ans0: from prompt
16922 ;; org-ans1: from mouse click
16923 ;; org-ans2: from calendar motion
16924 (setq ans
16925 (concat org-ans0 " " (or org-ans1 org-ans2))))
16926 (remove-hook 'post-command-hook 'org-read-date-display)
16927 (use-local-map old-map)
16928 (when org-read-date-overlay
16929 (delete-overlay org-read-date-overlay)
16930 (setq org-read-date-overlay nil)))))
16931 (bury-buffer "*Calendar*")
16932 (when cal-frame
16933 (delete-frame cal-frame)
16934 (select-frame-set-input-focus cur-frame))))))
16936 (t ; Naked prompt only
16937 (unwind-protect
16938 (setq ans (read-string prompt default-input
16939 'org-read-date-history timestr))
16940 (when org-read-date-overlay
16941 (delete-overlay org-read-date-overlay)
16942 (setq org-read-date-overlay nil))))))
16944 (setq final (org-read-date-analyze ans org-def org-defdecode))
16946 (when org-read-date-analyze-forced-year
16947 (message "Year was forced into %s"
16948 (if org-read-date-force-compatible-dates
16949 "compatible range (1970-2037)"
16950 "range representable on this machine"))
16951 (ding))
16953 ;; One round trip to get rid of 34th of August and stuff like that....
16954 (setq final (decode-time (apply 'encode-time final)))
16956 (setq org-read-date-final-answer ans)
16958 (if to-time
16959 (apply 'encode-time final)
16960 (if (and (boundp 'org-time-was-given) org-time-was-given)
16961 (format "%04d-%02d-%02d %02d:%02d"
16962 (nth 5 final) (nth 4 final) (nth 3 final)
16963 (nth 2 final) (nth 1 final))
16964 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16966 (defun org-read-date-display ()
16967 "Display the current date prompt interpretation in the minibuffer."
16968 (when org-read-date-display-live
16969 (when org-read-date-overlay
16970 (delete-overlay org-read-date-overlay))
16971 (when (minibufferp (current-buffer))
16972 (save-excursion
16973 (end-of-line 1)
16974 (while (not (equal (buffer-substring
16975 (max (point-min) (- (point) 4)) (point))
16976 " "))
16977 (insert " ")))
16978 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16979 " " (or org-ans1 org-ans2)))
16980 (org-end-time-was-given nil)
16981 (f (org-read-date-analyze ans org-def org-defdecode))
16982 (fmts (if org-dcst
16983 org-time-stamp-custom-formats
16984 org-time-stamp-formats))
16985 (fmt (if (or org-with-time
16986 (and (boundp 'org-time-was-given) org-time-was-given))
16987 (cdr fmts)
16988 (car fmts)))
16989 (txt (format-time-string fmt (apply 'encode-time f)))
16990 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16991 (txt (concat "=> " txt)))
16992 (when (and org-end-time-was-given
16993 (string-match org-plain-time-of-day-regexp txt))
16994 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16995 org-end-time-was-given
16996 (substring txt (match-end 0)))))
16997 (when org-read-date-analyze-futurep
16998 (setq txt (concat txt " (=>F)")))
16999 (setq org-read-date-overlay
17000 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17001 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17003 (defun org-read-date-analyze (ans def defdecode)
17004 "Analyze the combined answer of the date prompt."
17005 ;; FIXME: cleanup and comment
17006 ;; Pass `current-time' result to `decode-time' (instead of calling
17007 ;; without arguments) so that only `current-time' has to be
17008 ;; overriden in tests.
17009 (let ((org-def def)
17010 (org-defdecode defdecode)
17011 (nowdecode (decode-time (current-time)))
17012 delta deltan deltaw deltadef year month day
17013 hour minute second wday pm h2 m2 tl wday1
17014 iso-year iso-weekday iso-week iso-date futurep kill-year)
17015 (setq org-read-date-analyze-futurep nil
17016 org-read-date-analyze-forced-year nil)
17017 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17018 (setq ans "+0"))
17020 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17021 (setq ans (replace-match "" t t ans)
17022 deltan (car delta)
17023 deltaw (nth 1 delta)
17024 deltadef (nth 2 delta)))
17026 ;; Check if there is an iso week date in there. If yes, store the
17027 ;; info and postpone interpreting it until the rest of the parsing
17028 ;; is done.
17029 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17030 (setq iso-year (when (match-end 1)
17031 (org-small-year-to-year
17032 (string-to-number (match-string 1 ans))))
17033 iso-weekday (when (match-end 3)
17034 (string-to-number (match-string 3 ans)))
17035 iso-week (string-to-number (match-string 2 ans)))
17036 (setq ans (replace-match "" t t ans)))
17038 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17039 (when (string-match
17040 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17041 (setq year (if (match-end 2)
17042 (string-to-number (match-string 2 ans))
17043 (progn (setq kill-year t)
17044 (string-to-number (format-time-string "%Y"))))
17045 month (string-to-number (match-string 3 ans))
17046 day (string-to-number (match-string 4 ans)))
17047 (setq year (org-small-year-to-year year))
17048 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17049 t nil ans)))
17051 ;; Help matching dotted european dates
17052 (when (string-match
17053 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17054 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17055 (setq kill-year t)
17056 (string-to-number (format-time-string "%Y")))
17057 day (string-to-number (match-string 1 ans))
17058 month (string-to-number (match-string 2 ans))
17059 ans (replace-match (format "%04d-%02d-%02d" year month day)
17060 t nil ans)))
17062 ;; Help matching american dates, like 5/30 or 5/30/7
17063 (when (string-match
17064 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17065 (setq year (if (match-end 4)
17066 (string-to-number (match-string 4 ans))
17067 (progn (setq kill-year t)
17068 (string-to-number (format-time-string "%Y"))))
17069 month (string-to-number (match-string 1 ans))
17070 day (string-to-number (match-string 2 ans)))
17071 (setq year (org-small-year-to-year year))
17072 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17073 t nil ans)))
17074 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17075 ;; If there is a time with am/pm, and *no* time without it, we convert
17076 ;; so that matching will be successful.
17077 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17078 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17079 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17080 (setq hour (string-to-number (match-string 1 ans))
17081 minute (if (match-end 3)
17082 (string-to-number (match-string 3 ans))
17084 pm (equal ?p
17085 (string-to-char (downcase (match-string 4 ans)))))
17086 (if (and (= hour 12) (not pm))
17087 (setq hour 0)
17088 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17089 (setq ans (replace-match (format "%02d:%02d" hour minute)
17090 t t ans))))
17092 ;; Check if a time range is given as a duration
17093 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17094 (setq hour (string-to-number (match-string 1 ans))
17095 h2 (+ hour (string-to-number (match-string 3 ans)))
17096 minute (string-to-number (match-string 2 ans))
17097 m2 (+ minute (if (match-end 5) (string-to-number
17098 (match-string 5 ans))0)))
17099 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17100 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17101 t t ans)))
17103 ;; Check if there is a time range
17104 (when (boundp 'org-end-time-was-given)
17105 (setq org-time-was-given nil)
17106 (when (and (string-match org-plain-time-of-day-regexp ans)
17107 (match-end 8))
17108 (setq org-end-time-was-given (match-string 8 ans))
17109 (setq ans (concat (substring ans 0 (match-beginning 7))
17110 (substring ans (match-end 7))))))
17112 (setq tl (parse-time-string ans)
17113 day (or (nth 3 tl) (nth 3 org-defdecode))
17114 month
17115 (cond ((nth 4 tl))
17116 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17117 ;; Day was specified. Make sure DAY+MONTH
17118 ;; combination happens in the future.
17119 ((nth 3 tl)
17120 (setq futurep t)
17121 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17122 (nth 4 nowdecode)))
17123 (t (nth 4 org-defdecode)))
17124 year
17125 (cond ((and (not kill-year) (nth 5 tl)))
17126 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17127 ;; Month was guessed in the future and is at least
17128 ;; equal to NOWDECODE's. Fix year accordingly.
17129 (futurep
17130 (if (or (> month (nth 4 nowdecode))
17131 (>= day (nth 3 nowdecode)))
17132 (nth 5 nowdecode)
17133 (1+ (nth 5 nowdecode))))
17134 ;; Month was specified. Make sure MONTH+YEAR
17135 ;; combination happens in the future.
17136 ((nth 4 tl)
17137 (setq futurep t)
17138 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17139 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17140 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17141 (t (nth 5 nowdecode))))
17142 (t (nth 5 org-defdecode)))
17143 hour (or (nth 2 tl) (nth 2 org-defdecode))
17144 minute (or (nth 1 tl) (nth 1 org-defdecode))
17145 second (or (nth 0 tl) 0)
17146 wday (nth 6 tl))
17148 (when (and (eq org-read-date-prefer-future 'time)
17149 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17150 (equal day (nth 3 nowdecode))
17151 (equal month (nth 4 nowdecode))
17152 (equal year (nth 5 nowdecode))
17153 (nth 2 tl)
17154 (or (< (nth 2 tl) (nth 2 nowdecode))
17155 (and (= (nth 2 tl) (nth 2 nowdecode))
17156 (nth 1 tl)
17157 (< (nth 1 tl) (nth 1 nowdecode)))))
17158 (setq day (1+ day)
17159 futurep t))
17161 ;; Special date definitions below
17162 (cond
17163 (iso-week
17164 ;; There was an iso week
17165 (require 'cal-iso)
17166 (setq futurep nil)
17167 (setq year (or iso-year year)
17168 day (or iso-weekday wday 1)
17169 wday nil ; to make sure that the trigger below does not match
17170 iso-date (calendar-gregorian-from-absolute
17171 (calendar-iso-to-absolute
17172 (list iso-week day year))))
17173 ; FIXME: Should we also push ISO weeks into the future?
17174 ; (when (and org-read-date-prefer-future
17175 ; (not iso-year)
17176 ; (< (calendar-absolute-from-gregorian iso-date)
17177 ; (time-to-days (current-time))))
17178 ; (setq year (1+ year)
17179 ; iso-date (calendar-gregorian-from-absolute
17180 ; (calendar-iso-to-absolute
17181 ; (list iso-week day year)))))
17182 (setq month (car iso-date)
17183 year (nth 2 iso-date)
17184 day (nth 1 iso-date)))
17185 (deltan
17186 (setq futurep nil)
17187 (unless deltadef
17188 ;; Pass `current-time' result to `decode-time' (instead of
17189 ;; calling without arguments) so that only `current-time' has
17190 ;; to be overriden in tests.
17191 (let ((now (decode-time (current-time))))
17192 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17193 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17194 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17195 ((equal deltaw "m") (setq month (+ month deltan)))
17196 ((equal deltaw "y") (setq year (+ year deltan)))))
17197 ((and wday (not (nth 3 tl)))
17198 ;; Weekday was given, but no day, so pick that day in the week
17199 ;; on or after the derived date.
17200 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17201 (unless (equal wday wday1)
17202 (setq day (+ day (% (- wday wday1 -7) 7))))))
17203 (when (and (boundp 'org-time-was-given)
17204 (nth 2 tl))
17205 (setq org-time-was-given t))
17206 (when (< year 100) (setq year (+ 2000 year)))
17207 ;; Check of the date is representable
17208 (if org-read-date-force-compatible-dates
17209 (progn
17210 (when (< year 1970)
17211 (setq year 1970 org-read-date-analyze-forced-year t))
17212 (when (> year 2037)
17213 (setq year 2037 org-read-date-analyze-forced-year t)))
17214 (condition-case nil
17215 (ignore (encode-time second minute hour day month year))
17216 (error
17217 (setq year (nth 5 org-defdecode))
17218 (setq org-read-date-analyze-forced-year t))))
17219 (setq org-read-date-analyze-futurep futurep)
17220 (list second minute hour day month year)))
17222 (defvar parse-time-weekdays)
17223 (defun org-read-date-get-relative (s today default)
17224 "Check string S for special relative date string.
17225 TODAY and DEFAULT are internal times, for today and for a default.
17226 Return shift list (N what def-flag)
17227 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17228 N is the number of WHATs to shift.
17229 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17230 the DEFAULT date rather than TODAY."
17231 (require 'parse-time)
17232 (when (and
17233 (string-match
17234 (concat
17235 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17236 "\\([0-9]+\\)?"
17237 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17238 "\\([ \t]\\|$\\)") s)
17239 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17240 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17241 (string-to-char (substring (match-string 1 s) -1))
17242 ?+))
17243 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17244 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17245 (what (if (match-end 3) (match-string 3 s) "d"))
17246 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17247 (date (if rel default today))
17248 (wday (nth 6 (decode-time date)))
17249 delta)
17250 (if wday1
17251 (progn
17252 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17253 (when (= delta 0) (setq delta 7))
17254 (when (= dir ?-)
17255 (setq delta (- delta 7))
17256 (when (= delta 0) (setq delta -7)))
17257 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17258 (list delta "d" rel))
17259 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17261 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17262 "Turn a user-specified date into the internal representation.
17263 The internal representation needed by the calendar is (month day year).
17264 This is a wrapper to handle the brain-dead convention in calendar that
17265 user function argument order change dependent on argument order."
17266 (pcase calendar-date-style
17267 (`american (list arg1 arg2 arg3))
17268 (`european (list arg2 arg1 arg3))
17269 (`iso (list arg2 arg3 arg1))))
17271 (defun org-eval-in-calendar (form &optional keepdate)
17272 "Eval FORM in the calendar window and return to current window.
17273 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17274 (let ((sf (selected-frame))
17275 (sw (selected-window)))
17276 (select-window (get-buffer-window "*Calendar*" t))
17277 (eval form)
17278 (when (and (not keepdate) (calendar-cursor-to-date))
17279 (let* ((date (calendar-cursor-to-date))
17280 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17281 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17282 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17283 (select-window sw)
17284 (select-frame-set-input-focus sf)))
17286 (defun org-calendar-select ()
17287 "Return to `org-read-date' with the date currently selected.
17288 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17289 (interactive)
17290 (when (calendar-cursor-to-date)
17291 (let* ((date (calendar-cursor-to-date))
17292 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17293 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17294 (when (active-minibuffer-window) (exit-minibuffer))))
17296 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17297 "Insert a date stamp for the date given by the internal TIME.
17298 See `format-time-string' for the format of TIME.
17299 WITH-HM means use the stamp format that includes the time of the day.
17300 INACTIVE means use square brackets instead of angular ones, so that the
17301 stamp will not contribute to the agenda.
17302 PRE and POST are optional strings to be inserted before and after the
17303 stamp.
17304 The command returns the inserted time stamp."
17305 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17306 stamp)
17307 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17308 (insert-before-markers (or pre ""))
17309 (when (listp extra)
17310 (setq extra (car extra))
17311 (if (and (stringp extra)
17312 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17313 (setq extra (format "-%02d:%02d"
17314 (string-to-number (match-string 1 extra))
17315 (string-to-number (match-string 2 extra))))
17316 (setq extra nil)))
17317 (when extra
17318 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17319 (insert-before-markers (setq stamp (format-time-string fmt time)))
17320 (insert-before-markers (or post ""))
17321 (setq org-last-inserted-timestamp stamp)))
17323 (defun org-toggle-time-stamp-overlays ()
17324 "Toggle the use of custom time stamp formats."
17325 (interactive)
17326 (setq org-display-custom-times (not org-display-custom-times))
17327 (unless org-display-custom-times
17328 (let ((p (point-min)) (bmp (buffer-modified-p)))
17329 (while (setq p (next-single-property-change p 'display))
17330 (when (and (get-text-property p 'display)
17331 (eq (get-text-property p 'face) 'org-date))
17332 (remove-text-properties
17333 p (setq p (next-single-property-change p 'display))
17334 '(display t))))
17335 (set-buffer-modified-p bmp)))
17336 (org-restart-font-lock)
17337 (setq org-table-may-need-update t)
17338 (if org-display-custom-times
17339 (message "Time stamps are overlaid with custom format")
17340 (message "Time stamp overlays removed")))
17342 (defun org-display-custom-time (beg end)
17343 "Overlay modified time stamp format over timestamp between BEG and END."
17344 (let* ((ts (buffer-substring beg end))
17345 t1 w1 with-hm tf time str w2 (off 0))
17346 (save-match-data
17347 (setq t1 (org-parse-time-string ts t))
17348 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17349 (setq off (- (match-end 0) (match-beginning 0)))))
17350 (setq end (- end off))
17351 (setq w1 (- end beg)
17352 with-hm (and (nth 1 t1) (nth 2 t1))
17353 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17354 time (org-fix-decoded-time t1)
17355 str (org-add-props
17356 (format-time-string
17357 (substring tf 1 -1) (apply 'encode-time time))
17358 nil 'mouse-face 'highlight)
17359 w2 (length str))
17360 (unless (= w2 w1)
17361 (add-text-properties (1+ beg) (+ 2 beg)
17362 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17363 (put-text-property beg end 'display str)))
17365 (defun org-fix-decoded-time (time)
17366 "Set 0 instead of nil for the first 6 elements of time.
17367 Don't touch the rest."
17368 (let ((n 0))
17369 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17371 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17372 "Difference between TIMESTAMP-STRING and now in days.
17373 If SECONDS is non-nil, return the difference in seconds."
17374 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17375 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17376 (funcall fdiff (current-time)))))
17378 (defun org-deadline-close-p (timestamp-string &optional ndays)
17379 "Is the time in TIMESTAMP-STRING close to the current date?"
17380 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17381 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17382 (not (org-entry-is-done-p))))
17384 (defun org-get-wdays (ts &optional delay zero-delay)
17385 "Get the deadline lead time appropriate for timestring TS.
17386 When DELAY is non-nil, get the delay time for scheduled items
17387 instead of the deadline lead time. When ZERO-DELAY is non-nil
17388 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17389 don't try to find the delay cookie in the scheduled timestamp."
17390 (let ((tv (if delay org-scheduled-delay-days
17391 org-deadline-warning-days)))
17392 (cond
17393 ((or (and delay (< tv 0))
17394 (and delay zero-delay (<= tv 0))
17395 (and (not delay) (<= tv 0)))
17396 ;; Enforce this value no matter what
17397 (- tv))
17398 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17399 ;; lead time is specified.
17400 (floor (* (string-to-number (match-string 1 ts))
17401 (cdr (assoc (match-string 2 ts)
17402 '(("d" . 1) ("w" . 7)
17403 ("m" . 30.4) ("y" . 365.25)
17404 ("h" . 0.041667)))))))
17405 ;; go for the default.
17406 (t tv))))
17408 (defun org-calendar-select-mouse (ev)
17409 "Return to `org-read-date' with the date currently selected.
17410 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17411 (interactive "e")
17412 (mouse-set-point ev)
17413 (when (calendar-cursor-to-date)
17414 (let* ((date (calendar-cursor-to-date))
17415 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17416 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17417 (when (active-minibuffer-window) (exit-minibuffer))))
17419 (defun org-check-deadlines (ndays)
17420 "Check if there are any deadlines due or past due.
17421 A deadline is considered due if it happens within `org-deadline-warning-days'
17422 days from today's date. If the deadline appears in an entry marked DONE,
17423 it is not shown. A numeric prefix argument NDAYS can be used to test that
17424 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17425 are shown."
17426 (interactive "P")
17427 (let* ((org-warn-days
17428 (cond
17429 ((equal ndays '(4)) 100000)
17430 (ndays (prefix-numeric-value ndays))
17431 (t (abs org-deadline-warning-days))))
17432 (case-fold-search nil)
17433 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17434 (callback
17435 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17436 (message "%d deadlines past-due or due within %d days"
17437 (org-occur regexp nil callback)
17438 org-warn-days)))
17440 (defsubst org-re-timestamp (type)
17441 "Return a regexp for timestamp TYPE.
17442 Allowed values for TYPE are:
17444 all: all timestamps
17445 active: only active timestamps (<...>)
17446 inactive: only inactive timestamps ([...])
17447 scheduled: only scheduled timestamps
17448 deadline: only deadline timestamps
17449 closed: only closed time-stamps
17451 When TYPE is nil, fall back on returning a regexp that matches
17452 both scheduled and deadline timestamps."
17453 (cl-case type
17454 (all org-ts-regexp-both)
17455 (active org-ts-regexp)
17456 (inactive org-ts-regexp-inactive)
17457 (scheduled org-scheduled-time-regexp)
17458 (deadline org-deadline-time-regexp)
17459 (closed org-closed-time-regexp)
17460 (otherwise
17461 (concat "\\<"
17462 (regexp-opt (list org-deadline-string org-scheduled-string))
17463 " *<\\([^>]+\\)>"))))
17465 (defun org-check-before-date (d)
17466 "Check if there are deadlines or scheduled entries before date D."
17467 (interactive (list (org-read-date)))
17468 (let* ((case-fold-search nil)
17469 (regexp (org-re-timestamp org-ts-type))
17470 (ts-type org-ts-type)
17471 (callback
17472 (lambda ()
17473 (let ((match (match-string 1)))
17474 (and (if (memq ts-type '(active inactive all))
17475 (eq (org-element-type (save-excursion
17476 (backward-char)
17477 (org-element-context)))
17478 'timestamp)
17479 (org-at-planning-p))
17480 (time-less-p
17481 (org-time-string-to-time match)
17482 (org-time-string-to-time d)))))))
17483 (message "%d entries before %s"
17484 (org-occur regexp nil callback)
17485 d)))
17487 (defun org-check-after-date (d)
17488 "Check if there are deadlines or scheduled entries after date D."
17489 (interactive (list (org-read-date)))
17490 (let* ((case-fold-search nil)
17491 (regexp (org-re-timestamp org-ts-type))
17492 (ts-type org-ts-type)
17493 (callback
17494 (lambda ()
17495 (let ((match (match-string 1)))
17496 (and (if (memq ts-type '(active inactive all))
17497 (eq (org-element-type (save-excursion
17498 (backward-char)
17499 (org-element-context)))
17500 'timestamp)
17501 (org-at-planning-p))
17502 (not (time-less-p
17503 (org-time-string-to-time match)
17504 (org-time-string-to-time d))))))))
17505 (message "%d entries after %s"
17506 (org-occur regexp nil callback)
17507 d)))
17509 (defun org-check-dates-range (start-date end-date)
17510 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17511 (interactive (list (org-read-date nil nil nil "Range starts")
17512 (org-read-date nil nil nil "Range end")))
17513 (let ((case-fold-search nil)
17514 (regexp (org-re-timestamp org-ts-type))
17515 (callback
17516 (let ((type org-ts-type))
17517 (lambda ()
17518 (let ((match (match-string 1)))
17519 (and
17520 (if (memq type '(active inactive all))
17521 (eq (org-element-type (save-excursion
17522 (backward-char)
17523 (org-element-context)))
17524 'timestamp)
17525 (org-at-planning-p))
17526 (not (time-less-p
17527 (org-time-string-to-time match)
17528 (org-time-string-to-time start-date)))
17529 (time-less-p
17530 (org-time-string-to-time match)
17531 (org-time-string-to-time end-date))))))))
17532 (message "%d entries between %s and %s"
17533 (org-occur regexp nil callback) start-date end-date)))
17535 (defun org-evaluate-time-range (&optional to-buffer)
17536 "Evaluate a time range by computing the difference between start and end.
17537 Normally the result is just printed in the echo area, but with prefix arg
17538 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17539 If the time range is actually in a table, the result is inserted into the
17540 next column.
17541 For time difference computation, a year is assumed to be exactly 365
17542 days in order to avoid rounding problems."
17543 (interactive "P")
17545 (org-clock-update-time-maybe)
17546 (save-excursion
17547 (unless (org-at-date-range-p t)
17548 (goto-char (point-at-bol))
17549 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17550 (unless (org-at-date-range-p t)
17551 (user-error "Not at a time-stamp range, and none found in current line")))
17552 (let* ((ts1 (match-string 1))
17553 (ts2 (match-string 2))
17554 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17555 (match-end (match-end 0))
17556 (time1 (org-time-string-to-time ts1))
17557 (time2 (org-time-string-to-time ts2))
17558 (t1 (float-time time1))
17559 (t2 (float-time time2))
17560 (diff (abs (- t2 t1)))
17561 (negative (< (- t2 t1) 0))
17562 ;; (ys (floor (* 365 24 60 60)))
17563 (ds (* 24 60 60))
17564 (hs (* 60 60))
17565 (fy "%dy %dd %02d:%02d")
17566 (fy1 "%dy %dd")
17567 (fd "%dd %02d:%02d")
17568 (fd1 "%dd")
17569 (fh "%02d:%02d")
17570 y d h m align)
17571 (if havetime
17572 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17574 d (floor (/ diff ds)) diff (mod diff ds)
17575 h (floor (/ diff hs)) diff (mod diff hs)
17576 m (floor (/ diff 60)))
17577 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17579 d (floor (+ (/ diff ds) 0.5))
17580 h 0 m 0))
17581 (if (not to-buffer)
17582 (message "%s" (org-make-tdiff-string y d h m))
17583 (if (org-at-table-p)
17584 (progn
17585 (goto-char match-end)
17586 (setq align t)
17587 (and (looking-at " *|") (goto-char (match-end 0))))
17588 (goto-char match-end))
17589 (when (looking-at
17590 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17591 (replace-match ""))
17592 (when negative (insert " -"))
17593 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17594 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17595 (insert " " (format fh h m))))
17596 (when align (org-table-align))
17597 (message "Time difference inserted")))))
17599 (defun org-make-tdiff-string (y d h m)
17600 (let ((fmt "")
17601 (l nil))
17602 (when (> y 0)
17603 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17604 (push y l))
17605 (when (> d 0)
17606 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17607 (push d l))
17608 (when (> h 0)
17609 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17610 (push h l))
17611 (when (> m 0)
17612 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17613 (push m l))
17614 (apply 'format fmt (nreverse l))))
17616 (defun org-time-string-to-time (s &optional buffer pos)
17617 "Convert a timestamp string into internal time."
17618 (condition-case errdata
17619 (apply 'encode-time (org-parse-time-string s))
17620 (error (error "Bad timestamp `%s'%s\nError was: %s"
17621 s (if (not (and buffer pos))
17623 (format-message " at %d in buffer `%s'" pos buffer))
17624 (cdr errdata)))))
17626 (defun org-time-string-to-seconds (s)
17627 "Convert a timestamp string to a number of seconds."
17628 (float-time (org-time-string-to-time s)))
17630 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17632 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17633 "Convert time stamp S to an absolute day number.
17635 If DAYNR in non-nil, and there is a specifier for a cyclic time
17636 stamp, get the closest date to DAYNR. If PREFER is
17637 `past' (respectively `future') return a date past (respectively
17638 after) or equal to DAYNR.
17640 POS is the location of time stamp S, as a buffer position in
17641 BUFFER.
17643 Diary sexp timestamps are matched against DAYNR, when non-nil.
17644 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17645 signalled."
17646 (cond
17647 ((string-match "\\`%%\\((.*)\\)" s)
17648 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17649 ;; only able to match individual dates. If it fails, raise an
17650 ;; error.
17651 (if (and daynr
17652 (org-diary-sexp-entry
17653 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17654 daynr
17655 (signal 'org-diary-sexp-no-match (list s))))
17656 (daynr (org-closest-date s daynr prefer))
17657 (t (time-to-days
17658 (condition-case errdata
17659 (apply #'encode-time (org-parse-time-string s))
17660 (error (error "Bad timestamp `%s'%s\nError was: %s"
17662 (if (not (and buffer pos)) ""
17663 (format-message " at %d in buffer `%s'" pos buffer))
17664 (cdr errdata))))))))
17666 (defun org-days-to-iso-week (days)
17667 "Return the iso week number."
17668 (require 'cal-iso)
17669 (car (calendar-iso-from-absolute days)))
17671 (defun org-small-year-to-year (year)
17672 "Convert 2-digit years into 4-digit years.
17673 YEAR is expanded into one of the 30 next years, if possible, or
17674 into a past one. Any year larger than 99 is returned unchanged."
17675 (if (>= year 100) year
17676 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17677 (century (/ current 100))
17678 (offset (- year (% current 100))))
17679 (cond ((> offset 30) (+ (* (1- century) 100) year))
17680 ((> offset -70) (+ (* century 100) year))
17681 (t (+ (* (1+ century) 100) year))))))
17683 (defun org-time-from-absolute (d)
17684 "Return the time corresponding to date D.
17685 D may be an absolute day number, or a calendar-type list (month day year)."
17686 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17687 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17689 (defvar org-agenda-current-date)
17690 (defun org-calendar-holiday ()
17691 "List of holidays, for Diary display in Org mode."
17692 (require 'holidays)
17693 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17694 (and hl (mapconcat #'identity hl "; "))))
17696 (defun org-diary-sexp-entry (sexp entry d)
17697 "Process a SEXP diary ENTRY for date D."
17698 (require 'diary-lib)
17699 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17700 ;; dynamically.
17701 (let* ((sexp `(let ((entry ,entry)
17702 (date ',d))
17703 ,(car (read-from-string sexp))))
17704 (result (if calendar-debug-sexp (eval sexp)
17705 (condition-case nil
17706 (eval sexp)
17707 (error
17708 (beep)
17709 (message "Bad sexp at line %d in %s: %s"
17710 (org-current-line)
17711 (buffer-file-name) sexp)
17712 (sleep-for 2))))))
17713 (cond ((stringp result) (split-string result "; "))
17714 ((and (consp result)
17715 (not (consp (cdr result)))
17716 (stringp (cdr result))) (cdr result))
17717 ((and (consp result)
17718 (stringp (car result))) result)
17719 (result entry))))
17721 (defun org-diary-to-ical-string (frombuf)
17722 "Get iCalendar entries from diary entries in buffer FROMBUF.
17723 This uses the icalendar.el library."
17724 (let* ((tmpdir temporary-file-directory)
17725 (tmpfile (make-temp-name
17726 (expand-file-name "orgics" tmpdir)))
17727 buf rtn b e)
17728 (with-current-buffer frombuf
17729 (icalendar-export-region (point-min) (point-max) tmpfile)
17730 (setq buf (find-buffer-visiting tmpfile))
17731 (set-buffer buf)
17732 (goto-char (point-min))
17733 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17734 (setq b (match-beginning 0)))
17735 (goto-char (point-max))
17736 (when (re-search-backward "^END:VEVENT" nil t)
17737 (setq e (match-end 0)))
17738 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17739 (kill-buffer buf)
17740 (delete-file tmpfile)
17741 rtn))
17743 (defun org-closest-date (start current prefer)
17744 "Return closest date to CURRENT starting from START.
17746 CURRENT and START are both time stamps.
17748 When PREFER is `past', return a date that is either CURRENT or
17749 past. When PREFER is `future', return a date that is either
17750 CURRENT or future.
17752 Only time stamps with a repeater are modified. Any other time
17753 stamp stay unchanged. In any case, return value is an absolute
17754 day number."
17755 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17756 ;; No repeater. Do not shift time stamp.
17757 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17758 (let ((value (string-to-number (match-string 1 start)))
17759 (type (match-string 2 start)))
17760 (if (= 0 value)
17761 ;; Repeater with a 0-value is considered as void.
17762 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17763 (let* ((base (org-date-to-gregorian start))
17764 (target (org-date-to-gregorian current))
17765 (sday (calendar-absolute-from-gregorian base))
17766 (cday (calendar-absolute-from-gregorian target))
17767 n1 n2)
17768 ;; If START is already past CURRENT, just return START.
17769 (if (<= cday sday) sday
17770 ;; Compute closest date before (N1) and closest date past
17771 ;; (N2) CURRENT.
17772 (pcase type
17773 ("h"
17774 (let ((missing-hours
17775 (mod (+ (- (* 24 (- cday sday))
17776 (nth 2 (org-parse-time-string start)))
17777 org-extend-today-until)
17778 value)))
17779 (setf n1 (if (= missing-hours 0) cday
17780 (- cday (1+ (/ missing-hours 24)))))
17781 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17782 ((or "d" "w")
17783 (let ((value (if (equal type "w") (* 7 value) value)))
17784 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17785 (setf n2 (+ n1 value))))
17786 ("m"
17787 (let* ((add-months
17788 (lambda (d n)
17789 ;; Add N months to gregorian date D, i.e.,
17790 ;; a list (MONTH DAY YEAR). Return a valid
17791 ;; gregorian date.
17792 (let ((m (+ (nth 0 d) n)))
17793 (list (mod m 12)
17794 (nth 1 d)
17795 (+ (/ m 12) (nth 2 d))))))
17796 (months ; Complete months to TARGET.
17797 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17798 (- (nth 0 target) (nth 0 base))
17799 ;; If START's day is greater than
17800 ;; TARGET's, remove incomplete month.
17801 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17802 value)
17803 value))
17804 (before (funcall add-months base months)))
17805 (setf n1 (calendar-absolute-from-gregorian before))
17806 (setf n2
17807 (calendar-absolute-from-gregorian
17808 (funcall add-months before value)))))
17810 (let* ((d (nth 1 base))
17811 (m (nth 0 base))
17812 (y (nth 2 base))
17813 (years ; Complete years to TARGET.
17814 (* (/ (- (nth 2 target)
17816 ;; If START's month and day are
17817 ;; greater than TARGET's, remove
17818 ;; incomplete year.
17819 (if (or (> (nth 0 target) m)
17820 (and (= (nth 0 target) m)
17821 (> (nth 1 target) d)))
17824 value)
17825 value))
17826 (before (list m d (+ y years))))
17827 (setf n1 (calendar-absolute-from-gregorian before))
17828 (setf n2 (calendar-absolute-from-gregorian
17829 (list m d (+ (nth 2 before) value)))))))
17830 ;; Handle PREFER parameter, if any.
17831 (cond
17832 ((eq prefer 'past) (if (= cday n2) n2 n1))
17833 ((eq prefer 'future) (if (= cday n1) n1 n2))
17834 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17836 (defun org-date-to-gregorian (d)
17837 "Turn any specification of date D into a Gregorian date for the calendar."
17838 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17839 ((and (listp d) (= (length d) 3)) d)
17840 ((stringp d)
17841 (let ((d (org-parse-time-string d)))
17842 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17843 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17845 (defun org-parse-time-string (s &optional nodefault)
17846 "Parse the standard Org time string.
17847 This should be a lot faster than the normal `parse-time-string'.
17848 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17849 hour and minute fields will be nil if not given."
17850 (cond ((string-match org-ts-regexp0 s)
17851 (list 0
17852 (when (or (match-beginning 8) (not nodefault))
17853 (string-to-number (or (match-string 8 s) "0")))
17854 (when (or (match-beginning 7) (not nodefault))
17855 (string-to-number (or (match-string 7 s) "0")))
17856 (string-to-number (match-string 4 s))
17857 (string-to-number (match-string 3 s))
17858 (string-to-number (match-string 2 s))
17859 nil nil nil))
17860 ((string-match "^<[^>]+>$" s)
17861 (decode-time (seconds-to-time (org-matcher-time s))))
17862 (t (error "Not a standard Org time string: %s" s))))
17864 (defun org-timestamp-up (&optional arg)
17865 "Increase the date item at the cursor by one.
17866 If the cursor is on the year, change the year. If it is on the month,
17867 the day or the time, change that.
17868 With prefix ARG, change by that many units."
17869 (interactive "p")
17870 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17872 (defun org-timestamp-down (&optional arg)
17873 "Decrease the date item at the cursor by one.
17874 If the cursor is on the year, change the year. If it is on the month,
17875 the day or the time, change that.
17876 With prefix ARG, change by that many units."
17877 (interactive "p")
17878 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17880 (defun org-timestamp-up-day (&optional arg)
17881 "Increase the date in the time stamp by one day.
17882 With prefix ARG, change that many days."
17883 (interactive "p")
17884 (if (and (not (org-at-timestamp-p 'lax))
17885 (org-at-heading-p))
17886 (org-todo 'up)
17887 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17889 (defun org-timestamp-down-day (&optional arg)
17890 "Decrease the date in the time stamp by one day.
17891 With prefix ARG, change that many days."
17892 (interactive "p")
17893 (if (and (not (org-at-timestamp-p 'lax))
17894 (org-at-heading-p))
17895 (org-todo 'down)
17896 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17898 (defun org-at-timestamp-p (&optional extended)
17899 "Non-nil if point is inside a timestamp.
17901 By default, the function only consider syntactically valid active
17902 timestamps. However, the caller may have a broader definition
17903 for timestamps. As a consequence, optional argument EXTENDED can
17904 be set to the following values
17906 `inactive'
17908 Include also syntactically valid inactive timestamps.
17910 `agenda'
17912 Include timestamps allowed in Agenda, i.e., those in
17913 properties drawers, planning lines and clock lines.
17915 `lax'
17917 Ignore context. The function matches any part of the
17918 document looking like a timestamp. This includes comments,
17919 example blocks...
17921 For backward-compatibility with Org 9.0, every other non-nil
17922 value is equivalent to `inactive'.
17924 When at a timestamp, return the position of the point as a symbol
17925 among `bracket', `after', `year', `month', `hour', `minute',
17926 `day' or a number of character from the last know part of the
17927 time stamp.
17929 When matching, the match groups are the following:
17930 group 1: year
17931 group 2: month
17932 group 3: day number
17933 group 4: day name
17934 group 5: hours, if any
17935 group 6: minutes, if any"
17936 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17937 (pos (point))
17938 (match?
17939 (let ((boundaries (org-in-regexp regexp)))
17940 (save-match-data
17941 (cond ((null boundaries) nil)
17942 ((eq extended 'lax) t)
17944 (or (and (eq extended 'agenda)
17945 (or (org-at-planning-p)
17946 (org-at-property-p)
17947 (and org-agenda-include-inactive-timestamps
17948 (org-at-clock-log-p))))
17949 (eq 'timestamp
17950 (save-excursion
17951 (when (= pos (cdr boundaries)) (forward-char -1))
17952 (org-element-type (org-element-context)))))))))))
17953 (cond
17954 ((not match?) nil)
17955 ((= pos (match-beginning 0)) 'bracket)
17956 ;; Distinguish location right before the closing bracket from
17957 ;; right after it.
17958 ((= pos (1- (match-end 0))) 'bracket)
17959 ((= pos (match-end 0)) 'after)
17960 ((org-pos-in-match-range pos 2) 'year)
17961 ((org-pos-in-match-range pos 3) 'month)
17962 ((org-pos-in-match-range pos 7) 'hour)
17963 ((org-pos-in-match-range pos 8) 'minute)
17964 ((or (org-pos-in-match-range pos 4)
17965 (org-pos-in-match-range pos 5)) 'day)
17966 ((and (> pos (or (match-end 8) (match-end 5)))
17967 (< pos (match-end 0)))
17968 (- pos (or (match-end 8) (match-end 5))))
17969 (t 'day))))
17971 (defun org-toggle-timestamp-type ()
17972 "Toggle the type (<active> or [inactive]) of a time stamp."
17973 (interactive)
17974 (when (org-at-timestamp-p 'lax)
17975 (let ((beg (match-beginning 0)) (end (match-end 0))
17976 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17977 (save-excursion
17978 (goto-char beg)
17979 (while (re-search-forward "[][<>]" end t)
17980 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17981 t t)))
17982 (message "Timestamp is now %sactive"
17983 (if (equal (char-after beg) ?<) "" "in")))))
17985 (defun org-at-clock-log-p ()
17986 "Non-nil if point is on a clock log line."
17987 (and (org-match-line org-clock-line-re)
17988 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17990 (defvar org-clock-history) ; defined in org-clock.el
17991 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17992 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17993 "Change the date in the time stamp at point.
17994 The date will be changed by N times WHAT. WHAT can be `day', `month',
17995 `year', `minute', `second'. If WHAT is not given, the cursor position
17996 in the timestamp determines what will be changed.
17997 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17998 (let ((origin (point))
17999 (timestamp? (org-at-timestamp-p 'lax))
18000 origin-cat
18001 with-hm inactive
18002 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18003 extra rem
18004 ts time time0 fixnext clrgx)
18005 (unless timestamp? (user-error "Not at a timestamp"))
18006 (if (and (not what) (eq timestamp? 'bracket))
18007 (org-toggle-timestamp-type)
18008 ;; Point isn't on brackets. Remember the part of the time-stamp
18009 ;; the point was in. Indeed, size of time-stamps may change,
18010 ;; but point must be kept in the same category nonetheless.
18011 (setq origin-cat timestamp?)
18012 (when (and (not what) (not (eq timestamp? 'day))
18013 org-display-custom-times
18014 (get-text-property (point) 'display)
18015 (not (get-text-property (1- (point)) 'display)))
18016 (setq timestamp? 'day))
18017 (setq timestamp? (or what timestamp?)
18018 inactive (= (char-after (match-beginning 0)) ?\[)
18019 ts (match-string 0))
18020 (replace-match "")
18021 (when (string-match
18022 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18024 (setq extra (match-string 1 ts))
18025 (when suppress-tmp-delay
18026 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18027 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18028 (setq with-hm t))
18029 (setq time0 (org-parse-time-string ts))
18030 (when (and updown
18031 (eq timestamp? 'minute)
18032 (not current-prefix-arg))
18033 ;; This looks like s-up and s-down. Change by one rounding step.
18034 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18035 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18036 (setcar (cdr time0) (+ (nth 1 time0)
18037 (if (> n 0) (- rem) (- dm rem))))))
18038 (setq time
18039 (apply #'encode-time
18040 (or (car time0) 0)
18041 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
18042 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
18043 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
18044 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
18045 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
18046 (nthcdr 6 time0)))
18047 (when (and (memq timestamp? '(hour minute))
18048 extra
18049 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18050 (setq extra (org-modify-ts-extra
18051 extra
18052 (if (eq timestamp? 'hour) 2 5)
18053 n dm)))
18054 (when (integerp timestamp?)
18055 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
18056 (when (eq what 'calendar)
18057 (let ((cal-date (org-get-date-from-calendar)))
18058 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18059 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18060 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18061 (setcar time0 (or (car time0) 0))
18062 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18063 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18064 (setq time (apply 'encode-time time0))))
18065 ;; Insert the new time-stamp, and ensure point stays in the same
18066 ;; category as before (i.e. not after the last position in that
18067 ;; category).
18068 (let ((pos (point)))
18069 ;; Stay before inserted string. `save-excursion' is of no use.
18070 (setq org-last-changed-timestamp
18071 (org-insert-time-stamp time with-hm inactive nil nil extra))
18072 (goto-char pos))
18073 (save-match-data
18074 (looking-at org-ts-regexp3)
18075 (goto-char
18076 (pcase origin-cat
18077 ;; `day' category ends before `hour' if any, or at the end
18078 ;; of the day name.
18079 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18080 (`hour (min (match-end 7) origin))
18081 (`minute (min (1- (match-end 8)) origin))
18082 ((pred integerp) (min (1- (match-end 0)) origin))
18083 ;; Point was right after the time-stamp. However, the
18084 ;; time-stamp length might have changed, so refer to
18085 ;; (match-end 0) instead.
18086 (`after (match-end 0))
18087 ;; `year' and `month' have both fixed size: point couldn't
18088 ;; have moved into another part.
18089 (_ origin))))
18090 ;; Update clock if on a CLOCK line.
18091 (org-clock-update-time-maybe)
18092 ;; Maybe adjust the closest clock in `org-clock-history'
18093 (when org-clock-adjust-closest
18094 (if (not (and (org-at-clock-log-p)
18095 (< 1 (length (delq nil (mapcar 'marker-position
18096 org-clock-history))))))
18097 (message "No clock to adjust")
18098 (cond ((save-excursion ; fix previous clock?
18099 (re-search-backward org-ts-regexp0 nil t)
18100 (looking-back (concat org-clock-string " \\[")
18101 (line-beginning-position)))
18102 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18103 ((save-excursion ; fix next clock?
18104 (re-search-backward org-ts-regexp0 nil t)
18105 (looking-at (concat org-ts-regexp0 "\\] =>")))
18106 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18107 (save-window-excursion
18108 ;; Find closest clock to point, adjust the previous/next one in history
18109 (let* ((p (save-excursion (org-back-to-heading t)))
18110 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18111 (clfixnth
18112 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18113 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18114 (if (not clfixpos)
18115 (message "No clock to adjust")
18116 (save-excursion
18117 (org-goto-marker-or-bmk clfixpos)
18118 (org-show-subtree)
18119 (when (re-search-forward clrgx nil t)
18120 (goto-char (match-beginning 1))
18121 (let (org-clock-adjust-closest)
18122 (org-timestamp-change n timestamp? updown))
18123 (message "Clock adjusted in %s for heading: %s"
18124 (file-name-nondirectory (buffer-file-name))
18125 (org-get-heading t t)))))))))
18126 ;; Try to recenter the calendar window, if any.
18127 (when (and org-calendar-follow-timestamp-change
18128 (get-buffer-window "*Calendar*" t)
18129 (memq timestamp? '(day month year)))
18130 (org-recenter-calendar (time-to-days time))))))
18132 (defun org-modify-ts-extra (s pos n dm)
18133 "Change the different parts of the lead-time and repeat fields in timestamp."
18134 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18135 ng h m new rem)
18136 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18137 (cond
18138 ((or (org-pos-in-match-range pos 2)
18139 (org-pos-in-match-range pos 3))
18140 (setq m (string-to-number (match-string 3 s))
18141 h (string-to-number (match-string 2 s)))
18142 (if (org-pos-in-match-range pos 2)
18143 (setq h (+ h n))
18144 (setq n (* dm (with-no-warnings (signum n))))
18145 (unless (= 0 (setq rem (% m dm)))
18146 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18147 (setq m (+ m n)))
18148 (when (< m 0) (setq m (+ m 60) h (1- h)))
18149 (when (> m 59) (setq m (- m 60) h (1+ h)))
18150 (setq h (mod h 24))
18151 (setq ng 1 new (format "-%02d:%02d" h m)))
18152 ((org-pos-in-match-range pos 6)
18153 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18154 ((org-pos-in-match-range pos 5)
18155 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18157 ((org-pos-in-match-range pos 9)
18158 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18159 ((org-pos-in-match-range pos 8)
18160 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18162 (when ng
18163 (setq s (concat
18164 (substring s 0 (match-beginning ng))
18166 (substring s (match-end ng))))))
18169 (defun org-recenter-calendar (d)
18170 "If the calendar is visible, recenter it to date D."
18171 (let ((cwin (get-buffer-window "*Calendar*" t)))
18172 (when cwin
18173 (let ((calendar-move-hook nil))
18174 (with-selected-window cwin
18175 (calendar-goto-date
18176 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18178 (defun org-goto-calendar (&optional arg)
18179 "Go to the Emacs calendar at the current date.
18180 If there is a time stamp in the current line, go to that date.
18181 A prefix ARG can be used to force the current date."
18182 (interactive "P")
18183 (let ((calendar-move-hook nil)
18184 (calendar-view-holidays-initially-flag nil)
18185 (calendar-view-diary-initially-flag nil)
18186 diff)
18187 (when (or (org-at-timestamp-p 'lax)
18188 (org-match-line (concat ".*" org-ts-regexp)))
18189 (let ((d1 (time-to-days (current-time)))
18190 (d2 (time-to-days
18191 (org-time-string-to-time (match-string 1)))))
18192 (setq diff (- d2 d1))))
18193 (calendar)
18194 (calendar-goto-today)
18195 (when (and diff (not arg)) (calendar-forward-day diff))))
18197 (defun org-get-date-from-calendar ()
18198 "Return a list (month day year) of date at point in calendar."
18199 (with-current-buffer "*Calendar*"
18200 (save-match-data
18201 (calendar-cursor-to-date))))
18203 (defun org-date-from-calendar ()
18204 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18205 If there is already a time stamp at the cursor position, update it."
18206 (interactive)
18207 (if (org-at-timestamp-p 'lax)
18208 (org-timestamp-change 0 'calendar)
18209 (let ((cal-date (org-get-date-from-calendar)))
18210 (org-insert-time-stamp
18211 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18213 (defcustom org-effort-durations
18214 `(("min" . 1)
18215 ("h" . 60)
18216 ("d" . ,(* 60 8))
18217 ("w" . ,(* 60 8 5))
18218 ("m" . ,(* 60 8 5 4))
18219 ("y" . ,(* 60 8 5 40)))
18220 "Conversion factor to minutes for an effort modifier.
18222 Each entry has the form (MODIFIER . MINUTES).
18224 In an effort string, a number followed by MODIFIER is multiplied
18225 by the specified number of MINUTES to obtain an effort in
18226 minutes.
18228 For example, if the value of this variable is ((\"hours\" . 60)), then an
18229 effort string \"2hours\" is equivalent to 120 minutes."
18230 :group 'org-agenda
18231 :version "26.1"
18232 :package-version '(Org . "8.3")
18233 :type '(alist :key-type (string :tag "Modifier")
18234 :value-type (number :tag "Minutes")))
18236 (defcustom org-image-actual-width t
18237 "Should we use the actual width of images when inlining them?
18239 When set to t, always use the image width.
18241 When set to a number, use imagemagick (when available) to set
18242 the image's width to this value.
18244 When set to a number in a list, try to get the width from any
18245 #+ATTR.* keyword if it matches a width specification like
18247 #+ATTR_HTML: :width 300px
18249 and fall back on that number if none is found.
18251 When set to nil, try to get the width from an #+ATTR.* keyword
18252 and fall back on the original width if none is found.
18254 This requires Emacs >= 24.1, build with imagemagick support."
18255 :group 'org-appearance
18256 :version "24.4"
18257 :package-version '(Org . "8.0")
18258 :type '(choice
18259 (const :tag "Use the image width" t)
18260 (integer :tag "Use a number of pixels")
18261 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18262 (const :tag "Use #+ATTR* or don't resize" nil)))
18264 (defcustom org-agenda-inhibit-startup nil
18265 "Inhibit startup when preparing agenda buffers.
18266 When this variable is t, the initialization of the Org agenda
18267 buffers is inhibited: e.g. the visibility state is not set, the
18268 tables are not re-aligned, etc."
18269 :type 'boolean
18270 :version "24.3"
18271 :group 'org-agenda)
18273 (defcustom org-agenda-ignore-properties nil
18274 "Avoid updating text properties when building the agenda.
18275 Properties are used to prepare buffers for effort estimates,
18276 appointments, statistics and subtree-local categories.
18277 If you don't use these in the agenda, you can add them to this
18278 list and agenda building will be a bit faster.
18279 The value is a list, with zero or more of the symbols `effort', `appt',
18280 `stats' or `category'."
18281 :type '(set :greedy t
18282 (const effort)
18283 (const appt)
18284 (const stats)
18285 (const category))
18286 :version "26.1"
18287 :package-version '(Org . "8.3")
18288 :group 'org-agenda)
18290 ;;;; Files
18292 (defun org-save-all-org-buffers ()
18293 "Save all Org buffers without user confirmation."
18294 (interactive)
18295 (message "Saving all Org buffers...")
18296 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18297 (when (featurep 'org-id) (org-id-locations-save))
18298 (message "Saving all Org buffers... done"))
18300 (defun org-revert-all-org-buffers ()
18301 "Revert all Org buffers.
18302 Prompt for confirmation when there are unsaved changes.
18303 Be sure you know what you are doing before letting this function
18304 overwrite your changes.
18306 This function is useful in a setup where one tracks org files
18307 with a version control system, to revert on one machine after pulling
18308 changes from another. I believe the procedure must be like this:
18310 1. M-x org-save-all-org-buffers
18311 2. Pull changes from the other machine, resolve conflicts
18312 3. M-x org-revert-all-org-buffers"
18313 (interactive)
18314 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18315 (user-error "Abort"))
18316 (save-excursion
18317 (save-window-excursion
18318 (dolist (b (buffer-list))
18319 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18320 (with-current-buffer b buffer-file-name))
18321 (pop-to-buffer-same-window b)
18322 (revert-buffer t 'no-confirm)))
18323 (when (and (featurep 'org-id) org-id-track-globally)
18324 (org-id-locations-load)))))
18326 ;;;; Agenda files
18328 ;;;###autoload
18329 (defun org-switchb (&optional arg)
18330 "Switch between Org buffers.
18332 With `\\[universal-argument]' prefix, restrict available buffers to files.
18334 With `\\[universal-argument] \\[universal-argument]' \
18335 prefix, restrict available buffers to agenda files."
18336 (interactive "P")
18337 (let ((blist (org-buffer-list
18338 (cond ((equal arg '(4)) 'files)
18339 ((equal arg '(16)) 'agenda)))))
18340 (pop-to-buffer-same-window
18341 (completing-read "Org buffer: "
18342 (mapcar #'list (mapcar #'buffer-name blist))
18343 nil t))))
18345 (defun org-buffer-list (&optional predicate exclude-tmp)
18346 "Return a list of Org buffers.
18347 PREDICATE can be `export', `files' or `agenda'.
18349 export restrict the list to Export buffers.
18350 files restrict the list to buffers visiting Org files.
18351 agenda restrict the list to buffers visiting agenda files.
18353 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18354 (let* ((bfn nil)
18355 (agenda-files (and (eq predicate 'agenda)
18356 (mapcar 'file-truename (org-agenda-files t))))
18357 (filter
18358 (cond
18359 ((eq predicate 'files)
18360 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18361 ((eq predicate 'export)
18362 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18363 ((eq predicate 'agenda)
18364 (lambda (b)
18365 (with-current-buffer b
18366 (and (derived-mode-p 'org-mode)
18367 (setq bfn (buffer-file-name b))
18368 (member (file-truename bfn) agenda-files)))))
18369 (t (lambda (b) (with-current-buffer b
18370 (or (derived-mode-p 'org-mode)
18371 (string-match "\\*Org .*Export"
18372 (buffer-name b)))))))))
18373 (delq nil
18374 (mapcar
18375 (lambda(b)
18376 (if (and (funcall filter b)
18377 (or (not exclude-tmp)
18378 (not (string-match "tmp" (buffer-name b)))))
18380 nil))
18381 (buffer-list)))))
18383 (defun org-agenda-files (&optional unrestricted archives)
18384 "Get the list of agenda files.
18385 Optional UNRESTRICTED means return the full list even if a restriction
18386 is currently in place.
18387 When ARCHIVES is t, include all archive files that are really being
18388 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18389 `org-agenda-archives-mode' is t."
18390 (let ((files
18391 (cond
18392 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18393 ((stringp org-agenda-files) (org-read-agenda-file-list))
18394 ((listp org-agenda-files) org-agenda-files)
18395 (t (error "Invalid value of `org-agenda-files'")))))
18396 (setq files (apply 'append
18397 (mapcar (lambda (f)
18398 (if (file-directory-p f)
18399 (directory-files
18400 f t org-agenda-file-regexp)
18401 (list f)))
18402 files)))
18403 (when org-agenda-skip-unavailable-files
18404 (setq files (delq nil
18405 (mapcar (function
18406 (lambda (file)
18407 (and (file-readable-p file) file)))
18408 files))))
18409 (when (or (eq archives t)
18410 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18411 (setq files (org-add-archive-files files)))
18412 files))
18414 (defun org-agenda-file-p (&optional file)
18415 "Return non-nil, if FILE is an agenda file.
18416 If FILE is omitted, use the file associated with the current
18417 buffer."
18418 (let ((fname (or file (buffer-file-name))))
18419 (and fname
18420 (member (file-truename fname)
18421 (mapcar #'file-truename (org-agenda-files t))))))
18423 (defun org-edit-agenda-file-list ()
18424 "Edit the list of agenda files.
18425 Depending on setup, this either uses customize to edit the variable
18426 `org-agenda-files', or it visits the file that is holding the list. In the
18427 latter case, the buffer is set up in a way that saving it automatically kills
18428 the buffer and restores the previous window configuration."
18429 (interactive)
18430 (if (stringp org-agenda-files)
18431 (let ((cw (current-window-configuration)))
18432 (find-file org-agenda-files)
18433 (setq-local org-window-configuration cw)
18434 (add-hook 'after-save-hook
18435 (lambda ()
18436 (set-window-configuration
18437 (prog1 org-window-configuration
18438 (kill-buffer (current-buffer))))
18439 (org-install-agenda-files-menu)
18440 (message "New agenda file list installed"))
18441 nil 'local)
18442 (message "%s" (substitute-command-keys
18443 "Edit list and finish with \\[save-buffer]")))
18444 (customize-variable 'org-agenda-files)))
18446 (defun org-store-new-agenda-file-list (list)
18447 "Set new value for the agenda file list and save it correctly."
18448 (if (stringp org-agenda-files)
18449 (let ((fe (org-read-agenda-file-list t)) b u)
18450 (while (setq b (find-buffer-visiting org-agenda-files))
18451 (kill-buffer b))
18452 (with-temp-file org-agenda-files
18453 (insert
18454 (mapconcat
18455 (lambda (f) ;; Keep un-expanded entries.
18456 (if (setq u (assoc f fe))
18457 (cdr u)
18459 list "\n")
18460 "\n")))
18461 (let ((org-mode-hook nil) (org-inhibit-startup t)
18462 (org-insert-mode-line-in-empty-file nil))
18463 (setq org-agenda-files list)
18464 (customize-save-variable 'org-agenda-files org-agenda-files))))
18466 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18467 "Read the list of agenda files from a file.
18468 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18469 filenames, used by `org-store-new-agenda-file-list' to write back
18470 un-expanded file names."
18471 (when (file-directory-p org-agenda-files)
18472 (error "`org-agenda-files' cannot be a single directory"))
18473 (when (stringp org-agenda-files)
18474 (with-temp-buffer
18475 (insert-file-contents org-agenda-files)
18476 (mapcar
18477 (lambda (f)
18478 (let ((e (expand-file-name (substitute-in-file-name f)
18479 org-directory)))
18480 (if pair-with-expansion
18481 (cons e f)
18482 e)))
18483 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18485 ;;;###autoload
18486 (defun org-cycle-agenda-files ()
18487 "Cycle through the files in `org-agenda-files'.
18488 If the current buffer visits an agenda file, find the next one in the list.
18489 If the current buffer does not, find the first agenda file."
18490 (interactive)
18491 (let* ((fs (or (org-agenda-files t)
18492 (user-error "No agenda files")))
18493 (files (copy-sequence fs))
18494 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18495 file)
18496 (when tcf
18497 (while (and (setq file (pop files))
18498 (not (equal (file-truename file) tcf)))))
18499 (find-file (car (or files fs)))
18500 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18502 (defun org-agenda-file-to-front (&optional to-end)
18503 "Move/add the current file to the top of the agenda file list.
18504 If the file is not present in the list, it is added to the front. If it is
18505 present, it is moved there. With optional argument TO-END, add/move to the
18506 end of the list."
18507 (interactive "P")
18508 (let ((org-agenda-skip-unavailable-files nil)
18509 (file-alist (mapcar (lambda (x)
18510 (cons (file-truename x) x))
18511 (org-agenda-files t)))
18512 (ctf (file-truename
18513 (or buffer-file-name
18514 (user-error "Please save the current buffer to a file"))))
18515 x had)
18516 (setq x (assoc ctf file-alist) had x)
18518 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18519 (if to-end
18520 (setq file-alist (append (delq x file-alist) (list x)))
18521 (setq file-alist (cons x (delq x file-alist))))
18522 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18523 (org-install-agenda-files-menu)
18524 (message "File %s to %s of agenda file list"
18525 (if had "moved" "added") (if to-end "end" "front"))))
18527 (defun org-remove-file (&optional file)
18528 "Remove current file from the list of files in variable `org-agenda-files'.
18529 These are the files which are being checked for agenda entries.
18530 Optional argument FILE means use this file instead of the current."
18531 (interactive)
18532 (let* ((org-agenda-skip-unavailable-files nil)
18533 (file (or file buffer-file-name
18534 (user-error "Current buffer does not visit a file")))
18535 (true-file (file-truename file))
18536 (afile (abbreviate-file-name file))
18537 (files (delq nil (mapcar
18538 (lambda (x)
18539 (unless (equal true-file
18540 (file-truename x))
18542 (org-agenda-files t)))))
18543 (if (not (= (length files) (length (org-agenda-files t))))
18544 (progn
18545 (org-store-new-agenda-file-list files)
18546 (org-install-agenda-files-menu)
18547 (message "Removed from Org Agenda list: %s" afile))
18548 (message "File was not in list: %s (not removed)" afile))))
18550 (defun org-file-menu-entry (file)
18551 (vector file (list 'find-file file) t))
18553 (defun org-check-agenda-file (file)
18554 "Make sure FILE exists. If not, ask user what to do."
18555 (unless (file-exists-p file)
18556 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18557 (abbreviate-file-name file))
18558 (let ((r (downcase (read-char-exclusive))))
18559 (cond
18560 ((equal r ?r)
18561 (org-remove-file file)
18562 (throw 'nextfile t))
18563 (t (user-error "Abort"))))))
18565 (defun org-get-agenda-file-buffer (file)
18566 "Get an agenda buffer visiting FILE.
18567 If the buffer needs to be created, add it to the list of buffers
18568 which might be released later."
18569 (let ((buf (org-find-base-buffer-visiting file)))
18570 (if buf
18571 buf ; just return it
18572 ;; Make a new buffer and remember it
18573 (setq buf (find-file-noselect file))
18574 (when buf (push buf org-agenda-new-buffers))
18575 buf)))
18577 (defun org-release-buffers (blist)
18578 "Release all buffers in list, asking the user for confirmation when needed.
18579 When a buffer is unmodified, it is just killed. When modified, it is saved
18580 \(if the user agrees) and then killed."
18581 (let (file)
18582 (dolist (buf blist)
18583 (setq file (buffer-file-name buf))
18584 (when (and (buffer-modified-p buf)
18585 file
18586 (y-or-n-p (format "Save file %s? " file)))
18587 (with-current-buffer buf (save-buffer)))
18588 (kill-buffer buf))))
18590 (defun org-agenda-prepare-buffers (files)
18591 "Create buffers for all agenda files, protect archived trees and comments."
18592 (interactive)
18593 (let ((pa '(:org-archived t))
18594 (pc '(:org-comment t))
18595 (pall '(:org-archived t :org-comment t))
18596 (inhibit-read-only t)
18597 (org-inhibit-startup org-agenda-inhibit-startup)
18598 (rea (concat ":" org-archive-tag ":"))
18599 re pos)
18600 (setq org-tag-alist-for-agenda nil
18601 org-tag-groups-alist-for-agenda nil)
18602 (save-excursion
18603 (save-restriction
18604 (dolist (file files)
18605 (catch 'nextfile
18606 (if (bufferp file)
18607 (set-buffer file)
18608 (org-check-agenda-file file)
18609 (set-buffer (org-get-agenda-file-buffer file)))
18610 (widen)
18611 (org-set-regexps-and-options 'tags-only)
18612 (setq pos (point))
18613 (or (memq 'category org-agenda-ignore-properties)
18614 (org-refresh-category-properties))
18615 (or (memq 'stats org-agenda-ignore-properties)
18616 (org-refresh-stats-properties))
18617 (or (memq 'effort org-agenda-ignore-properties)
18618 (org-refresh-effort-properties))
18619 (or (memq 'appt org-agenda-ignore-properties)
18620 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18621 (setq org-todo-keywords-for-agenda
18622 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18623 (setq org-done-keywords-for-agenda
18624 (append org-done-keywords-for-agenda org-done-keywords))
18625 (setq org-todo-keyword-alist-for-agenda
18626 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18627 (setq org-tag-alist-for-agenda
18628 (org-uniquify
18629 (append org-tag-alist-for-agenda
18630 org-current-tag-alist)))
18631 ;; Merge current file's tag groups into global
18632 ;; `org-tag-groups-alist-for-agenda'.
18633 (when org-group-tags
18634 (dolist (alist org-tag-groups-alist)
18635 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18636 (if old
18637 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18638 (push alist org-tag-groups-alist-for-agenda)))))
18639 (org-with-silent-modifications
18640 (save-excursion
18641 (remove-text-properties (point-min) (point-max) pall)
18642 (when org-agenda-skip-archived-trees
18643 (goto-char (point-min))
18644 (while (re-search-forward rea nil t)
18645 (when (org-at-heading-p t)
18646 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18647 (goto-char (point-min))
18648 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18649 (while (re-search-forward re nil t)
18650 (when (save-match-data (org-in-commented-heading-p t))
18651 (add-text-properties
18652 (match-beginning 0) (org-end-of-subtree t) pc)))))
18653 (goto-char pos)))))
18654 (setq org-todo-keywords-for-agenda
18655 (org-uniquify org-todo-keywords-for-agenda))
18656 (setq org-todo-keyword-alist-for-agenda
18657 (org-uniquify org-todo-keyword-alist-for-agenda))))
18660 ;;;; CDLaTeX minor mode
18662 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18663 "Keymap for the minor `org-cdlatex-mode'.")
18665 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18666 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18667 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18668 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18669 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18671 (defvar org-cdlatex-texmathp-advice-is-done nil
18672 "Flag remembering if we have applied the advice to texmathp already.")
18674 (define-minor-mode org-cdlatex-mode
18675 "Toggle the minor `org-cdlatex-mode'.
18676 This mode supports entering LaTeX environment and math in LaTeX fragments
18677 in Org mode.
18678 \\{org-cdlatex-mode-map}"
18679 nil " OCDL" nil
18680 (when org-cdlatex-mode
18681 (require 'cdlatex)
18682 (run-hooks 'cdlatex-mode-hook)
18683 (cdlatex-compute-tables))
18684 (unless org-cdlatex-texmathp-advice-is-done
18685 (setq org-cdlatex-texmathp-advice-is-done t)
18686 (defadvice texmathp (around org-math-always-on activate)
18687 "Always return t in Org buffers.
18688 This is because we want to insert math symbols without dollars even outside
18689 the LaTeX math segments. If Org mode thinks that point is actually inside
18690 an embedded LaTeX fragment, let `texmathp' do its job.
18691 `\\[org-cdlatex-mode-map]'"
18692 (interactive)
18693 (let (p)
18694 (cond
18695 ((not (derived-mode-p 'org-mode)) ad-do-it)
18696 ((eq this-command 'cdlatex-math-symbol)
18697 (setq ad-return-value t
18698 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18700 (let ((p (org-inside-LaTeX-fragment-p)))
18701 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18702 (setq ad-return-value t
18703 texmathp-why '("Org mode embedded math" . 0))
18704 (when p ad-do-it)))))))))
18706 (defun turn-on-org-cdlatex ()
18707 "Unconditionally turn on `org-cdlatex-mode'."
18708 (org-cdlatex-mode 1))
18710 (defun org-try-cdlatex-tab ()
18711 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18712 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18713 - inside a LaTeX fragment, or
18714 - after the first word in a line, where an abbreviation expansion could
18715 insert a LaTeX environment."
18716 (when org-cdlatex-mode
18717 (cond
18718 ;; Before any word on the line: No expansion possible.
18719 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18720 ;; Just after first word on the line: Expand it. Make sure it
18721 ;; cannot happen on headlines, though.
18722 ((save-excursion
18723 (skip-chars-backward "a-zA-Z0-9*")
18724 (skip-chars-backward " \t")
18725 (and (bolp) (not (org-at-heading-p))))
18726 (cdlatex-tab) t)
18727 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18729 (defun org-cdlatex-underscore-caret (&optional _arg)
18730 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18731 Revert to the normal definition outside of these fragments."
18732 (interactive "P")
18733 (if (org-inside-LaTeX-fragment-p)
18734 (call-interactively 'cdlatex-sub-superscript)
18735 (let (org-cdlatex-mode)
18736 (call-interactively (key-binding (vector last-input-event))))))
18738 (defun org-cdlatex-math-modify (&optional _arg)
18739 "Execute `cdlatex-math-modify' in LaTeX fragments.
18740 Revert to the normal definition outside of these fragments."
18741 (interactive "P")
18742 (if (org-inside-LaTeX-fragment-p)
18743 (call-interactively 'cdlatex-math-modify)
18744 (let (org-cdlatex-mode)
18745 (call-interactively (key-binding (vector last-input-event))))))
18747 (defun org-cdlatex-environment-indent (&optional environment item)
18748 "Execute `cdlatex-environment' and indent the inserted environment.
18750 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18752 The inserted environment is indented to current indentation
18753 unless point is at the beginning of the line, in which the
18754 environment remains unintended."
18755 (interactive)
18756 ;; cdlatex-environment always return nil. Therefore, capture output
18757 ;; first and determine if an environment was selected.
18758 (let* ((beg (point-marker))
18759 (end (copy-marker (point) t))
18760 (inserted (progn
18761 (ignore-errors (cdlatex-environment environment item))
18762 (< beg end)))
18763 ;; Figure out how many lines to move forward after the
18764 ;; environment has been inserted.
18765 (lines (when inserted
18766 (save-excursion
18767 (- (cl-loop while (< beg (point))
18768 with x = 0
18769 do (forward-line -1)
18770 (cl-incf x)
18771 finally return x)
18772 (if (progn (goto-char beg)
18773 (and (progn (skip-chars-forward " \t") (eolp))
18774 (progn (skip-chars-backward " \t") (bolp))))
18775 1 0)))))
18776 (env (org-trim (delete-and-extract-region beg end))))
18777 (when inserted
18778 ;; Get indentation of next line unless at column 0.
18779 (let ((ind (if (bolp) 0
18780 (save-excursion
18781 (org-return-indent)
18782 (prog1 (org-get-indentation)
18783 (when (progn (skip-chars-forward " \t") (eolp))
18784 (delete-region beg (point)))))))
18785 (bol (progn (skip-chars-backward " \t") (bolp))))
18786 ;; Insert a newline before environment unless at column zero
18787 ;; to "escape" the current line. Insert a newline if
18788 ;; something is one the same line as \end{ENVIRONMENT}.
18789 (insert
18790 (concat (unless bol "\n") env
18791 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18792 (unless (zerop ind)
18793 (save-excursion
18794 (goto-char beg)
18795 (while (< (point) end)
18796 (unless (eolp) (indent-line-to ind))
18797 (forward-line))))
18798 (goto-char beg)
18799 (forward-line lines)
18800 (indent-line-to ind)))
18801 (set-marker beg nil)
18802 (set-marker end nil)))
18805 ;;;; LaTeX fragments
18807 (defun org-inside-LaTeX-fragment-p ()
18808 "Test if point is inside a LaTeX fragment.
18809 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18810 sequence appearing also before point.
18811 Even though the matchers for math are configurable, this function assumes
18812 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18813 delimiters are skipped when they have been removed by customization.
18814 The return value is nil, or a cons cell with the delimiter and the
18815 position of this delimiter.
18817 This function does a reasonably good job, but can locally be fooled by
18818 for example currency specifications. For example it will assume being in
18819 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18820 fragments that are properly closed, but during editing, we have to live
18821 with the uncertainty caused by missing closing delimiters. This function
18822 looks only before point, not after."
18823 (catch 'exit
18824 (let ((pos (point))
18825 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18826 (lim (progn
18827 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18828 (point)))
18829 dd-on str (start 0) m re)
18830 (goto-char pos)
18831 (when dodollar
18832 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18833 re (nth 1 (assoc "$" org-latex-regexps)))
18834 (while (string-match re str start)
18835 (cond
18836 ((= (match-end 0) (length str))
18837 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18838 ((= (match-end 0) (- (length str) 5))
18839 (throw 'exit nil))
18840 (t (setq start (match-end 0))))))
18841 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18842 (goto-char pos)
18843 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18844 (and (match-beginning 2) (throw 'exit nil))
18845 ;; count $$
18846 (while (re-search-backward "\\$\\$" lim t)
18847 (setq dd-on (not dd-on)))
18848 (goto-char pos)
18849 (when dd-on (cons "$$" m))))))
18851 (defun org-inside-latex-macro-p ()
18852 "Is point inside a LaTeX macro or its arguments?"
18853 (save-match-data
18854 (org-in-regexp
18855 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18857 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18858 "Build an overlay between BEG and END using IMAGE file.
18859 Argument IMAGETYPE is the extension of the displayed image,
18860 as a string. It defaults to \"png\"."
18861 (let ((ov (make-overlay beg end))
18862 (imagetype (or (intern imagetype) 'png)))
18863 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18864 (overlay-put ov 'evaporate t)
18865 (overlay-put ov
18866 'modification-hooks
18867 (list (lambda (o _flag _beg _end &optional _l)
18868 (delete-overlay o))))
18869 (overlay-put ov
18870 'display
18871 (list 'image :type imagetype :file image :ascent 'center))))
18873 (defun org--list-latex-overlays (&optional beg end)
18874 "List all Org LaTeX overlays in current buffer.
18875 Limit to overlays between BEG and END when those are provided."
18876 (cl-remove-if-not
18877 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18878 (overlays-in (or beg (point-min)) (or end (point-max)))))
18880 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18881 "Remove all overlays with LaTeX fragment images in current buffer.
18882 When optional arguments BEG and END are non-nil, remove all
18883 overlays between them instead. Return a non-nil value when some
18884 overlays were removed, nil otherwise."
18885 (let ((overlays (org--list-latex-overlays beg end)))
18886 (mapc #'delete-overlay overlays)
18887 overlays))
18889 (defun org-toggle-latex-fragment (&optional arg)
18890 "Preview the LaTeX fragment at point, or all locally or globally.
18892 If the cursor is on a LaTeX fragment, create the image and overlay
18893 it over the source code, if there is none. Remove it otherwise.
18894 If there is no fragment at point, display all fragments in the
18895 current section.
18897 With prefix ARG, preview or clear image for all fragments in the
18898 current subtree or in the whole buffer when used before the first
18899 headline. With a prefix ARG `\\[universal-argument] \
18900 \\[universal-argument]' preview or clear images
18901 for all fragments in the buffer."
18902 (interactive "P")
18903 (when (display-graphic-p)
18904 (catch 'exit
18905 (save-excursion
18906 (let (beg end msg)
18907 (cond
18908 ((or (equal arg '(16))
18909 (and (equal arg '(4))
18910 (org-with-limited-levels (org-before-first-heading-p))))
18911 (if (org-remove-latex-fragment-image-overlays)
18912 (progn (message "LaTeX fragments images removed from buffer")
18913 (throw 'exit nil))
18914 (setq msg "Creating images for buffer...")))
18915 ((equal arg '(4))
18916 (org-with-limited-levels (org-back-to-heading t))
18917 (setq beg (point))
18918 (setq end (progn (org-end-of-subtree t) (point)))
18919 (if (org-remove-latex-fragment-image-overlays beg end)
18920 (progn
18921 (message "LaTeX fragment images removed from subtree")
18922 (throw 'exit nil))
18923 (setq msg "Creating images for subtree...")))
18924 ((let ((datum (org-element-context)))
18925 (when (memq (org-element-type datum)
18926 '(latex-environment latex-fragment))
18927 (setq beg (org-element-property :begin datum))
18928 (setq end (org-element-property :end datum))
18929 (if (org-remove-latex-fragment-image-overlays beg end)
18930 (progn (message "LaTeX fragment image removed")
18931 (throw 'exit nil))
18932 (setq msg "Creating image...")))))
18934 (org-with-limited-levels
18935 (setq beg (if (org-at-heading-p) (line-beginning-position)
18936 (outline-previous-heading)
18937 (point)))
18938 (setq end (progn (outline-next-heading) (point)))
18939 (if (org-remove-latex-fragment-image-overlays beg end)
18940 (progn
18941 (message "LaTeX fragment images removed from section")
18942 (throw 'exit nil))
18943 (setq msg "Creating images for section...")))))
18944 (let ((file (buffer-file-name (buffer-base-buffer))))
18945 (org-format-latex
18946 (concat org-preview-latex-image-directory "org-ltximg")
18947 beg end
18948 ;; Emacs cannot overlay images from remote hosts. Create
18949 ;; it in `temporary-file-directory' instead.
18950 (if (or (not file) (file-remote-p file))
18951 temporary-file-directory
18952 default-directory)
18953 'overlays msg 'forbuffer org-preview-latex-default-process))
18954 (message (concat msg "done")))))))
18956 (defun org-format-latex
18957 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18958 "Replace LaTeX fragments with links to an image.
18960 The function takes care of creating the replacement image.
18962 Only consider fragments between BEG and END when those are
18963 provided.
18965 When optional argument OVERLAYS is non-nil, display the image on
18966 top of the fragment instead of replacing it.
18968 PROCESSING-TYPE is the conversion method to use, as a symbol.
18970 Some of the options can be changed using the variable
18971 `org-format-latex-options', which see."
18972 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18973 (unless (eq processing-type 'verbatim)
18974 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18975 (cnt 0)
18976 checkdir-flag)
18977 (goto-char (or beg (point-min)))
18978 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18979 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18980 (overlay-recenter (or end (point-max))))
18981 (while (re-search-forward math-regexp end t)
18982 (unless (and overlays
18983 (eq (get-char-property (point) 'org-overlay-type)
18984 'org-latex-overlay))
18985 (let* ((context (org-element-context))
18986 (type (org-element-type context)))
18987 (when (memq type '(latex-environment latex-fragment))
18988 (let ((block-type (eq type 'latex-environment))
18989 (value (org-element-property :value context))
18990 (beg (org-element-property :begin context))
18991 (end (save-excursion
18992 (goto-char (org-element-property :end context))
18993 (skip-chars-backward " \r\t\n")
18994 (point))))
18995 (cond
18996 ((eq processing-type 'mathjax)
18997 ;; Prepare for MathJax processing.
18998 (if (not (string-match "\\`\\$\\$?" value))
18999 (goto-char end)
19000 (delete-region beg end)
19001 (if (string= (match-string 0 value) "$$")
19002 (insert "\\[" (substring value 2 -2) "\\]")
19003 (insert "\\(" (substring value 1 -1) "\\)"))))
19004 ((assq processing-type org-preview-latex-process-alist)
19005 ;; Process to an image.
19006 (cl-incf cnt)
19007 (goto-char beg)
19008 (let* ((processing-info
19009 (cdr (assq processing-type org-preview-latex-process-alist)))
19010 (face (face-at-point))
19011 ;; Get the colors from the face at point.
19013 (let ((color (plist-get org-format-latex-options
19014 :foreground)))
19015 (if (and forbuffer (eq color 'auto))
19016 (face-attribute face :foreground nil 'default)
19017 color)))
19019 (let ((color (plist-get org-format-latex-options
19020 :background)))
19021 (if (and forbuffer (eq color 'auto))
19022 (face-attribute face :background nil 'default)
19023 color)))
19024 (hash (sha1 (prin1-to-string
19025 (list org-format-latex-header
19026 org-latex-default-packages-alist
19027 org-latex-packages-alist
19028 org-format-latex-options
19029 forbuffer value fg bg))))
19030 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19031 (absprefix (expand-file-name prefix dir))
19032 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19033 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19034 (sep (and block-type "\n\n"))
19035 (link (concat sep "[[file:" linkfile "]]" sep))
19036 (options
19037 (org-combine-plists
19038 org-format-latex-options
19039 `(:foreground ,fg :background ,bg))))
19040 (when msg (message msg cnt))
19041 (unless checkdir-flag ; Ensure the directory exists.
19042 (setq checkdir-flag t)
19043 (let ((todir (file-name-directory absprefix)))
19044 (unless (file-directory-p todir)
19045 (make-directory todir t))))
19046 (unless (file-exists-p movefile)
19047 (org-create-formula-image
19048 value movefile options forbuffer processing-type))
19049 (if overlays
19050 (progn
19051 (dolist (o (overlays-in beg end))
19052 (when (eq (overlay-get o 'org-overlay-type)
19053 'org-latex-overlay)
19054 (delete-overlay o)))
19055 (org--format-latex-make-overlay beg end movefile imagetype)
19056 (goto-char end))
19057 (delete-region beg end)
19058 (insert
19059 (org-add-props link
19060 (list 'org-latex-src
19061 (replace-regexp-in-string "\"" "" value)
19062 'org-latex-src-embed-type
19063 (if block-type 'paragraph 'character)))))))
19064 ((eq processing-type 'mathml)
19065 ;; Process to MathML.
19066 (unless (org-format-latex-mathml-available-p)
19067 (user-error "LaTeX to MathML converter not configured"))
19068 (cl-incf cnt)
19069 (when msg (message msg cnt))
19070 (goto-char beg)
19071 (delete-region beg end)
19072 (insert (org-format-latex-as-mathml
19073 value block-type prefix dir)))
19075 (error "Unknown conversion process %s for LaTeX fragments"
19076 processing-type)))))))))))
19078 (defun org-create-math-formula (latex-frag &optional mathml-file)
19079 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19080 Use `org-latex-to-mathml-convert-command'. If the conversion is
19081 sucessful, return the portion between \"<math...> </math>\"
19082 elements otherwise return nil. When MATHML-FILE is specified,
19083 write the results in to that file. When invoked as an
19084 interactive command, prompt for LATEX-FRAG, with initial value
19085 set to the current active region and echo the results for user
19086 inspection."
19087 (interactive (list (let ((frag (when (org-region-active-p)
19088 (buffer-substring-no-properties
19089 (region-beginning) (region-end)))))
19090 (read-string "LaTeX Fragment: " frag nil frag))))
19091 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19092 (let* ((tmp-in-file
19093 (let ((file (file-relative-name
19094 (make-temp-name (expand-file-name "ltxmathml-in")))))
19095 (write-region latex-frag nil file)
19096 file))
19097 (tmp-out-file (file-relative-name
19098 (make-temp-name (expand-file-name "ltxmathml-out"))))
19099 (cmd (format-spec
19100 org-latex-to-mathml-convert-command
19101 `((?j . ,(and org-latex-to-mathml-jar-file
19102 (shell-quote-argument
19103 (expand-file-name
19104 org-latex-to-mathml-jar-file))))
19105 (?I . ,(shell-quote-argument tmp-in-file))
19106 (?i . ,latex-frag)
19107 (?o . ,(shell-quote-argument tmp-out-file)))))
19108 mathml shell-command-output)
19109 (when (called-interactively-p 'any)
19110 (unless (org-format-latex-mathml-available-p)
19111 (user-error "LaTeX to MathML converter not configured")))
19112 (message "Running %s" cmd)
19113 (setq shell-command-output (shell-command-to-string cmd))
19114 (setq mathml
19115 (when (file-readable-p tmp-out-file)
19116 (with-current-buffer (find-file-noselect tmp-out-file t)
19117 (goto-char (point-min))
19118 (when (re-search-forward
19119 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19120 (regexp-quote
19121 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19122 nil t)
19123 (prog1 (match-string 0) (kill-buffer))))))
19124 (cond
19125 (mathml
19126 (setq mathml
19127 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19128 (when mathml-file
19129 (write-region mathml nil mathml-file))
19130 (when (called-interactively-p 'any)
19131 (message mathml)))
19132 ((message "LaTeX to MathML conversion failed")
19133 (message shell-command-output)))
19134 (delete-file tmp-in-file)
19135 (when (file-exists-p tmp-out-file)
19136 (delete-file tmp-out-file))
19137 mathml))
19139 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19140 prefix &optional dir)
19141 "Use `org-create-math-formula' but check local cache first."
19142 (let* ((absprefix (expand-file-name prefix dir))
19143 (print-length nil) (print-level nil)
19144 (formula-id (concat
19145 "formula-"
19146 (sha1
19147 (prin1-to-string
19148 (list latex-frag
19149 org-latex-to-mathml-convert-command)))))
19150 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19151 (formula-cache-dir (file-name-directory formula-cache)))
19153 (unless (file-directory-p formula-cache-dir)
19154 (make-directory formula-cache-dir t))
19156 (unless (file-exists-p formula-cache)
19157 (org-create-math-formula latex-frag formula-cache))
19159 (if (file-exists-p formula-cache)
19160 ;; Successful conversion. Return the link to MathML file.
19161 (org-add-props
19162 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19163 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19164 'org-latex-src-embed-type (if latex-frag-type
19165 'paragraph 'character)))
19166 ;; Failed conversion. Return the LaTeX fragment verbatim
19167 latex-frag)))
19169 (defun org--get-display-dpi ()
19170 "Get the DPI of the display.
19171 The function assumes that the display has the same pixel width in
19172 the horizontal and vertical directions."
19173 (if (display-graphic-p)
19174 (round (/ (display-pixel-height)
19175 (/ (display-mm-height) 25.4)))
19176 (error "Attempt to calculate the dpi of a non-graphic display")))
19178 (defun org-create-formula-image
19179 (string tofile options buffer &optional processing-type)
19180 "Create an image from LaTeX source using external processes.
19182 The LaTeX STRING is saved to a temporary LaTeX file, then
19183 converted to an image file by process PROCESSING-TYPE defined in
19184 `org-preview-latex-process-alist'. A nil value defaults to
19185 `org-preview-latex-default-process'.
19187 The generated image file is eventually moved to TOFILE.
19189 The OPTIONS argument controls the size, foreground color and
19190 background color of the generated image.
19192 When BUFFER non-nil, this function is used for LaTeX previewing.
19193 Otherwise, it is used to deal with LaTeX snippets showed in
19194 a HTML file."
19195 (let* ((processing-type (or processing-type
19196 org-preview-latex-default-process))
19197 (processing-info
19198 (cdr (assq processing-type org-preview-latex-process-alist)))
19199 (programs (plist-get processing-info :programs))
19200 (error-message (or (plist-get processing-info :message) ""))
19201 (use-xcolor (plist-get processing-info :use-xcolor))
19202 (image-input-type (plist-get processing-info :image-input-type))
19203 (image-output-type (plist-get processing-info :image-output-type))
19204 (post-clean (or (plist-get processing-info :post-clean)
19205 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19206 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19207 (latex-header
19208 (or (plist-get processing-info :latex-header)
19209 (org-latex-make-preamble
19210 (org-export-get-environment (org-export-get-backend 'latex))
19211 org-format-latex-header
19212 'snippet)))
19213 (latex-compiler (plist-get processing-info :latex-compiler))
19214 (image-converter (plist-get processing-info :image-converter))
19215 (tmpdir temporary-file-directory)
19216 (texfilebase (make-temp-name
19217 (expand-file-name "orgtex" tmpdir)))
19218 (texfile (concat texfilebase ".tex"))
19219 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19220 '(1.0 . 1.0)))
19221 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19222 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19223 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19224 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19225 "Black"))
19226 (bg (or (plist-get options (if buffer :background :html-background))
19227 "Transparent"))
19228 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19229 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19230 (dolist (program programs)
19231 (org-check-external-command program error-message))
19232 (if use-xcolor
19233 (progn (if (eq fg 'default)
19234 (setq fg (org-latex-color :foreground))
19235 (setq fg (org-latex-color-format fg)))
19236 (if (eq bg 'default)
19237 (setq bg (org-latex-color :background))
19238 (setq bg (org-latex-color-format
19239 (if (string= bg "Transparent") "white" bg))))
19240 (with-temp-file texfile
19241 (insert latex-header)
19242 (insert "\n\\begin{document}\n"
19243 "\\definecolor{fg}{rgb}{" fg "}\n"
19244 "\\definecolor{bg}{rgb}{" bg "}\n"
19245 "\n\\pagecolor{bg}\n"
19246 "\n{\\color{fg}\n"
19247 string
19248 "\n}\n"
19249 "\n\\end{document}\n")))
19250 (if (eq fg 'default)
19251 (setq fg (org-dvipng-color :foreground))
19252 (unless (string= fg "Transparent")
19253 (setq fg (org-dvipng-color-format fg))))
19254 (if (eq bg 'default)
19255 (setq bg (org-dvipng-color :background))
19256 (unless (string= bg "Transparent")
19257 (setq bg (org-dvipng-color-format bg))))
19258 (with-temp-file texfile
19259 (insert latex-header)
19260 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19262 (let* ((err-msg (format "Please adjust '%s' part of \
19263 `org-preview-latex-process-alist'."
19264 processing-type))
19265 (image-input-file
19266 (org-compile-file
19267 texfile latex-compiler image-input-type err-msg log-buf))
19268 (image-output-file
19269 (org-compile-file
19270 image-input-file image-converter image-output-type err-msg log-buf
19271 `((?F . ,(shell-quote-argument fg))
19272 (?B . ,(shell-quote-argument bg))
19273 (?D . ,(shell-quote-argument (format "%s" dpi)))
19274 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19275 (copy-file image-output-file tofile 'replace)
19276 (dolist (e post-clean)
19277 (when (file-exists-p (concat texfilebase e))
19278 (delete-file (concat texfilebase e))))
19279 image-output-file)))
19281 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19282 "Fill a LaTeX header template TPL.
19283 In the template, the following place holders will be recognized:
19285 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19286 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19287 [PACKAGES] \\usepackage statements for PKG
19288 [NO-PACKAGES] do not include PKG
19289 [EXTRA] the string EXTRA
19290 [NO-EXTRA] do not include EXTRA
19292 For backward compatibility, if both the positive and the negative place
19293 holder is missing, the positive one (without the \"NO-\") will be
19294 assumed to be present at the end of the template.
19295 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19296 EXTRA is a string.
19297 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19298 (let (rpl (end ""))
19299 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19300 (setq rpl (if (or (match-end 1) (not def-pkg))
19301 "" (org-latex-packages-to-string def-pkg snippets-p t))
19302 tpl (replace-match rpl t t tpl))
19303 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19305 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19306 (setq rpl (if (or (match-end 1) (not pkg))
19307 "" (org-latex-packages-to-string pkg snippets-p t))
19308 tpl (replace-match rpl t t tpl))
19309 (when pkg (setq end
19310 (concat end "\n"
19311 (org-latex-packages-to-string pkg snippets-p)))))
19313 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19314 (setq rpl (if (or (match-end 1) (not extra))
19315 "" (concat extra "\n"))
19316 tpl (replace-match rpl t t tpl))
19317 (when (and extra (string-match "\\S-" extra))
19318 (setq end (concat end "\n" extra))))
19320 (if (string-match "\\S-" end)
19321 (concat tpl "\n" end)
19322 tpl)))
19324 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19325 "Turn an alist of packages into a string with the \\usepackage macros."
19326 (setq pkg (mapconcat (lambda(p)
19327 (cond
19328 ((stringp p) p)
19329 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19330 (format "%% Package %s omitted" (cadr p)))
19331 ((equal "" (car p))
19332 (format "\\usepackage{%s}" (cadr p)))
19334 (format "\\usepackage[%s]{%s}"
19335 (car p) (cadr p)))))
19337 "\n"))
19338 (if newline (concat pkg "\n") pkg))
19340 (defun org-dvipng-color (attr)
19341 "Return a RGB color specification for dvipng."
19342 (org-dvipng-color-format (face-attribute 'default attr nil)))
19344 (defun org-dvipng-color-format (color-name)
19345 "Convert COLOR-NAME to a RGB color value for dvipng."
19346 (apply #'format "rgb %s %s %s"
19347 (mapcar 'org-normalize-color
19348 (color-values color-name))))
19350 (defun org-latex-color (attr)
19351 "Return a RGB color for the LaTeX color package."
19352 (org-latex-color-format (face-attribute 'default attr nil)))
19354 (defun org-latex-color-format (color-name)
19355 "Convert COLOR-NAME to a RGB color value."
19356 (apply #'format "%s,%s,%s"
19357 (mapcar 'org-normalize-color
19358 (color-values color-name))))
19360 (defun org-normalize-color (value)
19361 "Return string to be used as color value for an RGB component."
19362 (format "%g" (/ value 65535.0)))
19366 ;; Image display
19368 (defvar-local org-inline-image-overlays nil)
19370 (defun org-toggle-inline-images (&optional include-linked)
19371 "Toggle the display of inline images.
19372 INCLUDE-LINKED is passed to `org-display-inline-images'."
19373 (interactive "P")
19374 (if org-inline-image-overlays
19375 (progn
19376 (org-remove-inline-images)
19377 (when (called-interactively-p 'interactive)
19378 (message "Inline image display turned off")))
19379 (org-display-inline-images include-linked)
19380 (when (called-interactively-p 'interactive)
19381 (message (if org-inline-image-overlays
19382 (format "%d images displayed inline"
19383 (length org-inline-image-overlays))
19384 "No images to display inline")))))
19386 (defun org-redisplay-inline-images ()
19387 "Refresh the display of inline images."
19388 (interactive)
19389 (if (not org-inline-image-overlays)
19390 (org-toggle-inline-images)
19391 (org-toggle-inline-images)
19392 (org-toggle-inline-images)))
19394 (defun org-display-inline-images (&optional include-linked refresh beg end)
19395 "Display inline images.
19397 An inline image is a link which follows either of these
19398 conventions:
19400 1. Its path is a file with an extension matching return value
19401 from `image-file-name-regexp' and it has no contents.
19403 2. Its description consists in a single link of the previous
19404 type.
19406 When optional argument INCLUDE-LINKED is non-nil, also links with
19407 a text description part will be inlined. This can be nice for
19408 a quick look at those images, but it does not reflect what
19409 exported files will look like.
19411 When optional argument REFRESH is non-nil, refresh existing
19412 images between BEG and END. This will create new image displays
19413 only if necessary. BEG and END default to the buffer
19414 boundaries."
19415 (interactive "P")
19416 (when (display-graphic-p)
19417 (unless refresh
19418 (org-remove-inline-images)
19419 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19420 (org-with-wide-buffer
19421 (goto-char (or beg (point-min)))
19422 (let ((case-fold-search t)
19423 (file-extension-re (image-file-name-regexp)))
19424 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19425 (let ((link (save-match-data (org-element-context))))
19426 ;; Check if we're at an inline image.
19427 (when (and (equal (org-element-property :type link) "file")
19428 (or include-linked
19429 (not (org-element-property :contents-begin link)))
19430 (let ((parent (org-element-property :parent link)))
19431 (or (not (eq (org-element-type parent) 'link))
19432 (not (cdr (org-element-contents parent)))))
19433 (string-match-p file-extension-re
19434 (org-element-property :path link)))
19435 (let ((file (expand-file-name
19436 (org-link-unescape
19437 (org-element-property :path link)))))
19438 (when (file-exists-p file)
19439 (let ((width
19440 ;; Apply `org-image-actual-width' specifications.
19441 (cond
19442 ((not (image-type-available-p 'imagemagick)) nil)
19443 ((eq org-image-actual-width t) nil)
19444 ((listp org-image-actual-width)
19446 ;; First try to find a width among
19447 ;; attributes associated to the paragraph
19448 ;; containing link.
19449 (let ((paragraph
19450 (let ((e link))
19451 (while (and (setq e (org-element-property
19452 :parent e))
19453 (not (eq (org-element-type e)
19454 'paragraph))))
19455 e)))
19456 (when paragraph
19457 (save-excursion
19458 (goto-char (org-element-property :begin paragraph))
19459 (when
19460 (re-search-forward
19461 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19462 (org-element-property
19463 :post-affiliated paragraph)
19465 (string-to-number (match-string 1))))))
19466 ;; Otherwise, fall-back to provided number.
19467 (car org-image-actual-width)))
19468 ((numberp org-image-actual-width)
19469 org-image-actual-width)))
19470 (old (get-char-property-and-overlay
19471 (org-element-property :begin link)
19472 'org-image-overlay)))
19473 (if (and (car-safe old) refresh)
19474 (image-refresh (overlay-get (cdr old) 'display))
19475 (let ((image (create-image file
19476 (and width 'imagemagick)
19478 :width width)))
19479 (when image
19480 (let* ((link
19481 ;; If inline image is the description
19482 ;; of another link, be sure to
19483 ;; consider the latter as the one to
19484 ;; apply the overlay on.
19485 (let ((parent
19486 (org-element-property :parent link)))
19487 (if (eq (org-element-type parent) 'link)
19488 parent
19489 link)))
19490 (ov (make-overlay
19491 (org-element-property :begin link)
19492 (progn
19493 (goto-char
19494 (org-element-property :end link))
19495 (skip-chars-backward " \t")
19496 (point)))))
19497 (overlay-put ov 'display image)
19498 (overlay-put ov 'face 'default)
19499 (overlay-put ov 'org-image-overlay t)
19500 (overlay-put
19501 ov 'modification-hooks
19502 (list 'org-display-inline-remove-overlay))
19503 (push ov org-inline-image-overlays)))))))))))))))
19505 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19506 "Remove inline-display overlay if a corresponding region is modified."
19507 (let ((inhibit-modification-hooks t))
19508 (when (and ov after)
19509 (delete ov org-inline-image-overlays)
19510 (delete-overlay ov))))
19512 (defun org-remove-inline-images ()
19513 "Remove inline display of images."
19514 (interactive)
19515 (mapc #'delete-overlay org-inline-image-overlays)
19516 (setq org-inline-image-overlays nil))
19518 ;;;; Key bindings
19520 ;; Outline functions from `outline-mode-prefix-map'
19521 ;; that can be remapped in Org:
19522 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19523 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19524 (define-key org-mode-map [remap outline-forward-same-level]
19525 'org-forward-heading-same-level)
19526 (define-key org-mode-map [remap outline-backward-same-level]
19527 'org-backward-heading-same-level)
19528 (define-key org-mode-map [remap outline-show-branches]
19529 'org-kill-note-or-show-branches)
19530 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19531 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19532 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19533 (define-key org-mode-map [remap outline-next-visible-heading]
19534 'org-next-visible-heading)
19535 (define-key org-mode-map [remap outline-previous-visible-heading]
19536 'org-previous-visible-heading)
19537 (define-key org-mode-map [remap show-children] 'org-show-children)
19539 ;; Outline functions from `outline-mode-prefix-map' that can not
19540 ;; be remapped in Org:
19542 ;; - the column "key binding" shows whether the Outline function is still
19543 ;; available in Org mode on the same key that it has been bound to in
19544 ;; Outline mode:
19545 ;; - "overridden": key used for a different functionality in Org mode
19546 ;; - else: key still bound to the same Outline function in Org mode
19548 ;; | Outline function | key binding | Org replacement |
19549 ;; |------------------------------------+-------------+--------------------------|
19550 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19551 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19552 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19553 ;; | `show-entry' | overridden | no replacement |
19554 ;; | `show-branches' | `C-c C-k' | still same function |
19555 ;; | `show-subtree' | overridden | visibility cycling |
19556 ;; | `show-all' | overridden | no replacement |
19557 ;; | `hide-subtree' | overridden | visibility cycling |
19558 ;; | `hide-body' | overridden | no replacement |
19559 ;; | `hide-entry' | overridden | visibility cycling |
19560 ;; | `hide-leaves' | overridden | no replacement |
19561 ;; | `hide-sublevels' | overridden | no replacement |
19562 ;; | `hide-other' | overridden | no replacement |
19564 ;; Make `C-c C-x' a prefix key
19565 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19567 ;; TAB key with modifiers
19568 (org-defkey org-mode-map "\C-i" 'org-cycle)
19569 (org-defkey org-mode-map [(tab)] 'org-cycle)
19570 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19571 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19572 ;; The following line is necessary under Suse GNU/Linux
19573 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19574 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19575 (define-key org-mode-map [backtab] 'org-shifttab)
19577 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19578 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19579 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19581 ;; Cursor keys with modifiers
19582 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19583 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19584 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19585 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19587 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19588 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19589 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19590 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19591 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19592 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19594 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19595 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19596 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19597 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19599 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19600 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19601 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19602 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19604 ;; Babel keys
19605 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19606 (dolist (pair org-babel-key-bindings)
19607 (define-key org-babel-map (car pair) (cdr pair)))
19609 ;;; Extra keys for tty access.
19610 ;; We only set them when really needed because otherwise the
19611 ;; menus don't show the simple keys
19613 (when (or org-use-extra-keys (not window-system))
19614 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19615 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19616 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19617 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19618 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19619 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19620 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19621 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19622 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19623 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19624 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19625 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19626 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19627 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19628 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19629 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19630 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19631 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19632 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19633 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19634 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19635 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19636 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19637 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19638 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19639 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19640 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19641 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19643 ;; All the other keys
19645 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19646 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19647 (if (boundp 'narrow-map)
19648 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19649 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19650 (if (boundp 'narrow-map)
19651 (org-defkey narrow-map "b" 'org-narrow-to-block)
19652 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19653 (if (boundp 'narrow-map)
19654 (org-defkey narrow-map "e" 'org-narrow-to-element)
19655 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19656 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19657 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19658 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19659 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19660 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19661 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19662 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19663 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19664 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19665 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19666 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19667 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19668 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19669 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19670 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19671 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19672 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19673 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19674 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19675 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19676 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19677 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19678 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19679 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19680 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19681 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19682 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19683 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19684 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19685 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19686 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19687 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19688 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19689 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19690 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19691 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19692 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19693 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19694 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19695 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19696 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19697 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19698 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19699 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19700 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19701 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19702 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19703 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19704 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19705 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19706 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19707 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19708 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19709 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19710 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19711 (org-defkey org-mode-map "\C-c^" 'org-sort)
19712 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19713 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19714 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19715 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19716 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19717 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19718 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19719 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19720 (org-defkey org-mode-map "\C-m" 'org-return)
19721 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19722 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19723 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19724 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19725 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19726 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19727 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19728 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19729 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19730 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19731 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19732 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19733 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19734 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19735 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19736 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19737 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19738 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19739 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19740 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19741 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19742 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19743 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19744 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19745 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19747 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19748 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19749 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19751 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19752 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19753 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19754 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19755 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19756 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19757 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19758 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19759 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19760 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19761 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19762 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19763 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19764 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19765 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19766 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19767 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19768 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19769 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19770 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19771 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19772 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19774 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19775 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19776 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19777 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19778 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19780 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19782 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19784 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19785 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19787 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19790 (defconst org-speed-commands-default
19792 ("Outline Navigation")
19793 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19794 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19795 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19796 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19797 ("F" . org-next-block)
19798 ("B" . org-previous-block)
19799 ("u" . (org-speed-move-safe 'outline-up-heading))
19800 ("j" . org-goto)
19801 ("g" . (org-refile t))
19802 ("Outline Visibility")
19803 ("c" . org-cycle)
19804 ("C" . org-shifttab)
19805 (" " . org-display-outline-path)
19806 ("s" . org-narrow-to-subtree)
19807 ("=" . org-columns)
19808 ("Outline Structure Editing")
19809 ("U" . org-metaup)
19810 ("D" . org-metadown)
19811 ("r" . org-metaright)
19812 ("l" . org-metaleft)
19813 ("R" . org-shiftmetaright)
19814 ("L" . org-shiftmetaleft)
19815 ("i" . (progn (forward-char 1) (call-interactively
19816 'org-insert-heading-respect-content)))
19817 ("^" . org-sort)
19818 ("w" . org-refile)
19819 ("a" . org-archive-subtree-default-with-confirmation)
19820 ("@" . org-mark-subtree)
19821 ("#" . org-toggle-comment)
19822 ("Clock Commands")
19823 ("I" . org-clock-in)
19824 ("O" . org-clock-out)
19825 ("Meta Data Editing")
19826 ("t" . org-todo)
19827 ("," . (org-priority))
19828 ("0" . (org-priority ?\ ))
19829 ("1" . (org-priority ?A))
19830 ("2" . (org-priority ?B))
19831 ("3" . (org-priority ?C))
19832 (":" . org-set-tags-command)
19833 ("e" . org-set-effort)
19834 ("E" . org-inc-effort)
19835 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19836 (org-entry-put (point) "APPT_WARNTIME" m)))
19837 ("Agenda Views etc")
19838 ("v" . org-agenda)
19839 ("/" . org-sparse-tree)
19840 ("Misc")
19841 ("o" . org-open-at-point)
19842 ("?" . org-speed-command-help)
19843 ("<" . (org-agenda-set-restriction-lock 'subtree))
19844 (">" . (org-agenda-remove-restriction-lock))
19846 "The default speed commands.")
19848 (defun org-print-speed-command (e)
19849 (if (> (length (car e)) 1)
19850 (progn
19851 (princ "\n")
19852 (princ (car e))
19853 (princ "\n")
19854 (princ (make-string (length (car e)) ?-))
19855 (princ "\n"))
19856 (princ (car e))
19857 (princ " ")
19858 (if (symbolp (cdr e))
19859 (princ (symbol-name (cdr e)))
19860 (prin1 (cdr e)))
19861 (princ "\n")))
19863 (defun org-speed-command-help ()
19864 "Show the available speed commands."
19865 (interactive)
19866 (if (not org-use-speed-commands)
19867 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19868 (with-output-to-temp-buffer "*Help*"
19869 (princ "User-defined Speed commands\n===========================\n")
19870 (mapc #'org-print-speed-command org-speed-commands-user)
19871 (princ "\n")
19872 (princ "Built-in Speed commands\n=======================\n")
19873 (mapc #'org-print-speed-command org-speed-commands-default))
19874 (with-current-buffer "*Help*"
19875 (setq truncate-lines t))))
19877 (defun org-speed-move-safe (cmd)
19878 "Execute CMD, but make sure that the cursor always ends up in a headline.
19879 If not, return to the original position and throw an error."
19880 (interactive)
19881 (let ((pos (point)))
19882 (call-interactively cmd)
19883 (unless (and (bolp) (org-at-heading-p))
19884 (goto-char pos)
19885 (error "Boundary reached while executing %s" cmd))))
19887 (defvar org-self-insert-command-undo-counter 0)
19889 (defvar org-table-auto-blank-field) ; defined in org-table.el
19890 (defvar org-speed-command nil)
19892 (defun org-speed-command-activate (keys)
19893 "Hook for activating single-letter speed commands.
19894 `org-speed-commands-default' specifies a minimal command set.
19895 Use `org-speed-commands-user' for further customization."
19896 (when (or (and (bolp) (looking-at org-outline-regexp))
19897 (and (functionp org-use-speed-commands)
19898 (funcall org-use-speed-commands)))
19899 (cdr (assoc keys (append org-speed-commands-user
19900 org-speed-commands-default)))))
19902 (defun org-babel-speed-command-activate (keys)
19903 "Hook for activating single-letter code block commands."
19904 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19905 (cdr (assoc keys org-babel-key-bindings))))
19907 (defcustom org-speed-command-hook
19908 '(org-speed-command-activate org-babel-speed-command-activate)
19909 "Hook for activating speed commands at strategic locations.
19910 Hook functions are called in sequence until a valid handler is
19911 found.
19913 Each hook takes a single argument, a user-pressed command key
19914 which is also a `self-insert-command' from the global map.
19916 Within the hook, examine the cursor position and the command key
19917 and return nil or a valid handler as appropriate. Handler could
19918 be one of an interactive command, a function, or a form.
19920 Set `org-use-speed-commands' to non-nil value to enable this
19921 hook. The default setting is `org-speed-command-activate'."
19922 :group 'org-structure
19923 :version "24.1"
19924 :type 'hook)
19926 (defun org-self-insert-command (N)
19927 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19928 If the cursor is in a table looking at whitespace, the whitespace is
19929 overwritten, and the table is not marked as requiring realignment."
19930 (interactive "p")
19931 (org-check-before-invisible-edit 'insert)
19932 (cond
19933 ((and org-use-speed-commands
19934 (let ((kv (this-command-keys-vector)))
19935 (setq org-speed-command
19936 (run-hook-with-args-until-success
19937 'org-speed-command-hook
19938 (make-string 1 (aref kv (1- (length kv))))))))
19939 (cond
19940 ((commandp org-speed-command)
19941 (setq this-command org-speed-command)
19942 (call-interactively org-speed-command))
19943 ((functionp org-speed-command)
19944 (funcall org-speed-command))
19945 ((and org-speed-command (listp org-speed-command))
19946 (eval org-speed-command))
19947 (t (let (org-use-speed-commands)
19948 (call-interactively 'org-self-insert-command)))))
19949 ((and
19950 (org-at-table-p)
19951 (progn
19952 ;; Check if we blank the field, and if that triggers align.
19953 (and (featurep 'org-table) org-table-auto-blank-field
19954 (memq last-command
19955 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19956 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19957 ;; Got extra space, this field does not determine
19958 ;; column width.
19959 (let (org-table-may-need-update) (org-table-blank-field))
19960 ;; No extra space, this field may determine column
19961 ;; width.
19962 (org-table-blank-field)))
19964 (eq N 1)
19965 (looking-at "[^|\n]* \\( \\)|"))
19966 ;; There is room for insertion without re-aligning the table.
19967 (delete-region (match-beginning 1) (match-end 1))
19968 (self-insert-command N))
19970 (setq org-table-may-need-update t)
19971 (self-insert-command N)
19972 (org-fix-tags-on-the-fly)
19973 (when org-self-insert-cluster-for-undo
19974 (if (not (eq last-command 'org-self-insert-command))
19975 (setq org-self-insert-command-undo-counter 1)
19976 (if (>= org-self-insert-command-undo-counter 20)
19977 (setq org-self-insert-command-undo-counter 1)
19978 (and (> org-self-insert-command-undo-counter 0)
19979 buffer-undo-list (listp buffer-undo-list)
19980 (not (cadr buffer-undo-list)) ; remove nil entry
19981 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19982 (setq org-self-insert-command-undo-counter
19983 (1+ org-self-insert-command-undo-counter))))))))
19985 (defun org-check-before-invisible-edit (kind)
19986 "Check is editing if kind KIND would be dangerous with invisible text around.
19987 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19988 ;; First, try to get out of here as quickly as possible, to reduce overhead
19989 (when (and org-catch-invisible-edits
19990 (or (not (boundp 'visible-mode)) (not visible-mode))
19991 (or (get-char-property (point) 'invisible)
19992 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19993 ;; OK, we need to take a closer look
19994 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19995 (invisible-before-point (unless (bobp) (get-char-property
19996 (1- (point)) 'invisible)))
19997 (border-and-ok-direction
19999 ;; Check if we are acting predictably before invisible text
20000 (and invisible-at-point (not invisible-before-point)
20001 (memq kind '(insert delete-backward)))
20002 ;; Check if we are acting predictably after invisible text
20003 ;; This works not well, and I have turned it off. It seems
20004 ;; better to always show and stop after invisible text.
20005 ;; (and (not invisible-at-point) invisible-before-point
20006 ;; (memq kind '(insert delete)))
20008 (when (or (memq invisible-at-point '(outline org-hide-block t))
20009 (memq invisible-before-point '(outline org-hide-block t)))
20010 (when (eq org-catch-invisible-edits 'error)
20011 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20012 (if (and org-custom-properties-overlays
20013 (y-or-n-p "Display invisible properties in this buffer? "))
20014 (org-toggle-custom-properties-visibility)
20015 ;; Make the area visible
20016 (save-excursion
20017 (when invisible-before-point
20018 (goto-char (previous-single-char-property-change
20019 (point) 'invisible)))
20020 (outline-show-subtree))
20021 (cond
20022 ((eq org-catch-invisible-edits 'show)
20023 ;; That's it, we do the edit after showing
20024 (message
20025 "Unfolding invisible region around point before editing")
20026 (sit-for 1))
20027 ((and (eq org-catch-invisible-edits 'smart)
20028 border-and-ok-direction)
20029 (message "Unfolding invisible region around point before editing"))
20031 ;; Don't do the edit, make the user repeat it in full visibility
20032 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20034 (defun org-fix-tags-on-the-fly ()
20035 "Align tags in headline at point.
20036 Unlike to `org-set-tags', it ignores region and sorting."
20037 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20038 (org-at-heading-p))
20039 (let ((org-ignore-region t)
20040 (org-tags-sort-function nil))
20041 (org-set-tags nil t))))
20043 (defun org-delete-backward-char (N)
20044 "Like `delete-backward-char', insert whitespace at field end in tables.
20045 When deleting backwards, in tables this function will insert whitespace in
20046 front of the next \"|\" separator, to keep the table aligned. The table will
20047 still be marked for re-alignment if the field did fill the entire column,
20048 because, in this case the deletion might narrow the column."
20049 (interactive "p")
20050 (save-match-data
20051 (org-check-before-invisible-edit 'delete-backward)
20052 (if (and (org-at-table-p)
20053 (eq N 1)
20054 (string-match "|" (buffer-substring (point-at-bol) (point)))
20055 (looking-at ".*?|"))
20056 (let ((pos (point))
20057 (noalign (looking-at "[^|\n\r]* |"))
20058 (c org-table-may-need-update))
20059 (backward-delete-char N)
20060 (unless overwrite-mode
20061 (skip-chars-forward "^|")
20062 (insert " ")
20063 (goto-char (1- pos)))
20064 ;; noalign: if there were two spaces at the end, this field
20065 ;; does not determine the width of the column.
20066 (when noalign (setq org-table-may-need-update c)))
20067 (backward-delete-char N)
20068 (org-fix-tags-on-the-fly))))
20070 (defun org-delete-char (N)
20071 "Like `delete-char', but insert whitespace at field end in tables.
20072 When deleting characters, in tables this function will insert whitespace in
20073 front of the next \"|\" separator, to keep the table aligned. The table will
20074 still be marked for re-alignment if the field did fill the entire column,
20075 because, in this case the deletion might narrow the column."
20076 (interactive "p")
20077 (save-match-data
20078 (org-check-before-invisible-edit 'delete)
20079 (if (and (org-at-table-p)
20080 (not (bolp))
20081 (not (= (char-after) ?|))
20082 (eq N 1))
20083 (if (looking-at ".*?|")
20084 (let ((pos (point))
20085 (noalign (looking-at "[^|\n\r]* |"))
20086 (c org-table-may-need-update))
20087 (replace-match
20088 (concat (substring (match-string 0) 1 -1) " |") nil t)
20089 (goto-char pos)
20090 ;; noalign: if there were two spaces at the end, this field
20091 ;; does not determine the width of the column.
20092 (when noalign (setq org-table-may-need-update c)))
20093 (delete-char N))
20094 (delete-char N)
20095 (org-fix-tags-on-the-fly))))
20097 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20098 (put 'org-self-insert-command 'delete-selection
20099 (lambda ()
20100 (not (run-hook-with-args-until-success
20101 'self-insert-uses-region-functions))))
20102 (put 'orgtbl-self-insert-command 'delete-selection
20103 (lambda ()
20104 (not (run-hook-with-args-until-success
20105 'self-insert-uses-region-functions))))
20106 (put 'org-delete-char 'delete-selection 'supersede)
20107 (put 'org-delete-backward-char 'delete-selection 'supersede)
20108 (put 'org-yank 'delete-selection 'yank)
20110 ;; Make `flyspell-mode' delay after some commands
20111 (put 'org-self-insert-command 'flyspell-delayed t)
20112 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20113 (put 'org-delete-char 'flyspell-delayed t)
20114 (put 'org-delete-backward-char 'flyspell-delayed t)
20116 ;; Make pabbrev-mode expand after Org mode commands
20117 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20118 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20120 (defun org-remap (map &rest commands)
20121 "In MAP, remap the functions given in COMMANDS.
20122 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20123 (let (new old)
20124 (while commands
20125 (setq old (pop commands) new (pop commands))
20126 (org-defkey map (vector 'remap old) new))))
20128 (defun org-transpose-words ()
20129 "Transpose words for Org.
20130 This uses the `org-mode-transpose-word-syntax-table' syntax
20131 table, which interprets characters in `org-emphasis-alist' as
20132 word constituents."
20133 (interactive)
20134 (with-syntax-table org-mode-transpose-word-syntax-table
20135 (call-interactively 'transpose-words)))
20136 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20138 (when (eq org-enable-table-editor 'optimized)
20139 ;; If the user wants maximum table support, we need to hijack
20140 ;; some standard editing functions
20141 (org-remap org-mode-map
20142 'self-insert-command 'org-self-insert-command
20143 'delete-char 'org-delete-char
20144 'delete-backward-char 'org-delete-backward-char)
20145 (org-defkey org-mode-map "|" 'org-force-self-insert))
20147 (defvar org-ctrl-c-ctrl-c-hook nil
20148 "Hook for functions attaching themselves to `C-c C-c'.
20150 This can be used to add additional functionality to the C-c C-c
20151 key which executes context-dependent commands. This hook is run
20152 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20153 run after the last test.
20155 Each function will be called with no arguments. The function
20156 must check if the context is appropriate for it to act. If yes,
20157 it should do its thing and then return a non-nil value. If the
20158 context is wrong, just do nothing and return nil.")
20160 (defvar org-ctrl-c-ctrl-c-final-hook nil
20161 "Hook for functions attaching themselves to `C-c C-c'.
20163 This can be used to add additional functionality to the C-c C-c
20164 key which executes context-dependent commands. This hook is run
20165 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20166 before the first test.
20168 Each function will be called with no arguments. The function
20169 must check if the context is appropriate for it to act. If yes,
20170 it should do its thing and then return a non-nil value. If the
20171 context is wrong, just do nothing and return nil.")
20173 (defvar org-tab-first-hook nil
20174 "Hook for functions to attach themselves to TAB.
20175 See `org-ctrl-c-ctrl-c-hook' for more information.
20176 This hook runs as the first action when TAB is pressed, even before
20177 `org-cycle' messes around with the `outline-regexp' to cater for
20178 inline tasks and plain list item folding.
20179 If any function in this hook returns t, any other actions that
20180 would have been caused by TAB (such as table field motion or visibility
20181 cycling) will not occur.")
20183 (defvar org-tab-after-check-for-table-hook nil
20184 "Hook for functions to attach themselves to TAB.
20185 See `org-ctrl-c-ctrl-c-hook' for more information.
20186 This hook runs after it has been established that the cursor is not in a
20187 table, but before checking if the cursor is in a headline or if global cycling
20188 should be done.
20189 If any function in this hook returns t, not other actions like visibility
20190 cycling will be done.")
20192 (defvar org-tab-after-check-for-cycling-hook nil
20193 "Hook for functions to attach themselves to TAB.
20194 See `org-ctrl-c-ctrl-c-hook' for more information.
20195 This hook runs after it has been established that not table field motion and
20196 not visibility should be done because of current context. This is probably
20197 the place where a package like yasnippets can hook in.")
20199 (defvar org-tab-before-tab-emulation-hook nil
20200 "Hook for functions to attach themselves to TAB.
20201 See `org-ctrl-c-ctrl-c-hook' for more information.
20202 This hook runs after every other options for TAB have been exhausted, but
20203 before indentation and \t insertion takes place.")
20205 (defvar org-metaleft-hook nil
20206 "Hook for functions attaching themselves to `M-left'.
20207 See `org-ctrl-c-ctrl-c-hook' for more information.")
20208 (defvar org-metaright-hook nil
20209 "Hook for functions attaching themselves to `M-right'.
20210 See `org-ctrl-c-ctrl-c-hook' for more information.")
20211 (defvar org-metaup-hook nil
20212 "Hook for functions attaching themselves to `M-up'.
20213 See `org-ctrl-c-ctrl-c-hook' for more information.")
20214 (defvar org-metadown-hook nil
20215 "Hook for functions attaching themselves to `M-down'.
20216 See `org-ctrl-c-ctrl-c-hook' for more information.")
20217 (defvar org-shiftmetaleft-hook nil
20218 "Hook for functions attaching themselves to `M-S-left'.
20219 See `org-ctrl-c-ctrl-c-hook' for more information.")
20220 (defvar org-shiftmetaright-hook nil
20221 "Hook for functions attaching themselves to `M-S-right'.
20222 See `org-ctrl-c-ctrl-c-hook' for more information.")
20223 (defvar org-shiftmetaup-hook nil
20224 "Hook for functions attaching themselves to `M-S-up'.
20225 See `org-ctrl-c-ctrl-c-hook' for more information.")
20226 (defvar org-shiftmetadown-hook nil
20227 "Hook for functions attaching themselves to `M-S-down'.
20228 See `org-ctrl-c-ctrl-c-hook' for more information.")
20229 (defvar org-metareturn-hook nil
20230 "Hook for functions attaching themselves to `M-RET'.
20231 See `org-ctrl-c-ctrl-c-hook' for more information.")
20232 (defvar org-shiftup-hook nil
20233 "Hook for functions attaching themselves to `S-up'.
20234 See `org-ctrl-c-ctrl-c-hook' for more information.")
20235 (defvar org-shiftup-final-hook nil
20236 "Hook for functions attaching themselves to `S-up'.
20237 This one runs after all other options except shift-select have been excluded.
20238 See `org-ctrl-c-ctrl-c-hook' for more information.")
20239 (defvar org-shiftdown-hook nil
20240 "Hook for functions attaching themselves to `S-down'.
20241 See `org-ctrl-c-ctrl-c-hook' for more information.")
20242 (defvar org-shiftdown-final-hook nil
20243 "Hook for functions attaching themselves to `S-down'.
20244 This one runs after all other options except shift-select have been excluded.
20245 See `org-ctrl-c-ctrl-c-hook' for more information.")
20246 (defvar org-shiftleft-hook nil
20247 "Hook for functions attaching themselves to `S-left'.
20248 See `org-ctrl-c-ctrl-c-hook' for more information.")
20249 (defvar org-shiftleft-final-hook nil
20250 "Hook for functions attaching themselves to `S-left'.
20251 This one runs after all other options except shift-select have been excluded.
20252 See `org-ctrl-c-ctrl-c-hook' for more information.")
20253 (defvar org-shiftright-hook nil
20254 "Hook for functions attaching themselves to `S-right'.
20255 See `org-ctrl-c-ctrl-c-hook' for more information.")
20256 (defvar org-shiftright-final-hook nil
20257 "Hook for functions attaching themselves to `S-right'.
20258 This one runs after all other options except shift-select have been excluded.
20259 See `org-ctrl-c-ctrl-c-hook' for more information.")
20261 (defun org-modifier-cursor-error ()
20262 "Throw an error, a modified cursor command was applied in wrong context."
20263 (user-error "This command is active in special context like tables, headlines or items"))
20265 (defun org-shiftselect-error ()
20266 "Throw an error because Shift-Cursor command was applied in wrong context."
20267 (if (and (boundp 'shift-select-mode) shift-select-mode)
20268 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20269 (user-error "This command works only in special context like headlines or timestamps")))
20271 (defun org-call-for-shift-select (cmd)
20272 (let ((this-command-keys-shift-translated t))
20273 (call-interactively cmd)))
20275 (defun org-shifttab (&optional arg)
20276 "Global visibility cycling or move to previous table field.
20277 Call `org-table-previous-field' within a table.
20278 When ARG is nil, cycle globally through visibility states.
20279 When ARG is a numeric prefix, show contents of this level."
20280 (interactive "P")
20281 (cond
20282 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20283 ((integerp arg)
20284 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20285 (message "Content view to level: %d" arg)
20286 (org-content (prefix-numeric-value arg2))
20287 (org-cycle-show-empty-lines t)
20288 (setq org-cycle-global-status 'overview)))
20289 (t (call-interactively 'org-global-cycle))))
20291 (defun org-shiftmetaleft ()
20292 "Promote subtree or delete table column.
20293 Calls `org-promote-subtree', `org-outdent-item-tree', or
20294 `org-table-delete-column', depending on context. See the
20295 individual commands for more information."
20296 (interactive)
20297 (cond
20298 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20299 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20300 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20301 ((if (not (org-region-active-p)) (org-at-item-p)
20302 (save-excursion (goto-char (region-beginning))
20303 (org-at-item-p)))
20304 (call-interactively 'org-outdent-item-tree))
20305 (t (org-modifier-cursor-error))))
20307 (defun org-shiftmetaright ()
20308 "Demote subtree or insert table column.
20309 Calls `org-demote-subtree', `org-indent-item-tree', or
20310 `org-table-insert-column', depending on context. See the
20311 individual commands for more information."
20312 (interactive)
20313 (cond
20314 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20315 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20316 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20317 ((if (not (org-region-active-p)) (org-at-item-p)
20318 (save-excursion (goto-char (region-beginning))
20319 (org-at-item-p)))
20320 (call-interactively 'org-indent-item-tree))
20321 (t (org-modifier-cursor-error))))
20323 (defun org-shiftmetaup (&optional _arg)
20324 "Drag the line at point up.
20325 In a table, kill the current row.
20326 On a clock timestamp, update the value of the timestamp like `S-<up>'
20327 but also adjust the previous clocked item in the clock history.
20328 Everywhere else, drag the line at point up."
20329 (interactive "P")
20330 (cond
20331 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20332 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20333 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20334 (call-interactively 'org-timestamp-up)))
20335 (t (call-interactively 'org-drag-line-backward))))
20337 (defun org-shiftmetadown (&optional _arg)
20338 "Drag the line at point down.
20339 In a table, insert an empty row at the current line.
20340 On a clock timestamp, update the value of the timestamp like `S-<down>'
20341 but also adjust the previous clocked item in the clock history.
20342 Everywhere else, drag the line at point down."
20343 (interactive "P")
20344 (cond
20345 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20346 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20347 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20348 (call-interactively 'org-timestamp-down)))
20349 (t (call-interactively 'org-drag-line-forward))))
20351 (defsubst org-hidden-tree-error ()
20352 (user-error
20353 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20355 (defun org-metaleft (&optional _arg)
20356 "Promote heading, list item at point or move table column left.
20358 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20359 depending on context. With no specific context, calls the Emacs
20360 default `backward-word'. See the individual commands for more
20361 information.
20363 This function runs the hook `org-metaleft-hook' as a first step,
20364 and returns at first non-nil value."
20365 (interactive "P")
20366 (cond
20367 ((run-hook-with-args-until-success 'org-metaleft-hook))
20368 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20369 ((org-with-limited-levels
20370 (or (org-at-heading-p)
20371 (and (org-region-active-p)
20372 (save-excursion
20373 (goto-char (region-beginning))
20374 (org-at-heading-p)))))
20375 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20376 (call-interactively 'org-do-promote))
20377 ;; At an inline task.
20378 ((org-at-heading-p)
20379 (call-interactively 'org-inlinetask-promote))
20380 ((or (org-at-item-p)
20381 (and (org-region-active-p)
20382 (save-excursion
20383 (goto-char (region-beginning))
20384 (org-at-item-p))))
20385 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20386 (call-interactively 'org-outdent-item))
20387 (t (call-interactively 'backward-word))))
20389 (defun org-metaright (&optional _arg)
20390 "Demote heading, list item at point or move table column right.
20392 In front of a drawer or a block keyword, indent it correctly.
20394 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20395 `org-indent-drawer' or `org-indent-block' depending on context.
20396 With no specific context, calls the Emacs default `forward-word'.
20397 See the individual commands for more information.
20399 This function runs the hook `org-metaright-hook' as a first step,
20400 and returns at first non-nil value."
20401 (interactive "P")
20402 (cond
20403 ((run-hook-with-args-until-success 'org-metaright-hook))
20404 ((org-at-table-p) (call-interactively 'org-table-move-column))
20405 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20406 ((org-at-block-p) (call-interactively 'org-indent-block))
20407 ((org-with-limited-levels
20408 (or (org-at-heading-p)
20409 (and (org-region-active-p)
20410 (save-excursion
20411 (goto-char (region-beginning))
20412 (org-at-heading-p)))))
20413 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20414 (call-interactively 'org-do-demote))
20415 ;; At an inline task.
20416 ((org-at-heading-p)
20417 (call-interactively 'org-inlinetask-demote))
20418 ((or (org-at-item-p)
20419 (and (org-region-active-p)
20420 (save-excursion
20421 (goto-char (region-beginning))
20422 (org-at-item-p))))
20423 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20424 (call-interactively 'org-indent-item))
20425 (t (call-interactively 'forward-word))))
20427 (defun org-check-for-hidden (what)
20428 "Check if there are hidden headlines/items in the current visual line.
20429 WHAT can be either `headlines' or `items'. If the current line is
20430 an outline or item heading and it has a folded subtree below it,
20431 this function returns t, nil otherwise."
20432 (let ((re (cond
20433 ((eq what 'headlines) org-outline-regexp-bol)
20434 ((eq what 'items) (org-item-beginning-re))
20435 (t (error "This should not happen"))))
20436 beg end)
20437 (save-excursion
20438 (catch 'exit
20439 (unless (org-region-active-p)
20440 (setq beg (point-at-bol))
20441 (beginning-of-line 2)
20442 (while (and (not (eobp)) ;; this is like `next-line'
20443 (get-char-property (1- (point)) 'invisible))
20444 (beginning-of-line 2))
20445 (setq end (point))
20446 (goto-char beg)
20447 (goto-char (point-at-eol))
20448 (setq end (max end (point)))
20449 (while (re-search-forward re end t)
20450 (when (get-char-property (match-beginning 0) 'invisible)
20451 (throw 'exit t))))
20452 nil))))
20454 (defun org-metaup (&optional _arg)
20455 "Move subtree up or move table row up.
20456 Calls `org-move-subtree-up' or `org-table-move-row' or
20457 `org-move-item-up', depending on context. See the individual commands
20458 for more information."
20459 (interactive "P")
20460 (cond
20461 ((run-hook-with-args-until-success 'org-metaup-hook))
20462 ((org-region-active-p)
20463 (let* ((a (min (region-beginning) (region-end)))
20464 (b (1- (max (region-beginning) (region-end))))
20465 (c (save-excursion (goto-char a)
20466 (move-beginning-of-line 0)))
20467 (d (save-excursion (goto-char a)
20468 (move-end-of-line 0) (point))))
20469 (transpose-regions a b c d)
20470 (goto-char c)))
20471 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20472 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20473 ((org-at-item-p) (call-interactively 'org-move-item-up))
20474 (t (org-drag-element-backward))))
20476 (defun org-metadown (&optional _arg)
20477 "Move subtree down or move table row down.
20478 Calls `org-move-subtree-down' or `org-table-move-row' or
20479 `org-move-item-down', depending on context. See the individual
20480 commands for more information."
20481 (interactive "P")
20482 (cond
20483 ((run-hook-with-args-until-success 'org-metadown-hook))
20484 ((org-region-active-p)
20485 (let* ((a (min (region-beginning) (region-end)))
20486 (b (max (region-beginning) (region-end)))
20487 (c (save-excursion (goto-char b)
20488 (move-beginning-of-line 1)))
20489 (d (save-excursion (goto-char b)
20490 (move-end-of-line 1) (1+ (point)))))
20491 (transpose-regions a b c d)
20492 (goto-char d)))
20493 ((org-at-table-p) (call-interactively 'org-table-move-row))
20494 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20495 ((org-at-item-p) (call-interactively 'org-move-item-down))
20496 (t (org-drag-element-forward))))
20498 (defun org-shiftup (&optional arg)
20499 "Increase item in timestamp or increase priority of current headline.
20500 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20501 depending on context. See the individual commands for more information."
20502 (interactive "P")
20503 (cond
20504 ((run-hook-with-args-until-success 'org-shiftup-hook))
20505 ((and org-support-shift-select (org-region-active-p))
20506 (org-call-for-shift-select 'previous-line))
20507 ((org-at-timestamp-p 'lax)
20508 (call-interactively (if org-edit-timestamp-down-means-later
20509 'org-timestamp-down 'org-timestamp-up)))
20510 ((and (not (eq org-support-shift-select 'always))
20511 org-enable-priority-commands
20512 (org-at-heading-p))
20513 (call-interactively 'org-priority-up))
20514 ((and (not org-support-shift-select) (org-at-item-p))
20515 (call-interactively 'org-previous-item))
20516 ((org-clocktable-try-shift 'up arg))
20517 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20518 (org-support-shift-select
20519 (org-call-for-shift-select 'previous-line))
20520 (t (org-shiftselect-error))))
20522 (defun org-shiftdown (&optional arg)
20523 "Decrease item in timestamp or decrease priority of current headline.
20524 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20525 depending on context. See the individual commands for more information."
20526 (interactive "P")
20527 (cond
20528 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20529 ((and org-support-shift-select (org-region-active-p))
20530 (org-call-for-shift-select 'next-line))
20531 ((org-at-timestamp-p 'lax)
20532 (call-interactively (if org-edit-timestamp-down-means-later
20533 'org-timestamp-up 'org-timestamp-down)))
20534 ((and (not (eq org-support-shift-select 'always))
20535 org-enable-priority-commands
20536 (org-at-heading-p))
20537 (call-interactively 'org-priority-down))
20538 ((and (not org-support-shift-select) (org-at-item-p))
20539 (call-interactively 'org-next-item))
20540 ((org-clocktable-try-shift 'down arg))
20541 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20542 (org-support-shift-select
20543 (org-call-for-shift-select 'next-line))
20544 (t (org-shiftselect-error))))
20546 (defun org-shiftright (&optional arg)
20547 "Cycle the thing at point or in the current line, depending on context.
20548 Depending on context, this does one of the following:
20550 - switch a timestamp at point one day into the future
20551 - on a headline, switch to the next TODO keyword.
20552 - on an item, switch entire list to the next bullet type
20553 - on a property line, switch to the next allowed value
20554 - on a clocktable definition line, move time block into the future"
20555 (interactive "P")
20556 (cond
20557 ((run-hook-with-args-until-success 'org-shiftright-hook))
20558 ((and org-support-shift-select (org-region-active-p))
20559 (org-call-for-shift-select 'forward-char))
20560 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20561 ((and (not (eq org-support-shift-select 'always))
20562 (org-at-heading-p))
20563 (let ((org-inhibit-logging
20564 (not org-treat-S-cursor-todo-selection-as-state-change))
20565 (org-inhibit-blocking
20566 (not org-treat-S-cursor-todo-selection-as-state-change)))
20567 (org-call-with-arg 'org-todo 'right)))
20568 ((or (and org-support-shift-select
20569 (not (eq org-support-shift-select 'always))
20570 (org-at-item-bullet-p))
20571 (and (not org-support-shift-select) (org-at-item-p)))
20572 (org-call-with-arg 'org-cycle-list-bullet nil))
20573 ((and (not (eq org-support-shift-select 'always))
20574 (org-at-property-p))
20575 (call-interactively 'org-property-next-allowed-value))
20576 ((org-clocktable-try-shift 'right arg))
20577 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20578 (org-support-shift-select
20579 (org-call-for-shift-select 'forward-char))
20580 (t (org-shiftselect-error))))
20582 (defun org-shiftleft (&optional arg)
20583 "Cycle the thing at point or in the current line, depending on context.
20584 Depending on context, this does one of the following:
20586 - switch a timestamp at point one day into the past
20587 - on a headline, switch to the previous TODO keyword.
20588 - on an item, switch entire list to the previous bullet type
20589 - on a property line, switch to the previous allowed value
20590 - on a clocktable definition line, move time block into the past"
20591 (interactive "P")
20592 (cond
20593 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20594 ((and org-support-shift-select (org-region-active-p))
20595 (org-call-for-shift-select 'backward-char))
20596 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20597 ((and (not (eq org-support-shift-select 'always))
20598 (org-at-heading-p))
20599 (let ((org-inhibit-logging
20600 (not org-treat-S-cursor-todo-selection-as-state-change))
20601 (org-inhibit-blocking
20602 (not org-treat-S-cursor-todo-selection-as-state-change)))
20603 (org-call-with-arg 'org-todo 'left)))
20604 ((or (and org-support-shift-select
20605 (not (eq org-support-shift-select 'always))
20606 (org-at-item-bullet-p))
20607 (and (not org-support-shift-select) (org-at-item-p)))
20608 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20609 ((and (not (eq org-support-shift-select 'always))
20610 (org-at-property-p))
20611 (call-interactively 'org-property-previous-allowed-value))
20612 ((org-clocktable-try-shift 'left arg))
20613 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20614 (org-support-shift-select
20615 (org-call-for-shift-select 'backward-char))
20616 (t (org-shiftselect-error))))
20618 (defun org-shiftcontrolright ()
20619 "Switch to next TODO set."
20620 (interactive)
20621 (cond
20622 ((and org-support-shift-select (org-region-active-p))
20623 (org-call-for-shift-select 'forward-word))
20624 ((and (not (eq org-support-shift-select 'always))
20625 (org-at-heading-p))
20626 (org-call-with-arg 'org-todo 'nextset))
20627 (org-support-shift-select
20628 (org-call-for-shift-select 'forward-word))
20629 (t (org-shiftselect-error))))
20631 (defun org-shiftcontrolleft ()
20632 "Switch to previous TODO set."
20633 (interactive)
20634 (cond
20635 ((and org-support-shift-select (org-region-active-p))
20636 (org-call-for-shift-select 'backward-word))
20637 ((and (not (eq org-support-shift-select 'always))
20638 (org-at-heading-p))
20639 (org-call-with-arg 'org-todo 'previousset))
20640 (org-support-shift-select
20641 (org-call-for-shift-select 'backward-word))
20642 (t (org-shiftselect-error))))
20644 (defun org-shiftcontrolup (&optional n)
20645 "Change timestamps synchronously up in CLOCK log lines.
20646 Optional argument N tells to change by that many units."
20647 (interactive "P")
20648 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20649 (let (org-support-shift-select)
20650 (org-clock-timestamps-up n))
20651 (user-error "Not at a clock log")))
20653 (defun org-shiftcontroldown (&optional n)
20654 "Change timestamps synchronously down in CLOCK log lines.
20655 Optional argument N tells to change by that many units."
20656 (interactive "P")
20657 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20658 (let (org-support-shift-select)
20659 (org-clock-timestamps-down n))
20660 (user-error "Not at a clock log")))
20662 (defun org-increase-number-at-point (&optional inc)
20663 "Increment the number at point.
20664 With an optional prefix numeric argument INC, increment using
20665 this numeric value."
20666 (interactive "p")
20667 (if (not (number-at-point))
20668 (user-error "Not on a number")
20669 (unless inc (setq inc 1))
20670 (let ((pos (point))
20671 (beg (skip-chars-backward "-+^/*0-9eE."))
20672 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20673 (setq nap (buffer-substring-no-properties
20674 (+ pos beg) (+ pos beg end)))
20675 (delete-region (+ pos beg) (+ pos beg end))
20676 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20677 (when (org-at-table-p)
20678 (org-table-align)
20679 (org-table-end-of-field 1))))
20681 (defun org-decrease-number-at-point (&optional inc)
20682 "Decrement the number at point.
20683 With an optional prefix numeric argument INC, decrement using
20684 this numeric value."
20685 (interactive "p")
20686 (org-increase-number-at-point (- (or inc 1))))
20688 (defun org-ctrl-c-ret ()
20689 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20690 (interactive)
20691 (cond
20692 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20693 (t (call-interactively 'org-insert-heading))))
20695 (defun org-find-visible ()
20696 (let ((s (point)))
20697 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20698 (get-char-property s 'invisible)))
20700 (defun org-find-invisible ()
20701 (let ((s (point)))
20702 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20703 (not (get-char-property s 'invisible))))
20706 (defun org-copy-visible (beg end)
20707 "Copy the visible parts of the region."
20708 (interactive "r")
20709 (let (snippets s)
20710 (save-excursion
20711 (save-restriction
20712 (narrow-to-region beg end)
20713 (setq s (goto-char (point-min)))
20714 (while (not (= (point) (point-max)))
20715 (goto-char (org-find-invisible))
20716 (push (buffer-substring s (point)) snippets)
20717 (setq s (goto-char (org-find-visible))))))
20718 (kill-new (apply 'concat (nreverse snippets)))))
20720 (defun org-copy-special ()
20721 "Copy region in table or copy current subtree.
20722 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20723 context. See the individual commands for more information."
20724 (interactive)
20725 (call-interactively
20726 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20728 (defun org-cut-special ()
20729 "Cut region in table or cut current subtree.
20730 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20731 context. See the individual commands for more information."
20732 (interactive)
20733 (call-interactively
20734 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20736 (defun org-paste-special (arg)
20737 "Paste rectangular region into table, or past subtree relative to level.
20738 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20739 See the individual commands for more information."
20740 (interactive "P")
20741 (if (org-at-table-p)
20742 (org-table-paste-rectangle)
20743 (org-paste-subtree arg)))
20745 (defun org-edit-special (&optional arg)
20746 "Call a special editor for the element at point.
20747 When at a table, call the formula editor with `org-table-edit-formulas'.
20748 When in a source code block, call `org-edit-src-code'.
20749 When in a fixed-width region, call `org-edit-fixed-width-region'.
20750 When in an export block, call `org-edit-export-block'.
20751 When in a LaTeX environment, call `org-edit-latex-environment'.
20752 When at an #+INCLUDE keyword, visit the included file.
20753 When at a footnote reference, call `org-edit-footnote-reference'
20754 On a link, call `ffap' to visit the link at point.
20755 Otherwise, return a user error."
20756 (interactive "P")
20757 (let ((element (org-element-at-point)))
20758 (barf-if-buffer-read-only)
20759 (pcase (org-element-type element)
20760 (`src-block
20761 (if (not arg) (org-edit-src-code)
20762 (let* ((info (org-babel-get-src-block-info))
20763 (lang (nth 0 info))
20764 (params (nth 2 info))
20765 (session (cdr (assq :session params))))
20766 (if (not session) (org-edit-src-code)
20767 ;; At a src-block with a session and function called with
20768 ;; an ARG: switch to the buffer related to the inferior
20769 ;; process.
20770 (switch-to-buffer
20771 (funcall (intern (concat "org-babel-prep-session:" lang))
20772 session params))))))
20773 (`keyword
20774 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20775 (org-open-link-from-string
20776 (format "[[%s]]"
20777 (expand-file-name
20778 (let ((value (org-element-property :value element)))
20779 (cond ((not (org-string-nw-p value))
20780 (user-error "No file to edit"))
20781 ((string-match "\\`\"\\(.*?\\)\"" value)
20782 (match-string 1 value))
20783 ((string-match "\\`[^ \t\"]\\S-*" value)
20784 (match-string 0 value))
20785 (t (user-error "No valid file specified")))))))
20786 (user-error "No special environment to edit here")))
20787 (`table
20788 (if (eq (org-element-property :type element) 'table.el)
20789 (org-edit-table.el)
20790 (call-interactively 'org-table-edit-formulas)))
20791 ;; Only Org tables contain `table-row' type elements.
20792 (`table-row (call-interactively 'org-table-edit-formulas))
20793 (`example-block (org-edit-src-code))
20794 (`export-block (org-edit-export-block))
20795 (`fixed-width (org-edit-fixed-width-region))
20796 (`latex-environment (org-edit-latex-environment))
20798 ;; No notable element at point. Though, we may be at a link or
20799 ;; a footnote reference, which are objects. Thus, scan deeper.
20800 (let ((context (org-element-context element)))
20801 (pcase (org-element-type context)
20802 (`footnote-reference (org-edit-footnote-reference))
20803 (`inline-src-block (org-edit-inline-src-code))
20804 (`link (call-interactively #'ffap))
20805 (_ (user-error "No special environment to edit here"))))))))
20807 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20808 (defun org-ctrl-c-ctrl-c (&optional arg)
20809 "Set tags in headline, or update according to changed information at point.
20811 This command does many different things, depending on context:
20813 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20814 this is what we do.
20816 - If the cursor is on a statistics cookie, update it.
20818 - If the cursor is in a headline, prompt for tags and insert them
20819 into the current line, aligned to `org-tags-column'. When called
20820 with prefix arg, realign all tags in the current buffer.
20822 - If the cursor is in one of the special #+KEYWORD lines, this
20823 triggers scanning the buffer for these lines and updating the
20824 information.
20826 - If the cursor is inside a table, realign the table. This command
20827 works even if the automatic table editor has been turned off.
20829 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20830 the entire table.
20832 - If the cursor is at a footnote reference or definition, jump to
20833 the corresponding definition or references, respectively.
20835 - If the cursor is a the beginning of a dynamic block, update it.
20837 - If the current buffer is a capture buffer, close note and file it.
20839 - If the cursor is on a <<<target>>>, update radio targets and
20840 corresponding links in this buffer.
20842 - If the cursor is on a numbered item in a plain list, renumber the
20843 ordered list.
20845 - If the cursor is on a checkbox, toggle it.
20847 - If the cursor is on a code block, evaluate it. The variable
20848 `org-confirm-babel-evaluate' can be used to control prompting
20849 before code block evaluation, by default every code block
20850 evaluation requires confirmation. Code block evaluation can be
20851 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20852 (interactive "P")
20853 (cond
20854 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20855 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20856 (org-remove-occur-highlights)
20857 (message "Temporary highlights/overlays removed from current buffer"))
20858 ((and (local-variable-p 'org-finish-function)
20859 (fboundp org-finish-function))
20860 (funcall org-finish-function))
20861 ((org-babel-hash-at-point))
20862 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20864 (let* ((context
20865 (org-element-lineage
20866 (org-element-context)
20867 ;; Limit to supported contexts.
20868 '(babel-call clock dynamic-block footnote-definition
20869 footnote-reference inline-babel-call inline-src-block
20870 inlinetask item keyword node-property paragraph
20871 plain-list property-drawer radio-target src-block
20872 statistics-cookie table table-cell table-row
20873 timestamp)
20875 (type (org-element-type context)))
20876 ;; For convenience: at the first line of a paragraph on the same
20877 ;; line as an item, apply function on that item instead.
20878 (when (eq type 'paragraph)
20879 (let ((parent (org-element-property :parent context)))
20880 (when (and (eq (org-element-type parent) 'item)
20881 (= (line-beginning-position)
20882 (org-element-property :begin parent)))
20883 (setq context parent)
20884 (setq type 'item))))
20885 ;; Act according to type of element or object at point.
20887 ;; Do nothing on a blank line, except if it is contained in
20888 ;; a src block. Hence, we first check if point is in such
20889 ;; a block and then if it is at a blank line.
20890 (pcase type
20891 ((or `inline-src-block `src-block)
20892 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20893 (org-babel-eval-wipe-error-buffer)
20894 (org-babel-execute-src-block
20895 current-prefix-arg (org-babel-get-src-block-info nil context))))
20896 ((guard (org-match-line "[ \t]*$"))
20897 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20898 (user-error
20899 (substitute-command-keys
20900 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20901 ((or `babel-call `inline-babel-call)
20902 (let ((info (org-babel-lob-get-info context)))
20903 (when info (org-babel-execute-src-block nil info))))
20904 (`clock (org-clock-update-time-maybe))
20905 (`dynamic-block
20906 (save-excursion
20907 (goto-char (org-element-property :post-affiliated context))
20908 (org-update-dblock)))
20909 (`footnote-definition
20910 (goto-char (org-element-property :post-affiliated context))
20911 (call-interactively 'org-footnote-action))
20912 (`footnote-reference (call-interactively #'org-footnote-action))
20913 ((or `headline `inlinetask)
20914 (save-excursion (goto-char (org-element-property :begin context))
20915 (call-interactively #'org-set-tags)))
20916 (`item
20917 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20918 ;; unconditionally, whereas `C-u' will toggle its presence.
20919 ;; Without a universal argument, if the item has a checkbox,
20920 ;; toggle it. Otherwise repair the list.
20921 (let* ((box (org-element-property :checkbox context))
20922 (struct (org-element-property :structure context))
20923 (old-struct (copy-tree struct))
20924 (parents (org-list-parents-alist struct))
20925 (prevs (org-list-prevs-alist struct))
20926 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20927 (org-list-set-checkbox
20928 (org-element-property :begin context) struct
20929 (cond ((equal arg '(16)) "[-]")
20930 ((and (not box) (equal arg '(4))) "[ ]")
20931 ((or (not box) (equal arg '(4))) nil)
20932 ((eq box 'on) "[ ]")
20933 (t "[X]")))
20934 ;; Mimic `org-list-write-struct' but with grabbing a return
20935 ;; value from `org-list-struct-fix-box'.
20936 (org-list-struct-fix-ind struct parents 2)
20937 (org-list-struct-fix-item-end struct)
20938 (org-list-struct-fix-bul struct prevs)
20939 (org-list-struct-fix-ind struct parents)
20940 (let ((block-item
20941 (org-list-struct-fix-box struct parents prevs orderedp)))
20942 (if (and box (equal struct old-struct))
20943 (if (equal arg '(16))
20944 (message "Checkboxes already reset")
20945 (user-error "Cannot toggle this checkbox: %s"
20946 (if (eq box 'on)
20947 "all subitems checked"
20948 "unchecked subitems")))
20949 (org-list-struct-apply-struct struct old-struct)
20950 (org-update-checkbox-count-maybe))
20951 (when block-item
20952 (message "Checkboxes were removed due to empty box at line %d"
20953 (org-current-line block-item))))))
20954 (`keyword
20955 (let ((org-inhibit-startup-visibility-stuff t)
20956 (org-startup-align-all-tables nil))
20957 (when (boundp 'org-table-coordinate-overlays)
20958 (mapc #'delete-overlay org-table-coordinate-overlays)
20959 (setq org-table-coordinate-overlays nil))
20960 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20961 (message "Local setup has been refreshed"))
20962 (`plain-list
20963 ;; At a plain list, with a double C-u argument, set
20964 ;; checkboxes of each item to "[-]", whereas a single one
20965 ;; will toggle their presence according to the state of the
20966 ;; first item in the list. Without an argument, repair the
20967 ;; list.
20968 (let* ((begin (org-element-property :contents-begin context))
20969 (beginm (move-marker (make-marker) begin))
20970 (struct (org-element-property :structure context))
20971 (old-struct (copy-tree struct))
20972 (first-box (save-excursion
20973 (goto-char begin)
20974 (looking-at org-list-full-item-re)
20975 (match-string-no-properties 3)))
20976 (new-box (cond ((equal arg '(16)) "[-]")
20977 ((equal arg '(4)) (unless first-box "[ ]"))
20978 ((equal first-box "[X]") "[ ]")
20979 (t "[X]"))))
20980 (cond
20981 (arg
20982 (dolist (pos
20983 (org-list-get-all-items
20984 begin struct (org-list-prevs-alist struct)))
20985 (org-list-set-checkbox pos struct new-box)))
20986 ((and first-box (eq (point) begin))
20987 ;; For convenience, when point is at bol on the first
20988 ;; item of the list and no argument is provided, simply
20989 ;; toggle checkbox of that item, if any.
20990 (org-list-set-checkbox begin struct new-box)))
20991 (org-list-write-struct
20992 struct (org-list-parents-alist struct) old-struct)
20993 (org-update-checkbox-count-maybe)
20994 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20995 ((or `property-drawer `node-property)
20996 (call-interactively #'org-property-action))
20997 (`radio-target
20998 (call-interactively #'org-update-radio-target-regexp))
20999 (`statistics-cookie
21000 (call-interactively #'org-update-statistics-cookies))
21001 ((or `table `table-cell `table-row)
21002 ;; At a table, recalculate every field and align it. Also
21003 ;; send the table if necessary. If the table has
21004 ;; a `table.el' type, just give up. At a table row or cell,
21005 ;; maybe recalculate line but always align table.
21006 (if (eq (org-element-property :type context) 'table.el)
21007 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21008 Use `\\[org-edit-special]' to edit table.el tables"))
21009 (let ((org-enable-table-editor t))
21010 (if (or (eq type 'table)
21011 ;; Check if point is at a TBLFM line.
21012 (and (eq type 'table-row)
21013 (= (point) (org-element-property :end context))))
21014 (save-excursion
21015 (if (org-at-TBLFM-p)
21016 (progn (require 'org-table)
21017 (org-table-calc-current-TBLFM))
21018 (goto-char (org-element-property :contents-begin context))
21019 (org-call-with-arg 'org-table-recalculate (or arg t))
21020 (orgtbl-send-table 'maybe)))
21021 (org-table-maybe-eval-formula)
21022 (cond (arg (call-interactively #'org-table-recalculate))
21023 ((org-table-maybe-recalculate-line))
21024 (t (org-table-align)))))))
21025 (`timestamp (org-timestamp-change 0 'day))
21026 ((and `nil (guard (org-at-heading-p)))
21027 ;; When point is on an unsupported object type, we can miss
21028 ;; the fact that it also is at a heading. Handle it here.
21029 (call-interactively #'org-set-tags))
21030 ((guard
21031 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21033 (user-error
21034 (substitute-command-keys
21035 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21037 (defun org-mode-restart ()
21038 (interactive)
21039 (let ((indent-status (bound-and-true-p org-indent-mode)))
21040 (funcall major-mode)
21041 (hack-local-variables)
21042 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21043 (org-indent-mode -1)))
21044 (message "%s restarted" major-mode))
21046 (defun org-kill-note-or-show-branches ()
21047 "Abort storing current note, or call `outline-show-branches'."
21048 (interactive)
21049 (if (not org-finish-function)
21050 (progn
21051 (outline-hide-subtree)
21052 (call-interactively 'outline-show-branches))
21053 (let ((org-note-abort t))
21054 (funcall org-finish-function))))
21056 (defun org-delete-indentation (&optional arg)
21057 "Join current line to previous and fix whitespace at join.
21059 If previous line is a headline add to headline title. Otherwise
21060 the function calls `delete-indentation'.
21062 With a non-nil optional argument, join it to the following one."
21063 (interactive "*P")
21064 (if (save-excursion
21065 (beginning-of-line (if arg 1 0))
21066 (let ((case-fold-search nil))
21067 (looking-at org-complex-heading-regexp)))
21068 ;; At headline.
21069 (let ((tags-column (when (match-beginning 5)
21070 (save-excursion (goto-char (match-beginning 5))
21071 (current-column))))
21072 (string (concat " " (progn (when arg (forward-line 1))
21073 (org-trim (delete-and-extract-region
21074 (line-beginning-position)
21075 (line-end-position)))))))
21076 (unless (bobp) (delete-region (point) (1- (point))))
21077 (goto-char (or (match-end 4)
21078 (match-beginning 5)
21079 (match-end 0)))
21080 (skip-chars-backward " \t")
21081 (save-excursion (insert string))
21082 ;; Adjust alignment of tags.
21083 (cond
21084 ((not tags-column)) ;no tags
21085 (org-auto-align-tags (org-set-tags nil t))
21086 (t (org--align-tags-here tags-column)))) ;preserve tags column
21087 (delete-indentation arg)))
21089 (defun org-open-line (n)
21090 "Insert a new row in tables, call `open-line' elsewhere.
21091 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21092 As a special case, when a document starts with a table, allow to
21093 call `open-line' on the very first character."
21094 (interactive "*p")
21095 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21096 (org-table-insert-row)
21097 (open-line n)))
21099 (defun org-return (&optional indent)
21100 "Goto next table row or insert a newline.
21102 Calls `org-table-next-row' or `newline', depending on context.
21104 When optional INDENT argument is non-nil, call
21105 `newline-and-indent' instead of `newline'.
21107 When `org-return-follows-link' is non-nil and point is on
21108 a timestamp or a link, call `org-open-at-point'. However, it
21109 will not happen if point is in a table or on a \"dead\"
21110 object (e.g., within a comment). In these case, you need to use
21111 `org-open-at-point' directly."
21112 (interactive)
21113 (let ((context (if org-return-follows-link (org-element-context)
21114 (org-element-at-point))))
21115 (cond
21116 ;; In a table, call `org-table-next-row'.
21117 ((or (and (eq (org-element-type context) 'table)
21118 (>= (point) (org-element-property :contents-begin context))
21119 (< (point) (org-element-property :contents-end context)))
21120 (org-element-lineage context '(table-row table-cell) t))
21121 (org-table-justify-field-maybe)
21122 (call-interactively #'org-table-next-row))
21123 ;; On a link or a timestamp, call `org-open-at-point' if
21124 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21125 ;; locations, e.g., in a comment, as `org-open-at-point'.
21126 ((and org-return-follows-link
21127 (or (org-in-regexp org-ts-regexp-both nil t)
21128 (org-in-regexp org-tsr-regexp-both nil t)
21129 (org-in-regexp org-any-link-re nil t)))
21130 (call-interactively #'org-open-at-point))
21131 ;; Insert newline in heading, but preserve tags.
21132 ((and (not (bolp))
21133 (save-excursion (beginning-of-line)
21134 (let ((case-fold-search nil))
21135 (looking-at org-complex-heading-regexp))))
21136 ;; At headline. Split line. However, if point is on keyword,
21137 ;; priority cookie or tags, do not break any of them: add
21138 ;; a newline after the headline instead.
21139 (let ((tags-column (and (match-beginning 5)
21140 (save-excursion (goto-char (match-beginning 5))
21141 (current-column))))
21142 (string
21143 (when (and (match-end 4) (org-point-in-group (point) 4))
21144 (delete-and-extract-region (point) (match-end 4)))))
21145 ;; Adjust tag alignment.
21146 (cond
21147 ((not (and tags-column string)))
21148 (org-auto-align-tags (org-set-tags nil t))
21149 (t (org--align-tags-here tags-column))) ;preserve tags column
21150 (end-of-line)
21151 (org-show-entry)
21152 (if indent (newline-and-indent) (newline))
21153 (when string (save-excursion (insert (org-trim string))))))
21154 ;; In a list, make sure indenting keeps trailing text within.
21155 ((and indent
21156 (not (eolp))
21157 (org-element-lineage context '(item)))
21158 (let ((trailing-data
21159 (delete-and-extract-region (point) (line-end-position))))
21160 (newline-and-indent)
21161 (save-excursion (insert trailing-data))))
21162 (t (if indent (newline-and-indent) (newline))))))
21164 (defun org-return-indent ()
21165 "Goto next table row or insert a newline and indent.
21166 Calls `org-table-next-row' or `newline-and-indent', depending on
21167 context. See the individual commands for more information."
21168 (interactive)
21169 (org-return t))
21171 (defun org-ctrl-c-star ()
21172 "Compute table, or change heading status of lines.
21173 Calls `org-table-recalculate' or `org-toggle-heading',
21174 depending on context."
21175 (interactive)
21176 (cond
21177 ((org-at-table-p)
21178 (call-interactively 'org-table-recalculate))
21180 ;; Convert all lines in region to list items
21181 (call-interactively 'org-toggle-heading))))
21183 (defun org-ctrl-c-minus ()
21184 "Insert separator line in table or modify bullet status of line.
21185 Also turns a plain line or a region of lines into list items.
21186 Calls `org-table-insert-hline', `org-toggle-item', or
21187 `org-cycle-list-bullet', depending on context."
21188 (interactive)
21189 (cond
21190 ((org-at-table-p)
21191 (call-interactively 'org-table-insert-hline))
21192 ((org-region-active-p)
21193 (call-interactively 'org-toggle-item))
21194 ((org-in-item-p)
21195 (call-interactively 'org-cycle-list-bullet))
21197 (call-interactively 'org-toggle-item))))
21199 (defun org-toggle-heading (&optional nstars)
21200 "Convert headings to normal text, or items or text to headings.
21201 If there is no active region, only convert the current line.
21203 With a `\\[universal-argument]' prefix, convert the whole list at
21204 point into heading.
21206 In a region:
21208 - If the first non blank line is a headline, remove the stars
21209 from all headlines in the region.
21211 - If it is a normal line, turn each and every normal line (i.e.,
21212 not an heading or an item) in the region into headings. If you
21213 want to convert only the first line of this region, use one
21214 universal prefix argument.
21216 - If it is a plain list item, turn all plain list items into headings.
21218 When converting a line into a heading, the number of stars is chosen
21219 such that the lines become children of the current entry. However,
21220 when a numeric prefix argument is given, its value determines the
21221 number of stars to add."
21222 (interactive "P")
21223 (let ((skip-blanks
21224 (function
21225 ;; Return beginning of first non-blank line, starting from
21226 ;; line at POS.
21227 (lambda (pos)
21228 (save-excursion
21229 (goto-char pos)
21230 (while (org-at-comment-p) (forward-line))
21231 (skip-chars-forward " \r\t\n")
21232 (point-at-bol)))))
21233 beg end toggled)
21234 ;; Determine boundaries of changes. If a universal prefix has
21235 ;; been given, put the list in a region. If region ends at a bol,
21236 ;; do not consider the last line to be in the region.
21238 (when (and current-prefix-arg (org-at-item-p))
21239 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21240 (org-mark-element))
21242 (if (org-region-active-p)
21243 (setq beg (funcall skip-blanks (region-beginning))
21244 end (copy-marker (save-excursion
21245 (goto-char (region-end))
21246 (if (bolp) (point) (point-at-eol)))))
21247 (setq beg (funcall skip-blanks (point-at-bol))
21248 end (copy-marker (point-at-eol))))
21249 ;; Ensure inline tasks don't count as headings.
21250 (org-with-limited-levels
21251 (save-excursion
21252 (goto-char beg)
21253 (cond
21254 ;; Case 1. Started at an heading: de-star headings.
21255 ((org-at-heading-p)
21256 (while (< (point) end)
21257 (when (org-at-heading-p t)
21258 (looking-at org-outline-regexp) (replace-match "")
21259 (setq toggled t))
21260 (forward-line)))
21261 ;; Case 2. Started at an item: change items into headlines.
21262 ;; One star will be added by `org-list-to-subtree'.
21263 ((org-at-item-p)
21264 (while (< (point) end)
21265 (when (org-at-item-p)
21266 ;; Pay attention to cases when region ends before list.
21267 (let* ((struct (org-list-struct))
21268 (list-end
21269 (min (org-list-get-bottom-point struct) (1+ end))))
21270 (save-restriction
21271 (narrow-to-region (point) list-end)
21272 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21273 (setq toggled t))
21274 (forward-line)))
21275 ;; Case 3. Started at normal text: make every line an heading,
21276 ;; skipping headlines and items.
21277 (t (let* ((stars
21278 (make-string
21279 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21280 (add-stars
21281 (cond (nstars "") ; stars from prefix only
21282 ((equal stars "") "*") ; before first heading
21283 (org-odd-levels-only "**") ; inside heading, odd
21284 (t "*"))) ; inside heading, oddeven
21285 (rpl (concat stars add-stars " "))
21286 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21287 (while (< (point) (if (equal nstars '(4)) lend end))
21288 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21289 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21290 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21291 (forward-line)))))))
21292 (unless toggled (message "Cannot toggle heading from here"))))
21294 (defun org-meta-return (&optional arg)
21295 "Insert a new heading or wrap a region in a table.
21296 Calls `org-insert-heading', `org-insert-item' or
21297 `org-table-wrap-region', depending on context. When called with
21298 an argument, unconditionally call `org-insert-heading'."
21299 (interactive "P")
21300 (org-check-before-invisible-edit 'insert)
21301 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21302 (call-interactively (cond (arg #'org-insert-heading)
21303 ((org-at-table-p) #'org-table-wrap-region)
21304 ((org-in-item-p) #'org-insert-item)
21305 (t #'org-insert-heading)))))
21307 ;;; Menu entries
21309 (defsubst org-in-subtree-not-table-p ()
21310 "Are we in a subtree and not in a table?"
21311 (and (not (org-before-first-heading-p))
21312 (not (org-at-table-p))))
21314 ;; Define the Org mode menus
21315 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21316 '("Tbl"
21317 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21318 ["Next Field" org-cycle (org-at-table-p)]
21319 ["Previous Field" org-shifttab (org-at-table-p)]
21320 ["Next Row" org-return (org-at-table-p)]
21321 "--"
21322 ["Blank Field" org-table-blank-field (org-at-table-p)]
21323 ["Edit Field" org-table-edit-field (org-at-table-p)]
21324 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21325 "--"
21326 ("Column"
21327 ["Move Column Left" org-metaleft (org-at-table-p)]
21328 ["Move Column Right" org-metaright (org-at-table-p)]
21329 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21330 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21331 ("Row"
21332 ["Move Row Up" org-metaup (org-at-table-p)]
21333 ["Move Row Down" org-metadown (org-at-table-p)]
21334 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21335 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21336 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21337 "--"
21338 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21339 ("Rectangle"
21340 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21341 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21342 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21343 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21344 "--"
21345 ("Calculate"
21346 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21347 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21348 ["Edit Formulas" org-edit-special (org-at-table-p)]
21349 "--"
21350 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21351 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21352 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21353 "--"
21354 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21355 "--"
21356 ["Sum Column/Rectangle" org-table-sum
21357 (or (org-at-table-p) (org-region-active-p))]
21358 ["Which Column?" org-table-current-column (org-at-table-p)])
21359 ["Debug Formulas"
21360 org-table-toggle-formula-debugger
21361 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21362 ["Show Col/Row Numbers"
21363 org-table-toggle-coordinate-overlays
21364 :style toggle
21365 :selected (bound-and-true-p org-table-overlay-coordinates)]
21366 "--"
21367 ["Create" org-table-create (and (not (org-at-table-p))
21368 org-enable-table-editor)]
21369 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21370 ["Import from File" org-table-import (not (org-at-table-p))]
21371 ["Export to File" org-table-export (org-at-table-p)]
21372 "--"
21373 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21374 "--"
21375 ("Plot"
21376 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21377 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21379 (easy-menu-define org-org-menu org-mode-map "Org menu"
21380 '("Org"
21381 ("Show/Hide"
21382 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21383 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21384 ["Sparse Tree..." org-sparse-tree t]
21385 ["Reveal Context" org-reveal t]
21386 ["Show All" outline-show-all t]
21387 "--"
21388 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21389 "--"
21390 ["New Heading" org-insert-heading t]
21391 ("Navigate Headings"
21392 ["Up" outline-up-heading t]
21393 ["Next" outline-next-visible-heading t]
21394 ["Previous" outline-previous-visible-heading t]
21395 ["Next Same Level" outline-forward-same-level t]
21396 ["Previous Same Level" outline-backward-same-level t]
21397 "--"
21398 ["Jump" org-goto t])
21399 ("Edit Structure"
21400 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21401 "--"
21402 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21403 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21404 "--"
21405 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21406 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21407 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21408 "--"
21409 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21410 "--"
21411 ["Copy visible text" org-copy-visible t]
21412 "--"
21413 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21414 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21415 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21416 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21417 "--"
21418 ["Sort Region/Children" org-sort t]
21419 "--"
21420 ["Convert to odd levels" org-convert-to-odd-levels t]
21421 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21422 ("Editing"
21423 ["Emphasis..." org-emphasize t]
21424 ["Edit Source Example" org-edit-special t]
21425 "--"
21426 ["Footnote new/jump" org-footnote-action t]
21427 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21428 ("Archive"
21429 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21430 "--"
21431 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21432 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21433 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21435 "--"
21436 ("Hyperlinks"
21437 ["Store Link (Global)" org-store-link t]
21438 ["Find existing link to here" org-occur-link-in-agenda-files t]
21439 ["Insert Link" org-insert-link t]
21440 ["Follow Link" org-open-at-point t]
21441 "--"
21442 ["Next link" org-next-link t]
21443 ["Previous link" org-previous-link t]
21444 "--"
21445 ["Descriptive Links"
21446 org-toggle-link-display
21447 :style radio
21448 :selected org-descriptive-links
21450 ["Literal Links"
21451 org-toggle-link-display
21452 :style radio
21453 :selected (not org-descriptive-links)])
21454 "--"
21455 ("TODO Lists"
21456 ["TODO/DONE/-" org-todo t]
21457 ("Select keyword"
21458 ["Next keyword" org-shiftright (org-at-heading-p)]
21459 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21460 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21461 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21462 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21463 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21464 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21465 "--"
21466 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21467 :selected org-enforce-todo-dependencies :style toggle :active t]
21468 "Settings for tree at point"
21469 ["Do Children sequentially" org-toggle-ordered-property :style radio
21470 :selected (org-entry-get nil "ORDERED")
21471 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21472 ["Do Children parallel" org-toggle-ordered-property :style radio
21473 :selected (not (org-entry-get nil "ORDERED"))
21474 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21475 "--"
21476 ["Set Priority" org-priority t]
21477 ["Priority Up" org-shiftup t]
21478 ["Priority Down" org-shiftdown t]
21479 "--"
21480 ["Get news from all feeds" org-feed-update-all t]
21481 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21482 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21483 ("TAGS and Properties"
21484 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21485 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21486 "--"
21487 ["Set property" org-set-property (not (org-before-first-heading-p))]
21488 ["Column view of properties" org-columns t]
21489 ["Insert Column View DBlock" org-columns-insert-dblock t])
21490 ("Dates and Scheduling"
21491 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21492 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21493 ("Change Date"
21494 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21495 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21496 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21497 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21498 ["Compute Time Range" org-evaluate-time-range t]
21499 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21500 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21501 "--"
21502 ["Custom time format" org-toggle-time-stamp-overlays
21503 :style radio :selected org-display-custom-times]
21504 "--"
21505 ["Goto Calendar" org-goto-calendar t]
21506 ["Date from Calendar" org-date-from-calendar t]
21507 "--"
21508 ["Start/Restart Timer" org-timer-start t]
21509 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21510 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21511 ["Insert Timer String" org-timer t]
21512 ["Insert Timer Item" org-timer-item t])
21513 ("Logging work"
21514 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21515 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21516 ["Clock out" org-clock-out t]
21517 ["Clock cancel" org-clock-cancel t]
21518 "--"
21519 ["Mark as default task" org-clock-mark-default-task t]
21520 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21521 ["Goto running clock" org-clock-goto t]
21522 "--"
21523 ["Display times" org-clock-display t]
21524 ["Create clock table" org-clock-report t]
21525 "--"
21526 ["Record DONE time"
21527 (progn (setq org-log-done (not org-log-done))
21528 (message "Switching to %s will %s record a timestamp"
21529 (car org-done-keywords)
21530 (if org-log-done "automatically" "not")))
21531 :style toggle :selected org-log-done])
21532 "--"
21533 ["Agenda Command..." org-agenda t]
21534 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21535 ("File List for Agenda")
21536 ("Special views current file"
21537 ["TODO Tree" org-show-todo-tree t]
21538 ["Check Deadlines" org-check-deadlines t]
21539 ["Tags/Property tree" org-match-sparse-tree t])
21540 "--"
21541 ["Export/Publish..." org-export-dispatch t]
21542 ("LaTeX"
21543 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21544 :selected org-cdlatex-mode]
21545 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21546 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21547 ["Modify math symbol" org-cdlatex-math-modify
21548 (org-inside-LaTeX-fragment-p)]
21549 ["Insert citation" org-reftex-citation t])
21550 "--"
21551 ("MobileOrg"
21552 ["Push Files and Views" org-mobile-push t]
21553 ["Get Captured and Flagged" org-mobile-pull t]
21554 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21555 "--"
21556 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21557 "--"
21558 ("Documentation"
21559 ["Show Version" org-version t]
21560 ["Info Documentation" org-info t])
21561 ("Customize"
21562 ["Browse Org Group" org-customize t]
21563 "--"
21564 ["Expand This Menu" org-create-customize-menu
21565 (fboundp 'customize-menu-create)])
21566 ["Send bug report" org-submit-bug-report t]
21567 "--"
21568 ("Refresh/Reload"
21569 ["Refresh setup current buffer" org-mode-restart t]
21570 ["Reload Org (after update)" org-reload t]
21571 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21574 (defun org-info (&optional node)
21575 "Read documentation for Org in the info system.
21576 With optional NODE, go directly to that node."
21577 (interactive)
21578 (info (format "(org)%s" (or node ""))))
21580 ;;;###autoload
21581 (defun org-submit-bug-report ()
21582 "Submit a bug report on Org via mail.
21584 Don't hesitate to report any problems or inaccurate documentation.
21586 If you don't have setup sending mail from (X)Emacs, please copy the
21587 output buffer into your mail program, as it gives us important
21588 information about your Org version and configuration."
21589 (interactive)
21590 (require 'reporter)
21591 (defvar reporter-prompt-for-summary-p)
21592 (org-load-modules-maybe)
21593 (org-require-autoloaded-modules)
21594 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21595 (reporter-submit-bug-report
21596 "emacs-orgmode@gnu.org"
21597 (org-version nil 'full)
21598 (let (list)
21599 (save-window-excursion
21600 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21601 (delete-other-windows)
21602 (erase-buffer)
21603 (insert "You are about to submit a bug report to the Org mailing list.
21605 We would like to add your full Org and Outline configuration to the
21606 bug report. This greatly simplifies the work of the maintainer and
21607 other experts on the mailing list.
21609 HOWEVER, some variables you have customized may contain private
21610 information. The names of customers, colleagues, or friends, might
21611 appear in the form of file names, tags, todo states, or search strings.
21612 If you answer yes to the prompt, you might want to check and remove
21613 such private information before sending the email.")
21614 (add-text-properties (point-min) (point-max) '(face org-warning))
21615 (when (yes-or-no-p "Include your Org configuration ")
21616 (mapatoms
21617 (lambda (v)
21618 (and (boundp v)
21619 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21620 (or (and (symbol-value v)
21621 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21622 (and
21623 (get v 'custom-type) (get v 'standard-value)
21624 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21625 (push v list)))))
21626 (kill-buffer (get-buffer "*Warn about privacy*"))
21627 list))
21628 nil nil
21629 "Remember to cover the basics, that is, what you expected to happen and
21630 what in fact did happen. You don't know how to make a good report? See
21632 http://orgmode.org/manual/Feedback.html#Feedback
21634 Your bug report will be posted to the Org mailing list.
21635 ------------------------------------------------------------------------")
21636 (save-excursion
21637 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21638 (replace-match "\\1Bug: \\3 [\\2]")))))
21641 (defun org-install-agenda-files-menu ()
21642 (let ((bl (buffer-list)))
21643 (save-excursion
21644 (while bl
21645 (set-buffer (pop bl))
21646 (when (derived-mode-p 'org-mode) (setq bl nil)))
21647 (when (derived-mode-p 'org-mode)
21648 (easy-menu-change
21649 '("Org") "File List for Agenda"
21650 (append
21651 (list
21652 ["Edit File List" (org-edit-agenda-file-list) t]
21653 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21654 ["Remove Current File from List" org-remove-file t]
21655 ["Cycle through agenda files" org-cycle-agenda-files t]
21656 ["Occur in all agenda files" org-occur-in-agenda-files t]
21657 "--")
21658 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21660 ;;;; Documentation
21662 (defun org-require-autoloaded-modules ()
21663 (interactive)
21664 (mapc #'require
21665 '(org-agenda org-archive org-attach org-clock org-colview org-id
21666 org-table org-timer)))
21668 ;;;###autoload
21669 (defun org-reload (&optional uncompiled)
21670 "Reload all org lisp files.
21671 With prefix arg UNCOMPILED, load the uncompiled versions."
21672 (interactive "P")
21673 (require 'loadhist)
21674 (let* ((org-dir (org-find-library-dir "org"))
21675 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21676 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21677 (remove-re (format "\\`%s\\'"
21678 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21679 (feats (delete-dups
21680 (mapcar 'file-name-sans-extension
21681 (mapcar 'file-name-nondirectory
21682 (delq nil
21683 (mapcar 'feature-file
21684 features))))))
21685 (lfeat (append
21686 (sort
21687 (setq feats
21688 (delq nil (mapcar
21689 (lambda (f)
21690 (if (and (string-match feature-re f)
21691 (not (string-match remove-re f)))
21692 f nil))
21693 feats)))
21694 'string-lessp)
21695 (list "org-version" "org")))
21696 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21697 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21698 load-uncore load-misses)
21699 (setq load-misses
21700 (delq 't
21701 (mapcar (lambda (f)
21702 (or (org-load-noerror-mustsuffix (concat org-dir f))
21703 (and (string= org-dir contrib-dir)
21704 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21705 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21706 (add-to-list 'load-uncore f 'append)
21709 lfeat)))
21710 (when load-uncore
21711 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21712 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21713 (if load-misses
21714 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21715 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21716 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21718 ;;;###autoload
21719 (defun org-customize ()
21720 "Call the customize function with org as argument."
21721 (interactive)
21722 (org-load-modules-maybe)
21723 (org-require-autoloaded-modules)
21724 (customize-browse 'org))
21726 (defun org-create-customize-menu ()
21727 "Create a full customization menu for Org mode, insert it into the menu."
21728 (interactive)
21729 (org-load-modules-maybe)
21730 (org-require-autoloaded-modules)
21731 (if (fboundp 'customize-menu-create)
21732 (progn
21733 (easy-menu-change
21734 '("Org") "Customize"
21735 `(["Browse Org group" org-customize t]
21736 "--"
21737 ,(customize-menu-create 'org)
21738 ["Set" Custom-set t]
21739 ["Save" Custom-save t]
21740 ["Reset to Current" Custom-reset-current t]
21741 ["Reset to Saved" Custom-reset-saved t]
21742 ["Reset to Standard Settings" Custom-reset-standard t]))
21743 (message "\"Org\"-menu now contains full customization menu"))
21744 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21746 ;;;; Miscellaneous stuff
21748 ;;; Generally useful functions
21750 (defun org-get-at-eol (property n)
21751 "Get text property PROPERTY at the end of line less N characters."
21752 (get-text-property (- (point-at-eol) n) property))
21754 (defun org-find-text-property-in-string (prop s)
21755 "Return the first non-nil value of property PROP in string S."
21756 (or (get-text-property 0 prop s)
21757 (get-text-property (or (next-single-property-change 0 prop s) 0)
21758 prop s)))
21760 (defun org-display-warning (message)
21761 "Display the given MESSAGE as a warning."
21762 (display-warning 'org message :warning))
21764 (defun org-eval (form)
21765 "Eval FORM and return result."
21766 (condition-case error
21767 (eval form)
21768 (error (format "%%![Error: %s]" error))))
21770 (defun org-in-clocktable-p ()
21771 "Check if the cursor is in a clocktable."
21772 (let ((pos (point)) start)
21773 (save-excursion
21774 (end-of-line 1)
21775 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21776 (setq start (match-beginning 0))
21777 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21778 (>= (match-end 0) pos)
21779 start))))
21781 (defun org-in-verbatim-emphasis ()
21782 (save-match-data
21783 (and (org-in-regexp org-verbatim-re 2)
21784 (>= (point) (match-beginning 3))
21785 (<= (point) (match-end 4)))))
21787 (defun org-overlay-display (ovl text &optional face evap)
21788 "Make overlay OVL display TEXT with face FACE."
21789 (overlay-put ovl 'display text)
21790 (if face (overlay-put ovl 'face face))
21791 (if evap (overlay-put ovl 'evaporate t)))
21793 (defun org-overlay-before-string (ovl text &optional face evap)
21794 "Make overlay OVL display TEXT with face FACE."
21795 (if face (org-add-props text nil 'face face))
21796 (overlay-put ovl 'before-string text)
21797 (if evap (overlay-put ovl 'evaporate t)))
21799 (defun org-find-overlays (prop &optional pos delete)
21800 "Find all overlays specifying PROP at POS or point.
21801 If DELETE is non-nil, delete all those overlays."
21802 (let (found)
21803 (dolist (ov (overlays-at (or pos (point))) found)
21804 (cond ((not (overlay-get ov prop)))
21805 (delete (delete-overlay ov))
21806 (t (push ov found))))))
21808 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21809 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21810 (if (and marker (marker-buffer marker)
21811 (buffer-live-p (marker-buffer marker)))
21812 (progn
21813 (pop-to-buffer-same-window (marker-buffer marker))
21814 (when (or (> marker (point-max)) (< marker (point-min)))
21815 (widen))
21816 (goto-char marker)
21817 (org-show-context 'org-goto))
21818 (if bookmark
21819 (bookmark-jump bookmark)
21820 (error "Cannot find location"))))
21822 (defun org-quote-csv-field (s)
21823 "Quote field for inclusion in CSV material."
21824 (if (string-match "[\",]" s)
21825 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21828 (defun org-force-self-insert (N)
21829 "Needed to enforce self-insert under remapping."
21830 (interactive "p")
21831 (self-insert-command N))
21833 (defun org-string-width (s)
21834 "Compute width of string, ignoring invisible characters.
21835 This ignores character with invisibility property `org-link', and also
21836 characters with property `org-cwidth', because these will become invisible
21837 upon the next fontification round."
21838 (let (b l)
21839 (when (or (eq t buffer-invisibility-spec)
21840 (assq 'org-link buffer-invisibility-spec))
21841 (while (setq b (text-property-any 0 (length s)
21842 'invisible 'org-link s))
21843 (setq s (concat (substring s 0 b)
21844 (substring s (or (next-single-property-change
21845 b 'invisible s)
21846 (length s)))))))
21847 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21848 (setq s (concat (substring s 0 b)
21849 (substring s (or (next-single-property-change
21850 b 'org-cwidth s)
21851 (length s))))))
21852 (setq l (string-width s) b -1)
21853 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21854 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21857 (defun org-shorten-string (s maxlength)
21858 "Shorten string S so that it is no longer than MAXLENGTH characters.
21859 If the string is shorter or has length MAXLENGTH, just return the
21860 original string. If it is longer, the functions finds a space in the
21861 string, breaks this string off at that locations and adds three dots
21862 as ellipsis. Including the ellipsis, the string will not be longer
21863 than MAXLENGTH. If finding a good breaking point in the string does
21864 not work, the string is just chopped off in the middle of a word
21865 if necessary."
21866 (if (<= (length s) maxlength)
21868 (let* ((n (max (- maxlength 4) 1))
21869 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21870 (if (string-match re s)
21871 (concat (match-string 1 s) "...")
21872 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21874 (defun org-get-indentation (&optional line)
21875 "Get the indentation of the current line, interpreting tabs.
21876 When LINE is given, assume it represents a line and compute its indentation."
21877 (if line
21878 (when (string-match "^ *" (org-remove-tabs line))
21879 (match-end 0))
21880 (save-excursion
21881 (beginning-of-line 1)
21882 (skip-chars-forward " \t")
21883 (current-column))))
21885 (defun org-get-string-indentation (s)
21886 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21887 (let ((n -1) (i 0) (w tab-width) c)
21888 (catch 'exit
21889 (while (< (setq n (1+ n)) (length s))
21890 (setq c (aref s n))
21891 (cond ((= c ?\ ) (setq i (1+ i)))
21892 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21893 (t (throw 'exit t)))))
21896 (defun org-remove-tabs (s &optional width)
21897 "Replace tabulators in S with spaces.
21898 Assumes that s is a single line, starting in column 0."
21899 (setq width (or width tab-width))
21900 (while (string-match "\t" s)
21901 (setq s (replace-match
21902 (make-string
21903 (- (* width (/ (+ (match-beginning 0) width) width))
21904 (match-beginning 0)) ?\ )
21905 t t s)))
21908 (defun org-fix-indentation (line ind)
21909 "Fix indentation in LINE.
21910 IND is a cons cell with target and minimum indentation.
21911 If the current indentation in LINE is smaller than the minimum,
21912 leave it alone. If it is larger than ind, set it to the target."
21913 (let* ((l (org-remove-tabs line))
21914 (i (org-get-indentation l))
21915 (i1 (car ind)) (i2 (cdr ind)))
21916 (when (>= i i2) (setq l (substring line i2)))
21917 (if (> i1 0)
21918 (concat (make-string i1 ?\ ) l)
21919 l)))
21921 (defun org-remove-indentation (code &optional n)
21922 "Remove maximum common indentation in string CODE and return it.
21923 N may optionally be the number of columns to remove. Return CODE
21924 as-is if removal failed."
21925 (with-temp-buffer
21926 (insert code)
21927 (if (org-do-remove-indentation n) (buffer-string) code)))
21929 (defun org-do-remove-indentation (&optional n)
21930 "Remove the maximum common indentation from the buffer.
21931 When optional argument N is a positive integer, remove exactly
21932 that much characters from indentation, if possible. Return nil
21933 if it fails."
21934 (catch :exit
21935 (goto-char (point-min))
21936 ;; Find maximum common indentation, if not specified.
21937 (let ((n (or n
21938 (let ((min-ind (point-max)))
21939 (save-excursion
21940 (while (re-search-forward "^[ \t]*\\S-" nil t)
21941 (let ((ind (1- (current-column))))
21942 (if (zerop ind) (throw :exit nil)
21943 (setq min-ind (min min-ind ind))))))
21944 min-ind))))
21945 (if (zerop n) (throw :exit nil)
21946 ;; Remove exactly N indentation, but give up if not possible.
21947 (while (not (eobp))
21948 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21949 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21950 ((< ind n) (throw :exit nil))
21951 (t (indent-line-to (- ind n))))
21952 (forward-line)))
21953 ;; Signal success.
21954 t))))
21956 (defun org-fill-template (template alist)
21957 "Find each %key of ALIST in TEMPLATE and replace it."
21958 (let ((case-fold-search nil))
21959 (dolist (entry (sort (copy-sequence alist)
21960 (lambda (a b) (< (length (car a)) (length (car b))))))
21961 (setq template
21962 (replace-regexp-in-string
21963 (concat "%" (regexp-quote (car entry)))
21964 (or (cdr entry) "") template t t)))
21965 template))
21967 (defun org-base-buffer (buffer)
21968 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21969 (if (not buffer)
21970 buffer
21971 (or (buffer-base-buffer buffer)
21972 buffer)))
21974 (defun org-wrap (string &optional width lines)
21975 "Wrap string to either a number of lines, or a width in characters.
21976 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21977 that costs. If there is a word longer than WIDTH, the text is actually
21978 wrapped to the length of that word.
21979 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21980 many lines, whatever width that takes.
21981 The return value is a list of lines, without newlines at the end."
21982 (let* ((words (org-split-string string "[ \t\n]+"))
21983 (maxword (apply 'max (mapcar 'org-string-width words)))
21984 w ll)
21985 (cond (width
21986 (org-do-wrap words (max maxword width)))
21987 (lines
21988 (setq w maxword)
21989 (setq ll (org-do-wrap words maxword))
21990 (if (<= (length ll) lines)
21992 (setq ll words)
21993 (while (> (length ll) lines)
21994 (setq w (1+ w))
21995 (setq ll (org-do-wrap words w)))
21996 ll))
21997 (t (error "Cannot wrap this")))))
21999 (defun org-do-wrap (words width)
22000 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22001 (let (lines line)
22002 (while words
22003 (setq line (pop words))
22004 (while (and words (< (+ (length line) (length (car words))) width))
22005 (setq line (concat line " " (pop words))))
22006 (setq lines (push line lines)))
22007 (nreverse lines)))
22009 (defun org-split-string (string &optional separators)
22010 "Splits STRING into substrings at SEPARATORS.
22011 SEPARATORS is a regular expression.
22012 No empty strings are returned if there are matches at the beginning
22013 and end of string."
22014 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22015 (let ((start 0) notfirst list)
22016 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22017 (if (and notfirst
22018 (= start (match-beginning 0))
22019 (< start (length string)))
22020 (1+ start) start))
22021 (< (match-beginning 0) (length string)))
22022 (setq notfirst t)
22023 (or (eq (match-beginning 0) 0)
22024 (and (eq (match-beginning 0) (match-end 0))
22025 (eq (match-beginning 0) start))
22026 (push (substring string start (match-beginning 0)) list))
22027 (setq start (match-end 0)))
22028 (or (eq start (length string))
22029 (push (substring string start) list))
22030 (nreverse list)))
22032 (defun org-quote-vert (s)
22033 "Replace \"|\" with \"\\vert\"."
22034 (while (string-match "|" s)
22035 (setq s (replace-match "\\vert" t t s)))
22038 (defun org-uuidgen-p (s)
22039 "Is S an ID created by UUIDGEN?"
22040 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22042 (defun org-in-src-block-p (&optional inside)
22043 "Whether point is in a code source block.
22044 When INSIDE is non-nil, don't consider we are within a src block
22045 when point is at #+BEGIN_SRC or #+END_SRC."
22046 (let ((case-fold-search t))
22047 (or (and (eq (get-char-property (point) 'src-block) t))
22048 (and (not inside)
22049 (save-match-data
22050 (save-excursion
22051 (beginning-of-line)
22052 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22054 (defun org-context ()
22055 "Return a list of contexts of the current cursor position.
22056 If several contexts apply, all are returned.
22057 Each context entry is a list with a symbol naming the context, and
22058 two positions indicating start and end of the context. Possible
22059 contexts are:
22061 :headline anywhere in a headline
22062 :headline-stars on the leading stars in a headline
22063 :todo-keyword on a TODO keyword (including DONE) in a headline
22064 :tags on the TAGS in a headline
22065 :priority on the priority cookie in a headline
22066 :item on the first line of a plain list item
22067 :item-bullet on the bullet/number of a plain list item
22068 :checkbox on the checkbox in a plain list item
22069 :table in an Org table
22070 :table-special on a special filed in a table
22071 :table-table in a table.el table
22072 :clocktable in a clocktable
22073 :src-block in a source block
22074 :link on a hyperlink
22075 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22076 :target on a <<target>>
22077 :radio-target on a <<<radio-target>>>
22078 :latex-fragment on a LaTeX fragment
22079 :latex-preview on a LaTeX fragment with overlaid preview image
22081 This function expects the position to be visible because it uses font-lock
22082 faces as a help to recognize the following contexts: :table-special, :link,
22083 and :keyword."
22084 (let* ((f (get-text-property (point) 'face))
22085 (faces (if (listp f) f (list f)))
22086 (case-fold-search t)
22087 (p (point)) clist o)
22088 ;; First the large context
22089 (cond
22090 ((org-at-heading-p t)
22091 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22092 (when (progn
22093 (beginning-of-line 1)
22094 (looking-at org-todo-line-tags-regexp))
22095 (push (org-point-in-group p 1 :headline-stars) clist)
22096 (push (org-point-in-group p 2 :todo-keyword) clist)
22097 (push (org-point-in-group p 4 :tags) clist))
22098 (goto-char p)
22099 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22100 (when (looking-at "\\[#[A-Z0-9]\\]")
22101 (push (org-point-in-group p 0 :priority) clist)))
22103 ((org-at-item-p)
22104 (push (org-point-in-group p 2 :item-bullet) clist)
22105 (push (list :item (point-at-bol)
22106 (save-excursion (org-end-of-item) (point)))
22107 clist)
22108 (and (org-at-item-checkbox-p)
22109 (push (org-point-in-group p 0 :checkbox) clist)))
22111 ((org-at-table-p)
22112 (push (list :table (org-table-begin) (org-table-end)) clist)
22113 (when (memq 'org-formula faces)
22114 (push (list :table-special
22115 (previous-single-property-change p 'face)
22116 (next-single-property-change p 'face)) clist)))
22117 ((org-at-table-p 'any)
22118 (push (list :table-table) clist)))
22119 (goto-char p)
22121 (let ((case-fold-search t))
22122 ;; New the "medium" contexts: clocktables, source blocks
22123 (cond ((org-in-clocktable-p)
22124 (push (list :clocktable
22125 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22126 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22127 (match-beginning 1))
22128 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22129 (match-end 0))) clist))
22130 ((org-in-src-block-p)
22131 (push (list :src-block
22132 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22133 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22134 (match-beginning 1))
22135 (and (search-forward "#+END_SRC" nil t)
22136 (match-beginning 0))) clist))))
22137 (goto-char p)
22139 ;; Now the small context
22140 (cond
22141 ((org-at-timestamp-p)
22142 (push (org-point-in-group p 0 :timestamp) clist))
22143 ((memq 'org-link faces)
22144 (push (list :link
22145 (previous-single-property-change p 'face)
22146 (next-single-property-change p 'face)) clist))
22147 ((memq 'org-special-keyword faces)
22148 (push (list :keyword
22149 (previous-single-property-change p 'face)
22150 (next-single-property-change p 'face)) clist))
22151 ((org-at-target-p)
22152 (push (org-point-in-group p 0 :target) clist)
22153 (goto-char (1- (match-beginning 0)))
22154 (when (looking-at org-radio-target-regexp)
22155 (push (org-point-in-group p 0 :radio-target) clist))
22156 (goto-char p))
22157 ((setq o (cl-some
22158 (lambda (o)
22159 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22161 (overlays-at (point))))
22162 (push (list :latex-fragment
22163 (overlay-start o) (overlay-end o)) clist)
22164 (push (list :latex-preview
22165 (overlay-start o) (overlay-end o)) clist))
22166 ((org-inside-LaTeX-fragment-p)
22167 ;; FIXME: positions wrong.
22168 (push (list :latex-fragment (point) (point)) clist)))
22170 (setq clist (nreverse (delq nil clist)))
22171 clist))
22173 (defun org-in-regexp (regexp &optional nlines visually)
22174 "Check if point is inside a match of REGEXP.
22176 Normally only the current line is checked, but you can include
22177 NLINES extra lines around point into the search. If VISUALLY is
22178 set, require that the cursor is not after the match but really
22179 on, so that the block visually is on the match.
22181 Return nil or a cons cell (BEG . END) where BEG and END are,
22182 respectively, the positions at the beginning and the end of the
22183 match."
22184 (catch :exit
22185 (let ((pos (point))
22186 (eol (line-end-position (if nlines (1+ nlines) 1))))
22187 (save-excursion
22188 (beginning-of-line (- 1 (or nlines 0)))
22189 (while (and (re-search-forward regexp eol t)
22190 (<= (match-beginning 0) pos))
22191 (let ((end (match-end 0)))
22192 (when (or (> end pos) (and (= end pos) (not visually)))
22193 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22195 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22196 "Non-nil when point is between matches of START-RE and END-RE.
22198 Also return a non-nil value when point is on one of the matches.
22200 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22201 buffer positions. Default values are the positions of headlines
22202 surrounding the point.
22204 The functions returns a cons cell whose car (resp. cdr) is the
22205 position before START-RE (resp. after END-RE)."
22206 (save-match-data
22207 (let ((pos (point))
22208 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22209 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22210 beg end)
22211 (save-excursion
22212 ;; Point is on a block when on START-RE or if START-RE can be
22213 ;; found before it...
22214 (and (or (org-in-regexp start-re)
22215 (re-search-backward start-re limit-up t))
22216 (setq beg (match-beginning 0))
22217 ;; ... and END-RE after it...
22218 (goto-char (match-end 0))
22219 (re-search-forward end-re limit-down t)
22220 (> (setq end (match-end 0)) pos)
22221 ;; ... without another START-RE in-between.
22222 (goto-char (match-beginning 0))
22223 (not (re-search-backward start-re (1+ beg) t))
22224 ;; Return value.
22225 (cons beg end))))))
22227 (defun org-in-block-p (names)
22228 "Non-nil when point belongs to a block whose name belongs to NAMES.
22230 NAMES is a list of strings containing names of blocks.
22232 Return first block name matched, or nil. Beware that in case of
22233 nested blocks, the returned name may not belong to the closest
22234 block from point."
22235 (save-match-data
22236 (catch 'exit
22237 (let ((case-fold-search t)
22238 (lim-up (save-excursion (outline-previous-heading)))
22239 (lim-down (save-excursion (outline-next-heading))))
22240 (dolist (name names)
22241 (let ((n (regexp-quote name)))
22242 (when (org-between-regexps-p
22243 (concat "^[ \t]*#\\+begin_" n)
22244 (concat "^[ \t]*#\\+end_" n)
22245 lim-up lim-down)
22246 (throw 'exit n)))))
22247 nil)))
22249 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22250 "Call `multi-occur' with buffers for all agenda files."
22251 (interactive "sOrg-files matching: ")
22252 (let* ((files (org-agenda-files))
22253 (tnames (mapcar #'file-truename files))
22254 (extra org-agenda-text-search-extra-files))
22255 (when (eq (car extra) 'agenda-archives)
22256 (setq extra (cdr extra))
22257 (setq files (org-add-archive-files files)))
22258 (dolist (f extra)
22259 (unless (member (file-truename f) tnames)
22260 (unless (member f files) (setq files (append files (list f))))
22261 (setq tnames (append tnames (list (file-truename f))))))
22262 (multi-occur
22263 (mapcar (lambda (x)
22264 (with-current-buffer
22265 ;; FIXME: Why not just (find-file-noselect x)?
22266 ;; Is it to avoid the "revert buffer" prompt?
22267 (or (get-file-buffer x) (find-file-noselect x))
22268 (widen)
22269 (current-buffer)))
22270 files)
22271 regexp)))
22273 (add-hook 'occur-mode-find-occurrence-hook
22274 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22276 (defun org-occur-link-in-agenda-files ()
22277 "Create a link and search for it in the agendas.
22278 The link is not stored in `org-stored-links', it is just created
22279 for the search purpose."
22280 (interactive)
22281 (let ((link (condition-case nil
22282 (org-store-link nil)
22283 (error "Unable to create a link to here"))))
22284 (org-occur-in-agenda-files (regexp-quote link))))
22286 (defun org-reverse-string (string)
22287 "Return the reverse of STRING."
22288 (apply 'string (reverse (string-to-list string))))
22290 ;; defsubst org-uniquify must be defined before first use
22292 (defun org-uniquify-alist (alist)
22293 "Merge elements of ALIST with the same key.
22295 For example, in this alist:
22297 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22298 => \\='((a 1 3) (b 2))
22300 merge (a 1) and (a 3) into (a 1 3).
22302 The function returns the new ALIST."
22303 (let (rtn)
22304 (dolist (e alist rtn)
22305 (let (n)
22306 (if (not (assoc (car e) rtn))
22307 (push e rtn)
22308 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22309 (setq rtn (assq-delete-all (car e) rtn))
22310 (push n rtn))))))
22312 (defun org-delete-all (elts list)
22313 "Remove all elements in ELTS from LIST.
22314 Comparison is done with `equal'. It is a destructive operation
22315 that may remove elements by altering the list structure."
22316 (while elts
22317 (setq list (delete (pop elts) list)))
22318 list)
22320 (defun org-back-over-empty-lines ()
22321 "Move backwards over whitespace, to the beginning of the first empty line.
22322 Returns the number of empty lines passed."
22323 (let ((pos (point)))
22324 (if (cdr (assq 'heading org-blank-before-new-entry))
22325 (skip-chars-backward " \t\n\r")
22326 (unless (eobp)
22327 (forward-line -1)))
22328 (beginning-of-line 2)
22329 (goto-char (min (point) pos))
22330 (count-lines (point) pos)))
22332 (defun org-skip-whitespace ()
22333 (skip-chars-forward " \t\n\r"))
22335 (defun org-point-in-group (point group &optional context)
22336 "Check if POINT is in match-group GROUP.
22337 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22338 match. If the match group does not exist or point is not inside it,
22339 return nil."
22340 (and (match-beginning group)
22341 (>= point (match-beginning group))
22342 (<= point (match-end group))
22343 (if context
22344 (list context (match-beginning group) (match-end group))
22345 t)))
22347 (defun org-switch-to-buffer-other-window (&rest args)
22348 "Switch to buffer in a second window on the current frame.
22349 In particular, do not allow pop-up frames.
22350 Returns the newly created buffer."
22351 (org-no-popups
22352 (apply 'switch-to-buffer-other-window args)))
22354 (defun org-combine-plists (&rest plists)
22355 "Create a single property list from all plists in PLISTS.
22356 The process starts by copying the first list, and then setting properties
22357 from the other lists. Settings in the last list are the most significant
22358 ones and overrule settings in the other lists."
22359 (let ((rtn (copy-sequence (pop plists)))
22360 p v ls)
22361 (while plists
22362 (setq ls (pop plists))
22363 (while ls
22364 (setq p (pop ls) v (pop ls))
22365 (setq rtn (plist-put rtn p v))))
22366 rtn))
22368 (defun org-replace-escapes (string table)
22369 "Replace %-escapes in STRING with values in TABLE.
22370 TABLE is an association list with keys like \"%a\" and string values.
22371 The sequences in STRING may contain normal field width and padding information,
22372 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22373 so values can contain further %-escapes if they are define later in TABLE."
22374 (let ((tbl (copy-alist table))
22375 (case-fold-search nil)
22376 (pchg 0)
22377 re rpl)
22378 (dolist (e tbl)
22379 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22380 (when (and (cdr e) (string-match re (cdr e)))
22381 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22382 (safe "SREF"))
22383 (add-text-properties 0 3 (list 'sref sref) safe)
22384 (setcdr e (replace-match safe t t (cdr e)))))
22385 (while (string-match re string)
22386 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22387 (cdr e)))
22388 (setq string (replace-match rpl t t string))))
22389 (while (setq pchg (next-property-change pchg string))
22390 (let ((sref (get-text-property pchg 'sref string)))
22391 (when (and sref (string-match "SREF" string pchg))
22392 (setq string (replace-match sref t t string)))))
22393 string))
22395 (defun org-find-base-buffer-visiting (file)
22396 "Like `find-buffer-visiting' but always return the base buffer and
22397 not an indirect buffer."
22398 (let ((buf (or (get-file-buffer file)
22399 (find-buffer-visiting file))))
22400 (if buf
22401 (or (buffer-base-buffer buf) buf)
22402 nil)))
22404 ;;; TODO: Only called once, from ox-odt which should probably use
22405 ;;; org-export-inline-image-p or something.
22406 (defun org-file-image-p (file)
22407 "Return non-nil if FILE is an image."
22408 (save-match-data
22409 (string-match (image-file-name-regexp) file)))
22411 (defun org-get-cursor-date (&optional with-time)
22412 "Return the date at cursor in as a time.
22413 This works in the calendar and in the agenda, anywhere else it just
22414 returns the current time.
22415 If WITH-TIME is non-nil, returns the time of the event at point (in
22416 the agenda) or the current time of the day."
22417 (let (date day defd tp hod mod)
22418 (when with-time
22419 (setq tp (get-text-property (point) 'time))
22420 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22421 (setq hod (string-to-number (match-string 1 tp))
22422 mod (string-to-number (match-string 2 tp))))
22423 (or tp (let ((now (decode-time)))
22424 (setq hod (nth 2 now)
22425 mod (nth 1 now)))))
22426 (cond
22427 ((eq major-mode 'calendar-mode)
22428 (setq date (calendar-cursor-to-date)
22429 defd (encode-time 0 (or mod 0) (or hod 0)
22430 (nth 1 date) (nth 0 date) (nth 2 date))))
22431 ((eq major-mode 'org-agenda-mode)
22432 (setq day (get-text-property (point) 'day))
22433 (when day
22434 (setq date (calendar-gregorian-from-absolute day)
22435 defd (encode-time 0 (or mod 0) (or hod 0)
22436 (nth 1 date) (nth 0 date) (nth 2 date))))))
22437 (or defd (current-time))))
22439 (defun org-mark-subtree (&optional up)
22440 "Mark the current subtree.
22441 This puts point at the start of the current subtree, and mark at
22442 the end. If a numeric prefix UP is given, move up into the
22443 hierarchy of headlines by UP levels before marking the subtree."
22444 (interactive "P")
22445 (org-with-limited-levels
22446 (cond ((org-at-heading-p) (beginning-of-line))
22447 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22448 (t (outline-previous-visible-heading 1))))
22449 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22450 (if (called-interactively-p 'any)
22451 (call-interactively 'org-mark-element)
22452 (org-mark-element)))
22454 (defun org-file-newer-than-p (file time)
22455 "Non-nil if FILE is newer than TIME.
22456 FILE is a filename, as a string, TIME is a list of integers, as
22457 returned by, e.g., `current-time'."
22458 (and (file-exists-p file)
22459 ;; Only compare times up to whole seconds as some file-systems
22460 ;; (e.g. HFS+) do not retain any finer granularity. As
22461 ;; a consequence, make sure we return non-nil when the two
22462 ;; times are equal.
22463 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22464 (cl-subseq time 0 2)))))
22466 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22467 "Compile a SOURCE file using PROCESS.
22469 PROCESS is either a function or a list of shell commands, as
22470 strings. EXT is a file extension, without the leading dot, as
22471 a string. It is used to check if the process actually succeeded.
22473 PROCESS must create a file with the same base name and directory
22474 as SOURCE, but ending with EXT. The function then returns its
22475 filename. Otherwise, it raises an error. The error message can
22476 then be refined by providing string ERR-MSG, which is appended to
22477 the standard message.
22479 If PROCESS is a function, it is called with a single argument:
22480 the SOURCE file.
22482 If it is a list of commands, each of them is called using
22483 `shell-command'. By default, in each command, %b, %f, %F, %o and
22484 %O are replaced with, respectively, SOURCE base name, name, full
22485 name, directory and absolute output file name. It is possible,
22486 however, to use more place-holders by specifying them in optional
22487 argument SPEC, as an alist following the pattern
22489 (CHARACTER . REPLACEMENT-STRING).
22491 When PROCESS is a list of commands, optional argument LOG-BUF can
22492 be set to a buffer or a buffer name. `shell-command' then uses
22493 it for output."
22494 (let* ((base-name (file-name-base source))
22495 (full-name (file-truename source))
22496 (out-dir (or (file-name-directory source) "./"))
22497 (output (expand-file-name (concat base-name "." ext) out-dir))
22498 (time (current-time))
22499 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22500 (save-window-excursion
22501 (pcase process
22502 ((pred functionp) (funcall process (shell-quote-argument source)))
22503 ((pred consp)
22504 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22505 (spec (append spec
22506 `((?b . ,(shell-quote-argument base-name))
22507 (?f . ,(shell-quote-argument source))
22508 (?F . ,(shell-quote-argument full-name))
22509 (?o . ,(shell-quote-argument out-dir))
22510 (?O . ,(shell-quote-argument output))))))
22511 (dolist (command process)
22512 (shell-command (format-spec command spec) log-buf))
22513 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22514 (_ (error "No valid command to process %S%s" source err-msg))))
22515 ;; Check for process failure. Output file is expected to be
22516 ;; located in the same directory as SOURCE.
22517 (unless (org-file-newer-than-p output time)
22518 (error (format "File %S wasn't produced%s" output err-msg)))
22519 output))
22521 ;;; Indentation
22523 (defun org--get-expected-indentation (element contentsp)
22524 "Expected indentation column for current line, according to ELEMENT.
22525 ELEMENT is an element containing point. CONTENTSP is non-nil
22526 when indentation is to be computed according to contents of
22527 ELEMENT."
22528 (let ((type (org-element-type element))
22529 (start (org-element-property :begin element))
22530 (post-affiliated (org-element-property :post-affiliated element)))
22531 (org-with-wide-buffer
22532 (cond
22533 (contentsp
22534 (cl-case type
22535 ((diary-sexp footnote-definition) 0)
22536 ((headline inlinetask nil)
22537 (if (not org-adapt-indentation) 0
22538 (let ((level (org-current-level)))
22539 (if level (1+ level) 0))))
22540 ((item plain-list) (org-list-item-body-column post-affiliated))
22542 (goto-char start)
22543 (org-get-indentation))))
22544 ((memq type '(headline inlinetask nil))
22545 (if (org-match-line "[ \t]*$")
22546 (org--get-expected-indentation element t)
22548 ((memq type '(diary-sexp footnote-definition)) 0)
22549 ;; First paragraph of a footnote definition or an item.
22550 ;; Indent like parent.
22551 ((< (line-beginning-position) start)
22552 (org--get-expected-indentation
22553 (org-element-property :parent element) t))
22554 ;; At first line: indent according to previous sibling, if any,
22555 ;; ignoring footnote definitions and inline tasks, or parent's
22556 ;; contents.
22557 ((= (line-beginning-position) start)
22558 (catch 'exit
22559 (while t
22560 (if (= (point-min) start) (throw 'exit 0)
22561 (goto-char (1- start))
22562 (let* ((previous (org-element-at-point))
22563 (parent previous))
22564 (while (and parent (<= (org-element-property :end parent) start))
22565 (setq previous parent
22566 parent (org-element-property :parent parent)))
22567 (cond
22568 ((not previous) (throw 'exit 0))
22569 ((> (org-element-property :end previous) start)
22570 (throw 'exit (org--get-expected-indentation previous t)))
22571 ((memq (org-element-type previous)
22572 '(footnote-definition inlinetask))
22573 (setq start (org-element-property :begin previous)))
22574 (t (goto-char (org-element-property :begin previous))
22575 (throw 'exit
22576 (if (bolp) (org-get-indentation)
22577 ;; At first paragraph in an item or
22578 ;; a footnote definition.
22579 (org--get-expected-indentation
22580 (org-element-property :parent previous) t))))))))))
22581 ;; Otherwise, move to the first non-blank line above.
22583 (beginning-of-line)
22584 (let ((pos (point)))
22585 (skip-chars-backward " \r\t\n")
22586 (cond
22587 ;; Two blank lines end a footnote definition or a plain
22588 ;; list. When we indent an empty line after them, the
22589 ;; containing list or footnote definition is over, so it
22590 ;; qualifies as a previous sibling. Therefore, we indent
22591 ;; like its first line.
22592 ((and (memq type '(footnote-definition plain-list))
22593 (> (count-lines (point) pos) 2))
22594 (goto-char start)
22595 (org-get-indentation))
22596 ;; Line above is the first one of a paragraph at the
22597 ;; beginning of an item or a footnote definition. Indent
22598 ;; like parent.
22599 ((< (line-beginning-position) start)
22600 (org--get-expected-indentation
22601 (org-element-property :parent element) t))
22602 ;; Line above is the beginning of an element, i.e., point
22603 ;; was originally on the blank lines between element's start
22604 ;; and contents.
22605 ((= (line-beginning-position) post-affiliated)
22606 (org--get-expected-indentation element t))
22607 ;; POS is after contents in a greater element. Indent like
22608 ;; the beginning of the element.
22609 ((and (memq type org-element-greater-elements)
22610 (let ((cend (org-element-property :contents-end element)))
22611 (and cend (<= cend pos))))
22612 ;; As a special case, if point is at the end of a footnote
22613 ;; definition or an item, indent like the very last element
22614 ;; within. If that last element is an item, indent like
22615 ;; its contents.
22616 (if (memq type '(footnote-definition item plain-list))
22617 (let ((last (org-element-at-point)))
22618 (goto-char pos)
22619 (org--get-expected-indentation
22620 last (eq (org-element-type last) 'item)))
22621 (goto-char start)
22622 (org-get-indentation)))
22623 ;; In any other case, indent like the current line.
22624 (t (org-get-indentation)))))))))
22626 (defun org--align-node-property ()
22627 "Align node property at point.
22628 Alignment is done according to `org-property-format', which see."
22629 (when (save-excursion
22630 (beginning-of-line)
22631 (looking-at org-property-re))
22632 (replace-match
22633 (concat (match-string 4)
22634 (org-trim
22635 (format org-property-format (match-string 1) (match-string 3))))
22636 t t)))
22638 (defun org-indent-line ()
22639 "Indent line depending on context.
22641 Indentation is done according to the following rules:
22643 - Footnote definitions, diary sexps, headlines and inline tasks
22644 have to start at column 0.
22646 - On the very first line of an element, consider, in order, the
22647 next rules until one matches:
22649 1. If there's a sibling element before, ignoring footnote
22650 definitions and inline tasks, indent like its first line.
22652 2. If element has a parent, indent like its contents. More
22653 precisely, if parent is an item, indent after the
22654 description part, if any, or the bullet (see
22655 `org-list-description-max-indent'). Else, indent like
22656 parent's first line.
22658 3. Otherwise, indent relatively to current level, if
22659 `org-adapt-indentation' is non-nil, or to left margin.
22661 - On a blank line at the end of an element, indent according to
22662 the type of the element. More precisely
22664 1. If element is a plain list, an item, or a footnote
22665 definition, indent like the very last element within.
22667 2. If element is a paragraph, indent like its last non blank
22668 line.
22670 3. Otherwise, indent like its very first line.
22672 - In the code part of a source block, use language major mode
22673 to indent current line if `org-src-tab-acts-natively' is
22674 non-nil. If it is nil, do nothing.
22676 - Otherwise, indent like the first non-blank line above.
22678 The function doesn't indent an item as it could break the whole
22679 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22680 `\\[org-shiftmetaright]'.
22682 Also align node properties according to `org-property-format'."
22683 (interactive)
22684 (cond
22685 (orgstruct-is-++
22686 (let ((indent-line-function
22687 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22688 (indent-according-to-mode)))
22689 ((org-at-heading-p) 'noindent)
22691 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22692 (type (org-element-type element)))
22693 (cond ((and (memq type '(plain-list item))
22694 (= (line-beginning-position)
22695 (org-element-property :post-affiliated element)))
22696 'noindent)
22697 ((and (eq type 'latex-environment)
22698 (>= (point) (org-element-property :post-affiliated element))
22699 (< (point) (org-with-wide-buffer
22700 (goto-char (org-element-property :end element))
22701 (skip-chars-backward " \r\t\n")
22702 (line-beginning-position 2))))
22703 'noindent)
22704 ((and (eq type 'src-block)
22705 org-src-tab-acts-natively
22706 (> (line-beginning-position)
22707 (org-element-property :post-affiliated element))
22708 (< (line-beginning-position)
22709 (org-with-wide-buffer
22710 (goto-char (org-element-property :end element))
22711 (skip-chars-backward " \r\t\n")
22712 (line-beginning-position))))
22713 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22715 (let ((column (org--get-expected-indentation element nil)))
22716 ;; Preserve current column.
22717 (if (<= (current-column) (current-indentation))
22718 (indent-line-to column)
22719 (save-excursion (indent-line-to column))))
22720 ;; Align node property. Also preserve current column.
22721 (when (eq type 'node-property)
22722 (let ((column (current-column)))
22723 (org--align-node-property)
22724 (org-move-to-column column)))))))))
22726 (defun org-indent-region (start end)
22727 "Indent each non-blank line in the region.
22728 Called from a program, START and END specify the region to
22729 indent. The function will not indent contents of example blocks,
22730 verse blocks and export blocks as leading white spaces are
22731 assumed to be significant there."
22732 (interactive "r")
22733 (save-excursion
22734 (goto-char start)
22735 (skip-chars-forward " \r\t\n")
22736 (unless (eobp) (beginning-of-line))
22737 (let ((indent-to
22738 (lambda (ind pos)
22739 ;; Set IND as indentation for all lines between point and
22740 ;; POS. Blank lines are ignored. Leave point after POS
22741 ;; once done.
22742 (let ((limit (copy-marker pos)))
22743 (while (< (point) limit)
22744 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22745 (forward-line))
22746 (set-marker limit nil))))
22747 (end (copy-marker end)))
22748 (while (< (point) end)
22749 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22750 (let* ((element (org-element-at-point))
22751 (type (org-element-type element))
22752 (element-end (copy-marker (org-element-property :end element)))
22753 (ind (org--get-expected-indentation element nil)))
22754 (cond
22755 ;; Element indented as a single block. Example blocks
22756 ;; preserving indentation are a special case since the
22757 ;; "contents" must not be indented whereas the block
22758 ;; boundaries can.
22759 ((or (memq type '(export-block latex-environment))
22760 (and (eq type 'example-block)
22761 (not
22762 (or org-src-preserve-indentation
22763 (org-element-property :preserve-indent element)))))
22764 (let ((offset (- ind (org-get-indentation))))
22765 (unless (zerop offset)
22766 (indent-rigidly (org-element-property :begin element)
22767 (org-element-property :end element)
22768 offset)))
22769 (goto-char element-end))
22770 ;; Elements indented line wise. Be sure to exclude
22771 ;; example blocks (preserving indentation) and source
22772 ;; blocks from this category as they are treated
22773 ;; specially later.
22774 ((or (memq type '(paragraph table table-row))
22775 (not (or (org-element-property :contents-begin element)
22776 (memq type '(example-block src-block)))))
22777 (when (eq type 'node-property)
22778 (org--align-node-property)
22779 (beginning-of-line))
22780 (funcall indent-to ind (min element-end end)))
22781 ;; Elements consisting of three parts: before the
22782 ;; contents, the contents, and after the contents. The
22783 ;; contents are treated specially, according to the
22784 ;; element type, or not indented at all. Other parts are
22785 ;; indented as a single block.
22787 (let* ((post (copy-marker
22788 (org-element-property :post-affiliated element)))
22789 (cbeg
22790 (copy-marker
22791 (cond
22792 ((not (org-element-property :contents-begin element))
22793 ;; Fake contents for source blocks.
22794 (org-with-wide-buffer
22795 (goto-char post)
22796 (line-beginning-position 2)))
22797 ((memq type '(footnote-definition item plain-list))
22798 ;; Contents in these elements could start on
22799 ;; the same line as the beginning of the
22800 ;; element. Make sure we start indenting
22801 ;; from the second line.
22802 (org-with-wide-buffer
22803 (goto-char post)
22804 (end-of-line)
22805 (skip-chars-forward " \r\t\n")
22806 (if (eobp) (point) (line-beginning-position))))
22807 (t (org-element-property :contents-begin element)))))
22808 (cend (copy-marker
22809 (or (org-element-property :contents-end element)
22810 ;; Fake contents for source blocks.
22811 (org-with-wide-buffer
22812 (goto-char element-end)
22813 (skip-chars-backward " \r\t\n")
22814 (line-beginning-position)))
22815 t)))
22816 ;; Do not change items indentation individually as it
22817 ;; might break the list as a whole. On the other
22818 ;; hand, when at a plain list, indent it as a whole.
22819 (cond ((eq type 'plain-list)
22820 (let ((offset (- ind (org-get-indentation))))
22821 (unless (zerop offset)
22822 (indent-rigidly (org-element-property :begin element)
22823 (org-element-property :end element)
22824 offset))
22825 (goto-char cbeg)))
22826 ((eq type 'item) (goto-char cbeg))
22827 (t (funcall indent-to ind (min cbeg end))))
22828 (when (< (point) end)
22829 (cl-case type
22830 ((example-block verse-block))
22831 (src-block
22832 ;; In a source block, indent source code
22833 ;; according to language major mode, but only if
22834 ;; `org-src-tab-acts-natively' is non-nil.
22835 (when (and (< (point) end) org-src-tab-acts-natively)
22836 (ignore-errors
22837 (org-babel-do-in-edit-buffer
22838 (indent-region (point-min) (point-max))))))
22839 (t (org-indent-region (point) (min cend end))))
22840 (goto-char (min cend end))
22841 (when (< (point) end)
22842 (funcall indent-to ind (min element-end end))))
22843 (set-marker post nil)
22844 (set-marker cbeg nil)
22845 (set-marker cend nil))))
22846 (set-marker element-end nil))))
22847 (set-marker end nil))))
22849 (defun org-indent-drawer ()
22850 "Indent the drawer at point."
22851 (interactive)
22852 (unless (save-excursion
22853 (beginning-of-line)
22854 (looking-at-p org-drawer-regexp))
22855 (user-error "Not at a drawer"))
22856 (let ((element (org-element-at-point)))
22857 (unless (memq (org-element-type element) '(drawer property-drawer))
22858 (user-error "Not at a drawer"))
22859 (org-with-wide-buffer
22860 (org-indent-region (org-element-property :begin element)
22861 (org-element-property :end element))))
22862 (message "Drawer at point indented"))
22864 (defun org-indent-block ()
22865 "Indent the block at point."
22866 (interactive)
22867 (unless (save-excursion
22868 (beginning-of-line)
22869 (let ((case-fold-search t))
22870 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22871 (user-error "Not at a block"))
22872 (let ((element (org-element-at-point)))
22873 (unless (memq (org-element-type element)
22874 '(comment-block center-block dynamic-block example-block
22875 export-block quote-block special-block
22876 src-block verse-block))
22877 (user-error "Not at a block"))
22878 (org-with-wide-buffer
22879 (org-indent-region (org-element-property :begin element)
22880 (org-element-property :end element))))
22881 (message "Block at point indented"))
22884 ;;; Filling
22886 ;; We use our own fill-paragraph and auto-fill functions.
22888 ;; `org-fill-paragraph' relies on adaptive filling and context
22889 ;; checking. Appropriate `fill-prefix' is computed with
22890 ;; `org-adaptive-fill-function'.
22892 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22893 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22894 ;; `org-adaptive-fill-function' value. Internally,
22895 ;; `org-comment-line-break-function' breaks the line.
22897 ;; `org-setup-filling' installs filling and auto-filling related
22898 ;; variables during `org-mode' initialization.
22900 (defvar org-element-paragraph-separate) ; org-element.el
22901 (defun org-setup-filling ()
22902 (require 'org-element)
22903 ;; Prevent auto-fill from inserting unwanted new items.
22904 (when (boundp 'fill-nobreak-predicate)
22905 (setq-local
22906 fill-nobreak-predicate
22907 (org-uniquify
22908 (append fill-nobreak-predicate
22909 '(org-fill-line-break-nobreak-p
22910 org-fill-paragraph-with-timestamp-nobreak-p)))))
22911 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22912 (setq-local paragraph-start paragraph-ending)
22913 (setq-local paragraph-separate paragraph-ending))
22914 (setq-local fill-paragraph-function 'org-fill-paragraph)
22915 (setq-local auto-fill-inhibit-regexp nil)
22916 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22917 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22918 (setq-local comment-line-break-function 'org-comment-line-break-function))
22920 (defun org-fill-line-break-nobreak-p ()
22921 "Non-nil when a new line at point would create an Org line break."
22922 (save-excursion
22923 (skip-chars-backward "[ \t]")
22924 (skip-chars-backward "\\\\")
22925 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22927 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22928 "Non-nil when a new line at point would split a timestamp."
22929 (and (org-at-timestamp-p 'lax)
22930 (not (looking-at org-ts-regexp-both))))
22932 (declare-function message-in-body-p "message" ())
22933 (defvar orgtbl-line-start-regexp) ; From org-table.el
22934 (defun org-adaptive-fill-function ()
22935 "Compute a fill prefix for the current line.
22936 Return fill prefix, as a string, or nil if current line isn't
22937 meant to be filled. For convenience, if `adaptive-fill-regexp'
22938 matches in paragraphs or comments, use it."
22939 (catch 'exit
22940 (when (derived-mode-p 'message-mode)
22941 (save-excursion
22942 (beginning-of-line)
22943 (cond ((not (message-in-body-p)) (throw 'exit nil))
22944 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22945 ((looking-at message-cite-prefix-regexp)
22946 (throw 'exit (match-string-no-properties 0)))
22947 ((looking-at org-outline-regexp)
22948 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22949 (org-with-wide-buffer
22950 (unless (org-at-heading-p)
22951 (let* ((p (line-beginning-position))
22952 (element (save-excursion
22953 (beginning-of-line)
22954 (org-element-at-point)))
22955 (type (org-element-type element))
22956 (post-affiliated (org-element-property :post-affiliated element)))
22957 (unless (< p post-affiliated)
22958 (cl-case type
22959 (comment
22960 (save-excursion
22961 (beginning-of-line)
22962 (looking-at "[ \t]*")
22963 (concat (match-string 0) "# ")))
22964 (footnote-definition "")
22965 ((item plain-list)
22966 (make-string (org-list-item-body-column post-affiliated) ?\s))
22967 (paragraph
22968 ;; Fill prefix is usually the same as the current line,
22969 ;; unless the paragraph is at the beginning of an item.
22970 (let ((parent (org-element-property :parent element)))
22971 (save-excursion
22972 (beginning-of-line)
22973 (cond ((eq (org-element-type parent) 'item)
22974 (make-string (org-list-item-body-column
22975 (org-element-property :begin parent))
22976 ?\s))
22977 ((and adaptive-fill-regexp
22978 ;; Locally disable
22979 ;; `adaptive-fill-function' to let
22980 ;; `fill-context-prefix' handle
22981 ;; `adaptive-fill-regexp' variable.
22982 (let (adaptive-fill-function)
22983 (fill-context-prefix
22984 post-affiliated
22985 (org-element-property :end element)))))
22986 ((looking-at "[ \t]+") (match-string 0))
22987 (t "")))))
22988 (comment-block
22989 ;; Only fill contents if P is within block boundaries.
22990 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22991 (forward-line)
22992 (point)))
22993 (cend (save-excursion
22994 (goto-char (org-element-property :end element))
22995 (skip-chars-backward " \r\t\n")
22996 (line-beginning-position))))
22997 (when (and (>= p cbeg) (< p cend))
22998 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22999 (match-string 0)
23000 "")))))))))))
23002 (declare-function message-goto-body "message" ())
23003 (defvar message-cite-prefix-regexp) ; From message.el
23004 (defun org-fill-paragraph (&optional justify)
23005 "Fill element at point, when applicable.
23007 This function only applies to comment blocks, comments, example
23008 blocks and paragraphs. Also, as a special case, re-align table
23009 when point is at one.
23011 If JUSTIFY is non-nil (interactively, with prefix argument),
23012 justify as well. If `sentence-end-double-space' is non-nil, then
23013 period followed by one space does not end a sentence, so don't
23014 break a line there. The variable `fill-column' controls the
23015 width for filling.
23017 For convenience, when point is at a plain list, an item or
23018 a footnote definition, try to fill the first paragraph within."
23019 (interactive)
23020 (if (and (derived-mode-p 'message-mode)
23021 (or (not (message-in-body-p))
23022 (save-excursion (move-beginning-of-line 1)
23023 (looking-at message-cite-prefix-regexp))))
23024 ;; First ensure filling is correct in message-mode.
23025 (let ((fill-paragraph-function
23026 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23027 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23028 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23029 (paragraph-separate
23030 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23031 (fill-paragraph nil))
23032 (with-syntax-table org-mode-transpose-word-syntax-table
23033 ;; Move to end of line in order to get the first paragraph
23034 ;; within a plain list or a footnote definition.
23035 (let ((element (save-excursion
23036 (end-of-line)
23037 (or (ignore-errors (org-element-at-point))
23038 (user-error "An element cannot be parsed line %d"
23039 (line-number-at-pos (point)))))))
23040 ;; First check if point is in a blank line at the beginning of
23041 ;; the buffer. In that case, ignore filling.
23042 (cl-case (org-element-type element)
23043 ;; Use major mode filling function is src blocks.
23044 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23045 ;; Align Org tables, leave table.el tables as-is.
23046 (table-row (org-table-align) t)
23047 (table
23048 (when (eq (org-element-property :type element) 'org)
23049 (save-excursion
23050 (goto-char (org-element-property :post-affiliated element))
23051 (org-table-align)))
23053 (paragraph
23054 ;; Paragraphs may contain `line-break' type objects.
23055 (let ((beg (max (point-min)
23056 (org-element-property :contents-begin element)))
23057 (end (min (point-max)
23058 (org-element-property :contents-end element))))
23059 ;; Do nothing if point is at an affiliated keyword.
23060 (if (< (line-end-position) beg) t
23061 (when (derived-mode-p 'message-mode)
23062 ;; In `message-mode', do not fill following citation
23063 ;; in current paragraph nor text before message body.
23064 (let ((body-start (save-excursion (message-goto-body))))
23065 (when body-start (setq beg (max body-start beg))))
23066 (when (save-excursion
23067 (re-search-forward
23068 (concat "^" message-cite-prefix-regexp) end t))
23069 (setq end (match-beginning 0))))
23070 ;; Fill paragraph, taking line breaks into account.
23071 (save-excursion
23072 (goto-char beg)
23073 (let ((cuts (list beg)))
23074 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23075 (when (eq 'line-break
23076 (org-element-type
23077 (save-excursion (backward-char)
23078 (org-element-context))))
23079 (push (point) cuts)))
23080 (dolist (c (delq end cuts))
23081 (fill-region-as-paragraph c end justify)
23082 (setq end c))))
23083 t)))
23084 ;; Contents of `comment-block' type elements should be
23085 ;; filled as plain text, but only if point is within block
23086 ;; markers.
23087 (comment-block
23088 (let* ((case-fold-search t)
23089 (beg (save-excursion
23090 (goto-char (org-element-property :begin element))
23091 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23092 (forward-line)
23093 (point)))
23094 (end (save-excursion
23095 (goto-char (org-element-property :end element))
23096 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23097 (line-beginning-position))))
23098 (if (or (< (point) beg) (> (point) end)) t
23099 (fill-region-as-paragraph
23100 (save-excursion (end-of-line)
23101 (re-search-backward "^[ \t]*$" beg 'move)
23102 (line-beginning-position))
23103 (save-excursion (beginning-of-line)
23104 (re-search-forward "^[ \t]*$" end 'move)
23105 (line-beginning-position))
23106 justify))))
23107 ;; Fill comments.
23108 (comment
23109 (let ((begin (org-element-property :post-affiliated element))
23110 (end (org-element-property :end element)))
23111 (when (and (>= (point) begin) (<= (point) end))
23112 (let ((begin (save-excursion
23113 (end-of-line)
23114 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23115 (progn (forward-line) (point))
23116 begin)))
23117 (end (save-excursion
23118 (end-of-line)
23119 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23120 (1- (line-beginning-position))
23121 (skip-chars-backward " \r\t\n")
23122 (line-end-position)))))
23123 ;; Do not fill comments when at a blank line.
23124 (when (> end begin)
23125 (let ((fill-prefix
23126 (save-excursion
23127 (beginning-of-line)
23128 (looking-at "[ \t]*#")
23129 (let ((comment-prefix (match-string 0)))
23130 (goto-char (match-end 0))
23131 (if (looking-at adaptive-fill-regexp)
23132 (concat comment-prefix (match-string 0))
23133 (concat comment-prefix " "))))))
23134 (save-excursion
23135 (fill-region-as-paragraph begin end justify))))))
23137 ;; Ignore every other element.
23138 (otherwise t))))))
23140 (defun org-auto-fill-function ()
23141 "Auto-fill function."
23142 ;; Check if auto-filling is meaningful.
23143 (let ((fc (current-fill-column)))
23144 (when (and fc (> (current-column) fc))
23145 (let* ((fill-prefix (org-adaptive-fill-function))
23146 ;; Enforce empty fill prefix, if required. Otherwise, it
23147 ;; will be computed again.
23148 (adaptive-fill-mode (not (equal fill-prefix ""))))
23149 (when fill-prefix (do-auto-fill))))))
23151 (defun org-comment-line-break-function (&optional soft)
23152 "Break line at point and indent, continuing comment if within one.
23153 The inserted newline is marked hard if variable
23154 `use-hard-newlines' is true, unless optional argument SOFT is
23155 non-nil."
23156 (if soft (insert-and-inherit ?\n) (newline 1))
23157 (save-excursion (forward-char -1) (delete-horizontal-space))
23158 (delete-horizontal-space)
23159 (indent-to-left-margin)
23160 (insert-before-markers-and-inherit fill-prefix))
23163 ;;; Fixed Width Areas
23165 (defun org-toggle-fixed-width ()
23166 "Toggle fixed-width markup.
23168 Add or remove fixed-width markup on current line, whenever it
23169 makes sense. Return an error otherwise.
23171 If a region is active and if it contains only fixed-width areas
23172 or blank lines, remove all fixed-width markup in it. If the
23173 region contains anything else, convert all non-fixed-width lines
23174 to fixed-width ones.
23176 Blank lines at the end of the region are ignored unless the
23177 region only contains such lines."
23178 (interactive)
23179 (if (not (org-region-active-p))
23180 ;; No region:
23182 ;; Remove fixed width marker only in a fixed-with element.
23184 ;; Add fixed width maker in paragraphs, in blank lines after
23185 ;; elements or at the beginning of a headline or an inlinetask,
23186 ;; and before any one-line elements (e.g., a clock).
23187 (progn
23188 (beginning-of-line)
23189 (let* ((element (org-element-at-point))
23190 (type (org-element-type element)))
23191 (cond
23192 ((and (eq type 'fixed-width)
23193 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23194 (replace-match
23195 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23196 ((and (memq type '(babel-call clock comment diary-sexp headline
23197 horizontal-rule keyword paragraph
23198 planning))
23199 (<= (org-element-property :post-affiliated element) (point)))
23200 (skip-chars-forward " \t")
23201 (insert ": "))
23202 ((and (looking-at-p "[ \t]*$")
23203 (or (eq type 'inlinetask)
23204 (save-excursion
23205 (skip-chars-forward " \r\t\n")
23206 (<= (org-element-property :end element) (point)))))
23207 (delete-region (point) (line-end-position))
23208 (org-indent-line)
23209 (insert ": "))
23210 (t (user-error "Cannot insert a fixed-width line here")))))
23211 ;; Region active.
23212 (let* ((begin (save-excursion
23213 (goto-char (region-beginning))
23214 (line-beginning-position)))
23215 (end (copy-marker
23216 (save-excursion
23217 (goto-char (region-end))
23218 (unless (eolp) (beginning-of-line))
23219 (if (save-excursion (re-search-backward "\\S-" begin t))
23220 (progn (skip-chars-backward " \r\t\n") (point))
23221 (point)))))
23222 (all-fixed-width-p
23223 (catch 'not-all-p
23224 (save-excursion
23225 (goto-char begin)
23226 (skip-chars-forward " \r\t\n")
23227 (when (eobp) (throw 'not-all-p nil))
23228 (while (< (point) end)
23229 (let ((element (org-element-at-point)))
23230 (if (eq (org-element-type element) 'fixed-width)
23231 (goto-char (org-element-property :end element))
23232 (throw 'not-all-p nil))))
23233 t))))
23234 (if all-fixed-width-p
23235 (save-excursion
23236 (goto-char begin)
23237 (while (< (point) end)
23238 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23239 (replace-match
23240 "" nil nil nil
23241 (if (= (line-end-position) (match-end 0)) 0 1)))
23242 (forward-line)))
23243 (let ((min-ind (point-max)))
23244 ;; Find minimum indentation across all lines.
23245 (save-excursion
23246 (goto-char begin)
23247 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23248 (setq min-ind 0)
23249 (catch 'zerop
23250 (while (< (point) end)
23251 (unless (looking-at-p "[ \t]*$")
23252 (let ((ind (org-get-indentation)))
23253 (setq min-ind (min min-ind ind))
23254 (when (zerop ind) (throw 'zerop t))))
23255 (forward-line)))))
23256 ;; Loop over all lines and add fixed-width markup everywhere
23257 ;; but in fixed-width lines.
23258 (save-excursion
23259 (goto-char begin)
23260 (while (< (point) end)
23261 (cond
23262 ((org-at-heading-p)
23263 (insert ": ")
23264 (forward-line)
23265 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23266 (insert ":")
23267 (forward-line)))
23268 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23269 (let* ((element (org-element-at-point))
23270 (element-end (org-element-property :end element)))
23271 (if (eq (org-element-type element) 'fixed-width)
23272 (progn (goto-char element-end)
23273 (skip-chars-backward " \r\t\n")
23274 (forward-line))
23275 (let ((limit (min end element-end)))
23276 (while (< (point) limit)
23277 (org-move-to-column min-ind t)
23278 (insert ": ")
23279 (forward-line))))))
23281 (org-move-to-column min-ind t)
23282 (insert ": ")
23283 (forward-line)))))))
23284 (set-marker end nil))))
23287 ;;; Comments
23289 ;; Org comments syntax is quite complex. It requires the entire line
23290 ;; to be just a comment. Also, even with the right syntax at the
23291 ;; beginning of line, some elements (e.g., verse-block or
23292 ;; example-block) don't accept comments. Usual Emacs comment commands
23293 ;; cannot cope with those requirements. Therefore, Org replaces them.
23295 ;; Org still relies on `comment-dwim', but cannot trust
23296 ;; `comment-only-p'. So, `comment-region-function' and
23297 ;; `uncomment-region-function' both point
23298 ;; to`org-comment-or-uncomment-region'. Eventually,
23299 ;; `org-insert-comment' takes care of insertion of comments at the
23300 ;; beginning of line.
23302 ;; `org-setup-comments-handling' install comments related variables
23303 ;; during `org-mode' initialization.
23305 (defun org-setup-comments-handling ()
23306 (interactive)
23307 (setq-local comment-use-syntax nil)
23308 (setq-local comment-start "# ")
23309 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23310 (setq-local comment-insert-comment-function 'org-insert-comment)
23311 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23312 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23314 (defun org-insert-comment ()
23315 "Insert an empty comment above current line.
23316 If the line is empty, insert comment at its beginning. When
23317 point is within a source block, comment according to the related
23318 major mode."
23319 (if (let ((element (org-element-at-point)))
23320 (and (eq (org-element-type element) 'src-block)
23321 (< (save-excursion
23322 (goto-char (org-element-property :post-affiliated element))
23323 (line-end-position))
23324 (point))
23325 (> (save-excursion
23326 (goto-char (org-element-property :end element))
23327 (skip-chars-backward " \r\t\n")
23328 (line-beginning-position))
23329 (point))))
23330 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23331 (beginning-of-line)
23332 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23333 (open-line 1))
23334 (org-indent-line)
23335 (insert "# ")))
23337 (defvar comment-empty-lines) ; From newcomment.el.
23338 (defun org-comment-or-uncomment-region (beg end &rest _)
23339 "Comment or uncomment each non-blank line in the region.
23340 Uncomment each non-blank line between BEG and END if it only
23341 contains commented lines. Otherwise, comment them. If region is
23342 strictly within a source block, use appropriate comment syntax."
23343 (if (let ((element (org-element-at-point)))
23344 (and (eq (org-element-type element) 'src-block)
23345 (< (save-excursion
23346 (goto-char (org-element-property :post-affiliated element))
23347 (line-end-position))
23348 beg)
23349 (>= (save-excursion
23350 (goto-char (org-element-property :end element))
23351 (skip-chars-backward " \r\t\n")
23352 (line-beginning-position))
23353 end)))
23354 ;; Translate region boundaries for the Org buffer to the source
23355 ;; buffer.
23356 (let ((offset (- end beg)))
23357 (save-excursion
23358 (goto-char beg)
23359 (org-babel-do-in-edit-buffer
23360 (comment-or-uncomment-region (point) (+ offset (point))))))
23361 (save-restriction
23362 ;; Restrict region
23363 (narrow-to-region (save-excursion (goto-char beg)
23364 (skip-chars-forward " \r\t\n" end)
23365 (line-beginning-position))
23366 (save-excursion (goto-char end)
23367 (skip-chars-backward " \r\t\n" beg)
23368 (line-end-position)))
23369 (let ((uncommentp
23370 ;; UNCOMMENTP is non-nil when every non blank line between
23371 ;; BEG and END is a comment.
23372 (save-excursion
23373 (goto-char (point-min))
23374 (while (and (not (eobp))
23375 (let ((element (org-element-at-point)))
23376 (and (eq (org-element-type element) 'comment)
23377 (goto-char (min (point-max)
23378 (org-element-property
23379 :end element)))))))
23380 (eobp))))
23381 (if uncommentp
23382 ;; Only blank lines and comments in region: uncomment it.
23383 (save-excursion
23384 (goto-char (point-min))
23385 (while (not (eobp))
23386 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23387 (replace-match "" nil nil nil 1))
23388 (forward-line)))
23389 ;; Comment each line in region.
23390 (let ((min-indent (point-max)))
23391 ;; First find the minimum indentation across all lines.
23392 (save-excursion
23393 (goto-char (point-min))
23394 (while (and (not (eobp)) (not (zerop min-indent)))
23395 (unless (looking-at "[ \t]*$")
23396 (setq min-indent (min min-indent (current-indentation))))
23397 (forward-line)))
23398 ;; Then loop over all lines.
23399 (save-excursion
23400 (goto-char (point-min))
23401 (while (not (eobp))
23402 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23403 ;; Don't get fooled by invisible text (e.g. link path)
23404 ;; when moving to column MIN-INDENT.
23405 (let ((buffer-invisibility-spec nil))
23406 (org-move-to-column min-indent t))
23407 (insert comment-start))
23408 (forward-line)))))))))
23410 (defun org-comment-dwim (_arg)
23411 "Call `comment-dwim' within a source edit buffer if needed."
23412 (interactive "*P")
23413 (if (org-in-src-block-p)
23414 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23415 (call-interactively 'comment-dwim)))
23418 ;;; Timestamps API
23420 ;; This section contains tools to operate on timestamp objects, as
23421 ;; returned by, e.g. `org-element-context'.
23423 (defun org-timestamp--to-internal-time (timestamp &optional end)
23424 "Encode TIMESTAMP object into Emacs internal time.
23425 Use end of date range or time range when END is non-nil."
23426 (apply #'encode-time
23427 (cons 0
23428 (mapcar
23429 (lambda (prop) (or (org-element-property prop timestamp) 0))
23430 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23431 '(:minute-start :hour-start :day-start :month-start
23432 :year-start))))))
23434 (defun org-timestamp-has-time-p (timestamp)
23435 "Non-nil when TIMESTAMP has a time specified."
23436 (org-element-property :hour-start timestamp))
23438 (defun org-timestamp-format (timestamp format &optional end utc)
23439 "Format a TIMESTAMP object into a string.
23441 FORMAT is a format specifier to be passed to
23442 `format-time-string'.
23444 When optional argument END is non-nil, use end of date-range or
23445 time-range, if possible.
23447 When optional argument UTC is non-nil, time will be expressed as
23448 Universal Time."
23449 (format-time-string
23450 format (org-timestamp--to-internal-time timestamp end)
23451 (and utc t)))
23453 (defun org-timestamp-split-range (timestamp &optional end)
23454 "Extract a TIMESTAMP object from a date or time range.
23456 END, when non-nil, means extract the end of the range.
23457 Otherwise, extract its start.
23459 Return a new timestamp object."
23460 (let ((type (org-element-property :type timestamp)))
23461 (if (memq type '(active inactive diary)) timestamp
23462 (let ((split-ts (org-element-copy timestamp)))
23463 ;; Set new type.
23464 (org-element-put-property
23465 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23466 ;; Copy start properties over end properties if END is
23467 ;; non-nil. Otherwise, copy end properties over `start' ones.
23468 (let ((p-alist '((:minute-start . :minute-end)
23469 (:hour-start . :hour-end)
23470 (:day-start . :day-end)
23471 (:month-start . :month-end)
23472 (:year-start . :year-end))))
23473 (dolist (p-cell p-alist)
23474 (org-element-put-property
23475 split-ts
23476 (funcall (if end #'car #'cdr) p-cell)
23477 (org-element-property
23478 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23479 ;; Eventually refresh `:raw-value'.
23480 (org-element-put-property split-ts :raw-value nil)
23481 (org-element-put-property
23482 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23484 (defun org-timestamp-translate (timestamp &optional boundary)
23485 "Translate TIMESTAMP object to custom format.
23487 Format string is defined in `org-time-stamp-custom-formats',
23488 which see.
23490 When optional argument BOUNDARY is non-nil, it is either the
23491 symbol `start' or `end'. In this case, only translate the
23492 starting or ending part of TIMESTAMP if it is a date or time
23493 range. Otherwise, translate both parts.
23495 Return timestamp as-is if `org-display-custom-times' is nil or if
23496 it has a `diary' type."
23497 (let ((type (org-element-property :type timestamp)))
23498 (if (or (not org-display-custom-times) (eq type 'diary))
23499 (org-element-interpret-data timestamp)
23500 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23501 org-time-stamp-custom-formats)))
23502 (if (and (not boundary) (memq type '(active-range inactive-range)))
23503 (concat (org-timestamp-format timestamp fmt)
23504 "--"
23505 (org-timestamp-format timestamp fmt t))
23506 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23510 ;;; Other stuff.
23512 (defvar reftex-docstruct-symbol)
23513 (defvar org--rds)
23515 (defun org-reftex-citation ()
23516 "Use reftex-citation to insert a citation into the buffer.
23517 This looks for a line like
23519 #+BIBLIOGRAPHY: foo plain option:-d
23521 and derives from it that foo.bib is the bibliography file relevant
23522 for this document. It then installs the necessary environment for RefTeX
23523 to work in this buffer and calls `reftex-citation' to insert a citation
23524 into the buffer.
23526 Export of such citations to both LaTeX and HTML is handled by the contributed
23527 package ox-bibtex by Taru Karttunen."
23528 (interactive)
23529 (let ((reftex-docstruct-symbol 'org--rds)
23530 org--rds bib)
23531 (org-with-wide-buffer
23532 (let ((case-fold-search t)
23533 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23534 (if (not (save-excursion
23535 (or (re-search-forward re nil t)
23536 (re-search-backward re nil t))))
23537 (user-error "No bibliography defined in file")
23538 (setq bib (concat (match-string 1) ".bib")
23539 org--rds (list (list 'bib bib))))))
23540 (call-interactively 'reftex-citation)))
23542 ;;;; Functions extending outline functionality
23544 (defun org-beginning-of-line (&optional n)
23545 "Go to the beginning of the current visible line.
23547 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23548 tags on the first attempt, and only move to after the tags when
23549 the cursor is already beyond the end of the headline.
23551 With argument N not nil or 1, move forward N - 1 lines first."
23552 (interactive "^p")
23553 (let ((origin (point))
23554 (special (pcase org-special-ctrl-a/e
23555 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23556 deactivate-mark)
23557 ;; First move to a visible line.
23558 (if (bound-and-true-p visual-line-mode)
23559 (beginning-of-visual-line n)
23560 (move-beginning-of-line n)
23561 ;; `move-beginning-of-line' may leave point after invisible
23562 ;; characters if line starts with such of these (e.g., with
23563 ;; a link at column 0). Really move to the beginning of the
23564 ;; current visible line.
23565 (beginning-of-line))
23566 (cond
23567 ;; No special behavior. Point is already at the beginning of
23568 ;; a line, logical or visual.
23569 ((not special))
23570 ;; `beginning-of-visual-line' left point before logical beginning
23571 ;; of line: point is at the beginning of a visual line. Bail
23572 ;; out.
23573 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23574 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23575 ;; At a headline, special position is before the title, but
23576 ;; after any TODO keyword or priority cookie.
23577 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23578 (line-end-position)))
23579 (bol (point)))
23580 (if (eq special 'reversed)
23581 (when (and (= origin bol) (eq last-command this-command))
23582 (goto-char refpos))
23583 (when (or (> origin refpos) (= origin bol))
23584 (goto-char refpos)))))
23585 ((and (looking-at org-list-full-item-re)
23586 (memq (org-element-type (save-match-data (org-element-at-point)))
23587 '(item plain-list)))
23588 ;; Set special position at first white space character after
23589 ;; bullet, and check-box, if any.
23590 (let ((after-bullet
23591 (let ((box (match-end 3)))
23592 (cond ((not box) (match-end 1))
23593 ((eq (char-after box) ?\s) (1+ box))
23594 (t box)))))
23595 (if (eq special 'reversed)
23596 (when (and (= (point) origin) (eq last-command this-command))
23597 (goto-char after-bullet))
23598 (when (or (> origin after-bullet) (= (point) origin))
23599 (goto-char after-bullet)))))
23600 ;; No special context. Point is already at beginning of line.
23601 (t nil))))
23603 (defun org-end-of-line (&optional n)
23604 "Go to the end of the line, but before ellipsis, if any.
23606 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23607 tags on the first attempt, and only move to after the tags when
23608 the cursor is already beyond the end of the headline.
23610 With argument N not nil or 1, move forward N - 1 lines first."
23611 (interactive "^p")
23612 (let ((origin (point))
23613 (special (pcase org-special-ctrl-a/e
23614 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23615 deactivate-mark)
23616 ;; First move to a visible line.
23617 (if (bound-and-true-p visual-line-mode)
23618 (beginning-of-visual-line n)
23619 (move-beginning-of-line n))
23620 (cond
23621 ;; At a headline, with tags.
23622 ((and special
23623 (save-excursion
23624 (beginning-of-line)
23625 (let ((case-fold-search nil))
23626 (looking-at org-complex-heading-regexp)))
23627 (match-end 5))
23628 (let ((tags (save-excursion
23629 (goto-char (match-beginning 5))
23630 (skip-chars-backward " \t")
23631 (point)))
23632 (visual-end (and (bound-and-true-p visual-line-mode)
23633 (save-excursion
23634 (end-of-visual-line)
23635 (point)))))
23636 ;; If `end-of-visual-line' brings us before end of line or
23637 ;; even tags, i.e., the headline spans over multiple visual
23638 ;; lines, move there.
23639 (cond ((and visual-end
23640 (< visual-end tags)
23641 (<= origin visual-end))
23642 (goto-char visual-end))
23643 ((eq special 'reversed)
23644 (if (and (= origin (line-end-position))
23645 (eq this-command last-command))
23646 (goto-char tags)
23647 (end-of-line)))
23649 (if (or (< origin tags) (= origin (line-end-position)))
23650 (goto-char tags)
23651 (end-of-line))))))
23652 ((bound-and-true-p visual-line-mode)
23653 (let ((bol (line-beginning-position)))
23654 (end-of-visual-line)
23655 ;; If `end-of-visual-line' gets us past the ellipsis at the
23656 ;; end of a line, backtrack and use `end-of-line' instead.
23657 (when (/= bol (line-beginning-position))
23658 (goto-char bol)
23659 (end-of-line))))
23660 (t (end-of-line)))))
23662 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23663 (define-key org-mode-map "\C-e" 'org-end-of-line)
23665 (defun org-backward-sentence (&optional _arg)
23666 "Go to beginning of sentence, or beginning of table field.
23667 This will call `backward-sentence' or `org-table-beginning-of-field',
23668 depending on context."
23669 (interactive)
23670 (let* ((element (org-element-at-point))
23671 (contents-begin (org-element-property :contents-begin element))
23672 (table (org-element-lineage element '(table) t)))
23673 (if (and table
23674 (> (point) contents-begin)
23675 (<= (point) (org-element-property :contents-end table)))
23676 (call-interactively #'org-table-beginning-of-field)
23677 (save-restriction
23678 (when (and contents-begin
23679 (< (point-min) contents-begin)
23680 (> (point) contents-begin))
23681 (narrow-to-region contents-begin
23682 (org-element-property :contents-end element)))
23683 (call-interactively #'backward-sentence)))))
23685 (defun org-forward-sentence (&optional _arg)
23686 "Go to end of sentence, or end of table field.
23687 This will call `forward-sentence' or `org-table-end-of-field',
23688 depending on context."
23689 (interactive)
23690 (let* ((element (org-element-at-point))
23691 (contents-end (org-element-property :contents-end element))
23692 (table (org-element-lineage element '(table) t)))
23693 (if (and table
23694 (>= (point) (org-element-property :contents-begin table))
23695 (< (point) contents-end))
23696 (call-interactively #'org-table-end-of-field)
23697 (save-restriction
23698 (when (and contents-end
23699 (> (point-max) contents-end)
23700 ;; Skip blank lines between elements.
23701 (< (org-element-property :end element)
23702 (save-excursion (goto-char contents-end)
23703 (skip-chars-forward " \r\t\n"))))
23704 (narrow-to-region (org-element-property :contents-begin element)
23705 contents-end))
23706 (call-interactively #'forward-sentence)))))
23708 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23709 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23711 (defun org-kill-line (&optional _arg)
23712 "Kill line, to tags or end of line."
23713 (interactive)
23714 (cond
23715 ((or (not org-special-ctrl-k)
23716 (bolp)
23717 (not (org-at-heading-p)))
23718 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23719 org-ctrl-k-protect-subtree
23720 (or (eq org-ctrl-k-protect-subtree 'error)
23721 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23722 (user-error "C-k aborted as it would kill a hidden subtree"))
23723 (call-interactively
23724 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23725 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23726 (kill-region (point) (match-beginning 1))
23727 (org-set-tags nil t))
23728 (t (kill-region (point) (point-at-eol)))))
23730 (define-key org-mode-map "\C-k" 'org-kill-line)
23732 (defun org-yank (&optional arg)
23733 "Yank. If the kill is a subtree, treat it specially.
23734 This command will look at the current kill and check if is a single
23735 subtree, or a series of subtrees[1]. If it passes the test, and if the
23736 cursor is at the beginning of a line or after the stars of a currently
23737 empty headline, then the yank is handled specially. How exactly depends
23738 on the value of the following variables.
23740 `org-yank-folded-subtrees'
23741 By default, this variable is non-nil, which results in
23742 subtree(s) being folded after insertion, except if doing so
23743 would swallow text after the yanked text.
23745 `org-yank-adjusted-subtrees'
23746 When non-nil (the default value is nil), the subtree will be
23747 promoted or demoted in order to fit into the local outline tree
23748 structure, which means that the level will be adjusted so that it
23749 becomes the smaller one of the two *visible* surrounding headings.
23751 Any prefix to this command will cause `yank' to be called directly with
23752 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23753 will just
23754 plainly yank the text as it is.
23756 \[1] The test checks if the first non-white line is a heading
23757 and if there are no other headings with fewer stars."
23758 (interactive "P")
23759 (org-yank-generic 'yank arg))
23761 (defun org-yank-generic (command arg)
23762 "Perform some yank-like command.
23764 This function implements the behavior described in the `org-yank'
23765 documentation. However, it has been generalized to work for any
23766 interactive command with similar behavior."
23768 ;; pretend to be command COMMAND
23769 (setq this-command command)
23771 (if arg
23772 (call-interactively command)
23774 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23775 (and (org-kill-is-subtree-p)
23776 (or (bolp)
23777 (and (looking-at "[ \t]*$")
23778 (string-match
23779 "\\`\\*+\\'"
23780 (buffer-substring (point-at-bol) (point)))))))
23781 swallowp)
23782 (cond
23783 ((and subtreep org-yank-folded-subtrees)
23784 (let ((beg (point))
23785 end)
23786 (if (and subtreep org-yank-adjusted-subtrees)
23787 (org-paste-subtree nil nil 'for-yank)
23788 (call-interactively command))
23790 (setq end (point))
23791 (goto-char beg)
23792 (when (and (bolp) subtreep
23793 (not (setq swallowp
23794 (org-yank-folding-would-swallow-text beg end))))
23795 (org-with-limited-levels
23796 (or (looking-at org-outline-regexp)
23797 (re-search-forward org-outline-regexp-bol end t))
23798 (while (and (< (point) end) (looking-at org-outline-regexp))
23799 (outline-hide-subtree)
23800 (org-cycle-show-empty-lines 'folded)
23801 (condition-case nil
23802 (outline-forward-same-level 1)
23803 (error (goto-char end))))))
23804 (when swallowp
23805 (message
23806 "Inserted text not folded because that would swallow text"))
23808 (goto-char end)
23809 (skip-chars-forward " \t\n\r")
23810 (beginning-of-line 1)
23811 (push-mark beg 'nomsg)))
23812 ((and subtreep org-yank-adjusted-subtrees)
23813 (let ((beg (point-at-bol)))
23814 (org-paste-subtree nil nil 'for-yank)
23815 (push-mark beg 'nomsg)))
23817 (call-interactively command))))))
23819 (defun org-yank-folding-would-swallow-text (beg end)
23820 "Would hide-subtree at BEG swallow any text after END?"
23821 (let (level)
23822 (org-with-limited-levels
23823 (save-excursion
23824 (goto-char beg)
23825 (when (or (looking-at org-outline-regexp)
23826 (re-search-forward org-outline-regexp-bol end t))
23827 (setq level (org-outline-level)))
23828 (goto-char end)
23829 (skip-chars-forward " \t\r\n\v\f")
23830 (not (or (eobp)
23831 (and (bolp) (looking-at-p org-outline-regexp)
23832 (<= (org-outline-level) level))))))))
23834 (define-key org-mode-map "\C-y" 'org-yank)
23836 (defun org-truely-invisible-p ()
23837 "Check if point is at a character currently not visible.
23838 This version does not only check the character property, but also
23839 `visible-mode'."
23840 ;; Early versions of noutline don't have `outline-invisible-p'.
23841 (unless (bound-and-true-p visible-mode)
23842 (outline-invisible-p)))
23844 (defun org-invisible-p2 ()
23845 "Check if point is at a character currently not visible."
23846 (save-excursion
23847 (when (and (eolp) (not (bobp))) (backward-char 1))
23848 ;; Early versions of noutline don't have `outline-invisible-p'.
23849 (outline-invisible-p)))
23851 (defun org-back-to-heading (&optional invisible-ok)
23852 "Call `outline-back-to-heading', but provide a better error message."
23853 (condition-case nil
23854 (outline-back-to-heading invisible-ok)
23855 (error (error "Before first headline at position %d in buffer %s"
23856 (point) (current-buffer)))))
23858 (defun org-before-first-heading-p ()
23859 "Before first heading?"
23860 (save-excursion
23861 (end-of-line)
23862 (null (re-search-backward org-outline-regexp-bol nil t))))
23864 (defun org-at-heading-p (&optional ignored)
23865 (outline-on-heading-p t))
23867 (defun org-in-commented-heading-p (&optional no-inheritance)
23868 "Non-nil if point is under a commented heading.
23869 This function also checks ancestors of the current headline,
23870 unless optional argument NO-INHERITANCE is non-nil."
23871 (cond
23872 ((org-before-first-heading-p) nil)
23873 ((let ((headline (nth 4 (org-heading-components))))
23874 (and headline
23875 (let ((case-fold-search nil))
23876 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23877 headline)))))
23878 (no-inheritance nil)
23880 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23882 (defun org-at-comment-p nil
23883 "Is cursor in a commented line?"
23884 (save-excursion
23885 (save-match-data
23886 (beginning-of-line)
23887 (looking-at "^[ \t]*# "))))
23889 (defun org-at-drawer-p nil
23890 "Is cursor at a drawer keyword?"
23891 (save-excursion
23892 (move-beginning-of-line 1)
23893 (looking-at org-drawer-regexp)))
23895 (defun org-at-block-p nil
23896 "Is cursor at a block keyword?"
23897 (save-excursion
23898 (move-beginning-of-line 1)
23899 (looking-at org-block-regexp)))
23901 (defun org-point-at-end-of-empty-headline ()
23902 "If point is at the end of an empty headline, return t, else nil.
23903 If the heading only contains a TODO keyword, it is still still considered
23904 empty."
23905 (let ((case-fold-search nil))
23906 (and (looking-at "[ \t]*$")
23907 org-todo-line-regexp
23908 (save-excursion
23909 (beginning-of-line)
23910 (looking-at org-todo-line-regexp)
23911 (string= (match-string 3) "")))))
23913 (defun org-at-heading-or-item-p ()
23914 (or (org-at-heading-p) (org-at-item-p)))
23916 (defun org-at-target-p ()
23917 (or (org-in-regexp org-radio-target-regexp)
23918 (org-in-regexp org-target-regexp)))
23919 ;; Compatibility alias with Org versions < 7.8.03
23920 (defalias 'org-on-target-p 'org-at-target-p)
23922 (defun org-up-heading-all (arg)
23923 "Move to the heading line of which the present line is a subheading.
23924 This function considers both visible and invisible heading lines.
23925 With argument, move up ARG levels."
23926 (outline-up-heading arg t))
23928 (defun org-up-heading-safe ()
23929 "Move to the heading line of which the present line is a subheading.
23930 This version will not throw an error. It will return the level of the
23931 headline found, or nil if no higher level is found.
23933 Also, this function will be a lot faster than `outline-up-heading',
23934 because it relies on stars being the outline starters. This can really
23935 make a significant difference in outlines with very many siblings."
23936 (when (ignore-errors (org-back-to-heading t))
23937 (let ((level-up (1- (funcall outline-level))))
23938 (and (> level-up 0)
23939 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23940 (funcall outline-level)))))
23942 (defun org-first-sibling-p ()
23943 "Is this heading the first child of its parents?"
23944 (interactive)
23945 (let ((re org-outline-regexp-bol)
23946 level l)
23947 (unless (org-at-heading-p t)
23948 (user-error "Not at a heading"))
23949 (setq level (funcall outline-level))
23950 (save-excursion
23951 (if (not (re-search-backward re nil t))
23953 (setq l (funcall outline-level))
23954 (< l level)))))
23956 (defun org-goto-sibling (&optional previous)
23957 "Goto the next sibling, even if it is invisible.
23958 When PREVIOUS is set, go to the previous sibling instead. Returns t
23959 when a sibling was found. When none is found, return nil and don't
23960 move point."
23961 (let ((fun (if previous 're-search-backward 're-search-forward))
23962 (pos (point))
23963 (re org-outline-regexp-bol)
23964 level l)
23965 (when (ignore-errors (org-back-to-heading t))
23966 (setq level (funcall outline-level))
23967 (catch 'exit
23968 (or previous (forward-char 1))
23969 (while (funcall fun re nil t)
23970 (setq l (funcall outline-level))
23971 (when (< l level) (goto-char pos) (throw 'exit nil))
23972 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23973 (goto-char pos)
23974 nil))))
23976 (defun org-show-siblings ()
23977 "Show all siblings of the current headline."
23978 (save-excursion
23979 (while (org-goto-sibling) (org-flag-heading nil)))
23980 (save-excursion
23981 (while (org-goto-sibling 'previous)
23982 (org-flag-heading nil))))
23984 (defun org-goto-first-child ()
23985 "Goto the first child, even if it is invisible.
23986 Return t when a child was found. Otherwise don't move point and
23987 return nil."
23988 (let (level (pos (point)) (re org-outline-regexp-bol))
23989 (when (ignore-errors (org-back-to-heading t))
23990 (setq level (outline-level))
23991 (forward-char 1)
23992 (if (and (re-search-forward re nil t) (> (outline-level) level))
23993 (progn (goto-char (match-beginning 0)) t)
23994 (goto-char pos) nil))))
23996 (defun org-show-hidden-entry ()
23997 "Show an entry where even the heading is hidden."
23998 (save-excursion
23999 (org-show-entry)))
24001 (defun org-flag-heading (flag &optional entry)
24002 "Flag the current heading. FLAG non-nil means make invisible.
24003 When ENTRY is non-nil, show the entire entry."
24004 (save-excursion
24005 (org-back-to-heading t)
24006 ;; Check if we should show the entire entry
24007 (if entry
24008 (progn
24009 (org-show-entry)
24010 (save-excursion
24011 (and (outline-next-heading)
24012 (org-flag-heading nil))))
24013 (outline-flag-region (max (point-min) (1- (point)))
24014 (save-excursion (outline-end-of-heading) (point))
24015 flag))))
24017 (defun org-get-next-sibling ()
24018 "Move to next heading of the same level, and return point.
24019 If there is no such heading, return nil.
24020 This is like outline-next-sibling, but invisible headings are ok."
24021 (let ((level (funcall outline-level)))
24022 (outline-next-heading)
24023 (while (and (not (eobp)) (> (funcall outline-level) level))
24024 (outline-next-heading))
24025 (unless (or (eobp) (< (funcall outline-level) level))
24026 (point))))
24028 (defun org-get-last-sibling ()
24029 "Move to previous heading of the same level, and return point.
24030 If there is no such heading, return nil."
24031 (let ((opoint (point))
24032 (level (funcall outline-level)))
24033 (outline-previous-heading)
24034 (when (and (/= (point) opoint) (outline-on-heading-p t))
24035 (while (and (> (funcall outline-level) level)
24036 (not (bobp)))
24037 (outline-previous-heading))
24038 (unless (< (funcall outline-level) level)
24039 (point)))))
24041 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24042 "Goto to the end of a subtree."
24043 ;; This contains an exact copy of the original function, but it uses
24044 ;; `org-back-to-heading', to make it work also in invisible
24045 ;; trees. And is uses an invisible-ok argument.
24046 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24047 ;; Furthermore, when used inside Org, finding the end of a large subtree
24048 ;; with many children and grandchildren etc, this can be much faster
24049 ;; than the outline version.
24050 (org-back-to-heading invisible-ok)
24051 (let ((first t)
24052 (level (funcall outline-level)))
24053 (if (and (derived-mode-p 'org-mode) (< level 1000))
24054 ;; A true heading (not a plain list item), in Org
24055 ;; This means we can easily find the end by looking
24056 ;; only for the right number of stars. Using a regexp to do
24057 ;; this is so much faster than using a Lisp loop.
24058 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24059 (forward-char 1)
24060 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24061 ;; something else, do it the slow way
24062 (while (and (not (eobp))
24063 (or first (> (funcall outline-level) level)))
24064 (setq first nil)
24065 (outline-next-heading)))
24066 (unless to-heading
24067 (when (memq (preceding-char) '(?\n ?\^M))
24068 ;; Go to end of line before heading
24069 (forward-char -1)
24070 (when (memq (preceding-char) '(?\n ?\^M))
24071 ;; leave blank line before heading
24072 (forward-char -1)))))
24073 (point))
24075 (defun org-end-of-meta-data (&optional full)
24076 "Skip planning line and properties drawer in current entry.
24077 When optional argument FULL is non-nil, also skip empty lines,
24078 clocking lines and regular drawers at the beginning of the
24079 entry."
24080 (org-back-to-heading t)
24081 (forward-line)
24082 (when (looking-at-p org-planning-line-re) (forward-line))
24083 (when (looking-at org-property-drawer-re)
24084 (goto-char (match-end 0))
24085 (forward-line))
24086 (when (and full (not (org-at-heading-p)))
24087 (catch 'exit
24088 (let ((end (save-excursion (outline-next-heading) (point)))
24089 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24090 (while (not (eobp))
24091 (cond ((looking-at-p org-drawer-regexp)
24092 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24093 (forward-line)
24094 (throw 'exit t)))
24095 ((looking-at-p re) (forward-line))
24096 (t (throw 'exit t))))))))
24098 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24099 "Move forward to the ARG'th subheading at same level as this one.
24100 Stop at the first and last subheadings of a superior heading.
24101 Normally this only looks at visible headings, but when INVISIBLE-OK is
24102 non-nil it will also look at invisible ones."
24103 (interactive "p")
24104 (let ((backward? (and arg (< arg 0))))
24105 (if (org-before-first-heading-p)
24106 (if backward? (goto-char (point-min)) (outline-next-heading))
24107 (org-back-to-heading invisible-ok)
24108 (unless backward? (end-of-line)) ;do not match current headline
24109 (let ((level (- (match-end 0) (match-beginning 0) 1))
24110 (f (if backward? #'re-search-backward #'re-search-forward))
24111 (count (if arg (abs arg) 1))
24112 (result (point)))
24113 (while (and (> count 0)
24114 (funcall f org-outline-regexp-bol nil 'move))
24115 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24116 (cond ((< l level) (setq count 0))
24117 ((and (= l level)
24118 (or invisible-ok
24119 (not (outline-invisible-p
24120 (line-beginning-position)))))
24121 (cl-decf count)
24122 (when (= l level) (setq result (point)))))))
24123 (goto-char result))
24124 (beginning-of-line))))
24126 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24127 "Move backward to the ARG'th subheading at same level as this one.
24128 Stop at the first and last subheadings of a superior heading."
24129 (interactive "p")
24130 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24132 (defun org-next-visible-heading (arg)
24133 "Move to the next visible heading.
24135 This function wraps `outline-next-visible-heading' with
24136 `org-with-limited-levels' in order to skip over inline tasks and
24137 respect customization of `org-odd-levels-only'."
24138 (interactive "p")
24139 (org-with-limited-levels
24140 (outline-next-visible-heading arg)))
24142 (defun org-previous-visible-heading (arg)
24143 "Move to the previous visible heading.
24145 This function wraps `outline-previous-visible-heading' with
24146 `org-with-limited-levels' in order to skip over inline tasks and
24147 respect customization of `org-odd-levels-only'."
24148 (interactive "p")
24149 (org-with-limited-levels
24150 (outline-previous-visible-heading arg)))
24152 (defun org-next-block (arg &optional backward block-regexp)
24153 "Jump to the next block.
24155 With a prefix argument ARG, jump forward ARG many blocks.
24157 When BACKWARD is non-nil, jump to the previous block.
24159 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24160 Match data is set according to this regexp when the function
24161 returns.
24163 Return point at beginning of the opening line of found block.
24164 Throw an error if no block is found."
24165 (interactive "p")
24166 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24167 (case-fold-search t)
24168 (search-fn (if backward #'re-search-backward #'re-search-forward))
24169 (count (or arg 1))
24170 (origin (point))
24171 last-element)
24172 (if backward (beginning-of-line) (end-of-line))
24173 (while (and (> count 0) (funcall search-fn re nil t))
24174 (let ((element (save-excursion
24175 (goto-char (match-beginning 0))
24176 (save-match-data (org-element-at-point)))))
24177 (when (and (memq (org-element-type element)
24178 '(center-block comment-block dynamic-block
24179 example-block export-block quote-block
24180 special-block src-block verse-block))
24181 (<= (match-beginning 0)
24182 (org-element-property :post-affiliated element)))
24183 (setq last-element element)
24184 (cl-decf count))))
24185 (if (= count 0)
24186 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24187 (save-match-data (org-show-context)))
24188 (goto-char origin)
24189 (user-error "No %s code blocks" (if backward "previous" "further")))))
24191 (defun org-previous-block (arg &optional block-regexp)
24192 "Jump to the previous block.
24193 With a prefix argument ARG, jump backward ARG many source blocks.
24194 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24195 (interactive "p")
24196 (org-next-block arg t block-regexp))
24198 (defun org-forward-paragraph ()
24199 "Move forward to beginning of next paragraph or equivalent.
24201 The function moves point to the beginning of the next visible
24202 structural element, which can be a paragraph, a table, a list
24203 item, etc. It also provides some special moves for convenience:
24205 - On an affiliated keyword, jump to the beginning of the
24206 relative element.
24207 - On an item or a footnote definition, move to the second
24208 element inside, if any.
24209 - On a table or a property drawer, jump after it.
24210 - On a verse or source block, stop after blank lines."
24211 (interactive)
24212 (when (eobp) (user-error "Cannot move further down"))
24213 (let* ((deactivate-mark nil)
24214 (element (org-element-at-point))
24215 (type (org-element-type element))
24216 (post-affiliated (org-element-property :post-affiliated element))
24217 (contents-begin (org-element-property :contents-begin element))
24218 (contents-end (org-element-property :contents-end element))
24219 (end (let ((end (org-element-property :end element)) (parent element))
24220 (while (and (setq parent (org-element-property :parent parent))
24221 (= (org-element-property :contents-end parent) end))
24222 (setq end (org-element-property :end parent)))
24223 end)))
24224 (cond ((not element)
24225 (skip-chars-forward " \r\t\n")
24226 (or (eobp) (beginning-of-line)))
24227 ;; On affiliated keywords, move to element's beginning.
24228 ((< (point) post-affiliated)
24229 (goto-char post-affiliated))
24230 ;; At a table row, move to the end of the table. Similarly,
24231 ;; at a node property, move to the end of the property
24232 ;; drawer.
24233 ((memq type '(node-property table-row))
24234 (goto-char (org-element-property
24235 :end (org-element-property :parent element))))
24236 ((memq type '(property-drawer table)) (goto-char end))
24237 ;; Consider blank lines as separators in verse and source
24238 ;; blocks to ease editing.
24239 ((memq type '(src-block verse-block))
24240 (when (eq type 'src-block)
24241 (setq contents-end
24242 (save-excursion (goto-char end)
24243 (skip-chars-backward " \r\t\n")
24244 (line-beginning-position))))
24245 (beginning-of-line)
24246 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24247 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24248 (goto-char end)
24249 (skip-chars-forward " \r\t\n")
24250 (if (= (point) contents-end) (goto-char end)
24251 (beginning-of-line))))
24252 ;; With no contents, just skip element.
24253 ((not contents-begin) (goto-char end))
24254 ;; If contents are invisible, skip the element altogether.
24255 ((outline-invisible-p (line-end-position))
24256 (cl-case type
24257 (headline
24258 (org-with-limited-levels (outline-next-visible-heading 1)))
24259 ;; At a plain list, make sure we move to the next item
24260 ;; instead of skipping the whole list.
24261 (plain-list (forward-char)
24262 (org-forward-paragraph))
24263 (otherwise (goto-char end))))
24264 ((>= (point) contents-end) (goto-char end))
24265 ((>= (point) contents-begin)
24266 ;; This can only happen on paragraphs and plain lists.
24267 (cl-case type
24268 (paragraph (goto-char end))
24269 ;; At a plain list, try to move to second element in
24270 ;; first item, if possible.
24271 (plain-list (end-of-line)
24272 (org-forward-paragraph))))
24273 ;; When contents start on the middle of a line (e.g. in
24274 ;; items and footnote definitions), try to reach first
24275 ;; element starting after current line.
24276 ((> (line-end-position) contents-begin)
24277 (end-of-line)
24278 (org-forward-paragraph))
24279 (t (goto-char contents-begin)))))
24281 (defun org-backward-paragraph ()
24282 "Move backward to start of previous paragraph or equivalent.
24284 The function moves point to the beginning of the current
24285 structural element, which can be a paragraph, a table, a list
24286 item, etc., or to the beginning of the previous visible one if
24287 point is already there. It also provides some special moves for
24288 convenience:
24290 - On an affiliated keyword, jump to the first one.
24291 - On a table or a property drawer, move to its beginning.
24292 - On a verse or source block, stop before blank lines."
24293 (interactive)
24294 (when (bobp) (user-error "Cannot move further up"))
24295 (let* ((deactivate-mark nil)
24296 (element (org-element-at-point))
24297 (type (org-element-type element))
24298 (contents-begin (org-element-property :contents-begin element))
24299 (contents-end (org-element-property :contents-end element))
24300 (post-affiliated (org-element-property :post-affiliated element))
24301 (begin (org-element-property :begin element)))
24302 (cond
24303 ((not element) (goto-char (point-min)))
24304 ((= (point) begin)
24305 (backward-char)
24306 (org-backward-paragraph))
24307 ((<= (point) post-affiliated) (goto-char begin))
24308 ((memq type '(node-property table-row))
24309 (goto-char (org-element-property
24310 :post-affiliated (org-element-property :parent element))))
24311 ((memq type '(property-drawer table)) (goto-char begin))
24312 ((memq type '(src-block verse-block))
24313 (when (eq type 'src-block)
24314 (setq contents-begin
24315 (save-excursion (goto-char begin) (forward-line) (point))))
24316 (if (= (point) contents-begin) (goto-char post-affiliated)
24317 ;; Inside a verse block, see blank lines as paragraph
24318 ;; separators.
24319 (let ((origin (point)))
24320 (skip-chars-backward " \r\t\n" contents-begin)
24321 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24322 (skip-chars-forward " \r\t\n" origin)
24323 (if (= (point) origin) (goto-char contents-begin)
24324 (beginning-of-line))))))
24325 ((not contents-begin) (goto-char (or post-affiliated begin)))
24326 ((eq type 'paragraph)
24327 (goto-char contents-begin)
24328 ;; When at first paragraph in an item or a footnote definition,
24329 ;; move directly to beginning of line.
24330 (let ((parent-contents
24331 (org-element-property
24332 :contents-begin (org-element-property :parent element))))
24333 (when (and parent-contents (= parent-contents contents-begin))
24334 (beginning-of-line))))
24335 ;; At the end of a greater element, move to the beginning of the
24336 ;; last element within.
24337 ((>= (point) contents-end)
24338 (goto-char (1- contents-end))
24339 (org-backward-paragraph))
24340 (t (goto-char (or post-affiliated begin))))
24341 ;; Ensure we never leave point invisible.
24342 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24344 (defun org-forward-element ()
24345 "Move forward by one element.
24346 Move to the next element at the same level, when possible."
24347 (interactive)
24348 (cond ((eobp) (user-error "Cannot move further down"))
24349 ((org-with-limited-levels (org-at-heading-p))
24350 (let ((origin (point)))
24351 (goto-char (org-end-of-subtree nil t))
24352 (unless (org-with-limited-levels (org-at-heading-p))
24353 (goto-char origin)
24354 (user-error "Cannot move further down"))))
24356 (let* ((elem (org-element-at-point))
24357 (end (org-element-property :end elem))
24358 (parent (org-element-property :parent elem)))
24359 (cond ((and parent (= (org-element-property :contents-end parent) end))
24360 (goto-char (org-element-property :end parent)))
24361 ((integer-or-marker-p end) (goto-char end))
24362 (t (message "No element at point")))))))
24364 (defun org-backward-element ()
24365 "Move backward by one element.
24366 Move to the previous element at the same level, when possible."
24367 (interactive)
24368 (cond ((bobp) (user-error "Cannot move further up"))
24369 ((org-with-limited-levels (org-at-heading-p))
24370 ;; At a headline, move to the previous one, if any, or stay
24371 ;; here.
24372 (let ((origin (point)))
24373 (org-with-limited-levels (org-backward-heading-same-level 1))
24374 ;; When current headline has no sibling above, move to its
24375 ;; parent.
24376 (when (= (point) origin)
24377 (or (org-with-limited-levels (org-up-heading-safe))
24378 (progn (goto-char origin)
24379 (user-error "Cannot move further up"))))))
24381 (let* ((elem (org-element-at-point))
24382 (beg (org-element-property :begin elem)))
24383 (cond
24384 ;; Move to beginning of current element if point isn't
24385 ;; there already.
24386 ((null beg) (message "No element at point"))
24387 ((/= (point) beg) (goto-char beg))
24388 (t (goto-char beg)
24389 (skip-chars-backward " \r\t\n")
24390 (unless (bobp)
24391 (let ((prev (org-element-at-point)))
24392 (goto-char (org-element-property :begin prev))
24393 (while (and (setq prev (org-element-property :parent prev))
24394 (<= (org-element-property :end prev) beg))
24395 (goto-char (org-element-property :begin prev)))))))))))
24397 (defun org-up-element ()
24398 "Move to upper element."
24399 (interactive)
24400 (if (org-with-limited-levels (org-at-heading-p))
24401 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24402 (let* ((elem (org-element-at-point))
24403 (parent (org-element-property :parent elem)))
24404 (if parent (goto-char (org-element-property :begin parent))
24405 (if (org-with-limited-levels (org-before-first-heading-p))
24406 (user-error "No surrounding element")
24407 (org-with-limited-levels (org-back-to-heading)))))))
24409 (defvar org-element-greater-elements)
24410 (defun org-down-element ()
24411 "Move to inner element."
24412 (interactive)
24413 (let ((element (org-element-at-point)))
24414 (cond
24415 ((memq (org-element-type element) '(plain-list table))
24416 (goto-char (org-element-property :contents-begin element))
24417 (forward-char))
24418 ((memq (org-element-type element) org-element-greater-elements)
24419 ;; If contents are hidden, first disclose them.
24420 (when (outline-invisible-p (line-end-position)) (org-cycle))
24421 (goto-char (or (org-element-property :contents-begin element)
24422 (user-error "No content for this element"))))
24423 (t (user-error "No inner element")))))
24425 (defun org-drag-element-backward ()
24426 "Move backward element at point."
24427 (interactive)
24428 (let ((elem (or (org-element-at-point)
24429 (user-error "No element at point"))))
24430 (if (eq (org-element-type elem) 'headline)
24431 ;; Preserve point when moving a whole tree, even if point was
24432 ;; on blank lines below the headline.
24433 (let ((offset (skip-chars-backward " \t\n")))
24434 (unwind-protect (org-move-subtree-up)
24435 (forward-char (- offset))))
24436 (let ((prev-elem
24437 (save-excursion
24438 (goto-char (org-element-property :begin elem))
24439 (skip-chars-backward " \r\t\n")
24440 (unless (bobp)
24441 (let* ((beg (org-element-property :begin elem))
24442 (prev (org-element-at-point))
24443 (up prev))
24444 (while (and (setq up (org-element-property :parent up))
24445 (<= (org-element-property :end up) beg))
24446 (setq prev up))
24447 prev)))))
24448 ;; Error out if no previous element or previous element is
24449 ;; a parent of the current one.
24450 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24451 (user-error "Cannot drag element backward")
24452 (let ((pos (point)))
24453 (org-element-swap-A-B prev-elem elem)
24454 (goto-char (+ (org-element-property :begin prev-elem)
24455 (- pos (org-element-property :begin elem))))))))))
24457 (defun org-drag-element-forward ()
24458 "Move forward element at point."
24459 (interactive)
24460 (let* ((pos (point))
24461 (elem (or (org-element-at-point)
24462 (user-error "No element at point"))))
24463 (when (= (point-max) (org-element-property :end elem))
24464 (user-error "Cannot drag element forward"))
24465 (goto-char (org-element-property :end elem))
24466 (let ((next-elem (org-element-at-point)))
24467 (when (or (org-element-nested-p elem next-elem)
24468 (and (eq (org-element-type next-elem) 'headline)
24469 (not (eq (org-element-type elem) 'headline))))
24470 (goto-char pos)
24471 (user-error "Cannot drag element forward"))
24472 ;; Compute new position of point: it's shifted by NEXT-ELEM
24473 ;; body's length (without final blanks) and by the length of
24474 ;; blanks between ELEM and NEXT-ELEM.
24475 (let ((size-next (- (save-excursion
24476 (goto-char (org-element-property :end next-elem))
24477 (skip-chars-backward " \r\t\n")
24478 (forward-line)
24479 ;; Small correction if buffer doesn't end
24480 ;; with a newline character.
24481 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24482 (org-element-property :begin next-elem)))
24483 (size-blank (- (org-element-property :end elem)
24484 (save-excursion
24485 (goto-char (org-element-property :end elem))
24486 (skip-chars-backward " \r\t\n")
24487 (forward-line)
24488 (point)))))
24489 (org-element-swap-A-B elem next-elem)
24490 (goto-char (+ pos size-next size-blank))))))
24492 (defun org-drag-line-forward (arg)
24493 "Drag the line at point ARG lines forward."
24494 (interactive "p")
24495 (dotimes (_ (abs arg))
24496 (let ((c (current-column)))
24497 (if (< 0 arg)
24498 (progn
24499 (beginning-of-line 2)
24500 (transpose-lines 1)
24501 (beginning-of-line 0))
24502 (transpose-lines 1)
24503 (beginning-of-line -1))
24504 (org-move-to-column c))))
24506 (defun org-drag-line-backward (arg)
24507 "Drag the line at point ARG lines backward."
24508 (interactive "p")
24509 (org-drag-line-forward (- arg)))
24511 (defun org-mark-element ()
24512 "Put point at beginning of this element, mark at end.
24514 Interactively, if this command is repeated or (in Transient Mark
24515 mode) if the mark is active, it marks the next element after the
24516 ones already marked."
24517 (interactive)
24518 (let (deactivate-mark)
24519 (if (and (called-interactively-p 'any)
24520 (or (and (eq last-command this-command) (mark t))
24521 (and transient-mark-mode mark-active)))
24522 (set-mark
24523 (save-excursion
24524 (goto-char (mark))
24525 (goto-char (org-element-property :end (org-element-at-point)))))
24526 (let ((element (org-element-at-point)))
24527 (end-of-line)
24528 (push-mark (org-element-property :end element) t t)
24529 (goto-char (org-element-property :begin element))))))
24531 (defun org-narrow-to-element ()
24532 "Narrow buffer to current element."
24533 (interactive)
24534 (let ((elem (org-element-at-point)))
24535 (cond
24536 ((eq (car elem) 'headline)
24537 (narrow-to-region
24538 (org-element-property :begin elem)
24539 (org-element-property :end elem)))
24540 ((memq (car elem) org-element-greater-elements)
24541 (narrow-to-region
24542 (org-element-property :contents-begin elem)
24543 (org-element-property :contents-end elem)))
24545 (narrow-to-region
24546 (org-element-property :begin elem)
24547 (org-element-property :end elem))))))
24549 (defun org-transpose-element ()
24550 "Transpose current and previous elements, keeping blank lines between.
24551 Point is moved after both elements."
24552 (interactive)
24553 (org-skip-whitespace)
24554 (let ((end (org-element-property :end (org-element-at-point))))
24555 (org-drag-element-backward)
24556 (goto-char end)))
24558 (defun org-unindent-buffer ()
24559 "Un-indent the visible part of the buffer.
24560 Relative indentation (between items, inside blocks, etc.) isn't
24561 modified."
24562 (interactive)
24563 (unless (eq major-mode 'org-mode)
24564 (user-error "Cannot un-indent a buffer not in Org mode"))
24565 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24566 (unindent-tree
24567 (lambda (contents)
24568 (dolist (element (reverse contents))
24569 (if (memq (org-element-type element) '(headline section))
24570 (funcall unindent-tree (org-element-contents element))
24571 (save-excursion
24572 (save-restriction
24573 (narrow-to-region
24574 (org-element-property :begin element)
24575 (org-element-property :end element))
24576 (org-do-remove-indentation))))))))
24577 (funcall unindent-tree (org-element-contents parse-tree))))
24579 (defun org-show-children (&optional level)
24580 "Show all direct subheadings of this heading.
24581 Prefix arg LEVEL is how many levels below the current level
24582 should be shown. Default is enough to cause the following
24583 heading to appear."
24584 (interactive "p")
24585 ;; If `orgstruct-mode' is active, use the slower version.
24586 (if orgstruct-mode (call-interactively #'outline-show-children)
24587 (save-excursion
24588 (org-back-to-heading t)
24589 (let* ((current-level (funcall outline-level))
24590 (max-level (org-get-valid-level
24591 current-level
24592 (if level (prefix-numeric-value level) 1)))
24593 (end (save-excursion (org-end-of-subtree t t)))
24594 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24595 (past-first-child nil)
24596 ;; Make sure to skip inlinetasks.
24597 (re (format regexp-fmt
24598 current-level
24599 (cond
24600 ((not (featurep 'org-inlinetask)) "")
24601 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24603 (t (1- org-inlinetask-min-level))))))
24604 ;; Display parent heading.
24605 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24606 (forward-line)
24607 ;; Display children. First child may be deeper than expected
24608 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24609 ;; MAX-LEVEL accordingly.
24610 (while (re-search-forward re end t)
24611 (unless past-first-child
24612 (setq re (format regexp-fmt
24613 current-level
24614 (max (funcall outline-level) max-level)))
24615 (setq past-first-child t))
24616 (outline-flag-region
24617 (line-end-position 0) (line-end-position) nil))))))
24619 (defun org-show-subtree ()
24620 "Show everything after this heading at deeper levels."
24621 (interactive)
24622 (outline-flag-region
24623 (point)
24624 (save-excursion
24625 (org-end-of-subtree t t))
24626 nil))
24628 (defun org-show-entry ()
24629 "Show the body directly following this heading.
24630 Show the heading too, if it is currently invisible."
24631 (interactive)
24632 (save-excursion
24633 (ignore-errors
24634 (org-back-to-heading t)
24635 (outline-flag-region
24636 (max (point-min) (1- (point)))
24637 (save-excursion
24638 (if (re-search-forward
24639 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24640 (match-beginning 1)
24641 (point-max)))
24642 nil)
24643 (org-cycle-hide-drawers 'children))))
24645 (defun org-make-options-regexp (kwds &optional extra)
24646 "Make a regular expression for keyword lines.
24647 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24648 when non-nil, is a regexp matching keywords names."
24649 (concat "^[ \t]*#\\+\\("
24650 (regexp-opt kwds)
24651 (and extra (concat (and kwds "\\|") extra))
24652 "\\):[ \t]*\\(.*\\)"))
24654 ;;;; Integration with and fixes for other packages
24656 ;;; Imenu support
24658 (defvar-local org-imenu-markers nil
24659 "All markers currently used by Imenu.")
24661 (defun org-imenu-new-marker (&optional pos)
24662 "Return a new marker for use by Imenu, and remember the marker."
24663 (let ((m (make-marker)))
24664 (move-marker m (or pos (point)))
24665 (push m org-imenu-markers)
24668 (defun org-imenu-get-tree ()
24669 "Produce the index for Imenu."
24670 (dolist (x org-imenu-markers) (move-marker x nil))
24671 (setq org-imenu-markers nil)
24672 (let* ((case-fold-search nil)
24673 (n org-imenu-depth)
24674 (re (concat "^" (org-get-limited-outline-regexp)))
24675 (subs (make-vector (1+ n) nil))
24676 (last-level 0)
24677 m level head0 head)
24678 (org-with-wide-buffer
24679 (goto-char (point-max))
24680 (while (re-search-backward re nil t)
24681 (setq level (org-reduced-level (funcall outline-level)))
24682 (when (and (<= level n)
24683 (looking-at org-complex-heading-regexp)
24684 (setq head0 (match-string-no-properties 4)))
24685 (setq head (org-link-display-format head0)
24686 m (org-imenu-new-marker))
24687 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24688 (if (>= level last-level)
24689 (push (cons head m) (aref subs level))
24690 (push (cons head (aref subs (1+ level))) (aref subs level))
24691 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24692 (setq last-level level))))
24693 (aref subs 1)))
24695 (eval-after-load "imenu"
24696 '(progn
24697 (add-hook 'imenu-after-jump-hook
24698 (lambda ()
24699 (when (derived-mode-p 'org-mode)
24700 (org-show-context 'org-goto))))))
24702 (defun org-link-display-format (s)
24703 "Replace links in string S with their description.
24704 If there is no description, use the link target."
24705 (save-match-data
24706 (replace-regexp-in-string
24707 org-bracket-link-analytic-regexp
24708 (lambda (m)
24709 (if (match-end 5) (match-string 5 m)
24710 (concat (match-string 1 m) (match-string 3 m))))
24711 s nil t)))
24713 (defun org-toggle-link-display ()
24714 "Toggle the literal or descriptive display of links."
24715 (interactive)
24716 (if org-descriptive-links
24717 (progn (org-remove-from-invisibility-spec '(org-link))
24718 (org-restart-font-lock)
24719 (setq org-descriptive-links nil))
24720 (progn (add-to-invisibility-spec '(org-link))
24721 (org-restart-font-lock)
24722 (setq org-descriptive-links t))))
24724 ;; Speedbar support
24726 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24727 "Overlay marking the agenda restriction line in speedbar.")
24728 (overlay-put org-speedbar-restriction-lock-overlay
24729 'face 'org-agenda-restriction-lock)
24730 (overlay-put org-speedbar-restriction-lock-overlay
24731 'help-echo "Agendas are currently limited to this item.")
24732 (delete-overlay org-speedbar-restriction-lock-overlay)
24734 (defun org-speedbar-set-agenda-restriction ()
24735 "Restrict future agenda commands to the location at point in speedbar.
24736 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24737 (interactive)
24738 (require 'org-agenda)
24739 (let (p m tp np dir txt)
24740 (cond
24741 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24742 'org-imenu t))
24743 (setq m (get-text-property p 'org-imenu-marker))
24744 (with-current-buffer (marker-buffer m)
24745 (goto-char m)
24746 (org-agenda-set-restriction-lock 'subtree)))
24747 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24748 'speedbar-function 'speedbar-find-file))
24749 (setq tp (previous-single-property-change
24750 (1+ p) 'speedbar-function)
24751 np (next-single-property-change
24752 tp 'speedbar-function)
24753 dir (speedbar-line-directory)
24754 txt (buffer-substring-no-properties (or tp (point-min))
24755 (or np (point-max))))
24756 (with-current-buffer (find-file-noselect
24757 (let ((default-directory dir))
24758 (expand-file-name txt)))
24759 (unless (derived-mode-p 'org-mode)
24760 (user-error "Cannot restrict to non-Org mode file"))
24761 (org-agenda-set-restriction-lock 'file)))
24762 (t (user-error "Don't know how to restrict Org mode agenda")))
24763 (move-overlay org-speedbar-restriction-lock-overlay
24764 (point-at-bol) (point-at-eol))
24765 (setq current-prefix-arg nil)
24766 (org-agenda-maybe-redo)))
24768 (defvar speedbar-file-key-map)
24769 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24770 (eval-after-load "speedbar"
24771 '(progn
24772 (speedbar-add-supported-extension ".org")
24773 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24774 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24775 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24776 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24777 (add-hook 'speedbar-visiting-tag-hook
24778 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24780 ;;; Fixes and Hacks for problems with other packages
24782 (defun org--flyspell-object-check-p (element)
24783 "Non-nil when Flyspell can check object at point.
24784 ELEMENT is the element at point."
24785 (let ((object (save-excursion
24786 (when (looking-at-p "\\>") (backward-char))
24787 (org-element-context element))))
24788 (cl-case (org-element-type object)
24789 ;; Prevent checks in links due to keybinding conflict with
24790 ;; Flyspell.
24791 ((code entity export-snippet inline-babel-call
24792 inline-src-block line-break latex-fragment link macro
24793 statistics-cookie target timestamp verbatim)
24794 nil)
24795 (footnote-reference
24796 ;; Only in inline footnotes, within the definition.
24797 (and (eq (org-element-property :type object) 'inline)
24798 (< (save-excursion
24799 (goto-char (org-element-property :begin object))
24800 (search-forward ":" nil t 2))
24801 (point))))
24802 (otherwise t))))
24804 (defun org-mode-flyspell-verify ()
24805 "Function used for `flyspell-generic-check-word-predicate'."
24806 (if (org-at-heading-p)
24807 ;; At a headline or an inlinetask, check title only. This is
24808 ;; faster than relying on `org-element-at-point'.
24809 (and (save-excursion (beginning-of-line)
24810 (and (let ((case-fold-search t))
24811 (not (looking-at-p "\\*+ END[ \t]*$")))
24812 (let ((case-fold-search nil))
24813 (looking-at org-complex-heading-regexp))))
24814 (match-beginning 4)
24815 (>= (point) (match-beginning 4))
24816 (or (not (match-beginning 5))
24817 (< (point) (match-beginning 5))))
24818 (let* ((element (org-element-at-point))
24819 (post-affiliated (org-element-property :post-affiliated element)))
24820 (cond
24821 ;; Ignore checks in all affiliated keywords but captions.
24822 ((< (point) post-affiliated)
24823 (and (save-excursion
24824 (beginning-of-line)
24825 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24826 (> (point) (match-end 0))
24827 (org--flyspell-object-check-p element)))
24828 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24829 ((let ((log (org-log-into-drawer)))
24830 (and log
24831 (let ((drawer (org-element-lineage element '(drawer))))
24832 (and drawer
24833 (eq (compare-strings
24834 log nil nil
24835 (org-element-property :drawer-name drawer) nil nil t)
24836 t)))))
24837 nil)
24839 (cl-case (org-element-type element)
24840 ((comment quote-section) t)
24841 (comment-block
24842 ;; Allow checks between block markers, not on them.
24843 (and (> (line-beginning-position) post-affiliated)
24844 (save-excursion
24845 (end-of-line)
24846 (skip-chars-forward " \r\t\n")
24847 (< (point) (org-element-property :end element)))))
24848 ;; Arbitrary list of keywords where checks are meaningful.
24849 ;; Make sure point is on the value part of the element.
24850 (keyword
24851 (and (member (org-element-property :key element)
24852 '("DESCRIPTION" "TITLE"))
24853 (save-excursion
24854 (search-backward ":" (line-beginning-position) t))))
24855 ;; Check is globally allowed in paragraphs verse blocks and
24856 ;; table rows (after affiliated keywords) but some objects
24857 ;; must not be affected.
24858 ((paragraph table-row verse-block)
24859 (let ((cbeg (org-element-property :contents-begin element))
24860 (cend (org-element-property :contents-end element)))
24861 (and cbeg (>= (point) cbeg) (< (point) cend)
24862 (org--flyspell-object-check-p element))))))))))
24863 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24865 (defun org-remove-flyspell-overlays-in (beg end)
24866 "Remove flyspell overlays in region."
24867 (and (bound-and-true-p flyspell-mode)
24868 (fboundp 'flyspell-delete-region-overlays)
24869 (flyspell-delete-region-overlays beg end)))
24871 (defvar flyspell-delayed-commands)
24872 (eval-after-load "flyspell"
24873 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24875 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24876 (eval-after-load "bookmark"
24877 '(if (boundp 'bookmark-after-jump-hook)
24878 ;; We can use the hook
24879 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24880 ;; Hook not available, use advice
24881 (defadvice bookmark-jump (after org-make-visible activate)
24882 "Make the position visible."
24883 (org-bookmark-jump-unhide))))
24885 ;; Make sure saveplace shows the location if it was hidden
24886 (eval-after-load "saveplace"
24887 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24888 "Make the position visible."
24889 (org-bookmark-jump-unhide)))
24891 ;; Make sure ecb shows the location if it was hidden
24892 (eval-after-load "ecb"
24893 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24894 "Make hierarchy visible when jumping into location from ECB tree buffer."
24895 (when (derived-mode-p 'org-mode)
24896 (org-show-context))))
24898 (defun org-bookmark-jump-unhide ()
24899 "Unhide the current position, to show the bookmark location."
24900 (and (derived-mode-p 'org-mode)
24901 (or (outline-invisible-p)
24902 (save-excursion (goto-char (max (point-min) (1- (point))))
24903 (outline-invisible-p)))
24904 (org-show-context 'bookmark-jump)))
24906 (defun org-mark-jump-unhide ()
24907 "Make the point visible with `org-show-context' after jumping to the mark."
24908 (when (and (derived-mode-p 'org-mode)
24909 (outline-invisible-p))
24910 (org-show-context 'mark-goto)))
24912 (eval-after-load "simple"
24913 '(defadvice pop-to-mark-command (after org-make-visible activate)
24914 "Make the point visible with `org-show-context'."
24915 (org-mark-jump-unhide)))
24917 (eval-after-load "simple"
24918 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24919 "Make the point visible with `org-show-context'."
24920 (org-mark-jump-unhide)))
24922 (eval-after-load "simple"
24923 '(defadvice pop-global-mark (after org-make-visible activate)
24924 "Make the point visible with `org-show-context'."
24925 (org-mark-jump-unhide)))
24927 ;; Make session.el ignore our circular variable
24928 (defvar session-globals-exclude)
24929 (eval-after-load "session"
24930 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24932 ;;;; Finish up
24934 (provide 'org)
24936 (run-hooks 'org-load-hook)
24938 ;;; org.el ends here