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.
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/>.
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
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
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
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
74 (eval-when-compile (require 'gnus-sum
))
78 (require 'format-spec
)
80 (or (eq this-command
'eval-buffer
)
82 (load (concat (file-name-directory load-file-name
)
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp
"\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol
"^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp
"^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays
"holidays" (date))
114 (declare-function cdlatex-environment
"ext:cdlatex" (environment item
))
115 (declare-function isearch-no-upper-case-p
"isearch" (string regexp-flag
))
116 (declare-function org-add-archive-files
"org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp
"org-agenda" (pom))
118 (declare-function org-agenda-list
"org-agenda"
119 (&optional arg start-day span with-hour
))
120 (declare-function org-agenda-redo
"org-agenda" (&optional all
))
121 (declare-function org-babel-do-in-edit-buffer
"ob-core" (&rest body
) t
)
122 (declare-function org-babel-tangle-file
"ob-tangle" (file &optional target-file lang
))
123 (declare-function org-beamer-mode
"ox-beamer" (&optional prefix
) t
)
124 (declare-function org-clock-get-last-clock-out-time
"org-clock" ())
125 (declare-function org-clock-out
"org-clock" (&optional switch-to-state fail-quietly at-time
))
126 (declare-function org-clock-remove-overlays
"org-clock" (&optional beg end noremove
))
127 (declare-function org-clock-sum
"org-clock" (&optional tstart tend headline-filter propname
))
128 (declare-function org-clock-sum-current-item
"org-clock" (&optional tstart
))
129 (declare-function org-clock-timestamps-down
"org-clock" (&optional n
))
130 (declare-function org-clock-timestamps-up
"org-clock" (&optional n
))
131 (declare-function org-clock-update-time-maybe
"org-clock" ())
132 (declare-function org-clocktable-shift
"org-clock" (dir n
))
133 (declare-function org-element-at-point
"org-element" ())
134 (declare-function org-element-cache-refresh
"org-element" (pos))
135 (declare-function org-element-cache-reset
"org-element" (&optional all
))
136 (declare-function org-element-contents
"org-element" (element))
137 (declare-function org-element-context
"org-element" (&optional element
))
138 (declare-function org-element-copy
"org-element" (datum))
139 (declare-function org-element-interpret-data
"org-element" (data))
140 (declare-function org-element-lineage
"org-element" (blob &optional types with-self
))
141 (declare-function org-element-nested-p
"org-element" (elem-a elem-b
))
142 (declare-function org-element-parse-buffer
"org-element" (&optional granularity visible-only
))
143 (declare-function org-element-property
"org-element" (property element
))
144 (declare-function org-element-put-property
"org-element" (element property value
))
145 (declare-function org-element-swap-A-B
"org-element" (elem-a elem-b
))
146 (declare-function org-element-type
"org-element" (element))
147 (declare-function org-element-update-syntax
"org-element" ())
148 (declare-function org-id-find-id-file
"org-id" (id))
149 (declare-function org-id-get-create
"org-id" (&optional force
))
150 (declare-function org-inlinetask-at-task-p
"org-inlinetask" ())
151 (declare-function org-inlinetask-outline-regexp
"org-inlinetask" ())
152 (declare-function org-inlinetask-toggle-visibility
"org-inlinetask" ())
153 (declare-function org-plot
/gnuplot
"org-plot" (&optional params
))
154 (declare-function org-table-align
"org-table" ())
155 (declare-function org-table-begin
"org-table" (&optional table-type
))
156 (declare-function org-table-beginning-of-field
"org-table" (&optional n
))
157 (declare-function org-table-blank-field
"org-table" ())
158 (declare-function org-table-calc-current-TBLFM
"org-table" (&optional arg
))
159 (declare-function org-table-copy-region
"org-table" (beg end
&optional cut
))
160 (declare-function org-table-cut-region
"org-table" (beg end
))
161 (declare-function org-table-edit-field
"org-table" (arg))
162 (declare-function org-table-end
"org-table" (&optional table-type
))
163 (declare-function org-table-end-of-field
"org-table" (&optional n
))
164 (declare-function org-table-insert-row
"org-table" (&optional arg
))
165 (declare-function org-table-justify-field-maybe
"org-table" (&optional new
))
166 (declare-function org-table-maybe-eval-formula
"org-table" ())
167 (declare-function org-table-maybe-recalculate-line
"org-table" ())
168 (declare-function org-table-next-row
"org-table" ())
169 (declare-function org-table-paste-rectangle
"org-table" ())
170 (declare-function org-table-recalculate
"org-table" (&optional all noalign
))
171 (declare-function org-table-wrap-region
"org-table" (arg))
172 (declare-function org-tags-view
"org-agenda" (&optional todo-only match
))
173 (declare-function orgtbl-ascii-plot
"org-table" (&optional ask
))
174 (declare-function orgtbl-mode
"org-table" (&optional arg
))
176 (defsubst org-uniquify
(list)
177 "Non-destructively remove duplicate elements from LIST."
178 (let ((res (copy-sequence list
))) (delete-dups res
)))
180 (defsubst org-get-at-bol
(property)
181 "Get text property PROPERTY at the beginning of line."
182 (get-text-property (point-at-bol) property
))
184 (defsubst org-trim
(s &optional keep-lead
)
185 "Remove whitespace at the beginning and the end of string S.
186 When optional argument KEEP-LEAD is non-nil, removing blank lines
187 at the beginning of the string does not affect leading indentation."
188 (replace-regexp-in-string
189 (if keep-lead
"\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
190 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s
)))
192 ;; load languages based on value of `org-babel-load-languages'
193 (defvar org-babel-load-languages
)
196 (defun org-babel-do-load-languages (sym value
)
197 "Load the languages defined in `org-babel-load-languages'."
198 (set-default sym value
)
199 (dolist (pair org-babel-load-languages
)
200 (let ((active (cdr pair
)) (lang (symbol-name (car pair
))))
202 (require (intern (concat "ob-" lang
)))
203 (funcall 'fmakunbound
204 (intern (concat "org-babel-execute:" lang
)))
205 (funcall 'fmakunbound
206 (intern (concat "org-babel-expand-body:" lang
)))))))
208 (declare-function org-babel-tangle-file
"ob-tangle" (file &optional target-file lang
))
210 (defun org-babel-load-file (file &optional compile
)
211 "Load Emacs Lisp source code blocks in the Org FILE.
212 This function exports the source code using `org-babel-tangle'
213 and then loads the resulting file using `load-file'. With prefix
214 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
215 file to byte-code before it is loaded."
216 (interactive "fFile to load: \nP")
217 (let* ((age (lambda (file)
219 (time-subtract (current-time)
220 (nth 5 (or (file-attributes (file-truename file
))
221 (file-attributes file
)))))))
222 (base-name (file-name-sans-extension file
))
223 (exported-file (concat base-name
".el")))
224 ;; tangle if the Org file is newer than the elisp file
225 (unless (and (file-exists-p exported-file
)
226 (> (funcall age file
) (funcall age exported-file
)))
227 ;; Tangle-file traversal returns reversed list of tangled files
228 ;; and we want to evaluate the first target.
230 (car (last (org-babel-tangle-file file exported-file
"emacs-lisp")))))
233 (progn (byte-compile-file exported-file
'load
)
234 "Compiled and loaded")
235 (progn (load-file exported-file
) "Loaded"))
238 (defcustom org-babel-load-languages
'((emacs-lisp . t
))
239 "Languages which can be evaluated in Org buffers.
240 This list can be used to load support for any of the languages
241 below, note that each language will depend on a different set of
242 system executables and/or Emacs modes. When a language is
243 \"loaded\", then code blocks in that language can be evaluated
244 with `org-babel-execute-src-block' bound by default to C-c
245 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
246 be set to remove code block evaluation from the C-c C-c
247 keybinding. By default only Emacs Lisp (which has no
248 requirements) is loaded."
250 :set
'org-babel-do-load-languages
252 :type
'(alist :tag
"Babel Languages"
255 (const :tag
"Awk" awk
)
258 (const :tag
"Asymptote" asymptote
)
259 (const :tag
"Calc" calc
)
260 (const :tag
"Clojure" clojure
)
261 (const :tag
"CSS" css
)
262 (const :tag
"Ditaa" ditaa
)
263 (const :tag
"Dot" dot
)
264 (const :tag
"Emacs Lisp" emacs-lisp
)
265 (const :tag
"Forth" forth
)
266 (const :tag
"Fortran" fortran
)
267 (const :tag
"Gnuplot" gnuplot
)
268 (const :tag
"Haskell" haskell
)
271 (const :tag
"Java" java
)
272 (const :tag
"Javascript" js
)
273 (const :tag
"LaTeX" latex
)
274 (const :tag
"Ledger" ledger
)
275 (const :tag
"Lilypond" lilypond
)
276 (const :tag
"Lisp" lisp
)
277 (const :tag
"Makefile" makefile
)
278 (const :tag
"Maxima" maxima
)
279 (const :tag
"Matlab" matlab
)
280 (const :tag
"Mscgen" mscgen
)
281 (const :tag
"Ocaml" ocaml
)
282 (const :tag
"Octave" octave
)
283 (const :tag
"Org" org
)
284 (const :tag
"Perl" perl
)
285 (const :tag
"Pico Lisp" picolisp
)
286 (const :tag
"PlantUML" plantuml
)
287 (const :tag
"Python" python
)
288 (const :tag
"Ruby" ruby
)
289 (const :tag
"Sass" sass
)
290 (const :tag
"Scala" scala
)
291 (const :tag
"Scheme" scheme
)
292 (const :tag
"Screen" screen
)
293 (const :tag
"Shell Script" shell
)
294 (const :tag
"Shen" shen
)
295 (const :tag
"Sql" sql
)
296 (const :tag
"Sqlite" sqlite
)
297 (const :tag
"Stan" stan
)
298 (const :tag
"ebnf2ps" ebnf2ps
))
299 :value-type
(boolean :tag
"Activate" :value t
)))
301 ;;;; Customization variables
302 (defcustom org-clone-delete-id nil
303 "Remove ID property of clones of a subtree.
304 When non-nil, clones of a subtree don't inherit the ID property.
305 Otherwise they inherit the ID property with a new unique
315 (defun org-version (&optional here full message
)
316 "Show the Org version.
317 Interactively, or when MESSAGE is non-nil, show it in echo area.
318 With prefix argument, or when HERE is non-nil, insert it at point.
319 In non-interactive uses, a reduced version string is output unless
321 (interactive (list current-prefix-arg t
(not current-prefix-arg
)))
322 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
323 (save-load-suffixes (when (boundp 'load-suffixes
) load-suffixes
))
324 (load-suffixes (list ".el"))
326 (ignore-errors (org-find-library-dir "org-loaddefs"))))
327 (unless (and (fboundp 'org-release
) (fboundp 'org-git-version
))
328 (org-load-noerror-mustsuffix (concat org-dir
"org-version")))
329 (let* ((load-suffixes save-load-suffixes
)
330 (release (org-release))
331 (git-version (org-git-version))
332 (version (format "Org mode version %s (%s @ %s)"
336 (if (string= org-dir org-install-dir
)
338 (concat "mixed installation! "
342 "org-loaddefs.el can not be found!")))
343 (version1 (if full version release
)))
344 (when here
(insert version1
))
345 (when message
(message "%s" version1
))
348 (defconst org-version
(org-version))
355 (defconst org-block-regexp
356 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
357 "Regular expression for hiding blocks.")
359 (defconst org-dblock-start-re
360 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
361 "Matches the start line of a dynamic block, with parameters.")
363 (defconst org-dblock-end-re
"^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
364 "Matches the end of a dynamic block.")
366 ;;;; Clock and Planning
368 (defconst org-clock-string
"CLOCK:"
369 "String used as prefix for timestamps clocking work hours on an item.")
371 (defvar org-closed-string
"CLOSED:"
372 "String used as the prefix for timestamps logging closing a TODO entry.")
374 (defvar org-deadline-string
"DEADLINE:"
375 "String to mark deadline entries.
377 A deadline is this string, followed by a time stamp. It must be
378 a word, terminated by a colon. You can insert a schedule keyword
379 and a timestamp with `\\[org-deadline]'.")
381 (defvar org-scheduled-string
"SCHEDULED:"
382 "String to mark scheduled TODO entries.
384 A schedule is this string, followed by a time stamp. It must be
385 a word, terminated by a colon. You can insert a schedule keyword
386 and a timestamp with `\\[org-schedule]'.")
388 (defconst org-ds-keyword-length
392 (list org-deadline-string org-scheduled-string
393 org-clock-string org-closed-string
))))
394 "Maximum length of the DEADLINE and SCHEDULED keywords.")
396 (defconst org-planning-line-re
399 (list org-closed-string org-deadline-string org-scheduled-string
)
401 "Matches a line with planning info.
402 Matched keyword is in group 1.")
404 (defconst org-clock-line-re
405 (concat "^[ \t]*" org-clock-string
)
406 "Matches a line with clock info.")
408 (defconst org-deadline-regexp
(concat "\\<" org-deadline-string
)
409 "Matches the DEADLINE keyword.")
411 (defconst org-deadline-time-regexp
412 (concat "\\<" org-deadline-string
" *<\\([^>]+\\)>")
413 "Matches the DEADLINE keyword together with a time stamp.")
415 (defconst org-deadline-time-hour-regexp
416 (concat "\\<" org-deadline-string
417 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
418 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
420 (defconst org-deadline-line-regexp
421 (concat "\\<\\(" org-deadline-string
"\\).*")
422 "Matches the DEADLINE keyword and the rest of the line.")
424 (defconst org-scheduled-regexp
(concat "\\<" org-scheduled-string
)
425 "Matches the SCHEDULED keyword.")
427 (defconst org-scheduled-time-regexp
428 (concat "\\<" org-scheduled-string
" *<\\([^>]+\\)>")
429 "Matches the SCHEDULED keyword together with a time stamp.")
431 (defconst org-scheduled-time-hour-regexp
432 (concat "\\<" org-scheduled-string
433 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
434 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
436 (defconst org-closed-time-regexp
437 (concat "\\<" org-closed-string
" *\\[\\([^]]+\\)\\]")
438 "Matches the CLOSED keyword together with a time stamp.")
440 (defconst org-keyword-time-regexp
443 (list org-scheduled-string org-deadline-string org-closed-string
446 " *[[<]\\([^]>]+\\)[]>]")
447 "Matches any of the 4 keywords, together with the time stamp.")
449 (defconst org-keyword-time-not-clock-regexp
453 (list org-scheduled-string org-deadline-string org-closed-string
) t
)
454 " *[[<]\\([^]>]+\\)[]>]")
455 "Matches any of the 3 keywords, together with the time stamp.")
457 (defconst org-maybe-keyword-time-regexp
460 (list org-scheduled-string org-deadline-string org-closed-string
464 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
467 "Matches a timestamp, possibly preceded by a keyword.")
469 (defconst org-all-time-keywords
470 (mapcar (lambda (w) (substring w
0 -
1))
471 (list org-scheduled-string org-deadline-string
472 org-clock-string org-closed-string
))
473 "List of time keywords.")
477 (defconst org-drawer-regexp
"^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
478 "Matches first or last line of a hidden block.
479 Group 1 contains drawer's name or \"END\".")
481 (defconst org-property-start-re
"^[ \t]*:PROPERTIES:[ \t]*$"
482 "Regular expression matching the first line of a property drawer.")
484 (defconst org-property-end-re
"^[ \t]*:END:[ \t]*$"
485 "Regular expression matching the last line of a property drawer.")
487 (defconst org-clock-drawer-start-re
"^[ \t]*:CLOCK:[ \t]*$"
488 "Regular expression matching the first line of a clock drawer.")
490 (defconst org-clock-drawer-end-re
"^[ \t]*:END:[ \t]*$"
491 "Regular expression matching the last line of a clock drawer.")
493 (defconst org-property-drawer-re
494 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
495 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
496 "[ \t]*:END:[ \t]*$")
497 "Matches an entire property drawer.")
499 (defconst org-clock-drawer-re
500 (concat "\\(" org-clock-drawer-start-re
"\\)[^\000]*?\\("
501 org-clock-drawer-end-re
"\\)\n?")
502 "Matches an entire clock drawer.")
506 (defconst org-heading-keyword-regexp-format
507 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
508 "Printf format for a regexp matching a headline with some keyword.
509 This regexp will match the headline of any node which has the
510 exact keyword that is put into the format. The keyword isn't in
511 any group by default, but the stars and the body are.")
513 (defconst org-heading-keyword-maybe-regexp-format
514 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
515 "Printf format for a regexp matching a headline, possibly with some keyword.
516 This regexp can match any headline with the specified keyword, or
517 without a keyword. The keyword isn't in any group by default,
518 but the stars and the body are.")
520 (defconst org-archive-tag
"ARCHIVE"
521 "The tag that marks a subtree as archived.
522 An archived subtree does not open during visibility cycling, and does
523 not contribute to the agenda listings.")
525 (defconst org-comment-string
"COMMENT"
526 "Entries starting with this keyword will never be exported.
528 An entry can be toggled between COMMENT and normal with
529 `\\[org-toggle-comment]'.")
532 ;;;; LaTeX Environments and Fragments
534 (defconst org-latex-regexps
535 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t
)
536 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
537 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
538 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil
)
539 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil
)
540 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil
)
541 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil
)
542 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil
))
543 "Regular expressions for matching embedded LaTeX.")
547 (defconst org-effort-property
"Effort"
548 "The property that is being used to keep track of effort estimates.
549 Effort estimates given in this property need to have the format H:MM.")
553 (defconst org-table-any-line-regexp
"^[ \t]*\\(|\\|\\+-[-+]\\)"
554 "Detect an org-type or table-type table.")
556 (defconst org-table-line-regexp
"^[ \t]*|"
557 "Detect an org-type table line.")
559 (defconst org-table-dataline-regexp
"^[ \t]*|[^-]"
560 "Detect an org-type table line.")
562 (defconst org-table-hline-regexp
"^[ \t]*|-"
563 "Detect an org-type table hline.")
565 (defconst org-table1-hline-regexp
"^[ \t]*\\+-[-+]"
566 "Detect a table-type table hline.")
568 (defconst org-table-any-border-regexp
"^[ \t]*[^|+ \t]"
569 "Detect the first line outside a table when searching from within it.
570 This works for both table types.")
572 (defconst org-TBLFM-regexp
"^[ \t]*#\\+TBLFM: "
573 "Detect a #+TBLFM line.")
577 (defconst org-ts-regexp
"<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
578 "Regular expression for fast time stamp matching.")
580 (defconst org-ts-regexp-inactive
581 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
582 "Regular expression for fast inactive time stamp matching.")
584 (defconst org-ts-regexp-both
"[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
585 "Regular expression for fast time stamp matching.")
587 (defconst org-ts-regexp0
588 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
589 "Regular expression matching time strings for analysis.
590 This one does not require the space after the date, so it can be used
591 on a string that terminates immediately after the date.")
593 (defconst org-ts-regexp1
"\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
594 "Regular expression matching time strings for analysis.")
596 (defconst org-ts-regexp2
(concat "<" org-ts-regexp1
"[^>\n]\\{0,16\\}>")
597 "Regular expression matching time stamps, with groups.")
599 (defconst org-ts-regexp3
(concat "[[<]" org-ts-regexp1
"[^]>\n]\\{0,16\\}[]>]")
600 "Regular expression matching time stamps (also [..]), with groups.")
602 (defconst org-tr-regexp
(concat org-ts-regexp
"--?-?" org-ts-regexp
)
603 "Regular expression matching a time stamp range.")
605 (defconst org-tr-regexp-both
606 (concat org-ts-regexp-both
"--?-?" org-ts-regexp-both
)
607 "Regular expression matching a time stamp range.")
609 (defconst org-tsr-regexp
(concat org-ts-regexp
"\\(--?-?"
610 org-ts-regexp
"\\)?")
611 "Regular expression matching a time stamp or time stamp range.")
613 (defconst org-tsr-regexp-both
614 (concat org-ts-regexp-both
"\\(--?-?"
615 org-ts-regexp-both
"\\)?")
616 "Regular expression matching a time stamp or time stamp range.
617 The time stamps may be either active or inactive.")
619 (defconst org-repeat-re
620 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
621 "Regular expression for specifying repeated events.
622 After a match, group 1 contains the repeat expression.")
624 (defconst org-time-stamp-formats
'("<%Y-%m-%d %a>" .
"<%Y-%m-%d %a %H:%M>")
625 "Formats for `format-time-string' which are used for time stamps.")
628 ;;; The custom variables
631 "Outline-based notes management and organizer."
636 (defcustom org-mode-hook nil
637 "Mode hook for Org mode, run after the mode was turned on."
641 (defcustom org-load-hook nil
642 "Hook that is run after org.el has been loaded."
646 (defcustom org-log-buffer-setup-hook nil
647 "Hook that is run after an Org log buffer is created."
652 (defvar org-modules
) ; defined below
653 (defvar org-modules-loaded nil
654 "Have the modules been loaded already?")
656 (defun org-load-modules-maybe (&optional force
)
657 "Load all extensions listed in `org-modules'."
658 (when (or force
(not org-modules-loaded
))
659 (dolist (ext org-modules
)
660 (condition-case nil
(require ext
)
661 (error (message "Problems while trying to load feature `%s'" ext
))))
662 (setq org-modules-loaded t
)))
664 (defun org-set-modules (var value
)
665 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
667 (when (featurep 'org
)
668 (org-load-modules-maybe 'force
)
669 (org-element-cache-reset 'all
)))
671 (defcustom org-modules
'(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail
)
672 "Modules that should always be loaded together with org.el.
674 If a description starts with <C>, the file is not part of Emacs
675 and loading it will require that you have downloaded and properly
676 installed the Org mode distribution.
678 You can also use this system to load external packages (i.e. neither Org
679 core modules, nor modules from the CONTRIB directory). Just add symbols
680 to the end of the list. If the package is called org-xyz.el, then you need
681 to add the symbol `xyz', and the package must have a call to:
683 (provide \\='org-xyz)
685 For export specific modules, see also `org-export-backends'."
687 :set
'org-set-modules
689 :package-version
'(Org .
"8.0")
692 (const :tag
" bbdb: Links to BBDB entries" org-bbdb
)
693 (const :tag
" bibtex: Links to BibTeX entries" org-bibtex
)
694 (const :tag
" crypt: Encryption of subtrees" org-crypt
)
695 (const :tag
" ctags: Access to Emacs tags with links" org-ctags
)
696 (const :tag
" docview: Links to doc-view buffers" org-docview
)
697 (const :tag
" eww: Store link to url of eww" org-eww
)
698 (const :tag
" gnus: Links to GNUS folders/messages" org-gnus
)
699 (const :tag
" habit: Track your consistency with habits" org-habit
)
700 (const :tag
" id: Global IDs for identifying entries" org-id
)
701 (const :tag
" info: Links to Info nodes" org-info
)
702 (const :tag
" inlinetask: Tasks independent of outline hierarchy" org-inlinetask
)
703 (const :tag
" irc: Links to IRC/ERC chat sessions" org-irc
)
704 (const :tag
" mhe: Links to MHE folders/messages" org-mhe
)
705 (const :tag
" mouse: Additional mouse support" org-mouse
)
706 (const :tag
" protocol: Intercept calls from emacsclient" org-protocol
)
707 (const :tag
" rmail: Links to RMAIL folders/messages" org-rmail
)
708 (const :tag
" w3m: Special cut/paste from w3m to Org mode." org-w3m
)
710 (const :tag
"C annotate-file: Annotate a file with org syntax" org-annotate-file
)
711 (const :tag
"C bookmark: Org links to bookmarks" org-bookmark
)
712 (const :tag
"C checklist: Extra functions for checklists in repeated tasks" org-checklist
)
713 (const :tag
"C choose: Use TODO keywords to mark decisions states" org-choose
)
714 (const :tag
"C collector: Collect properties into tables" org-collector
)
715 (const :tag
"C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend
)
716 (const :tag
"C drill: Flashcards and spaced repetition for Org mode" org-drill
)
717 (const :tag
"C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol
)
718 (const :tag
"C eshell Support for links to working directories in eshell" org-eshell
)
719 (const :tag
"C eval-light: Evaluate inbuffer-code on demand" org-eval-light
)
720 (const :tag
"C eval: Include command output as text" org-eval
)
721 (const :tag
"C expiry: Expiry mechanism for Org entries" org-expiry
)
722 (const :tag
"C favtable: Lookup table of favorite references and links" org-favtable
)
723 (const :tag
"C git-link: Provide org links to specific file version" org-git-link
)
724 (const :tag
"C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query
)
725 (const :tag
"C invoice: Help manage client invoices in Org mode" org-invoice
)
726 (const :tag
"C learn: SuperMemo's incremental learning algorithm" org-learn
)
727 (const :tag
"C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal
)
728 (const :tag
"C mac-link: Grab links and url from various mac Applications" org-mac-link
)
729 (const :tag
"C mairix: Hook mairix search into Org for different MUAs" org-mairix
)
730 (const :tag
"C man: Support for links to manpages in Org mode" org-man
)
731 (const :tag
"C mew: Links to Mew folders/messages" org-mew
)
732 (const :tag
"C mtags: Support for muse-like tags" org-mtags
)
733 (const :tag
"C notmuch: Provide org links to notmuch searches or messages" org-notmuch
)
734 (const :tag
"C panel: Simple routines for us with bad memory" org-panel
)
735 (const :tag
"C registry: A registry for Org links" org-registry
)
736 (const :tag
"C screen: Visit screen sessions through Org links" org-screen
)
737 (const :tag
"C secretary: Team management with org-mode" org-secretary
)
738 (const :tag
"C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert
)
739 (const :tag
"C toc: Table of contents for Org buffer" org-toc
)
740 (const :tag
"C track: Keep up with Org mode development" org-track
)
741 (const :tag
"C velocity Something like Notational Velocity for Org" org-velocity
)
742 (const :tag
"C vm: Links to VM folders/messages" org-vm
)
743 (const :tag
"C wikinodes: CamelCase wiki-like links" org-wikinodes
)
744 (const :tag
"C wl: Links to Wanderlust folders/messages" org-wl
)
745 (repeat :tag
"External packages" :inline t
(symbol :tag
"Package"))))
747 (defvar org-export-registered-backends
) ; From ox.el.
748 (declare-function org-export-derived-backend-p
"ox" (backend &rest backends
))
749 (declare-function org-export-backend-name
"ox" (backend) t
)
750 (defcustom org-export-backends
'(ascii html icalendar latex odt
)
751 "List of export back-ends that should be always available.
753 If a description starts with <C>, the file is not part of Emacs
754 and loading it will require that you have downloaded and properly
755 installed the Org mode distribution.
757 Unlike to `org-modules', libraries in this list will not be
758 loaded along with Org, but only once the export framework is
761 This variable needs to be set before org.el is loaded. If you
762 need to make a change while Emacs is running, use the customize
763 interface or run the following code, where VAL stands for the new
764 value of the variable, after updating it:
767 (setq org-export-registered-backends
770 (let ((name (org-export-backend-name backend)))
774 (and (org-export-derived-backend-p b name)
775 (throw \\='parentp t)))))))
776 org-export-registered-backends))
777 (let ((new-list (mapcar #\\='org-export-backend-name
778 org-export-registered-backends)))
779 (dolist (backend val)
781 ((not (load (format \"ox-%s\" backend) t t))
782 (message \"Problems while trying to load export back-end \\=`%s\\='\"
784 ((not (memq backend new-list)) (push backend new-list))))
785 (set-default \\='org-export-backends new-list)))
787 Adding a back-end to this list will also pull the back-end it
792 :package-version
'(Org .
"9.0")
793 :initialize
'custom-initialize-set
794 :set
(lambda (var val
)
795 (if (not (featurep 'ox
)) (set-default var val
)
796 ;; Any back-end not required anymore (not present in VAL and not
797 ;; a parent of any back-end in the new value) is removed from the
798 ;; list of registered back-ends.
799 (setq org-export-registered-backends
802 (let ((name (org-export-backend-name backend
)))
806 (and (org-export-derived-backend-p b name
)
807 (throw 'parentp t
)))))))
808 org-export-registered-backends
))
809 ;; Now build NEW-LIST of both new back-ends and required
811 (let ((new-list (mapcar #'org-export-backend-name
812 org-export-registered-backends
)))
813 (dolist (backend val
)
815 ((not (load (format "ox-%s" backend
) t t
))
816 (message "Problems while trying to load export back-end `%s'"
818 ((not (memq backend new-list
)) (push backend new-list
))))
819 ;; Set VAR to that list with fixed dependencies.
820 (set-default var new-list
))))
821 :type
'(set :greedy t
822 (const :tag
" ascii Export buffer to ASCII format" ascii
)
823 (const :tag
" beamer Export buffer to Beamer presentation" beamer
)
824 (const :tag
" html Export buffer to HTML format" html
)
825 (const :tag
" icalendar Export buffer to iCalendar format" icalendar
)
826 (const :tag
" latex Export buffer to LaTeX format" latex
)
827 (const :tag
" man Export buffer to MAN format" man
)
828 (const :tag
" md Export buffer to Markdown format" md
)
829 (const :tag
" odt Export buffer to ODT format" odt
)
830 (const :tag
" org Export buffer to Org format" org
)
831 (const :tag
" texinfo Export buffer to Texinfo format" texinfo
)
832 (const :tag
"C confluence Export buffer to Confluence Wiki format" confluence
)
833 (const :tag
"C deck Export buffer to deck.js presentations" deck
)
834 (const :tag
"C freemind Export buffer to Freemind mindmap format" freemind
)
835 (const :tag
"C groff Export buffer to Groff format" groff
)
836 (const :tag
"C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter
)
837 (const :tag
"C RSS 2.0 Export buffer to RSS 2.0 format" rss
)
838 (const :tag
"C s5 Export buffer to s5 presentations" s5
)
839 (const :tag
"C taskjuggler Export buffer to TaskJuggler format" taskjuggler
)))
842 '(dolist (backend org-export-backends
)
843 (condition-case nil
(require (intern (format "ox-%s" backend
)))
844 (error (message "Problems while trying to load export back-end `%s'"
847 (defcustom org-support-shift-select nil
848 "Non-nil means make shift-cursor commands select text when possible.
851 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
852 start selecting a region, or enlarge regions started in this way.
853 In Org mode, in special contexts, these same keys are used for
854 other purposes, important enough to compete with shift selection.
855 Org tries to balance these needs by supporting `shift-select-mode'
856 outside these special contexts, under control of this variable.
858 The default of this variable is nil, to avoid confusing behavior. Shifted
859 cursor keys will then execute Org commands in the following contexts:
860 - on a headline, changing TODO state (left/right) and priority (up/down)
861 - on a time stamp, changing the time
862 - in a plain list item, changing the bullet type
863 - in a property definition line, switching between allowed values
864 - in the BEGIN line of a clock table (changing the time block).
865 Outside these contexts, the commands will throw an error.
867 When this variable is t and the cursor is not in a special
868 context, Org mode will support shift-selection for making and
869 enlarging regions. To make this more effective, the bullet
870 cycling will no longer happen anywhere in an item line, but only
871 if the cursor is exactly on the bullet.
873 If you set this variable to the symbol `always', then the keys
874 will not be special in headlines, property lines, and item lines,
875 to make shift selection work there as well. If this is what you
876 want, you can use the following alternative commands:
877 `\\[org-todo]' and `\\[org-priority]' \
878 to change TODO state and priority,
879 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
880 can be used to switch TODO sets,
881 `\\[org-ctrl-c-minus]' to cycle item bullet types,
882 and properties can be edited by hand or in column view.
884 However, when the cursor is on a timestamp, shift-cursor commands
885 will still edit the time stamp - this is just too good to give up."
888 (const :tag
"Never" nil
)
889 (const :tag
"When outside special context" t
)
890 (const :tag
"Everywhere except timestamps" always
)))
892 (defcustom org-loop-over-headlines-in-active-region nil
893 "Shall some commands act upon headlines in the active region?
895 When set to t, some commands will be performed in all headlines
896 within the active region.
898 When set to `start-level', some commands will be performed in all
899 headlines within the active region, provided that these headlines
900 are of the same level than the first one.
902 When set to a string, those commands will be performed on the
903 matching headlines within the active region. Such string must be
904 a tags/property/todo match as it is used in the agenda tags view.
906 The list of commands is: `org-schedule', `org-deadline',
907 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
908 `org-archive-to-archive-sibling'. The archiving commands skip
909 already archived entries."
910 :type
'(choice (const :tag
"Don't loop" nil
)
911 (const :tag
"All headlines in active region" t
)
912 (const :tag
"In active region, headlines at the same level than the first one" start-level
)
913 (string :tag
"Tags/Property/Todo matcher"))
918 (defgroup org-startup nil
919 "Options concerning startup of Org mode."
923 (defcustom org-startup-folded t
924 "Non-nil means entering Org mode will switch to OVERVIEW.
926 This can also be configured on a per-file basis by adding one of
927 the following lines anywhere in the buffer:
929 #+STARTUP: fold (or `overview', this is equivalent)
930 #+STARTUP: nofold (or `showall', this is equivalent)
932 #+STARTUP: showeverything
934 Set `org-agenda-inhibit-startup' to a non-nil value if you want
935 to ignore this option when Org opens agenda files for the first
939 (const :tag
"nofold: show all" nil
)
940 (const :tag
"fold: overview" t
)
941 (const :tag
"content: all headlines" content
)
942 (const :tag
"show everything, even drawers" showeverything
)))
944 (defcustom org-startup-truncated t
945 "Non-nil means entering Org mode will set `truncate-lines'.
946 This is useful since some lines containing links can be very long and
947 uninteresting. Also tables look terrible when wrapped.
949 The variable `org-startup-truncated' allows to configure
950 truncation for Org mode different to the other modes that use the
951 variable `truncate-lines' and as a shortcut instead of putting
952 the variable `truncate-lines' into the `org-mode-hook'. If one
953 wants to configure truncation for Org mode not statically but
954 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
955 the variable `truncate-lines' has to be used because in such a
956 case it is too late to set the variable `org-startup-truncated'."
960 (defcustom org-startup-indented nil
961 "Non-nil means turn on `org-indent-mode' on startup.
962 This can also be configured on a per-file basis by adding one of
963 the following lines anywhere in the buffer:
967 :group
'org-structure
969 (const :tag
"Not" nil
)
970 (const :tag
"Globally (slow on startup in large files)" t
)))
972 (defcustom org-use-sub-superscripts t
973 "Non-nil means interpret \"_\" and \"^\" for display.
975 If you want to control how Org exports those characters, see
976 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
977 used to be an alias for `org-export-with-sub-superscripts' in
978 Org <8.0, it is not anymore.
980 When this option is turned on, you can use TeX-like syntax for
981 sub- and superscripts within the buffer. Several characters after
982 \"_\" or \"^\" will be considered as a single item - so grouping
983 with {} is normally not needed. For example, the following things
984 will be parsed as single sub- or superscripts:
986 10^24 or 10^tau several digits will be considered 1 item.
987 10^-12 or 10^-tau a leading sign with digits or a word
988 x^2-y^3 will be read as x^2 - y^3, because items are
989 terminated by almost any nonword/nondigit char.
990 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
992 Still, ambiguity is possible. So when in doubt, use {} to enclose
993 the sub/superscript. If you set this variable to the symbol `{}',
994 the braces are *required* in order to trigger interpretations as
995 sub/superscript. This can be helpful in documents that need \"_\"
996 frequently in plain text."
999 :package-version
'(Org .
"8.0")
1001 (const :tag
"Always interpret" t
)
1002 (const :tag
"Only with braces" {})
1003 (const :tag
"Never interpret" nil
)))
1005 (defcustom org-startup-with-beamer-mode nil
1006 "Non-nil means turn on `org-beamer-mode' on startup.
1007 This can also be configured on a per-file basis by adding one of
1008 the following lines anywhere in the buffer:
1015 (defcustom org-startup-align-all-tables nil
1016 "Non-nil means align all tables when visiting a file.
1017 This is useful when the column width in tables is forced with <N> cookies
1018 in table fields. Such tables will look correct only after the first re-align.
1019 This can also be configured on a per-file basis by adding one of
1020 the following lines anywhere in the buffer:
1026 (defcustom org-startup-with-inline-images nil
1027 "Non-nil means show inline images when loading a new Org file.
1028 This can also be configured on a per-file basis by adding one of
1029 the following lines anywhere in the buffer:
1030 #+STARTUP: inlineimages
1031 #+STARTUP: noinlineimages"
1036 (defcustom org-startup-with-latex-preview nil
1037 "Non-nil means preview LaTeX fragments when loading a new Org file.
1039 This can also be configured on a per-file basis by adding one of
1040 the following lines anywhere in the buffer:
1041 #+STARTUP: latexpreview
1042 #+STARTUP: nolatexpreview"
1045 :package-version
'(Org .
"8.0")
1048 (defcustom org-insert-mode-line-in-empty-file nil
1049 "Non-nil means insert the first line setting Org mode in empty files.
1050 When the function `org-mode' is called interactively in an empty file, this
1051 normally means that the file name does not automatically trigger Org mode.
1052 To ensure that the file will always be in Org mode in the future, a
1053 line enforcing Org mode will be inserted into the buffer, if this option
1058 (defcustom org-replace-disputed-keys nil
1059 "Non-nil means use alternative key bindings for some keys.
1060 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1061 These keys are also used by other packages like shift-selection-mode'
1062 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1063 If you want to use Org mode together with one of these other modes,
1064 or more generally if you would like to move some Org mode commands to
1065 other keys, set this variable and configure the keys with the variable
1066 `org-disputed-keys'.
1068 This option is only relevant at load-time of Org mode, and must be set
1069 *before* org.el is loaded. Changing it requires a restart of Emacs to
1074 (defcustom org-use-extra-keys nil
1075 "Non-nil means use extra key sequence definitions for certain commands.
1076 This happens automatically if `window-system' is nil. This
1077 variable lets you do the same manually. You must set it before
1082 (defvaralias 'org-CUA-compatible
'org-replace-disputed-keys
)
1084 (defcustom org-disputed-keys
1085 '(([(shift up
)] .
[(meta p
)])
1086 ([(shift down
)] .
[(meta n
)])
1087 ([(shift left
)] .
[(meta -
)])
1088 ([(shift right
)] .
[(meta +)])
1089 ([(control shift right
)] .
[(meta shift
+)])
1090 ([(control shift left
)] .
[(meta shift -
)]))
1091 "Keys for which Org mode and other modes compete.
1092 This is an alist, cars are the default keys, second element specifies
1093 the alternative to use when `org-replace-disputed-keys' is t.
1095 Keys can be specified in any syntax supported by `define-key'.
1096 The value of this option takes effect only at Org mode startup,
1097 therefore you'll have to restart Emacs to apply it after changing."
1101 (defun org-key (key)
1102 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1103 Or return the original if not disputed."
1104 (when org-replace-disputed-keys
1105 (let* ((nkey (key-description key
))
1106 (x (cl-find-if (lambda (x) (equal (key-description (car x
)) nkey
))
1107 org-disputed-keys
)))
1108 (setq key
(if x
(cdr x
) key
))))
1111 (defun org-defkey (keymap key def
)
1112 "Define a key, possibly translated, as returned by `org-key'."
1113 (define-key keymap
(org-key key
) def
))
1115 (defcustom org-ellipsis nil
1116 "The ellipsis to use in the Org mode outline.
1118 When nil, just use the standard three dots.
1119 When a string, use that string instead.
1121 The change affects only Org mode (which will then use its own display table).
1122 Changing this requires executing `\\[org-mode]' in a buffer to become
1125 :type
'(choice (const :tag
"Default" nil
)
1126 (string :tag
"String" :value
"...#"))
1127 :safe
#'string-or-null-p
)
1129 (defvar org-display-table nil
1130 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1132 (defgroup org-keywords nil
1133 "Keywords in Org mode."
1137 (defcustom org-closed-keep-when-no-todo nil
1138 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1140 :group
'org-keywords
1142 :package-version
'(Org .
"8.0")
1145 (defgroup org-structure nil
1146 "Options concerning the general structure of Org files."
1147 :tag
"Org Structure"
1150 (defgroup org-reveal-location nil
1151 "Options about how to make context of a location visible."
1152 :tag
"Org Reveal Location"
1153 :group
'org-structure
)
1155 (defcustom org-show-context-detail
'((agenda . local
)
1156 (bookmark-jump . lineage
)
1158 (default . ancestors
))
1159 "Alist between context and visibility span when revealing a location.
1161 \\<org-mode-map>Some actions may move point into invisible
1162 locations. As a consequence, Org always expose a neighborhood
1163 around point. How much is shown depends on the initial action,
1164 or context. Valid contexts are
1166 agenda when exposing an entry from the agenda
1167 org-goto when using the command `org-goto' (`\\[org-goto]')
1168 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1169 tags-tree when constructing a sparse tree based on tags matches
1170 link-search when exposing search matches associated with a link
1171 mark-goto when exposing the jump goal of a mark
1172 bookmark-jump when exposing a bookmark location
1173 isearch when exiting from an incremental search
1174 default default for all contexts not set explicitly
1176 Allowed visibility spans are
1178 minimal show current headline; if point is not on headline,
1181 local show current headline, entry and next headline
1183 ancestors show current headline and its direct ancestors; if
1184 point is not on headline, also show entry
1186 lineage show current headline, its direct ancestors and all
1187 their children; if point is not on headline, also show
1188 entry and first child
1190 tree show current headline, its direct ancestors and all
1191 their children; if point is not on headline, also show
1192 entry and all children
1194 canonical show current headline, its direct ancestors along with
1195 their entries and children; if point is not located on
1196 the headline, also show current entry and all children
1198 As special cases, a nil or t value means show all contexts in
1199 `minimal' or `canonical' view, respectively.
1201 Some views can make displayed information very compact, but also
1202 make it harder to edit the location of the match. In such
1203 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1205 :group
'org-reveal-location
1207 :package-version
'(Org .
"9.0")
1209 (const :tag
"Canonical" t
)
1210 (const :tag
"Minimal" nil
)
1211 (repeat :greedy t
:tag
"Individual contexts"
1213 (choice :tag
"Context"
1220 (const bookmark-jump
)
1223 (choice :tag
"Detail level"
1229 (const canonical
))))))
1231 (defcustom org-indirect-buffer-display
'other-window
1232 "How should indirect tree buffers be displayed?
1234 This applies to indirect buffers created with the commands
1235 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1238 current-window Display in the current window
1239 other-window Just display in another window.
1240 dedicated-frame Create one new frame, and re-use it each time.
1241 new-frame Make a new frame each time. Note that in this case
1242 previously-made indirect buffers are kept, and you need to
1243 kill these buffers yourself."
1244 :group
'org-structure
1245 :group
'org-agenda-windows
1247 (const :tag
"In current window" current-window
)
1248 (const :tag
"In current frame, other window" other-window
)
1249 (const :tag
"Each time a new frame" new-frame
)
1250 (const :tag
"One dedicated frame" dedicated-frame
)))
1252 (defcustom org-use-speed-commands nil
1253 "Non-nil means activate single letter commands at beginning of a headline.
1254 This may also be a function to test for appropriate locations where speed
1255 commands should be active.
1257 For example, to activate speed commands when the point is on any
1258 star at the beginning of the headline, you can do this:
1260 (setq org-use-speed-commands
1261 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1262 :group
'org-structure
1264 (const :tag
"Never" nil
)
1265 (const :tag
"At beginning of headline stars" t
)
1268 (defcustom org-speed-commands-user nil
1269 "Alist of additional speed commands.
1270 This list will be checked before `org-speed-commands-default'
1271 when the variable `org-use-speed-commands' is non-nil
1272 and when the cursor is at the beginning of a headline.
1273 The car if each entry is a string with a single letter, which must
1274 be assigned to `self-insert-command' in the global map.
1275 The cdr is either a command to be called interactively, a function
1276 to be called, or a form to be evaluated.
1277 An entry that is just a list with a single string will be interpreted
1278 as a descriptive headline that will be added when listing the speed
1279 commands in the Help buffer using the `?' speed command."
1280 :group
'org-structure
1281 :type
'(repeat :value
("k" . ignore
)
1282 (choice :value
("k" . ignore
)
1283 (list :tag
"Descriptive Headline" (string :tag
"Headline"))
1284 (cons :tag
"Letter and Command"
1285 (string :tag
"Command letter")
1290 (defcustom org-bookmark-names-plist
1291 '(:last-capture
"org-capture-last-stored"
1292 :last-refile
"org-refile-last-stored"
1293 :last-capture-marker
"org-capture-last-stored-marker")
1294 "Names for bookmarks automatically set by some Org commands.
1295 This can provide strings as names for a number of bookmarks Org sets
1296 automatically. The following keys are currently implemented:
1298 :last-capture-marker
1300 When a key does not show up in the property list, the corresponding bookmark
1302 :group
'org-structure
1305 (defgroup org-cycle nil
1306 "Options concerning visibility cycling in Org mode."
1308 :group
'org-structure
)
1310 (defcustom org-cycle-skip-children-state-if-no-children t
1311 "Non-nil means skip CHILDREN state in entries that don't have any."
1315 (defcustom org-cycle-max-level nil
1316 "Maximum level which should still be subject to visibility cycling.
1317 Levels higher than this will, for cycling, be treated as text, not a headline.
1318 When `org-odd-levels-only' is set, a value of N in this variable actually
1319 means 2N-1 stars as the limiting headline.
1320 When nil, cycle all levels.
1321 Note that the limiting level of cycling is also influenced by
1322 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1323 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1327 (const :tag
"No limit" nil
)
1328 (integer :tag
"Maximum level")))
1330 (defcustom org-hide-block-startup nil
1331 "Non-nil means entering Org mode will fold all blocks.
1332 This can also be set in on a per-file basis with
1334 #+STARTUP: hideblocks
1335 #+STARTUP: showblocks"
1340 (defcustom org-cycle-global-at-bob nil
1341 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1343 This makes it possible to do global cycling without having to use `S-TAB'
1344 or `\\[universal-argument] TAB'. For this special case to work, the first \
1346 must not be a headline -- it may be empty or some other text.
1348 When used in this way, `org-cycle-hook' is disabled temporarily to make
1349 sure the cursor stays at the beginning of the buffer.
1351 When this option is nil, don't do anything special at the beginning of
1356 (defcustom org-cycle-level-after-item
/entry-creation t
1357 "Non-nil means cycle entry level or item indentation in new empty entries.
1359 When the cursor is at the end of an empty headline, i.e., with only stars
1360 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1361 and then all possible ancestor states, before returning to the original state.
1362 This makes data entry extremely fast: M-RET to create a new headline,
1363 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1365 When the cursor is at the end of an empty plain list item, one TAB will
1366 make it a subitem, two or more tabs will back up to make this an item
1367 higher up in the item hierarchy."
1371 (defcustom org-cycle-emulate-tab t
1372 "Where should `org-cycle' emulate TAB.
1374 white Only in completely white lines
1375 whitestart Only at the beginning of lines, before the first non-white char
1376 t Everywhere except in headlines
1377 exc-hl-bol Everywhere except at the start of a headline
1378 If TAB is used in a place where it does not emulate TAB, the current subtree
1379 visibility is cycled."
1381 :type
'(choice (const :tag
"Never" nil
)
1382 (const :tag
"Only in completely white lines" white
)
1383 (const :tag
"Before first char in a line" whitestart
)
1384 (const :tag
"Everywhere except in headlines" t
)
1385 (const :tag
"Everywhere except at bol in headlines" exc-hl-bol
)))
1387 (defcustom org-cycle-separator-lines
2
1388 "Number of empty lines needed to keep an empty line between collapsed trees.
1389 If you leave an empty line between the end of a subtree and the following
1390 headline, this empty line is hidden when the subtree is folded.
1391 Org mode will leave (exactly) one empty line visible if the number of
1392 empty lines is equal or larger to the number given in this variable.
1393 So the default 2 means at least 2 empty lines after the end of a subtree
1394 are needed to produce free space between a collapsed subtree and the
1397 If the number is negative, and the number of empty lines is at least -N,
1398 all empty lines are shown.
1400 Special case: when 0, never leave empty lines in collapsed view."
1403 (put 'org-cycle-separator-lines
'safe-local-variable
'integerp
)
1405 (defcustom org-pre-cycle-hook nil
1406 "Hook that is run before visibility cycling is happening.
1407 The function(s) in this hook must accept a single argument which indicates
1408 the new state that will be set right after running this hook. The
1409 argument is a symbol. Before a global state change, it can have the values
1410 `overview', `content', or `all'. Before a local state change, it can have
1411 the values `folded', `children', or `subtree'."
1415 (defcustom org-cycle-hook
'(org-cycle-hide-archived-subtrees
1416 org-cycle-hide-drawers
1417 org-cycle-show-empty-lines
1418 org-optimize-window-after-visibility-change
)
1419 "Hook that is run after `org-cycle' has changed the buffer visibility.
1420 The function(s) in this hook must accept a single argument which indicates
1421 the new state that was set by the most recent `org-cycle' command. The
1422 argument is a symbol. After a global state change, it can have the values
1423 `overview', `contents', or `all'. After a local state change, it can have
1424 the values `folded', `children', or `subtree'."
1428 :package-version
'(Org .
"8.3"))
1430 (defgroup org-edit-structure nil
1431 "Options concerning structure editing in Org mode."
1432 :tag
"Org Edit Structure"
1433 :group
'org-structure
)
1435 (defcustom org-odd-levels-only nil
1436 "Non-nil means skip even levels and only use odd levels for the outline.
1437 This has the effect that two stars are being added/taken away in
1438 promotion/demotion commands. It also influences how levels are
1439 handled by the exporters.
1440 Changing it requires restart of `font-lock-mode' to become effective
1441 for fontification also in regions already fontified.
1442 You may also set this on a per-file basis by adding one of the following
1443 lines to the buffer:
1447 :group
'org-edit-structure
1448 :group
'org-appearance
1451 (defcustom org-adapt-indentation t
1452 "Non-nil means adapt indentation to outline node level.
1454 When this variable is set, Org assumes that you write outlines by
1455 indenting text in each node to align with the headline (after the
1456 stars). The following issues are influenced by this variable:
1458 - The indentation is increased by one space in a demotion
1459 command, and decreased by one in a promotion command. However,
1460 in the latter case, if shifting some line in the entry body
1461 would alter document structure (e.g., insert a new headline),
1462 indentation is not changed at all.
1464 - Property drawers and planning information is inserted indented
1465 when this variable is set. When nil, they will not be indented.
1467 - TAB indents a line relative to current level. The lines below
1468 a headline will be indented when this variable is set.
1470 Note that this is all about true indentation, by adding and
1471 removing space characters. See also `org-indent.el' which does
1472 level-dependent indentation in a virtual way, i.e. at display
1474 :group
'org-edit-structure
1477 (defcustom org-special-ctrl-a
/e nil
1478 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1480 When t, `C-a' will bring back the cursor to the beginning of the
1481 headline text, i.e. after the stars and after a possible TODO
1482 keyword. In an item, this will be the position after bullet and
1483 check-box, if any. When the cursor is already at that position,
1484 another `C-a' will bring it to the beginning of the line.
1486 `C-e' will jump to the end of the headline, ignoring the presence
1487 of tags in the headline. A second `C-e' will then jump to the
1488 true end of the line, after any tags. This also means that, when
1489 this variable is non-nil, `C-e' also will never jump beyond the
1490 end of the heading of a folded section, i.e. not after the
1493 When set to the symbol `reversed', the first `C-a' or `C-e' works
1494 normally, going to the true line boundary first. Only a directly
1495 following, identical keypress will bring the cursor to the
1498 This may also be a cons cell where the behavior for `C-a' and
1499 `C-e' is set separately."
1500 :group
'org-edit-structure
1502 (const :tag
"off" nil
)
1503 (const :tag
"on: after stars/bullet and before tags first" t
)
1504 (const :tag
"reversed: true line boundary first" reversed
)
1505 (cons :tag
"Set C-a and C-e separately"
1506 (choice :tag
"Special C-a"
1507 (const :tag
"off" nil
)
1508 (const :tag
"on: after stars/bullet first" t
)
1509 (const :tag
"reversed: before stars/bullet first" reversed
))
1510 (choice :tag
"Special C-e"
1511 (const :tag
"off" nil
)
1512 (const :tag
"on: before tags first" t
)
1513 (const :tag
"reversed: after tags first" reversed
)))))
1514 (defvaralias 'org-special-ctrl-a
'org-special-ctrl-a
/e
)
1516 (defcustom org-special-ctrl-k nil
1517 "Non-nil means `C-k' will behave specially in headlines.
1518 When nil, `C-k' will call the default `kill-line' command.
1519 When t, the following will happen while the cursor is in the headline:
1521 - When the cursor is at the beginning of a headline, kill the entire
1522 line and possible the folded subtree below the line.
1523 - When in the middle of the headline text, kill the headline up to the tags.
1524 - When after the headline text, kill the tags."
1525 :group
'org-edit-structure
1528 (defcustom org-ctrl-k-protect-subtree nil
1529 "Non-nil means, do not delete a hidden subtree with C-k.
1530 When set to the symbol `error', simply throw an error when C-k is
1531 used to kill (part-of) a headline that has hidden text behind it.
1532 Any other non-nil value will result in a query to the user, if it is
1533 OK to kill that hidden subtree. When nil, kill without remorse."
1534 :group
'org-edit-structure
1537 (const :tag
"Do not protect hidden subtrees" nil
)
1538 (const :tag
"Protect hidden subtrees with a security query" t
)
1539 (const :tag
"Never kill a hidden subtree with C-k" error
)))
1541 (defcustom org-special-ctrl-o t
1542 "Non-nil means, make `C-o' insert a row in tables."
1543 :group
'org-edit-structure
1546 (defcustom org-catch-invisible-edits nil
1547 "Check if in invisible region before inserting or deleting a character.
1550 nil Do not check, so just do invisible edits.
1551 error Throw an error and do nothing.
1552 show Make point visible, and do the requested edit.
1553 show-and-error Make point visible, then throw an error and abort the edit.
1554 smart Make point visible, and do insertion/deletion if it is
1555 adjacent to visible text and the change feels predictable.
1556 Never delete a previously invisible character or add in the
1557 middle or right after an invisible region. Basically, this
1558 allows insertion and backward-delete right before ellipses.
1559 FIXME: maybe in this case we should not even show?"
1560 :group
'org-edit-structure
1563 (const :tag
"Do not check" nil
)
1564 (const :tag
"Throw error when trying to edit" error
)
1565 (const :tag
"Unhide, but do not do the edit" show-and-error
)
1566 (const :tag
"Show invisible part and do the edit" show
)
1567 (const :tag
"Be smart and do the right thing" smart
)))
1569 (defcustom org-yank-folded-subtrees t
1570 "Non-nil means when yanking subtrees, fold them.
1571 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1572 it starts with a heading and all other headings in it are either children
1573 or siblings, then fold all the subtrees. However, do this only if no
1574 text after the yank would be swallowed into a folded tree by this action."
1575 :group
'org-edit-structure
1578 (defcustom org-yank-adjusted-subtrees nil
1579 "Non-nil means when yanking subtrees, adjust the level.
1580 With this setting, `org-paste-subtree' is used to insert the subtree, see
1581 this function for details."
1582 :group
'org-edit-structure
1585 (defcustom org-M-RET-may-split-line
'((default . t
))
1586 "Non-nil means M-RET will split the line at the cursor position.
1587 When nil, it will go to the end of the line before making a
1589 You may also set this option in a different way for different
1590 contexts. Valid contexts are:
1592 headline when creating a new headline
1593 item when creating a new item
1594 table in a table field
1595 default the value to be used for all contexts not explicitly
1597 :group
'org-structure
1600 (const :tag
"Always" t
)
1601 (const :tag
"Never" nil
)
1602 (repeat :greedy t
:tag
"Individual contexts"
1604 (choice :tag
"Context"
1612 (defcustom org-insert-heading-respect-content nil
1613 "Non-nil means insert new headings after the current subtree.
1615 When nil, the new heading is created directly after the current line.
1616 The commands `\\[org-insert-heading-respect-content]' and \
1617 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1618 for the duration of the command."
1619 :group
'org-structure
1622 (defcustom org-blank-before-new-entry
'((heading . auto
)
1623 (plain-list-item . auto
))
1624 "Should `org-insert-heading' leave a blank line before new heading/item?
1625 The value is an alist, with `heading' and `plain-list-item' as CAR,
1626 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1627 which case Org will look at the surrounding headings/items and try to
1628 make an intelligent decision whether to insert a blank line or not."
1629 :group
'org-edit-structure
1631 (cons (const heading
)
1632 (choice (const :tag
"Never" nil
)
1633 (const :tag
"Always" t
)
1634 (const :tag
"Auto" auto
)))
1635 (cons (const plain-list-item
)
1636 (choice (const :tag
"Never" nil
)
1637 (const :tag
"Always" t
)
1638 (const :tag
"Auto" auto
)))))
1640 (defcustom org-insert-heading-hook nil
1641 "Hook being run after inserting a new heading."
1642 :group
'org-edit-structure
1645 (defcustom org-enable-fixed-width-editor t
1646 "Non-nil means lines starting with \":\" are treated as fixed-width.
1647 This currently only means they are never auto-wrapped.
1648 When nil, such lines will be treated like ordinary lines."
1649 :group
'org-edit-structure
1652 (defcustom org-goto-auto-isearch t
1653 "Non-nil means typing characters in `org-goto' starts incremental search.
1654 When nil, you can use these keybindings to navigate the buffer:
1656 q Quit the org-goto interface
1657 n Go to the next visible heading
1658 p Go to the previous visible heading
1659 f Go one heading forward on same level
1660 b Go one heading backward on same level
1661 u Go one heading up"
1662 :group
'org-edit-structure
1665 (defgroup org-sparse-trees nil
1666 "Options concerning sparse trees in Org mode."
1667 :tag
"Org Sparse Trees"
1668 :group
'org-structure
)
1670 (defcustom org-highlight-sparse-tree-matches t
1671 "Non-nil means highlight all matches that define a sparse tree.
1672 The highlights will automatically disappear the next time the buffer is
1673 changed by an edit command."
1674 :group
'org-sparse-trees
1677 (defcustom org-remove-highlights-with-change t
1678 "Non-nil means any change to the buffer will remove temporary highlights.
1680 Such highlights are created by `org-occur' and `org-clock-display'.
1681 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1682 to get rid of the highlights.
1683 The highlights created by `org-toggle-latex-fragment' always need
1684 `\\[org-toggle-latex-fragment]' to be removed."
1685 :group
'org-sparse-trees
1689 (defcustom org-occur-case-fold-search t
1690 "Non-nil means `org-occur' should be case-insensitive.
1691 If set to `smart' the search will be case-insensitive only if it
1692 doesn't specify any upper case character."
1693 :group
'org-sparse-trees
1696 (const :tag
"Case-sensitive" nil
)
1697 (const :tag
"Case-insensitive" t
)
1698 (const :tag
"Case-insensitive for lower case searches only" 'smart
)))
1700 (defcustom org-occur-hook
'(org-first-headline-recenter)
1701 "Hook that is run after `org-occur' has constructed a sparse tree.
1702 This can be used to recenter the window to show as much of the structure
1704 :group
'org-sparse-trees
1707 (defgroup org-imenu-and-speedbar nil
1708 "Options concerning imenu and speedbar in Org mode."
1709 :tag
"Org Imenu and Speedbar"
1710 :group
'org-structure
)
1712 (defcustom org-imenu-depth
2
1713 "The maximum level for Imenu access to Org headlines.
1714 This also applied for speedbar access."
1715 :group
'org-imenu-and-speedbar
1718 (defgroup org-table nil
1719 "Options concerning tables in Org mode."
1723 (defcustom org-enable-table-editor
'optimized
1724 "Non-nil means lines starting with \"|\" are handled by the table editor.
1725 When nil, such lines will be treated like ordinary lines.
1727 When equal to the symbol `optimized', the table editor will be optimized to
1729 - Automatic overwrite mode in front of whitespace in table fields.
1730 This makes the structure of the table stay in tact as long as the edited
1731 field does not exceed the column width.
1732 - Minimize the number of realigns. Normally, the table is aligned each time
1733 TAB or RET are pressed to move to another field. With optimization this
1734 happens only if changes to a field might have changed the column width.
1735 Optimization requires replacing the functions `self-insert-command',
1736 `delete-char', and `backward-delete-char' in Org buffers, with a
1737 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1738 good at guessing when a re-align will be necessary, but you can always
1739 force one with `\\[org-ctrl-c-ctrl-c]'.
1741 If you would like to use the optimized version in Org mode, but the
1742 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1744 This variable can be used to turn on and off the table editor during a session,
1745 but in order to toggle optimization, a restart is required.
1747 See also the variable `org-table-auto-blank-field'."
1750 (const :tag
"off" nil
)
1752 (const :tag
"on, optimized" optimized
)))
1754 (defcustom org-self-insert-cluster-for-undo nil
1755 "Non-nil means cluster self-insert commands for undo when possible.
1756 If this is set, then, like in the Emacs command loop, 20 consecutive
1757 characters will be undone together.
1758 This is configurable, because there is some impact on typing performance."
1762 (defcustom org-table-tab-recognizes-table.el t
1763 "Non-nil means TAB will automatically notice a table.el table.
1764 When it sees such a table, it moves point into it and - if necessary -
1765 calls `table-recognize-table'."
1766 :group
'org-table-editing
1769 (defgroup org-link nil
1770 "Options concerning links in Org mode."
1774 (defvar-local org-link-abbrev-alist-local nil
1775 "Buffer-local version of `org-link-abbrev-alist', which see.
1776 The value of this is taken from the #+LINK lines.")
1778 (defcustom org-link-parameters
1779 '(("doi" :follow org--open-doi-link
)
1780 ("elisp" :follow org--open-elisp-link
)
1781 ("file" :complete org-file-complete-link
)
1782 ("ftp" :follow
(lambda (path) (browse-url (concat "ftp:" path
))))
1783 ("help" :follow org--open-help-link
)
1784 ("http" :follow
(lambda (path) (browse-url (concat "http:" path
))))
1785 ("https" :follow
(lambda (path) (browse-url (concat "https:" path
))))
1786 ("mailto" :follow
(lambda (path) (browse-url (concat "mailto:" path
))))
1787 ("message" :follow
(lambda (path) (browse-url (concat "message:" path
))))
1788 ("news" :follow
(lambda (path) (browse-url (concat "news:" path
))))
1789 ("shell" :follow org--open-shell-link
))
1790 "An alist of properties that defines all the links in Org mode.
1791 The key in each association is a string of the link type.
1792 Subsequent optional elements make up a p-list of link properties.
1794 :follow - A function that takes the link path as an argument.
1796 :export - A function that takes the link path, description and
1797 export-backend as arguments.
1799 :store - A function responsible for storing the link. See the
1800 function `org-store-link-functions'.
1802 :complete - A function that inserts a link with completion. The
1803 function takes one optional prefix arg.
1805 :face - A face for the link, or a function that returns a face.
1806 The function takes one argument which is the link path. The
1807 default face is `org-link'.
1809 :mouse-face - The mouse-face. The default is `highlight'.
1811 :display - `full' will not fold the link in descriptive
1812 display. Default is `org-link'.
1814 :help-echo - A string or function that takes (window object position)
1815 as arguments and returns a string.
1817 :keymap - A keymap that is active on the link. The default is
1820 :htmlize-link - A function for the htmlize-link. Defaults
1821 to (list :uri \"type:path\")
1823 :activate-func - A function to run at the end of font-lock
1824 activation. The function must accept (link-start link-end path bracketp)
1827 :type
'(alist :tag
"Link display parameters"
1830 (defun org-link-get-parameter (type key
)
1831 "Get TYPE link property for KEY.
1832 TYPE is a string and KEY is a plist keyword."
1834 (cdr (assoc type org-link-parameters
))
1837 (defun org-link-set-parameters (type &rest parameters
)
1838 "Set link TYPE properties to PARAMETERS.
1839 PARAMETERS should be :key val pairs."
1840 (let ((data (assoc type org-link-parameters
)))
1841 (if data
(setcdr data
(org-combine-plists (cdr data
) parameters
))
1842 (push (cons type parameters
) org-link-parameters
)
1843 (org-make-link-regexps)
1844 (org-element-update-syntax))))
1846 (defun org-link-types ()
1847 "Return a list of known link types."
1848 (mapcar #'car org-link-parameters
))
1850 (defcustom org-link-abbrev-alist nil
1851 "Alist of link abbreviations.
1852 The car of each element is a string, to be replaced at the start of a link.
1853 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1854 links in Org buffers can have an optional tag after a double colon, e.g.,
1856 [[linkkey:tag][description]]
1858 The `linkkey' must be a single word, starting with a letter, followed
1859 by letters, numbers, `-' or `_'.
1861 If REPLACE is a string, the tag will simply be appended to create the link.
1862 If the string contains \"%s\", the tag will be inserted there. If the string
1863 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1864 at that point (see the function `url-hexify-string'). If the string contains
1865 the specifier \"%(my-function)\", then the custom function `my-function' will
1866 be invoked: this function takes the tag as its only argument and must return
1869 REPLACE may also be a function that will be called with the tag as the
1870 only argument to create the link, which should be returned as a string.
1872 See the manual for examples."
1876 (string :tag
"Protocol")
1878 (string :tag
"Format")
1881 (defcustom org-descriptive-links t
1882 "Non-nil means Org will display descriptive links.
1883 E.g. [[http://orgmode.org][Org website]] will be displayed as
1884 \"Org Website\", hiding the link itself and just displaying its
1885 description. When set to nil, Org will display the full links
1888 You can interactively set the value of this variable by calling
1889 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1893 (defcustom org-link-file-path-type
'adaptive
1894 "How the path name in file links should be stored.
1897 relative Relative to the current directory, i.e. the directory of the file
1898 into which the link is being inserted.
1899 absolute Absolute path, if possible with ~ for home directory.
1900 noabbrev Absolute path, no abbreviation of home directory.
1901 adaptive Use relative path for files in the current directory and sub-
1902 directories of it. For other files, use an absolute path."
1910 (defvaralias 'org-activate-links
'org-highlight-links
)
1911 (defcustom org-highlight-links
'(bracket angle plain radio tag date footnote
)
1912 "Types of links that should be highlighted in Org files.
1914 This is a list of symbols, each one of them leading to the
1915 highlighting of a certain link type.
1917 You can still open links that are not highlighted.
1919 In principle, it does not hurt to turn on highlighting for all
1920 link types. There may be a small gain when turning off unused
1921 link types. The types are:
1923 bracket The recommended [[link][description]] or [[link]] links with hiding.
1924 angle Links in angular brackets that may contain whitespace like
1925 <bbdb:Carsten Dominik>.
1926 plain Plain links in normal text, no whitespace, like http://google.com.
1927 radio Text that is matched by a radio target, see manual for details.
1928 tag Tag settings in a headline (link to tag search).
1929 date Time stamps (link to calendar).
1930 footnote Footnote labels.
1932 If you set this variable during an Emacs session, use `org-mode-restart'
1933 in the Org buffer so that the change takes effect."
1935 :group
'org-appearance
1936 :type
'(set :greedy t
1937 (const :tag
"Double bracket links" bracket
)
1938 (const :tag
"Angular bracket links" angle
)
1939 (const :tag
"Plain text links" plain
)
1940 (const :tag
"Radio target matches" radio
)
1941 (const :tag
"Tags" tag
)
1942 (const :tag
"Timestamps" date
)
1943 (const :tag
"Footnotes" footnote
)))
1945 (defcustom org-make-link-description-function nil
1946 "Function to use for generating link descriptions from links.
1947 When nil, the link location will be used. This function must take
1948 two parameters: the first one is the link, the second one is the
1949 description generated by `org-insert-link'. The function should
1950 return the description to use."
1952 :type
'(choice (const nil
) (function)))
1954 (defgroup org-link-store nil
1955 "Options concerning storing links in Org mode."
1956 :tag
"Org Store Link"
1959 (defcustom org-url-hexify-p t
1960 "When non-nil, hexify URL when creating a link."
1963 :group
'org-link-store
)
1965 (defcustom org-email-link-description-format
"Email %c: %.30s"
1966 "Format of the description part of a link to an email or usenet message.
1967 The following %-escapes will be replaced by corresponding information:
1969 %F full \"From\" field
1970 %f name, taken from \"From\" field, address if no name
1971 %T full \"To\" field
1972 %t first name in \"To\" field, address if no name
1973 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1974 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1979 You may use normal field width specification between the % and the letter.
1980 This is for example useful to limit the length of the subject.
1982 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1983 :group
'org-link-store
1986 (defcustom org-from-is-user-regexp
1988 (when (and user-mail-address
(not (string= user-mail-address
"")))
1989 (setq r1
(concat "\\<" (regexp-quote user-mail-address
) "\\>")))
1990 (when (and user-full-name
(not (string= user-full-name
"")))
1991 (setq r2
(concat "\\<" (regexp-quote user-full-name
) "\\>")))
1992 (if (and r1 r2
) (concat r1
"\\|" r2
) (or r1 r2
)))
1993 "Regexp matched against the \"From:\" header of an email or usenet message.
1994 It should match if the message is from the user him/herself."
1995 :group
'org-link-store
1998 (defcustom org-context-in-file-links t
1999 "Non-nil means file links from `org-store-link' contain context.
2001 A search string will be added to the file name with :: as separator
2002 and used to find the context when the link is activated by the command
2003 `org-open-at-point'. When this option is t, the entire active region
2004 will be placed in the search string of the file link. If set to a
2005 positive integer, only the first n lines of context will be stored.
2007 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2008 \\[org-store-link]')
2009 negates this setting for the duration of the command."
2010 :group
'org-link-store
2011 :type
'(choice boolean integer
))
2013 (defcustom org-keep-stored-link-after-insertion nil
2014 "Non-nil means keep link in list for entire session.
2016 The command `org-store-link' adds a link pointing to the current
2017 location to an internal list. These links accumulate during a session.
2018 The command `org-insert-link' can be used to insert links into any
2019 Org file (offering completion for all stored links).
2021 When this option is nil, every link which has been inserted once using
2022 `\\[org-insert-link]' will be removed from the list, to make completing the \
2024 links more efficient."
2025 :group
'org-link-store
2028 (defgroup org-link-follow nil
2029 "Options concerning following links in Org mode."
2030 :tag
"Org Follow Link"
2033 (defcustom org-link-translation-function nil
2034 "Function to translate links with different syntax to Org syntax.
2035 This can be used to translate links created for example by the Planner
2036 or emacs-wiki packages to Org syntax.
2037 The function must accept two parameters, a TYPE containing the link
2038 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2039 which is everything after the link protocol. It should return a cons
2040 with possibly modified values of type and path.
2041 Org contains a function for this, so if you set this variable to
2042 `org-translate-link-from-planner', you should be able follow many
2043 links created by planner."
2044 :group
'org-link-follow
2045 :type
'(choice (const nil
) (function)))
2047 (defcustom org-follow-link-hook nil
2048 "Hook that is run after a link has been followed."
2049 :group
'org-link-follow
2052 (defcustom org-tab-follows-link nil
2053 "Non-nil means on links TAB will follow the link.
2054 Needs to be set before org.el is loaded.
2055 This really should not be used, it does not make sense, and the
2056 implementation is bad."
2057 :group
'org-link-follow
2060 (defcustom org-return-follows-link nil
2061 "Non-nil means on links RET will follow the link.
2062 In tables, the special behavior of RET has precedence."
2063 :group
'org-link-follow
2066 (defcustom org-mouse-1-follows-link
2067 (if (boundp 'mouse-1-click-follows-link
) mouse-1-click-follows-link t
)
2068 "Non-nil means mouse-1 on a link will follow the link.
2069 A longer mouse click will still set point. Needs to be set
2070 before org.el is loaded."
2071 :group
'org-link-follow
2073 :package-version
'(Org .
"8.3")
2075 (const :tag
"A double click follows the link" double
)
2076 (const :tag
"Unconditionally follow the link with mouse-1" t
)
2077 (integer :tag
"mouse-1 click does not follow the link if longer than N ms" 450)))
2079 (defcustom org-mark-ring-length
4
2080 "Number of different positions to be recorded in the ring.
2081 Changing this requires a restart of Emacs to work correctly."
2082 :group
'org-link-follow
2085 (defcustom org-link-search-must-match-exact-headline
'query-to-create
2086 "Non-nil means internal fuzzy links can only match headlines.
2088 When nil, the a fuzzy link may point to a target or a named
2089 construct in the document. When set to the special value
2090 `query-to-create', offer to create a new headline when none
2093 Spaces and statistics cookies are ignored during heading searches."
2094 :group
'org-link-follow
2097 (const :tag
"Use fuzzy text search" nil
)
2098 (const :tag
"Match only exact headline" t
)
2099 (const :tag
"Match exact headline or query to create it"
2103 (defcustom org-link-frame-setup
2104 '((vm . vm-visit-folder-other-frame
)
2105 (vm-imap . vm-visit-imap-folder-other-frame
)
2106 (gnus . org-gnus-no-new-news
)
2107 (file . find-file-other-window
)
2108 (wl . wl-other-frame
))
2109 "Setup the frame configuration for following links.
2110 When following a link with Emacs, it may often be useful to display
2111 this link in another window or frame. This variable can be used to
2112 set this up for the different types of links.
2115 `vm-visit-folder-other-window'
2116 `vm-visit-folder-other-frame'
2117 For Gnus, use any of
2120 `org-gnus-no-new-news'
2121 For FILE, use any of
2123 `find-file-other-window'
2124 `find-file-other-frame'
2125 For Wanderlust use any of
2128 For the calendar, use the variable `calendar-setup'.
2129 For BBDB, it is currently only possible to display the matches in
2131 :group
'org-link-follow
2135 (const vm-visit-folder
)
2136 (const vm-visit-folder-other-window
)
2137 (const vm-visit-folder-other-frame
)))
2138 (cons (const vm-imap
)
2140 (const vm-visit-imap-folder
)
2141 (const vm-visit-imap-folder-other-window
)
2142 (const vm-visit-imap-folder-other-frame
)))
2146 (const gnus-other-frame
)
2147 (const org-gnus-no-new-news
)))
2151 (const find-file-other-window
)
2152 (const find-file-other-frame
)))
2156 (const wl-other-frame
)))))
2158 (defcustom org-display-internal-link-with-indirect-buffer nil
2159 "Non-nil means use indirect buffer to display infile links.
2160 Activating internal links (from one location in a file to another location
2161 in the same file) normally just jumps to the location. When the link is
2162 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2164 another window. When this option is set, the other window actually displays
2165 an indirect buffer clone of the current buffer, to avoid any visibility
2166 changes to the current buffer."
2167 :group
'org-link-follow
2170 (defcustom org-open-non-existing-files nil
2171 "Non-nil means `org-open-file' will open non-existing files.
2172 When nil, an error will be generated.
2173 This variable applies only to external applications because they
2174 might choke on non-existing files. If the link is to a file that
2175 will be opened in Emacs, the variable is ignored."
2176 :group
'org-link-follow
2179 (defcustom org-open-directory-means-index-dot-org nil
2180 "Non-nil means a link to a directory really means to index.org.
2181 When nil, following a directory link will run dired or open a finder/explorer
2182 window on that directory."
2183 :group
'org-link-follow
2186 (defcustom org-confirm-shell-link-function
'yes-or-no-p
2187 "Non-nil means ask for confirmation before executing shell links.
2188 Shell links can be dangerous: just think about a link
2190 [[shell:rm -rf ~/*][Google Search]]
2192 This link would show up in your Org document as \"Google Search\",
2193 but really it would remove your entire home directory.
2194 Therefore we advise against setting this variable to nil.
2195 Just change it to `y-or-n-p' if you want to confirm with a
2196 single keystroke rather than having to type \"yes\"."
2197 :group
'org-link-follow
2199 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
2200 (const :tag
"with y-or-n (faster)" y-or-n-p
)
2201 (const :tag
"no confirmation (dangerous)" nil
)))
2202 (put 'org-confirm-shell-link-function
2203 'safe-local-variable
2204 (lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
2206 (defcustom org-confirm-shell-link-not-regexp
""
2207 "A regexp to skip confirmation for shell links."
2208 :group
'org-link-follow
2212 (defcustom org-confirm-elisp-link-function
'yes-or-no-p
2213 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2214 Elisp links can be dangerous: just think about a link
2216 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2218 This link would show up in your Org document as \"Google Search\",
2219 but really it would remove your entire home directory.
2220 Therefore we advise against setting this variable to nil.
2221 Just change it to `y-or-n-p' if you want to confirm with a
2222 single keystroke rather than having to type \"yes\"."
2223 :group
'org-link-follow
2225 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
2226 (const :tag
"with y-or-n (faster)" y-or-n-p
)
2227 (const :tag
"no confirmation (dangerous)" nil
)))
2228 (put 'org-confirm-shell-link-function
2229 'safe-local-variable
2230 (lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
2232 (defcustom org-confirm-elisp-link-not-regexp
""
2233 "A regexp to skip confirmation for Elisp links."
2234 :group
'org-link-follow
2238 (defconst org-file-apps-defaults-gnu
2242 "Default file applications on a UNIX or GNU/Linux system.
2243 See `org-file-apps'.")
2245 (defconst org-file-apps-defaults-macosx
2247 (system .
"open %s")
2249 ("eps.gz" .
"gv %s")
2253 "Default file applications on a macOS system.
2254 The system \"open\" is known as a default, but we use X11 applications
2255 for some files for which the OS does not have a good default.
2256 See `org-file-apps'.")
2258 (defconst org-file-apps-defaults-windowsnt
2259 (list '(remote . emacs
)
2260 (cons 'system
(lambda (file _path
)
2261 (with-no-warnings (w32-shell-execute "open" file
))))
2262 (cons t
(lambda (file _path
)
2263 (with-no-warnings (w32-shell-execute "open" file
)))))
2264 "Default file applications on a Windows NT system.
2265 The system \"open\" is used for most files.
2266 See `org-file-apps'.")
2268 (defcustom org-file-apps
2269 '((auto-mode . emacs
)
2270 ("\\.mm\\'" . default
)
2271 ("\\.x?html?\\'" . default
)
2272 ("\\.pdf\\'" . default
))
2273 "External applications for opening `file:path' items in a document.
2276 Org mode uses system defaults for different file types, but
2277 you can use this variable to set the application for a given file
2278 extension. The entries in this list are cons cells where the car identifies
2279 files and the cdr the corresponding command.
2281 Possible values for the file identifier are:
2283 \"string\" A string as a file identifier can be interpreted in different
2284 ways, depending on its contents:
2286 - Alphanumeric characters only:
2287 Match links with this file extension.
2288 Example: (\"pdf\" . \"evince %s\")
2289 to open PDFs with evince.
2291 - Regular expression: Match links where the
2292 filename matches the regexp. If you want to
2293 use groups here, use shy groups.
2295 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2296 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2297 to open *.html and *.xhtml with firefox.
2299 - Regular expression which contains (non-shy) groups:
2300 Match links where the whole link, including \"::\", and
2301 anything after that, matches the regexp.
2302 In a custom command string, %1, %2, etc. are replaced with
2303 the parts of the link that were matched by the groups.
2304 For backwards compatibility, if a command string is given
2305 that does not use any of the group matches, this case is
2306 handled identically to the second one (i.e. match against
2308 In a custom function, you can access the group matches with
2309 (match-string n link).
2311 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2312 \"evince -p %1 %s\")
2313 to open [[file:document.pdf::5]] with evince at page 5.
2315 `directory' Matches a directory
2316 `remote' Matches a remote file, accessible through tramp or efs.
2317 Remote files most likely should be visited through Emacs
2318 because external applications cannot handle such paths.
2319 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2320 so all files Emacs knows how to handle. Using this with
2321 command `emacs' will open most files in Emacs. Beware that this
2322 will also open html files inside Emacs, unless you add
2323 (\"html\" . default) to the list as well.
2324 `system' The system command to open files, like `open' on Windows
2325 and macOS, and mailcap under GNU/Linux. This is the command
2326 that will be selected if you call `org-open-at-point' with a
2327 double prefix argument (`\\[universal-argument] \
2328 \\[universal-argument] \\[org-open-at-point]').
2329 t Default for files not matched by any of the other options.
2331 Possible values for the command are:
2333 `emacs' The file will be visited by the current Emacs process.
2334 `default' Use the default application for this file type, which is the
2335 association for t in the list, most likely in the system-specific
2336 part. This can be used to overrule an unwanted setting in the
2337 system-specific variable.
2338 `system' Use the system command for opening files, like \"open\".
2339 This command is specified by the entry whose car is `system'.
2340 Most likely, the system-specific version of this variable
2341 does define this command, but you can overrule/replace it
2343 `mailcap' Use command specified in the mailcaps.
2344 string A command to be executed by a shell; %s will be replaced
2345 by the path to the file.
2346 function A Lisp function, which will be called with two arguments:
2347 the file path and the original link string, without the
2350 For more examples, see the system specific constants
2351 `org-file-apps-defaults-macosx'
2352 `org-file-apps-defaults-windowsnt'
2353 `org-file-apps-defaults-gnu'."
2354 :group
'org-link-follow
2356 (cons (choice :value
""
2357 (string :tag
"Extension")
2358 (const :tag
"System command to open files" system
)
2359 (const :tag
"Default for unrecognized files" t
)
2360 (const :tag
"Remote file" remote
)
2361 (const :tag
"Links to a directory" directory
)
2362 (const :tag
"Any files that have Emacs modes"
2365 (const :tag
"Visit with Emacs" emacs
)
2366 (const :tag
"Use default" default
)
2367 (const :tag
"Use the system command" system
)
2368 (string :tag
"Command")
2369 (function :tag
"Function")))))
2371 (defcustom org-doi-server-url
"http://dx.doi.org/"
2372 "The URL of the DOI server."
2375 :group
'org-link-follow
)
2377 (defgroup org-refile nil
2378 "Options concerning refiling entries in Org mode."
2382 (defcustom org-directory
"~/org"
2383 "Directory with Org files.
2384 This is just a default location to look for Org files. There is no need
2385 at all to put your files into this directory. It is used in the
2386 following situations:
2388 1. When a capture template specifies a target file that is not an
2389 absolute path. The path will then be interpreted relative to
2391 2. When the value of variable `org-agenda-files' is a single file, any
2392 relative paths in this file will be taken as relative to
2398 (defcustom org-default-notes-file
(convert-standard-filename "~/.notes")
2399 "Default target for storing notes.
2400 Used as a fall back file for org-capture.el, for templates that
2401 do not specify a target file."
2406 (defcustom org-goto-interface
'outline
2407 "The default interface to be used for `org-goto'.
2409 outline The interface shows an outline of the relevant file
2410 and the correct heading is found by moving through
2411 the outline or by searching with incremental search.
2412 outline-path-completion Headlines in the current buffer are offered via
2413 completion. This is the interface also used by
2414 the refile command."
2417 (const :tag
"Outline" outline
)
2418 (const :tag
"Outline-path-completion" outline-path-completion
)))
2420 (defcustom org-goto-max-level
5
2421 "Maximum target level when running `org-goto' with refile interface."
2425 (defcustom org-reverse-note-order nil
2426 "Non-nil means store new notes at the beginning of a file or entry.
2427 When nil, new notes will be filed to the end of a file or entry.
2428 This can also be a list with cons cells of regular expressions that
2429 are matched against file names, and values."
2433 (const :tag
"Reverse always" t
)
2434 (const :tag
"Reverse never" nil
)
2435 (repeat :tag
"By file name regexp"
2436 (cons regexp boolean
))))
2438 (defcustom org-log-refile nil
2439 "Information to record when a task is refiled.
2441 Possible values are:
2443 nil Don't add anything
2444 time Add a time stamp to the task
2445 note Prompt for a note and add it with template `org-log-note-headings'
2447 This option can also be set with on a per-file-basis with
2449 #+STARTUP: nologrefile
2450 #+STARTUP: logrefile
2451 #+STARTUP: lognoterefile
2453 You can have local logging settings for a subtree by setting the LOGGING
2454 property to one or more of these keywords.
2456 When bulk-refiling from the agenda, the value `note' is forbidden and
2457 will temporarily be changed to `time'."
2459 :group
'org-progress
2462 (const :tag
"No logging" nil
)
2463 (const :tag
"Record timestamp" time
)
2464 (const :tag
"Record timestamp with note." note
)))
2466 (defcustom org-refile-targets nil
2467 "Targets for refiling entries with `\\[org-refile]'.
2468 This is a list of cons cells. Each cell contains:
2469 - a specification of the files to be considered, either a list of files,
2470 or a symbol whose function or variable value will be used to retrieve
2471 a file name or a list of file names. If you use `org-agenda-files' for
2472 that, all agenda files will be scanned for targets. Nil means consider
2473 headings in the current buffer.
2474 - A specification of how to find candidate refile targets. This may be
2476 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2477 This tag has to be present in all target headlines, inheritance will
2479 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2481 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2482 headlines that are refiling targets.
2483 - a cons cell (:level . N). Any headline of level N is considered a target.
2484 Note that, when `org-odd-levels-only' is set, level corresponds to
2485 order in hierarchy, not to the number of stars.
2486 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2487 Note that, when `org-odd-levels-only' is set, level corresponds to
2488 order in hierarchy, not to the number of stars.
2490 Each element of this list generates a set of possible targets.
2491 The union of these sets is presented (with completion) to
2492 the user by `org-refile'.
2494 You can set the variable `org-refile-target-verify-function' to a function
2495 to verify each headline found by the simple criteria above.
2497 When this variable is nil, all top-level headlines in the current buffer
2498 are used, equivalent to the value `((nil . (:level . 1))'."
2502 (choice :value org-agenda-files
2503 (const :tag
"All agenda files" org-agenda-files
)
2504 (const :tag
"Current buffer" nil
)
2505 (function) (variable) (file))
2506 (choice :tag
"Identify target headline by"
2507 (cons :tag
"Specific tag" (const :value
:tag
) (string))
2508 (cons :tag
"TODO keyword" (const :value
:todo
) (string))
2509 (cons :tag
"Regular expression" (const :value
:regexp
) (regexp))
2510 (cons :tag
"Level number" (const :value
:level
) (integer))
2511 (cons :tag
"Max Level number" (const :value
:maxlevel
) (integer))))))
2513 (defcustom org-refile-target-verify-function nil
2514 "Function to verify if the headline at point should be a refile target.
2515 The function will be called without arguments, with point at the
2516 beginning of the headline. It should return t and leave point
2517 where it is if the headline is a valid target for refiling.
2519 If the target should not be selected, the function must return nil.
2520 In addition to this, it may move point to a place from where the search
2521 should be continued. For example, the function may decide that the entire
2522 subtree of the current entry should be excluded and move point to the end
2529 (defcustom org-refile-use-cache nil
2530 "Non-nil means cache refile targets to speed up the process.
2532 The cache for a particular file will be updated automatically when
2533 the buffer has been killed, or when any of the marker used for flagging
2534 refile targets no longer points at a live buffer.
2535 If you have added new entries to a buffer that might themselves be targets,
2536 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2537 if you find that easier, \
2538 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2544 (defcustom org-refile-use-outline-path nil
2545 "Non-nil means provide refile targets as paths.
2546 So a level 3 headline will be available as level1/level2/level3.
2548 When the value is `file', also include the file name (without directory)
2549 into the path. In this case, you can also stop the completion after
2550 the file name, to get entries inserted as top level in the file.
2552 When `full-file-path', include the full file path."
2555 (const :tag
"Not" nil
)
2556 (const :tag
"Yes" t
)
2557 (const :tag
"Start with file name" file
)
2558 (const :tag
"Start with full file path" full-file-path
)))
2560 (defcustom org-outline-path-complete-in-steps t
2561 "Non-nil means complete the outline path in hierarchical steps.
2562 When Org uses the refile interface to select an outline path (see
2563 `org-refile-use-outline-path'), the completion of the path can be
2564 done in a single go, or it can be done in steps down the headline
2565 hierarchy. Going in steps is probably the best if you do not use
2566 a special completion package like `ido' or `icicles'. However,
2567 when using these packages, going in one step can be very fast,
2568 while still showing the whole path to the entry."
2572 (defcustom org-refile-allow-creating-parent-nodes nil
2573 "Non-nil means allow the creation of new nodes as refile targets.
2574 New nodes are then created by adding \"/new node name\" to the completion
2575 of an existing node. When the value of this variable is `confirm',
2576 new node creation must be confirmed by the user (recommended).
2577 When nil, the completion must match an existing entry.
2579 Note that, if the new heading is not seen by the criteria
2580 listed in `org-refile-targets', multiple instances of the same
2581 heading would be created by trying again to file under the new
2585 (const :tag
"Never" nil
)
2586 (const :tag
"Always" t
)
2587 (const :tag
"Prompt for confirmation" confirm
)))
2589 (defcustom org-refile-active-region-within-subtree nil
2590 "Non-nil means also refile active region within a subtree.
2592 By default `org-refile' doesn't allow refiling regions if they
2593 don't contain a set of subtrees, but it might be convenient to
2594 do so sometimes: in that case, the first line of the region is
2595 converted to a headline before refiling."
2600 (defgroup org-todo nil
2601 "Options concerning TODO items in Org mode."
2605 (defgroup org-progress nil
2606 "Options concerning Progress logging in Org mode."
2610 (defvar org-todo-interpretation-widgets
2611 '((:tag
"Sequence (cycling hits every state)" sequence
)
2612 (:tag
"Type (cycling directly to DONE)" type
))
2613 "The available interpretation symbols for customizing `org-todo-keywords'.
2614 Interested libraries should add to this list.")
2616 (defcustom org-todo-keywords
'((sequence "TODO" "DONE"))
2617 "List of TODO entry keyword sequences and their interpretation.
2618 \\<org-mode-map>This is a list of sequences.
2620 Each sequence starts with a symbol, either `sequence' or `type',
2621 indicating if the keywords should be interpreted as a sequence of
2622 action steps, or as different types of TODO items. The first
2623 keywords are states requiring action - these states will select a headline
2624 for inclusion into the global TODO list Org produces. If one of the
2625 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2626 signify that no further action is necessary. If \"|\" is not found,
2627 the last keyword is treated as the only DONE state of the sequence.
2629 The command `\\[org-todo]' cycles an entry through these states, and one
2630 additional state where no keyword is present. For details about this
2631 cycling, see the manual.
2633 TODO keywords and interpretation can also be set on a per-file basis with
2634 the special #+SEQ_TODO and #+TYP_TODO lines.
2636 Each keyword can optionally specify a character for fast state selection
2637 \(in combination with the variable `org-use-fast-todo-selection')
2638 and specifiers for state change logging, using the same syntax that
2639 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2640 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2641 indicates to record a time stamp each time this state is selected.
2643 Each keyword may also specify if a timestamp or a note should be
2644 recorded when entering or leaving the state, by adding additional
2645 characters in the parenthesis after the keyword. This looks like this:
2646 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2647 record only the time of the state change. With X and Y being either
2648 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2649 Y when leaving the state if and only if the *target* state does not
2650 define X. You may omit any of the fast-selection key or X or /Y,
2651 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2653 For backward compatibility, this variable may also be just a list
2654 of keywords. In this case the interpretation (sequence or type) will be
2655 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2657 :group
'org-keywords
2659 (repeat :tag
"Old syntax, just keywords"
2660 (string :tag
"Keyword"))
2661 (repeat :tag
"New syntax"
2664 :tag
"Interpretation"
2665 ;;Quick and dirty way to see
2666 ;;`org-todo-interpretations'. This takes the
2667 ;;place of item arguments
2675 org-todo-interpretation-widgets
))
2678 (string :tag
"Keyword"))))))
2680 (defvar-local org-todo-keywords-1 nil
2681 "All TODO and DONE keywords active in a buffer.")
2682 (defvar org-todo-keywords-for-agenda nil
)
2683 (defvar org-done-keywords-for-agenda nil
)
2684 (defvar org-todo-keyword-alist-for-agenda nil
)
2685 (defvar org-tag-alist-for-agenda nil
2686 "Alist of all tags from all agenda files.")
2687 (defvar org-tag-groups-alist-for-agenda nil
2688 "Alist of all groups tags from all current agenda files.")
2689 (defvar-local org-tag-groups-alist nil
)
2690 (defvar org-agenda-contributing-files nil
)
2691 (defvar-local org-current-tag-alist nil
2692 "Alist of all tag groups in current buffer.
2693 This variable takes into consideration `org-tag-alist',
2694 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2695 (defvar-local org-not-done-keywords nil
)
2696 (defvar-local org-done-keywords nil
)
2697 (defvar-local org-todo-heads nil
)
2698 (defvar-local org-todo-sets nil
)
2699 (defvar-local org-todo-log-states nil
)
2700 (defvar-local org-todo-kwd-alist nil
)
2701 (defvar-local org-todo-key-alist nil
)
2702 (defvar-local org-todo-key-trigger nil
)
2704 (defcustom org-todo-interpretation
'sequence
2705 "Controls how TODO keywords are interpreted.
2706 This variable is in principle obsolete and is only used for
2707 backward compatibility, if the interpretation of todo keywords is
2708 not given already in `org-todo-keywords'. See that variable for
2711 :group
'org-keywords
2712 :type
'(choice (const sequence
)
2715 (defcustom org-use-fast-todo-selection t
2717 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2718 This variable describes if and under what circumstances the cycling
2719 mechanism for TODO keywords will be replaced by a single-key, direct
2722 When nil, fast selection is never used.
2724 When the symbol `prefix', it will be used when `org-todo' is called
2725 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2726 in an Org buffer, and
2727 `\\[universal-argument] t' in an agenda buffer.
2729 When t, fast selection is used by default. In this case, the prefix
2730 argument forces cycling instead.
2732 In all cases, the special interface is only used if access keys have
2733 actually been assigned by the user, i.e. if keywords in the configuration
2734 are followed by a letter in parenthesis, like TODO(t)."
2737 (const :tag
"Never" nil
)
2738 (const :tag
"By default" t
)
2739 (const :tag
"Only with C-u C-c C-t" prefix
)))
2741 (defcustom org-provide-todo-statistics t
2742 "Non-nil means update todo statistics after insert and toggle.
2743 ALL-HEADLINES means update todo statistics by including headlines
2744 with no TODO keyword as well, counting them as not done.
2745 A list of TODO keywords means the same, but skip keywords that are
2747 When set to a list of two lists, the first list contains keywords
2748 to consider as TODO keywords, the second list contains keywords
2749 to consider as DONE keywords.
2751 When this is set, todo statistics is updated in the parent of the
2752 current entry each time a todo state is changed."
2755 (const :tag
"Yes, only for TODO entries" t
)
2756 (const :tag
"Yes, including all entries" all-headlines
)
2757 (repeat :tag
"Yes, for TODOs in this list"
2758 (string :tag
"TODO keyword"))
2759 (list :tag
"Yes, for TODOs and DONEs in these lists"
2760 (repeat (string :tag
"TODO keyword"))
2761 (repeat (string :tag
"DONE keyword")))
2762 (other :tag
"No TODO statistics" nil
)))
2764 (defcustom org-hierarchical-todo-statistics t
2765 "Non-nil means TODO statistics covers just direct children.
2766 When nil, all entries in the subtree are considered.
2767 This has only an effect if `org-provide-todo-statistics' is set.
2768 To set this to nil for only a single subtree, use a COOKIE_DATA
2769 property and include the word \"recursive\" into the value."
2773 (defcustom org-after-todo-state-change-hook nil
2774 "Hook which is run after the state of a TODO item was changed.
2775 The new state (a string with a TODO keyword, or nil) is available in the
2776 Lisp variable `org-state'."
2780 (defvar org-blocker-hook nil
2781 "Hook for functions that are allowed to block a state change.
2783 Functions in this hook should not modify the buffer.
2784 Each function gets as its single argument a property list,
2785 see `org-trigger-hook' for more information about this list.
2787 If any of the functions in this hook returns nil, the state change
2790 (defvar org-trigger-hook nil
2791 "Hook for functions that are triggered by a state change.
2793 Each function gets as its single argument a property list with at
2794 least the following elements:
2796 (:type type-of-change :position pos-at-entry-start
2797 :from old-state :to new-state)
2799 Depending on the type, more properties may be present.
2801 This mechanism is currently implemented for:
2805 :type todo-state-change
2806 :from previous state (keyword as a string), or nil, or a symbol
2807 `todo' or `done', to indicate the general type of state.
2808 :to new state, like in :from")
2810 (defcustom org-enforce-todo-dependencies nil
2811 "Non-nil means undone TODO entries will block switching the parent to DONE.
2812 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2813 be blocked if any prior sibling is not yet done.
2814 Finally, if the parent is blocked because of ordered siblings of its own,
2815 the child will also be blocked."
2816 :set
(lambda (var val
)
2819 (add-hook 'org-blocker-hook
2820 'org-block-todo-from-children-or-siblings-or-parent
)
2821 (remove-hook 'org-blocker-hook
2822 'org-block-todo-from-children-or-siblings-or-parent
)))
2826 (defcustom org-enforce-todo-checkbox-dependencies nil
2827 "Non-nil means unchecked boxes will block switching the parent to DONE.
2828 When this is nil, checkboxes have no influence on switching TODO states.
2829 When non-nil, you first need to check off all check boxes before the TODO
2830 entry can be switched to DONE.
2831 This variable needs to be set before org.el is loaded, and you need to
2832 restart Emacs after a change to make the change effective. The only way
2833 to change is while Emacs is running is through the customize interface."
2834 :set
(lambda (var val
)
2837 (add-hook 'org-blocker-hook
2838 'org-block-todo-from-checkboxes
)
2839 (remove-hook 'org-blocker-hook
2840 'org-block-todo-from-checkboxes
)))
2844 (defcustom org-treat-insert-todo-heading-as-state-change nil
2845 "Non-nil means inserting a TODO heading is treated as state change.
2846 So when the command `\\[org-insert-todo-heading]' is used, state change
2847 logging will apply if appropriate. When nil, the new TODO item will
2848 be inserted directly, and no logging will take place."
2852 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2853 "Non-nil means switching TODO states with S-cursor counts as state change.
2854 This is the default behavior. However, setting this to nil allows a
2855 convenient way to select a TODO state and bypass any logging associated
2860 (defcustom org-todo-state-tags-triggers nil
2861 "Tag changes that should be triggered by TODO state changes.
2862 This is a list. Each entry is
2864 (state-change (tag . flag) .......)
2866 State-change can be a string with a state, and empty string to indicate the
2867 state that has no TODO keyword, or it can be one of the symbols `todo'
2868 or `done', meaning any not-done or done state, respectively."
2872 (cons (choice :tag
"When changing to"
2873 (const :tag
"Not-done state" todo
)
2874 (const :tag
"Done state" done
)
2875 (string :tag
"State"))
2877 (cons :tag
"Tag action"
2879 (choice (const :tag
"Add" t
) (const :tag
"Remove" nil
)))))))
2881 (defcustom org-log-done nil
2882 "Information to record when a task moves to the DONE state.
2884 Possible values are:
2886 nil Don't add anything, just change the keyword
2887 time Add a time stamp to the task
2888 note Prompt for a note and add it with template `org-log-note-headings'
2890 This option can also be set with on a per-file-basis with
2892 #+STARTUP: nologdone
2894 #+STARTUP: lognotedone
2896 You can have local logging settings for a subtree by setting the LOGGING
2897 property to one or more of these keywords."
2899 :group
'org-progress
2901 (const :tag
"No logging" nil
)
2902 (const :tag
"Record CLOSED timestamp" time
)
2903 (const :tag
"Record CLOSED timestamp with note." note
)))
2905 ;; Normalize old uses of org-log-done.
2907 ((eq org-log-done t
) (setq org-log-done
'time
))
2908 ((and (listp org-log-done
) (memq 'done org-log-done
))
2909 (setq org-log-done
'note
)))
2911 (defcustom org-log-reschedule nil
2912 "Information to record when the scheduling date of a tasks is modified.
2914 Possible values are:
2916 nil Don't add anything, just change the date
2917 time Add a time stamp to the task
2918 note Prompt for a note and add it with template `org-log-note-headings'
2920 This option can also be set with on a per-file-basis with
2922 #+STARTUP: nologreschedule
2923 #+STARTUP: logreschedule
2924 #+STARTUP: lognotereschedule"
2926 :group
'org-progress
2928 (const :tag
"No logging" nil
)
2929 (const :tag
"Record timestamp" time
)
2930 (const :tag
"Record timestamp with note." note
)))
2932 (defcustom org-log-redeadline nil
2933 "Information to record when the deadline date of a tasks is modified.
2935 Possible values are:
2937 nil Don't add anything, just change the date
2938 time Add a time stamp to the task
2939 note Prompt for a note and add it with template `org-log-note-headings'
2941 This option can also be set with on a per-file-basis with
2943 #+STARTUP: nologredeadline
2944 #+STARTUP: logredeadline
2945 #+STARTUP: lognoteredeadline
2947 You can have local logging settings for a subtree by setting the LOGGING
2948 property to one or more of these keywords."
2950 :group
'org-progress
2952 (const :tag
"No logging" nil
)
2953 (const :tag
"Record timestamp" time
)
2954 (const :tag
"Record timestamp with note." note
)))
2956 (defcustom org-log-note-clock-out nil
2957 "Non-nil means record a note when clocking out of an item.
2958 This can also be configured on a per-file basis by adding one of
2959 the following lines anywhere in the buffer:
2961 #+STARTUP: lognoteclock-out
2962 #+STARTUP: nolognoteclock-out"
2964 :group
'org-progress
2967 (defcustom org-log-done-with-time t
2968 "Non-nil means the CLOSED time stamp will contain date and time.
2969 When nil, only the date will be recorded."
2970 :group
'org-progress
2973 (defcustom org-log-note-headings
2974 '((done .
"CLOSING NOTE %t")
2975 (state .
"State %-12s from %-12S %t")
2976 (note .
"Note taken on %t")
2977 (reschedule .
"Rescheduled from %S on %t")
2978 (delschedule .
"Not scheduled, was %S on %t")
2979 (redeadline .
"New deadline from %S on %t")
2980 (deldeadline .
"Removed deadline, was %S on %t")
2981 (refile .
"Refiled on %t")
2983 "Headings for notes added to entries.
2985 The value is an alist, with the car being a symbol indicating the
2986 note context, and the cdr is the heading to be used. The heading
2987 may also be the empty string. The following placeholders can be
2991 %T an active time stamp instead the default inactive one
2992 %d a short-format time stamp.
2993 %D an active short-format time stamp.
2994 %s the new TODO state or time stamp (inactive), in double quotes.
2995 %S the old TODO state or time stamp (inactive), in double quotes.
2999 In fact, it is not a good idea to change the `state' entry,
3000 because Agenda Log mode depends on the format of these entries."
3002 :group
'org-progress
3003 :type
'(list :greedy t
3004 (cons (const :tag
"Heading when closing an item" done
) string
)
3006 "Heading when changing todo state (todo sequence only)"
3008 (cons (const :tag
"Heading when just taking a note" note
) string
)
3009 (cons (const :tag
"Heading when rescheduling" reschedule
) string
)
3010 (cons (const :tag
"Heading when an item is no longer scheduled" delschedule
) string
)
3011 (cons (const :tag
"Heading when changing deadline" redeadline
) string
)
3012 (cons (const :tag
"Heading when deleting a deadline" deldeadline
) string
)
3013 (cons (const :tag
"Heading when refiling" refile
) string
)
3014 (cons (const :tag
"Heading when clocking out" clock-out
) string
)))
3016 (unless (assq 'note org-log-note-headings
)
3017 (push '(note .
"%t") org-log-note-headings
))
3019 (defcustom org-log-into-drawer nil
3020 "Non-nil means insert state change notes and time stamps into a drawer.
3021 When nil, state changes notes will be inserted after the headline and
3022 any scheduling and clock lines, but not inside a drawer.
3024 The value of this variable should be the name of the drawer to use.
3025 LOGBOOK is proposed as the default drawer for this purpose, you can
3026 also set this to a string to define the drawer of your choice.
3028 A value of t is also allowed, representing \"LOGBOOK\".
3030 A value of t or nil can also be set with on a per-file-basis with
3032 #+STARTUP: logdrawer
3033 #+STARTUP: nologdrawer
3035 If this variable is set, `org-log-state-notes-insert-after-drawers'
3038 You can set the property LOG_INTO_DRAWER to overrule this setting for
3041 Do not check directly this variable in a Lisp program. Call
3042 function `org-log-into-drawer' instead."
3044 :group
'org-progress
3046 (const :tag
"Not into a drawer" nil
)
3047 (const :tag
"LOGBOOK" t
)
3048 (string :tag
"Other")))
3050 (defvaralias 'org-log-state-notes-into-drawer
'org-log-into-drawer
)
3052 (defun org-log-into-drawer ()
3053 "Name of the log drawer, as a string, or nil.
3054 This is the value of `org-log-into-drawer'. However, if the
3055 current entry has or inherits a LOG_INTO_DRAWER property, it will
3056 be used instead of the default value."
3057 (let ((p (org-entry-get nil
"LOG_INTO_DRAWER" 'inherit t
)))
3058 (cond ((equal p
"nil") nil
)
3059 ((equal p
"t") "LOGBOOK")
3062 ((stringp org-log-into-drawer
) org-log-into-drawer
)
3063 (org-log-into-drawer "LOGBOOK"))))
3065 (defcustom org-log-state-notes-insert-after-drawers nil
3066 "Non-nil means insert state change notes after any drawers in entry.
3067 Only the drawers that *immediately* follow the headline and the
3068 deadline/scheduled line are skipped.
3069 When nil, insert notes right after the heading and perhaps the line
3070 with deadline/scheduling if present.
3072 This variable will have no effect if `org-log-into-drawer' is
3075 :group
'org-progress
3078 (defcustom org-log-states-order-reversed t
3079 "Non-nil means the latest state note will be directly after heading.
3080 When nil, the state change notes will be ordered according to time.
3082 This option can also be set with on a per-file-basis with
3084 #+STARTUP: logstatesreversed
3085 #+STARTUP: nologstatesreversed"
3087 :group
'org-progress
3090 (defcustom org-todo-repeat-to-state nil
3091 "The TODO state to which a repeater should return the repeating task.
3092 By default this is the first task in a TODO sequence, or the previous state
3093 in a TODO_TYP set. But you can specify another task here.
3094 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3097 :type
'(choice (const :tag
"Head of sequence" nil
)
3098 (string :tag
"Specific state")))
3100 (defcustom org-log-repeat
'time
3101 "Non-nil means record moving through the DONE state when triggering repeat.
3102 An auto-repeating task is immediately switched back to TODO when
3103 marked DONE. If you are not logging state changes (by adding \"@\"
3104 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3105 record a closing note, there will be no record of the task moving
3106 through DONE. This variable forces taking a note anyway.
3108 nil Don't force a record
3109 time Record a time stamp
3110 note Prompt for a note and add it with template `org-log-note-headings'
3112 This option can also be set with on a per-file-basis with
3114 #+STARTUP: nologrepeat
3115 #+STARTUP: logrepeat
3116 #+STARTUP: lognoterepeat
3118 You can have local logging settings for a subtree by setting the LOGGING
3119 property to one or more of these keywords."
3121 :group
'org-progress
3123 (const :tag
"Don't force a record" nil
)
3124 (const :tag
"Force recording the DONE state" time
)
3125 (const :tag
"Force recording a note with the DONE state" note
)))
3128 (defgroup org-priorities nil
3129 "Priorities in Org mode."
3130 :tag
"Org Priorities"
3133 (defcustom org-enable-priority-commands t
3134 "Non-nil means priority commands are active.
3135 When nil, these commands will be disabled, so that you never accidentally
3137 :group
'org-priorities
3140 (defcustom org-highest-priority ?A
3141 "The highest priority of TODO items. A character like ?A, ?B etc.
3142 Must have a smaller ASCII number than `org-lowest-priority'."
3143 :group
'org-priorities
3146 (defcustom org-lowest-priority ?C
3147 "The lowest priority of TODO items. A character like ?A, ?B etc.
3148 Must have a larger ASCII number than `org-highest-priority'."
3149 :group
'org-priorities
3152 (defcustom org-default-priority ?B
3153 "The default priority of TODO items.
3154 This is the priority an item gets if no explicit priority is given.
3155 When starting to cycle on an empty priority the first step in the cycle
3156 depends on `org-priority-start-cycle-with-default'. The resulting first
3157 step priority must not exceed the range from `org-highest-priority' to
3158 `org-lowest-priority' which means that `org-default-priority' has to be
3159 in this range exclusive or inclusive the range boundaries. Else the
3160 first step refuses to set the default and the second will fall back
3161 to (depending on the command used) the highest or lowest priority."
3162 :group
'org-priorities
3165 (defcustom org-priority-start-cycle-with-default t
3166 "Non-nil means start with default priority when starting to cycle.
3167 When this is nil, the first step in the cycle will be (depending on the
3168 command used) one higher or lower than the default priority.
3169 See also `org-default-priority'."
3170 :group
'org-priorities
3173 (defcustom org-get-priority-function nil
3174 "Function to extract the priority from a string.
3175 The string is normally the headline. If this is nil Org computes the
3176 priority from the priority cookie like [#A] in the headline. It returns
3177 an integer, increasing by 1000 for each priority level.
3178 The user can set a different function here, which should take a string
3179 as an argument and return the numeric priority."
3180 :group
'org-priorities
3186 (defgroup org-time nil
3187 "Options concerning time stamps and deadlines in Org mode."
3191 (defcustom org-time-stamp-rounding-minutes
'(0 5)
3192 "Number of minutes to round time stamps to.
3194 These are two values, the first applies when first creating a time stamp.
3195 The second applies when changing it with the commands `S-up' and `S-down'.
3196 When changing the time stamp, this means that it will change in steps
3197 of N minutes, as given by the second value.
3199 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3200 numbers should be factors of 60, so for example 5, 10, 15.
3202 When this is larger than 1, you can still force an exact time stamp by using
3203 a double prefix argument to a time stamp command like \
3204 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3205 and by using a prefix arg to `S-up/down' to specify the exact number
3206 of minutes to shift."
3208 :get
(lambda (var) ; Make sure both elements are there
3209 (if (integerp (default-value var
))
3210 (list (default-value var
) 5)
3211 (default-value var
)))
3213 (integer :tag
"when inserting times")
3214 (integer :tag
"when modifying times")))
3216 ;; Normalize old customizations of this variable.
3217 (when (integerp org-time-stamp-rounding-minutes
)
3218 (setq org-time-stamp-rounding-minutes
3219 (list org-time-stamp-rounding-minutes
3220 org-time-stamp-rounding-minutes
)))
3222 (defcustom org-display-custom-times nil
3223 "Non-nil means overlay custom formats over all time stamps.
3224 The formats are defined through the variable `org-time-stamp-custom-formats'.
3225 To turn this on on a per-file basis, insert anywhere in the file:
3226 #+STARTUP: customtime"
3230 (make-variable-buffer-local 'org-display-custom-times
)
3232 (defcustom org-time-stamp-custom-formats
3233 '("<%m/%d/%y %a>" .
"<%m/%d/%y %a %H:%M>") ; american
3234 "Custom formats for time stamps. See `format-time-string' for the syntax.
3235 These are overlaid over the default ISO format if the variable
3236 `org-display-custom-times' is set. Time like %H:%M should be at the
3237 end of the second format. The custom formats are also honored by export
3238 commands, if custom time display is turned on at the time of export."
3242 (defun org-time-stamp-format (&optional long inactive
)
3243 "Get the right format for a time string."
3244 (let ((f (if long
(cdr org-time-stamp-formats
)
3245 (car org-time-stamp-formats
))))
3247 (concat "[" (substring f
1 -
1) "]")
3250 (defcustom org-time-clocksum-format
3251 '(:days
"%dd " :hours
"%d" :require-hours t
:minutes
":%02d" :require-minutes t
)
3252 "The format string used when creating CLOCKSUM lines.
3253 This is also used when Org mode generates a time duration.
3255 The value can be a single format string containing two
3256 %-sequences, which will be filled with the number of hours and
3257 minutes in that order.
3259 Alternatively, the value can be a plist associating any of the
3260 keys :years, :months, :weeks, :days, :hours or :minutes with
3261 format strings. The time duration is formatted using only the
3262 time components that are needed and concatenating the results.
3263 If a time unit in absent, it falls back to the next smallest
3266 The keys :require-years, :require-months, :require-days,
3267 :require-weeks, :require-hours, :require-minutes are also
3268 meaningful. A non-nil value for these keys indicates that the
3269 corresponding time component should always be included, even if
3275 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3278 means durations longer than a day will be expressed in days,
3279 hours and minutes, and durations less than a day will always be
3280 expressed in hours and minutes (even for durations less than an
3285 (:days \"%dd\" :minutes \"%dm\")
3287 means durations longer than a day will be expressed in days and
3288 minutes, and durations less than a day will be expressed entirely
3289 in minutes (even for durations longer than an hour)."
3293 :package-version
'(Org .
"8.0")
3294 :type
'(choice (string :tag
"Format string")
3296 (group :inline t
(const :tag
"Years" :years
)
3297 (string :tag
"Format string"))
3299 (const :tag
"Always show years" :require-years
)
3301 (group :inline t
(const :tag
"Months" :months
)
3302 (string :tag
"Format string"))
3304 (const :tag
"Always show months" :require-months
)
3306 (group :inline t
(const :tag
"Weeks" :weeks
)
3307 (string :tag
"Format string"))
3309 (const :tag
"Always show weeks" :require-weeks
)
3311 (group :inline t
(const :tag
"Days" :days
)
3312 (string :tag
"Format string"))
3314 (const :tag
"Always show days" :require-days
)
3316 (group :inline t
(const :tag
"Hours" :hours
)
3317 (string :tag
"Format string"))
3319 (const :tag
"Always show hours" :require-hours
)
3321 (group :inline t
(const :tag
"Minutes" :minutes
)
3322 (string :tag
"Format string"))
3324 (const :tag
"Always show minutes" :require-minutes
)
3327 (defcustom org-time-clocksum-use-fractional nil
3328 "When non-nil, `\\[org-clock-display]' uses fractional times.
3329 See `org-time-clocksum-format' for more on time clock formats."
3335 (defcustom org-time-clocksum-use-effort-durations nil
3336 "When non-nil, `\\[org-clock-display]' uses effort durations.
3337 E.g. by default, one day is considered to be a 8 hours effort,
3338 so a task that has been clocked for 16 hours will be displayed
3339 as during 2 days in the clock display or in the clocktable.
3341 See `org-effort-durations' on how to set effort durations
3342 and `org-time-clocksum-format' for more on time clock formats."
3346 :package-version
'(Org .
"8.0")
3349 (defcustom org-time-clocksum-fractional-format
"%.2f"
3350 "The format string used when creating CLOCKSUM lines,
3351 or when Org mode generates a time duration, if
3352 `org-time-clocksum-use-fractional' is enabled.
3354 The value can be a single format string containing one
3355 %-sequence, which will be filled with the number of hours as
3358 Alternatively, the value can be a plist associating any of the
3359 keys :years, :months, :weeks, :days, :hours or :minutes with
3360 a format string. The time duration is formatted using the
3361 largest time unit which gives a non-zero integer part. If all
3362 specified formats have zero integer part, the smallest time unit
3365 :type
'(choice (string :tag
"Format string")
3366 (set (group :inline t
(const :tag
"Years" :years
)
3367 (string :tag
"Format string"))
3368 (group :inline t
(const :tag
"Months" :months
)
3369 (string :tag
"Format string"))
3370 (group :inline t
(const :tag
"Weeks" :weeks
)
3371 (string :tag
"Format string"))
3372 (group :inline t
(const :tag
"Days" :days
)
3373 (string :tag
"Format string"))
3374 (group :inline t
(const :tag
"Hours" :hours
)
3375 (string :tag
"Format string"))
3376 (group :inline t
(const :tag
"Minutes" :minutes
)
3377 (string :tag
"Format string")))))
3379 (defcustom org-deadline-warning-days
14
3380 "Number of days before expiration during which a deadline becomes active.
3381 This variable governs the display in sparse trees and in the agenda.
3382 When 0 or negative, it means use this number (the absolute value of it)
3383 even if a deadline has a different individual lead time specified.
3385 Custom commands can set this variable in the options section."
3387 :group
'org-agenda-daily
/weekly
3390 (defcustom org-scheduled-delay-days
0
3391 "Number of days before a scheduled item becomes active.
3392 This variable governs the display in sparse trees and in the agenda.
3393 The default value (i.e. 0) means: don't delay scheduled item.
3394 When negative, it means use this number (the absolute value of it)
3395 even if a scheduled item has a different individual delay time
3398 Custom commands can set this variable in the options section."
3400 :group
'org-agenda-daily
/weekly
3402 :package-version
'(Org .
"8.0")
3405 (defcustom org-read-date-prefer-future t
3406 "Non-nil means assume future for incomplete date input from user.
3407 This affects the following situations:
3408 1. The user gives a month but not a year.
3409 For example, if it is April and you enter \"feb 2\", this will be read
3410 as Feb 2, *next* year. \"May 5\", however, will be this year.
3411 2. The user gives a day, but no month.
3412 For example, if today is the 15th, and you enter \"3\", Org will read
3413 this as the third of *next* month. However, if you enter \"17\",
3414 it will be considered as *this* month.
3416 If you set this variable to the symbol `time', then also the following
3419 3. If the user gives a time.
3420 If the time is before now, it will be interpreted as tomorrow.
3422 Currently none of this works for ISO week specifications.
3424 When this option is nil, the current day, month and year will always be
3427 See also `org-agenda-jump-prefer-future'."
3430 (const :tag
"Never" nil
)
3431 (const :tag
"Check month and day" t
)
3432 (const :tag
"Check month, day, and time" time
)))
3434 (defcustom org-agenda-jump-prefer-future
'org-read-date-prefer-future
3435 "Should the agenda jump command prefer the future for incomplete dates?
3436 The default is to do the same as configured in `org-read-date-prefer-future'.
3437 But you can also set a deviating value here.
3438 This may t or nil, or the symbol `org-read-date-prefer-future'."
3443 (const :tag
"Use org-read-date-prefer-future"
3444 org-read-date-prefer-future
)
3445 (const :tag
"Never" nil
)
3446 (const :tag
"Always" t
)))
3448 (defcustom org-read-date-force-compatible-dates t
3449 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3451 Depending on the system Emacs is running on, certain dates cannot
3452 be represented with the type used internally to represent time.
3453 Dates between 1970-1-1 and 2038-1-1 can always be represented
3454 correctly. Some systems allow for earlier dates, some for later,
3455 some for both. One way to find out it to insert any date into an
3456 Org buffer, putting the cursor on the year and hitting S-up and
3457 S-down to test the range.
3459 When this variable is set to t, the date/time prompt will not let
3460 you specify dates outside the 1970-2037 range, so it is certain that
3461 these dates will work in whatever version of Emacs you are
3462 running, and also that you can move a file from one Emacs implementation
3463 to another. WHenever Org is forcing the year for you, it will display
3466 When this variable is nil, Org will check if the date is
3467 representable in the specific Emacs implementation you are using.
3468 If not, it will force a year, usually the current year, and beep
3469 to remind you. Currently this setting is not recommended because
3470 the likelihood that you will open your Org files in an Emacs that
3471 has limited date range is not negligible.
3473 A workaround for this problem is to use diary sexp dates for time
3474 stamps outside of this range."
3479 (defcustom org-read-date-display-live t
3480 "Non-nil means display current interpretation of date prompt live.
3481 This display will be in an overlay, in the minibuffer."
3485 (defcustom org-read-date-popup-calendar t
3486 "Non-nil means pop up a calendar when prompting for a date.
3487 In the calendar, the date can be selected with mouse-1. However, the
3488 minibuffer will also be active, and you can simply enter the date as well.
3489 When nil, only the minibuffer will be available."
3492 (defvaralias 'org-popup-calendar-for-date-prompt
3493 'org-read-date-popup-calendar
)
3495 (defcustom org-extend-today-until
0
3496 "The hour when your day really ends. Must be an integer.
3497 This has influence for the following applications:
3498 - When switching the agenda to \"today\". It it is still earlier than
3499 the time given here, the day recognized as TODAY is actually yesterday.
3500 - When a date is read from the user and it is still before the time given
3501 here, the current date and time will be assumed to be yesterday, 23:59.
3502 Also, timestamps inserted in capture templates follow this rule.
3504 IMPORTANT: This is a feature whose implementation is and likely will
3505 remain incomplete. Really, it is only here because past midnight seems to
3506 be the favorite working time of John Wiegley :-)"
3510 (defcustom org-use-effective-time nil
3511 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3512 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3513 \"effective time\" of any timestamps between midnight and 8am will be
3514 23:59 of the previous day."
3519 (defcustom org-use-last-clock-out-time-as-effective-time nil
3520 "When non-nil, use the last clock out time for `org-todo'.
3521 Note that this option has precedence over the combined use of
3522 `org-use-effective-time' and `org-extend-today-until'."
3525 :package-version
'(Org .
"8.0")
3528 (defcustom org-edit-timestamp-down-means-later nil
3529 "Non-nil means S-down will increase the time in a time stamp.
3530 When nil, S-up will increase."
3534 (defcustom org-calendar-follow-timestamp-change t
3535 "Non-nil means make the calendar window follow timestamp changes.
3536 When a timestamp is modified and the calendar window is visible, it will be
3537 moved to the new date."
3541 (defgroup org-tags nil
3542 "Options concerning tags in Org mode."
3546 (defcustom org-tag-alist nil
3547 "Default tags available in Org files.
3549 The value of this variable is an alist. Associations either:
3555 where TAG is a tag as a string, SELECT is character, used to
3556 select that tag through the fast tag selection interface, and
3557 SPECIAL is one of the following keywords: `:startgroup',
3558 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3559 `:newline'. These keywords are used to define a hierarchy of
3560 tags. See manual for details.
3562 When this variable is nil, Org mode bases tag input on what is
3563 already in the buffer. The value can be overridden locally by
3564 using a TAGS keyword, e.g.,
3568 See also `org-tag-persistent-alist' to sidestep this behavior."
3572 (cons (string :tag
"Tag name")
3573 (character :tag
"Access char"))
3574 (const :tag
"Start radio group" (:startgroup
))
3575 (const :tag
"Start tag group, non distinct" (:startgrouptag
))
3576 (const :tag
"Group tags delimiter" (:grouptags
))
3577 (const :tag
"End radio group" (:endgroup
))
3578 (const :tag
"End tag group, non distinct" (:endgrouptag
))
3579 (const :tag
"New line" (:newline
)))))
3581 (defcustom org-tag-persistent-alist nil
3582 "Tags always available in Org files.
3584 The value of this variable is an alist. Associations either:
3590 where TAG is a tag as a string, SELECT is a character, used to
3591 select that tag through the fast tag selection interface, and
3592 SPECIAL is one of the following keywords: `:startgroup',
3593 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3594 `:newline'. These keywords are used to define a hierarchy of
3595 tags. See manual for details.
3597 Unlike to `org-tag-alist', tags defined in this variable do not
3598 depend on a local TAGS keyword. Instead, to disable these tags
3599 on a per-file basis, insert anywhere in the file:
3605 (cons (string :tag
"Tag name")
3606 (character :tag
"Access char"))
3607 (const :tag
"Start radio group" (:startgroup
))
3608 (const :tag
"Start tag group, non distinct" (:startgrouptag
))
3609 (const :tag
"Group tags delimiter" (:grouptags
))
3610 (const :tag
"End radio group" (:endgroup
))
3611 (const :tag
"End tag group, non distinct" (:endgrouptag
))
3612 (const :tag
"New line" (:newline
)))))
3614 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3615 "If non-nil, always offer completion for all tags of all agenda files.
3616 Instead of customizing this variable directly, you might want to
3617 set it locally for capture buffers, because there no list of
3618 tags in that file can be created dynamically (there are none).
3620 (add-hook \\='org-capture-mode-hook
3622 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3627 (defvar org-file-tags nil
3628 "List of tags that can be inherited by all entries in the file.
3629 The tags will be inherited if the variable `org-use-tag-inheritance'
3630 says they should be.
3631 This variable is populated from #+FILETAGS lines.")
3633 (defcustom org-use-fast-tag-selection
'auto
3634 "Non-nil means use fast tag selection scheme.
3635 This is a special interface to select and deselect tags with single keys.
3636 When nil, fast selection is never used.
3637 When the symbol `auto', fast selection is used if and only if selection
3638 characters for tags have been configured, either through the variable
3639 `org-tag-alist' or through a #+TAGS line in the buffer.
3640 When t, fast selection is always used and selection keys are assigned
3641 automatically if necessary."
3644 (const :tag
"Always" t
)
3645 (const :tag
"Never" nil
)
3646 (const :tag
"When selection characters are configured" auto
)))
3648 (defcustom org-fast-tag-selection-single-key nil
3649 "Non-nil means fast tag selection exits after first change.
3650 When nil, you have to press RET to exit it.
3651 During fast tag selection, you can toggle this flag with `C-c'.
3652 This variable can also have the value `expert'. In this case, the window
3653 displaying the tags menu is not even shown, until you press C-c again."
3656 (const :tag
"No" nil
)
3657 (const :tag
"Yes" t
)
3658 (const :tag
"Expert" expert
)))
3660 (defvar org-fast-tag-selection-include-todo nil
3661 "Non-nil means fast tags selection interface will also offer TODO states.
3662 This is an undocumented feature, you should not rely on it.")
3664 (defcustom org-tags-column -
77
3665 "The column to which tags should be indented in a headline.
3666 If this number is positive, it specifies the column. If it is negative,
3667 it means that the tags should be flushright to that column. For example,
3668 -80 works well for a normal 80 character screen.
3669 When 0, place tags directly after headline text, with only one space in
3674 (defcustom org-auto-align-tags t
3675 "Non-nil keeps tags aligned when modifying headlines.
3676 Some operations (i.e. demoting) change the length of a headline and
3677 therefore shift the tags around. With this option turned on, after
3678 each such operation the tags are again aligned to `org-tags-column'."
3682 (defcustom org-use-tag-inheritance t
3683 "Non-nil means tags in levels apply also for sublevels.
3684 When nil, only the tags directly given in a specific line apply there.
3685 This may also be a list of tags that should be inherited, or a regexp that
3686 matches tags that should be inherited. Additional control is possible
3687 with the variable `org-tags-exclude-from-inheritance' which gives an
3688 explicit list of tags to be excluded from inheritance, even if the value of
3689 `org-use-tag-inheritance' would select it for inheritance.
3691 If this option is t, a match early-on in a tree can lead to a large
3692 number of matches in the subtree when constructing the agenda or creating
3693 a sparse tree. If you only want to see the first match in a tree during
3694 a search, check out the variable `org-tags-match-list-sublevels'."
3697 (const :tag
"Not" nil
)
3698 (const :tag
"Always" t
)
3699 (repeat :tag
"Specific tags" (string :tag
"Tag"))
3700 (regexp :tag
"Tags matched by regexp")))
3702 (defcustom org-tags-exclude-from-inheritance nil
3703 "List of tags that should never be inherited.
3704 This is a way to exclude a few tags from inheritance. For way to do
3705 the opposite, to actively allow inheritance for selected tags,
3706 see the variable `org-use-tag-inheritance'."
3708 :type
'(repeat (string :tag
"Tag")))
3710 (defun org-tag-inherit-p (tag)
3711 "Check if TAG is one that should be inherited."
3713 ((member tag org-tags-exclude-from-inheritance
) nil
)
3714 ((eq org-use-tag-inheritance t
) t
)
3715 ((not org-use-tag-inheritance
) nil
)
3716 ((stringp org-use-tag-inheritance
)
3717 (string-match org-use-tag-inheritance tag
))
3718 ((listp org-use-tag-inheritance
)
3719 (member tag org-use-tag-inheritance
))
3720 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3722 (defcustom org-tags-match-list-sublevels t
3723 "Non-nil means list also sublevels of headlines matching a search.
3724 This variable applies to tags/property searches, and also to stuck
3725 projects because this search is based on a tags match as well.
3727 When set to the symbol `indented', sublevels are indented with
3730 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3731 the sublevels of a headline matching a tag search often also match
3732 the same search. Listing all of them can create very long lists.
3733 Setting this variable to nil causes subtrees of a match to be skipped.
3735 This variable is semi-obsolete and probably should always be true. It
3736 is better to limit inheritance to certain tags using the variables
3737 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3740 (const :tag
"No, don't list them" nil
)
3741 (const :tag
"Yes, do list them" t
)
3742 (const :tag
"List them, indented with leading dots" indented
)))
3744 (defcustom org-tags-sort-function nil
3745 "When set, tags are sorted using this function as a comparator."
3748 (const :tag
"No sorting" nil
)
3749 (const :tag
"Alphabetical" string
<)
3750 (const :tag
"Reverse alphabetical" string
>)
3751 (function :tag
"Custom function" nil
)))
3753 (defvar org-tags-history nil
3754 "History of minibuffer reads for tags.")
3755 (defvar org-last-tags-completion-table nil
3756 "The last used completion table for tags.")
3757 (defvar org-after-tags-change-hook nil
3758 "Hook that is run after the tags in a line have changed.")
3760 (defgroup org-properties nil
3761 "Options concerning properties in Org mode."
3762 :tag
"Org Properties"
3765 (defcustom org-property-format
"%-10s %s"
3766 "How property key/value pairs should be formatted by `indent-line'.
3767 When `indent-line' hits a property definition, it will format the line
3768 according to this format, mainly to make sure that the values are
3769 lined-up with respect to each other."
3770 :group
'org-properties
3773 (defcustom org-properties-postprocess-alist nil
3774 "Alist of properties and functions to adjust inserted values.
3775 Elements of this alist must be of the form
3777 ([string] [function])
3779 where [string] must be a property name and [function] must be a
3780 lambda expression: this lambda expression must take one argument,
3781 the value to adjust, and return the new value as a string.
3783 For example, this element will allow the property \"Remaining\"
3784 to be updated wrt the relation between the \"Effort\" property
3785 and the clock summary:
3787 ((\"Remaining\" (lambda(value)
3788 (let ((clocksum (org-clock-sum-current-item))
3789 (effort (org-duration-string-to-minutes
3790 (org-entry-get (point) \"Effort\"))))
3791 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3792 :group
'org-properties
3794 :type
'(alist :key-type
(string :tag
"Property")
3795 :value-type
(function :tag
"Function")))
3797 (defcustom org-use-property-inheritance nil
3798 "Non-nil means properties apply also for sublevels.
3800 This setting is chiefly used during property searches. Turning it on can
3801 cause significant overhead when doing a search, which is why it is not
3804 When nil, only the properties directly given in the current entry count.
3805 When t, every property is inherited. The value may also be a list of
3806 properties that should have inheritance, or a regular expression matching
3807 properties that should be inherited.
3809 However, note that some special properties use inheritance under special
3810 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3811 and the properties ending in \"_ALL\" when they are used as descriptor
3812 for valid values of a property.
3814 Note for programmers:
3815 When querying an entry with `org-entry-get', you can control if inheritance
3816 should be used. By default, `org-entry-get' looks only at the local
3817 properties. You can request inheritance by setting the inherit argument
3818 to t (to force inheritance) or to `selective' (to respect the setting
3820 :group
'org-properties
3822 (const :tag
"Not" nil
)
3823 (const :tag
"Always" t
)
3824 (repeat :tag
"Specific properties" (string :tag
"Property"))
3825 (regexp :tag
"Properties matched by regexp")))
3827 (defun org-property-inherit-p (property)
3828 "Check if PROPERTY is one that should be inherited."
3830 ((eq org-use-property-inheritance t
) t
)
3831 ((not org-use-property-inheritance
) nil
)
3832 ((stringp org-use-property-inheritance
)
3833 (string-match org-use-property-inheritance property
))
3834 ((listp org-use-property-inheritance
)
3835 (member property org-use-property-inheritance
))
3836 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3838 (defcustom org-columns-default-format
"%25ITEM %TODO %3PRIORITY %TAGS"
3839 "The default column format, if no other format has been defined.
3840 This variable can be set on the per-file basis by inserting a line
3842 #+COLUMNS: %25ITEM ....."
3843 :group
'org-properties
3846 (defcustom org-columns-ellipses
".."
3847 "The ellipses to be used when a field in column view is truncated.
3848 When this is the empty string, as many characters as possible are shown,
3849 but then there will be no visual indication that the field has been truncated.
3850 When this is a string of length N, the last N characters of a truncated
3851 field are replaced by this string. If the column is narrower than the
3852 ellipses string, only part of the ellipses string will be shown."
3853 :group
'org-properties
3856 (defconst org-global-properties-fixed
3857 '(("VISIBILITY_ALL" .
"folded children content all")
3858 ("CLOCK_MODELINE_TOTAL_ALL" .
"current today repeat all auto"))
3859 "List of property/value pairs that can be inherited by any entry.
3861 These are fixed values, for the preset properties. The user variable
3862 that can be used to add to this list is `org-global-properties'.
3864 The entries in this list are cons cells where the car is a property
3865 name and cdr is a string with the value. If the value represents
3866 multiple items like an \"_ALL\" property, separate the items by
3869 (defcustom org-global-properties nil
3870 "List of property/value pairs that can be inherited by any entry.
3872 This list will be combined with the constant `org-global-properties-fixed'.
3874 The entries in this list are cons cells where the car is a property
3875 name and cdr is a string with the value.
3877 You can set buffer-local values for the same purpose in the variable
3878 `org-file-properties' this by adding lines like
3880 #+PROPERTY: NAME VALUE"
3881 :group
'org-properties
3883 (cons (string :tag
"Property")
3884 (string :tag
"Value"))))
3886 (defvar-local org-file-properties nil
3887 "List of property/value pairs that can be inherited by any entry.
3888 Valid for the current buffer.
3889 This variable is populated from #+PROPERTY lines.")
3891 (defgroup org-agenda nil
3892 "Options concerning agenda views in Org mode."
3896 (defvar-local org-category nil
3897 "Variable used by org files to set a category for agenda display.
3898 Such files should use a file variable to set it, for example
3900 # -*- mode: org; org-category: \"ELisp\"
3902 or contain a special line
3906 If the file does not specify a category, then file's base name
3908 (put 'org-category
'safe-local-variable
(lambda (x) (or (symbolp x
) (stringp x
))))
3910 (defcustom org-agenda-files nil
3911 "The files to be used for agenda display.
3913 If an entry is a directory, all files in that directory that are matched
3914 by `org-agenda-file-regexp' will be part of the file list.
3916 If the value of the variable is not a list but a single file name, then
3917 the list of agenda files is actually stored and maintained in that file,
3918 one agenda file per line. In this file paths can be given relative to
3919 `org-directory'. Tilde expansion and environment variable substitution
3922 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3923 and removed with `\\[org-remove-file]'."
3926 (repeat :tag
"List of files and directories" file
)
3927 (file :tag
"Store list in a file\n" :value
"~/.agenda_files")))
3929 (defcustom org-agenda-file-regexp
"\\`[^.].*\\.org\\'"
3930 "Regular expression to match files for `org-agenda-files'.
3931 If any element in the list in that variable contains a directory instead
3932 of a normal file, all files in that directory that are matched by this
3933 regular expression will be included."
3937 (defcustom org-agenda-text-search-extra-files nil
3938 "List of extra files to be searched by text search commands.
3939 These files will be searched in addition to the agenda files by the
3940 commands `org-search-view' (`\\[org-agenda] s') \
3941 and `org-occur-in-agenda-files'.
3942 Note that these files will only be searched for text search commands,
3943 not for the other agenda views like todo lists, tag searches or the weekly
3944 agenda. This variable is intended to list notes and possibly archive files
3945 that should also be searched by these two commands.
3946 In fact, if the first element in the list is the symbol `agenda-archives',
3947 then all archive files of all agenda files will be added to the search
3950 :type
'(set :greedy t
3951 (const :tag
"Agenda Archives" agenda-archives
)
3952 (repeat :inline t
(file))))
3954 (defvaralias 'org-agenda-multi-occur-extra-files
3955 'org-agenda-text-search-extra-files
)
3957 (defcustom org-agenda-skip-unavailable-files nil
3958 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3959 A nil value means to remove them, after a query, from the list."
3963 (defcustom org-calendar-to-agenda-key
[?c
]
3964 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3965 The command `org-calendar-goto-agenda' will be bound to this key. The
3966 default is the character `c' because then `c' can be used to switch back and
3967 forth between agenda and calendar."
3971 (defcustom org-calendar-insert-diary-entry-key
[?i
]
3972 "The key to be installed in `calendar-mode-map' for adding diary entries.
3973 This option is irrelevant until `org-agenda-diary-file' has been configured
3974 to point to an Org file. When that is the case, the command
3975 `org-agenda-diary-entry' will be bound to the key given here, by default
3976 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3977 if you want to continue doing this, you need to change this to a different
3982 (defcustom org-agenda-diary-file
'diary-file
3983 "File to which to add new entries with the `i' key in agenda and calendar.
3984 When this is the symbol `diary-file', the functionality in the Emacs
3985 calendar will be used to add entries to the `diary-file'. But when this
3986 points to a file, `org-agenda-diary-entry' will be used instead."
3989 (const :tag
"The standard Emacs diary file" diary-file
)
3990 (file :tag
"Special Org file diary entries")))
3992 (eval-after-load "calendar"
3994 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3995 'org-calendar-goto-agenda
)
3996 (add-hook 'calendar-mode-hook
3998 (unless (eq org-agenda-diary-file
'diary-file
)
3999 (define-key calendar-mode-map
4000 org-calendar-insert-diary-entry-key
4001 'org-agenda-diary-entry
))))))
4003 (defgroup org-latex nil
4004 "Options for embedding LaTeX code into Org mode."
4008 (defcustom org-format-latex-options
4009 '(:foreground default
:background default
:scale
1.0
4010 :html-foreground
"Black" :html-background
"Transparent"
4011 :html-scale
1.0 :matchers
("begin" "$1" "$" "$$" "\\(" "\\["))
4012 "Options for creating images from LaTeX fragments.
4013 This is a property list with the following properties:
4014 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
4015 `default' means use the foreground of the default face.
4016 `auto' means use the foreground from the text face.
4017 :background the background color, or \"Transparent\".
4018 `default' means use the background of the default face.
4019 `auto' means use the background from the text face.
4020 :scale a scaling factor for the size of the images, to get more pixels
4021 :html-foreground, :html-background, :html-scale
4022 the same numbers for HTML export.
4023 :matchers a list indicating which matchers should be used to
4024 find LaTeX fragments. Valid members of this list are:
4025 \"begin\" find environments
4026 \"$1\" find single characters surrounded by $.$
4027 \"$\" find math expressions surrounded by $...$
4028 \"$$\" find math expressions surrounded by $$....$$
4029 \"\\(\" find math expressions surrounded by \\(...\\)
4030 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4034 (defcustom org-format-latex-signal-error t
4035 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4036 When nil, just push out a message."
4041 (defcustom org-latex-to-mathml-jar-file nil
4042 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4043 Use this to specify additional executable file say a jar file.
4045 When using MathToWeb as the converter, specify the full-path to
4046 your mathtoweb.jar file."
4050 (const :tag
"None" nil
)
4051 (file :tag
"JAR file" :must-match t
)))
4053 (defcustom org-latex-to-mathml-convert-command nil
4054 "Command to convert LaTeX fragments to MathML.
4055 Replace format-specifiers in the command as noted below and use
4056 `shell-command' to convert LaTeX to MathML.
4057 %j: Executable file in fully expanded form as specified by
4058 `org-latex-to-mathml-jar-file'.
4059 %I: Input LaTeX file in fully expanded form.
4060 %i: The latex fragment to be converted.
4061 %o: Output MathML file.
4063 This command is used by `org-create-math-formula'.
4065 When using MathToWeb as the converter, set this option to
4066 \"java -jar %j -unicode -force -df %o %I\".
4068 When using LaTeXML set this option to
4069 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4073 (const :tag
"None" nil
)
4074 (string :tag
"\nShell command")))
4076 (defcustom org-preview-latex-default-process
'dvipng
4077 "The default process to convert LaTeX fragments to image files.
4078 All available processes and theirs documents can be found in
4079 `org-preview-latex-process-alist', which see."
4082 :package-version
'(Org .
"9.0")
4085 (defcustom org-preview-latex-process-alist
4087 :programs
("latex" "dvipng")
4088 :description
"dvi > png"
4089 :message
"you need to install the programs: latex and dvipng."
4090 :image-input-type
"dvi"
4091 :image-output-type
"png"
4092 :image-size-adjust
(1.0 .
1.0)
4093 :latex-compiler
("latex -interaction nonstopmode -output-directory %o %f")
4094 :image-converter
("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
4096 :programs
("latex" "dvisvgm")
4097 :description
"dvi > svg"
4098 :message
"you need to install the programs: latex and dvisvgm."
4100 :image-input-type
"dvi"
4101 :image-output-type
"svg"
4102 :image-size-adjust
(1.7 .
1.5)
4103 :latex-compiler
("latex -interaction nonstopmode -output-directory %o %f")
4104 :image-converter
("dvisvgm %f -n -b min -c %S -o %O"))
4106 :programs
("latex" "convert")
4107 :description
"pdf > png"
4108 :message
"you need to install the programs: latex and imagemagick."
4110 :image-input-type
"pdf"
4111 :image-output-type
"png"
4112 :image-size-adjust
(1.0 .
1.0)
4113 :latex-compiler
("pdflatex -interaction nonstopmode -output-directory %o %f")
4115 ("convert -density %D -trim -antialias %f -quality 100 %O")))
4116 "Definitions of external processes for LaTeX previewing.
4117 Org mode can use some external commands to generate TeX snippet's images for
4118 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4119 `org-create-formula-image' how to call them.
4121 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4122 PROPERTIES accepts the following attributes:
4124 :programs list of strings, required programs.
4125 :description string, describe the process.
4126 :message string, message it when required programs cannot be found.
4127 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4128 :image-output-type string, output file type of image converter (e.g., \"png\").
4129 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4130 deal with background and foreground color of image.
4131 Otherwise, dvipng style background and foregroud color
4132 format are generated. You may then refer to them in
4133 command options with \"%F\" and \"%B\".
4134 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4135 image size showed in buffer and the cdr element is for
4136 HTML file. This option is only useful for process
4137 developers, users should use variable
4138 `org-format-latex-options' instead.
4139 :post-clean list of strings, files matched are to be cleaned up once
4140 the image is generated. When nil, the files with \".dvi\",
4141 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4142 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4144 :latex-header list of strings, the LaTeX header of the snippet file.
4145 When nil, the fallback value is used instead, which is
4146 controlled by `org-format-latex-header',
4147 `org-latex-default-packages-alist' and
4148 `org-latex-packages-alist', which see.
4149 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4150 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4151 replaced with values defined below.
4152 :image-converter list of image converter commands strings. Each of them is
4153 given to the shell and supports any of the following
4154 place-holders defined below.
4156 Place-holders used by `:image-converter' and `:latex-compiler':
4159 %b base name of input file
4160 %o base directory of input file
4161 %O absolute output file name
4163 Place-holders only used by `:image-converter':
4165 %F foreground of image
4166 %B background of image
4167 %D dpi, which is used to adjust image size by some processing commands.
4168 %S the image size scale ratio, which is used to adjust image size by some
4169 processing commands."
4172 :package-version
'(Org .
"9.0")
4173 :type
'(alist :tag
"LaTeX to image backends"
4174 :value-type
(plist)))
4176 (defcustom org-preview-latex-image-directory
"ltximg/"
4177 "Path to store latex preview images.
4178 A relative path here creates many directories relative to the
4179 processed org files paths. An absolute path puts all preview
4180 images at the same place."
4183 :package-version
'(Org .
"9.0")
4186 (defun org-format-latex-mathml-available-p ()
4187 "Return t if `org-latex-to-mathml-convert-command' is usable."
4189 (when (and (boundp 'org-latex-to-mathml-convert-command
)
4190 org-latex-to-mathml-convert-command
)
4191 (let ((executable (car (split-string
4192 org-latex-to-mathml-convert-command
))))
4193 (when (executable-find executable
)
4195 "%j" org-latex-to-mathml-convert-command
)
4196 (file-readable-p org-latex-to-mathml-jar-file
)
4199 (defcustom org-format-latex-header
"\\documentclass{article}
4200 \\usepackage[usenames]{color}
4203 \\pagestyle{empty} % do not remove
4204 % The settings below are copied from fullpage.sty
4205 \\setlength{\\textwidth}{\\paperwidth}
4206 \\addtolength{\\textwidth}{-3cm}
4207 \\setlength{\\oddsidemargin}{1.5cm}
4208 \\addtolength{\\oddsidemargin}{-2.54cm}
4209 \\setlength{\\evensidemargin}{\\oddsidemargin}
4210 \\setlength{\\textheight}{\\paperheight}
4211 \\addtolength{\\textheight}{-\\headheight}
4212 \\addtolength{\\textheight}{-\\headsep}
4213 \\addtolength{\\textheight}{-\\footskip}
4214 \\addtolength{\\textheight}{-3cm}
4215 \\setlength{\\topmargin}{1.5cm}
4216 \\addtolength{\\topmargin}{-2.54cm}"
4217 "The document header used for processing LaTeX fragments.
4218 It is imperative that this header make sure that no page number
4219 appears on the page. The package defined in the variables
4220 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4221 will either replace the placeholder \"[PACKAGES]\" in this
4222 header, or they will be appended."
4226 (defun org-set-packages-alist (var val
)
4227 "Set the packages alist and make sure it has 3 elements per entry."
4228 (set var
(mapcar (lambda (x)
4229 (if (and (consp x
) (= (length x
) 2))
4230 (list (car x
) (nth 1 x
) t
)
4234 (defun org-get-packages-alist (var)
4235 "Get the packages alist and make sure it has 3 elements per entry."
4237 (if (and (consp x
) (= (length x
) 2))
4238 (list (car x
) (nth 1 x
) t
)
4240 (default-value var
)))
4242 (defcustom org-latex-default-packages-alist
4243 '(("AUTO" "inputenc" t
("pdflatex"))
4244 ("T1" "fontenc" t
("pdflatex"))
4247 ("" "longtable" nil
)
4250 ("normalem" "ulem" t
)
4255 ("" "hyperref" nil
))
4256 "Alist of default packages to be inserted in the header.
4258 Change this only if one of the packages here causes an
4259 incompatibility with another package you are using.
4261 The packages in this list are needed by one part or another of
4262 Org mode to function properly:
4264 - inputenc, fontenc: for basic font and character selection
4265 - graphicx: for including images
4266 - grffile: allow periods and spaces in graphics file names
4267 - longtable: For multipage tables
4268 - wrapfig: for figure placement
4269 - rotating: for sideways figures and tables
4270 - ulem: for underline and strike-through
4271 - amsmath: for subscript and superscript and math environments
4272 - textcomp, amssymb: for various symbols used
4273 for interpreting the entities in `org-entities'. You can skip
4274 some of these packages if you don't use any of their symbols.
4275 - capt-of: for captions outside of floats
4276 - hyperref: for cross references
4278 Therefore you should not modify this variable unless you know
4279 what you are doing. The one reason to change it anyway is that
4280 you might be loading some other package that conflicts with one
4281 of the default packages. Each element is either a cell or
4284 A cell is of the format
4286 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4288 If SNIPPET-FLAG is non-nil, the package also needs to be included
4289 when compiling LaTeX snippets into images for inclusion into
4290 non-LaTeX output. COMPILERS is a list of compilers that should
4291 include the package, see `org-latex-compiler'. If the document
4292 compiler is not in the list, and the list is non-nil, the package
4293 will not be inserted in the final document.
4295 A string will be inserted as-is in the header of the document."
4297 :group
'org-export-latex
4298 :set
'org-set-packages-alist
4299 :get
'org-get-packages-alist
4301 :package-version
'(Org .
"8.3")
4304 (list :tag
"options/package pair"
4305 (string :tag
"options")
4306 (string :tag
"package")
4307 (boolean :tag
"Snippet"))
4308 (string :tag
"A line of LaTeX"))))
4310 (defcustom org-latex-packages-alist nil
4311 "Alist of packages to be inserted in every LaTeX header.
4313 These will be inserted after `org-latex-default-packages-alist'.
4314 Each element is either a cell or a string.
4316 A cell is of the format:
4318 (\"options\" \"package\" SNIPPET-FLAG)
4320 SNIPPET-FLAG, when non-nil, indicates that this package is also
4321 needed when turning LaTeX snippets into images for inclusion into
4324 A string will be inserted as-is in the header of the document.
4326 Make sure that you only list packages here which:
4328 - you want in every file;
4329 - do not conflict with the setup in `org-format-latex-header';
4330 - do not conflict with the default packages in
4331 `org-latex-default-packages-alist'."
4333 :group
'org-export-latex
4334 :set
'org-set-packages-alist
4335 :get
'org-get-packages-alist
4338 (list :tag
"options/package pair"
4339 (string :tag
"options")
4340 (string :tag
"package")
4341 (boolean :tag
"Snippet"))
4342 (string :tag
"A line of LaTeX"))))
4344 (defgroup org-appearance nil
4345 "Settings for Org mode appearance."
4346 :tag
"Org Appearance"
4349 (defcustom org-level-color-stars-only nil
4350 "Non-nil means fontify only the stars in each headline.
4351 When nil, the entire headline is fontified.
4352 Changing it requires restart of `font-lock-mode' to become effective
4353 also in regions already fontified."
4354 :group
'org-appearance
4357 (defcustom org-hide-leading-stars nil
4358 "Non-nil means hide the first N-1 stars in a headline.
4359 This works by using the face `org-hide' for these stars. This
4360 face is white for a light background, and black for a dark
4361 background. You may have to customize the face `org-hide' to
4363 Changing it requires restart of `font-lock-mode' to become effective
4364 also in regions already fontified.
4365 You may also set this on a per-file basis by adding one of the following
4366 lines to the buffer:
4368 #+STARTUP: hidestars
4369 #+STARTUP: showstars"
4370 :group
'org-appearance
4373 (defcustom org-hidden-keywords nil
4374 "List of symbols corresponding to keywords to be hidden the org buffer.
4375 For example, a value \\='(title) for this list will make the document's title
4376 appear in the buffer without the initial #+TITLE: keyword."
4377 :group
'org-appearance
4379 :type
'(set (const :tag
"#+AUTHOR" author
)
4380 (const :tag
"#+DATE" date
)
4381 (const :tag
"#+EMAIL" email
)
4382 (const :tag
"#+TITLE" title
)))
4384 (defcustom org-custom-properties nil
4385 "List of properties (as strings) with a special meaning.
4386 The default use of these custom properties is to let the user
4387 hide them with `org-toggle-custom-properties-visibility'."
4388 :group
'org-properties
4389 :group
'org-appearance
4391 :type
'(repeat (string :tag
"Property Name")))
4393 (defcustom org-fontify-done-headline nil
4394 "Non-nil means change the face of a headline if it is marked DONE.
4395 Normally, only the TODO/DONE keyword indicates the state of a headline.
4396 When this is non-nil, the headline after the keyword is set to the
4397 `org-headline-done' as an additional indication."
4398 :group
'org-appearance
4401 (defcustom org-fontify-emphasized-text t
4402 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4403 Changing this variable requires a restart of Emacs to take effect."
4404 :group
'org-appearance
4407 (defcustom org-fontify-whole-heading-line nil
4408 "Non-nil means fontify the whole line for headings.
4409 This is useful when setting a background color for the
4411 :group
'org-appearance
4414 (defcustom org-highlight-latex-and-related nil
4415 "Non-nil means highlight LaTeX related syntax in the buffer.
4416 When non nil, the value should be a list containing any of the
4418 `latex' Highlight LaTeX snippets and environments.
4419 `script' Highlight subscript and superscript.
4420 `entities' Highlight entities."
4421 :group
'org-appearance
4423 :package-version
'(Org .
"8.0")
4425 (const :tag
"No highlighting" nil
)
4426 (set :greedy t
:tag
"Highlight"
4427 (const :tag
"LaTeX snippets and environments" latex
)
4428 (const :tag
"Subscript and superscript" script
)
4429 (const :tag
"Entities" entities
))))
4431 (defcustom org-hide-emphasis-markers nil
4432 "Non-nil mean font-lock should hide the emphasis marker characters."
4433 :group
'org-appearance
4436 (defcustom org-hide-macro-markers nil
4437 "Non-nil mean font-lock should hide the brackets marking macro calls."
4438 :group
'org-appearance
4441 (defcustom org-pretty-entities nil
4442 "Non-nil means show entities as UTF8 characters.
4443 When nil, the \\name form remains in the buffer."
4444 :group
'org-appearance
4448 (defcustom org-pretty-entities-include-sub-superscripts t
4449 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4450 :group
'org-appearance
4454 (defvar org-emph-re nil
4455 "Regular expression for matching emphasis.
4456 After a match, the match groups contain these elements:
4457 0 The match of the full regular expression, including the characters
4458 before and after the proper match
4459 1 The character before the proper match, or empty at beginning of line
4460 2 The proper match, including the leading and trailing markers
4461 3 The leading marker like * or /, indicating the type of highlighting
4462 4 The text between the emphasis markers, not including the markers
4463 5 The character after the match, empty at the end of a line")
4465 (defvar org-verbatim-re nil
4466 "Regular expression for matching verbatim text.")
4468 (defvar org-emphasis-regexp-components
) ; defined just below
4469 (defvar org-emphasis-alist
) ; defined just below
4470 (defun org-set-emph-re (var val
)
4471 "Set variable and compute the emphasis regular expression."
4473 (when (and (boundp 'org-emphasis-alist
)
4474 (boundp 'org-emphasis-regexp-components
)
4475 org-emphasis-alist org-emphasis-regexp-components
)
4477 ((`(,pre
,post
,border
,body
,nl
) org-emphasis-regexp-components
)
4478 (body (if (<= nl
0) body
4479 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl
)))
4481 (format (concat "\\([%s]\\|^\\)" ;before markers
4482 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4483 "\\([%s]\\|$\\)") ;after markers
4484 pre border border body border post
)))
4485 (setq org-emph-re
(format template
"*/_+"))
4486 (setq org-verbatim-re
(format template
"=~")))))
4488 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4489 ;; set this option proved cumbersome. See this message/thread:
4490 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4491 (defvar org-emphasis-regexp-components
4492 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4493 "Components used to build the regular expression for emphasis.
4494 This is a list with five entries. Terminology: In an emphasis string
4495 like \" *strong word* \", we call the initial space PREMATCH, the final
4496 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4497 and \"trong wor\" is the body. The different components in this variable
4498 specify what is allowed/forbidden in each part:
4500 pre Chars allowed as prematch. Beginning of line will be allowed too.
4501 post Chars allowed as postmatch. End of line will be allowed too.
4502 border The chars *forbidden* as border characters.
4503 body-regexp A regexp like \".\" to match a body character. Don't use
4504 non-shy groups here, and don't allow newline here.
4505 newline The maximum number of newlines allowed in an emphasis exp.
4507 You need to reload Org or to restart Emacs after customizing this.")
4509 (defcustom org-emphasis-alist
4513 ("=" org-verbatim verbatim
)
4514 ("~" org-code verbatim
)
4515 ("+" (:strike-through t
)))
4516 "Alist of characters and faces to emphasize text.
4517 Text starting and ending with a special character will be emphasized,
4518 for example *bold*, _underlined_ and /italic/. This variable sets the
4519 marker characters and the face to be used by font-lock for highlighting
4522 You need to reload Org or to restart Emacs after customizing this."
4523 :group
'org-appearance
4524 :set
'org-set-emph-re
4526 :package-version
'(Org .
"8.0")
4529 (string :tag
"Marker character")
4531 (face :tag
"Font-lock-face")
4532 (plist :tag
"Face property list"))
4533 (option (const verbatim
)))))
4535 (defvar org-protecting-blocks
'("src" "example" "export")
4536 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4537 This is needed for font-lock setup.")
4539 ;;; Functions and variables from their packages
4540 ;; Declared here to avoid compiler warnings
4541 (defvar mark-active
)
4544 (declare-function calc-eval
"calc" (str &optional separator
&rest args
))
4545 (declare-function calendar-forward-day
"cal-move" (arg))
4546 (declare-function calendar-goto-date
"cal-move" (date))
4547 (declare-function calendar-goto-today
"cal-move" ())
4548 (declare-function calendar-iso-from-absolute
"cal-iso" (date))
4549 (declare-function calendar-iso-to-absolute
"cal-iso" (date))
4550 (declare-function cdlatex-compute-tables
"ext:cdlatex" ())
4551 (declare-function cdlatex-tab
"ext:cdlatex" ())
4552 (declare-function dired-get-filename
4554 (&optional localp no-error-if-not-filep
))
4555 (declare-function iswitchb-read-buffer
4558 default require-match _predicate start matches-set
))
4559 (declare-function org-agenda-change-all-lines
4561 (newhead hdmarker
&optional fixface just-this
))
4562 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4565 (declare-function org-agenda-copy-local-variable
"org-agenda" (var))
4566 (declare-function org-agenda-format-item
4568 (extra txt
&optional level category tags dotime
4570 (declare-function org-agenda-maybe-redo
"org-agenda" ())
4571 (declare-function org-agenda-new-marker
"org-agenda" (&optional pos
))
4572 (declare-function org-agenda-save-markers-for-cut-and-paste
4575 (declare-function org-agenda-set-restriction-lock
"org-agenda" (&optional type
))
4576 (declare-function org-agenda-skip
"org-agenda" ())
4577 (declare-function org-attach-reveal
"org-attach" (&optional if-exists
))
4578 (declare-function org-gnus-follow-link
"org-gnus" (&optional group article
))
4579 (declare-function org-indent-mode
"org-indent" (&optional arg
))
4580 (declare-function org-inlinetask-goto-beginning
"org-inlinetask" ())
4581 (declare-function org-inlinetask-goto-end
"org-inlinetask" ())
4582 (declare-function org-inlinetask-in-task-p
"org-inlinetask" ())
4583 (declare-function org-inlinetask-remove-END-maybe
"org-inlinetask" ())
4584 (declare-function orgtbl-send-table
"org-table" (&optional maybe
))
4585 (declare-function parse-time-string
"parse-time" (string))
4586 (declare-function speedbar-line-directory
"speedbar" (&optional depth
))
4588 (defvar align-mode-rules-list
)
4589 (defvar calc-embedded-close-formula
)
4590 (defvar calc-embedded-open-formula
)
4591 (defvar calc-embedded-open-mode
)
4592 (defvar font-lock-unfontify-region-function
)
4593 (defvar iswitchb-temp-buflist
)
4594 (defvar org-agenda-tags-todo-honor-ignore-options
)
4595 (defvar remember-data-file
)
4596 (defvar texmathp-why
)
4599 (defun turn-on-orgtbl ()
4600 "Unconditionally turn on `orgtbl-mode'."
4601 (require 'org-table
)
4604 (defun org-at-table-p (&optional table-type
)
4605 "Non-nil if the cursor is inside an Org table.
4606 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4607 If `org-enable-table-editor' is nil, return nil unconditionally."
4609 org-enable-table-editor
4612 (looking-at-p (if table-type
"[ \t]*[|+]" "[ \t]*|")))
4613 (or (not (derived-mode-p 'org-mode
))
4614 (let ((e (org-element-lineage (org-element-at-point) '(table) t
)))
4615 (and e
(or table-type
(eq (org-element-property :type e
) 'org
)))))))
4617 (defun org-at-table.el-p
()
4618 "Non-nil when point is at a table.el table."
4619 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4620 (let ((element (org-element-at-point)))
4621 (and (eq (org-element-type element
) 'table
)
4622 (eq (org-element-property :type element
) 'table.el
)))))
4624 (defun org-at-table-hline-p ()
4625 "Non-nil when point is inside a hline in a table.
4626 Assume point is already in a table. If `org-enable-table-editor'
4627 is nil, return nil unconditionally."
4628 (and org-enable-table-editor
4631 (looking-at org-table-hline-regexp
))))
4633 (defun org-table-map-tables (function &optional quietly
)
4634 "Apply FUNCTION to the start of all tables in the buffer."
4635 (org-with-wide-buffer
4636 (goto-char (point-min))
4637 (while (re-search-forward org-table-any-line-regexp nil t
)
4639 (message "Mapping tables: %d%%"
4640 (floor (* 100.0 (point)) (buffer-size))))
4641 (beginning-of-line 1)
4642 (when (and (looking-at org-table-line-regexp
)
4643 ;; Exclude tables in src/example/verbatim/clocktable blocks
4644 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4645 (save-excursion (funcall function
))
4646 (or (looking-at org-table-line-regexp
)
4648 (re-search-forward org-table-any-border-regexp nil
1)))
4649 (unless quietly
(message "Mapping tables: done")))
4651 (declare-function org-clock-save-markers-for-cut-and-paste
"org-clock" (beg end
))
4652 (declare-function org-clock-update-mode-line
"org-clock" ())
4653 (declare-function org-resolve-clocks
"org-clock"
4654 (&optional also-non-dangling-p prompt last-valid
))
4656 (defun org-at-TBLFM-p (&optional pos
)
4657 "Non-nil when point (or POS) is in #+TBLFM line."
4659 (goto-char (or pos
(point)))
4661 (and (let ((case-fold-search t
)) (looking-at org-TBLFM-regexp
))
4662 (eq (org-element-type (org-element-at-point)) 'table
))))
4664 (defvar org-clock-start-time
)
4665 (defvar org-clock-marker
(make-marker)
4666 "Marker recording the last clock-in.")
4667 (defvar org-clock-hd-marker
(make-marker)
4668 "Marker recording the last clock-in, but the headline position.")
4669 (defvar org-clock-heading
""
4670 "The heading of the current clock entry.")
4671 (defun org-clock-is-active ()
4672 "Return the buffer where the clock is currently running.
4673 Return nil if no clock is running."
4674 (marker-buffer org-clock-marker
))
4676 (defun org-check-running-clock ()
4677 "Check if the current buffer contains the running clock.
4678 If yes, offer to stop it and to save the buffer with the changes."
4679 (when (and (equal (marker-buffer org-clock-marker
) (current-buffer))
4680 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4683 (when (y-or-n-p "Save changed buffer?")
4686 (defun org-clocktable-try-shift (dir n
)
4687 "Check if this line starts a clock table, if yes, shift the time block."
4688 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4689 (org-clocktable-shift dir n
)))
4692 (defun org-clock-persistence-insinuate ()
4693 "Set up hooks for clock persistence."
4694 (require 'org-clock
)
4695 (add-hook 'org-mode-hook
'org-clock-load
)
4696 (add-hook 'kill-emacs-hook
'org-clock-save
))
4698 (defgroup org-archive nil
4699 "Options concerning archiving in Org mode."
4701 :group
'org-structure
)
4703 (defcustom org-archive-location
"%s_archive::"
4704 "The location where subtrees should be archived.
4706 The value of this variable is a string, consisting of two parts,
4707 separated by a double-colon. The first part is a filename and
4708 the second part is a headline.
4710 When the filename is omitted, archiving happens in the same file.
4711 %s in the filename will be replaced by the current file
4712 name (without the directory part). Archiving to a different file
4713 is useful to keep archived entries from contributing to the
4716 The archived entries will be filed as subtrees of the specified
4717 headline. When the headline is omitted, the subtrees are simply
4718 filed away at the end of the file, as top-level entries. Also in
4719 the heading you can use %s to represent the file name, this can be
4720 useful when using the same archive for a number of different files.
4722 Here are a few examples:
4724 If the current file is Projects.org, archive in file
4725 Projects.org_archive, as top-level trees. This is the default.
4727 \"::* Archived Tasks\"
4728 Archive in the current file, under the top-level headline
4729 \"* Archived Tasks\".
4731 \"~/org/archive.org::\"
4732 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4734 \"~/org/archive.org::* From %s\"
4735 Archive in file ~/org/archive.org (absolute path), under headlines
4736 \"From FILENAME\" where file name is the current file name.
4738 \"~/org/datetree.org::datetree/* Finished Tasks\"
4739 The \"datetree/\" string is special, signifying to archive
4740 items to the datetree. Items are placed in either the CLOSED
4741 date of the item, or the current date if there is no CLOSED date.
4742 The heading will be a subentry to the current date. There doesn't
4743 need to be a heading, but there always needs to be a slash after
4744 datetree. For example, to store archived items directly in the
4745 datetree, use \"~/org/datetree.org::datetree/\".
4747 \"basement::** Finished Tasks\"
4748 Archive in file ./basement (relative path), as level 3 trees
4749 below the level 2 heading \"** Finished Tasks\".
4751 You may set this option on a per-file basis by adding to the buffer a
4754 #+ARCHIVE: basement::** Finished Tasks
4756 You may also define it locally for a subtree by setting an ARCHIVE property
4757 in the entry. If such a property is found in an entry, or anywhere up
4758 the hierarchy, it will be used."
4762 (defcustom org-agenda-skip-archived-trees t
4763 "Non-nil means the agenda will skip any items located in archived trees.
4764 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4765 variable is no longer recommended, you should leave it at the value t.
4766 Instead, use the key `v' to cycle the archives-mode in the agenda."
4768 :group
'org-agenda-skip
4771 (defcustom org-columns-skip-archived-trees t
4772 "Non-nil means ignore archived trees when creating column view."
4774 :group
'org-properties
4777 (defcustom org-cycle-open-archived-trees nil
4778 "Non-nil means `org-cycle' will open archived trees.
4779 An archived tree is a tree marked with the tag ARCHIVE.
4780 When nil, archived trees will stay folded. You can still open them with
4781 normal outline commands like `show-all', but not with the cycling commands."
4786 (defcustom org-sparse-tree-open-archived-trees nil
4787 "Non-nil means sparse tree construction shows matches in archived trees.
4788 When nil, matches in these trees are highlighted, but the trees are kept in
4791 :group
'org-sparse-trees
4794 (defcustom org-sparse-tree-default-date-type nil
4795 "The default date type when building a sparse tree.
4796 When this is nil, a date is a scheduled or a deadline timestamp.
4797 Otherwise, these types are allowed:
4800 active: only active timestamps (<...>)
4801 inactive: only inactive timestamps ([...])
4802 scheduled: only scheduled timestamps
4803 deadline: only deadline timestamps"
4804 :type
'(choice (const :tag
"Scheduled or deadline" nil
)
4805 (const :tag
"All timestamps" all
)
4806 (const :tag
"Only active timestamps" active
)
4807 (const :tag
"Only inactive timestamps" inactive
)
4808 (const :tag
"Only scheduled timestamps" scheduled
)
4809 (const :tag
"Only deadline timestamps" deadline
)
4810 (const :tag
"Only closed timestamps" closed
))
4812 :package-version
'(Org .
"8.3")
4813 :group
'org-sparse-trees
)
4815 (defun org-cycle-hide-archived-subtrees (state)
4816 "Re-hide all archived subtrees after a visibility state change."
4817 (when (and (not org-cycle-open-archived-trees
)
4818 (not (memq state
'(overview folded
))))
4820 (let* ((globalp (memq state
'(contents all
)))
4821 (beg (if globalp
(point-min) (point)))
4822 (end (if globalp
(point-max) (org-end-of-subtree t
))))
4823 (org-hide-archived-subtrees beg end
)
4825 (when (looking-at-p (concat ".*:" org-archive-tag
":"))
4826 (message "%s" (substitute-command-keys
4827 "Subtree is archived and stays closed. Use \
4828 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4830 (defun org-force-cycle-archived ()
4831 "Cycle subtree even if it is archived."
4833 (setq this-command
'org-cycle
)
4834 (let ((org-cycle-open-archived-trees t
))
4835 (call-interactively 'org-cycle
)))
4837 (defun org-hide-archived-subtrees (beg end
)
4838 "Re-hide all archived subtrees after a visibility state change."
4839 (org-with-wide-buffer
4840 (let ((case-fold-search nil
)
4841 (re (concat org-outline-regexp-bol
".*:" org-archive-tag
":")))
4843 ;; Include headline point is currently on.
4845 (while (and (< (point) end
) (re-search-forward re end t
))
4846 (when (member org-archive-tag
(org-get-tags))
4847 (org-flag-subtree t
)
4848 (org-end-of-subtree t
))))))
4850 (declare-function outline-end-of-heading
"outline" ())
4851 (declare-function outline-flag-region
"outline" (from to flag
))
4852 (defun org-flag-subtree (flag)
4854 (org-back-to-heading t
)
4855 (outline-end-of-heading)
4856 (outline-flag-region (point)
4857 (progn (org-end-of-subtree t
) (point))
4860 (defalias 'org-advertized-archive-subtree
'org-archive-subtree
)
4862 ;; Declare Column View Code
4864 (declare-function org-columns-get-format-and-top-level
"org-colview" ())
4865 (declare-function org-columns-compute
"org-colview" (property))
4869 (declare-function org-id-store-link
"org-id")
4870 (declare-function org-id-locations-load
"org-id")
4871 (declare-function org-id-locations-save
"org-id")
4872 (defvar org-id-track-globally
)
4874 ;;; Variables for pre-computed regular expressions, all buffer local
4876 (defvar-local org-todo-regexp nil
4877 "Matches any of the TODO state keywords.
4878 Since TODO keywords are case-sensitive, `case-fold-search' is
4879 expected to be bound to nil when matching against this regexp.")
4881 (defvar-local org-not-done-regexp nil
4882 "Matches any of the TODO state keywords except the last one.
4883 Since TODO keywords are case-sensitive, `case-fold-search' is
4884 expected to be bound to nil when matching against this regexp.")
4886 (defvar-local org-not-done-heading-regexp nil
4887 "Matches a TODO headline that is not done.
4888 Since TODO keywords are case-sensitive, `case-fold-search' is
4889 expected to be bound to nil when matching against this regexp.")
4891 (defvar-local org-todo-line-regexp nil
4892 "Matches a headline and puts TODO state into group 2 if present.
4893 Since TODO keywords are case-sensitive, `case-fold-search' is
4894 expected to be bound to nil when matching against this regexp.")
4896 (defvar-local org-complex-heading-regexp nil
4897 "Matches a headline and puts everything into groups:
4900 group 2: The TODO keyword, maybe
4901 group 3: Priority cookie
4902 group 4: True headline
4905 Since TODO keywords are case-sensitive, `case-fold-search' is
4906 expected to be bound to nil when matching against this regexp.")
4908 (defvar-local org-complex-heading-regexp-format nil
4909 "Printf format to make regexp to match an exact headline.
4910 This regexp will match the headline of any node which has the
4911 exact headline text that is put into the format, but may have any
4912 TODO state, priority and tags.")
4914 (defvar-local org-todo-line-tags-regexp nil
4915 "Matches a headline and puts TODO state into group 2 if present.
4916 Also put tags into group 4 if tags are present.")
4918 (defconst org-plain-time-of-day-regexp
4921 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4924 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4926 "Regular expression to match a plain time or time range.
4927 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4928 groups carry important information:
4930 1 the first time, range or not
4931 8 the second time, if it is a range.")
4933 (defconst org-plain-time-extension-regexp
4936 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4937 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4938 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4939 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4940 groups carry important information:
4943 9 minutes of duration")
4945 (defconst org-stamp-time-of-day-regexp
4947 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4948 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4950 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4951 "Regular expression to match a timestamp time or time range.
4952 After a match, the following groups carry important information:
4954 1 date plus weekday, for back referencing to make sure both times are on the same day
4955 2 the first time, range or not
4956 4 the second time, if it is a range.")
4958 (defconst org-startup-options
4959 '(("fold" org-startup-folded t
)
4960 ("overview" org-startup-folded t
)
4961 ("nofold" org-startup-folded nil
)
4962 ("showall" org-startup-folded nil
)
4963 ("showeverything" org-startup-folded showeverything
)
4964 ("content" org-startup-folded content
)
4965 ("indent" org-startup-indented t
)
4966 ("noindent" org-startup-indented nil
)
4967 ("hidestars" org-hide-leading-stars t
)
4968 ("showstars" org-hide-leading-stars nil
)
4969 ("odd" org-odd-levels-only t
)
4970 ("oddeven" org-odd-levels-only nil
)
4971 ("align" org-startup-align-all-tables t
)
4972 ("noalign" org-startup-align-all-tables nil
)
4973 ("inlineimages" org-startup-with-inline-images t
)
4974 ("noinlineimages" org-startup-with-inline-images nil
)
4975 ("latexpreview" org-startup-with-latex-preview t
)
4976 ("nolatexpreview" org-startup-with-latex-preview nil
)
4977 ("customtime" org-display-custom-times t
)
4978 ("logdone" org-log-done time
)
4979 ("lognotedone" org-log-done note
)
4980 ("nologdone" org-log-done nil
)
4981 ("lognoteclock-out" org-log-note-clock-out t
)
4982 ("nolognoteclock-out" org-log-note-clock-out nil
)
4983 ("logrepeat" org-log-repeat state
)
4984 ("lognoterepeat" org-log-repeat note
)
4985 ("logdrawer" org-log-into-drawer t
)
4986 ("nologdrawer" org-log-into-drawer nil
)
4987 ("logstatesreversed" org-log-states-order-reversed t
)
4988 ("nologstatesreversed" org-log-states-order-reversed nil
)
4989 ("nologrepeat" org-log-repeat nil
)
4990 ("logreschedule" org-log-reschedule time
)
4991 ("lognotereschedule" org-log-reschedule note
)
4992 ("nologreschedule" org-log-reschedule nil
)
4993 ("logredeadline" org-log-redeadline time
)
4994 ("lognoteredeadline" org-log-redeadline note
)
4995 ("nologredeadline" org-log-redeadline nil
)
4996 ("logrefile" org-log-refile time
)
4997 ("lognoterefile" org-log-refile note
)
4998 ("nologrefile" org-log-refile nil
)
4999 ("fninline" org-footnote-define-inline t
)
5000 ("nofninline" org-footnote-define-inline nil
)
5001 ("fnlocal" org-footnote-section nil
)
5002 ("fnauto" org-footnote-auto-label t
)
5003 ("fnprompt" org-footnote-auto-label nil
)
5004 ("fnconfirm" org-footnote-auto-label confirm
)
5005 ("fnplain" org-footnote-auto-label plain
)
5006 ("fnadjust" org-footnote-auto-adjust t
)
5007 ("nofnadjust" org-footnote-auto-adjust nil
)
5008 ("constcgs" constants-unit-system cgs
)
5009 ("constSI" constants-unit-system SI
)
5010 ("noptag" org-tag-persistent-alist nil
)
5011 ("hideblocks" org-hide-block-startup t
)
5012 ("nohideblocks" org-hide-block-startup nil
)
5013 ("beamer" org-startup-with-beamer-mode t
)
5014 ("entitiespretty" org-pretty-entities t
)
5015 ("entitiesplain" org-pretty-entities nil
))
5016 "Variable associated with STARTUP options for org-mode.
5017 Each element is a list of three items: the startup options (as written
5018 in the #+STARTUP line), the corresponding variable, and the value to set
5019 this variable to if the option is found. An optional forth element PUSH
5020 means to push this value onto the list in the variable.")
5022 (defcustom org-group-tags t
5023 "When non-nil (the default), use group tags.
5024 This can be turned on/off through `org-toggle-tags-groups'."
5029 (defvar org-inhibit-startup nil
) ; Dynamically-scoped param.
5031 (defun org-toggle-tags-groups ()
5032 "Toggle support for group tags.
5033 Support for group tags is controlled by the option
5034 `org-group-tags', which is non-nil by default."
5036 (setq org-group-tags
(not org-group-tags
))
5037 (cond ((and (derived-mode-p 'org-agenda-mode
)
5040 ((derived-mode-p 'org-mode
)
5041 (let ((org-inhibit-startup t
)) (org-mode))))
5042 (message "Groups tags support has been turned %s"
5043 (if org-group-tags
"on" "off")))
5045 (defun org-set-regexps-and-options (&optional tags-only
)
5046 "Precompute regular expressions used in the current buffer.
5047 When optional argument TAGS-ONLY is non-nil, only compute tags
5048 related expressions."
5049 (when (derived-mode-p 'org-mode
)
5050 (let ((alist (org--setup-collect-keywords
5051 (org-make-options-regexp
5052 (append '("FILETAGS" "TAGS" "SETUPFILE")
5053 (and (not tags-only
)
5054 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5055 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5056 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5057 ;; Startup options. Get this early since it does change
5058 ;; behavior for other options (e.g., tags).
5059 (let ((startup (cdr (assq 'startup alist
))))
5060 (dolist (option startup
)
5061 (let ((entry (assoc-string option org-startup-options t
)))
5063 (let ((var (nth 1 entry
))
5064 (val (nth 2 entry
)))
5065 (if (not (nth 3 entry
)) (set (make-local-variable var
) val
)
5066 (unless (listp (symbol-value var
))
5067 (set (make-local-variable var
) nil
))
5068 (add-to-list var val
)))))))
5069 (setq-local org-file-tags
5070 (mapcar #'org-add-prop-inherited
5071 (cdr (assq 'filetags alist
))))
5072 (setq org-current-tag-alist
5073 (append org-tag-persistent-alist
5074 (let ((tags (cdr (assq 'tags alist
))))
5075 (if tags
(org-tag-string-to-alist tags
)
5077 (setq org-tag-groups-alist
5078 (org-tag-alist-to-groups org-current-tag-alist
))
5081 (setq-local org-file-properties
(cdr (assq 'property alist
)))
5082 ;; Archive location.
5083 (let ((archive (cdr (assq 'archive alist
))))
5084 (when archive
(setq-local org-archive-location archive
)))
5086 (let ((cat (org-string-nw-p (cdr (assq 'category alist
)))))
5088 (setq-local org-category
(intern cat
))
5089 (setq-local org-file-properties
5090 (org--update-property-plist
5091 "CATEGORY" cat org-file-properties
))))
5093 (let ((column (cdr (assq 'columns alist
))))
5094 (when column
(setq-local org-columns-default-format column
)))
5096 (setq org-table-formula-constants-local
(cdr (assq 'constants alist
)))
5097 ;; Link abbreviations.
5098 (let ((links (cdr (assq 'link alist
))))
5099 (when links
(setq org-link-abbrev-alist-local
(nreverse links
))))
5101 (let ((priorities (cdr (assq 'priorities alist
))))
5103 (setq-local org-highest-priority
(nth 0 priorities
))
5104 (setq-local org-lowest-priority
(nth 1 priorities
))
5105 (setq-local org-default-priority
(nth 2 priorities
))))
5107 (let ((scripts (assq 'scripts alist
)))
5109 (setq-local org-use-sub-superscripts
(cdr scripts
))))
5111 (setq-local org-todo-kwd-alist nil
)
5112 (setq-local org-todo-key-alist nil
)
5113 (setq-local org-todo-key-trigger nil
)
5114 (setq-local org-todo-keywords-1 nil
)
5115 (setq-local org-done-keywords nil
)
5116 (setq-local org-todo-heads nil
)
5117 (setq-local org-todo-sets nil
)
5118 (setq-local org-todo-log-states nil
)
5119 (let ((todo-sequences
5120 (or (nreverse (cdr (assq 'todo alist
)))
5121 (let ((d (default-value 'org-todo-keywords
)))
5122 (if (not (stringp (car d
))) d
5123 ;; XXX: Backward compatibility code.
5124 (list (cons org-todo-interpretation d
)))))))
5125 (dolist (sequence todo-sequences
)
5126 (let* ((sequence (or (run-hook-with-args-until-success
5127 'org-todo-setup-filter-hook sequence
)
5129 (sequence-type (car sequence
))
5130 (keywords (cdr sequence
))
5131 (sep (member "|" keywords
))
5133 (dolist (k (remove "|" keywords
))
5134 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5136 (error "Invalid TODO keyword %s" k
))
5137 (let ((name (match-string 1 k
))
5138 (key (match-string 2 k
))
5139 (log (org-extract-log-state-settings k
)))
5141 (push (cons name
(and key
(string-to-char key
))) alist
)
5142 (when log
(push log org-todo-log-states
))))
5143 (let* ((names (nreverse names
))
5144 (done (if sep
(org-remove-keyword-keys (cdr sep
))
5147 (tail (list sequence-type head
(car done
) (org-last done
))))
5148 (add-to-list 'org-todo-heads head
'append
)
5149 (push names org-todo-sets
)
5150 (setq org-done-keywords
(append org-done-keywords done nil
))
5151 (setq org-todo-keywords-1
(append org-todo-keywords-1 names nil
))
5152 (setq org-todo-key-alist
5153 (append org-todo-key-alist
5155 (append '((:startgroup
))
5158 (dolist (k names
) (push (cons k tail
) org-todo-kwd-alist
))))))
5159 (setq org-todo-sets
(nreverse org-todo-sets
)
5160 org-todo-kwd-alist
(nreverse org-todo-kwd-alist
)
5161 org-todo-key-trigger
(delq nil
(mapcar #'cdr org-todo-key-alist
))
5162 org-todo-key-alist
(org-assign-fast-keys org-todo-key-alist
))
5163 ;; Compute the regular expressions and other local variables.
5164 ;; Using `org-outline-regexp-bol' would complicate them much,
5165 ;; because of the fixed white space at the end of that string.
5166 (unless org-done-keywords
5167 (setq org-done-keywords
5168 (and org-todo-keywords-1
(last org-todo-keywords-1
))))
5169 (setq org-not-done-keywords
5170 (org-delete-all org-done-keywords
5171 (copy-sequence org-todo-keywords-1
))
5172 org-todo-regexp
(regexp-opt org-todo-keywords-1 t
)
5173 org-not-done-regexp
(regexp-opt org-not-done-keywords t
)
5174 org-not-done-heading-regexp
5175 (format org-heading-keyword-regexp-format org-not-done-regexp
)
5176 org-todo-line-regexp
5177 (format org-heading-keyword-maybe-regexp-format org-todo-regexp
)
5178 org-complex-heading-regexp
5179 (concat "^\\(\\*+\\)"
5180 "\\(?: +" org-todo-regexp
"\\)?"
5181 "\\(?: +\\(\\[#.\\]\\)\\)?"
5182 "\\(?: +\\(.*?\\)\\)??"
5183 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5185 org-complex-heading-regexp-format
5186 (concat "^\\(\\*+\\)"
5187 "\\(?: +" org-todo-regexp
"\\)?"
5188 "\\(?: +\\(\\[#.\\]\\)\\)?"
5190 ;; Stats cookies can be stuck to body.
5191 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5193 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5195 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5197 org-todo-line-tags-regexp
5198 (concat "^\\(\\*+\\)"
5199 "\\(?: +" org-todo-regexp
"\\)?"
5200 "\\(?: +\\(.*?\\)\\)??"
5201 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5203 (org-compute-latex-and-related-regexp)))))
5205 (defun org--setup-collect-keywords (regexp &optional files alist
)
5206 "Return setup keywords values as an alist.
5208 REGEXP matches a subset of setup keywords. FILES is a list of
5209 file names already visited. It is used to avoid circular setup
5210 files. ALIST, when non-nil, is the alist computed so far.
5212 Return value contains the following keys: `archive', `category',
5213 `columns', `constants', `filetags', `link', `priorities',
5214 `property', `scripts', `startup', `tags' and `todo'."
5215 (org-with-wide-buffer
5216 (goto-char (point-min))
5217 (let ((case-fold-search t
))
5218 (while (re-search-forward regexp nil t
)
5219 (let ((element (org-element-at-point)))
5220 (when (eq (org-element-type element
) 'keyword
)
5221 (let ((key (org-element-property :key element
))
5222 (value (org-element-property :value element
)))
5224 ((equal key
"ARCHIVE")
5225 (when (org-string-nw-p value
)
5226 (push (cons 'archive value
) alist
)))
5227 ((equal key
"CATEGORY") (push (cons 'category value
) alist
))
5228 ((equal key
"COLUMNS") (push (cons 'columns value
) alist
))
5229 ((equal key
"CONSTANTS")
5230 (let* ((constants (assq 'constants alist
))
5231 (store (cdr constants
)))
5232 (dolist (pair (org-split-string value
))
5233 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5235 (let* ((name (match-string 1 pair
))
5236 (value (match-string 2 pair
))
5237 (old (assoc name store
)))
5238 (if old
(setcdr old value
)
5239 (push (cons name value
) store
)))))
5240 (if constants
(setcdr constants store
)
5241 (push (cons 'constants store
) alist
))))
5242 ((equal key
"FILETAGS")
5243 (when (org-string-nw-p value
)
5244 (let ((old (assq 'filetags alist
))
5246 (mapcar (lambda (x) (org-split-string x
":"))
5247 (org-split-string value
)))))
5248 (if old
(setcdr old
(append new
(cdr old
)))
5249 (push (cons 'filetags new
) alist
)))))
5251 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value
)
5252 (let ((links (assq 'link alist
))
5253 (pair (cons (match-string-no-properties 1 value
)
5254 (match-string-no-properties 2 value
))))
5255 (if links
(push pair
(cdr links
))
5256 (push (list 'link pair
) alist
)))))
5257 ((equal key
"OPTIONS")
5258 (when (and (org-string-nw-p value
)
5259 (string-match "\\^:\\(t\\|nil\\|{}\\)" value
))
5260 (push (cons 'scripts
(read (match-string 1 value
))) alist
)))
5261 ((equal key
"PRIORITIES")
5262 (push (cons 'priorities
5263 (let ((prio (org-split-string value
)))
5264 (if (< (length prio
) 3) '(?A ?C ?B
)
5265 (mapcar #'string-to-char prio
))))
5267 ((equal key
"PROPERTY")
5268 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value
)
5269 (let* ((property (assq 'property alist
))
5270 (value (org--update-property-plist
5271 (match-string-no-properties 1 value
)
5272 (match-string-no-properties 2 value
)
5274 (if property
(setcdr property value
)
5275 (push (cons 'property value
) alist
)))))
5276 ((equal key
"STARTUP")
5277 (let ((startup (assq 'startup alist
)))
5280 (append (cdr startup
) (org-split-string value
)))
5281 (push (cons 'startup
(org-split-string value
)) alist
))))
5283 (let ((tag-cell (assq 'tags alist
)))
5285 (setcdr tag-cell
(concat (cdr tag-cell
) "\n" value
))
5286 (push (cons 'tags value
) alist
))))
5287 ((member key
'("TODO" "SEQ_TODO" "TYP_TODO"))
5288 (let ((todo (assq 'todo alist
))
5289 (value (cons (if (equal key
"TYP_TODO") 'type
'sequence
)
5290 (org-split-string value
))))
5291 (if todo
(push value
(cdr todo
))
5292 (push (list 'todo value
) alist
))))
5293 ((equal key
"SETUPFILE")
5294 (unless buffer-read-only
; Do not check in Gnus messages.
5295 (let ((f (and (org-string-nw-p value
)
5297 (org-unbracket-string "\"" "\"" value
)))))
5298 (when (and f
(file-readable-p f
) (not (member f files
)))
5300 (setq default-directory
(file-name-directory f
))
5301 (insert-file-contents f
)
5303 ;; Fake Org mode to benefit from cache
5304 ;; without recurring needlessly.
5305 (let ((major-mode 'org-mode
))
5306 (org--setup-collect-keywords
5307 regexp
(cons f files
) alist
)))))))))))))))
5310 (defun org-tag-string-to-alist (s)
5311 "Return tag alist associated to string S.
5312 S is a value for TAGS keyword or produced with
5313 `org-tag-alist-to-string'. Return value is an alist suitable for
5314 `org-tag-alist' or `org-tag-persistent-alist'."
5315 (let ((lines (mapcar #'split-string
(split-string s
"\n" t
)))
5316 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5317 "\\|{.+?}\\)" ; regular expression
5318 "\\(?:(\\(.\\))\\)?\\'"))
5320 (dolist (tokens lines
(cdr (nreverse alist
)))
5321 (push '(:newline
) alist
)
5323 (let ((token (pop tokens
)))
5326 (push '(:startgroup
) alist
)
5327 (when (equal (nth 1 tokens
) ":") (setq group-flag t
)))
5329 (push '(:endgroup
) alist
)
5330 (setq group-flag nil
))
5332 (push '(:startgrouptag
) alist
)
5333 (when (equal (nth 1 tokens
) ":") (setq group-flag t
)))
5335 (push '(:endgrouptag
) alist
)
5336 (setq group-flag nil
))
5338 (push '(:grouptags
) alist
))
5339 ((guard (string-match tag-re token
))
5340 (let ((tag (match-string 1 token
))
5341 (key (and (match-beginning 2)
5342 (string-to-char (match-string 2 token
)))))
5343 ;; Push all tags in groups, no matter if they already
5344 ;; appear somewhere else in the list.
5345 (when (or group-flag
(not (assoc tag alist
)))
5346 (push (cons tag key
) alist
))))))))))
5348 (defun org-tag-alist-to-string (alist &optional skip-key
)
5349 "Return tag string associated to ALIST.
5351 ALIST is an alist, as defined in `org-tag-alist' or
5352 `org-tag-persistent-alist', or produced with
5353 `org-tag-string-to-alist'.
5355 Return value is a string suitable as a value for \"TAGS\"
5358 When optional argument SKIP-KEY is non-nil, skip selection keys
5360 (mapconcat (lambda (token)
5362 (`(:startgroup
) "{")
5364 (`(:startgrouptag
) "[")
5365 (`(:endgrouptag
) "]")
5369 (guard (not skip-key
))
5370 `(,(and tag
(pred stringp
)) .
,(and key
(pred characterp
))))
5371 (format "%s(%c)" tag key
))
5372 (`(,(and tag
(pred stringp
)) .
,_
) tag
)
5373 (_ (user-error "Invalid tag token: %S" token
))))
5377 (defun org-tag-alist-to-groups (alist)
5378 "Return group alist from tag ALIST.
5379 ALIST is an alist, as defined in `org-tag-alist' or
5380 `org-tag-persistent-alist', or produced with
5381 `org-tag-string-to-alist'. Return value is an alist following
5382 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5383 a string, summarizing TAGS, as a list of strings."
5384 (let (groups group-status current-group
)
5385 (dolist (token alist
(nreverse groups
))
5387 (`(,(or :startgroup
:startgrouptag
)) (setq group-status t
))
5388 (`(,(or :endgroup
:endgrouptag
))
5389 (when (eq group-status
'append
)
5390 (push (nreverse current-group
) groups
))
5391 (setq group-status nil
))
5392 (`(:grouptags
) (setq group-status
'append
))
5393 ((and `(,tag .
,_
) (guard group-status
))
5394 (if (eq group-status
'append
) (push tag current-group
)
5395 (setq current-group
(list tag
))))
5398 (defun org-file-contents (file &optional noerror
)
5399 "Return the contents of FILE, as a string."
5400 (if (and file
(file-readable-p file
))
5402 (insert-file-contents file
)
5404 (funcall (if noerror
'message
'error
)
5405 "Cannot read file \"%s\"%s"
5407 (let ((from (buffer-file-name (buffer-base-buffer))))
5408 (if from
(concat " (referenced in file \"" from
"\")") "")))))
5410 (defun org-extract-log-state-settings (x)
5411 "Extract the log state setting from a TODO keyword string.
5412 This will extract info from a string like \"WAIT(w@/!)\"."
5413 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x
)
5414 (let ((kw (match-string 1 x
))
5415 (log1 (and (match-end 3) (match-string 3 x
)))
5416 (log2 (and (match-end 4) (match-string 4 x
))))
5419 (and log1
(if (equal log1
"!") 'time
'note
))
5420 (and log2
(if (equal log2
"!") 'time
'note
)))))))
5422 (defun org-remove-keyword-keys (list)
5423 "Remove a pair of parenthesis at the end of each string in LIST."
5425 (if (string-match "(.*)$" x
)
5426 (substring x
0 (match-beginning 0))
5430 (defun org-assign-fast-keys (alist)
5431 "Assign fast keys to a keyword-key alist.
5432 Respect keys that are already there."
5433 (let (new e
(alt ?
0))
5434 (while (setq e
(pop alist
))
5435 (if (or (memq (car e
) '(:newline
:grouptags
:endgroup
:startgroup
))
5436 (cdr e
)) ;; Key already assigned.
5438 (let ((clist (string-to-list (downcase (car e
))))
5439 (used (append new alist
)))
5440 (when (= (car clist
) ?
@)
5442 (while (and clist
(rassoc (car clist
) used
))
5445 (while (rassoc alt used
)
5447 (push (cons (car e
) (or (car clist
) alt
)) new
))))
5450 ;;; Some variables used in various places
5452 (defvar org-window-configuration nil
5453 "Used in various places to store a window configuration.")
5454 (defvar org-selected-window nil
5455 "Used in various places to store a window configuration.")
5456 (defvar org-finish-function nil
5457 "Function to be called when `C-c C-c' is used.
5458 This is for getting out of special buffers like capture.")
5459 (defvar org-last-state
)
5461 ;; Defined somewhere in this file, but used before definition.
5462 (defvar org-entities
) ;; defined in org-entities.el
5463 (defvar org-struct-menu
)
5464 (defvar org-org-menu
)
5465 (defvar org-tbl-menu
)
5467 ;;;; Define the Org mode
5469 ;; We use a before-change function to check if a table might need
5471 (defvar org-table-may-need-update t
5472 "Indicates that a table might need an update.
5473 This variable is set by `org-before-change-function'.
5474 `org-table-align' sets it back to nil.")
5475 (defun org-before-change-function (_beg _end
)
5476 "Every change indicates that a table might need an update."
5477 (setq org-table-may-need-update t
))
5478 (defvar org-mode-map
)
5479 (defvar org-inhibit-startup-visibility-stuff nil
) ; Dynamically-scoped param.
5480 (defvar org-agenda-keep-modes nil
) ; Dynamically-scoped param.
5481 (defvar org-inhibit-logging nil
) ; Dynamically-scoped param.
5482 (defvar org-inhibit-blocking nil
) ; Dynamically-scoped param.
5483 (defvar org-table-buffer-is-an nil
)
5485 (defvar bidi-paragraph-direction
)
5486 (defvar buffer-face-mode-face
)
5490 ;; Other stuff we need.
5491 (require 'time-date
)
5492 (unless (fboundp 'time-subtract
) (defalias 'time-subtract
'subtract-time
))
5494 (autoload 'easy-menu-add
"easymenu")
5497 ;; (require 'org-macs) moved higher up in the file before it is first used
5498 (require 'org-entities
)
5499 ;; (require 'org-compat) moved higher up in the file before it is first used
5500 (require 'org-faces
)
5502 (require 'org-pcomplete
)
5504 (require 'org-footnote
)
5505 (require 'org-macro
)
5511 (define-derived-mode org-mode outline-mode
"Org"
5512 "Outline-based notes management and organizer, alias
5513 \"Carsten's outline-mode for keeping track of everything.\"
5515 Org mode develops organizational tasks around a NOTES file which
5516 contains information about projects as plain text. Org mode is
5517 implemented on top of Outline mode, which is ideal to keep the content
5518 of large files well structured. It supports ToDo items, deadlines and
5519 time stamps, which magically appear in the diary listing of the Emacs
5520 calendar. Tables are easily created with a built-in table editor.
5521 Plain text URL-like links connect to websites, emails (VM), Usenet
5522 messages (Gnus), BBDB entries, and any files related to the project.
5523 For printing and sharing of notes, an Org file (or a part of it)
5524 can be exported as a structured ASCII or HTML file.
5526 The following commands are available:
5530 ;; Get rid of Outline menus, they are not needed
5531 ;; Need to do this here because define-derived-mode sets up
5532 ;; the keymap so late. Still, it is a waste to call this each time
5533 ;; we switch another buffer into Org mode.
5534 (define-key org-mode-map
[menu-bar headings
] 'undefined
)
5535 (define-key org-mode-map
[menu-bar hide
] 'undefined
)
5536 (define-key org-mode-map
[menu-bar show
] 'undefined
)
5538 (org-load-modules-maybe)
5539 (org-install-agenda-files-menu)
5540 (when org-descriptive-links
(add-to-invisibility-spec '(org-link)))
5541 (add-to-invisibility-spec '(org-cwidth))
5542 (add-to-invisibility-spec '(org-hide-block . t
))
5543 (setq-local outline-regexp org-outline-regexp
)
5544 (setq-local outline-level
'org-outline-level
)
5545 (setq bidi-paragraph-direction
'left-to-right
)
5546 (when (and org-ellipsis
5547 (fboundp 'set-display-table-slot
) (boundp 'buffer-display-table
)
5548 (fboundp 'make-glyph-code
))
5549 (unless org-display-table
5550 (setq org-display-table
(make-display-table)))
5551 (set-display-table-slot
5553 (vconcat (mapcar (lambda (c) (make-glyph-code c
'org-ellipsis
))
5554 (if (stringp org-ellipsis
) org-ellipsis
"..."))))
5555 (setq buffer-display-table org-display-table
))
5556 (org-set-regexps-and-options)
5557 (org-set-font-lock-defaults)
5558 (when (and org-tag-faces
(not org-tags-special-faces-re
))
5559 ;; tag faces set outside customize.... force initialization.
5560 (org-set-tag-faces 'org-tag-faces org-tag-faces
))
5562 (setq-local calc-embedded-open-mode
"# ")
5563 ;; Modify a few syntax entries
5564 (modify-syntax-entry ?
@ "w")
5565 (modify-syntax-entry ?
\" "\"")
5566 (modify-syntax-entry ?
\\ "_")
5567 (modify-syntax-entry ?~
"_")
5568 (setq-local font-lock-unfontify-region-function
'org-unfontify-region
)
5569 ;; Activate before-change-function
5570 (setq-local org-table-may-need-update t
)
5571 (add-hook 'before-change-functions
'org-before-change-function nil
'local
)
5572 ;; Check for running clock before killing a buffer
5573 (add-hook 'kill-buffer-hook
'org-check-running-clock nil
'local
)
5574 ;; Initialize macros templates.
5575 (org-macro-initialize-templates)
5576 ;; Initialize radio targets.
5577 (org-update-radio-target-regexp)
5579 (setq-local indent-line-function
'org-indent-line
)
5580 (setq-local indent-region-function
'org-indent-region
)
5581 ;; Filling and auto-filling.
5584 (org-setup-comments-handling)
5585 ;; Initialize cache.
5586 (org-element-cache-reset)
5587 ;; Beginning/end of defun
5588 (setq-local beginning-of-defun-function
'org-backward-element
)
5589 (setq-local end-of-defun-function
5591 (if (not (org-at-heading-p))
5592 (org-forward-element)
5593 (org-forward-element)
5594 (forward-char -
1))))
5595 ;; Next error for sparse trees
5596 (setq-local next-error-function
'org-occur-next-match
)
5597 ;; Make sure dependence stuff works reliably, even for users who set it
5599 (if org-enforce-todo-dependencies
5600 (add-hook 'org-blocker-hook
5601 'org-block-todo-from-children-or-siblings-or-parent
)
5602 (remove-hook 'org-blocker-hook
5603 'org-block-todo-from-children-or-siblings-or-parent
))
5604 (if org-enforce-todo-checkbox-dependencies
5605 (add-hook 'org-blocker-hook
5606 'org-block-todo-from-checkboxes
)
5607 (remove-hook 'org-blocker-hook
5608 'org-block-todo-from-checkboxes
))
5610 ;; Align options lines
5612 align-mode-rules-list
5613 '((org-in-buffer-settings
5614 (regexp .
"^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5615 (modes .
'(org-mode)))))
5618 (setq-local imenu-create-index-function
'org-imenu-get-tree
)
5620 ;; Make isearch reveal context
5621 (setq-local outline-isearch-open-invisible-function
5622 (lambda (&rest _
) (org-show-context 'isearch
)))
5624 ;; Setup the pcomplete hooks
5625 (setq-local pcomplete-command-completion-function
'org-pcomplete-initial
)
5626 (setq-local pcomplete-command-name-function
'org-command-at-point
)
5627 (setq-local pcomplete-default-completion-function
'ignore
)
5628 (setq-local pcomplete-parse-arguments-function
'org-parse-arguments
)
5629 (setq-local pcomplete-termination-string
"")
5630 (setq-local buffer-face-mode-face
'org-default
)
5632 ;; If empty file that did not turn on Org mode automatically, make
5634 (when (and org-insert-mode-line-in-empty-file
5635 (called-interactively-p 'any
)
5636 (= (point-min) (point-max)))
5637 (insert "# -*- mode: org -*-\n\n"))
5638 (unless org-inhibit-startup
5640 (when org-startup-with-beamer-mode
(org-beamer-mode))
5641 (when org-startup-align-all-tables
5642 (org-table-map-tables #'org-table-align t
))
5643 (when org-startup-with-inline-images
(org-display-inline-images))
5644 (when org-startup-with-latex-preview
(org-toggle-latex-fragment))
5645 (unless org-inhibit-startup-visibility-stuff
(org-set-startup-visibility))
5646 (when org-startup-truncated
(setq truncate-lines t
))
5647 (when org-startup-indented
(require 'org-indent
) (org-indent-mode 1))
5648 (org-refresh-effort-properties)))
5649 ;; Try to set `org-hide' face correctly.
5650 (let ((foreground (org-find-invisible-foreground)))
5652 (set-face-foreground 'org-hide foreground
))))
5654 ;; Update `customize-package-emacs-version-alist'
5655 (add-to-list 'customize-package-emacs-version-alist
5656 '(Org ("6.21b" .
"23.1") ("6.33x" .
"23.2")
5657 ("7.8.11" .
"24.1") ("7.9.4" .
"24.3")
5658 ("8.2.6" .
"24.4") ("8.2.10" .
"24.5")
5661 (defvar org-mode-transpose-word-syntax-table
5662 (let ((st (make-syntax-table text-mode-syntax-table
)))
5663 (dolist (c org-emphasis-alist st
)
5664 (modify-syntax-entry (string-to-char (car c
)) "w p" st
))))
5666 (when (fboundp 'abbrev-table-put
)
5667 (abbrev-table-put org-mode-abbrev-table
5668 :parents
(list text-mode-abbrev-table
)))
5670 (defun org-find-invisible-foreground ()
5671 (let ((candidates (remove
5674 (list (face-background 'default
)
5675 (face-background 'org-default
))
5678 (when (boundp alist
)
5679 (cdr (assq 'background-color
(symbol-value alist
)))))
5680 '(default-frame-alist initial-frame-alist window-system-default-frame-alist
))
5681 (list (face-foreground 'org-hide
))))))
5682 (car (remove nil candidates
))))
5684 (defun org-current-time (&optional rounding-minutes past
)
5685 "Current time, possibly rounded to ROUNDING-MINUTES.
5686 When ROUNDING-MINUTES is not an integer, fall back on the car of
5687 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5688 the rounding returns a past time."
5689 (let ((r (or (and (integerp rounding-minutes
) rounding-minutes
)
5690 (car org-time-stamp-rounding-minutes
)))
5691 (time (decode-time)) res
)
5696 (append (list 0 (* r
(floor (+ .5 (/ (float (nth 1 time
)) r
)))))
5698 (if (and past
(< (float-time (time-subtract (current-time) res
)) 0))
5699 (seconds-to-time (- (float-time res
) (* r
60)))
5703 "Return today date, considering `org-extend-today-until'."
5705 (time-subtract (current-time)
5706 (list 0 (* 3600 org-extend-today-until
) 0))))
5708 ;;;; Font-Lock stuff, including the activators
5710 (defvar org-mouse-map
(make-sparse-keymap))
5711 (org-defkey org-mouse-map
[mouse-2
] 'org-open-at-mouse
)
5712 (org-defkey org-mouse-map
[mouse-3
] 'org-find-file-at-mouse
)
5713 (when org-mouse-1-follows-link
5714 (org-defkey org-mouse-map
[follow-link
] 'mouse-face
))
5715 (when org-tab-follows-link
5716 (org-defkey org-mouse-map
[(tab)] 'org-open-at-point
)
5717 (org-defkey org-mouse-map
"\C-i" 'org-open-at-point
))
5719 (require 'font-lock
)
5721 (defconst org-non-link-chars
"]\t\n\r<>")
5722 (defvar org-link-types-re nil
5723 "Matches a link that has a url-like prefix like \"http:\"")
5724 (defvar org-link-re-with-space nil
5725 "Matches a link with spaces, optional angular brackets around it.")
5726 (defvar org-link-re-with-space2 nil
5727 "Matches a link with spaces, optional angular brackets around it.")
5728 (defvar org-link-re-with-space3 nil
5729 "Matches a link with spaces, only for internal part in bracket links.")
5730 (defvar org-angle-link-re nil
5731 "Matches link with angular brackets, spaces are allowed.")
5732 (defvar org-plain-link-re nil
5733 "Matches plain link, without spaces.")
5734 (defvar org-bracket-link-regexp nil
5735 "Matches a link in double brackets.")
5736 (defvar org-bracket-link-analytic-regexp nil
5737 "Regular expression used to analyze links.
5738 Here is what the match groups contain after a match:
5744 (defvar org-bracket-link-analytic-regexp
++ nil
5745 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5746 (defvar org-any-link-re nil
5747 "Regular expression matching any link.")
5749 (defconst org-match-sexp-depth
3
5750 "Number of stacked braces for sub/superscript matching.")
5752 (defun org-create-multibrace-regexp (left right n
)
5753 "Create a regular expression which will match a balanced sexp.
5754 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5755 as single character strings.
5756 The regexp returned will match the entire expression including the
5757 delimiters. It will also define a single group which contains the
5758 match except for the outermost delimiters. The maximum depth of
5759 stacked delimiters is N. Escaping delimiters is not possible."
5760 (let* ((nothing (concat "[^" left right
"]*?"))
5763 (next (concat "\\(?:" nothing left nothing right
"\\)+" nothing
)))
5766 re
(concat re or next
)
5767 next
(concat "\\(?:" nothing left next right
"\\)+" nothing
)))
5768 (concat left
"\\(" re
"\\)" right
)))
5770 (defconst org-match-substring-regexp
5772 "\\(\\S-\\)\\([_^]\\)\\("
5773 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)"
5775 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth
) "\\)"
5777 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5778 "The regular expression matching a sub- or superscript.")
5780 (defconst org-match-substring-with-braces-regexp
5782 "\\(\\S-\\)\\([_^]\\)"
5783 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)")
5784 "The regular expression matching a sub- or superscript, forcing braces.")
5786 (defun org-make-link-regexps ()
5787 "Update the link regular expressions.
5788 This should be called after the variable `org-link-parameters' has changed."
5789 (let ((types-re (regexp-opt (org-link-types) t
)))
5790 (setq org-link-types-re
5791 (concat "\\`" types-re
":")
5792 org-link-re-with-space
5793 (concat "<?" types-re
":"
5794 "\\([^" org-non-link-chars
" ]"
5795 "[^" org-non-link-chars
"]*"
5796 "[^" org-non-link-chars
" ]\\)>?")
5797 org-link-re-with-space2
5798 (concat "<?" types-re
":"
5799 "\\([^" org-non-link-chars
" ]"
5801 "[^" org-non-link-chars
" ]\\)>?")
5802 org-link-re-with-space3
5803 (concat "<?" types-re
":"
5804 "\\([^" org-non-link-chars
" ]"
5807 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5812 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5813 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5814 org-bracket-link-regexp
5815 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5816 org-bracket-link-analytic-regexp
5819 "\\(" types-re
":\\)?"
5822 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5824 org-bracket-link-analytic-regexp
++
5827 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t
) ":\\)?"
5830 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5833 (concat "\\(" org-bracket-link-regexp
"\\)\\|\\("
5834 org-angle-link-re
"\\)\\|\\("
5835 org-plain-link-re
"\\)"))))
5837 (org-make-link-regexps)
5839 (defvar org-emph-face nil
)
5841 (defun org-do-emphasis-faces (limit)
5842 "Run through the buffer and emphasize strings."
5843 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5844 (car org-emphasis-regexp-components
))))
5846 (while (re-search-forward quick-re limit t
)
5847 (let* ((marker (match-string 2))
5848 (verbatim?
(member marker
'("~" "="))))
5849 (when (save-excursion
5850 (goto-char (match-beginning 0))
5851 ;; Do not match headline stars. Do not consider
5852 ;; stars of a headline as closing marker for bold
5854 (and (not (looking-at-p org-outline-regexp-bol
))
5855 (looking-at (if verbatim? org-verbatim-re org-emph-re
))
5856 (not (string-match-p
5857 (concat org-outline-regexp-bol
"\\'")
5858 (match-string 0)))))
5859 (pcase-let ((`(,_
,face
,_
) (assoc marker org-emphasis-alist
)))
5860 (font-lock-prepend-text-property
5861 (match-beginning 2) (match-end 2) 'face face
)
5863 (org-remove-flyspell-overlays-in
5864 (match-beginning 0) (match-end 0)))
5865 (add-text-properties (match-beginning 2) (match-end 2)
5866 '(font-lock-multiline t org-emphasis t
))
5867 (when org-hide-emphasis-markers
5868 (add-text-properties (match-end 4) (match-beginning 5)
5869 '(invisible org-link
))
5870 (add-text-properties (match-beginning 3) (match-end 3)
5871 '(invisible org-link
)))
5872 (throw :exit t
))))))))
5874 (defun org-emphasize (&optional char
)
5875 "Insert or change an emphasis, i.e. a font like bold or italic.
5876 If there is an active region, change that region to a new emphasis.
5877 If there is no region, just insert the marker characters and position
5878 the cursor between them.
5879 CHAR should be the marker character. If it is a space, it means to
5880 remove the emphasis of the selected region.
5881 If CHAR is not given (for example in an interactive call) it will be
5884 (let ((erc org-emphasis-regexp-components
)
5885 (string "") beg end move s
)
5886 (if (org-region-active-p)
5887 (setq beg
(region-beginning)
5889 string
(buffer-substring beg end
))
5893 (message "Emphasis marker or tag: [%s]"
5894 (mapconcat #'car org-emphasis-alist
""))
5895 (setq char
(read-char-exclusive)))
5896 (if (equal char ?\s
)
5899 (unless (assoc (char-to-string char
) org-emphasis-alist
)
5900 (user-error "No such emphasis marker: \"%c\"" char
))
5901 (setq s
(char-to-string char
)))
5902 (while (and (> (length string
) 1)
5903 (equal (substring string
0 1) (substring string -
1))
5904 (assoc (substring string
0 1) org-emphasis-alist
))
5905 (setq string
(substring string
1 -
1)))
5906 (setq string
(concat s string s
))
5907 (when beg
(delete-region beg end
))
5909 (string-match (concat "[" (nth 0 erc
) "\n]")
5910 (char-to-string (char-before (point)))))
5913 (string-match (concat "[" (nth 1 erc
) "\n]")
5914 (char-to-string (char-after (point)))))
5915 (insert " ") (backward-char 1))
5917 (and move
(backward-char 1))))
5919 (defconst org-nonsticky-props
5920 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link
))
5922 (defsubst org-rear-nonsticky-at
(pos)
5923 (add-text-properties (1- pos
) pos
(list 'rear-nonsticky org-nonsticky-props
)))
5925 (defun org-activate-plain-links (limit)
5926 "Add link properties for plain links."
5927 (when (and (re-search-forward org-plain-link-re limit t
)
5928 (not (org-in-src-block-p)))
5930 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5932 (link (match-string-no-properties 0))
5933 (type (match-string-no-properties 1))
5934 (path (match-string-no-properties 2))
5935 (link-start (match-beginning 0))
5936 (link-end (match-end 0))
5937 (link-face (org-link-get-parameter type
:face
))
5938 (help-echo (org-link-get-parameter type
:help-echo
))
5939 (htmlize-link (org-link-get-parameter type
:htmlize-link
))
5940 (activate-func (org-link-get-parameter type
:activate-func
)))
5941 (unless (if (consp face
) (memq 'org-tag face
) (eq 'org-tag face
))
5942 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5943 (add-text-properties (match-beginning 0) (match-end 0)
5945 'mouse-face
(or (org-link-get-parameter type
:mouse-face
)
5948 ;; A function that returns a face
5949 ((functionp link-face
)
5950 (funcall link-face path
))
5954 ;; An anonymous face
5961 ((stringp help-echo
)
5963 ((functionp help-echo
)
5968 (org-link-unescape link
)))))
5970 ((functionp htmlize-link
)
5971 (funcall htmlize-link path
))
5974 'keymap
(or (org-link-get-parameter type
:keymap
)
5976 'org-link-start
(match-beginning 0)))
5977 (org-rear-nonsticky-at (match-end 0))
5979 (funcall activate-func link-start link-end path nil
))
5982 (defun org-activate-code (limit)
5983 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t
)
5984 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5985 (remove-text-properties (match-beginning 0) (match-end 0)
5986 '(display t invisible t intangible t
))
5989 (defcustom org-src-fontify-natively t
5990 "When non-nil, fontify code in code blocks.
5991 See also the `org-block' face."
5994 :package-version
'(Org .
"8.3")
5995 :group
'org-appearance
5998 (defcustom org-allow-promoting-top-level-subtree nil
5999 "When non-nil, allow promoting a top level subtree.
6000 The leading star of the top level headline will be replaced
6004 :group
'org-appearance
)
6006 (defun org-fontify-meta-lines-and-blocks (limit)
6008 (org-fontify-meta-lines-and-blocks-1 limit
)
6009 (error (message "org-mode fontification error in %S at %d"
6011 (line-number-at-pos)))))
6013 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6014 "Fontify #+ lines and blocks."
6015 (let ((case-fold-search t
))
6016 (when (re-search-forward
6017 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6019 (let ((beg (match-beginning 0))
6020 (block-start (match-end 0))
6022 (lang (match-string 7))
6023 (beg1 (line-beginning-position 2))
6024 (dc1 (downcase (match-string 2)))
6025 (dc3 (downcase (match-string 3)))
6026 end end1 quoting block-type
)
6028 ((and (match-end 4) (equal dc3
"+begin"))
6030 (setq block-type
(downcase (match-string 5))
6031 quoting
(member block-type org-protecting-blocks
))
6032 (when (re-search-forward
6033 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6034 nil t
) ;; on purpose, we look further than LIMIT
6035 (setq end
(min (point-max) (match-end 0))
6036 end1
(min (point-max) (1- (match-beginning 0))))
6037 (setq block-end
(match-beginning 0))
6039 (org-remove-flyspell-overlays-in beg1 end1
)
6040 (remove-text-properties beg end
6041 '(display t invisible t intangible t
)))
6042 (add-text-properties
6043 beg end
'(font-lock-fontified t font-lock-multiline t
))
6044 (add-text-properties beg beg1
'(face org-meta-line
))
6045 (org-remove-flyspell-overlays-in beg beg1
)
6046 (add-text-properties ; For end_src
6047 end1
(min (point-max) (1+ end
)) '(face org-meta-line
))
6048 (org-remove-flyspell-overlays-in end1 end
)
6050 ((and lang
(not (string= lang
"")) org-src-fontify-natively
)
6051 (org-src-font-lock-fontify-block lang block-start block-end
)
6052 (add-text-properties beg1 block-end
'(src-block t
)))
6054 (add-text-properties beg1
(min (point-max) (1+ end1
))
6058 (intern (format "org-block-%s" lang
))))
6059 (append (and (facep face-name
) (list face-name
))
6060 '(org-block))))))) ; end of source block
6061 ((not org-fontify-quote-and-verse-blocks
))
6062 ((string= block-type
"quote")
6063 (add-text-properties beg1
(min (point-max) (1+ end1
)) '(face org-quote
)))
6064 ((string= block-type
"verse")
6065 (add-text-properties beg1
(min (point-max) (1+ end1
)) '(face org-verse
))))
6066 (add-text-properties beg beg1
'(face org-block-begin-line
))
6067 (add-text-properties (min (point-max) (1+ end
)) (min (point-max) (1+ end1
))
6068 '(face org-block-end-line
))
6070 ((member dc1
'("+title:" "+author:" "+email:" "+date:"))
6071 (org-remove-flyspell-overlays-in
6073 (if (equal "+title:" dc1
) (match-end 2) (match-end 0)))
6074 (add-text-properties
6076 (if (member (intern (substring dc1
1 -
1)) org-hidden-keywords
)
6077 '(font-lock-fontified t invisible t
)
6078 '(font-lock-fontified t face org-document-info-keyword
)))
6079 (add-text-properties
6080 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6081 (if (string-equal dc1
"+title:")
6082 '(font-lock-fontified t face org-document-title
)
6083 '(font-lock-fontified t face org-document-info
))))
6084 ((string-prefix-p "+caption" dc1
)
6085 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6086 (remove-text-properties (match-beginning 0) (match-end 0)
6087 '(display t invisible t intangible t
))
6088 ;; Handle short captions.
6091 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6092 (add-text-properties (line-beginning-position) (match-end 1)
6093 '(font-lock-fontified t face org-meta-line
))
6094 (add-text-properties (match-end 0) (line-end-position)
6095 '(font-lock-fontified t face org-block
))
6097 ((member dc3
'(" " ""))
6098 (org-remove-flyspell-overlays-in beg
(match-end 0))
6099 (add-text-properties
6101 '(font-lock-fontified t face font-lock-comment-face
)))
6102 (t ;; just any other in-buffer setting, but not indented
6103 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6104 (remove-text-properties (match-beginning 0) (match-end 0)
6105 '(display t invisible t intangible t
))
6106 (add-text-properties beg
(match-end 0)
6107 '(font-lock-fontified t face org-meta-line
))
6110 (defun org-fontify-drawers (limit)
6112 (when (re-search-forward org-drawer-regexp limit t
)
6113 (add-text-properties
6114 (match-beginning 0) (match-end 0)
6115 '(font-lock-fontified t face org-special-keyword
))
6116 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6119 (defun org-fontify-macros (limit)
6121 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t
)
6122 (add-text-properties
6123 (match-beginning 0) (match-end 0)
6124 '(font-lock-fontified t face org-macro
))
6125 (when org-hide-macro-markers
6126 (add-text-properties (match-end 2) (match-beginning 2)
6128 (add-text-properties (match-beginning 1) (match-end 1)
6130 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6133 (defun org-activate-angle-links (limit)
6134 "Add text properties for angle links."
6135 (when (and (re-search-forward org-angle-link-re limit t
)
6136 (not (org-in-src-block-p)))
6137 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6138 (add-text-properties (match-beginning 0) (match-end 0)
6139 (list 'mouse-face
'highlight
6140 'keymap org-mouse-map
6141 'font-lock-multiline t
))
6142 (org-rear-nonsticky-at (match-end 0))
6145 (defun org-activate-footnote-links (limit)
6146 "Add text properties for footnotes."
6147 (let ((fn (org-footnote-next-reference-or-definition limit
)))
6149 (let* ((beg (nth 1 fn
))
6152 (referencep (/= (line-beginning-position) beg
)))
6153 (when (and referencep
(nth 3 fn
))
6156 (search-forward (or label
"fn:"))
6157 (org-remove-flyspell-overlays-in beg
(match-end 0))))
6158 (add-text-properties beg end
6159 (list 'mouse-face
'highlight
6160 'keymap org-mouse-map
6162 (if referencep
"Footnote reference"
6163 "Footnote definition")
6164 'font-lock-fontified t
6165 'font-lock-multiline t
6166 'face
'org-footnote
))))))
6168 (defun org-activate-bracket-links (limit)
6169 "Add text properties for bracketed links."
6170 (when (and (re-search-forward org-bracket-link-regexp limit t
)
6171 (not (org-in-src-block-p)))
6172 (let* ((hl (save-match-data
6173 (org-link-expand-abbrev (match-string-no-properties 1))))
6174 (type (save-match-data
6175 (and (string-match org-plain-link-re hl
)
6176 (match-string-no-properties 1 hl
))))
6177 (path (save-match-data
6178 (and (string-match org-plain-link-re hl
)
6179 (match-string-no-properties 2 hl
))))
6180 (link-start (match-beginning 0))
6181 (link-end (match-end 0))
6183 (help-echo (org-link-get-parameter type
:help-echo
))
6185 ((stringp help-echo
)
6187 ((functionp help-echo
)
6192 (org-link-unescape hl
))))))
6193 (link-face (org-link-get-parameter type
:face
))
6195 ;; A function that returns a face
6196 ((functionp link-face
)
6197 (funcall link-face path
))
6201 ;; An anonymous face
6207 (keymap (or (org-link-get-parameter type
:keymap
)
6209 (mouse-face (or (org-link-get-parameter type
:mouse-face
)
6211 (htmlize (org-link-get-parameter type
:htmlize-link
))
6213 ((functionp htmlize
)
6216 `(:uri
,(format "%s:%s" type path
)))))
6217 (activate-func (org-link-get-parameter type
:activate-func
))
6219 (ip (list 'invisible
(or
6220 (org-link-get-parameter type
:display
)
6224 'mouse-face mouse-face
6225 'font-lock-multiline t
6227 'htmlize-link htmlize-link
))
6229 (vp (list 'keymap keymap
6231 'mouse-face mouse-face
6232 'font-lock-multiline t
6234 'htmlize-link htmlize-link
)))
6235 ;; We need to remove the invisible property here. Table narrowing
6236 ;; may have made some of this invisible.
6237 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6238 (remove-text-properties (match-beginning 0) (match-end 0)
6242 (add-text-properties (match-beginning 0) (match-beginning 3) ip
)
6243 (org-rear-nonsticky-at (match-beginning 3))
6244 (add-text-properties (match-beginning 3) (match-end 3) vp
)
6245 (org-rear-nonsticky-at (match-end 3))
6246 (add-text-properties (match-end 3) (match-end 0) ip
)
6247 (org-rear-nonsticky-at (match-end 0)))
6248 (add-text-properties (match-beginning 0) (match-beginning 1) ip
)
6249 (org-rear-nonsticky-at (match-beginning 1))
6250 (add-text-properties (match-beginning 1) (match-end 1) vp
)
6251 (org-rear-nonsticky-at (match-end 1))
6252 (add-text-properties (match-end 1) (match-end 0) ip
)
6253 (org-rear-nonsticky-at (match-end 0)))
6255 (funcall activate-func link-start link-end path bracketp
))
6258 (defun org-activate-dates (limit)
6259 "Add text properties for dates."
6260 (when (and (re-search-forward org-tsr-regexp-both limit t
)
6261 (not (equal (char-before (match-beginning 0)) 91)))
6262 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6263 (add-text-properties (match-beginning 0) (match-end 0)
6264 (list 'mouse-face
'highlight
6265 'keymap org-mouse-map
))
6266 (org-rear-nonsticky-at (match-end 0))
6267 (when org-display-custom-times
6269 (org-display-custom-time (match-beginning 3) (match-end 3))
6270 (org-display-custom-time (match-beginning 1) (match-end 1))))
6273 (defvar-local org-target-link-regexp nil
6274 "Regular expression matching radio targets in plain text.")
6276 (defconst org-target-regexp
(let ((border "[^<>\n\r \t]"))
6277 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6278 border border border
))
6279 "Regular expression matching a link target.")
6281 (defconst org-radio-target-regexp
(format "<%s>" org-target-regexp
)
6282 "Regular expression matching a radio target.")
6284 (defconst org-any-target-regexp
6285 (format "%s\\|%s" org-radio-target-regexp org-target-regexp
)
6286 "Regular expression matching any target.")
6288 (defun org-activate-target-links (limit)
6289 "Add text properties for target matches."
6290 (when org-target-link-regexp
6291 (let ((case-fold-search t
))
6292 (when (re-search-forward org-target-link-regexp limit t
)
6293 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6294 (add-text-properties (match-beginning 1) (match-end 1)
6295 (list 'mouse-face
'highlight
6296 'keymap org-mouse-map
6297 'help-echo
"Radio target link"
6298 'org-linked-text t
))
6299 (org-rear-nonsticky-at (match-end 1))
6302 (defun org-update-radio-target-regexp ()
6303 "Find all radio targets in this file and update the regular expression.
6304 Also refresh fontification if needed."
6306 (let ((old-regexp org-target-link-regexp
)
6307 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6308 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6310 (org-with-wide-buffer
6311 (goto-char (point-min))
6313 (while (re-search-forward org-radio-target-regexp nil t
)
6314 ;; Make sure point is really within the object.
6316 (let ((obj (org-element-context)))
6317 (when (eq (org-element-type obj
) 'radio-target
)
6318 (cl-pushnew (org-element-property :value obj
) rtn
6321 (setq org-target-link-regexp
6326 (replace-regexp-in-string
6327 " +" "\\s-+" (regexp-quote x
) t t
))
6331 (unless (equal old-regexp org-target-link-regexp
)
6333 (let ((regexp (cond ((not old-regexp
) org-target-link-regexp
)
6334 ((not org-target-link-regexp
) old-regexp
)
6339 (substring re
(length before-re
)
6340 (- (length after-re
))))
6341 (list old-regexp org-target-link-regexp
)
6344 (org-with-wide-buffer
6345 (goto-char (point-min))
6346 (while (re-search-forward regexp nil t
)
6347 (org-element-cache-refresh (match-beginning 1)))))
6348 ;; Re fontify buffer.
6349 (when (memq 'radio org-highlight-links
)
6350 (org-restart-font-lock)))))
6352 (defun org-hide-wide-columns (limit)
6354 (setq s
(text-property-any (point) (or limit
(point-max))
6357 (setq e
(next-single-property-change s
'org-cwidth
))
6358 (add-text-properties s e
'(invisible org-cwidth
))
6362 (defvar org-latex-and-related-regexp nil
6363 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6365 (defun org-compute-latex-and-related-regexp ()
6366 "Compute regular expression for LaTeX, entities and sub/superscript.
6367 Result depends on variable `org-highlight-latex-and-related'."
6369 org-latex-and-related-regexp
6371 (cond ((not (memq 'script org-highlight-latex-and-related
)) nil
)
6372 ((eq org-use-sub-superscripts
'{})
6373 (list org-match-substring-with-braces-regexp
))
6374 (org-use-sub-superscripts (list org-match-substring-regexp
))))
6376 (when (memq 'latex org-highlight-latex-and-related
)
6377 (let ((matchers (plist-get org-format-latex-options
:matchers
)))
6380 (and (member (car x
) matchers
) (nth 1 x
)))
6381 org-latex-regexps
)))))
6383 (when (memq 'entities org-highlight-latex-and-related
)
6384 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6385 (mapconcat 'identity
(append re-latex re-entities re-sub
) "\\|"))))
6387 (defun org-do-latex-and-related (limit)
6388 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6389 LIMIT bounds the search for syntax to highlight. Stop at first
6390 highlighted object, if any. Return t if some highlighting was
6391 done, nil otherwise."
6392 (when (org-string-nw-p org-latex-and-related-regexp
)
6394 (while (re-search-forward org-latex-and-related-regexp limit t
)
6398 (memq f
'(org-code org-verbatim underline org-special-keyword
)))
6400 (goto-char (1+ (match-beginning 0)))
6401 (face-at-point nil t
)))
6402 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6406 (font-lock-prepend-text-property
6407 (+ offset
(match-beginning 0)) (match-end 0)
6408 'face
'org-latex-and-related
)
6409 (add-text-properties (+ offset
(match-beginning 0)) (match-end 0)
6410 '(font-lock-multiline t
)))
6414 (defun org-restart-font-lock ()
6415 "Restart `font-lock-mode', to force refontification."
6416 (when (and (boundp 'font-lock-mode
) font-lock-mode
)
6418 (font-lock-mode 1)))
6420 (defun org-activate-tags (limit)
6421 (when (re-search-forward
6422 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t
)
6423 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6424 (add-text-properties (match-beginning 1) (match-end 1)
6425 (list 'mouse-face
'highlight
6426 'keymap org-mouse-map
))
6427 (org-rear-nonsticky-at (match-end 1))
6430 (defun org-outline-level ()
6431 "Compute the outline level of the heading at point.
6433 If this is called at a normal headline, the level is the number
6434 of stars. Use `org-reduced-level' to remove the effect of
6435 `org-odd-levels'. Unlike to `org-current-level', this function
6436 takes into consideration inlinetasks."
6437 (org-with-wide-buffer
6439 (if (re-search-backward org-outline-regexp-bol nil t
)
6440 (1- (- (match-end 0) (match-beginning 0)))
6443 (defvar org-font-lock-keywords nil
)
6445 (defsubst org-re-property
(property &optional literal allow-null value
)
6446 "Return a regexp matching a PROPERTY line.
6448 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6449 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6450 non-nil, match properties even without a value.
6452 Match group 3 is set to the value when it exists. If there is no
6453 value and ALLOW-NULL is non-nil, it is set to the empty string.
6455 With optional argument VALUE, match only property lines with
6456 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6457 unless LITERAL is non-nil."
6460 (format "\\(?1::\\(?2:%s\\):\\)"
6461 (if literal property
(regexp-quote property
)))
6463 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6464 (if literal value
(regexp-quote value
))))
6466 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6468 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6470 (defconst org-property-re
6471 (org-re-property "\\S-+" 'literal t
)
6472 "Regular expression matching a property line.
6473 There are four matching groups:
6474 1: :PROPKEY: including the leading and trailing colon,
6475 2: PROPKEY without the leading and trailing colon,
6476 3: PROPVAL without leading or trailing spaces,
6477 4: the indentation of the current line,
6478 5: trailing whitespace.")
6480 (defvar org-font-lock-hook nil
6481 "Functions to be called for special font lock stuff.")
6483 (defvar org-font-lock-extra-keywords nil
) ;Dynamically scoped.
6485 (defvar org-font-lock-set-keywords-hook nil
6486 "Functions that can manipulate `org-font-lock-extra-keywords'.
6487 This is called after `org-font-lock-extra-keywords' is defined, but before
6488 it is installed to be used by font lock. This can be useful if something
6489 needs to be inserted at a specific position in the font-lock sequence.")
6491 (defun org-font-lock-hook (limit)
6492 "Run `org-font-lock-hook' within LIMIT."
6493 (run-hook-with-args 'org-font-lock-hook limit
))
6495 (defun org-set-font-lock-defaults ()
6496 "Set font lock defaults for the current buffer."
6497 (let* ((em org-fontify-emphasized-text
)
6498 (lk org-highlight-links
)
6499 (org-font-lock-extra-keywords
6502 '(org-font-lock-hook)
6504 `(,(if org-fontify-whole-heading-line
6505 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6506 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6507 (1 (org-get-level-face 1))
6508 (2 (org-get-level-face 2))
6509 (3 (org-get-level-face 3)))
6511 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6514 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t
))
6515 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t
))
6516 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t
))
6517 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t
))
6519 '(org-fontify-drawers)
6521 (list org-property-re
6522 '(1 'org-special-keyword t
)
6523 '(3 'org-property-value t
))
6525 (when (memq 'tag lk
) '(org-activate-tags (1 'org-tag prepend
)))
6526 (when (memq 'angle lk
) '(org-activate-angle-links (0 'org-link t
)))
6527 (when (memq 'plain lk
) '(org-activate-plain-links (0 'org-link
)))
6528 (when (memq 'bracket lk
) '(org-activate-bracket-links (0 'org-link
)))
6529 (when (memq 'radio lk
) '(org-activate-target-links (1 'org-link t
)))
6530 (when (memq 'date lk
) '(org-activate-dates (0 'org-date t
)))
6531 (when (memq 'footnote lk
) '(org-activate-footnote-links))
6533 (list org-any-target-regexp
'(0 'org-target t
))
6535 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t
))
6537 '(org-fontify-macros)
6538 '(org-hide-wide-columns (0 nil append
))
6540 (list (format org-heading-keyword-regexp-format
6542 '(2 (org-get-todo-face 2) t
))
6544 (if org-fontify-done-headline
6545 (list (format org-heading-keyword-regexp-format
6548 (mapconcat 'regexp-quote org-done-keywords
"\\|")
6550 '(2 'org-headline-done t
))
6553 '(org-font-lock-add-priority-faces)
6555 '(org-font-lock-add-tag-faces)
6557 (when (and org-group-tags org-tag-groups-alist
)
6558 (list (concat org-outline-regexp-bol
".+\\(:"
6559 (regexp-opt (mapcar 'car org-tag-groups-alist
))
6561 '(1 'org-tag-group prepend
)))
6563 (list (concat "\\<" org-deadline-string
) '(0 'org-special-keyword t
))
6564 (list (concat "\\<" org-scheduled-string
) '(0 'org-special-keyword t
))
6565 (list (concat "\\<" org-closed-string
) '(0 'org-special-keyword t
))
6566 (list (concat "\\<" org-clock-string
) '(0 'org-special-keyword t
))
6568 (when em
'(org-do-emphasis-faces))
6570 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6571 1 'org-checkbox prepend
)
6572 (when (cdr (assq 'checkbox org-list-automatic-rules
))
6573 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6574 (0 (org-get-checkbox-statistics-face) t
)))
6575 ;; Description list items
6576 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6577 1 'org-list-dt prepend
)
6578 ;; ARCHIVEd headings
6580 org-outline-regexp-bol
6581 "\\(.*:" org-archive-tag
":.*\\)")
6582 '(1 'org-archived prepend
))
6584 '(org-do-latex-and-related)
6585 '(org-fontify-entities)
6586 '(org-raise-scripts)
6588 '(org-activate-code (1 'org-code t
))
6591 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6594 '(9 'org-special-keyword t
))
6595 ;; Blocks and meta lines
6596 '(org-fontify-meta-lines-and-blocks))))
6597 (setq org-font-lock-extra-keywords
(delq nil org-font-lock-extra-keywords
))
6598 (run-hooks 'org-font-lock-set-keywords-hook
)
6599 ;; Now set the full font-lock-keywords
6600 (setq-local org-font-lock-keywords org-font-lock-extra-keywords
)
6601 (setq-local font-lock-defaults
6602 '(org-font-lock-keywords t nil nil backward-paragraph
))
6603 (kill-local-variable 'font-lock-keywords
)
6606 (defun org-toggle-pretty-entities ()
6607 "Toggle the composition display of entities as UTF8 characters."
6609 (setq-local org-pretty-entities
(not org-pretty-entities
))
6610 (org-restart-font-lock)
6611 (if org-pretty-entities
6612 (message "Entities are now displayed as UTF8 characters")
6615 (decompose-region (point-min) (point-max))
6616 (message "Entities are now displayed as plain text"))))
6618 (defvar-local org-custom-properties-overlays nil
6619 "List of overlays used for custom properties.")
6621 (defun org-toggle-custom-properties-visibility ()
6622 "Display or hide properties in `org-custom-properties'."
6624 (if org-custom-properties-overlays
6625 (progn (mapc #'delete-overlay org-custom-properties-overlays
)
6626 (setq org-custom-properties-overlays nil
))
6627 (when org-custom-properties
6628 (org-with-wide-buffer
6629 (goto-char (point-min))
6630 (let ((regexp (org-re-property (regexp-opt org-custom-properties
) t t
)))
6631 (while (re-search-forward regexp nil t
)
6632 (let ((end (cdr (save-match-data (org-get-property-block)))))
6633 (when (and end
(< (point) end
))
6634 ;; Hide first custom property in current drawer.
6635 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6636 (overlay-put o
'invisible t
)
6637 (overlay-put o
'org-custom-property t
)
6638 (push o org-custom-properties-overlays
))
6639 ;; Hide additional custom properties in the same drawer.
6640 (while (re-search-forward regexp end t
)
6641 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6642 (overlay-put o
'invisible t
)
6643 (overlay-put o
'org-custom-property t
)
6644 (push o org-custom-properties-overlays
)))))
6645 ;; Each entry is limited to a single property drawer.
6646 (outline-next-heading)))))))
6648 (defun org-fontify-entities (limit)
6649 "Find an entity to fontify."
6651 (when org-pretty-entities
6653 ;; "\_ "-family is left out on purpose. Only the first one,
6654 ;; i.e., "\_ ", could be fontified anyway, and it would be
6655 ;; confusing when adding a second white space character.
6656 (while (re-search-forward
6657 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6659 (when (and (not (org-at-comment-p))
6660 (setq ee
(org-entity-get (match-string 1)))
6661 (= (length (nth 6 ee
)) 1))
6662 (let* ((end (if (equal (match-string 2) "{}")
6665 (add-text-properties
6666 (match-beginning 0) end
6667 (list 'font-lock-fontified t
))
6668 (compose-region (match-beginning 0) end
6674 (defun org-fontify-like-in-org-mode (s &optional odd-levels
)
6675 "Fontify string S like in Org mode."
6678 (let ((org-odd-levels-only odd-levels
))
6680 (org-font-lock-ensure)
6686 (defun org-get-level-face (n)
6687 "Get the right face for match N in font-lock matching of headlines."
6688 (setq org-l
(- (match-end 2) (match-beginning 1) 1))
6689 (when org-odd-levels-only
(setq org-l
(1+ (/ org-l
2))))
6690 (if org-cycle-level-faces
6691 (setq org-f
(nth (%
(1- org-l
) org-n-level-faces
) org-level-faces
))
6692 (setq org-f
(nth (1- (min org-l org-n-level-faces
)) org-level-faces
)))
6694 ((eq n
1) (if org-hide-leading-stars
'org-hide org-f
))
6696 (t (unless org-level-color-stars-only org-f
))))
6698 (defun org-face-from-face-or-color (context inherit face-or-color
)
6699 "Create a face list that inherits INHERIT, but sets the foreground color.
6700 When FACE-OR-COLOR is not a string, just return it."
6701 (if (stringp face-or-color
)
6702 (list :inherit inherit
6703 (cdr (assoc context org-faces-easy-properties
))
6707 (defun org-get-todo-face (kwd)
6708 "Get the right face for a TODO keyword KWD.
6709 If KWD is a number, get the corresponding match group."
6710 (when (numberp kwd
) (setq kwd
(match-string kwd
)))
6711 (or (org-face-from-face-or-color
6712 'todo
'org-todo
(cdr (assoc kwd org-todo-keyword-faces
)))
6713 (and (member kwd org-done-keywords
) 'org-done
)
6716 (defun org-get-priority-face (priority)
6717 "Get the right face for PRIORITY.
6718 PRIORITY is a character."
6719 (or (org-face-from-face-or-color
6720 'priority
'org-priority
(cdr (assq priority org-priority-faces
)))
6723 (defun org-get-tag-face (tag)
6724 "Get the right face for TAG.
6725 If TAG is a number, get the corresponding match group."
6726 (let ((tag (if (wholenump tag
) (match-string tag
) tag
)))
6727 (or (org-face-from-face-or-color
6728 'tag
'org-tag
(cdr (assoc tag org-tag-faces
)))
6731 (defun org-font-lock-add-priority-faces (limit)
6732 "Add the special priority faces."
6733 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t
)
6734 (add-text-properties
6735 (match-beginning 1) (match-end 1)
6736 (list 'face
(org-get-priority-face (string-to-char (match-string 2)))
6737 'font-lock-fontified t
))))
6739 (defun org-font-lock-add-tag-faces (limit)
6740 "Add the special tag faces."
6741 (when (and org-tag-faces org-tags-special-faces-re
)
6742 (while (re-search-forward org-tags-special-faces-re limit t
)
6743 (add-text-properties (match-beginning 1) (match-end 1)
6744 (list 'face
(org-get-tag-face 1)
6745 'font-lock-fontified t
))
6746 (backward-char 1))))
6748 (defun org-unfontify-region (beg end
&optional _maybe_loudly
)
6749 "Remove fontification and activation overlays from links."
6750 (font-lock-default-unfontify-region beg end
)
6751 (let* ((buffer-undo-list t
)
6752 (inhibit-read-only t
) (inhibit-point-motion-hooks t
)
6753 (inhibit-modification-hooks t
)
6754 deactivate-mark buffer-file-name buffer-file-truename
)
6755 (decompose-region beg end
)
6756 (remove-text-properties beg end
6757 '(mouse-face t keymap t org-linked-text t
6758 invisible t intangible t
6760 (org-remove-font-lock-display-properties beg end
)))
6762 (defconst org-script-display
'(((raise -
0.3) (height 0.7))
6763 ((raise 0.3) (height 0.7))
6766 "Display properties for showing superscripts and subscripts.")
6768 (defun org-remove-font-lock-display-properties (beg end
)
6769 "Remove specific display properties that have been added by font lock.
6770 The will remove the raise properties that are used to show superscripts
6774 (setq next
(next-single-property-change beg
'display nil end
)
6775 prop
(get-text-property beg
'display
))
6776 (when (member prop org-script-display
)
6777 (put-text-property beg next
'display nil
))
6780 (defun org-raise-scripts (limit)
6781 "Add raise properties to sub/superscripts."
6782 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6784 (if (eq org-use-sub-superscripts t
)
6785 org-match-substring-regexp
6786 org-match-substring-with-braces-regexp
)
6788 (let* ((pos (point)) table-p comment-p
6789 (mpos (match-beginning 3))
6790 (emph-p (get-text-property mpos
'org-emphasis
))
6791 (link-p (get-text-property mpos
'mouse-face
))
6792 (keyw-p (eq 'org-special-keyword
(get-text-property mpos
'face
))))
6793 (goto-char (point-at-bol))
6794 (setq table-p
(looking-at-p org-table-dataline-regexp
)
6795 comment-p
(looking-at-p "^[ \t]*#[ +]"))
6798 (when (member (char-after) '(?_ ?^
)) (goto-char (1- pos
)))
6799 (unless (or comment-p emph-p link-p keyw-p
)
6800 (put-text-property (match-beginning 3) (match-end 0)
6802 (if (equal (char-after (match-beginning 2)) ?^
)
6803 (nth (if table-p
3 1) org-script-display
)
6804 (nth (if table-p
2 0) org-script-display
)))
6805 (add-text-properties (match-beginning 2) (match-end 2)
6807 'org-dwidth t
'org-dwidth-n
1))
6808 (if (and (eq (char-after (match-beginning 3)) ?
{)
6809 (eq (char-before (match-end 3)) ?
}))
6811 (add-text-properties
6812 (match-beginning 3) (1+ (match-beginning 3))
6813 (list 'invisible t
'org-dwidth t
'org-dwidth-n
1))
6814 (add-text-properties
6815 (1- (match-end 3)) (match-end 3)
6816 (list 'invisible t
'org-dwidth t
'org-dwidth-n
1)))))
6819 ;;;; Visibility cycling, including org-goto and indirect buffer
6823 (defvar-local org-cycle-global-status nil
)
6824 (put 'org-cycle-global-status
'org-state t
)
6825 (defvar-local org-cycle-subtree-status nil
)
6826 (put 'org-cycle-subtree-status
'org-state t
)
6828 (defvar org-inlinetask-min-level
)
6830 (defun org-unlogged-message (&rest args
)
6831 "Display a message, but avoid logging it in the *Messages* buffer."
6832 (let ((message-log-max nil
))
6833 (apply 'message args
)))
6836 (defun org-cycle (&optional arg
)
6837 "TAB-action and visibility cycling for Org mode.
6839 This is the command invoked in Org mode by the `TAB' key. Its main
6840 purpose is outline visibility cycling, but it also invokes other actions
6841 in special contexts.
6843 When this function is called with a `\\[universal-argument]' prefix, rotate \
6845 buffer through 3 states (global cycling)
6846 1. OVERVIEW: Show only top-level headlines.
6847 2. CONTENTS: Show all headlines of all levels, but no body text.
6848 3. SHOW ALL: Show everything.
6850 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6851 switch to the startup visibility,
6852 determined by the variable `org-startup-folded', and by any VISIBILITY
6853 properties in the buffer.
6855 With a `\\[universal-argument] \\[universal-argument] \
6856 \\[universal-argument]' prefix argument, show the entire buffer, including
6859 When inside a table, re-align the table and move to the next field.
6861 When point is at the beginning of a headline, rotate the subtree started
6862 by this line through 3 different states (local cycling)
6863 1. FOLDED: Only the main headline is shown.
6864 2. CHILDREN: The main headline and the direct children are shown.
6865 From this state, you can move to one of the children
6866 and zoom in further.
6867 3. SUBTREE: Show the entire subtree, including body text.
6868 If there is no subtree, switch directly from CHILDREN to FOLDED.
6870 When point is at the beginning of an empty headline and the variable
6871 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6872 of the headline by demoting and promoting it to likely levels. This
6873 speeds up creation document structure by pressing `TAB' once or several
6874 times right after creating a new headline.
6876 When there is a numeric prefix, go up to a heading with level ARG, do
6877 a `show-subtree' and return to the previous cursor position. If ARG
6878 is negative, go up that many levels.
6880 When point is not at the beginning of a headline, execute the global
6881 binding for `TAB', which is re-indenting the line. See the option
6882 `org-cycle-emulate-tab' for details.
6884 As a special case, if point is at the beginning of the buffer and there is
6885 no headline in line 1, this function will act as if called with prefix arg
6886 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6887 prefix arg, but only
6888 if the variable `org-cycle-global-at-bob' is t."
6890 (org-load-modules-maybe)
6891 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook
)
6892 (and org-cycle-level-after-item
/entry-creation
6893 (or (org-cycle-level)
6894 (org-cycle-item-indentation))))
6896 (or org-cycle-max-level
6897 (and (boundp 'org-inlinetask-min-level
)
6898 org-inlinetask-min-level
6899 (1- org-inlinetask-min-level
))))
6900 (nstars (and limit-level
6901 (if org-odd-levels-only
6902 (and limit-level
(1- (* limit-level
2)))
6905 (if (not (derived-mode-p 'org-mode
))
6907 (concat "\\*" (if nstars
(format "\\{1,%d\\} " nstars
) "+ "))))
6908 (bob-special (and org-cycle-global-at-bob
(not arg
) (bobp)
6909 (not (looking-at org-outline-regexp
))))
6912 (delq 'org-optimize-window-after-visibility-change
6913 (copy-sequence org-cycle-hook
))
6920 (setq last-command
'dummy
)
6921 (org-set-startup-visibility)
6922 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6926 (org-unlogged-message "Entire buffer visible, including drawers"))
6928 ((equal arg
'(4)) (org-cycle-internal-global))
6930 ;; Try hiding block at point.
6931 ((org-hide-block-toggle-maybe))
6933 ;; Try cdlatex TAB completion
6934 ((org-try-cdlatex-tab))
6936 ;; Table: enter it or move to the next field.
6937 ((org-at-table-p 'any
)
6938 (if (org-at-table.el-p
)
6939 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6940 Use `\\[org-edit-special]' to edit table.el tables"))
6941 (if arg
(org-table-edit-field t
)
6942 (org-table-justify-field-maybe)
6943 (call-interactively 'org-table-next-field
))))
6945 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook
))
6947 ;; Global cycling: delegate to `org-cycle-internal-global'.
6948 (bob-special (org-cycle-internal-global))
6950 ;; Drawers: delegate to `org-flag-drawer'.
6952 (beginning-of-line 1)
6953 (looking-at org-drawer-regexp
))
6954 (org-flag-drawer ; toggle block visibility
6955 (not (get-char-property (match-end 0) 'invisible
))))
6957 ;; Show-subtree, ARG levels up from here.
6960 (org-back-to-heading)
6961 (outline-up-heading (if (< arg
0) (- arg
)
6962 (- (funcall outline-level
) arg
)))
6963 (org-show-subtree)))
6965 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6966 ((and (featurep 'org-inlinetask
)
6967 (org-inlinetask-at-task-p)
6968 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6969 (org-inlinetask-toggle-visibility))
6971 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6972 ((and (or (and org-cycle-include-plain-lists
(org-at-item-p))
6973 (save-excursion (move-beginning-of-line 1)
6974 (looking-at org-outline-regexp
)))
6975 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6976 (org-cycle-internal-local))
6978 ;; From there: TAB emulation and template completion.
6979 (buffer-read-only (org-back-to-heading))
6981 ((run-hook-with-args-until-success
6982 'org-tab-after-check-for-cycling-hook
))
6984 ((org-try-structure-completion))
6986 ((run-hook-with-args-until-success
6987 'org-tab-before-tab-emulation-hook
))
6989 ((and (eq org-cycle-emulate-tab
'exc-hl-bol
)
6991 (not (looking-at org-outline-regexp
))))
6992 (call-interactively (global-key-binding "\t")))
6994 ((if (and (memq org-cycle-emulate-tab
'(white whitestart
))
6995 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6996 (or (and (eq org-cycle-emulate-tab
'white
)
6997 (= (match-end 0) (point-at-eol)))
6998 (and (eq org-cycle-emulate-tab
'whitestart
)
6999 (>= (match-end 0) pos
))))
7001 (eq org-cycle-emulate-tab t
))
7002 (call-interactively (global-key-binding "\t")))
7005 (org-back-to-heading)
7008 (defun org-cycle-internal-global ()
7009 "Do the global cycling action."
7010 ;; Hack to avoid display of messages for .org attachments in Gnus
7011 (let ((ga (string-match "\\*fontification" (buffer-name))))
7013 ((and (eq last-command this-command
)
7014 (eq org-cycle-global-status
'overview
))
7015 ;; We just created the overview - now do table of contents
7016 ;; This can be slow in very large buffers, so indicate action
7017 (run-hook-with-args 'org-pre-cycle-hook
'contents
)
7018 (unless ga
(org-unlogged-message "CONTENTS..."))
7020 (unless ga
(org-unlogged-message "CONTENTS...done"))
7021 (setq org-cycle-global-status
'contents
)
7022 (run-hook-with-args 'org-cycle-hook
'contents
))
7024 ((and (eq last-command this-command
)
7025 (eq org-cycle-global-status
'contents
))
7026 ;; We just showed the table of contents - now show everything
7027 (run-hook-with-args 'org-pre-cycle-hook
'all
)
7029 (unless ga
(org-unlogged-message "SHOW ALL"))
7030 (setq org-cycle-global-status
'all
)
7031 (run-hook-with-args 'org-cycle-hook
'all
))
7034 ;; Default action: go to overview
7035 (run-hook-with-args 'org-pre-cycle-hook
'overview
)
7037 (unless ga
(org-unlogged-message "OVERVIEW"))
7038 (setq org-cycle-global-status
'overview
)
7039 (run-hook-with-args 'org-cycle-hook
'overview
)))))
7041 (defvar org-called-with-limited-levels nil
7042 "Non-nil when `org-with-limited-levels' is currently active.")
7044 (defun org-cycle-internal-local ()
7045 "Do the local cycling action."
7046 (let ((goal-column 0) eoh eol eos has-children children-skipped struct
)
7047 ;; First, determine end of headline (EOH), end of subtree or item
7048 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7053 (setq struct
(org-list-struct))
7054 (setq eoh
(point-at-eol))
7055 (setq eos
(org-list-get-item-end-before-blank (point) struct
))
7056 (setq has-children
(org-list-has-child-p (point) struct
)))
7057 (org-back-to-heading)
7058 (setq eoh
(save-excursion (outline-end-of-heading) (point)))
7059 (setq eos
(save-excursion (org-end-of-subtree t t
)
7060 (when (bolp) (backward-char)) (point)))
7063 (let ((level (funcall outline-level
)))
7064 (outline-next-heading)
7065 (and (org-at-heading-p t
)
7066 (> (funcall outline-level
) level
))))
7068 (org-list-search-forward (org-item-beginning-re) eos t
)))))
7069 ;; Determine end invisible part of buffer (EOL)
7070 (beginning-of-line 2)
7071 (while (and (not (eobp)) ;This is like `next-line'.
7072 (get-char-property (1- (point)) 'invisible
))
7073 (goto-char (next-single-char-property-change (point) 'invisible
))
7074 (and (eolp) (beginning-of-line 2)))
7076 ;; Find out what to do next and set `this-command'
7079 ;; Nothing is hidden behind this heading
7080 (unless (org-before-first-heading-p)
7081 (run-hook-with-args 'org-pre-cycle-hook
'empty
))
7082 (org-unlogged-message "EMPTY ENTRY")
7083 (setq org-cycle-subtree-status nil
)
7086 (outline-next-heading)
7087 (when (outline-invisible-p) (org-flag-heading nil
))))
7088 ((and (or (>= eol eos
)
7089 (not (string-match "\\S-" (buffer-substring eol eos
))))
7091 (not (setq children-skipped
7092 org-cycle-skip-children-state-if-no-children
))))
7093 ;; Entire subtree is hidden in one line: children view
7094 (unless (org-before-first-heading-p)
7095 (run-hook-with-args 'org-pre-cycle-hook
'children
))
7097 (org-list-set-item-visibility (point-at-bol) struct
'children
)
7099 (org-with-limited-levels (org-show-children))
7100 ;; FIXME: This slows down the func way too much.
7101 ;; How keep drawers hidden in subtree anyway?
7102 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7103 ;; (org-cycle-hide-drawers 'subtree))
7105 ;; Fold every list in subtree to top-level items.
7106 (when (eq org-cycle-include-plain-lists
'integrate
)
7108 (org-back-to-heading)
7109 (while (org-list-search-forward (org-item-beginning-re) eos t
)
7110 (beginning-of-line 1)
7111 (let* ((struct (org-list-struct))
7112 (prevs (org-list-prevs-alist struct
))
7113 (end (org-list-get-bottom-point struct
)))
7114 (dolist (e (org-list-get-all-items (point) struct prevs
))
7115 (org-list-set-item-visibility e struct
'folded
))
7116 (goto-char (if (< end eos
) end eos
)))))))
7117 (org-unlogged-message "CHILDREN")
7120 (outline-next-heading)
7121 (when (outline-invisible-p) (org-flag-heading nil
)))
7122 (setq org-cycle-subtree-status
'children
)
7123 (unless (org-before-first-heading-p)
7124 (run-hook-with-args 'org-cycle-hook
'children
)))
7125 ((or children-skipped
7126 (and (eq last-command this-command
)
7127 (eq org-cycle-subtree-status
'children
)))
7128 ;; We just showed the children, or no children are there,
7129 ;; now show everything.
7130 (unless (org-before-first-heading-p)
7131 (run-hook-with-args 'org-pre-cycle-hook
'subtree
))
7132 (outline-flag-region eoh eos nil
)
7133 (org-unlogged-message
7134 (if children-skipped
"SUBTREE (NO CHILDREN)" "SUBTREE"))
7135 (setq org-cycle-subtree-status
'subtree
)
7136 (unless (org-before-first-heading-p)
7137 (run-hook-with-args 'org-cycle-hook
'subtree
)))
7139 ;; Default action: hide the subtree.
7140 (run-hook-with-args 'org-pre-cycle-hook
'folded
)
7141 (outline-flag-region eoh eos t
)
7142 (org-unlogged-message "FOLDED")
7143 (setq org-cycle-subtree-status
'folded
)
7144 (unless (org-before-first-heading-p)
7145 (run-hook-with-args 'org-cycle-hook
'folded
))))))
7148 (defun org-global-cycle (&optional arg
)
7149 "Cycle the global visibility. For details see `org-cycle'.
7150 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7151 With a numeric prefix, show all headlines up to that level."
7153 (let ((org-cycle-include-plain-lists
7154 (if (derived-mode-p 'org-mode
) org-cycle-include-plain-lists nil
)))
7158 (outline-hide-sublevels arg
)
7159 (setq org-cycle-global-status
'contents
))
7161 (org-set-startup-visibility)
7162 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7164 (org-cycle '(4))))))
7166 (defun org-set-startup-visibility ()
7167 "Set the visibility required by startup options and properties."
7169 ((eq org-startup-folded t
)
7171 ((eq org-startup-folded
'content
)
7173 ((or (eq org-startup-folded
'showeverything
)
7174 (eq org-startup-folded nil
))
7175 (outline-show-all)))
7176 (unless (eq org-startup-folded
'showeverything
)
7177 (when org-hide-block-startup
(org-hide-block-all))
7178 (org-set-visibility-according-to-property 'no-cleanup
)
7179 (org-cycle-hide-archived-subtrees 'all
)
7180 (org-cycle-hide-drawers 'all
)
7181 (org-cycle-show-empty-lines t
)))
7183 (defun org-set-visibility-according-to-property (&optional no-cleanup
)
7184 "Switch subtree visibilities according to :VISIBILITY: property."
7186 (org-with-wide-buffer
7187 (goto-char (point-min))
7188 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t
)
7189 (if (not (org-at-property-p)) (outline-next-heading)
7190 (let ((state (match-string 3)))
7192 (org-back-to-heading t
)
7193 (outline-hide-subtree)
7196 ((equal state
"folded")
7197 (outline-hide-subtree))
7198 ((equal state
"children")
7199 (org-show-hidden-entry)
7200 (org-show-children))
7201 ((equal state
"content")
7204 (org-narrow-to-subtree)
7206 ((member state
'("all" "showall"))
7207 (outline-show-subtree)))))))
7209 (org-cycle-hide-archived-subtrees 'all
)
7210 (org-cycle-hide-drawers 'all
)
7211 (org-cycle-show-empty-lines 'all
))))
7213 ;; This function uses outline-regexp instead of the more fundamental
7214 ;; org-outline-regexp so that org-cycle-global works outside of Org
7215 ;; buffers, where outline-regexp is needed.
7216 (defun org-overview ()
7217 "Switch to overview mode, showing only top-level headlines.
7218 This shows all headlines with a level equal or greater than the level
7219 of the first headline in the buffer. This is important, because if the
7220 first headline is not level one, then (hide-sublevels 1) gives confusing
7226 (goto-char (point-min))
7227 (when (re-search-forward (concat "^" outline-regexp
) nil t
)
7228 (goto-char (match-beginning 0))
7229 (funcall outline-level
)))))
7230 (and level
(outline-hide-sublevels level
)))))
7232 (defun org-content (&optional arg
)
7233 "Show all headlines in the buffer, like a table of contents.
7234 With numerical argument N, show content up to level N."
7238 ;; Visit all headings and show their offspring
7239 (and (integerp arg
) (org-overview))
7240 (goto-char (point-max))
7242 (while (and (progn (condition-case nil
7243 (outline-previous-visible-heading 1)
7244 (error (goto-char (point-min))))
7246 (looking-at org-outline-regexp
))
7248 (org-show-children (1- arg
))
7249 (outline-show-branches))
7250 (when (bobp) (throw 'exit nil
))))))
7252 (defun org-optimize-window-after-visibility-change (state)
7253 "Adjust the window after a change in outline visibility.
7254 This function is the default value of the hook `org-cycle-hook'."
7255 (when (get-buffer-window (current-buffer))
7257 ((eq state
'content
) nil
)
7258 ((eq state
'all
) nil
)
7259 ((eq state
'folded
) nil
)
7260 ((eq state
'children
) (or (org-subtree-end-visible-p) (recenter 1)))
7261 ((eq state
'subtree
) (or (org-subtree-end-visible-p) (recenter 1))))))
7263 (defun org-remove-empty-overlays-at (pos)
7264 "Remove outline overlays that do not contain non-white stuff."
7265 (dolist (o (overlays-at pos
))
7266 (and (eq 'outline
(overlay-get o
'invisible
))
7267 (not (string-match "\\S-" (buffer-substring (overlay-start o
)
7269 (delete-overlay o
))))
7271 (defun org-clean-visibility-after-subtree-move ()
7272 "Fix visibility issues after moving a subtree."
7273 ;; First, find a reasonable region to look at:
7274 ;; Start two siblings above, end three below
7275 (let* ((beg (save-excursion
7276 (and (org-get-last-sibling)
7277 (org-get-last-sibling))
7279 (end (save-excursion
7280 (and (org-get-next-sibling)
7281 (org-get-next-sibling)
7282 (org-get-next-sibling))
7283 (if (org-at-heading-p)
7286 (level (looking-at "\\*+"))
7287 (re (when level
(concat "^" (regexp-quote (match-string 0)) " "))))
7290 (narrow-to-region beg end
)
7292 ;; Properly fold already folded siblings
7293 (goto-char (point-min))
7294 (while (re-search-forward re nil t
)
7295 (when (and (not (outline-invisible-p))
7297 (goto-char (point-at-eol)) (outline-invisible-p)))
7298 (outline-hide-entry))))
7299 (org-cycle-show-empty-lines 'overview
)
7300 (org-cycle-hide-drawers 'overview
)))))
7302 (defun org-cycle-show-empty-lines (state)
7303 "Show empty lines above all visible headlines.
7304 The region to be covered depends on STATE when called through
7305 `org-cycle-hook'. Lisp program can use t for STATE to get the
7306 entire buffer covered. Note that an empty line is only shown if there
7307 are at least `org-cycle-separator-lines' empty lines before the headline."
7308 (when (/= org-cycle-separator-lines
0)
7310 (let* ((n (abs org-cycle-separator-lines
))
7312 ((= n
1) "\\(\n[ \t]*\n\\*+\\) ")
7313 ((= n
2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7314 (t (let ((ns (number-to-string (- n
2))))
7315 (concat "^\\(?:[ \t]*\n\\)\\{" ns
"," ns
"\\}"
7316 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7319 ((memq state
'(overview contents t
))
7320 (setq beg
(point-min) end
(point-max)))
7321 ((memq state
'(children folded
))
7323 end
(progn (org-end-of-subtree t t
)
7324 (line-beginning-position 2)))))
7327 (while (re-search-forward re end t
)
7328 (unless (get-char-property (match-end 1) 'invisible
)
7329 (let ((e (match-end 1))
7330 (b (if (>= org-cycle-separator-lines
0)
7333 (goto-char (match-beginning 0))
7334 (skip-chars-backward " \t\n")
7335 (line-end-position)))))
7336 (outline-flag-region b e nil
))))))))
7337 ;; Never hide empty lines at the end of the file.
7339 (goto-char (point-max))
7340 (outline-previous-heading)
7341 (outline-end-of-heading)
7342 (when (and (looking-at "[ \t\n]+")
7343 (= (match-end 0) (point-max)))
7344 (outline-flag-region (point) (match-end 0) nil
))))
7346 (defun org-show-empty-lines-in-parent ()
7347 "Move to the parent and re-show empty lines before visible headlines."
7349 (let ((context (if (org-up-heading-safe) 'children
'overview
)))
7350 (org-cycle-show-empty-lines context
))))
7352 (defun org-files-list ()
7353 "Return `org-agenda-files' list, plus all open Org files.
7354 This is useful for operations that need to scan all of a user's
7355 open and agenda-wise Org files."
7356 (let ((files (mapcar 'expand-file-name
(org-agenda-files))))
7357 (dolist (buf (buffer-list))
7358 (with-current-buffer buf
7359 (when (and (derived-mode-p 'org-mode
) (buffer-file-name))
7360 (cl-pushnew (expand-file-name (buffer-file-name)) files
))))
7363 (defsubst org-entry-beginning-position
()
7364 "Return the beginning position of the current entry."
7365 (save-excursion (org-back-to-heading t
) (point)))
7367 (defsubst org-entry-end-position
()
7368 "Return the end position of the current entry."
7369 (save-excursion (outline-next-heading) (point)))
7371 (defun org-cycle-hide-drawers (state &optional exceptions
)
7372 "Re-hide all drawers after a visibility state change.
7373 When non-nil, optional argument EXCEPTIONS is a list of strings
7374 specifying which drawers should not be hidden."
7375 (when (and (derived-mode-p 'org-mode
)
7376 (not (memq state
'(overview folded contents
))))
7378 (let* ((globalp (memq state
'(contents all
)))
7379 (beg (if globalp
(point-min) (point)))
7380 (end (if globalp
(point-max)
7381 (if (eq state
'children
)
7382 (save-excursion (outline-next-heading) (point))
7383 (org-end-of-subtree t
)))))
7385 (while (re-search-forward org-drawer-regexp
(max end
(point)) t
)
7386 (unless (member-ignore-case (match-string 1) exceptions
)
7387 (let ((drawer (org-element-at-point)))
7388 (when (memq (org-element-type drawer
) '(drawer property-drawer
))
7389 (org-flag-drawer t drawer
)
7390 ;; Make sure to skip drawer entirely or we might flag
7391 ;; it another time when matching its ending line with
7392 ;; `org-drawer-regexp'.
7393 (goto-char (org-element-property :end drawer
))))))))))
7395 (defun org-flag-drawer (flag &optional element
)
7396 "When FLAG is non-nil, hide the drawer we are at.
7397 Otherwise make it visible. When optional argument ELEMENT is
7398 a parsed drawer, as returned by `org-element-at-point', hide or
7399 show that drawer instead."
7400 (let ((drawer (or element
7401 (and (save-excursion
7403 (looking-at-p org-drawer-regexp
))
7404 (org-element-at-point)))))
7405 (when (memq (org-element-type drawer
) '(drawer property-drawer
))
7406 (let ((post (org-element-property :post-affiliated drawer
)))
7408 (outline-flag-region
7409 (progn (goto-char post
) (line-end-position))
7410 (progn (goto-char (org-element-property :end drawer
))
7411 (skip-chars-backward " \r\t\n")
7412 (line-end-position))
7414 ;; When the drawer is hidden away, make sure point lies in
7415 ;; a visible part of the buffer.
7416 (when (and flag
(> (line-beginning-position) post
))
7417 (goto-char post
))))))
7419 (defun org-subtree-end-visible-p ()
7420 "Is the end of the current subtree visible?"
7421 (pos-visible-in-window-p
7422 (save-excursion (org-end-of-subtree t
) (point))))
7424 (defun org-first-headline-recenter ()
7425 "Move cursor to the first headline and recenter the headline."
7426 (let ((window (get-buffer-window)))
7428 (goto-char (point-min))
7429 (when (re-search-forward (concat "^\\(" org-outline-regexp
"\\)") nil t
)
7430 (set-window-start window
(line-beginning-position))))))
7432 ;;; Saving and restoring visibility
7434 (defun org-outline-overlay-data (&optional use-markers
)
7435 "Return a list of the locations of all outline overlays.
7436 These are overlays with the `invisible' property value `outline'.
7437 The return value is a list of cons cells, with start and stop
7438 positions for each overlay.
7439 If USE-MARKERS is set, return the positions as markers."
7441 (org-with-wide-buffer
7444 (when (eq (overlay-get o
'invisible
) 'outline
)
7445 (setq beg
(overlay-start o
)
7446 end
(overlay-end o
))
7447 (and beg end
(> end beg
)
7449 (cons (copy-marker beg
)
7450 (copy-marker end t
))
7452 (overlays-in (point-min) (point-max)))))))
7454 (defun org-set-outline-overlay-data (data)
7455 "Create visibility overlays for all positions in DATA.
7456 DATA should have been made by `org-outline-overlay-data'."
7457 (org-with-wide-buffer
7459 (dolist (c data
) (outline-flag-region (car c
) (cdr c
) t
))))
7461 ;;; Folding of blocks
7463 (defvar-local org-hide-block-overlays nil
7464 "Overlays hiding blocks.")
7466 (defun org-block-map (function &optional start end
)
7467 "Call FUNCTION at the head of all source blocks in the current buffer.
7468 Optional arguments START and END can be used to limit the range."
7469 (let ((start (or start
(point-min)))
7470 (end (or end
(point-max))))
7473 (while (and (< (point) end
) (re-search-forward org-block-regexp end t
))
7476 (goto-char (match-beginning 0))
7477 (funcall function
)))))))
7479 (defun org-hide-block-toggle-all ()
7480 "Toggle the visibility of all blocks in the current buffer."
7481 (org-block-map 'org-hide-block-toggle
))
7483 (defun org-hide-block-all ()
7484 "Fold all blocks in the current buffer."
7486 (org-show-block-all)
7487 (org-block-map 'org-hide-block-toggle-maybe
))
7489 (defun org-show-block-all ()
7490 "Unfold all blocks in the current buffer."
7492 (mapc #'delete-overlay org-hide-block-overlays
)
7493 (setq org-hide-block-overlays nil
))
7495 (defun org-hide-block-toggle-maybe ()
7496 "Toggle visibility of block at point.
7497 Unlike to `org-hide-block-toggle', this function does not throw
7498 an error. Return a non-nil value when toggling is successful."
7500 (ignore-errors (org-hide-block-toggle)))
7502 (defun org-hide-block-toggle (&optional force
)
7503 "Toggle the visibility of the current block.
7504 When optional argument FORCE is `off', make block visible. If it
7505 is non-nil, hide it unconditionally. Throw an error when not at
7506 a block. Return a non-nil value when toggling is successful."
7508 (let ((element (org-element-at-point)))
7509 (unless (memq (org-element-type element
)
7510 '(center-block comment-block dynamic-block example-block
7511 export-block quote-block special-block
7512 src-block verse-block
))
7513 (user-error "Not at a block"))
7514 (let* ((start (save-excursion
7515 (goto-char (org-element-property :post-affiliated element
))
7516 (line-end-position)))
7517 (end (save-excursion
7518 (goto-char (org-element-property :end element
))
7519 (skip-chars-backward " \r\t\n")
7520 (line-end-position)))
7521 (overlays (overlays-at start
)))
7523 ;; Do nothing when not before or at the block opening line or
7524 ;; at the block closing line.
7525 ((let ((eol (line-end-position))) (and (> eol start
) (/= eol end
))) nil
)
7526 ((and (not (eq force
'off
))
7527 (not (memq t
(mapcar
7529 (eq (overlay-get o
'invisible
) 'org-hide-block
))
7531 (let ((ov (make-overlay start end
)))
7532 (overlay-put ov
'invisible
'org-hide-block
)
7533 ;; Make the block accessible to `isearch'.
7535 ov
'isearch-open-invisible
7537 (when (memq ov org-hide-block-overlays
)
7538 (setq org-hide-block-overlays
(delq ov org-hide-block-overlays
)))
7539 (when (eq (overlay-get ov
'invisible
) 'org-hide-block
)
7540 (delete-overlay ov
))))
7541 (push ov org-hide-block-overlays
)
7542 ;; When the block is hidden away, make sure point is left in
7543 ;; a visible part of the buffer.
7544 (when (> (line-beginning-position) start
)
7546 (beginning-of-line))
7547 ;; Signal successful toggling.
7549 ((or (not force
) (eq force
'off
))
7550 (dolist (ov overlays t
)
7551 (when (memq ov org-hide-block-overlays
)
7552 (setq org-hide-block-overlays
(delq ov org-hide-block-overlays
)))
7553 (when (eq (overlay-get ov
'invisible
) 'org-hide-block
)
7554 (delete-overlay ov
))))))))
7556 ;; Remove overlays when changing major mode
7557 (add-hook 'org-mode-hook
7558 (lambda () (add-hook 'change-major-mode-hook
7559 'org-show-block-all
'append
'local
)))
7563 (defvar org-goto-window-configuration nil
)
7564 (defvar org-goto-marker nil
)
7565 (defvar org-goto-map
)
7566 (defun org-goto-map ()
7567 "Set the keymap `org-goto'."
7569 (let ((map (make-sparse-keymap)))
7570 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7571 mouse-drag-region universal-argument org-occur
)))
7573 (substitute-key-definition cmd cmd map global-map
)))
7574 (suppress-keymap map
)
7575 (org-defkey map
"\C-m" 'org-goto-ret
)
7576 (org-defkey map
[(return)] 'org-goto-ret
)
7577 (org-defkey map
[(left)] 'org-goto-left
)
7578 (org-defkey map
[(right)] 'org-goto-right
)
7579 (org-defkey map
[(control ?g
)] 'org-goto-quit
)
7580 (org-defkey map
"\C-i" 'org-cycle
)
7581 (org-defkey map
[(tab)] 'org-cycle
)
7582 (org-defkey map
[(down)] 'outline-next-visible-heading
)
7583 (org-defkey map
[(up)] 'outline-previous-visible-heading
)
7584 (if org-goto-auto-isearch
7585 (if (fboundp 'define-key-after
)
7586 (define-key-after map
[t] 'org-goto-local-auto-isearch)
7588 (org-defkey map "q" 'org-goto-quit)
7589 (org-defkey map "n" 'outline-next-visible-heading)
7590 (org-defkey map "p" 'outline-previous-visible-heading)
7591 (org-defkey map "f" 'outline-forward-same-level)
7592 (org-defkey map "b" 'outline-backward-same-level)
7593 (org-defkey map "u" 'outline-up-heading))
7594 (org-defkey map "/" 'org-occur)
7595 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7596 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7597 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7598 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7599 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7602 (defconst org-goto-help
7603 "Browse buffer copy, to find location or copy text.%s
7604 RET=jump to location C-g=quit and return to previous location
7605 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7607 (defvar org-goto-start-pos) ; dynamically scoped parameter
7609 (defun org-goto (&optional alternative-interface)
7610 "Look up a different location in the current file, keeping current visibility.
7612 When you want look-up or go to a different location in a
7613 document, the fastest way is often to fold the entire buffer and
7614 then dive into the tree. This method has the disadvantage, that
7615 the previous location will be folded, which may not be what you
7618 This command works around this by showing a copy of the current
7619 buffer in an indirect buffer, in overview mode. You can dive
7620 into the tree in that copy, use org-occur and incremental search
7621 to find a location. When pressing RET or `Q', the command
7622 returns to the original buffer in which the visibility is still
7623 unchanged. After RET it will also jump to the location selected
7624 in the indirect buffer and expose the headline hierarchy above.
7626 With a prefix argument, use the alternative interface: e.g., if
7627 `org-goto-interface' is `outline' use `outline-path-completion'."
7630 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7631 (org-refile-use-outline-path t)
7632 (org-refile-target-verify-function nil)
7634 (if (not alternative-interface)
7636 (if (eq org-goto-interface 'outline)
7637 'outline-path-completion
7639 (org-goto-start-pos (point))
7641 (if (eq interface 'outline)
7642 (car (org-get-location (current-buffer) org-goto-help))
7643 (let ((pa (org-refile-get-location "Goto")))
7644 (org-refile-check-position pa)
7648 (org-mark-ring-push org-goto-start-pos)
7649 (goto-char selected-point)
7650 (when (or (outline-invisible-p) (org-invisible-p2))
7651 (org-show-context 'org-goto)))
7654 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7655 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7656 (defvar org-goto-local-auto-isearch-map) ; defined below
7658 (defun org-get-location (_buf help)
7659 "Let the user select a location in current buffer.
7660 This function uses a recursive edit. It returns the selected position
7663 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7664 (isearch-hide-immediately nil)
7665 (isearch-search-fun-function
7666 (lambda () 'org-goto-local-search-headings))
7667 (org-goto-selected-point org-goto-exit-command))
7669 (save-window-excursion
7670 (delete-other-windows)
7671 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7672 (pop-to-buffer-same-window
7674 (make-indirect-buffer (current-buffer) "*org-goto*")
7675 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7676 (with-output-to-temp-buffer "*Org Help*"
7677 (princ (format help (if org-goto-auto-isearch
7678 " Just type for auto-isearch."
7679 " n/p/f/b/u to navigate, q to quit."))))
7680 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7681 (setq buffer-read-only nil)
7682 (let ((org-startup-truncated t)
7683 (org-startup-folded nil)
7684 (org-startup-align-all-tables nil))
7687 (setq buffer-read-only t)
7688 (if (and (boundp 'org-goto-start-pos)
7689 (integer-or-marker-p org-goto-start-pos))
7690 (progn (goto-char org-goto-start-pos)
7691 (when (outline-invisible-p)
7692 (org-show-set-visibility 'lineage)))
7693 (goto-char (point-min)))
7694 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7695 (message "Select location and press RET")
7696 (use-local-map org-goto-map)
7698 (kill-buffer "*org-goto*")
7699 (cons org-goto-selected-point org-goto-exit-command))))
7701 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7702 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7703 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7704 (if (fboundp 'isearch-other-control-char)
7706 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7707 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7708 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7709 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7710 (define-key org-goto-local-auto-isearch-map [return] nil))
7712 (defun org-goto-local-search-headings (string bound noerror)
7713 "Search and make sure that any matches are in headlines."
7715 (while (if isearch-forward
7716 (search-forward string bound noerror)
7717 (search-backward string bound noerror))
7718 (when (save-match-data
7719 (and (save-excursion
7721 (looking-at org-complex-heading-regexp))
7722 (or (not (match-beginning 5))
7723 (< (point) (match-beginning 5)))))
7724 (throw 'return (point))))))
7726 (defun org-goto-local-auto-isearch ()
7729 (goto-char (point-min))
7730 (let ((keys (this-command-keys)))
7731 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7733 (isearch-process-search-char (string-to-char keys)))))
7735 (defun org-goto-ret (&optional _arg)
7736 "Finish `org-goto' by going to the new location."
7738 (setq org-goto-selected-point (point))
7739 (setq org-goto-exit-command 'return)
7742 (defun org-goto-left ()
7743 "Finish `org-goto' by going to the new location."
7745 (if (org-at-heading-p)
7747 (beginning-of-line 1)
7748 (setq org-goto-selected-point (point)
7749 org-goto-exit-command 'left)
7751 (user-error "Not on a heading")))
7753 (defun org-goto-right ()
7754 "Finish `org-goto' by going to the new location."
7756 (if (org-at-heading-p)
7758 (setq org-goto-selected-point (point)
7759 org-goto-exit-command 'right)
7761 (user-error "Not on a heading")))
7763 (defun org-goto-quit ()
7764 "Finish `org-goto' without cursor motion."
7766 (setq org-goto-selected-point nil)
7767 (setq org-goto-exit-command 'quit)
7770 ;;; Indirect buffer display of subtrees
7772 (defvar org-indirect-dedicated-frame nil
7773 "This is the frame being used for indirect tree display.")
7774 (defvar org-last-indirect-buffer nil)
7776 (defun org-tree-to-indirect-buffer (&optional arg)
7777 "Create indirect buffer and narrow it to current subtree.
7779 With a numerical prefix ARG, go up to this level and then take that tree.
7780 If ARG is negative, go up that many levels.
7782 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7783 indirect buffer previously made with this command, to avoid proliferation of
7784 indirect buffers. However, when you call the command with a \
7785 `\\[universal-argument]' prefix, or
7786 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7787 so that you can work with several indirect buffers at the same time. If
7788 `org-indirect-buffer-display' is `dedicated-frame', the \
7789 `\\[universal-argument]' prefix also
7790 requests that a new frame be made for the new buffer, so that the dedicated
7791 frame is not changed."
7793 (let ((cbuf (current-buffer))
7794 (cwin (selected-window))
7796 beg end level heading ibuf)
7798 (org-back-to-heading t)
7800 (setq level (org-outline-level))
7801 (when (< arg 0) (setq arg (+ level arg)))
7802 (while (> (setq level (org-outline-level)) arg)
7803 (org-up-heading-safe)))
7805 heading (org-get-heading 'no-tags))
7806 (org-end-of-subtree t t)
7807 (when (org-at-heading-p) (backward-char 1))
7809 (when (and (buffer-live-p org-last-indirect-buffer)
7810 (not (eq org-indirect-buffer-display 'new-frame))
7812 (kill-buffer org-last-indirect-buffer))
7813 (setq ibuf (org-get-indirect-buffer cbuf heading)
7814 org-last-indirect-buffer ibuf)
7816 ((or (eq org-indirect-buffer-display 'new-frame)
7817 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7818 (select-frame (make-frame))
7819 (delete-other-windows)
7820 (pop-to-buffer-same-window ibuf)
7821 (org-set-frame-title heading))
7822 ((eq org-indirect-buffer-display 'dedicated-frame)
7824 (select-frame (or (and org-indirect-dedicated-frame
7825 (frame-live-p org-indirect-dedicated-frame)
7826 org-indirect-dedicated-frame)
7827 (setq org-indirect-dedicated-frame (make-frame)))))
7828 (delete-other-windows)
7829 (pop-to-buffer-same-window ibuf)
7830 (org-set-frame-title (concat "Indirect: " heading)))
7831 ((eq org-indirect-buffer-display 'current-window)
7832 (pop-to-buffer-same-window ibuf))
7833 ((eq org-indirect-buffer-display 'other-window)
7834 (pop-to-buffer ibuf))
7835 (t (error "Invalid value")))
7836 (narrow-to-region beg end)
7839 (run-hook-with-args 'org-cycle-hook 'all)
7840 (and (window-live-p cwin) (select-window cwin))))
7842 (defun org-get-indirect-buffer (&optional buffer heading)
7843 (setq buffer (or buffer (current-buffer)))
7844 (let ((n 1) (base (buffer-name buffer)) bname)
7845 (while (buffer-live-p
7849 (if heading (concat heading "-" (number-to-string n))
7850 (number-to-string n))))))
7853 (make-indirect-buffer buffer bname 'clone)
7854 (error (make-indirect-buffer buffer bname)))))
7856 (defun org-set-frame-title (title)
7857 "Set the title of the current frame to the string TITLE."
7858 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7860 ;;;; Structure editing
7862 ;;; Inserting headlines
7864 (defun org--line-empty-p (n)
7865 "Is the Nth next line empty?
7867 Counts the current line as N = 1 and the previous line as N = 0;
7868 see `beginning-of-line'."
7871 (or (beginning-of-line n) t)
7873 (looking-at "[ \t]*$")))))
7875 (defun org-previous-line-empty-p ()
7876 "Is the previous line a blank line?
7877 When NEXT is non-nil, check the next line instead."
7878 (org--line-empty-p 0))
7880 (defun org-next-line-empty-p ()
7881 "Is the previous line a blank line?
7882 When NEXT is non-nil, check the next line instead."
7883 (org--line-empty-p 2))
7885 (defun org--blank-before-heading-p (&optional parent)
7886 "Non-nil when an empty line should precede a new heading here.
7887 When optional argument PARENT is non-nil, consider parent
7888 headline instead of current one."
7889 (pcase (assq 'heading org-blank-before-new-entry)
7892 (org-with-limited-levels
7893 (unless (and (org-before-first-heading-p)
7894 (not (outline-next-heading)))
7895 (org-back-to-heading t)
7896 (when parent (org-up-heading-safe))
7898 (org-previous-line-empty-p))
7899 ((outline-next-heading)
7900 (org-previous-line-empty-p))
7901 ;; Ignore trailing spaces on last buffer line.
7902 ((progn (skip-chars-backward " \t") (bolp))
7903 (org-previous-line-empty-p))
7905 (`(heading . ,value) value)
7908 (defun org-insert-heading (&optional arg invisible-ok top)
7909 "Insert a new heading or an item with the same depth at point.
7911 If point is at the beginning of a heading, insert a new heading
7912 or a new headline above the current one. When at the beginning
7913 of a regular line of text, turn it into a heading.
7915 If point is in the middle of a line, split it and create a new
7916 headline with the text in the current line after point (see
7917 `org-M-RET-may-split-line' on how to modify this behavior). As
7918 a special case, on a headline, splitting can only happen on the
7919 title itself. E.g., this excludes breaking stars or tags.
7921 With a `\\[universal-argument]' prefix, set \
7922 `org-insert-heading-respect-content' to
7923 a non-nil value for the duration of the command. This forces the
7924 insertion of a heading after the current subtree, independently
7925 on the location of point.
7927 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7928 insert the heading at the end of the tree
7929 above the current heading. For example, if point is within a
7930 2nd-level heading, then it will insert a 2nd-level heading at
7931 the end of the 1st-level parent subtree.
7933 When INVISIBLE-OK is set, stop at invisible headlines when going
7934 back. This is important for non-interactive uses of the
7937 When optional argument TOP is non-nil, insert a level 1 heading,
7940 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7941 (level (org-current-level))
7942 (stars (make-string (if (and level (not top)) level 1) ?*)))
7944 ((or org-insert-heading-respect-content
7945 (member arg '((4) (16)))
7946 (and (not invisible-ok)
7947 (invisible-p (max (1- (point)) (point-min)))))
7948 ;; Position point at the location of insertion.
7949 (if (not level) ;before first headline
7950 (org-with-limited-levels (outline-next-heading))
7951 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7953 (org-with-limited-levels (org-back-to-heading invisible-ok))
7954 (cond ((equal arg '(16))
7955 (org-up-heading-safe)
7956 (org-end-of-subtree t t))
7958 (org-end-of-subtree t t))))
7959 (unless (bolp) (insert "\n")) ;ensure final newline
7960 (unless (and blank? (org-previous-line-empty-p))
7961 (org-N-empty-lines-before-current (if blank? 1 0)))
7962 (insert stars " \n")
7967 (when blank? (save-excursion (insert "\n")))
7968 (save-excursion (insert stars " \n"))
7969 (unless (and blank? (org-previous-line-empty-p))
7970 (org-N-empty-lines-before-current (if blank? 1 0)))
7972 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7973 (org-match-line org-complex-heading-regexp)
7974 (org-pos-in-match-range (point) 4))
7975 ;; Grab the text that should moved to the new headline.
7977 (let ((split (delete-and-extract-region (point) (match-end 4))))
7978 (if (looking-at "[ \t]*$") (replace-match "")
7979 (org-set-tags nil t))
7981 (when blank? (insert "\n"))
7982 (insert "\n" stars " ")
7983 (when (org-string-nw-p split) (insert split))
7988 (when blank? (insert "\n"))
7989 (insert "\n" stars " \n")
7990 (forward-char -1))))
7991 ;; On regular text, turn line into a headline or split, if
7995 (unless (and blank? (org-previous-line-empty-p))
7996 (org-N-empty-lines-before-current (if blank? 1 0))))
7998 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
8000 (insert "\n" stars " ")
8001 (unless (and blank? (org-previous-line-empty-p))
8002 (org-N-empty-lines-before-current (if blank? 1 0))))))
8003 (run-hooks 'org-insert-heading-hook))
8005 (defun org-N-empty-lines-before-current (n)
8006 "Make the number of empty lines before current exactly N.
8007 So this will delete or add empty lines."
8008 (let ((column (current-column))
8009 (empty-lines (make-string n ?\n)))
8012 (skip-chars-backward " \r\t\n")
8013 (unless (bolp) (forward-line))
8014 (delete-region (point) p))
8015 (insert empty-lines)
8016 (move-to-column column)))
8018 (defun org-get-heading (&optional no-tags no-todo)
8019 "Return the heading of the current entry, without the stars.
8020 When NO-TAGS is non-nil, don't include tags.
8021 When NO-TODO is non-nil, don't include TODO keywords."
8023 (org-back-to-heading t)
8024 (let ((case-fold-search nil))
8026 ((and no-tags no-todo)
8027 (looking-at org-complex-heading-regexp)
8028 ;; Return value has to be a string, but match group 4 is
8030 (or (match-string 4) ""))
8032 (looking-at (concat org-outline-regexp
8034 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8037 (looking-at org-todo-line-regexp)
8039 (t (looking-at org-heading-regexp)
8040 (match-string 2))))))
8042 (defvar orgstruct-mode) ; defined below
8044 (defun org-heading-components ()
8045 "Return the components of the current heading.
8046 This is a list with the following elements:
8047 - the level as an integer
8048 - the reduced level, different if `org-odd-levels-only' is set.
8049 - the TODO keyword, or nil
8050 - the priority character, like ?A, or nil if no priority is given
8051 - the headline text itself, or the tags string if no headline text
8052 - the tags string, or nil."
8054 (org-back-to-heading t)
8055 (when (let (case-fold-search)
8059 org-complex-heading-regexp)))
8061 (list (length (match-string 1))
8062 (org-reduced-level (length (match-string 1)))
8067 (list (length (match-string 1))
8068 (org-reduced-level (length (match-string 1)))
8069 (match-string-no-properties 2)
8070 (and (match-end 3) (aref (match-string 3) 2))
8071 (match-string-no-properties 4)
8072 (match-string-no-properties 5))))))
8074 (defun org-get-entry ()
8075 "Get the entry text, after heading, entire subtree."
8077 (org-back-to-heading t)
8078 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8080 (defun org-edit-headline (&optional heading)
8081 "Edit the current headline.
8082 Set it to HEADING when provided."
8084 (org-with-wide-buffer
8085 (org-back-to-heading t)
8086 (let ((case-fold-search nil))
8087 (when (looking-at org-complex-heading-regexp)
8088 (let* ((old (match-string-no-properties 4))
8089 (new (save-match-data
8090 (org-trim (or heading (read-string "Edit: " old))))))
8091 (unless (equal old new)
8092 (if old (replace-match new t t nil 4)
8093 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8095 (org-set-tags nil t)
8096 (when (looking-at "[ \t]*$") (replace-match ""))))))))
8098 (defun org-insert-heading-after-current ()
8099 "Insert a new heading with same level as current, after current subtree."
8101 (org-back-to-heading)
8102 (org-insert-heading)
8103 (org-move-subtree-down)
8106 (defun org-insert-heading-respect-content (&optional invisible-ok)
8107 "Insert heading with `org-insert-heading-respect-content' set to t."
8109 (org-insert-heading '(4) invisible-ok))
8111 (defun org-insert-todo-heading-respect-content (&optional force-state)
8112 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8114 (org-insert-todo-heading force-state '(4)))
8116 (defun org-insert-todo-heading (arg &optional force-heading)
8117 "Insert a new heading with the same level and TODO state as current heading.
8119 If the heading has no TODO state, or if the state is DONE, use
8120 the first state (TODO by default). Also with one prefix arg,
8121 force first state. With two prefix args, force inserting at the
8122 end of the parent subtree.
8124 When called at a plain list item, insert a new item with an
8125 unchecked check box."
8127 (when (or force-heading (not (org-insert-item 'checkbox)))
8128 (org-insert-heading (or (and (equal arg '(16)) '(16))
8131 (org-back-to-heading)
8132 (outline-previous-heading)
8133 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
8135 (if (or (equal arg '(4))
8136 (not (match-beginning 2))
8137 (member (match-string 2) org-done-keywords))
8138 (car org-todo-keywords-1)
8142 (run-hook-with-args-until-success
8143 'org-todo-get-default-hook new-mark-x nil)
8145 (beginning-of-line 1)
8146 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8147 (if org-treat-insert-todo-heading-as-state-change
8149 (insert new-mark " "))))
8150 (when org-provide-todo-statistics
8151 (org-update-parent-todo-statistics))))
8153 (defun org-insert-subheading (arg)
8154 "Insert a new subheading and demote it.
8155 Works for outline headings and for plain lists alike."
8157 (org-insert-heading arg)
8159 ((org-at-heading-p) (org-do-demote))
8160 ((org-at-item-p) (org-indent-item))))
8162 (defun org-insert-todo-subheading (arg)
8163 "Insert a new subheading with TODO keyword or checkbox and demote it.
8164 Works for outline headings and for plain lists alike."
8166 (org-insert-todo-heading arg)
8168 ((org-at-heading-p) (org-do-demote))
8169 ((org-at-item-p) (org-indent-item))))
8171 ;;; Promotion and Demotion
8173 (defvar org-after-demote-entry-hook nil
8174 "Hook run after an entry has been demoted.
8175 The cursor will be at the beginning of the entry.
8176 When a subtree is being demoted, the hook will be called for each node.")
8178 (defvar org-after-promote-entry-hook nil
8179 "Hook run after an entry has been promoted.
8180 The cursor will be at the beginning of the entry.
8181 When a subtree is being promoted, the hook will be called for each node.")
8183 (defun org-promote-subtree ()
8184 "Promote the entire subtree.
8185 See also `org-promote'."
8188 (org-with-limited-levels (org-map-tree 'org-promote)))
8189 (org-fix-position-after-promote))
8191 (defun org-demote-subtree ()
8192 "Demote the entire subtree.
8193 See `org-demote' and `org-promote'."
8196 (org-with-limited-levels (org-map-tree 'org-demote)))
8197 (org-fix-position-after-promote))
8199 (defun org-do-promote ()
8200 "Promote the current heading higher up the tree.
8201 If the region is active in `transient-mark-mode', promote all
8202 headings in the region."
8205 (if (org-region-active-p)
8206 (org-map-region 'org-promote (region-beginning) (region-end))
8208 (org-fix-position-after-promote))
8210 (defun org-do-demote ()
8211 "Demote the current heading lower down the tree.
8212 If the region is active in `transient-mark-mode', demote all
8213 headings in the region."
8216 (if (org-region-active-p)
8217 (org-map-region 'org-demote (region-beginning) (region-end))
8219 (org-fix-position-after-promote))
8221 (defun org-fix-position-after-promote ()
8222 "Fix cursor position and indentation after demoting/promoting."
8223 (let ((pos (point)))
8224 (when (save-excursion
8226 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8227 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8228 (cond ((eobp) (insert " "))
8229 ((eolp) (insert " "))
8230 ((equal (char-after) ?\s) (forward-char 1))))))
8232 (defun org-current-level ()
8233 "Return the level of the current entry, or nil if before the first headline.
8234 The level is the number of stars at the beginning of the
8235 headline. Use `org-reduced-level' to remove the effect of
8236 `org-odd-levels'. Unlike to `org-outline-level', this function
8237 ignores inlinetasks."
8238 (let ((level (org-with-limited-levels (org-outline-level))))
8239 (and (> level 0) level)))
8241 (defun org-get-previous-line-level ()
8242 "Return the outline depth of the last headline before the current line.
8243 Returns 0 for the first headline in the buffer, and nil if before the
8245 (and (org-current-level)
8246 (or (and (/= (line-beginning-position) (point-min))
8247 (save-excursion (beginning-of-line 0) (org-current-level)))
8250 (defun org-reduced-level (l)
8251 "Compute the effective level of a heading.
8252 This takes into account the setting of `org-odd-levels-only'."
8255 (org-odd-levels-only (1+ (floor (/ l 2))))
8258 (defun org-level-increment ()
8259 "Return the number of stars that will be added or removed at a
8260 time to headlines when structure editing, based on the value of
8261 `org-odd-levels-only'."
8262 (if org-odd-levels-only 2 1))
8264 (defun org-get-valid-level (level &optional change)
8265 "Rectify a level change under the influence of `org-odd-levels-only'
8266 LEVEL is a current level, CHANGE is by how much the level should be
8267 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8268 even level numbers will become the next higher odd number."
8269 (if org-odd-levels-only
8270 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8271 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8272 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8273 (max 1 (+ level (or change 0)))))
8275 (defun org-promote ()
8276 "Promote the current heading higher up the tree."
8277 (org-with-wide-buffer
8278 (org-back-to-heading t)
8279 (let* ((after-change-functions (remq 'flyspell-after-change-function
8280 after-change-functions))
8281 (level (save-match-data (funcall outline-level)))
8282 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8283 (diff (abs (- level (length up-head) -1))))
8285 ((and (= level 1) org-allow-promoting-top-level-subtree)
8286 (replace-match "# " nil t))
8288 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8289 (t (replace-match up-head nil t)))
8291 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8292 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8293 (run-hooks 'org-after-promote-entry-hook))))
8295 (defun org-demote ()
8296 "Demote the current heading lower down the tree."
8297 (org-with-wide-buffer
8298 (org-back-to-heading t)
8299 (let* ((after-change-functions (remq 'flyspell-after-change-function
8300 after-change-functions))
8301 (level (save-match-data (funcall outline-level)))
8302 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8303 (diff (abs (- level (length down-head) -1))))
8304 (replace-match down-head nil t)
8305 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8306 (when org-adapt-indentation (org-fixup-indentation diff))
8307 (run-hooks 'org-after-demote-entry-hook))))
8309 (defun org-cycle-level ()
8310 "Cycle the level of an empty headline through possible states.
8311 This goes first to child, then to parent, level, then up the hierarchy.
8312 After top level, it switches back to sibling level."
8314 (let ((org-adapt-indentation nil))
8315 (when (org-point-at-end-of-empty-headline)
8316 (setq this-command 'org-cycle-level) ; Only needed for caching
8317 (let ((cur-level (org-current-level))
8318 (prev-level (org-get-previous-line-level)))
8320 ;; If first headline in file, promote to top-level.
8322 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8323 do (org-do-promote)))
8324 ;; If same level as prev, demote one.
8325 ((= prev-level cur-level)
8327 ;; If parent is top-level, promote to top level if not already.
8329 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8330 do (org-do-promote)))
8331 ;; If top-level, return to prev-level.
8333 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8334 do (org-do-demote)))
8335 ;; If less than prev-level, promote one.
8336 ((< cur-level prev-level)
8338 ;; If deeper than prev-level, promote until higher than
8340 ((> cur-level prev-level)
8341 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8342 do (org-do-promote))))
8345 (defun org-map-tree (fun)
8346 "Call FUN for every heading underneath the current one."
8347 (org-back-to-heading t)
8348 (let ((level (funcall outline-level)))
8352 (outline-next-heading)
8353 (> (funcall outline-level) level))
8357 (defun org-map-region (fun beg end)
8358 "Call FUN for every heading between BEG and END."
8359 (let ((org-ignore-region t))
8361 (setq end (copy-marker end))
8363 (when (and (re-search-forward org-outline-regexp-bol nil t)
8367 (outline-next-heading)
8372 (defun org-fixup-indentation (diff)
8373 "Change the indentation in the current entry by DIFF.
8375 DIFF is an integer. Indentation is done according to the
8378 - Planning information and property drawers are always indented
8379 according to the new level of the headline;
8381 - Footnote definitions and their contents are ignored;
8383 - Inlinetasks' boundaries are not shifted;
8385 - Empty lines are ignored;
8387 - Other lines' indentation are shifted by DIFF columns, unless
8388 it would introduce a structural change in the document, in
8389 which case no shifting is done at all.
8391 Assume point is at a heading or an inlinetask beginning."
8392 (org-with-wide-buffer
8393 (narrow-to-region (line-beginning-position)
8395 (if (org-with-limited-levels (org-at-heading-p))
8396 (org-with-limited-levels (outline-next-heading))
8397 (org-inlinetask-goto-end))
8400 ;; Indent properly planning info and property drawer.
8401 (when (looking-at-p org-planning-line-re)
8404 (when (looking-at org-property-drawer-re)
8405 (goto-char (match-end 0))
8407 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8409 (when (zerop diff) (throw 'no-shift nil))
8410 ;; If DIFF is negative, first check if a shift is possible at all
8411 ;; (e.g., it doesn't break structure). This can only happen if
8412 ;; some contents are not properly indented.
8413 (let ((case-fold-search t))
8415 (let ((diff (- diff))
8416 (forbidden-re (concat org-outline-regexp
8418 (substring org-footnote-definition-re 1))))
8422 ((looking-at-p "[ \t]*$") (forward-line))
8423 ((and (looking-at-p org-footnote-definition-re)
8424 (let ((e (org-element-at-point)))
8425 (and (eq (org-element-type e) 'footnote-definition)
8426 (goto-char (org-element-property :end e))))))
8427 ((looking-at-p org-outline-regexp) (forward-line))
8428 ;; Give up if shifting would move before column 0 or
8429 ;; if it would introduce a headline or a footnote
8432 (skip-chars-forward " \t")
8433 (let ((ind (current-column)))
8434 (when (or (< ind diff)
8435 (and (= ind diff) (looking-at-p forbidden-re)))
8436 (throw 'no-shift nil)))
8437 ;; Ignore contents of example blocks and source
8438 ;; blocks if their indentation is meant to be
8439 ;; preserved. Jump to block's closing line.
8441 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8442 (let ((e (org-element-at-point)))
8443 (and (memq (org-element-type e)
8444 '(example-block src-block))
8445 (or org-src-preserve-indentation
8446 (org-element-property :preserve-indent e))
8447 (goto-char (org-element-property :end e))
8448 (progn (skip-chars-backward " \r\t\n")
8451 (forward-line))))))))
8452 ;; Shift lines but footnote definitions, inlinetasks boundaries
8453 ;; by DIFF. Also skip contents of source or example blocks
8454 ;; when indentation is meant to be preserved.
8457 ((and (looking-at-p org-footnote-definition-re)
8458 (let ((e (org-element-at-point)))
8459 (and (eq (org-element-type e) 'footnote-definition)
8460 (goto-char (org-element-property :end e))))))
8461 ((looking-at-p org-outline-regexp) (forward-line))
8462 ((looking-at-p "[ \t]*$") (forward-line))
8464 (indent-line-to (+ (org-get-indentation) diff))
8466 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8467 (let ((e (org-element-at-point)))
8468 (and (memq (org-element-type e)
8469 '(example-block src-block))
8470 (or org-src-preserve-indentation
8471 (org-element-property :preserve-indent e))
8472 (goto-char (org-element-property :end e))
8473 (progn (skip-chars-backward " \r\t\n")
8476 (forward-line)))))))))
8478 (defun org-convert-to-odd-levels ()
8479 "Convert an Org file with all levels allowed to one with odd levels.
8480 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8483 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8484 (let ((outline-level 'org-outline-level)
8485 (org-odd-levels-only nil) n)
8487 (goto-char (point-min))
8488 (while (re-search-forward "^\\*\\*+ " nil t)
8489 (setq n (- (length (match-string 0)) 2))
8490 (while (>= (setq n (1- n)) 0)
8492 (end-of-line 1))))))
8494 (defun org-convert-to-oddeven-levels ()
8495 "Convert an Org file with only odd levels to one with odd/even levels.
8496 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8497 file contains a section with an even level, conversion would
8498 destroy the structure of the file. An error is signaled in this
8501 (goto-char (point-min))
8502 ;; First check if there are no even levels
8503 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8504 (org-show-set-visibility 'canonical)
8505 (error "Not all levels are odd in this file. Conversion not possible"))
8506 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8507 (let ((outline-regexp org-outline-regexp)
8508 (outline-level 'org-outline-level)
8509 (org-odd-levels-only nil) n)
8511 (goto-char (point-min))
8512 (while (re-search-forward "^\\*\\*+ " nil t)
8513 (setq n (/ (1- (length (match-string 0))) 2))
8514 (while (>= (setq n (1- n)) 0)
8516 (end-of-line 1))))))
8518 (defun org-tr-level (n)
8519 "Make N odd if required."
8520 (if org-odd-levels-only (1+ (/ n 2)) n))
8522 ;;; Vertical tree motion, cutting and pasting of subtrees
8524 (defun org-move-subtree-up (&optional arg)
8525 "Move the current subtree up past ARG headlines of the same level."
8527 (org-move-subtree-down (- (prefix-numeric-value arg))))
8529 (defun org-move-subtree-down (&optional arg)
8530 "Move the current subtree down past ARG headlines of the same level."
8532 (setq arg (prefix-numeric-value arg))
8533 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8534 'org-get-last-sibling))
8535 (ins-point (make-marker))
8537 (col (current-column))
8538 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8540 (org-back-to-heading)
8543 (setq ne-beg (org-back-over-empty-lines))
8546 (save-excursion (outline-end-of-heading)
8547 (setq folded (outline-invisible-p)))
8548 (progn (org-end-of-subtree nil t)
8549 (unless (eobp) (backward-char))))
8550 (outline-next-heading)
8551 (setq ne-end (org-back-over-empty-lines))
8554 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8555 ;; include less whitespace
8558 (forward-line (- ne-beg ne-end))
8559 (setq beg (point))))
8560 ;; Find insertion point, with error handling
8562 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8563 (progn (goto-char beg0)
8564 (user-error "Cannot move past superior level or buffer limit")))
8565 (setq cnt (1- cnt)))
8567 ;; Moving forward - still need to move over subtree
8568 (org-end-of-subtree t t)
8570 (org-back-over-empty-lines)
8571 (or (bolp) (newline))))
8572 (setq ne-ins (org-back-over-empty-lines))
8573 (move-marker ins-point (point))
8574 (setq txt (buffer-substring beg end))
8575 (org-save-markers-in-region beg end)
8576 (delete-region beg end)
8577 (org-remove-empty-overlays-at beg)
8578 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8579 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8580 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8581 (let ((bbb (point)))
8582 (insert-before-markers txt)
8583 (org-reinstall-markers-in-region bbb)
8584 (move-marker ins-point bbb))
8585 (or (bolp) (insert "\n"))
8586 (setq ins-end (point))
8587 (goto-char ins-point)
8588 (org-skip-whitespace)
8589 (when (and (< arg 0)
8590 (org-first-sibling-p)
8592 ;; Move whitespace back to beginning
8595 (let ((kill-whole-line t))
8596 (kill-line (- ne-ins ne-beg)) (point)))
8597 (insert (make-string (- ne-ins ne-beg) ?\n)))
8598 (move-marker ins-point nil)
8600 (outline-hide-subtree)
8603 (org-cycle-hide-drawers 'children))
8604 (org-clean-visibility-after-subtree-move)
8605 ;; move back to the initial column we were at
8606 (move-to-column col)))
8608 (defvar org-subtree-clip ""
8609 "Clipboard for cut and paste of subtrees.
8610 This is actually only a copy of the kill, because we use the normal kill
8611 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8613 (defvar org-subtree-clip-folded nil
8614 "Was the last copied subtree folded?
8615 This is used to fold the tree back after pasting.")
8617 (defun org-cut-subtree (&optional n)
8618 "Cut the current subtree into the clipboard.
8619 With prefix arg N, cut this many sequential subtrees.
8620 This is a short-hand for marking the subtree and then cutting it."
8622 (org-copy-subtree n 'cut))
8624 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8625 "Copy the current subtree it in the clipboard.
8626 With prefix arg N, copy this many sequential subtrees.
8627 This is a short-hand for marking the subtree and then copying it.
8628 If CUT is non-nil, actually cut the subtree.
8629 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8630 of some markers in the region, even if CUT is non-nil. This is
8631 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8633 (let (beg end folded (beg0 (point)))
8634 (if (called-interactively-p 'any)
8635 (org-back-to-heading nil) ; take what looks like a subtree
8636 (org-back-to-heading t)) ; take what is really there
8638 (skip-chars-forward " \t\r\n")
8641 (outline-next-heading)
8642 (save-excursion (outline-end-of-heading)
8643 (setq folded (outline-invisible-p)))
8644 (ignore-errors (org-forward-heading-same-level (1- n) t))
8645 (org-end-of-subtree t t)))
8646 ;; Include the end of an inlinetask
8647 (when (and (featurep 'org-inlinetask)
8648 (looking-at-p (concat (org-inlinetask-outline-regexp)
8654 (setq org-subtree-clip-folded folded)
8655 (when (or cut force-store-markers)
8656 (org-save-markers-in-region beg end))
8657 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8658 (setq org-subtree-clip (current-kill 0))
8659 (message "%s: Subtree(s) with %d characters"
8660 (if cut "Cut" "Copied")
8661 (length org-subtree-clip)))))
8663 (defun org-paste-subtree (&optional level tree for-yank remove)
8664 "Paste the clipboard as a subtree, with modification of headline level.
8665 The entire subtree is promoted or demoted in order to match a new headline
8668 If the cursor is at the beginning of a headline, the same level as
8669 that headline is used to paste the tree.
8671 If not, the new level is derived from the *visible* headings
8672 before and after the insertion point, and taken to be the inferior headline
8673 level of the two. So if the previous visible heading is level 3 and the
8674 next is level 4 (or vice versa), level 4 will be used for insertion.
8675 This makes sure that the subtree remains an independent subtree and does
8676 not swallow low level entries.
8678 You can also force a different level, either by using a numeric prefix
8679 argument, or by inserting the heading marker by hand. For example, if the
8680 cursor is after \"*****\", then the tree will be shifted to level 5.
8682 If optional TREE is given, use this text instead of the kill ring.
8684 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8685 move back over whitespace before inserting, and move point to the end of
8686 the inserted text when done.
8688 When REMOVE is non-nil, remove the subtree from the clipboard."
8690 (setq tree (or tree (and kill-ring (current-kill 0))))
8691 (unless (org-kill-is-subtree-p tree)
8693 (substitute-command-keys
8694 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8695 (org-with-limited-levels
8696 (let* ((visp (not (outline-invisible-p)))
8698 (^re_ "\\(\\*+\\)[ \t]*")
8699 (old-level (if (string-match org-outline-regexp-bol txt)
8700 (- (match-end 0) (match-beginning 0) 1)
8702 (force-level (cond (level (prefix-numeric-value level))
8703 ((and (looking-at "[ \t]*$")
8705 "^\\*+$" (buffer-substring
8706 (point-at-bol) (point))))
8707 (- (match-end 0) (match-beginning 0)))
8709 (looking-at org-outline-regexp))
8710 (- (match-end 0) (point) 1))))
8711 (previous-level (save-excursion
8714 (outline-previous-visible-heading 1)
8715 (if (looking-at ^re_)
8716 (- (match-end 0) (match-beginning 0) 1)
8719 (next-level (save-excursion
8722 (or (looking-at org-outline-regexp)
8723 (outline-next-visible-heading 1))
8724 (if (looking-at ^re_)
8725 (- (match-end 0) (match-beginning 0) 1)
8728 (new-level (or force-level (max previous-level next-level)))
8729 (shift (if (or (= old-level -1)
8731 (= old-level new-level))
8733 (- new-level old-level)))
8734 (delta (if (> shift 0) -1 1))
8735 (func (if (> shift 0) 'org-demote 'org-promote))
8736 (org-odd-levels-only nil)
8738 ;; Remove the forced level indicator
8740 (delete-region (point-at-bol) (point)))
8742 (beginning-of-line (if (bolp) 1 2))
8744 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8745 (insert-before-markers txt)
8746 (unless (string-suffix-p "\n" txt) (insert "\n"))
8747 (setq newend (point))
8748 (org-reinstall-markers-in-region beg)
8751 (skip-chars-forward " \t\n\r")
8753 (when (and (outline-invisible-p) visp)
8754 (save-excursion (outline-show-heading)))
8755 ;; Shift if necessary
8758 (narrow-to-region beg end)
8759 (while (not (= shift 0))
8760 (org-map-region func (point-min) (point-max))
8761 (setq shift (+ delta shift)))
8762 (goto-char (point-min))
8763 (setq newend (point-max))))
8764 (when (or (called-interactively-p 'interactive) for-yank)
8765 (message "Clipboard pasted as level %d subtree" new-level))
8766 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8768 (eq org-subtree-clip (current-kill 0))
8769 org-subtree-clip-folded)
8770 ;; The tree was folded before it was killed/copied
8771 (outline-hide-subtree))
8772 (and for-yank (goto-char newend))
8773 (and remove (setq kill-ring (cdr kill-ring))))))
8775 (defun org-kill-is-subtree-p (&optional txt)
8776 "Check if the current kill is an outline subtree, or a set of trees.
8777 Returns nil if kill does not start with a headline, or if the first
8778 headline level is not the largest headline level in the tree.
8779 So this will actually accept several entries of equal levels as well,
8780 which is OK for `org-paste-subtree'.
8781 If optional TXT is given, check this string instead of the current kill."
8782 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8783 (re (org-get-limited-outline-regexp))
8784 (^re (concat "^" re))
8785 (start-level (and kill
8787 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8789 (- (match-end 2) (match-beginning 2) 1)))
8790 (start (1+ (or (match-beginning 2) -1))))
8791 (if (not start-level)
8793 nil) ;; does not even start with a heading
8795 (while (setq start (string-match ^re kill (1+ start)))
8796 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8800 (defvar org-markers-to-move nil
8801 "Markers that should be moved with a cut-and-paste operation.
8802 Those markers are stored together with their positions relative to
8803 the start of the region.")
8805 (defun org-save-markers-in-region (beg end)
8806 "Check markers in region.
8807 If these markers are between BEG and END, record their position relative
8808 to BEG, so that after moving the block of text, we can put the markers back
8810 This function gets called just before an entry or tree gets cut from the
8811 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8812 called immediately, to move the markers with the entries."
8813 (setq org-markers-to-move nil)
8814 (when (featurep 'org-clock)
8815 (org-clock-save-markers-for-cut-and-paste beg end))
8816 (when (featurep 'org-agenda)
8817 (org-agenda-save-markers-for-cut-and-paste beg end)))
8819 (defun org-check-and-save-marker (marker beg end)
8820 "Check if MARKER is between BEG and END.
8821 If yes, remember the marker and the distance to BEG."
8822 (when (and (marker-buffer marker)
8823 (equal (marker-buffer marker) (current-buffer))
8824 (>= marker beg) (< marker end))
8825 (push (cons marker (- marker beg)) org-markers-to-move)))
8827 (defun org-reinstall-markers-in-region (beg)
8828 "Move all remembered markers to their position relative to BEG."
8829 (dolist (x org-markers-to-move)
8830 (move-marker (car x) (+ beg (cdr x))))
8831 (setq org-markers-to-move nil))
8833 (defun org-narrow-to-subtree ()
8834 "Narrow buffer to the current subtree."
8838 (org-with-limited-levels
8840 (progn (org-back-to-heading t) (point))
8841 (progn (org-end-of-subtree t t)
8842 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8845 (defun org-narrow-to-block ()
8846 "Narrow buffer to the current block."
8848 (let* ((case-fold-search t)
8849 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8850 "^[ \t]*#\\+end_.*")))
8852 (narrow-to-region (car blockp) (cdr blockp))
8853 (user-error "Not in a block"))))
8855 (defun org-clone-subtree-with-time-shift (n &optional shift)
8856 "Clone the task (subtree) at point N times.
8857 The clones will be inserted as siblings.
8859 In interactive use, the user will be prompted for the number of
8860 clones to be produced. If the entry has a timestamp, the user
8861 will also be prompted for a time shift, which may be a repeater
8862 as used in time stamps, for example `+3d'. To disable this,
8863 you can call the function with a universal prefix argument.
8865 When a valid repeater is given and the entry contains any time
8866 stamps, the clones will become a sequence in time, with time
8867 stamps in the subtree shifted for each clone produced. If SHIFT
8868 is nil or the empty string, time stamps will be left alone. The
8869 ID property of the original subtree is removed.
8871 In each clone, all the CLOCK entries will be removed. This
8872 prevents Org from considering that the clocked times overlap.
8874 If the original subtree did contain time stamps with a repeater,
8875 the following will happen:
8876 - the repeater will be removed in each clone
8877 - an additional clone will be produced, with the current, unshifted
8878 date(s) in the entry.
8879 - the original entry will be placed *after* all the clones, with
8881 - the start days in the repeater in the original entry will be shifted
8882 to past the last clone.
8883 In this way you can spell out a number of instances of a repeating task,
8884 and still retain the repeater to cover future instances of the task.
8886 As described above, N+1 clones are produced when the original
8887 subtree has a repeater. Setting N to 0, then, can be used to
8888 remove the repeater from a subtree and create a shifted clone
8889 with the original repeater."
8890 (interactive "nNumber of clones to produce: ")
8891 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8892 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8893 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8894 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8897 (if (and (not (equal current-prefix-arg '(4)))
8900 (re-search-forward org-ts-regexp-both end-of-tree t)))
8901 (read-from-minibuffer
8902 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8903 ""))) ;No time shift
8905 (or (not (org-string-nw-p shift))
8906 (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8908 (user-error "Invalid shift specification %s" shift))))
8909 (goto-char end-of-tree)
8910 (unless (bolp) (insert "\n"))
8911 (let* ((end (point))
8912 (template (buffer-substring beg end))
8913 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8914 (shift-what (pcase (and doshift (match-string 2 shift))
8917 ("w" (setq shift-n (* 7 shift-n)) 'day)
8920 (_ (error "Unsupported time unit"))))
8924 (idprop (org-entry-get nil "ID")))
8926 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8928 (delete-region beg end)
8931 (setq nmax (1+ nmax))
8932 (setq n-no-remove nmax))
8934 (cl-loop for n from nmin to nmax do
8940 (goto-char (point-min))
8942 (and idprop (if org-clone-delete-id
8943 (org-entry-delete nil "ID")
8944 (org-id-get-create t)))
8946 (while (re-search-forward org-clock-line-re nil t)
8947 (delete-region (line-beginning-position)
8948 (line-beginning-position 2)))
8949 (goto-char (point-min))
8950 (while (re-search-forward org-drawer-regexp nil t)
8951 (org-remove-empty-drawer-at (point))))
8952 (goto-char (point-min))
8954 (while (re-search-forward org-ts-regexp-both nil t)
8955 (org-timestamp-change (* n shift-n) shift-what))
8956 (unless (= n n-no-remove)
8957 (goto-char (point-min))
8958 (while (re-search-forward org-ts-regexp nil t)
8960 (goto-char (match-beginning 0))
8961 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8962 (delete-region (match-beginning 1) (match-end 1)))))))
8968 (defun org-sort (with-case)
8969 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8970 Optional argument WITH-CASE means sort case-sensitively."
8973 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8974 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8976 (org-call-with-arg 'org-sort-entries with-case))))
8978 (defun org-sort-remove-invisible (s)
8979 "Remove invisible part of links and emphasis markers from string S."
8980 (remove-text-properties 0 (length s) org-rm-props s)
8981 (replace-regexp-in-string
8982 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8983 (replace-regexp-in-string
8984 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8985 (org-link-display-format s)
8988 (defvar org-priority-regexp) ; defined later in the file
8990 (defvar org-after-sorting-entries-or-items-hook nil
8991 "Hook that is run after a bunch of entries or items have been sorted.
8992 When children are sorted, the cursor is in the parent line when this
8993 hook gets called. When a region or a plain list is sorted, the cursor
8994 will be in the first entry of the sorted region/list.")
8996 (defun org-sort-entries
8997 (&optional with-case sorting-type getkey-func compare-func property)
8998 "Sort entries on a certain level of an outline tree.
8999 If there is an active region, the entries in the region are sorted.
9000 Else, if the cursor is before the first entry, sort the top-level items.
9001 Else, the children of the entry at point are sorted.
9003 Sorting can be alphabetically, numerically, by date/time as given by
9004 a time stamp, by a property, by priority order, or by a custom function.
9006 The command prompts for the sorting type unless it has been given to the
9007 function through the SORTING-TYPE argument, which needs to be a character,
9008 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9009 the precise meaning of each character:
9011 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9012 c By creation time, which is assumed to be the first inactive time stamp
9013 at the beginning of a line.
9014 d By deadline date/time.
9016 n Numerically, by converting the beginning of the entry/item to a number.
9017 o By order of TODO keywords.
9018 p By priority according to the cookie.
9019 r By the value of a property.
9020 s By scheduled date/time.
9021 t By date/time, either the first active time stamp in the entry, or, if
9022 none exist, by the first inactive one.
9024 Capital letters will reverse the sort order.
9026 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9027 called with point at the beginning of the record. It must return either
9028 a string or a number that should serve as the sorting key for that record.
9030 Comparing entries ignores case by default. However, with an optional argument
9031 WITH-CASE, the sorting considers case as well.
9033 Sorting is done against the visible part of the headlines, it ignores hidden
9036 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
9038 (let ((case-func (if with-case 'identity 'downcase))
9040 ;; The clock marker is lost when using `sort-subr', let's
9041 ;; store the clocking string.
9042 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9044 (goto-char org-clock-marker)
9045 (buffer-substring-no-properties (line-beginning-position)
9047 start beg end stars re re2
9049 ;; Find beginning and end of region to sort
9051 ((org-region-active-p)
9052 ;; we will sort the region
9053 (setq end (region-end)
9055 (goto-char (region-beginning))
9056 (unless (org-at-heading-p) (outline-next-heading))
9057 (setq start (point)))
9058 ((or (org-at-heading-p)
9059 (ignore-errors (progn (org-back-to-heading) t)))
9060 ;; we will sort the children of the current headline
9061 (org-back-to-heading)
9063 end (progn (org-end-of-subtree t t)
9064 (or (bolp) (insert "\n"))
9065 (when (>= (org-back-over-empty-lines) 1)
9070 (outline-show-subtree)
9071 (outline-next-heading))
9073 ;; we will sort the top-level entries in this file
9074 (goto-char (point-min))
9075 (or (org-at-heading-p) (outline-next-heading))
9076 (setq start (point))
9077 (goto-char (point-max))
9078 (beginning-of-line 1)
9079 (when (looking-at ".*?\\S-")
9080 ;; File ends in a non-white line
9083 (setq end (point-max))
9084 (setq what "top-level")
9086 (outline-show-all)))
9089 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9091 (looking-at "\\(\\*+\\)")
9092 (setq stars (match-string 1)
9093 re (concat "^" (regexp-quote stars) " +")
9094 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9095 txt (buffer-substring beg end))
9096 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9097 (when (and (not (equal stars "*")) (string-match re2 txt))
9098 (user-error "Region to sort contains a level above the first entry"))
9100 (unless sorting-type
9102 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9103 [t]ime
[s]cheduled [d]eadline [c]reated cloc[k]ing
9104 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9106 (setq sorting-type (read-char-exclusive))
9109 (and (= (downcase sorting-type) ?f)
9111 (completing-read "Sort using function: "
9112 obarray 'fboundp t nil nil))
9113 (setq getkey-func (intern getkey-func))))
9115 (and (= (downcase sorting-type) ?r)
9118 (completing-read "Property: "
9119 (mapcar #'list (org-buffer-property-keys t))
9122 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9123 (message "Sorting entries...")
9126 (narrow-to-region start end)
9127 (let ((dcst (downcase sorting-type))
9128 (case-fold-search nil)
9129 (now (current-time)))
9131 (/= dcst sorting-type)
9132 ;; This function moves to the beginning character of the "record" to
9135 (if (re-search-forward re nil t)
9136 (goto-char (match-beginning 0))
9137 (goto-char (point-max))))
9138 ;; This function moves to the last character of the "record" being
9143 (outline-forward-same-level 1)
9145 (goto-char (point-max))))))
9146 ;; This function returns the value that gets sorted against.
9150 (if (looking-at org-complex-heading-regexp)
9151 (string-to-number (org-sort-remove-invisible (match-string 4)))
9154 (if (looking-at org-complex-heading-regexp)
9155 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9158 (or (get-text-property (point) :org-clock-minutes) 0))
9160 (let ((end (save-excursion (outline-next-heading) (point))))
9161 (if (or (re-search-forward org-ts-regexp end t)
9162 (re-search-forward org-ts-regexp-both end t))
9163 (org-time-string-to-seconds (match-string 0))
9166 (let ((end (save-excursion (outline-next-heading) (point))))
9167 (if (re-search-forward
9168 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9170 (org-time-string-to-seconds (match-string 0))
9173 (let ((end (save-excursion (outline-next-heading) (point))))
9174 (if (re-search-forward org-scheduled-time-regexp end t)
9175 (org-time-string-to-seconds (match-string 1))
9178 (let ((end (save-excursion (outline-next-heading) (point))))
9179 (if (re-search-forward org-deadline-time-regexp end t)
9180 (org-time-string-to-seconds (match-string 1))
9183 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9184 (string-to-char (match-string 2))
9185 org-default-priority))
9187 (or (org-entry-get nil property) ""))
9189 (when (looking-at org-complex-heading-regexp)
9190 (let* ((m (match-string 2))
9191 (s (if (member m org-done-keywords) '- '+)))
9192 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9196 (setq tmp (funcall getkey-func))
9197 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9199 (error "Invalid key function `%s'" getkey-func)))
9200 (t (error "Invalid sorting type `%c'" sorting-type))))
9203 ((= dcst ?a) 'string<)
9204 ((= dcst ?f) compare-func)
9205 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9206 (run-hooks 'org-after-sorting-entries-or-items-hook)
9207 ;; Reset the clock marker if needed
9211 (search-forward cmstr nil t)
9212 (move-marker org-clock-marker (point))))
9213 (message "Sorting entries...done")))
9215 ;;; The orgstruct minor mode
9217 ;; Define a minor mode which can be used in other modes in order to
9218 ;; integrate the Org mode structure editing commands.
9220 ;; This is really a hack, because the Org mode structure commands use
9221 ;; keys which normally belong to the major mode. Here is how it
9222 ;; works: The minor mode defines all the keys necessary to operate the
9223 ;; structure commands, but wraps the commands into a function which
9224 ;; tests if the cursor is currently at a headline or a plain list
9225 ;; item. If that is the case, the structure command is used,
9226 ;; temporarily setting many Org mode variables like regular
9227 ;; expressions for filling etc. However, when any of those keys is
9228 ;; used at a different location, function uses `key-binding' to look
9229 ;; up if the key has an associated command in another currently active
9230 ;; keymap (minor modes, major mode, global), and executes that
9231 ;; command. There might be problems if any of the keys is otherwise
9232 ;; used as a prefix key.
9234 (defcustom orgstruct-heading-prefix-regexp ""
9235 "Regexp that matches the custom prefix of Org headlines in
9236 orgstruct(++)-mode."
9239 :package-version '(Org . "8.3")
9241 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9243 (defcustom orgstruct-setup-hook nil
9244 "Hook run after orgstruct-mode-map is filled."
9247 :package-version '(Org . "8.0")
9250 (defvar orgstruct-initialized nil)
9252 (defvar org-local-vars nil
9253 "List of local variables, for use by `orgstruct-mode'.")
9256 (define-minor-mode orgstruct-mode
9257 "Toggle the minor mode `orgstruct-mode'.
9258 This mode is for using Org mode structure commands in other
9259 modes. The following keys behave as if Org mode were active, if
9260 the cursor is on a headline, or on a plain list item (both as
9261 defined by Org mode)."
9262 nil " OrgStruct" (make-sparse-keymap)
9263 (funcall (if orgstruct-mode
9264 'add-to-invisibility-spec
9265 'remove-from-invisibility-spec)
9267 (when orgstruct-mode
9268 (org-load-modules-maybe)
9269 (unless orgstruct-initialized
9271 (setq orgstruct-initialized t))))
9274 (defun turn-on-orgstruct ()
9275 "Unconditionally turn on `orgstruct-mode'."
9278 (defvar-local orgstruct-is-++ nil
9279 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9280 (defvar-local org-fb-vars nil)
9281 (defun orgstruct++-mode (&optional arg)
9282 "Toggle `orgstruct-mode', the enhanced version of it.
9283 In addition to setting orgstruct-mode, this also exports all
9284 indentation and autofilling variables from Org mode into the
9285 buffer. It will also recognize item context in multiline items."
9287 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9289 (progn (orgstruct-mode -1)
9290 (dolist (v org-fb-vars)
9291 (set (make-local-variable (car v))
9292 (if (eq (car-safe (cadr v)) 'quote)
9296 (setq org-fb-vars nil)
9297 (unless org-local-vars
9298 (setq org-local-vars (org-get-local-variables)))
9300 (dolist (x org-local-vars)
9302 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9303 \\|fill-prefix\\|indent-\\)"
9304 (symbol-name (car x)))
9305 (setq var (car x) val (nth 1 x))
9306 (push (list var `(quote ,(eval var))) org-fb-vars)
9307 (set (make-local-variable var)
9308 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9309 (setq-local orgstruct-is-++ t))))
9312 (defun turn-on-orgstruct++ ()
9313 "Unconditionally turn on `orgstruct++-mode'."
9314 (orgstruct++-mode 1))
9316 (defun orgstruct-error ()
9317 "Error when there is no default binding for a structure key."
9319 (funcall (if (fboundp 'user-error)
9322 "This key has no function outside structure elements"))
9324 (defun orgstruct-setup ()
9325 "Setup orgstruct keymap."
9326 (dolist (cell '((org-demote . t)
9330 (org-shiftmetaleft . t)
9331 (org-shiftmetaright . t)
9332 org-backward-element
9333 org-backward-heading-same-level
9338 org-force-cycle-archived
9339 org-forward-heading-same-level
9341 org-insert-heading-respect-content
9342 org-kill-note-or-show-branches
9347 org-narrow-to-subtree
9363 outline-next-visible-heading
9364 outline-previous-visible-heading
9366 outline-up-heading))
9367 (let ((f (or (car-safe cell) cell))
9368 (disable-when-heading-prefix (cdr-safe cell)))
9370 (let ((new-bindings))
9371 (dolist (binding (nconc (where-is-internal f org-mode-map)
9372 (where-is-internal f outline-mode-map)))
9373 (push binding new-bindings)
9374 ;; TODO use local-function-key-map
9375 (dolist (rep '(("<tab>" . "TAB")
9376 ("<return>" . "RET")
9377 ("<escape>" . "ESC")
9378 ("<delete>" . "DEL")))
9379 (setq binding (read-kbd-macro
9380 (let ((case-fold-search))
9381 (replace-regexp-in-string
9382 (regexp-quote (cdr rep))
9384 (key-description binding)))))
9385 (cl-pushnew binding new-bindings :test 'equal)))
9386 (dolist (binding new-bindings)
9387 (let ((key (lookup-key orgstruct-mode-map binding)))
9388 (when (or (not key) (numberp key))
9390 (org-defkey orgstruct-mode-map
9392 (orgstruct-make-binding
9393 f binding disable-when-heading-prefix))))))))))
9394 (run-hooks 'orgstruct-setup-hook))
9396 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9397 "Create a function for binding in the structure minor mode.
9398 FUN is the command to call inside a table. KEY is the key that
9399 should be checked in for a command to execute outside of tables.
9400 Non-nil `disable-when-heading-prefix' means to disable the command
9401 if `orgstruct-heading-prefix-regexp' is not empty."
9402 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9405 (while (fboundp (intern nname))
9406 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9407 (setq name (intern nname)))
9409 (let ((bindings '((org-heading-regexp
9411 orgstruct-heading-prefix-regexp
9412 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9414 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9415 (org-outline-regexp-bol
9416 (concat "^" org-outline-regexp))
9417 (outline-regexp org-outline-regexp)
9418 (outline-heading-end-regexp "\n")
9419 (outline-level 'org-outline-level)
9420 (outline-heading-alist))))
9422 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9423 "Outside of structure, run the binding of `"
9424 (key-description key) "'."
9425 (when disable-when-heading-prefix
9427 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9428 "back to the default binding due to limitations of Org's implementation of\n"
9429 "`" (symbol-name fun) "'.")))
9432 ,(and disable-when-heading-prefix
9433 '(not (string= orgstruct-heading-prefix-regexp ""))))
9438 (org-context-p 'headline 'item
9440 '(org-insert-heading
9441 org-insert-heading-respect-content
9443 '(when orgstruct-is-++
9446 (let* ((orgstruct-mode)
9453 ("<\\([^>]*\\)tab>" . "\\1TAB")
9454 ("<\\([^>]*\\)return>" . "\\1RET")
9455 ("<\\([^>]*\\)escape>" . "\\1ESC")
9456 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9459 (setq key (read-kbd-macro
9460 (let ((case-fold-search))
9461 (replace-regexp-in-string
9464 (key-description key))))))
9465 (when (key-binding key)
9466 (throw 'exit (key-binding key))))))))
9467 (if (keymapp binding)
9468 (org-set-transient-map binding)
9469 (let ((func (or binding
9471 'orgstruct-error))))
9473 (call-interactively func)))))
9474 (org-run-like-in-org-mode
9478 (call-interactively ',fun)))))))))
9481 (defun org-contextualize-keys (alist contexts)
9482 "Return valid elements in ALIST depending on CONTEXTS.
9484 `org-agenda-custom-commands' or `org-capture-templates' are the
9485 values used for ALIST, and `org-agenda-custom-commands-contexts'
9486 or `org-capture-templates-contexts' are the associated contexts
9489 ;; normalize contexts
9491 (lambda(c) (cond ((listp (cadr c))
9492 (list (car c) (car c) (nth 1 c)))
9493 ((string= "" (cadr c))
9494 (list (car c) (car c) (nth 2 c)))
9498 ;; loop over all commands or templates
9502 ((not (assoc (car c) contexts))
9504 ((and (assoc (car c) contexts)
9505 (setq vrules (org-contextualize-validate-key
9508 (unless (equal (car vr) (cadr vr))
9511 (if (not repl) (push c r)
9512 (push (cadr repl) s)
9515 (cdr (or (assoc (cadr repl) alist)
9516 (error "Undefined key `%s' as contextual replacement for `%s'"
9517 (cadr repl) (car c)))))
9519 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9524 (let ((tpl (car x)))
9533 (defun org-contextualize-validate-key (key contexts)
9534 "Check CONTEXTS for agenda or capture KEY."
9536 (dolist (r contexts)
9537 (dolist (rr (car (last r)))
9539 (and (equal key (car r))
9540 (if (functionp rr) (funcall rr)
9541 (or (and (eq (car rr) 'in-file)
9543 (string-match (cdr rr) (buffer-file-name)))
9544 (and (eq (car rr) 'in-mode)
9545 (string-match (cdr rr) (symbol-name major-mode)))
9546 (and (eq (car rr) 'in-buffer)
9547 (string-match (cdr rr) (buffer-name)))
9548 (when (and (eq (car rr) 'not-in-file)
9550 (not (string-match (cdr rr) (buffer-file-name))))
9551 (when (eq (car rr) 'not-in-mode)
9552 (not (string-match (cdr rr) (symbol-name major-mode))))
9553 (when (eq (car rr) 'not-in-buffer)
9554 (not (string-match (cdr rr) (buffer-name)))))))
9556 (delete-dups (delq nil res))))
9558 (defun org-context-p (&rest contexts)
9559 "Check if local context is any of CONTEXTS.
9560 Possible values in the list of contexts are `table', `headline', and `item'."
9561 (let ((pos (point)))
9562 (goto-char (point-at-bol))
9563 (prog1 (or (and (memq 'table contexts)
9564 (looking-at "[ \t]*|"))
9565 (and (memq 'headline contexts)
9566 (looking-at org-outline-regexp))
9567 (and (memq 'item contexts)
9568 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9569 (and (memq 'item-body contexts)
9573 (defconst org-unique-local-variables
9574 '(org-element--cache
9575 org-element--cache-objects
9576 org-element--cache-sync-keys
9577 org-element--cache-sync-requests
9578 org-element--cache-sync-timer)
9579 "List of local variables that cannot be transferred to another buffer.")
9581 (defun org-get-local-variables ()
9582 "Return a list of all local variables in an Org mode buffer."
9586 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9587 (name (car binding)))
9588 (and (not (get name 'org-state))
9589 (not (memq name org-unique-local-variables))
9591 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9592 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9597 (buffer-local-variables)))))
9599 (defun org-clone-local-variables (from-buffer &optional regexp)
9600 "Clone local variables from FROM-BUFFER.
9601 Optional argument REGEXP selects variables to clone."
9602 (dolist (pair (buffer-local-variables from-buffer))
9603 (let ((name (car pair)))
9604 (when (and (symbolp name)
9605 (not (memq name org-unique-local-variables))
9606 (or (null regexp) (string-match regexp (symbol-name name))))
9607 (set (make-local-variable name) (cdr pair))))))
9610 (defun org-run-like-in-org-mode (cmd)
9611 "Run a command, pretending that the current buffer is in Org mode.
9612 This will temporarily bind local variables that are typically bound in
9613 Org mode to the values they have in Org mode, and then interactively
9615 (org-load-modules-maybe)
9616 (unless org-local-vars
9617 (setq org-local-vars (org-get-local-variables)))
9619 (dolist (var org-local-vars)
9620 (when (or (not (boundp (car var)))
9621 (eq (symbol-value (car var))
9622 (default-value (car var))))
9623 (push (list (car var) `(quote ,(cadr var))) binds)))
9625 (call-interactively (quote ,cmd))))))
9627 (defun org-get-category (&optional pos force-refresh)
9628 "Get the category applying to position POS."
9630 (when force-refresh (org-refresh-category-properties))
9631 (let ((pos (or pos (point))))
9632 (or (get-text-property pos 'org-category)
9633 (progn (org-refresh-category-properties)
9634 (get-text-property pos 'org-category))))))
9636 ;;; Refresh properties
9638 (defun org-refresh-properties (dprop tprop)
9639 "Refresh buffer text properties.
9640 DPROP is the drawer property and TPROP is either the
9641 corresponding text property to set, or an alist with each element
9642 being a text property (as a symbol) and a function to apply to
9643 the value of the drawer property."
9644 (let ((case-fold-search t)
9645 (inhibit-read-only t))
9646 (org-with-silent-modifications
9647 (org-with-wide-buffer
9648 (goto-char (point-min))
9649 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9650 (org-refresh-property tprop (match-string-no-properties 1)))))))
9652 (defun org-refresh-property (tprop p)
9653 "Refresh the buffer text property TPROP from the drawer property P.
9654 The refresh happens only for the current tree (not subtree)."
9655 (unless (org-before-first-heading-p)
9657 (org-back-to-heading t)
9659 ;; TPROP is a text property symbol
9661 (point) (or (outline-next-heading) (point-max)) tprop p)
9662 ;; TPROP is an alist with (properties . function) elements
9666 (line-beginning-position) (or (outline-next-heading) (point-max))
9668 (funcall (cdr al) p))))))))
9670 (defun org-refresh-category-properties ()
9671 "Refresh category text properties in the buffer."
9672 (let ((case-fold-search t)
9673 (inhibit-read-only t)
9675 (cond ((null org-category)
9676 (if buffer-file-name
9677 (file-name-sans-extension
9678 (file-name-nondirectory buffer-file-name))
9680 ((symbolp org-category) (symbol-name org-category))
9682 (org-with-silent-modifications
9683 (org-with-wide-buffer
9684 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9685 ;; This is the default category for the buffer. If none is
9686 ;; found, fall-back to `org-category' or buffer file name.
9688 (point-min) (point-max)
9690 (catch 'buffer-category
9691 (goto-char (point-max))
9692 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9693 (let ((element (org-element-at-point)))
9694 (when (eq (org-element-type element) 'keyword)
9695 (throw 'buffer-category
9696 (org-element-property :value element)))))
9698 ;; Set sub-tree specific categories.
9699 (goto-char (point-min))
9700 (let ((regexp (org-re-property "CATEGORY")))
9701 (while (re-search-forward regexp nil t)
9702 (let ((value (match-string-no-properties 3)))
9703 (when (org-at-property-p)
9705 (save-excursion (org-back-to-heading t) (point))
9706 (save-excursion (org-end-of-subtree t t) (point))
9710 (defun org-refresh-stats-properties ()
9711 "Refresh stats text properties in the buffer."
9713 (org-with-silent-modifications
9714 (org-with-wide-buffer
9715 (goto-char (point-min))
9716 (while (re-search-forward
9717 (concat org-outline-regexp-bol ".*"
9718 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9720 (setq stats (cond ((equal (match-string 3) "0") 0)
9722 (/ (* (string-to-number (match-string 2)) 100)
9723 (string-to-number (match-string 3))))
9724 (t (string-to-number (match-string 1)))))
9725 (org-back-to-heading t)
9726 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9727 'org-stats stats))))))
9729 (defun org-refresh-effort-properties ()
9730 "Refresh effort properties"
9731 (org-refresh-properties
9733 '((effort . identity)
9734 (effort-minutes . org-duration-string-to-minutes))))
9738 ;;; Link abbreviations
9740 (defun org-link-expand-abbrev (link)
9741 "Apply replacements as defined in `org-link-abbrev-alist'."
9742 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9743 (let* ((key (match-string 1 link))
9744 (as (or (assoc key org-link-abbrev-alist-local)
9745 (assoc key org-link-abbrev-alist)))
9746 (tag (and (match-end 2) (match-string 3 link)))
9752 ((symbolp rpl) (funcall rpl tag))
9753 ((string-match "%(\\([^)]+\\))" rpl)
9756 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9757 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9758 ((string-match "%h" rpl)
9759 (replace-match (url-hexify-string (or tag "")) t t rpl))
9760 (t (concat rpl tag)))))
9763 ;;; Storing and inserting links
9765 (defvar org-insert-link-history nil
9766 "Minibuffer history for links inserted with `org-insert-link'.")
9768 (defvar org-stored-links nil
9769 "Contains the links stored with `org-store-link'.")
9771 (defvar org-store-link-plist nil
9772 "Plist with info about the most recently link created with `org-store-link'.")
9774 (defun org-store-link-functions ()
9775 "Return a list of functions that are called to create and store a link.
9776 The functions defined in the :store property of
9777 `org-link-parameters'.
9779 Each function will be called in turn until one returns a non-nil
9780 value. Each function should check if it is responsible for
9781 creating this link (for example by looking at the major mode).
9782 If not, it must exit and return nil. If yes, it should return
9783 a non-nil value after calling `org-store-link-props' with a list
9784 of properties and values. Special properties are:
9786 :type The link prefix, like \"http\". This must be given.
9787 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9788 This is obligatory as well.
9789 :description Optional default description for the second pair
9790 of brackets in an Org mode link. The user can still change
9791 this when inserting this link into an Org mode buffer.
9793 In addition to these, any additional properties can be specified
9794 and then used in capture templates."
9795 (cl-loop for link in org-link-parameters
9797 do (setq store-func (org-link-get-parameter (car link) :store))
9799 collect store-func))
9801 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9802 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9805 (defun org-store-link (arg)
9806 "Store an org-link to the current location.
9808 This link is added to `org-stored-links' and can later be inserted
9809 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9811 For some link types, a `\\[universal-argument]' prefix ARG is interpreted.
9812 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9813 For file links, ARG negates `org-context-in-file-links'.
9815 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9816 skipping storing functions that are not
9819 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9820 prefix ARG forces storing a link for each line in the
9823 (org-load-modules-maybe)
9824 (if (and (equal arg '(64)) (org-region-active-p))
9826 (let ((end (region-end)))
9827 (goto-char (region-beginning))
9829 (while (< (point-at-eol) end)
9830 (move-end-of-line 1) (activate-mark)
9831 (let (current-prefix-arg)
9832 (call-interactively 'org-store-link))
9833 (move-beginning-of-line 2)
9834 (set-mark (point)))))
9835 (setq org-store-link-plist nil)
9836 (let (link cpltxt desc description search
9837 txt custom-id agenda-link sfuns sfunsn)
9840 ;; Store a link using an external link type
9841 ((and (not (equal arg '(16)))
9844 nil (mapcar (lambda (f)
9845 (let (fs) (if (funcall f) (push f fs))))
9846 (org-store-link-functions)))
9847 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9848 (or (and (cdr sfuns)
9851 "Which function for creating the link? "
9852 sfunsn nil t (car sfunsn)))))
9853 (funcall (caar sfuns)))
9854 (setq link (plist-get org-store-link-plist :link)
9855 desc (or (plist-get org-store-link-plist
9859 ;; Store a link from a source code buffer.
9860 ((org-src-edit-buffer-p)
9861 (let ((coderef-format (org-src-coderef-format)))
9862 (cond ((save-excursion
9864 (looking-at (org-src-coderef-regexp coderef-format)))
9865 (setq link (format "(%s)" (match-string-no-properties 3))))
9866 ((called-interactively-p 'any)
9867 (let ((label (read-string "Code line label: ")))
9869 (setq link (format coderef-format label))
9870 (let ((gc (- 79 (length link))))
9871 (if (< (current-column) gc)
9872 (org-move-to-column gc t)
9875 (setq link (concat "(" label ")"))
9877 (t (setq link nil)))))
9879 ;; We are in the agenda, link to referenced location
9880 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9881 (let ((m (or (get-text-property (point) 'org-hd-marker)
9882 (get-text-property (point) 'org-marker))))
9884 (org-with-point-at m
9886 (if (called-interactively-p 'any)
9887 (call-interactively 'org-store-link)
9888 (org-store-link nil)))))))
9890 ((eq major-mode 'calendar-mode)
9891 (let ((cd (calendar-cursor-to-date)))
9894 (car org-time-stamp-formats)
9896 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9898 (org-store-link-props :type "calendar" :date cd)))
9900 ((eq major-mode 'help-mode)
9901 (setq link (concat "help:" (save-excursion
9902 (goto-char (point-min))
9903 (looking-at "^[^ ]+")
9905 (org-store-link-props :type "help"))
9907 ((eq major-mode 'w3-mode)
9908 (setq cpltxt (if (and (buffer-name)
9909 (not (string-match "Untitled" (buffer-name))))
9912 link (url-view-url t))
9913 (org-store-link-props :type "w3" :url (url-view-url t)))
9915 ((eq major-mode 'image-mode)
9916 (setq cpltxt (concat "file:"
9917 (abbreviate-file-name buffer-file-name))
9919 (org-store-link-props :type "image" :file buffer-file-name))
9921 ;; In dired, store a link to the file of the current line
9922 ((derived-mode-p 'dired-mode)
9923 (let ((file (dired-get-filename nil t)))
9925 (abbreviate-file-name
9926 (expand-file-name (dired-get-filename nil t)))
9927 ;; otherwise, no file so use current directory.
9929 (setq cpltxt (concat "file:" file)
9932 ((setq search (run-hook-with-args-until-success
9933 'org-create-file-search-functions))
9934 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9936 (setq cpltxt (or description link)))
9938 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9939 (org-with-limited-levels
9940 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9942 ;; Store a link using the target at point
9943 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9946 (abbreviate-file-name
9947 (buffer-file-name (buffer-base-buffer)))
9948 "::" (match-string 1))
9950 ((and (featurep 'org-id)
9951 (or (eq org-id-link-to-org-use-id t)
9952 (and (called-interactively-p 'any)
9953 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9954 (and (eq org-id-link-to-org-use-id
9955 'create-if-interactive-and-no-custom-id)
9957 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9958 ;; Store a link using the ID at point
9959 (setq link (condition-case nil
9960 (prog1 (org-id-store-link)
9961 (setq desc (or (plist-get org-store-link-plist
9965 ;; Probably before first headline, link only to file
9967 (abbreviate-file-name
9968 (buffer-file-name (buffer-base-buffer))))))))
9970 ;; Just link to current headline
9971 (setq cpltxt (concat "file:"
9972 (abbreviate-file-name
9973 (buffer-file-name (buffer-base-buffer)))))
9974 ;; Add a context search string
9975 (when (org-xor org-context-in-file-links arg)
9976 (let* ((element (org-element-at-point))
9977 (name (org-element-property :name element)))
9979 ((org-at-heading-p) nil)
9981 ((org-region-active-p)
9982 (buffer-substring (region-beginning) (region-end)))))
9983 (when (or (null txt) (string-match "\\S-" txt))
9987 (org-make-org-heading-search-string txt)
9990 (nth 4 (ignore-errors (org-heading-components)))
9992 (when (string-match "::\\'" cpltxt)
9993 (setq cpltxt (substring cpltxt 0 -2)))
9994 (setq link cpltxt)))))
9996 ((buffer-file-name (buffer-base-buffer))
9997 ;; Just link to this file here.
9998 (setq cpltxt (concat "file:"
9999 (abbreviate-file-name
10000 (buffer-file-name (buffer-base-buffer)))))
10001 ;; Add a context string.
10002 (when (org-xor org-context-in-file-links arg)
10003 (setq txt (if (org-region-active-p)
10004 (buffer-substring (region-beginning) (region-end))
10005 (buffer-substring (point-at-bol) (point-at-eol))))
10006 ;; Only use search option if there is some text.
10007 (when (string-match "\\S-" txt)
10009 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10011 (setq link cpltxt))
10013 ((called-interactively-p 'interactive)
10014 (user-error "No method for storing a link from this buffer"))
10016 (t (setq link nil)))
10018 ;; We're done setting link and desc, clean up
10019 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10020 (setq link (or link cpltxt)
10021 desc (or desc cpltxt))
10023 ((equal desc "NONE") (setq desc nil))
10025 (replace-regexp-in-string
10026 org-bracket-link-analytic-regexp
10027 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10030 (if (not (and (or (called-interactively-p 'any)
10031 executing-kbd-macro)
10033 (or agenda-link (and link (org-make-link-string link desc)))
10034 (push (list link desc) org-stored-links)
10035 (message "Stored: %s" (or desc link))
10037 (setq link (concat "file:" (abbreviate-file-name
10038 (buffer-file-name)) "::#" custom-id))
10039 (push (list link desc) org-stored-links))
10040 (car org-stored-links)))))
10042 (defun org-store-link-props (&rest plist)
10043 "Store link properties, extract names, addresses and dates."
10044 (let ((x (plist-get plist :from)))
10046 (let ((adr (mail-extract-address-components x)))
10047 (setq plist (plist-put plist :fromname (car adr)))
10048 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10049 (let ((x (plist-get plist :to)))
10051 (let ((adr (mail-extract-address-components x)))
10052 (setq plist (plist-put plist :toname (car adr)))
10053 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10054 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10056 (setq plist (plist-put plist :date-timestamp
10057 (format-time-string
10058 (org-time-stamp-format t) x)))
10059 (setq plist (plist-put plist :date-timestamp-inactive
10060 (format-time-string
10061 (org-time-stamp-format t t) x)))))
10062 (let ((from (plist-get plist :from))
10063 (to (plist-get plist :to)))
10064 (when (and from to org-from-is-user-regexp)
10066 (plist-put plist :fromto
10067 (if (string-match org-from-is-user-regexp from)
10069 (concat "from %f"))))))
10070 (setq org-store-link-plist plist))
10072 (defun org-add-link-props (&rest plist)
10073 "Add these properties to the link property list."
10076 (setq key (pop plist) value (pop plist))
10077 (setq org-store-link-plist
10078 (plist-put org-store-link-plist key value)))))
10080 (defun org-email-link-description (&optional fmt)
10081 "Return the description part of an email link.
10082 This takes information from `org-store-link-plist' and formats it
10083 according to FMT (default from `org-email-link-description-format')."
10084 (setq fmt (or fmt org-email-link-description-format))
10085 (let* ((p org-store-link-plist)
10086 (to (plist-get p :toaddress))
10087 (from (plist-get p :fromaddress))
10090 (cons "%c" (plist-get p :fromto))
10091 (cons "%F" (plist-get p :from))
10092 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10093 (cons "%T" (plist-get p :to))
10094 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10095 (cons "%s" (plist-get p :subject))
10096 (cons "%d" (plist-get p :date))
10097 (cons "%m" (plist-get p :message-id)))))
10098 (when (string-match "%c" fmt)
10099 ;; Check if the user wrote this message
10100 (if (and org-from-is-user-regexp from to
10101 (save-match-data (string-match org-from-is-user-regexp from)))
10102 (setq fmt (replace-match "to %t" t t fmt))
10103 (setq fmt (replace-match "from %f" t t fmt))))
10104 (org-replace-escapes fmt table)))
10106 (defun org-make-org-heading-search-string (&optional string)
10107 "Make search string for the current headline or STRING."
10108 (let ((s (or string
10109 (and (derived-mode-p 'org-mode)
10111 (org-back-to-heading t)
10112 (org-element-property :raw-value (org-element-at-point))))))
10113 (lines org-context-in-file-links))
10114 (or string (setq s (concat "*" s))) ; Add * for headlines
10115 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10116 (when (and string (integerp lines) (> lines 0))
10117 (let ((slines (org-split-string s "\n")))
10118 (when (< lines (length slines))
10121 (reverse (nthcdr (- (length slines) lines)
10122 (reverse slines))) "\n")))))
10123 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10125 (defun org-make-link-string (link &optional description)
10126 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10127 (unless (org-string-nw-p link) (error "Empty link"))
10128 (let ((uri (cond ((string-match org-link-types-re link)
10129 (concat (match-string 1 link)
10130 (org-link-escape (substring link (match-end 1)))))
10131 ;; For readability, url-encode internal links only
10132 ;; when absolutely needed (i.e, when they contain
10133 ;; square brackets). File links however, are
10134 ;; encoded since, e.g., spaces are significant.
10135 ((or (file-name-absolute-p link)
10136 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10137 (org-link-escape link))
10140 (and (org-string-nw-p description)
10141 ;; Remove brackets from description, as they are fatal.
10142 (replace-regexp-in-string
10143 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10144 (org-trim description)))))
10147 (if description (format "[%s]" description) ""))))
10149 (defconst org-link-escape-chars
10152 "List of characters that should be escaped in a link when stored to Org.
10153 This is the list that is used for internal purposes.")
10155 (defun org-link-escape (text &optional table merge)
10156 "Return percent escaped representation of TEXT.
10157 TEXT is a string with the text to escape.
10158 Optional argument TABLE is a list with characters that should be
10159 escaped. When nil, `org-link-escape-chars' is used.
10160 If optional argument MERGE is set, merge TABLE into
10161 `org-link-escape-chars'."
10162 (let ((characters-to-encode
10163 (cond ((null table) org-link-escape-chars)
10164 (merge (append org-link-escape-chars table))
10168 (if (or (memq c characters-to-encode)
10169 (and org-url-hexify-p (or (< c 32) (> c 126))))
10170 (mapconcat (lambda (e) (format "%%%.2X" e))
10171 (or (encode-coding-char c 'utf-8)
10172 (error "Unable to percent escape character: %c" c))
10174 (char-to-string c)))
10177 (defun org-link-unescape (str)
10178 "Unhex hexified Unicode parts in string STR.
10179 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10180 reciprocal of `org-link-escape', which see."
10181 (if (org-string-nw-p str)
10182 (replace-regexp-in-string
10183 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10186 (defun org-link-unescape-compound (hex)
10187 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10188 Note: this function also decodes single byte encodings like
10189 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10191 (let* ((bytes (cdr (split-string hex "%")))
10196 (let* ((val (string-to-number (pop bytes) 16))
10200 ((>= val 252) (cons 6 252))
10201 ((>= val 248) (cons 5 248))
10202 ((>= val 240) (cons 4 240))
10203 ((>= val 224) (cons 3 224))
10204 ((>= val 192) (cons 2 192))
10207 (when (>= val 192) (setq eat (car shift-xor)))
10208 (setq val (logxor val (cdr shift-xor)))
10209 (setq sum (+ (lsh sum (car shift-xor)) val))
10210 (when (> eat 0) (setq eat (- eat 1)))
10212 ((= 0 eat) ;multi byte
10213 (setq ret (concat ret (char-to-string sum)))
10215 ((not bytes) ; single byte(s)
10216 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10219 (defun org-link-unescape-single-byte-sequence (hex)
10220 "Unhexify hex-encoded single byte character sequences."
10221 (mapconcat (lambda (byte)
10222 (char-to-string (string-to-number byte 16)))
10223 (cdr (split-string hex "%")) ""))
10225 (defun org-xor (a b)
10229 (defun org-fixup-message-id-for-http (s)
10230 "Replace special characters in a message id, so it can be used in an http query."
10231 (when (string-match "%" s)
10232 (setq s (mapconcat (lambda (c)
10235 (char-to-string c)))
10237 (while (string-match "<" s)
10238 (setq s (replace-match "%3C" t t s)))
10239 (while (string-match ">" s)
10240 (setq s (replace-match "%3E" t t s)))
10241 (while (string-match "@" s)
10242 (setq s (replace-match "%40" t t s)))
10245 (defun org-link-prettify (link)
10246 "Return a human-readable representation of LINK.
10247 The car of LINK must be a raw link.
10248 The cdr of LINK must be either a link description or nil."
10249 (let ((desc (or (cadr link) "<no description>")))
10250 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10251 "<" (car link) ">")))
10254 (defun org-insert-link-global ()
10255 "Insert a link like Org mode does.
10256 This command can be called in any mode to insert a link in Org syntax."
10258 (org-load-modules-maybe)
10259 (org-run-like-in-org-mode 'org-insert-link))
10261 (defun org-insert-all-links (arg &optional pre post)
10262 "Insert all links in `org-stored-links'.
10263 When a universal prefix, do not delete the links from `org-stored-links'.
10264 When `ARG' is a number, insert the last N link(s).
10265 `PRE' and `POST' are optional arguments to define a string to
10266 prepend or to append."
10268 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10269 (links (copy-sequence org-stored-links))
10271 (po (or post "\n"))
10273 (if (null org-stored-links)
10274 (message "No link to insert")
10275 (while (and (or (listp arg) (>= arg cnt))
10276 (setq l (if (listp arg)
10278 (pop org-stored-links))))
10279 (setq cnt (1+ cnt))
10281 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10284 (defun org-insert-last-stored-link (arg)
10285 "Insert the last link stored in `org-stored-links'."
10287 (org-insert-all-links arg "" "\n"))
10289 (defun org-link-fontify-links-to-this-file ()
10290 "Fontify links to the current file in `org-stored-links'."
10291 (let ((f (buffer-file-name)) a b)
10292 (setq a (mapcar (lambda(l)
10293 (let ((ll (car l)))
10294 (when (and (string-match "^file:\\(.+\\)::" ll)
10295 (equal f (expand-file-name (match-string 1 ll))))
10298 (when (featurep 'org-id)
10299 (setq b (mapcar (lambda(l)
10300 (let ((ll (car l)))
10301 (when (and (string-match "^id:\\(.+\\)$" ll)
10302 (equal f (expand-file-name
10303 (or (org-id-find-id-file
10304 (match-string 1 ll)) ""))))
10306 org-stored-links)))
10308 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10309 (delq nil (append a b)))))
10311 (defvar org--links-history nil)
10312 (defun org-insert-link (&optional complete-file link-location default-description)
10313 "Insert a link. At the prompt, enter the link.
10315 Completion can be used to insert any of the link protocol prefixes in use.
10317 The history can be used to select a link previously stored with
10318 `org-store-link'. When the empty string is entered (i.e. if you just
10319 press `RET' at the prompt), the link defaults to the most recently
10320 stored link. As `SPC' triggers completion in the minibuffer, you need to
10321 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10323 You will also be prompted for a description, and if one is given, it will
10324 be displayed in the buffer instead of the link.
10326 If there is already a link at point, this command will allow you to edit
10327 link and description parts.
10329 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10331 selected using completion. The path to the file will be relative to the
10332 current directory if the file is in the current directory or a subdirectory.
10333 Otherwise, the link will be the absolute path as completed in the minibuffer
10334 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10335 option `org-link-file-path-type'.
10337 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10338 absolute path even if the file is in
10339 the current directory or below.
10341 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10342 prefix negates `org-keep-stored-link-after-insertion'.
10344 If `org-make-link-description-function' is non-nil, this function will be
10345 called with the link target, and the result will be the default
10348 If the LINK-LOCATION parameter is non-nil, this value will be used as
10349 the link location instead of reading one interactively.
10351 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10352 as the default description."
10354 (let* ((wcf (current-window-configuration))
10355 (origbuf (current-buffer))
10356 (region (when (org-region-active-p)
10357 (buffer-substring (region-beginning) (region-end))))
10358 (remove (and region (list (region-beginning) (region-end))))
10360 (link link-location)
10361 (abbrevs org-link-abbrev-alist-local)
10362 entry all-prefixes auto-desc)
10364 (link-location) ; specified by arg, just use it.
10365 ((org-in-regexp org-bracket-link-regexp 1)
10366 ;; We do have a link at point, and we are going to edit it.
10367 (setq remove (list (match-beginning 0) (match-end 0)))
10368 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10369 (setq link (read-string "Link: "
10371 (match-string-no-properties 1)))))
10372 ((or (org-in-regexp org-angle-link-re)
10373 (org-in-regexp org-plain-link-re))
10374 ;; Convert to bracket link
10375 (setq remove (list (match-beginning 0) (match-end 0))
10376 link (read-string "Link: "
10377 (org-unbracket-string "<" ">" (match-string 0)))))
10378 ((member complete-file '((4) (16)))
10379 ;; Completing read for file names.
10380 (setq link (org-file-complete-link complete-file)))
10382 ;; Read link, with completion for stored links.
10383 (org-link-fontify-links-to-this-file)
10384 (org-switch-to-buffer-other-window "*Org Links*")
10385 (with-current-buffer "*Org Links*"
10387 (insert "Insert a link.
10388 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10389 (when org-stored-links
10390 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10391 (insert (mapconcat 'org-link-prettify
10392 (reverse org-stored-links) "\n")))
10393 (goto-char (point-min)))
10394 (let ((cw (selected-window)))
10395 (select-window (get-buffer-window "*Org Links*" 'visible))
10396 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10397 (unless (pos-visible-in-window-p (point-max))
10398 (org-fit-window-to-buffer))
10399 (and (window-live-p cw) (select-window cw)))
10400 (setq all-prefixes (append (mapcar 'car abbrevs)
10401 (mapcar 'car org-link-abbrev-alist)
10404 ;; Fake a link history, containing the stored links.
10405 (let ((org--links-history
10406 (append (mapcar #'car org-stored-links)
10407 org-insert-link-history)))
10409 (org-completing-read
10412 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10413 (mapcar #'car org-stored-links))
10415 'org--links-history
10416 (caar org-stored-links)))
10417 (unless (org-string-nw-p link) (user-error "No link selected"))
10418 (dolist (l org-stored-links)
10419 (when (equal link (cadr l))
10420 (setq link (car l))
10421 (setq auto-desc t)))
10422 (when (or (member link all-prefixes)
10423 (and (equal ":" (substring link -1))
10424 (member (substring link 0 -1) all-prefixes)
10425 (setq link (substring link 0 -1))))
10426 (setq link (with-current-buffer origbuf
10427 (org-link-try-special-completion link)))))
10428 (set-window-configuration wcf)
10429 (kill-buffer "*Org Links*"))
10430 (setq entry (assoc link org-stored-links))
10431 (or entry (push link org-insert-link-history))
10432 (setq desc (or desc (nth 1 entry)))))
10434 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10435 (not org-keep-stored-link-after-insertion))
10436 (setq org-stored-links (delq (assoc link org-stored-links)
10437 org-stored-links)))
10439 (when (and (string-match org-plain-link-re link)
10440 (not (string-match org-ts-regexp link)))
10441 ;; URL-like link, normalize the use of angular brackets.
10442 (setq link (org-unbracket-string "<" ">" link)))
10444 ;; Check if we are linking to the current file with a search
10445 ;; option If yes, simplify the link by using only the search
10447 (when (and buffer-file-name
10448 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10449 (let* ((path (match-string 1 link))
10450 (case-fold-search nil)
10451 (search (match-string 2 link)))
10453 (when (equal (file-truename buffer-file-name) (file-truename path))
10454 ;; We are linking to this same file, with a search option
10455 (setq link search)))))
10457 ;; Check if we can/should use a relative path. If yes, simplify the link
10458 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10459 (let* ((type (match-string 1 link))
10460 (path (match-string 2 link))
10462 (case-fold-search nil))
10464 ((or (eq org-link-file-path-type 'absolute)
10465 (equal complete-file '(16)))
10466 (setq path (abbreviate-file-name (expand-file-name path))))
10467 ((eq org-link-file-path-type 'noabbrev)
10468 (setq path (expand-file-name path)))
10469 ((eq org-link-file-path-type 'relative)
10470 (setq path (file-relative-name path)))
10473 (if (string-match (concat "^" (regexp-quote
10475 (file-name-as-directory
10476 default-directory))))
10477 (expand-file-name path))
10478 ;; We are linking a file with relative path name.
10479 (setq path (substring (expand-file-name path)
10481 (setq path (abbreviate-file-name (expand-file-name path)))))))
10482 (setq link (concat type path))
10483 (when (equal desc origpath)
10484 (setq desc path))))
10486 (if org-make-link-description-function
10488 (or (condition-case nil
10489 (funcall org-make-link-description-function link desc)
10490 (error (progn (message "Can't get link description from `%s'"
10491 (symbol-name org-make-link-description-function))
10493 (read-string "Description: " default-description)))
10494 (if default-description (setq desc default-description)
10495 (setq desc (or (and auto-desc desc)
10496 (read-string "Description: " desc)))))
10498 (unless (string-match "\\S-" desc) (setq desc nil))
10499 (when remove (apply 'delete-region remove))
10500 (insert (org-make-link-string link desc))
10501 ;; Redisplay so as the new link has proper invisible characters.
10504 (defun org-link-try-special-completion (type)
10505 "If there is completion support for link type TYPE, offer it."
10506 (let ((fun (org-link-get-parameter type :complete)))
10507 (if (functionp fun)
10509 (read-string "Link (no completion support): " (concat type ":")))))
10511 (defun org-file-complete-link (&optional arg)
10512 "Create a file link using completion."
10513 (let ((file (read-file-name "File: "))
10514 (pwd (file-name-as-directory (expand-file-name ".")))
10515 (pwd1 (file-name-as-directory (abbreviate-file-name
10516 (expand-file-name ".")))))
10517 (cond ((equal arg '(16))
10519 (abbreviate-file-name (expand-file-name file))))
10521 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10522 (concat "file:" (match-string 1 file)))
10524 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10525 (expand-file-name file))
10527 (match-string 1 (expand-file-name file))))
10528 (t (concat "file:" file)))))
10530 (defun org-completing-read (&rest args)
10531 "Completing-read with SPACE being a normal character."
10532 (let ((enable-recursive-minibuffers t)
10533 (minibuffer-local-completion-map
10534 (copy-keymap minibuffer-local-completion-map)))
10535 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10536 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10537 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10538 'org-time-stamp-inactive)
10539 (apply #'completing-read args)))
10541 ;;; Opening/following a link
10543 (defvar org-link-search-failed nil)
10545 (defvar org-open-link-functions nil
10546 "Hook for functions finding a plain text link.
10547 These functions must take a single argument, the link content.
10548 They will be called for links that look like [[link text][description]]
10549 when LINK TEXT does not have a protocol like \"http:\" and does not look
10550 like a filename (e.g. \"./blue.png\").
10552 These functions will be called *before* Org attempts to resolve the
10553 link by doing text searches in the current buffer - so if you want a
10554 link \"[[target]]\" to still find \"<<target>>\", your function should
10555 handle this as a special case.
10557 When the function does handle the link, it must return a non-nil value.
10558 If it decides that it is not responsible for this link, it must return
10559 nil to indicate that that Org can continue with other options like
10560 exact and fuzzy text search.")
10562 (defun org-next-link (&optional search-backward)
10563 "Move forward to the next link.
10564 If the link is in hidden text, expose it."
10566 (when (and org-link-search-failed (eq this-command last-command))
10567 (goto-char (point-min))
10568 (message "Link search wrapped back to beginning of buffer"))
10569 (setq org-link-search-failed nil)
10570 (let* ((pos (point))
10572 (a (assq :link ct))
10573 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10574 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10575 ((looking-at org-any-link-re)
10576 ;; Don't stay stuck at link without an org-link face
10577 (forward-char (if search-backward -1 1))))
10578 (if (funcall srch-fun org-any-link-re nil t)
10580 (goto-char (match-beginning 0))
10581 (when (outline-invisible-p) (org-show-context)))
10583 (setq org-link-search-failed t)
10584 (message "No further link found"))))
10586 (defun org-previous-link ()
10587 "Move backward to the previous link.
10588 If the link is in hidden text, expose it."
10590 (funcall 'org-next-link t))
10592 (defun org-translate-link (s)
10593 "Translate a link string if a translation function has been defined."
10595 (insert (org-trim s))
10596 (org-trim (org-element-interpret-data (org-element-context)))))
10598 (defun org-translate-link-from-planner (type path)
10599 "Translate a link from Emacs Planner syntax so that Org can follow it.
10600 This is still an experimental function, your mileage may vary."
10602 ((member type '("http" "https" "news" "ftp"))
10603 ;; standard Internet links are the same.
10605 ((and (equal type "irc") (string-match "^//" path))
10606 ;; Planner has two / at the beginning of an irc link, we have 1.
10607 ;; We should have zero, actually....
10608 (setq path (substring path 1)))
10609 ((and (equal type "lisp") (string-match "^/" path))
10610 ;; Planner has a slash, we do not.
10611 (setq type "elisp" path (substring path 1)))
10612 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10613 ;; A typical message link. Planner has the id after the final slash,
10614 ;; we separate it with a hash mark
10615 (setq path (concat (match-string 1 path) "#"
10616 (org-unbracket-string "<" ">" (match-string 2 path))))))
10619 (defun org-find-file-at-mouse (ev)
10620 "Open file link or URL at mouse."
10622 (mouse-set-point ev)
10623 (org-open-at-point 'in-emacs))
10625 (defun org-open-at-mouse (ev)
10626 "Open file link or URL at mouse.
10627 See the docstring of `org-open-file' for details."
10629 (mouse-set-point ev)
10630 (when (eq major-mode 'org-agenda-mode)
10631 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10632 (org-open-at-point))
10634 (defvar org-window-config-before-follow-link nil
10635 "The window configuration before following a link.
10636 This is saved in case the need arises to restore it.")
10639 (defun org-open-at-point-global ()
10640 "Follow a link or time-stamp like Org mode does.
10641 This command can be called in any mode to follow an external link
10642 or a time-stamp that has Org mode syntax. Its behavior is
10643 undefined when called on internal links (e.g., fuzzy links).
10644 Raise an error when there is nothing to follow. "
10646 (cond ((org-in-regexp org-any-link-re)
10647 (org-open-link-from-string (match-string-no-properties 0)))
10648 ((or (org-in-regexp org-ts-regexp-both nil t)
10649 (org-in-regexp org-tsr-regexp-both nil t))
10650 (org-follow-timestamp-link))
10651 (t (user-error "No link found"))))
10654 (defun org-open-link-from-string (s &optional arg reference-buffer)
10655 "Open a link in the string S, as if it was in Org mode."
10656 (interactive "sLink: \nP")
10657 (let ((reference-buffer (or reference-buffer (current-buffer))))
10659 (let ((org-inhibit-startup (not reference-buffer)))
10662 (goto-char (point-min))
10663 (when reference-buffer
10664 (setq org-link-abbrev-alist-local
10665 (with-current-buffer reference-buffer
10666 org-link-abbrev-alist-local)))
10667 (org-open-at-point arg reference-buffer)))))
10669 (defvar org-open-at-point-functions nil
10670 "Hook that is run when following a link at point.
10672 Functions in this hook must return t if they identify and follow
10673 a link at point. If they don't find anything interesting at point,
10674 they must return nil.")
10676 (defvar org-link-search-inhibit-query nil)
10677 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10678 (defun org--open-doi-link (path)
10679 "Open a \"doi\" type link.
10680 PATH is a the path to search for, as a string."
10681 (browse-url (url-encode-url (concat org-doi-server-url path))))
10683 (defun org--open-elisp-link (path)
10684 "Open a \"elisp\" type link.
10685 PATH is the sexp to evaluate, as a string."
10687 (if (or (and (org-string-nw-p
10688 org-confirm-elisp-link-not-regexp)
10689 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10690 (not org-confirm-elisp-link-function)
10691 (funcall org-confirm-elisp-link-function
10692 (format "Execute \"%s\" as elisp? "
10693 (org-add-props cmd nil 'face 'org-warning))))
10694 (message "%s => %s" cmd
10695 (if (eq (string-to-char cmd) ?\()
10697 (call-interactively (read cmd))))
10698 (user-error "Abort"))))
10700 (defun org--open-help-link (path)
10701 "Open a \"help\" type link.
10702 PATH is a symbol name, as a string."
10703 (pcase (intern path)
10704 ((and (pred fboundp) variable) (describe-function variable))
10705 ((and (pred boundp) function) (describe-variable function))
10706 (name (user-error "Unknown function or variable: %s" name))))
10708 (defun org--open-shell-link (path)
10709 "Open a \"shell\" type link.
10710 PATH is the command to execute, as a string."
10711 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10713 (if (or (and (org-string-nw-p
10714 org-confirm-shell-link-not-regexp)
10716 org-confirm-shell-link-not-regexp cmd))
10717 (not org-confirm-shell-link-function)
10718 (funcall org-confirm-shell-link-function
10719 (format "Execute \"%s\" in shell? "
10720 (org-add-props cmd nil
10721 'face 'org-warning))))
10723 (message "Executing %s" cmd)
10724 (shell-command cmd buf)
10725 (when (featurep 'midnight)
10726 (setq clean-buffer-list-kill-buffer-names
10727 (cons (buffer-name buf)
10728 clean-buffer-list-kill-buffer-names))))
10729 (user-error "Abort"))))
10731 (defun org-open-at-point (&optional arg reference-buffer)
10732 "Open link, timestamp, footnote or tags at point.
10734 When point is on a link, follow it. Normally, files will be
10735 opened by an appropriate application. If the optional prefix
10736 argument ARG is non-nil, Emacs will visit the file. With
10737 a double prefix argument, try to open outside of Emacs, in the
10738 application the system uses for this file type.
10740 When point is on a timestamp, open the agenda at the day
10743 When point is a footnote definition, move to the first reference
10744 found. If it is on a reference, move to the associated
10747 When point is on a headline, display a list of every link in the
10748 entry, so it is possible to pick one, or all, of them. If point
10749 is on a tag, call `org-tags-view' instead.
10751 When optional argument REFERENCE-BUFFER is non-nil, it should
10752 specify a buffer from where the link search should happen. This
10753 is used internally by `org-open-link-from-string'.
10755 On top of syntactically correct links, this function will open
10756 the link at point in comments or comment blocks and the first
10757 link in a property drawer line."
10759 ;; On a code block, open block's results.
10760 (unless (call-interactively 'org-babel-open-src-block-result)
10761 (org-load-modules-maybe)
10762 (setq org-window-config-before-follow-link (current-window-configuration))
10763 (org-remove-occur-highlights nil nil t)
10764 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10766 ;; Only consider supported types, even if they are not
10767 ;; the closest one.
10768 (org-element-lineage
10769 (org-element-context)
10770 '(clock comment comment-block footnote-definition
10771 footnote-reference headline inlinetask keyword link
10772 node-property timestamp)
10774 (type (org-element-type context))
10775 (value (org-element-property :value context)))
10777 ((not context) (user-error "No link found"))
10778 ;; Exception: open timestamps and links in properties
10779 ;; drawers, keywords and comments.
10780 ((memq type '(comment comment-block keyword node-property))
10781 (call-interactively #'org-open-at-point-global))
10782 ;; On a headline or an inlinetask, but not on a timestamp,
10783 ;; a link, a footnote reference or on tags.
10784 ((and (memq type '(headline inlinetask))
10786 (let ((case-fold-search nil))
10788 (beginning-of-line)
10789 (looking-at org-complex-heading-regexp))
10790 (or (not (match-beginning 5))
10791 (< (point) (match-beginning 5)))))
10792 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10794 (links-end (cdr data)))
10796 (dolist (link (if (stringp links) (list links) links))
10797 (search-forward link nil links-end)
10798 (goto-char (match-beginning 0))
10799 (org-open-at-point))
10800 (require 'org-attach)
10801 (org-attach-reveal 'if-exists))))
10802 ;; On a clock line, make sure point is on the timestamp
10803 ;; before opening it.
10804 ((and (eq type 'clock)
10806 (>= (point) (org-element-property :begin value))
10807 (<= (point) (org-element-property :end value)))
10808 (org-follow-timestamp-link))
10809 ;; Do nothing on white spaces after an object.
10812 (goto-char (org-element-property :end context))
10813 (skip-chars-backward " \t")
10815 (user-error "No link found"))
10816 ((eq type 'timestamp) (org-follow-timestamp-link))
10817 ;; On tags within a headline or an inlinetask.
10818 ((and (memq type '(headline inlinetask))
10819 (let ((case-fold-search nil))
10820 (save-excursion (beginning-of-line)
10821 (looking-at org-complex-heading-regexp))
10822 (and (match-beginning 5)
10823 (>= (point) (match-beginning 5)))))
10824 (org-tags-view arg (substring (match-string 5) 0 -1)))
10826 (let ((type (org-element-property :type context))
10827 (path (org-link-unescape (org-element-property :path context))))
10828 ;; Switch back to REFERENCE-BUFFER needed when called in
10829 ;; a temporary buffer through `org-open-link-from-string'.
10830 (with-current-buffer (or reference-buffer (current-buffer))
10832 ((equal type "file")
10833 (if (string-match "[*?{]" (file-name-nondirectory path))
10835 ;; Look into `org-link-parameters' in order to find
10836 ;; a DEDICATED-FUNCTION to open file. The function
10837 ;; will be applied on raw link instead of parsed
10838 ;; link due to the limitation in `org-add-link-type'
10839 ;; ("open" function called with a single argument).
10840 ;; If no such function is found, fallback to
10841 ;; `org-open-file'.
10842 (let* ((option (org-element-property :search-option context))
10843 (app (org-element-property :application context))
10844 (dedicated-function
10845 (org-link-get-parameter
10846 (if app (concat type "+" app) type)
10848 (if dedicated-function
10849 (funcall dedicated-function
10851 (and option (concat "::" option))))
10852 (apply #'org-open-file
10855 ((equal app "emacs") 'emacs)
10856 ((equal app "sys") 'system))
10857 (cond ((not option) nil)
10858 ((string-match-p "\\`[0-9]+\\'" option)
10859 (list (string-to-number option)))
10861 (org-link-unescape option)))))))))
10862 ((functionp (org-link-get-parameter type :follow))
10863 (funcall (org-link-get-parameter type :follow) path))
10864 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10865 (unless (run-hook-with-args-until-success
10866 'org-open-link-functions path)
10867 (if (not arg) (org-mark-ring-push)
10868 (switch-to-buffer-other-window
10869 (org-get-buffer-for-internal-link (current-buffer))))
10871 (org-with-wide-buffer
10872 (if (equal type "radio")
10873 (org-search-radio-target
10874 (org-element-property :path context))
10876 (if (member type '("custom-id" "coderef"))
10877 (org-element-property :raw-link context)
10879 ;; Prevent fuzzy links from matching
10881 (and (equal type "fuzzy")
10882 (+ 2 (org-element-property :begin context)))))
10884 (unless (and (<= (point-min) destination)
10885 (>= (point-max) destination))
10887 (goto-char destination))))
10888 (t (browse-url-at-point))))))
10889 ;; On a footnote reference or at a footnote definition's label.
10890 ((or (eq type 'footnote-reference)
10891 (and (eq type 'footnote-definition)
10893 ;; Do not validate action when point is on the
10894 ;; spaces right after the footnote label, in
10895 ;; order to be on par with behaviour on links.
10896 (skip-chars-forward " \t")
10898 (org-element-property :contents-begin context)))
10899 (if begin (< (point) begin)
10900 (= (org-element-property :post-affiliated context)
10901 (line-beginning-position)))))))
10902 (org-footnote-action))
10903 (t (user-error "No link found")))))
10904 (run-hook-with-args 'org-follow-link-hook)))
10906 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10907 "Offer links in the current entry and return the selected link.
10908 If there is only one link, return it.
10909 If NTH is an integer, return the NTH link found.
10910 If ZERO is a string, check also this string for a link, and if
10911 there is one, return it."
10912 (with-current-buffer buffer
10913 (org-with-wide-buffer
10916 have-zero end links link c)
10917 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10918 (push (match-string 0 zero) links)
10919 (setq cnt (1- cnt) have-zero t))
10921 (org-back-to-heading t)
10922 (setq end (save-excursion (outline-next-heading) (point)))
10923 (while (re-search-forward org-any-link-re end t)
10924 (push (match-string 0) links))
10925 (setq links (org-uniquify (reverse links))))
10928 (message "No links"))
10929 ((equal (length links) 1)
10930 (setq link (car links)))
10931 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10932 (setq link (nth (if have-zero nth (1- nth)) links)))
10933 (t ; we have to select a link
10935 (save-window-excursion
10936 (delete-other-windows)
10937 (with-output-to-temp-buffer "*Select Link*"
10940 ((not (string-match org-bracket-link-regexp l))
10941 (princ (format "[%c] %s\n" (cl-incf cnt)
10942 (org-unbracket-string "<" ">" l))))
10944 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10945 (match-string 3 l) (match-string 1 l))))
10946 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10947 (match-string 1 l)))))))
10948 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10949 (message "Select link to open, RET to open all:")
10950 (setq c (read-char-exclusive))
10951 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10952 (when (equal c ?q) (user-error "Abort"))
10953 (if (equal c ?\C-m)
10955 (setq nth (- c ?0))
10956 (when have-zero (setq nth (1+ nth)))
10957 (unless (and (integerp nth) (>= (length links) nth))
10958 (user-error "Invalid link selection"))
10959 (setq link (nth (1- nth) links)))))
10960 (cons link end)))))
10962 ;; TODO: These functions are deprecated since `org-open-at-point'
10963 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10964 (defun org-open-file-with-system (path)
10965 "Open file at PATH using the system way of opening it."
10966 (org-open-file path 'system))
10967 (defun org-open-file-with-emacs (path)
10968 "Open file at PATH in Emacs."
10969 (org-open-file path 'emacs))
10974 (defvar org-create-file-search-functions nil
10975 "List of functions to construct the right search string for a file link.
10976 These functions are called in turn with point at the location to
10977 which the link should point.
10979 A function in the hook should first test if it would like to
10980 handle this file type, for example by checking the `major-mode'
10981 or the file extension. If it decides not to handle this file, it
10982 should just return nil to give other functions a chance. If it
10983 does handle the file, it must return the search string to be used
10984 when following the link. The search string will be part of the
10985 file link, given after a double colon, and `org-open-at-point'
10986 will automatically search for it. If special measures must be
10987 taken to make the search successful, another function should be
10988 added to the companion hook `org-execute-file-search-functions',
10991 A function in this hook may also use `setq' to set the variable
10992 `description' to provide a suggestion for the descriptive text to
10993 be used for this link when it gets inserted into an Org buffer
10994 with \\[org-insert-link].")
10996 (defvar org-execute-file-search-functions nil
10997 "List of functions to execute a file search triggered by a link.
10999 Functions added to this hook must accept a single argument, the
11000 search string that was part of the file link, the part after the
11001 double colon. The function must first check if it would like to
11002 handle this search, for example by checking the `major-mode' or
11003 the file extension. If it decides not to handle this search, it
11004 should just return nil to give other functions a chance. If it
11005 does handle the search, it must return a non-nil value to keep
11006 other functions from trying.
11008 Each function can access the current prefix argument through the
11009 variable `current-prefix-arg'. Note that a single prefix is used
11010 to force opening a link in Emacs, so it may be good to only use a
11011 numeric or double prefix to guide the search function.
11013 In case this is needed, a function in this hook can also restore
11014 the window configuration before `org-open-at-point' was called using:
11016 (set-window-configuration org-window-config-before-follow-link)")
11018 (defun org-search-radio-target (target)
11019 "Search a radio target matching TARGET in current buffer.
11020 White spaces are not significant."
11021 (let ((re (format "<<<%s>>>"
11022 (mapconcat #'regexp-quote
11023 (org-split-string target "[ \t\n]+")
11024 "[ \t]+\\(?:\n[ \t]*\\)?")))
11026 (goto-char (point-min))
11027 (catch :radio-match
11028 (while (re-search-forward re nil t)
11030 (let ((object (org-element-context)))
11031 (when (eq (org-element-type object) 'radio-target)
11032 (goto-char (org-element-property :begin object))
11033 (org-show-context 'link-search)
11034 (throw :radio-match nil))))
11036 (user-error "No match for radio target: %s" target))))
11038 (defun org-link-search (s &optional avoid-pos stealth)
11039 "Search for a search string S.
11041 If S starts with \"#\", it triggers a custom ID search.
11043 If S is enclosed within parenthesis, it initiates a coderef
11046 If S is surrounded by forward slashes, it is interpreted as
11047 a regular expression. In Org mode files, this will create an
11048 `org-occur' sparse tree. In ordinary files, `occur' will be used
11049 to list matches. If the current buffer is in `dired-mode', grep
11050 will be used to search in all files.
11052 When AVOID-POS is given, ignore matches near that position.
11054 When optional argument STEALTH is non-nil, do not modify
11055 visibility around point, thus ignoring `org-show-context-detail'
11058 Search is case-insensitive and ignores white spaces. Return type
11059 of matched result, which is either `dedicated' or `fuzzy'."
11060 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11061 (let* ((case-fold-search t)
11063 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11064 (starred (eq (string-to-char normalized) ?*))
11065 (words (split-string (if starred (substring s 1) s)))
11066 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11067 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11070 ;; Check if there are any special search functions.
11071 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11072 ((eq (string-to-char s) ?#)
11073 ;; Look for a custom ID S if S starts with "#".
11074 (let* ((id (substring normalized 1))
11075 (match (org-find-property "CUSTOM_ID" id)))
11076 (if match (progn (goto-char match) (setf type 'dedicated))
11077 (error "No match for custom ID: %s" id))))
11078 ((string-match "\\`(\\(.*\\))\\'" normalized)
11079 ;; Look for coderef targets if S is enclosed within parenthesis.
11080 (let ((coderef (match-string-no-properties 1 normalized))
11081 (re (substring s-single-re 1 -1)))
11082 (goto-char (point-min))
11083 (catch :coderef-match
11084 (while (re-search-forward re nil t)
11085 (let ((element (org-element-at-point)))
11086 (when (and (memq (org-element-type element)
11087 '(example-block src-block))
11088 ;; Build proper regexp according to current
11089 ;; block's label format.
11092 (or (org-element-property :label-fmt element)
11093 org-coderef-label-format))))
11095 (beginning-of-line)
11096 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11097 (format label-fmt coderef))))))
11098 (setq type 'dedicated)
11099 (goto-char (match-beginning 1))
11100 (throw :coderef-match nil))))
11102 (error "No match for coderef: %s" coderef))))
11103 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11104 ;; Look for a regular expression.
11105 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11106 (match-string 1 s)))
11107 ;; From here, we handle fuzzy links.
11109 ;; Look for targets, only if not in a headline search.
11110 ((and (not starred)
11111 (let ((target (format "<<%s>>" s-multi-re)))
11112 (catch :target-match
11113 (goto-char (point-min))
11114 (while (re-search-forward target nil t)
11116 (let ((context (org-element-context)))
11117 (when (eq (org-element-type context) 'target)
11118 (setq type 'dedicated)
11119 (goto-char (org-element-property :begin context))
11120 (throw :target-match t))))
11122 ;; Look for elements named after S, only if not in a headline
11124 ((and (not starred)
11125 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11127 (goto-char (point-min))
11128 (while (re-search-forward name nil t)
11129 (let ((element (org-element-at-point)))
11132 (org-element-property :name element)))
11133 (setq type 'dedicated)
11134 (beginning-of-line)
11135 (throw :name-match t))))
11137 ;; Regular text search. Prefer headlines in Org mode buffers.
11138 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11139 ;; statistics cookies and tags.
11140 ((and (derived-mode-p 'org-mode)
11142 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11143 org-outline-regexp-bol
11145 (mapconcat #'regexp-quote words ".+")))
11146 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11147 (comment-re (format "\\`%s[ \t]+" org-comment-string)))
11148 (goto-char (point-min))
11150 (while (re-search-forward title-re nil t)
11153 (replace-regexp-in-string
11155 (replace-regexp-in-string
11156 comment-re "" (org-get-heading t t)))))
11159 (beginning-of-line)
11160 (setq type 'dedicated))
11161 ;; Offer to create non-existent headline depending on
11162 ;; `org-link-search-must-match-exact-headline'.
11163 ((and (derived-mode-p 'org-mode)
11164 (not org-link-search-inhibit-query)
11165 (eq org-link-search-must-match-exact-headline 'query-to-create)
11166 (yes-or-no-p "No match - create this as a new heading? "))
11167 (goto-char (point-max))
11168 (unless (bolp) (newline))
11169 (org-insert-heading nil t t)
11171 (beginning-of-line 0))
11172 ;; Only headlines are looked after. No need to process
11173 ;; further: throw an error.
11174 ((and (derived-mode-p 'org-mode)
11175 (or starred org-link-search-must-match-exact-headline))
11177 (error "No match for fuzzy expression: %s" normalized))
11178 ;; Regular text search.
11179 ((catch :fuzzy-match
11180 (goto-char (point-min))
11181 (while (re-search-forward s-multi-re nil t)
11182 ;; Skip match if it contains AVOID-POS or it is included in
11183 ;; a link with a description but outside the description.
11184 (unless (or (and avoid-pos
11185 (<= (match-beginning 0) avoid-pos)
11186 (> (match-end 0) avoid-pos))
11187 (and (save-match-data
11188 (org-in-regexp org-bracket-link-regexp))
11189 (match-beginning 3)
11190 (or (> (match-beginning 3) (point))
11191 (<= (match-end 3) (point)))
11192 (org-element-lineage
11193 (save-match-data (org-element-context))
11195 (goto-char (match-beginning 0))
11197 (throw :fuzzy-match t)))
11199 ;; All failed. Throw an error.
11200 (t (goto-char origin)
11201 (error "No match for fuzzy expression: %s" normalized)))
11202 ;; Disclose surroundings of match, if appropriate.
11203 (when (and (derived-mode-p 'org-mode) (not stealth))
11204 (org-show-context 'link-search))
11207 (defun org-get-buffer-for-internal-link (buffer)
11208 "Return a buffer to be used for displaying the link target of internal links."
11210 ((not org-display-internal-link-with-indirect-buffer)
11212 ((string-suffix-p "(Clone)" (buffer-name buffer))
11213 (message "Buffer is already a clone, not making another one")
11214 ;; we also do not modify visibility in this case
11216 (t ; make a new indirect buffer for displaying the link
11217 (let* ((bn (buffer-name buffer))
11218 (ibn (concat bn "(Clone)"))
11219 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11220 (with-current-buffer ib (org-overview))
11223 (defun org-do-occur (regexp &optional cleanup)
11224 "Call the Emacs command `occur'.
11225 If CLEANUP is non-nil, remove the printout of the regular expression
11226 in the *Occur* buffer. This is useful if the regex is long and not useful
11230 (let ((cwin (selected-window)) win beg end)
11231 (when (setq win (get-buffer-window "*Occur*"))
11232 (select-window win))
11233 (goto-char (point-min))
11234 (when (re-search-forward "match[a-z]+" nil t)
11235 (setq beg (match-end 0))
11236 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11237 (setq end (1- (match-beginning 0)))))
11238 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11239 (goto-char (point-min))
11240 (select-window cwin))))
11242 ;;; The mark ring for links jumps
11244 (defvar org-mark-ring nil
11245 "Mark ring for positions before jumps in Org mode.")
11246 (defvar org-mark-ring-last-goto nil
11247 "Last position in the mark ring used to go back.")
11248 ;; Fill and close the ring
11249 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11250 (dotimes (_ org-mark-ring-length)
11251 (push (make-marker) org-mark-ring))
11252 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11255 (defun org-mark-ring-push (&optional pos buffer)
11256 "Put the current position or POS into the mark ring and rotate it."
11258 (setq pos (or pos (point)))
11259 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11260 (move-marker (car org-mark-ring)
11262 (or buffer (current-buffer)))
11264 (substitute-command-keys
11265 "Position saved to mark ring, go back with \
11266 `\\[org-mark-ring-goto]'.")))
11268 (defun org-mark-ring-goto (&optional n)
11269 "Jump to the previous position in the mark ring.
11270 With prefix arg N, jump back that many stored positions. When
11271 called several times in succession, walk through the entire ring.
11272 Org mode commands jumping to a different position in the current file,
11273 or to another Org file, automatically push the old position onto the ring."
11276 (if (eq last-command this-command)
11277 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11278 (setq p org-mark-ring))
11279 (setq org-mark-ring-last-goto p)
11281 (pop-to-buffer-same-window (marker-buffer m))
11283 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11285 (defun org-add-angle-brackets (s)
11286 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11287 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11290 ;;; Following specific links
11292 (defvar org-agenda-buffer-tmp-name)
11293 (defvar org-agenda-start-on-weekday)
11294 (defun org-follow-timestamp-link ()
11295 "Open an agenda view for the time-stamp date/range at point."
11297 ((org-at-date-range-p t)
11298 (let ((org-agenda-start-on-weekday)
11299 (t1 (match-string 1))
11300 (t2 (match-string 2)) tt1 tt2)
11301 (setq tt1 (time-to-days (org-time-string-to-time t1))
11302 tt2 (time-to-days (org-time-string-to-time t2)))
11303 (let ((org-agenda-buffer-tmp-name
11304 (format "*Org Agenda(a:%s)"
11305 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11306 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11307 ((org-at-timestamp-p t)
11308 (let ((org-agenda-buffer-tmp-name
11309 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11310 (org-agenda-list nil (time-to-days (org-time-string-to-time
11311 (substring (match-string 1) 0 10)))
11313 (t (error "This should not happen"))))
11316 ;;; Following file links
11317 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11318 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11319 (declare-function mailcap-mime-info
11320 "mailcap" (string &optional request no-decode))
11321 (defvar org-wait nil)
11322 (defun org-open-file (path &optional in-emacs line search)
11323 "Open the file at PATH.
11324 First, this expands any special file name abbreviations. Then the
11325 configuration variable `org-file-apps' is checked if it contains an
11326 entry for this file type, and if yes, the corresponding command is launched.
11328 If no application is found, Emacs simply visits the file.
11330 With optional prefix argument IN-EMACS, Emacs will visit the file.
11331 With a double \\[universal-argument] \\[universal-argument] \
11332 prefix arg, Org tries to avoid opening in Emacs
11333 and to use an external application to visit the file.
11335 Optional LINE specifies a line to go to, optional SEARCH a string
11336 to search for. If LINE or SEARCH is given, the file will be
11337 opened in Emacs, unless an entry from org-file-apps that makes
11338 use of groups in a regexp matches.
11340 If you want to change the way frames are used when following a
11341 link, please customize `org-link-frame-setup'.
11343 If the file does not exist, an error is thrown."
11344 (let* ((file (if (equal path "")
11346 (substitute-in-file-name (expand-file-name path))))
11347 (file-apps (append org-file-apps (org-default-apps)))
11348 (apps (cl-remove-if
11349 'org-file-apps-entry-match-against-dlink-p file-apps))
11350 (apps-dlink (cl-remove-if-not
11351 'org-file-apps-entry-match-against-dlink-p file-apps))
11352 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11353 (dirp (unless remp (file-directory-p file)))
11354 (file (if (and dirp org-open-directory-means-index-dot-org)
11355 (concat (file-name-as-directory file) "index.org")
11357 (a-m-a-p (assq 'auto-mode apps))
11358 (dfile (downcase file))
11359 ;; Reconstruct the original link from the PATH, LINE and
11361 (link (cond (line (concat file "::" (number-to-string line)))
11362 (search (concat file "::" search))
11364 (dlink (downcase link))
11366 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11367 (match-string 1 dfile)))
11368 (save-position-maybe
11369 (let ((old-buffer (current-buffer))
11371 (old-mode major-mode))
11373 (and (derived-mode-p 'org-mode)
11374 (eq old-mode 'org-mode)
11375 (or (not (eq old-buffer (current-buffer)))
11376 (not (eq old-pos (point))))
11377 (org-mark-ring-push old-pos old-buffer)))))
11378 cmd link-match-data)
11380 ((member in-emacs '((16) system))
11381 (setq cmd (cdr (assq 'system apps))))
11382 (in-emacs (setq cmd 'emacs))
11384 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11385 (and dirp (cdr (assq 'directory apps)))
11386 ;; First, try matching against apps-dlink if we
11387 ;; get a match here, store the match data for
11389 (let ((match (assoc-default dlink apps-dlink
11392 (progn (setq link-match-data (match-data))
11394 (progn (setq in-emacs (or in-emacs line search))
11395 nil))) ; if we have no match in apps-dlink,
11396 ; always open the file in emacs if line or search
11397 ; is given (for backwards compatibility)
11398 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11400 (cdr (assoc ext apps))
11401 (cdr (assq t apps))))))
11402 (when (eq cmd 'system)
11403 (setq cmd (cdr (assq 'system apps))))
11404 (when (eq cmd 'default)
11405 (setq cmd (cdr (assoc t apps))))
11406 (when (eq cmd 'mailcap)
11408 (mailcap-parse-mailcaps)
11409 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11410 (command (mailcap-mime-info mime-type)))
11411 (if (stringp command)
11413 (setq cmd 'emacs))))
11414 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11415 (not (file-exists-p file))
11416 (not org-open-non-existing-files))
11417 (user-error "No such file: %s" file))
11419 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11420 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11421 (while (string-match "['\"]%s['\"]" cmd)
11422 (setq cmd (replace-match "%s" t t cmd)))
11423 (setq cmd (replace-regexp-in-string
11425 (shell-quote-argument (convert-standard-filename file))
11429 ;; Replace "%1", "%2" etc. in command with group matches from regex
11431 (let ((match-index 1)
11432 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11433 (set-match-data link-match-data)
11434 (while (<= match-index number-of-groups)
11435 (let ((regex (concat "%" (number-to-string match-index)))
11436 (replace-with (match-string match-index dlink)))
11437 (while (string-match regex cmd)
11438 (setq cmd (replace-match replace-with t t cmd))))
11439 (setq match-index (+ match-index 1)))))
11441 (save-window-excursion
11442 (message "Running %s...done" cmd)
11443 (start-process-shell-command cmd nil cmd)
11444 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11447 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11449 (cond (line (org-goto-line line)
11450 (when (derived-mode-p 'org-mode) (org-reveal)))
11451 (search (condition-case err
11452 (org-link-search search)
11453 ;; Save position before error-ing out so user
11454 ;; can easily move back to the original buffer.
11455 (error (funcall save-position-maybe)
11456 (error (nth 1 err)))))))
11459 (set-match-data link-match-data)
11460 (condition-case nil
11461 (funcall cmd file link)
11462 ;; FIXME: Remove this check when most default installations
11463 ;; of Emacs have at least Org 9.0.
11464 ((debug wrong-number-of-arguments wrong-type-argument
11466 (user-error "Please see Org News for version 9.0 about \
11467 `org-file-apps'--Lisp error: %S" cmd)))))
11469 ;; FIXME: Remove this check when most default installations of
11470 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11471 ;; fall back to `org-link-frame-setup' for an old usage of
11472 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11473 (user-error "Please see Org News for version 9.0 about \
11474 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11475 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11476 (funcall save-position-maybe)))
11478 (defun org-file-apps-entry-match-against-dlink-p (entry)
11479 "This function returns non-nil if `entry' uses a regular
11480 expression which should be matched against the whole link by
11483 It assumes that is the case when the entry uses a regular
11484 expression which has at least one grouping construct and the
11485 action is either a lisp form or a command string containing
11486 `%1', i.e. using at least one subexpression match as a
11488 (let ((selector (car entry))
11489 (action (cdr entry)))
11490 (if (stringp selector)
11491 (and (> (regexp-opt-depth selector) 0)
11492 (or (and (stringp action)
11493 (string-match "%[0-9]" action))
11497 (defun org-default-apps ()
11498 "Return the default applications for this operating system."
11500 ((eq system-type 'darwin)
11501 org-file-apps-defaults-macosx)
11502 ((eq system-type 'windows-nt)
11503 org-file-apps-defaults-windowsnt)
11504 (t org-file-apps-defaults-gnu)))
11506 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11507 "Convert extensions to regular expressions in the cars of LIST.
11508 Also, weed out any non-string entries, because the return value is used
11509 only for regexp matching.
11510 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11511 point to the symbol `emacs', indicating that the file should
11512 be opened in Emacs."
11515 (mapcar (lambda (x)
11516 (unless (not (stringp (car x)))
11517 (if (string-match "\\W" (car x))
11519 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11521 (when add-auto-mode
11522 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11524 (defvar ange-ftp-name-format)
11525 (defun org-file-remote-p (file)
11526 "Test whether FILE specifies a location on a remote system.
11527 Return non-nil if the location is indeed remote.
11529 For example, the filename \"/user@host:/foo\" specifies a location
11530 on the system \"/user@host:\"."
11531 (cond ((fboundp 'file-remote-p)
11532 (file-remote-p file))
11533 ((fboundp 'tramp-handle-file-remote-p)
11534 (tramp-handle-file-remote-p file))
11535 ((and (boundp 'ange-ftp-name-format)
11536 (string-match (car ange-ftp-name-format) file))
11542 (defun org-get-org-file ()
11543 "Read a filename, with default directory `org-directory'."
11544 (let ((default (or org-default-notes-file remember-data-file)))
11545 (read-file-name (format "File name [%s]: " default)
11546 (file-name-as-directory org-directory)
11549 (defun org-notes-order-reversed-p ()
11550 "Check if the current file should receive notes in reversed order."
11552 ((not org-reverse-note-order) nil)
11553 ((eq t org-reverse-note-order) t)
11554 ((not (listp org-reverse-note-order)) nil)
11556 (dolist (entry org-reverse-note-order)
11557 (when (string-match (car entry) buffer-file-name)
11558 (throw 'exit (cdr entry))))))))
11560 (defvar org-refile-target-table nil
11561 "The list of refile targets, created by `org-refile'.")
11563 (defvar org-agenda-new-buffers nil
11564 "Buffers created to visit agenda files.")
11566 (defvar org-refile-cache nil
11567 "Cache for refile targets.")
11569 (defvar org-refile-markers nil
11570 "All the markers used for caching refile locations.")
11572 (defun org-refile-marker (pos)
11573 "Get a new refile marker, but only if caching is in use."
11574 (if (not org-refile-use-cache)
11576 (let ((m (make-marker)))
11577 (move-marker m pos)
11578 (push m org-refile-markers)
11581 (defun org-refile-cache-clear ()
11582 "Clear the refile cache and disable all the markers."
11583 (dolist (m org-refile-markers) (move-marker m nil))
11584 (setq org-refile-markers nil)
11585 (setq org-refile-cache nil)
11586 (message "Refile cache has been cleared"))
11588 (defun org-refile-cache-check-set (set)
11589 "Check if all the markers in the cache still have live buffers."
11592 (while (and set (setq marker (nth 3 (pop set))))
11593 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11594 (when (and marker (null (marker-buffer marker)))
11595 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11597 (throw 'exit nil)))
11600 (defun org-refile-cache-put (set &rest identifiers)
11601 "Push the refile targets SET into the cache, under IDENTIFIERS."
11602 (let* ((key (sha1 (prin1-to-string identifiers)))
11603 (entry (assoc key org-refile-cache)))
11606 (push (cons key set) org-refile-cache))))
11608 (defun org-refile-cache-get (&rest identifiers)
11609 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11611 ((not org-refile-cache) nil)
11612 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11614 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11615 org-refile-cache))))
11616 (and set (org-refile-cache-check-set set) set)))))
11618 (defvar org-outline-path-cache nil
11619 "Alist between buffer positions and outline paths.
11620 It value is an alist (POSITION . PATH) where POSITION is the
11621 buffer position at the beginning of an entry and PATH is a list
11622 of strings describing the outline path for that entry, in reverse
11625 (defun org-refile-get-targets (&optional default-buffer)
11626 "Produce a table with refile targets."
11627 (let ((case-fold-search nil)
11628 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11629 (entries (or org-refile-targets '((nil . (:level . 1)))))
11630 targets tgs files desc descre)
11631 (message "Getting targets...")
11632 (with-current-buffer (or default-buffer (current-buffer))
11633 (dolist (entry entries)
11634 (setq files (car entry) desc (cdr entry))
11636 ((null files) (setq files (list (current-buffer))))
11637 ((eq files 'org-agenda-files)
11638 (setq files (org-agenda-files 'unrestricted)))
11639 ((and (symbolp files) (fboundp files))
11640 (setq files (funcall files)))
11641 ((and (symbolp files) (boundp files))
11642 (setq files (symbol-value files))))
11643 (when (stringp files) (setq files (list files)))
11645 ((eq (car desc) :tag)
11646 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11647 ((eq (car desc) :todo)
11648 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11649 ((eq (car desc) :regexp)
11650 (setq descre (cdr desc)))
11651 ((eq (car desc) :level)
11652 (setq descre (concat "^\\*\\{" (number-to-string
11653 (if org-odd-levels-only
11654 (1- (* 2 (cdr desc)))
11657 ((eq (car desc) :maxlevel)
11658 (setq descre (concat "^\\*\\{1," (number-to-string
11659 (if org-odd-levels-only
11660 (1- (* 2 (cdr desc)))
11663 (t (error "Bad refiling target description %s" desc)))
11665 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11667 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11670 (setq f (buffer-file-name (buffer-base-buffer f))))
11671 (setq f (and f (expand-file-name f)))
11672 (when (eq org-refile-use-outline-path 'file)
11673 (push (list (file-name-nondirectory f) f nil nil) tgs))
11674 (org-with-wide-buffer
11675 (goto-char (point-min))
11676 (setq org-outline-path-cache nil)
11677 (while (re-search-forward descre nil t)
11678 (beginning-of-line)
11679 (let ((case-fold-search nil))
11680 (looking-at org-complex-heading-regexp))
11681 (let ((begin (point))
11682 (heading (match-string-no-properties 4)))
11684 org-refile-target-verify-function
11686 (funcall org-refile-target-verify-function)))
11688 (let ((re (format org-complex-heading-regexp-format
11689 (regexp-quote heading)))
11691 (if (not org-refile-use-outline-path) heading
11693 #'org-protect-slash
11695 (pcase org-refile-use-outline-path
11696 (`file (list (file-name-nondirectory
11698 (buffer-base-buffer)))))
11700 (list (buffer-file-name
11701 (buffer-base-buffer))))
11703 (org-get-outline-path t t))
11705 (push (list target f re (org-refile-marker (point)))
11707 (when (= (point) begin)
11708 ;; Verification function has not moved point.
11709 (end-of-line)))))))
11710 (when org-refile-use-cache
11711 (org-refile-cache-put tgs (buffer-file-name) descre))
11712 (setq targets (append tgs targets))))))
11713 (message "Getting targets...done")
11714 (nreverse targets)))
11716 (defun org-protect-slash (s)
11717 (replace-regexp-in-string "/" "\\/" s nil t))
11719 (defun org--get-outline-path-1 (&optional use-cache)
11720 "Return outline path to current headline.
11722 Outline path is a list of strings, in reverse order. When
11723 optional argument USE-CACHE is non-nil, make use of a cache. See
11724 `org-get-outline-path' for details.
11726 Assume buffer is widened and point is on a headline."
11727 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11729 (heading (let ((case-fold-search nil))
11730 (looking-at org-complex-heading-regexp)
11731 (if (not (match-end 4)) ""
11732 ;; Remove statistics cookies.
11734 (org-link-display-format
11735 (replace-regexp-in-string
11736 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11737 (match-string-no-properties 4))))))))
11738 (if (org-up-heading-safe)
11739 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11741 (push (cons p path) org-outline-path-cache))
11743 ;; This is a new root node. Since we assume we are moving
11744 ;; forward, we can drop previous cache so as to limit number
11745 ;; of associations there.
11746 (let ((path (list heading)))
11747 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11750 (defun org-get-outline-path (&optional with-self use-cache)
11751 "Return the outline path to the current entry.
11753 An outline path is a list of ancestors for current headline, as
11754 a list of strings. Statistics cookies are removed and links are
11755 replaced with their description, if any, or their path otherwise.
11757 When optional argument WITH-SELF is non-nil, the path also
11758 includes the current headline.
11760 When optional argument USE-CACHE is non-nil, cache outline paths
11761 between calls to this function so as to avoid backtracking. This
11762 argument is useful when planning to find more than one outline
11763 path in the same document. In that case, there are two
11764 conditions to satisfy:
11765 - `org-outline-path-cache' is set to nil before starting the
11767 - outline paths are computed by increasing buffer positions."
11768 (org-with-wide-buffer
11769 (and (or (and with-self (org-back-to-heading t))
11770 (org-up-heading-safe))
11771 (reverse (org--get-outline-path-1 use-cache)))))
11773 (defun org-format-outline-path (path &optional width prefix separator)
11774 "Format the outline path PATH for display.
11775 WIDTH is the maximum number of characters that is available.
11776 PREFIX is a prefix to be included in the returned string,
11777 such as the file name.
11778 SEPARATOR is inserted between the different parts of the path,
11779 the default is \"/\"."
11780 (setq width (or width 79))
11781 (setq path (delq nil path))
11782 (unless (> width 0)
11783 (user-error "Argument `width' must be positive"))
11784 (setq separator (or separator "/"))
11785 (let* ((org-odd-levels-only nil)
11787 prefix (and prefix path separator)
11789 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11790 (cl-loop for head in path
11792 collect (org-add-props
11794 (nth (% n org-n-level-faces) org-level-faces)))
11796 (when (> (length fpath) width)
11798 ;; It's unlikely that `width' will be this small, but don't
11799 ;; waste characters by adding ".." if it is.
11800 (setq fpath (substring fpath 0 width))
11801 (setf (substring fpath (- width 2)) "..")))
11804 (defun org-display-outline-path (&optional file current separator just-return-string)
11805 "Display the current outline path in the echo area.
11807 If FILE is non-nil, prepend the output with the file name.
11808 If CURRENT is non-nil, append the current heading to the output.
11809 SEPARATOR is passed through to `org-format-outline-path'. It separates
11810 the different parts of the path and defaults to \"/\".
11811 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11813 (let* (case-fold-search
11814 (bfn (buffer-file-name (buffer-base-buffer)))
11815 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11817 (when current (setq path (append path
11819 (org-back-to-heading t)
11820 (when (looking-at org-complex-heading-regexp)
11821 (list (match-string 4)))))))
11823 (org-format-outline-path
11826 (and file bfn (concat (file-name-nondirectory bfn) separator))
11828 (if just-return-string
11829 (org-no-properties res)
11830 (org-unlogged-message "%s" res))))
11832 (defvar org-refile-history nil
11833 "History for refiling operations.")
11835 (defvar org-after-refile-insert-hook nil
11836 "Hook run after `org-refile' has inserted its stuff at the new location.
11837 Note that this is still *before* the stuff will be removed from
11838 the *old* location.")
11840 (defvar org-capture-last-stored-marker)
11841 (defvar org-refile-keep nil
11842 "Non-nil means `org-refile' will copy instead of refile.")
11845 "Like `org-refile', but copy."
11847 (let ((org-refile-keep t))
11848 (funcall 'org-refile nil nil nil "Copy")))
11850 (defun org-refile (&optional arg default-buffer rfloc msg)
11851 "Move the entry or entries at point to another heading.
11853 The list of target headings is compiled using the information in
11854 `org-refile-targets', which see.
11856 At the target location, the entry is filed as a subitem of the
11857 target heading. Depending on `org-reverse-note-order', the new
11858 subitem will either be the first or the last subitem.
11860 If there is an active region, all entries in that region will be
11861 refiled. However, the region must fulfill the requirement that
11862 the first heading sets the top-level of the moved text.
11864 With a `\\[universal-argument]' ARG, the command will only visit the target \
11866 and not actually move anything.
11868 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11869 location where the last
11870 refiling operation has put the subtree.
11872 With a numeric prefix argument of `2', refile to the running clock.
11874 With a numeric prefix argument of `3', emulate `org-refile-keep'
11875 being set to t and copy to the target location, don't move it.
11876 Beware that keeping refiled entries may result in duplicated ID
11879 RFLOC can be a refile location obtained in a different way.
11881 MSG is a string to replace \"Refile\" in the default prompt with
11882 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11884 See also `org-refile-use-outline-path'.
11886 If you are using target caching (see `org-refile-use-cache'), you
11887 have to clear the target cache in order to find new targets.
11888 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11889 prefix argument (`C-u C-u C-u C-c C-w')."
11891 (if (member arg '(0 (64)))
11892 (org-refile-cache-clear)
11893 (let* ((actionmsg (cond (msg msg)
11894 ((equal arg 3) "Refile (and keep)")
11896 (regionp (org-region-active-p))
11897 (region-start (and regionp (region-beginning)))
11898 (region-end (and regionp (region-end)))
11899 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11900 pos it nbuf file level reversed)
11901 (setq last-command nil)
11903 (goto-char region-start)
11904 (or (bolp) (goto-char (point-at-bol)))
11905 (setq region-start (point))
11906 (unless (or (org-kill-is-subtree-p
11907 (buffer-substring region-start region-end))
11908 (prog1 org-refile-active-region-within-subtree
11909 (let ((s (point-at-eol)))
11910 (org-toggle-heading)
11911 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11912 (user-error "The region is not a (sequence of) subtree(s)")))
11913 (if (equal arg '(16))
11914 (org-refile-goto-last-stored)
11917 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11919 (setq it (list (or org-clock-heading "running clock")
11921 (marker-buffer org-clock-hd-marker))
11923 (marker-position org-clock-hd-marker)))
11927 (let (heading-text)
11929 (unless (and arg (listp arg))
11930 (org-back-to-heading t)
11932 (replace-regexp-in-string
11933 org-bracket-link-regexp
11935 (or (nth 4 (org-heading-components))
11937 (org-refile-get-location
11938 (cond ((and arg (listp arg)) "Goto")
11939 (regionp (concat actionmsg " region to"))
11940 (t (concat actionmsg " subtree \""
11941 heading-text "\" to")))
11943 (and (not (equal '(4) arg))
11944 org-refile-allow-creating-parent-nodes)))))))
11945 (setq file (nth 1 it)
11947 (when (and (not arg)
11949 (equal (buffer-file-name) file)
11951 (and (>= pos region-start)
11952 (<= pos region-end))
11953 (and (>= pos (point))
11954 (< pos (save-excursion
11955 (org-end-of-subtree t t))))))
11956 (error "Cannot refile to position inside the tree or region"))
11957 (setq nbuf (or (find-buffer-visiting file)
11958 (find-file-noselect file)))
11959 (if (and arg (not (equal arg 3)))
11961 (pop-to-buffer-same-window nbuf)
11963 (org-show-context 'org-goto))
11966 (org-kill-new (buffer-substring region-start region-end))
11967 (org-save-markers-in-region region-start region-end))
11968 (org-copy-subtree 1 nil t))
11969 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11970 (find-file-noselect file)))
11971 (setq reversed (org-notes-order-reversed-p))
11972 (org-with-wide-buffer
11976 (looking-at org-outline-regexp)
11977 (setq level (org-get-valid-level (funcall outline-level) 1))
11980 (or (outline-next-heading) (point-max))
11981 (or (save-excursion (org-get-next-sibling))
11982 (org-end-of-subtree t t)
11986 (goto-char (point-max))
11987 (goto-char (point-min))
11988 (or (outline-next-heading) (goto-char (point-max)))))
11989 (unless (bolp) (newline))
11990 (org-paste-subtree level nil nil t)
11991 (when org-log-refile
11992 (org-add-log-setup 'refile nil nil org-log-refile)
11993 (unless (eq org-log-refile 'note)
11994 (save-excursion (org-add-log-note))))
11995 (and org-auto-align-tags
11996 (let ((org-loop-over-headlines-in-active-region nil))
11997 (org-set-tags nil t)))
11998 (let ((bookmark-name (plist-get org-bookmark-names-plist
12000 (when bookmark-name
12001 (with-demoted-errors
12002 (bookmark-set bookmark-name))))
12003 ;; If we are refiling for capture, make sure that the
12004 ;; last-capture pointers point here
12005 (when (bound-and-true-p org-capture-is-refiling)
12006 (let ((bookmark-name (plist-get org-bookmark-names-plist
12007 :last-capture-marker)))
12008 (when bookmark-name
12009 (with-demoted-errors
12010 (bookmark-set bookmark-name))))
12011 (move-marker org-capture-last-stored-marker (point)))
12012 (when (fboundp 'deactivate-mark) (deactivate-mark))
12013 (run-hooks 'org-after-refile-insert-hook)))
12014 (unless org-refile-keep
12016 (delete-region (point) (+ (point) (- region-end region-start)))
12018 (and (org-back-to-heading t) (point))
12019 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12020 (when (featurep 'org-inlinetask)
12021 (org-inlinetask-remove-END-maybe))
12022 (setq org-markers-to-move nil)
12023 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12025 (defun org-refile-goto-last-stored ()
12026 "Go to the location where the last refile was stored."
12028 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12029 (message "This is the location of the last refile"))
12031 (defun org-refile--get-location (refloc tbl)
12032 "When user refile to REFLOC, find the associated target in TBL.
12033 Also check `org-refile-target-table'."
12037 (lambda (r) (or (assoc r tbl)
12038 (assoc r org-refile-target-table)))
12039 (list (replace-regexp-in-string "/$" "" refloc)
12040 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12042 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12043 "Prompt the user for a refile location, using PROMPT.
12044 PROMPT should not be suffixed with a colon and a space, because
12045 this function appends the default value from
12046 `org-refile-history' automatically, if that is not empty."
12047 (let ((org-refile-targets org-refile-targets)
12048 (org-refile-use-outline-path org-refile-use-outline-path))
12049 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12050 (unless org-refile-target-table
12051 (user-error "No refile targets"))
12052 (let* ((cbuf (current-buffer))
12053 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12054 (cfunc (if (and org-refile-use-outline-path
12055 org-outline-path-complete-in-steps)
12056 #'org-olpath-completing-read
12057 #'completing-read))
12058 (extra (if org-refile-use-outline-path "/" ""))
12059 (cbnex (concat (buffer-name) extra))
12060 (filename (and cfn (expand-file-name cfn)))
12063 (if (and (not (member org-refile-use-outline-path
12064 '(file full-file-path)))
12065 (not (equal filename (nth 1 x))))
12066 (cons (concat (car x) extra " ("
12067 (file-name-nondirectory (nth 1 x)) ")")
12069 (cons (concat (car x) extra) (cdr x))))
12070 org-refile-target-table))
12071 (completion-ignore-case t)
12073 (prompt (concat prompt
12074 (or (and (car org-refile-history)
12075 (concat " (default " (car org-refile-history) ")"))
12076 (and (assoc cbnex tbl) (setq cdef cbnex)
12077 (concat " (default " cbnex ")"))) ": "))
12078 pa answ parent-target child parent old-hist)
12079 (setq old-hist org-refile-history)
12080 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12081 nil 'org-refile-history (or cdef (car org-refile-history))))
12082 (if (setq pa (org-refile--get-location answ tbl))
12084 (org-refile-check-position pa)
12085 (when (or (not org-refile-history)
12086 (not (eq old-hist org-refile-history))
12087 (not (equal (car pa) (car org-refile-history))))
12088 (setq org-refile-history
12089 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12091 (cdr org-refile-history))))
12092 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12093 (pop org-refile-history)))
12095 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12097 (setq parent (match-string 1 answ)
12098 child (match-string 2 answ))
12099 (setq parent-target (org-refile--get-location parent tbl))
12100 (when (and parent-target
12101 (or (eq new-nodes t)
12102 (and (eq new-nodes 'confirm)
12103 (y-or-n-p (format "Create new node \"%s\"? "
12105 (org-refile-new-child parent-target child)))
12106 (user-error "Invalid target location")))))
12108 (declare-function org-string-nw-p "org-macs" (s))
12109 (defun org-refile-check-position (refile-pointer)
12110 "Check if the refile pointer matches the headline to which it points."
12111 (let* ((file (nth 1 refile-pointer))
12112 (re (nth 2 refile-pointer))
12113 (pos (nth 3 refile-pointer))
12115 (if (and (not (markerp pos)) (not file))
12116 (user-error "Please indicate a target file in the refile path")
12117 (when (org-string-nw-p re)
12118 (setq buffer (if (markerp pos)
12119 (marker-buffer pos)
12120 (or (find-buffer-visiting file)
12121 (find-file-noselect file))))
12122 (with-current-buffer buffer
12123 (org-with-wide-buffer
12125 (beginning-of-line 1)
12126 (unless (looking-at-p re)
12127 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12129 (defun org-refile-new-child (parent-target child)
12130 "Use refile target PARENT-TARGET to add new CHILD below it."
12131 (unless parent-target
12132 (error "Cannot find parent for new node"))
12133 (let ((file (nth 1 parent-target))
12134 (pos (nth 3 parent-target))
12136 (with-current-buffer (or (find-buffer-visiting file)
12137 (find-file-noselect file))
12138 (org-with-wide-buffer
12141 (goto-char (point-max))
12142 (unless (bolp) (newline)))
12143 (when (looking-at org-outline-regexp)
12144 (setq level (funcall outline-level))
12145 (org-end-of-subtree t t))
12146 (org-back-over-empty-lines)
12147 (insert "\n" (make-string
12148 (if pos (org-get-valid-level level 1) 1) ?*)
12150 (beginning-of-line 0)
12151 (list (concat (car parent-target) "/" child) file "" (point))))))
12153 (defun org-olpath-completing-read (prompt collection &rest args)
12154 "Read an outline path like a file name."
12155 (let ((thetable collection))
12156 (apply #'completing-read
12158 (lambda (string predicate &optional flag)
12160 ((eq flag nil) (try-completion string thetable))
12162 (let ((l (length string)))
12163 (mapcar (lambda (x)
12164 (let ((r (substring x l))
12165 (f (if (string-match " ([^)]*)$" x)
12168 (if (string-match "/" r)
12169 (concat string (substring r 0 (match-end 0)) f)
12171 (all-completions string thetable predicate))))
12173 ((eq flag 'lambda) (assoc string thetable))))
12176 ;;;; Dynamic blocks
12178 (defun org-find-dblock (name)
12179 "Find the first dynamic block with name NAME in the buffer.
12180 If not found, stay at current position and return nil."
12181 (let ((case-fold-search t) pos)
12183 (goto-char (point-min))
12184 (setq pos (and (re-search-forward
12185 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12186 (match-beginning 0))))
12187 (when pos (goto-char pos))
12190 (defun org-create-dblock (plist)
12191 "Create a dynamic block section, with parameters taken from PLIST.
12192 PLIST must contain a :name entry which is used as the name of the block."
12193 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12196 (let ((col (current-column))
12197 (name (plist-get plist :name)))
12198 (insert "#+BEGIN: " name)
12200 (if (eq (car plist) :name)
12201 (setq plist (cddr plist))
12202 (insert " " (prin1-to-string (pop plist)))))
12203 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12204 (beginning-of-line -2)))
12206 (defun org-prepare-dblock ()
12207 "Prepare dynamic block for refresh.
12208 This empties the block, puts the cursor at the insert position and returns
12209 the property list including an extra property :name with the block name."
12210 (unless (looking-at org-dblock-start-re)
12211 (user-error "Not at a dynamic block"))
12212 (let* ((begdel (1+ (match-end 0)))
12213 (name (org-no-properties (match-string 1)))
12214 (params (append (list :name name)
12215 (read (concat "(" (match-string 3) ")")))))
12217 (beginning-of-line 1)
12218 (skip-chars-forward " \t")
12219 (setq params (plist-put params :indentation-column (current-column))))
12220 (unless (re-search-forward org-dblock-end-re nil t)
12221 (error "Dynamic block not terminated"))
12224 (list :content (buffer-substring
12225 begdel (match-beginning 0)))))
12226 (delete-region begdel (match-beginning 0))
12231 (defun org-map-dblocks (&optional command)
12232 "Apply COMMAND to all dynamic blocks in the current buffer.
12233 If COMMAND is not given, use `org-update-dblock'."
12234 (let ((cmd (or command 'org-update-dblock)))
12236 (goto-char (point-min))
12237 (while (re-search-forward org-dblock-start-re nil t)
12238 (goto-char (match-beginning 0))
12240 (condition-case nil
12242 (error (message "Error during update of dynamic block"))))
12243 (unless (re-search-forward org-dblock-end-re nil t)
12244 (error "Dynamic block not terminated"))))))
12246 (defun org-dblock-update (&optional arg)
12247 "User command for updating dynamic blocks.
12248 Update the dynamic block at point. With prefix ARG, update all dynamic
12249 blocks in the buffer."
12252 (org-update-all-dblocks)
12253 (or (looking-at org-dblock-start-re)
12254 (org-beginning-of-dblock))
12255 (org-update-dblock)))
12257 (defun org-update-dblock ()
12258 "Update the dynamic block at point.
12259 This means to empty the block, parse for parameters and then call
12260 the correct writing function."
12263 (let* ((win (selected-window))
12265 (line (org-current-line))
12266 (params (org-prepare-dblock))
12267 (name (plist-get params :name))
12268 (indent (plist-get params :indentation-column))
12269 (cmd (intern (concat "org-dblock-write:" name))))
12270 (message "Updating dynamic block `%s' at line %d..." name line)
12271 (funcall cmd params)
12272 (message "Updating dynamic block `%s' at line %d...done" name line)
12274 (when (and indent (> indent 0))
12275 (setq indent (make-string indent ?\ ))
12277 (select-window win)
12278 (org-beginning-of-dblock)
12280 (while (not (looking-at org-dblock-end-re))
12282 (beginning-of-line 2))
12283 (when (looking-at org-dblock-end-re)
12284 (and (looking-at "[ \t]+")
12285 (replace-match ""))
12286 (insert indent)))))))
12288 (defun org-beginning-of-dblock ()
12289 "Find the beginning of the dynamic block at point.
12290 Error if there is no such block at point."
12291 (let ((pos (point))
12294 (if (and (re-search-backward org-dblock-start-re nil t)
12295 (setq beg (match-beginning 0))
12296 (re-search-forward org-dblock-end-re nil t)
12297 (> (match-end 0) pos))
12300 (error "Not in a dynamic block"))))
12302 (defun org-update-all-dblocks ()
12303 "Update all dynamic blocks in the buffer.
12304 This function can be used in a hook."
12306 (when (derived-mode-p 'org-mode)
12307 (org-map-dblocks 'org-update-dblock)))
12312 (declare-function org-export-backend-options "ox" (cl-x) t)
12313 (defun org-get-export-keywords ()
12314 "Return a list of all currently understood export keywords.
12315 Export keywords include options, block names, attributes and
12316 keywords relative to each registered export back-end."
12319 (bound-and-true-p org-export-registered-backends)
12320 (delq nil keywords))
12321 ;; Back-end name (for keywords, like #+LATEX:)
12322 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12323 (dolist (option-entry (org-export-backend-options backend))
12324 ;; Back-end options.
12325 (push (nth 1 option-entry) keywords)))))
12327 (defconst org-options-keywords
12328 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12329 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12330 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12331 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12332 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12334 (defcustom org-structure-template-alist
12335 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12336 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12337 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12338 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12339 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12340 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12341 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12343 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12345 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12348 ("I" "#+INCLUDE: %file ?"))
12349 "Structure completion elements.
12350 This is a list of abbreviation keys and values. The value gets inserted
12351 if you type `<' followed by the key and then press the completion key,
12352 usually `TAB'. %file will be replaced by a file name after prompting
12353 for the file using completion. The cursor will be placed at the position
12354 of the `?' in the template.
12355 There are two templates for each key, the first uses the original Org syntax,
12356 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12357 the default when the /org-mtags.el/ module has been loaded. See also the
12358 variable `org-mtags-prefer-muse-templates'."
12359 :group 'org-completion
12362 (string :tag "Key")
12363 (string :tag "Template")))
12365 :package-version '(Org . "8.3"))
12367 (defun org-try-structure-completion ()
12368 "Try to complete a structure template before point.
12369 This looks for strings like \"<e\" on an otherwise empty line and
12371 (let ((l (buffer-substring (point-at-bol) (point)))
12373 (when (and (looking-at "[ \t]*$")
12374 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12375 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12376 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12377 (match-beginning 1)) a)
12380 (defun org-complete-expand-structure-template (start cell)
12381 "Expand a structure template."
12382 (let ((rpl (nth 1 cell))
12384 (delete-region start (point))
12385 (when (string-match "\\`[ \t]*#\\+" rpl)
12388 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12389 (setq ind (buffer-substring (point-at-bol) (point))))
12391 (setq start (point))
12392 (when (string-match "%file" rpl)
12393 (setq rpl (replace-match
12397 (abbreviate-file-name (read-file-name "Include file: ")))
12400 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12401 (concat "\n" ind)))
12403 (when (re-search-backward "\\?" start t) (delete-char 1))))
12405 ;;;; TODO, DEADLINE, Comments
12407 (defun org-toggle-comment ()
12408 "Change the COMMENT state of an entry."
12411 (org-back-to-heading)
12412 (let ((case-fold-search nil))
12413 (looking-at org-complex-heading-regexp))
12414 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12415 (skip-chars-forward " \t")
12416 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12417 (if (org-in-commented-heading-p t)
12418 (delete-region (point)
12419 (progn (search-forward " " (line-end-position) 'move)
12420 (skip-chars-forward " \t")
12422 (insert org-comment-string)
12423 (unless (eolp) (insert " ")))))
12425 (defvar org-last-todo-state-is-todo nil
12426 "This is non-nil when the last TODO state change led to a TODO state.
12427 If the last change removed the TODO tag or switched to DONE, then
12430 (defvar org-setting-tags nil) ; dynamically skipped
12432 (defvar org-todo-setup-filter-hook nil
12433 "Hook for functions that pre-filter todo specs.
12434 Each function takes a todo spec and returns either nil or the spec
12435 transformed into canonical form." )
12437 (defvar org-todo-get-default-hook nil
12438 "Hook for functions that get a default item for todo.
12439 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12440 nil or a string to be used for the todo mark." )
12442 (defvar org-agenda-headline-snapshot-before-repeat)
12444 (defun org-current-effective-time ()
12445 "Return current time adjusted for `org-extend-today-until' variable."
12446 (let* ((ct (org-current-time))
12447 (dct (decode-time ct))
12450 (org-use-last-clock-out-time-as-effective-time
12451 (or (org-clock-get-last-clock-out-time) ct))
12452 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12453 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12457 (defun org-todo-yesterday (&optional arg)
12458 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12460 (if (eq major-mode 'org-agenda-mode)
12461 (apply 'org-agenda-todo-yesterday arg)
12462 (let* ((org-use-effective-time t)
12463 (hour (nth 2 (decode-time (org-current-time))))
12464 (org-extend-today-until (1+ hour)))
12467 (defvar org-block-entry-blocking ""
12468 "First entry preventing the TODO state change.")
12470 (defun org-cancel-repeater ()
12471 "Cancel a repeater by setting its numeric value to zero."
12474 (org-back-to-heading t)
12475 (let ((bound1 (point))
12476 (bound0 (save-excursion (outline-next-heading) (point))))
12477 (when (and (re-search-forward
12478 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12479 org-deadline-time-regexp "\\)\\|\\("
12480 org-ts-regexp "\\)")
12482 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12484 (replace-match "0" t nil nil 1)))))
12486 (defvar org-state) ;; dynamically scoped into this function
12487 (defun org-todo (&optional arg)
12488 "Change the TODO state of an item.
12490 The state of an item is given by a keyword at the start of the heading,
12492 *** TODO Write paper
12495 The different keywords are specified in the variable `org-todo-keywords'.
12496 By default the available states are \"TODO\" and \"DONE\". So, for this
12497 example: when the item starts with TODO, it is changed to DONE.
12498 When it starts with DONE, the DONE is removed. And when neither TODO nor
12499 DONE are present, add TODO at the beginning of the heading.
12501 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12503 With numeric prefix ARG, switch to that state.
12504 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12506 keywords (nextset).
12507 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12508 prefix, circumvent any state blocking.
12509 With a numeric prefix arg of 0, inhibit note taking for the change.
12510 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12512 When called through ELisp, arg is also interpreted in the following way:
12513 `none' -> empty state
12514 \"\" -> switch to empty state
12515 `done' -> switch to DONE
12516 `nextset' -> switch to the next set of keywords
12517 `previousset' -> switch to the previous set of keywords
12518 \"WAITING\" -> switch to the specified keyword, but only if it
12519 really is a member of `org-todo-keywords'."
12521 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12522 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12523 'region-start-level 'region))
12524 org-loop-over-headlines-in-active-region)
12527 org-loop-over-headlines-in-active-region
12528 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12529 (when (equal arg '(16)) (setq arg 'nextset))
12530 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12531 (let ((org-blocker-hook org-blocker-hook)
12534 (when (equal arg '(64))
12535 (setq arg nil org-blocker-hook nil))
12536 (when (and org-blocker-hook
12537 (or org-inhibit-blocking
12538 (org-entry-get nil "NOBLOCKING")))
12539 (setq org-blocker-hook nil))
12542 (org-back-to-heading t)
12543 (when (org-in-commented-heading-p t)
12544 (org-toggle-comment)
12546 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12547 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12548 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12549 (let* ((match-data (match-data))
12550 (startpos (point-at-bol))
12551 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12552 (org-log-done org-log-done)
12553 (org-log-repeat org-log-repeat)
12554 (org-todo-log-states org-todo-log-states)
12555 (org-inhibit-logging
12557 (progn (setq arg nil) 'note) org-inhibit-logging))
12558 (this (match-string 1))
12559 (hl-pos (match-beginning 0))
12560 (head (org-get-todo-sequence-head this))
12561 (ass (assoc head org-todo-kwd-alist))
12562 (interpret (nth 1 ass))
12563 (done-word (nth 3 ass))
12564 (final-done-word (nth 4 ass))
12565 (org-last-state (or this ""))
12566 (completion-ignore-case t)
12567 (member (member this org-todo-keywords-1))
12568 (tail (cdr member))
12570 ((and org-todo-key-trigger
12571 (or (and (equal arg '(4))
12572 (eq org-use-fast-todo-selection 'prefix))
12573 (and (not arg) org-use-fast-todo-selection
12574 (not (eq org-use-fast-todo-selection
12576 ;; Use fast selection
12577 (org-fast-todo-selection))
12578 ((and (equal arg '(4))
12579 (or (not org-use-fast-todo-selection)
12580 (not org-todo-key-trigger)))
12581 ;; Read a state with completion
12583 "State: " (mapcar #'list org-todo-keywords-1)
12587 (if tail (car tail) nil)
12588 (car org-todo-keywords-1)))
12590 (unless (equal member org-todo-keywords-1)
12592 (nth (- (length org-todo-keywords-1)
12594 org-todo-keywords-1)
12595 (org-last org-todo-keywords-1))))
12596 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12597 (setq arg nil))) ; hack to fall back to cycling
12599 ;; user or caller requests a specific state
12601 ((equal arg "") nil)
12602 ((eq arg 'none) nil)
12603 ((eq arg 'done) (or done-word (car org-done-keywords)))
12605 (or (car (cdr (member head org-todo-heads)))
12606 (car org-todo-heads)))
12607 ((eq arg 'previousset)
12608 (let ((org-todo-heads (reverse org-todo-heads)))
12609 (or (car (cdr (member head org-todo-heads)))
12610 (car org-todo-heads))))
12611 ((car (member arg org-todo-keywords-1)))
12613 (user-error "State `%s' not valid in this file" arg))
12614 ((nth (1- (prefix-numeric-value arg))
12615 org-todo-keywords-1))))
12616 ((null member) (or head (car org-todo-keywords-1)))
12617 ((equal this final-done-word) nil) ;; -> make empty
12618 ((null tail) nil) ;; -> first entry
12619 ((memq interpret '(type priority))
12620 (if (eq this-command last-command)
12622 (if (> (length tail) 0)
12623 (or done-word (car org-done-keywords))
12628 (run-hook-with-args-until-success
12629 'org-todo-get-default-hook org-state org-last-state)
12631 (next (if org-state (concat " " org-state " ") " "))
12632 (change-plist (list :type 'todo-state-change :from this :to org-state
12633 :position startpos))
12635 (when org-blocker-hook
12636 (setq org-last-todo-state-is-todo
12637 (not (member this org-done-keywords)))
12638 (unless (save-excursion
12640 (org-with-wide-buffer
12641 (run-hook-with-args-until-failure
12642 'org-blocker-hook change-plist))))
12643 (if (called-interactively-p 'interactive)
12644 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12645 this org-state org-block-entry-blocking)
12647 (message "TODO state change from %s to %s blocked (by \"%s\")"
12648 this org-state org-block-entry-blocking)
12649 (throw 'exit nil))))
12650 (store-match-data match-data)
12651 (replace-match next t t)
12652 (cond ((equal this org-state)
12653 (message "TODO state was already %s" (org-trim next)))
12654 ((pos-visible-in-window-p hl-pos)
12655 (message "TODO state changed to %s" (org-trim next))))
12657 (setq head (org-get-todo-sequence-head org-state)
12658 ass (assoc head org-todo-kwd-alist)
12659 interpret (nth 1 ass)
12660 done-word (nth 3 ass)
12661 final-done-word (nth 4 ass)))
12662 (when (memq arg '(nextset previousset))
12663 (message "Keyword-Set %d/%d: %s"
12664 (- (length org-todo-sets) -1
12665 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12666 (length org-todo-sets)
12667 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12668 (setq org-last-todo-state-is-todo
12669 (not (member org-state org-done-keywords)))
12670 (setq now-done-p (and (member org-state org-done-keywords)
12671 (not (member this org-done-keywords))))
12672 (and logging (org-local-logging logging))
12673 (when (and (or org-todo-log-states org-log-done)
12674 (not (eq org-inhibit-logging t))
12675 (not (memq arg '(nextset previousset))))
12676 ;; we need to look at recording a time and note
12677 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12678 (nth 2 (assoc this org-todo-log-states))))
12679 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12680 (setq dolog 'time))
12681 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12683 (member org-state org-not-done-keywords)
12684 (not (member this org-not-done-keywords))))
12685 ;; This is now a todo state and was not one before
12686 ;; If there was a CLOSED time stamp, get rid of it.
12687 (org-add-planning-info nil nil 'closed))
12688 (when (and now-done-p org-log-done)
12689 ;; It is now done, and it was not done before
12690 (org-add-planning-info 'closed (org-current-effective-time))
12691 (when (and (not dolog) (eq 'note org-log-done))
12692 (org-add-log-setup 'done org-state this 'note)))
12693 (when (and org-state dolog)
12694 ;; This is a non-nil state, and we need to log it
12695 (org-add-log-setup 'state org-state this dolog)))
12696 ;; Fixup tag positioning
12697 (org-todo-trigger-tag-changes org-state)
12698 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12699 (when org-provide-todo-statistics
12700 (org-update-parent-todo-statistics))
12701 (run-hooks 'org-after-todo-state-change-hook)
12702 (when (and arg (not (member org-state org-done-keywords)))
12703 (setq head (org-get-todo-sequence-head org-state)))
12704 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12705 ;; Do we need to trigger a repeat?
12707 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12708 ;; This is for the agenda, take a snapshot of the headline.
12710 (setq org-agenda-headline-snapshot-before-repeat
12711 (org-get-heading))))
12712 (org-auto-repeat-maybe org-state))
12713 ;; Fixup cursor location if close to the keyword
12714 (when (and (outline-on-heading-p)
12716 (save-excursion (beginning-of-line 1)
12717 (looking-at org-todo-line-regexp))
12718 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12719 (goto-char (or (match-end 2) (match-end 1)))
12720 (and (looking-at " ") (just-one-space)))
12721 (when org-trigger-hook
12723 (run-hook-with-args 'org-trigger-hook change-plist)))
12724 (when commentp (org-toggle-comment))))))))
12726 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12727 "Block turning an entry into a TODO, using the hierarchy.
12728 This checks whether the current task should be blocked from state
12729 changes. Such blocking occurs when:
12731 1. The task has children which are not all in a completed state.
12733 2. A task has a parent with the property :ORDERED:, and there
12734 are siblings prior to the current task with incomplete
12737 3. The parent of the task is blocked because it has siblings that should
12738 be done first, or is child of a block grandparent TODO entry."
12740 (if (not org-enforce-todo-dependencies)
12741 t ; if locally turned off don't block
12743 ;; If this is not a todo state change, or if this entry is already DONE,
12745 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12746 (member (plist-get change-plist :from)
12747 (cons 'done org-done-keywords))
12748 (member (plist-get change-plist :to)
12749 (cons 'todo org-not-done-keywords))
12750 (not (plist-get change-plist :to)))
12751 (throw 'dont-block t))
12752 ;; If this task has children, and any are undone, it's blocked
12754 (org-back-to-heading t)
12755 (let ((this-level (funcall outline-level)))
12756 (outline-next-heading)
12757 (let ((child-level (funcall outline-level)))
12758 (while (and (not (eobp))
12759 (> child-level this-level))
12760 ;; this todo has children, check whether they are all
12762 (when (and (not (org-entry-is-done-p))
12763 (org-entry-is-todo-p))
12764 (setq org-block-entry-blocking (org-get-heading))
12765 (throw 'dont-block nil))
12766 (outline-next-heading)
12767 (setq child-level (funcall outline-level))))))
12768 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12769 ;; any previous siblings are undone, it's blocked
12771 (org-back-to-heading t)
12772 (let* ((pos (point))
12773 (parent-pos (and (org-up-heading-safe) (point)))
12774 (case-fold-search nil))
12775 (unless parent-pos (throw 'dont-block t)) ; no parent
12776 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12778 (re-search-forward org-not-done-heading-regexp pos t))
12779 (setq org-block-entry-blocking (match-string 0))
12780 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12781 ;; Search further up the hierarchy, to see if an ancestor is blocked
12783 (goto-char parent-pos)
12784 (unless (looking-at org-not-done-heading-regexp)
12785 (throw 'dont-block t)) ; do not block, parent is not a TODO
12787 (setq parent-pos (and (org-up-heading-safe) (point)))
12788 (unless parent-pos (throw 'dont-block t)) ; no parent
12789 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12791 (re-search-forward org-not-done-heading-regexp pos t)
12792 (setq org-block-entry-blocking (org-get-heading)))
12793 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12795 (defcustom org-track-ordered-property-with-tag nil
12796 "Should the ORDERED property also be shown as a tag?
12797 The ORDERED property decides if an entry should require subtasks to be
12798 completed in sequence. Since a property is not very visible, setting
12799 this option means that toggling the ORDERED property with the command
12800 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12801 not relevant for the behavior, but it makes things more visible.
12803 Note that toggling the tag with tags commands will not change the property
12804 and therefore not influence behavior!
12806 This can be t, meaning the tag ORDERED should be used, It can also be a
12807 string to select a different tag for this task."
12810 (const :tag "No tracking" nil)
12811 (const :tag "Track with ORDERED tag" t)
12812 (string :tag "Use other tag")))
12814 (defun org-toggle-ordered-property ()
12815 "Toggle the ORDERED property of the current entry.
12816 For better visibility, you can track the value of this property with a tag.
12817 See variable `org-track-ordered-property-with-tag'."
12819 (let* ((t1 org-track-ordered-property-with-tag)
12820 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12822 (org-back-to-heading)
12823 (if (org-entry-get nil "ORDERED")
12825 (org-delete-property "ORDERED")
12826 (and tag (org-toggle-tag tag 'off))
12827 (message "Subtasks can be completed in arbitrary order"))
12828 (org-entry-put nil "ORDERED" "t")
12829 (and tag (org-toggle-tag tag 'on))
12830 (message "Subtasks must be completed in sequence")))))
12832 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12833 (defun org-block-todo-from-checkboxes (change-plist)
12834 "Block turning an entry into a TODO, using checkboxes.
12835 This checks whether the current task should be blocked from state
12836 changes because there are unchecked boxes in this entry."
12837 (if (not org-enforce-todo-checkbox-dependencies)
12838 t ; if locally turned off don't block
12840 ;; If this is not a todo state change, or if this entry is already DONE,
12842 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12843 (member (plist-get change-plist :from)
12844 (cons 'done org-done-keywords))
12845 (member (plist-get change-plist :to)
12846 (cons 'todo org-not-done-keywords))
12847 (not (plist-get change-plist :to)))
12848 (throw 'dont-block t))
12849 ;; If this task has checkboxes that are not checked, it's blocked
12851 (org-back-to-heading t)
12852 (let ((beg (point)) end)
12853 (outline-next-heading)
12856 (when (org-list-search-forward
12857 (concat (org-item-beginning-re)
12858 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12861 (when (boundp 'org-blocked-by-checkboxes)
12862 (setq org-blocked-by-checkboxes t))
12863 (throw 'dont-block nil))))
12864 t))) ; do not block
12866 (defun org-entry-blocked-p ()
12867 "Non-nil if entry at point is blocked."
12868 (and (not (org-entry-get nil "NOBLOCKING"))
12869 (member (org-entry-get nil "TODO") org-not-done-keywords)
12870 (not (run-hook-with-args-until-failure
12872 (list :type 'todo-state-change
12877 (defun org-update-statistics-cookies (all)
12878 "Update the statistics cookie, either from TODO or from checkboxes.
12879 This should be called with the cursor in a line with a statistics
12880 cookie. When called with a \\[universal-argument] prefix, update
12881 all statistics cookies in the buffer."
12885 (org-update-checkbox-count 'all)
12886 (org-map-entries 'org-update-parent-todo-statistics))
12887 (if (not (org-at-heading-p))
12888 (org-update-checkbox-count)
12889 (let ((pos (point-marker))
12891 (ignore-errors (org-back-to-heading t))
12892 (if (not (org-at-heading-p))
12893 (org-update-checkbox-count)
12894 (setq l1 (org-outline-level))
12895 (setq end (save-excursion
12896 (outline-next-heading)
12897 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12899 (if (and (save-excursion
12901 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12902 (not (save-excursion (re-search-forward
12903 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12904 (org-update-checkbox-count)
12905 (if (and l2 (> l2 l1))
12908 (org-update-parent-todo-statistics))
12910 (beginning-of-line 1)
12911 (while (re-search-forward
12912 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12914 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12916 (move-marker pos nil)))))
12918 (defvar org-entry-property-inherited-from) ;; defined below
12919 (defun org-update-parent-todo-statistics ()
12920 "Update any statistics cookie in the parent of the current headline.
12921 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12922 the entire subtree and this will travel up the hierarchy and update
12923 statistics everywhere."
12924 (let* ((prop (save-excursion (org-up-heading-safe)
12925 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12926 (recursive (or (not org-hierarchical-todo-statistics)
12927 (and prop (string-match "\\<recursive\\>" prop))))
12928 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12931 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12932 level ltoggle l1 new ndel
12933 (cnt-all 0) (cnt-done 0) is-percent kwd
12934 checkbox-beg cookie-present)
12937 (beginning-of-line 1)
12938 (setq ltoggle (funcall outline-level))
12939 ;; Three situations are to consider:
12941 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12942 ;; to the top-level ancestor on the headline;
12944 ;; 2. If parent has "recursive" property, repeat up to the
12945 ;; headline setting that property, taking inheritance into
12948 ;; 3. Else, move up to direct parent and proceed only once.
12949 (while (and (setq level (org-up-heading-safe))
12950 (or recursive first)
12952 (setq first nil cookie-present nil)
12956 (downcase (or (org-entry-get nil "COOKIE_DATA")
12959 (while (re-search-forward box-re (point-at-eol) t)
12960 (setq cnt-all 0 cnt-done 0 cookie-present t)
12961 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12963 (unless (outline-next-heading) (throw 'exit nil))
12964 (while (and (looking-at org-complex-heading-regexp)
12965 (> (setq l1 (length (match-string 1))) level))
12966 (setq kwd (and (or recursive (= l1 ltoggle))
12968 (if (or (eq org-provide-todo-statistics 'all-headlines)
12969 (and (eq org-provide-todo-statistics t)
12970 (or (member kwd org-done-keywords)))
12971 (and (listp org-provide-todo-statistics)
12972 (stringp (car org-provide-todo-statistics))
12973 (or (member kwd org-provide-todo-statistics)
12974 (member kwd org-done-keywords)))
12975 (and (listp org-provide-todo-statistics)
12976 (listp (car org-provide-todo-statistics))
12977 (or (member kwd (car org-provide-todo-statistics))
12978 (and (member kwd org-done-keywords)
12979 (member kwd (cadr org-provide-todo-statistics))))))
12980 (setq cnt-all (1+ cnt-all))
12981 (and (eq org-provide-todo-statistics t)
12983 (setq cnt-all (1+ cnt-all))))
12984 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12985 (member kwd org-done-keywords))
12986 (and (listp org-provide-todo-statistics)
12987 (listp (car org-provide-todo-statistics))
12988 (member kwd org-done-keywords)
12989 (member kwd (cadr org-provide-todo-statistics)))
12990 (and (listp org-provide-todo-statistics)
12991 (stringp (car org-provide-todo-statistics))
12992 (member kwd org-done-keywords)))
12993 (setq cnt-done (1+ cnt-done)))
12994 (outline-next-heading)))
12997 (format "[%d%%]" (floor (* 100.0 cnt-done)
12999 (format "[%d/%d]" cnt-done cnt-all))
13000 ndel (- (match-end 0) checkbox-beg))
13001 (goto-char checkbox-beg)
13003 (delete-region (point) (+ (point) ndel))
13004 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13005 (when cookie-present
13006 (run-hook-with-args 'org-after-todo-statistics-hook
13007 cnt-done (- cnt-all cnt-done))))))
13008 (run-hooks 'org-todo-statistics-hook)))
13010 (defvar org-after-todo-statistics-hook nil
13011 "Hook that is called after a TODO statistics cookie has been updated.
13012 Each function is called with two arguments: the number of not-done entries
13013 and the number of done entries.
13015 For example, the following function, when added to this hook, will switch
13016 an entry to DONE when all children are done, and back to TODO when new
13017 entries are set to a TODO status. Note that this hook is only called
13018 when there is a statistics cookie in the headline!
13020 (defun org-summary-todo (n-done n-not-done)
13021 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13022 (let (org-log-done org-log-states) ; turn off logging
13023 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13026 (defvar org-todo-statistics-hook nil
13027 "Hook that is run whenever Org thinks TODO statistics should be updated.
13028 This hook runs even if there is no statistics cookie present, in which case
13029 `org-after-todo-statistics-hook' would not run.")
13031 (defun org-todo-trigger-tag-changes (state)
13032 "Apply the changes defined in `org-todo-state-tags-triggers'."
13033 (let ((l org-todo-state-tags-triggers)
13035 (when (or (not state) (equal state ""))
13036 (setq changes (append changes (cdr (assoc "" l)))))
13037 (when (and (stringp state) (> (length state) 0))
13038 (setq changes (append changes (cdr (assoc state l)))))
13039 (when (member state org-not-done-keywords)
13040 (setq changes (append changes (cdr (assq 'todo l)))))
13041 (when (member state org-done-keywords)
13042 (setq changes (append changes (cdr (assq 'done l)))))
13043 (dolist (c changes)
13044 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13046 (defun org-local-logging (value)
13047 "Get logging settings from a property VALUE."
13048 ;; Directly set the variables, they are already local.
13049 (setq org-log-done nil
13051 org-todo-log-states nil)
13052 (dolist (w (org-split-string value))
13055 ((setq a (assoc w org-startup-options))
13056 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13057 (set (nth 1 a) (nth 2 a))))
13058 ((setq a (org-extract-log-state-settings w))
13059 (and (member (car a) org-todo-keywords-1)
13060 (push a org-todo-log-states)))))))
13062 (defun org-get-todo-sequence-head (kwd)
13063 "Return the head of the TODO sequence to which KWD belongs.
13064 If KWD is not set, check if there is a text property remembering the
13069 (or (get-text-property (point-at-bol) 'org-todo-head)
13071 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13072 nil (point-at-eol)))
13073 (get-text-property p 'org-todo-head))))
13074 ((not (member kwd org-todo-keywords-1))
13075 (car org-todo-keywords-1))
13076 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13078 (defun org-fast-todo-selection ()
13079 "Fast TODO keyword selection with single keys.
13080 Returns the new TODO keyword, or nil if no state change should occur."
13081 (let* ((fulltable org-todo-key-alist)
13082 (done-keywords org-done-keywords) ;; needed for the faces.
13083 (maxlen (apply 'max (mapcar
13085 (if (stringp (car x)) (string-width (car x)) 0))
13088 (fwidth (+ maxlen 3 1 3))
13089 (ncol (/ (- (window-width) 4) fwidth))
13093 (save-window-excursion
13095 (set-buffer (get-buffer-create " *Org todo*"))
13096 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13098 (setq-local org-done-keywords done-keywords)
13099 (setq tbl fulltable cnt 0)
13100 (while (setq e (pop tbl))
13102 ((equal e '(:startgroup))
13103 (push '() groups) (setq ingroup t)
13108 ((equal e '(:endgroup))
13109 (setq ingroup nil cnt 0)
13111 ((equal e '(:newline))
13116 (while (equal (car tbl) '(:newline))
13118 (setq tbl (cdr tbl)))))
13120 (setq tg (car e) c (cdr e))
13121 (when ingroup (push tg (car groups)))
13122 (setq tg (org-add-props tg nil 'face
13123 (org-get-todo-face tg)))
13124 (when (and (= cnt 0) (not ingroup)) (insert " "))
13125 (insert "[" c "] " tg (make-string
13126 (- fwidth 4 (length tg)) ?\ ))
13127 (when (= (setq cnt (1+ cnt)) ncol)
13129 (when ingroup (insert " "))
13132 (goto-char (point-min))
13133 (unless expert (org-fit-window-to-buffer))
13134 (message "[a-z..]:Set [SPC]:clear")
13135 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13138 (and (= c ?q) (not (rassoc c fulltable))))
13139 (setq quit-flag t))
13141 ((setq e (rassoc c fulltable) tg (car e))
13143 (t (setq quit-flag t)))))))
13145 (defun org-entry-is-todo-p ()
13146 (member (org-get-todo-state) org-not-done-keywords))
13148 (defun org-entry-is-done-p ()
13149 (member (org-get-todo-state) org-done-keywords))
13151 (defun org-get-todo-state ()
13152 "Return the TODO keyword of the current subtree."
13154 (org-back-to-heading t)
13155 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13157 (match-string 2))))
13159 (defun org-at-date-range-p (&optional inactive-ok)
13160 "Non-nil if point is inside a date range.
13162 When optional argument INACTIVE-OK is non-nil, also consider
13163 inactive time ranges.
13165 When this function returns a non-nil value, match data is set
13166 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13171 (let ((pos (point)))
13172 (skip-chars-backward "^[<\r\n")
13173 (skip-chars-backward "<[")
13174 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13175 (>= (match-end 0) pos)
13177 (skip-chars-backward "^<[\r\n")
13178 (skip-chars-backward "<[")
13179 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13180 (>= (match-end 0) pos)
13184 (defun org-get-repeat (&optional tagline)
13185 "Check if there is a deadline/schedule with repeater in this entry."
13188 (org-back-to-heading t)
13189 (and (re-search-forward (if tagline
13190 (concat tagline "\\s-*" org-repeat-re)
13192 (org-entry-end-position) t)
13193 (match-string-no-properties 1)))))
13195 (defvar org-last-changed-timestamp)
13196 (defvar org-last-inserted-timestamp)
13197 (defvar org-log-post-message)
13198 (defvar org-log-note-purpose)
13199 (defvar org-log-note-how nil)
13200 (defvar org-log-note-extra)
13201 (defun org-auto-repeat-maybe (done-word)
13202 "Check if the current headline contains a repeated time-stamp.
13204 If yes, set TODO state back to what it was and change the base date
13205 of repeating deadline/scheduled time stamps to new date.
13207 This function is run automatically after each state change to a DONE state."
13208 (let* ((repeat (org-get-repeat))
13209 (aa (assoc org-last-state org-todo-kwd-alist))
13210 (interpret (nth 1 aa))
13212 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13213 (msg "Entry repeats: ")
13215 (org-todo-log-states nil))
13216 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13217 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13218 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13219 org-todo-repeat-to-state)))
13220 (unless (and to-state (member to-state org-todo-keywords-1))
13221 (setq to-state (if (eq interpret 'type) org-last-state head)))
13222 (org-todo to-state))
13223 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13224 (org-entry-put nil "LAST_REPEAT" (format-time-string
13225 (org-time-stamp-format t t))))
13226 (when org-log-repeat
13227 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13228 (memq 'org-add-log-note post-command-hook))
13229 ;; We are already setup for some record.
13230 (when (eq org-log-repeat 'note)
13231 ;; Make sure we take a note, not only a time stamp.
13232 (setq org-log-note-how 'note))
13233 ;; Set up for taking a record.
13234 (org-add-log-setup 'state
13235 (or done-word (car org-done-keywords))
13238 (org-back-to-heading t)
13239 (org-add-planning-info nil nil 'closed)
13240 (let ((end (save-excursion (outline-next-heading) (point)))
13241 (planning-re (regexp-opt
13242 (list org-scheduled-string org-deadline-string))))
13243 (while (re-search-forward org-ts-regexp end t)
13244 (let* ((ts (match-string 0))
13245 (planning? (org-at-planning-p))
13246 (type (if (not planning?) "Plain:"
13248 (re-search-backward
13249 planning-re (line-beginning-position) t)
13250 (match-string 0)))))
13252 ;; Ignore fake time-stamps (e.g., within comments).
13253 ((and (not planning?)
13254 (not (org-at-property-p))
13255 (not (eq 'timestamp
13256 (org-element-type (save-excursion
13258 (org-element-context)))))))
13259 ;; Time-stamps without a repeater are usually skipped.
13260 ;; However, a SCHEDULED time-stamp without one is
13261 ;; removed, as it is considered as no longer relevant.
13262 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13263 (when (equal type org-scheduled-string)
13264 (org-remove-timestamp-with-keyword type)))
13266 (let ((n (string-to-number (match-string 2 ts)))
13267 (what (match-string 3 ts)))
13268 (when (equal what "w") (setq n (* n 7) what "d"))
13269 (when (and (equal what "h")
13270 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13273 "Cannot repeat in Repeat in %d hour(s) because no hour \
13276 ;; Preparation, see if we need to modify the start
13277 ;; date for the change.
13278 (when (match-end 1)
13279 (let ((time (save-match-data (org-time-string-to-time ts))))
13281 ((equal (match-string 1 ts) ".")
13282 ;; Shift starting date to today
13283 (org-timestamp-change
13284 (- (org-today) (time-to-days time))
13286 ((equal (match-string 1 ts) "+")
13287 (let ((nshiftmax 10)
13289 (while (or (= nshift 0)
13290 (not (time-less-p (current-time) time)))
13291 (when (= (cl-incf nshift) nshiftmax)
13293 (format "%d repeater intervals were not \
13294 enough to shift date past today. Continue? "
13296 (user-error "Abort")))
13297 (org-timestamp-change n (cdr (assoc what whata)))
13298 (org-at-timestamp-p t)
13299 (setq ts (match-string 1))
13302 (org-time-string-to-time ts)))))
13303 (org-timestamp-change (- n) (cdr (assoc what whata)))
13304 ;; Rematch, so that we have everything in place
13305 ;; for the real shift.
13306 (org-at-timestamp-p t)
13307 (setq ts (match-string 1))
13308 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13311 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13314 msg type " " org-last-changed-timestamp " "))))))))
13315 (setq org-log-post-message msg)
13316 (message "%s" msg))))
13318 (defun org-show-todo-tree (arg)
13319 "Make a compact tree which shows all headlines marked with TODO.
13320 The tree will show the lines where the regexp matches, and all higher
13321 headlines above the match.
13322 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13323 With a numeric prefix N, construct a sparse tree for the Nth element
13324 of `org-todo-keywords-1'."
13326 (let ((case-fold-search nil)
13328 (cond ((null arg) org-not-done-regexp)
13331 (completing-read "Keyword (or KWD1|KWD2|...): "
13332 (mapcar #'list org-todo-keywords-1))))
13334 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13336 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13337 (regexp-quote (nth (1- (prefix-numeric-value arg))
13338 org-todo-keywords-1)))
13339 (t (user-error "Invalid prefix argument: %s" arg)))))
13340 (message "%d TODO entries found"
13341 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13343 (defun org-deadline (arg &optional time)
13344 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13345 With one universal prefix argument, remove any deadline from the item.
13346 With two universal prefix arguments, prompt for a warning delay.
13347 With argument TIME, set the deadline at the corresponding date. TIME
13348 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13350 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13351 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13352 'region-start-level 'region))
13353 org-loop-over-headlines-in-active-region)
13355 `(org-deadline ',arg ,time)
13356 org-loop-over-headlines-in-active-region
13357 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13358 (let* ((old-date (org-entry-get nil "DEADLINE"))
13359 (old-date-time (when old-date (org-time-string-to-time old-date)))
13360 (repeater (and old-date
13362 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13364 (match-string 1 old-date))))
13367 (when (and old-date org-log-redeadline)
13368 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13369 (org-remove-timestamp-with-keyword org-deadline-string)
13370 (message "Item no longer has a deadline."))
13373 (org-back-to-heading t)
13374 (if (re-search-forward
13375 org-deadline-time-regexp
13376 (save-excursion (outline-next-heading) (point)) t)
13377 (let* ((rpl0 (match-string 1))
13378 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13380 (concat org-deadline-string
13386 (org-read-date nil t nil "Warn starting from" old-date-time)))
13387 (time-to-days old-date-time))))
13389 (user-error "No deadline information to update"))))
13391 (org-add-planning-info 'deadline time 'closed)
13392 (when (and old-date
13394 (not (equal old-date org-last-inserted-timestamp)))
13396 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13399 (org-back-to-heading t)
13400 (when (re-search-forward (concat org-deadline-string " "
13401 org-last-inserted-timestamp)
13403 (outline-next-heading) (point)) t)
13404 (goto-char (1- (match-end 0)))
13405 (insert " " repeater)
13406 (setq org-last-inserted-timestamp
13407 (concat (substring org-last-inserted-timestamp 0 -1)
13409 (substring org-last-inserted-timestamp -1))))))
13410 (message "Deadline on %s" org-last-inserted-timestamp))))))
13412 (defun org-schedule (arg &optional time)
13413 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13414 With one universal prefix argument, remove any scheduling date from the item.
13415 With two universal prefix arguments, prompt for a delay cookie.
13416 With argument TIME, scheduled at the corresponding date. TIME can
13417 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13419 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13420 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13421 'region-start-level 'region))
13422 org-loop-over-headlines-in-active-region)
13424 `(org-schedule ',arg ,time)
13425 org-loop-over-headlines-in-active-region
13426 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13427 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13428 (old-date-time (when old-date (org-time-string-to-time old-date)))
13429 (repeater (and old-date
13431 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13433 (match-string 1 old-date))))
13437 (when (and old-date org-log-reschedule)
13438 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13439 (org-remove-timestamp-with-keyword org-scheduled-string)
13440 (message "Item is no longer scheduled.")))
13443 (org-back-to-heading t)
13444 (if (re-search-forward
13445 org-scheduled-time-regexp
13446 (save-excursion (outline-next-heading) (point)) t)
13447 (let* ((rpl0 (match-string 1))
13448 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13450 (concat org-scheduled-string
13456 (org-read-date nil t nil "Delay until" old-date-time)))
13457 (time-to-days old-date-time))))
13459 (user-error "No scheduled information to update"))))
13461 (org-add-planning-info 'scheduled time 'closed)
13462 (when (and old-date
13464 (not (equal old-date org-last-inserted-timestamp)))
13466 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13469 (org-back-to-heading t)
13470 (when (re-search-forward (concat org-scheduled-string " "
13471 org-last-inserted-timestamp)
13473 (outline-next-heading) (point)) t)
13474 (goto-char (1- (match-end 0)))
13475 (insert " " repeater)
13476 (setq org-last-inserted-timestamp
13477 (concat (substring org-last-inserted-timestamp 0 -1)
13479 (substring org-last-inserted-timestamp -1))))))
13480 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13482 (defun org-get-scheduled-time (pom &optional inherit)
13483 "Get the scheduled time as a time tuple, of a format suitable
13484 for calling org-schedule with, or if there is no scheduling,
13486 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13488 (apply 'encode-time (org-parse-time-string time)))))
13490 (defun org-get-deadline-time (pom &optional inherit)
13491 "Get the deadline as a time tuple, of a format suitable for
13492 calling org-deadline with, or if there is no scheduling, returns
13494 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13496 (apply 'encode-time (org-parse-time-string time)))))
13498 (defun org-remove-timestamp-with-keyword (keyword)
13499 "Remove all time stamps with KEYWORD in the current entry."
13500 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13503 (org-back-to-heading t)
13505 (outline-next-heading)
13506 (while (re-search-backward re beg t)
13508 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13509 (equal (char-before) ?\ ))
13510 (backward-delete-char 1)
13511 (when (string-match "^[ \t]*$" (buffer-substring
13512 (point-at-bol) (point-at-eol)))
13513 (delete-region (point-at-bol)
13514 (min (point-max) (1+ (point-at-eol))))))))))
13516 (defvar org-time-was-given) ; dynamically scoped parameter
13517 (defvar org-end-time-was-given) ; dynamically scoped parameter
13519 (defun org-at-planning-p ()
13520 "Non-nil when point is on a planning info line."
13521 ;; This is as accurate and faster than `org-element-at-point' since
13522 ;; planning info location is fixed in the section.
13523 (org-with-wide-buffer
13524 (beginning-of-line)
13525 (and (looking-at-p org-planning-line-re)
13528 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13529 (org-back-to-heading t)
13530 (org-with-limited-levels (org-back-to-heading t)))
13531 (line-beginning-position 2))))))
13533 (defun org-add-planning-info (what &optional time &rest remove)
13534 "Insert new timestamp with keyword in the planning line.
13535 WHAT indicates what kind of time stamp to add. It is a symbol
13536 among `closed', `deadline', `scheduled' and nil. TIME indicates
13537 the time to use. If none is given, the user is prompted for
13538 a date. REMOVE indicates what kind of entries to remove. An old
13539 WHAT entry will also be removed."
13540 (let (org-time-was-given org-end-time-was-given default-time default-input)
13542 (when (and (memq what '(scheduled deadline))
13544 (and (stringp time)
13545 (string-match "^[-+]+[0-9]" time))))
13546 ;; Try to get a default date/time from existing timestamp
13548 (org-back-to-heading t)
13549 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13550 (when (re-search-forward (if (eq what 'scheduled)
13551 org-scheduled-time-regexp
13552 org-deadline-time-regexp)
13554 (setq ts (match-string 1)
13555 default-time (apply 'encode-time (org-parse-time-string ts))
13556 default-input (and ts (org-get-compact-tod ts)))))))
13560 ;; This is a string (relative or absolute), set
13562 (apply #'encode-time
13563 (org-read-date-analyze
13564 time default-time (decode-time default-time)))
13565 ;; If necessary, get the time from the user
13566 (or time (org-read-date nil 'to-time nil nil
13567 default-time default-input)))))
13569 (org-with-wide-buffer
13570 (org-back-to-heading t)
13572 (unless (bolp) (insert "\n"))
13573 (cond ((looking-at-p org-planning-line-re)
13574 ;; Move to current indentation.
13575 (skip-chars-forward " \t")
13576 ;; Check if we have to remove something.
13577 (dolist (type (if what (cons what remove) remove))
13579 (when (re-search-forward
13581 (closed org-closed-time-regexp)
13582 (deadline org-deadline-time-regexp)
13583 (scheduled org-scheduled-time-regexp)
13585 (error "Invalid planning type: %s" type)))
13586 (line-end-position) t)
13587 ;; Delete until next keyword or end of line.
13589 (match-beginning 0)
13590 (if (re-search-forward org-keyword-time-not-clock-regexp
13591 (line-end-position)
13593 (match-beginning 0)
13594 (line-end-position))))))
13595 ;; If there is nothing more to add and no more keyword
13596 ;; is left, remove the line completely.
13597 (if (and (looking-at-p "[ \t]*$") (not what))
13598 (delete-region (line-beginning-position)
13599 (line-beginning-position 2))
13600 ;; If we removed last keyword, do not leave trailing
13601 ;; white space at the end of line.
13605 (unless (= (skip-chars-backward " \t" p) 0)
13606 (delete-region (point) (line-end-position)))))))
13607 ((not what) (throw 'exit nil)) ; Nothing to do.
13608 (t (insert-before-markers "\n")
13610 (when org-adapt-indentation
13611 (indent-to-column (1+ (org-outline-level))))))
13613 ;; Insert planning keyword.
13614 (insert (cl-case what
13615 (closed org-closed-string)
13616 (deadline org-deadline-string)
13617 (scheduled org-scheduled-string)
13618 (otherwise (error "Invalid planning type: %s" what)))
13620 ;; Insert associated timestamp.
13621 (let ((ts (org-insert-time-stamp
13623 (or org-time-was-given
13624 (and (eq what 'closed) org-log-done-with-time))
13626 nil nil (list org-end-time-was-given))))
13627 (unless (eolp) (insert " "))
13630 (defvar org-log-note-marker (make-marker)
13631 "Marker pointing at the entry where the note is to be inserted.")
13632 (defvar org-log-note-purpose nil)
13633 (defvar org-log-note-state nil)
13634 (defvar org-log-note-previous-state nil)
13635 (defvar org-log-note-extra nil)
13636 (defvar org-log-note-window-configuration nil)
13637 (defvar org-log-note-return-to (make-marker))
13638 (defvar org-log-note-effective-time nil
13639 "Remembered current time so that dynamically scoped
13640 `org-extend-today-until' affects timestamps in state change log")
13642 (defvar org-log-post-message nil
13643 "Message to be displayed after a log note has been stored.
13644 The auto-repeater uses this.")
13646 (defun org-add-note ()
13647 "Add a note to the current entry.
13648 This is done in the same way as adding a state change note."
13650 (org-add-log-setup 'note))
13652 (defun org-log-beginning (&optional create)
13653 "Return expected start of log notes in current entry.
13654 When optional argument CREATE is non-nil, the function creates
13655 a drawer to store notes, if necessary. Returned position ignores
13657 (org-with-wide-buffer
13658 (let ((drawer (org-log-into-drawer)))
13661 (org-end-of-meta-data)
13662 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13663 (end (if (org-at-heading-p) (point)
13664 (save-excursion (outline-next-heading) (point))))
13665 (case-fold-search t))
13667 ;; Try to find existing drawer.
13668 (while (re-search-forward regexp end t)
13669 (let ((element (org-element-at-point)))
13670 (when (eq (org-element-type element) 'drawer)
13671 (let ((cend (org-element-property :contents-end element)))
13672 (when (and (not org-log-states-order-reversed) cend)
13674 (throw 'exit nil))))
13675 ;; No drawer found. Create one, if permitted.
13677 (unless (bolp) (insert "\n"))
13678 (let ((beg (point)))
13679 (insert ":" drawer ":\n:END:\n")
13680 (org-indent-region beg (point)))
13681 (end-of-line -1)))))
13683 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13684 (skip-chars-forward " \t\n")
13685 (beginning-of-line)
13686 (unless org-log-states-order-reversed
13687 (org-skip-over-state-notes)
13688 (skip-chars-backward " \t\n")
13690 (if (bolp) (point) (line-beginning-position 2))))
13692 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13693 "Set up the post command hook to take a note.
13694 If this is about to TODO state change, the new state is expected in STATE.
13695 HOW is an indicator what kind of note should be created.
13696 EXTRA is additional text that will be inserted into the notes buffer."
13697 (move-marker org-log-note-marker (point))
13698 (setq org-log-note-purpose purpose
13699 org-log-note-state state
13700 org-log-note-previous-state prev-state
13701 org-log-note-how how
13702 org-log-note-extra extra
13703 org-log-note-effective-time (org-current-effective-time))
13704 (add-hook 'post-command-hook 'org-add-log-note 'append))
13706 (defun org-skip-over-state-notes ()
13707 "Skip past the list of State notes in an entry."
13708 (when (ignore-errors (goto-char (org-in-item-p)))
13709 (let* ((struct (org-list-struct))
13710 (prevs (org-list-prevs-alist struct))
13712 (concat "[ \t]*- +"
13713 (replace-regexp-in-string
13715 (org-replace-escapes
13716 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13717 `(("%d" . ,org-ts-regexp-inactive)
13718 ("%D" . ,org-ts-regexp)
13719 ("%s" . "\"\\S-+\"")
13720 ("%S" . "\"\\S-+\"")
13721 ("%t" . ,org-ts-regexp-inactive)
13722 ("%T" . ,org-ts-regexp)
13724 ("%U" . ".*?")))))))
13725 (while (looking-at-p regexp)
13726 (goto-char (or (org-list-get-next-item (point) struct prevs)
13727 (org-list-get-item-end (point) struct)))))))
13729 (defun org-add-log-note (&optional _purpose)
13730 "Pop up a window for taking a note, and add this note later."
13731 (remove-hook 'post-command-hook 'org-add-log-note)
13732 (setq org-log-note-window-configuration (current-window-configuration))
13733 (delete-other-windows)
13734 (move-marker org-log-note-return-to (point))
13735 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13736 (goto-char org-log-note-marker)
13737 (org-switch-to-buffer-other-window "*Org Note*")
13739 (if (memq org-log-note-how '(time state))
13740 (let (current-prefix-arg) (org-store-log-note))
13741 (let ((org-inhibit-startup t)) (org-mode))
13742 (insert (format "# Insert note for %s.
13743 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13745 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13746 ((eq org-log-note-purpose 'done) "closed todo item")
13747 ((eq org-log-note-purpose 'state)
13748 (format "state change from \"%s\" to \"%s\""
13749 (or org-log-note-previous-state "")
13750 (or org-log-note-state "")))
13751 ((eq org-log-note-purpose 'reschedule)
13753 ((eq org-log-note-purpose 'delschedule)
13754 "no longer scheduled")
13755 ((eq org-log-note-purpose 'redeadline)
13756 "changing deadline")
13757 ((eq org-log-note-purpose 'deldeadline)
13758 "removing deadline")
13759 ((eq org-log-note-purpose 'refile)
13761 ((eq org-log-note-purpose 'note)
13763 (t (error "This should not happen")))))
13764 (when org-log-note-extra (insert org-log-note-extra))
13765 (setq-local org-finish-function 'org-store-log-note)
13766 (run-hooks 'org-log-buffer-setup-hook)))
13768 (defvar org-note-abort nil) ; dynamically scoped
13769 (defun org-store-log-note ()
13770 "Finish taking a log note, and insert it to where it belongs."
13771 (let ((txt (prog1 (buffer-string)
13773 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13775 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13776 (setq txt (replace-match "" t t txt)))
13777 (when (string-match "\\s-+\\'" txt)
13778 (setq txt (replace-match "" t t txt)))
13779 (setq lines (org-split-string txt "\n"))
13780 (when (org-string-nw-p note)
13782 (org-replace-escapes
13784 (list (cons "%u" (user-login-name))
13785 (cons "%U" user-full-name)
13786 (cons "%t" (format-time-string
13787 (org-time-stamp-format 'long 'inactive)
13788 org-log-note-effective-time))
13789 (cons "%T" (format-time-string
13790 (org-time-stamp-format 'long nil)
13791 org-log-note-effective-time))
13792 (cons "%d" (format-time-string
13793 (org-time-stamp-format nil 'inactive)
13794 org-log-note-effective-time))
13795 (cons "%D" (format-time-string
13796 (org-time-stamp-format nil nil)
13797 org-log-note-effective-time))
13799 ((not org-log-note-state) "")
13800 ((string-match-p org-ts-regexp
13801 org-log-note-state)
13803 (substring org-log-note-state 1 -1)))
13804 (t (format "\"%s\"" org-log-note-state))))
13807 ((not org-log-note-previous-state) "")
13808 ((string-match-p org-ts-regexp
13809 org-log-note-previous-state)
13812 org-log-note-previous-state 1 -1)))
13813 (t (format "\"%s\""
13814 org-log-note-previous-state)))))))
13815 (when lines (setq note (concat note " \\\\")))
13817 (when (and lines (not (or current-prefix-arg org-note-abort)))
13818 (with-current-buffer (marker-buffer org-log-note-marker)
13819 (org-with-wide-buffer
13820 ;; Find location for the new note.
13821 (goto-char org-log-note-marker)
13822 (set-marker org-log-note-marker nil)
13823 (goto-char (org-log-beginning t))
13824 ;; Make sure point is at the beginning of an empty line.
13825 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13826 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13827 ;; In an existing list, add a new item at the top level.
13828 ;; Otherwise, indent line like a regular one.
13829 (let ((itemp (org-in-item-p)))
13832 (let ((struct (save-excursion
13833 (goto-char itemp) (org-list-struct))))
13834 (org-list-get-ind (org-list-get-top-point struct) struct)))
13835 (org-indent-line)))
13836 (insert (org-list-bullet-string "-") (pop lines))
13837 (let ((ind (org-list-item-body-column (line-beginning-position))))
13838 (dolist (line lines)
13840 (indent-line-to ind)
13842 (message "Note stored")
13843 (org-back-to-heading t)
13844 (org-cycle-hide-drawers 'children))
13845 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13846 ;; from within `org-add-log-note' because `buffer-undo-list'
13847 ;; is then modified outside of `org-with-remote-undo'.
13848 (when (eq this-command 'org-agenda-todo)
13849 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13850 ;; Don't add undo information when called from `org-agenda-todo'.
13851 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13852 (set-window-configuration org-log-note-window-configuration)
13853 (with-current-buffer (marker-buffer org-log-note-return-to)
13854 (goto-char org-log-note-return-to))
13855 (move-marker org-log-note-return-to nil)
13856 (when org-log-post-message (message "%s" org-log-post-message))))
13858 (defun org-remove-empty-drawer-at (pos)
13859 "Remove an empty drawer at position POS.
13860 POS may also be a marker."
13861 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13862 (org-with-wide-buffer
13864 (let ((drawer (org-element-at-point)))
13865 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13866 (not (org-element-property :contents-begin drawer)))
13867 (delete-region (org-element-property :begin drawer)
13868 (progn (goto-char (org-element-property :end drawer))
13869 (skip-chars-backward " \r\t\n")
13873 (defvar org-ts-type nil)
13874 (defun org-sparse-tree (&optional arg type)
13875 "Create a sparse tree, prompt for the details.
13876 This command can create sparse trees. You first need to select the type
13877 of match used to create the tree:
13879 t Show all TODO entries.
13880 T Show entries with a specific TODO keyword.
13881 m Show entries selected by a tags/property match.
13882 p Enter a property name and its value (both with completion on existing
13883 names/values) and show entries with that property.
13884 r Show entries matching a regular expression (`/' can be used as well).
13885 b Show deadlines and scheduled items before a date.
13886 a Show deadlines and scheduled items after a date.
13887 d Show deadlines due within `org-deadline-warning-days'.
13888 D Show deadlines and scheduled items between a date range."
13890 (setq type (or type org-sparse-tree-default-date-type))
13891 (setq org-ts-type type)
13892 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13893 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13894 \[c]ycle through date types: %s"
13896 (all "all timestamps")
13897 (scheduled "only scheduled")
13898 (deadline "only deadline")
13899 (active "only active timestamps")
13900 (inactive "only inactive timestamps")
13901 (closed "with a closed time-stamp")
13902 (otherwise "scheduled/deadline")))
13903 (let ((answer (read-char-exclusive)))
13909 (memq type '(nil all scheduled deadline active inactive closed)))))
13910 (?d (call-interactively 'org-check-deadlines))
13911 (?b (call-interactively 'org-check-before-date))
13912 (?a (call-interactively 'org-check-after-date))
13913 (?D (call-interactively 'org-check-dates-range))
13914 (?t (call-interactively 'org-show-todo-tree))
13915 (?T (org-show-todo-tree '(4)))
13916 (?m (call-interactively 'org-match-sparse-tree))
13918 (let* ((kwd (completing-read
13919 "Property: " (mapcar #'list (org-buffer-property-keys))))
13920 (value (completing-read
13921 "Value: " (mapcar #'list (org-property-values kwd)))))
13922 (unless (string-match "\\`{.*}\\'" value)
13923 (setq value (concat "\"" value "\"")))
13924 (org-match-sparse-tree arg (concat kwd "=" value))))
13925 ((?r ?R ?/) (call-interactively 'org-occur))
13926 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13928 (defvar-local org-occur-highlights nil
13929 "List of overlays used for occur matches.")
13930 (defvar-local org-occur-parameters nil
13931 "Parameters of the active org-occur calls.
13932 This is a list, each call to org-occur pushes as cons cell,
13933 containing the regular expression and the callback, onto the list.
13934 The list can contain several entries if `org-occur' has been called
13935 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13936 will only contain one set of parameters. When the highlights are
13937 removed (for example with `C-c C-c', or with the next edit (depending
13938 on `org-remove-highlights-with-change'), this variable is emptied
13941 (defun org-occur (regexp &optional keep-previous callback)
13942 "Make a compact tree which shows all matches of REGEXP.
13944 The tree will show the lines where the regexp matches, and any other context
13945 defined in `org-show-context-detail', which see.
13947 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13948 done by a previous call to `org-occur' will be kept, to allow stacking of
13949 calls to this command.
13951 Optional argument CALLBACK can be a function of no argument. In this case,
13952 it is called with point at the end of the match, match data being set
13953 accordingly. Current match is shown only if the return value is non-nil.
13954 The function must neither move point nor alter narrowing."
13955 (interactive "sRegexp: \nP")
13956 (when (equal regexp "")
13957 (user-error "Regexp cannot be empty"))
13958 (unless keep-previous
13959 (org-remove-occur-highlights nil nil t))
13960 (push (cons regexp callback) org-occur-parameters)
13963 (goto-char (point-min))
13964 (when (or (not keep-previous) ; do not want to keep
13965 (not org-occur-highlights)) ; no previous matches
13968 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13969 (isearch-no-upper-case-p regexp t)
13970 org-occur-case-fold-search)))
13971 (while (re-search-forward regexp nil t)
13972 (when (or (not callback)
13973 (save-match-data (funcall callback)))
13974 (setq cnt (1+ cnt))
13975 (when org-highlight-sparse-tree-matches
13976 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13977 (org-show-context 'occur-tree)))))
13978 (when org-remove-highlights-with-change
13979 (add-hook 'before-change-functions 'org-remove-occur-highlights
13981 (unless org-sparse-tree-open-archived-trees
13982 (org-hide-archived-subtrees (point-min) (point-max)))
13983 (run-hooks 'org-occur-hook)
13984 (when (called-interactively-p 'interactive)
13985 (message "%d match(es) for regexp %s" cnt regexp))
13988 (defun org-occur-next-match (&optional n _reset)
13989 "Function for `next-error-function' to find sparse tree matches.
13990 N is the number of matches to move, when negative move backwards.
13991 This function always goes back to the starting point when no
13993 (let* ((limit (if (< n 0) (point-min) (point-max)))
13994 (search-func (if (< n 0)
13995 'previous-single-char-property-change
13996 'next-single-char-property-change))
14001 (while (setq p1 (funcall search-func (point) 'org-type))
14002 (when (equal p1 limit)
14004 (user-error "No more matches"))
14005 (when (equal (get-char-property p1 'org-type) 'org-occur)
14009 (throw 'exit (point))))
14012 (user-error "No more matches"))))
14014 (defun org-show-context (&optional key)
14015 "Make sure point and context are visible.
14016 Optional argument KEY, when non-nil, is a symbol. See
14017 `org-show-context-detail' for allowed values and how much is to
14019 (org-show-set-visibility
14020 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14021 ((cdr (assq key org-show-context-detail)))
14022 (t (cdr (assq 'default org-show-context-detail))))))
14024 (defun org-show-set-visibility (detail)
14025 "Set visibility around point according to DETAIL.
14026 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14027 `tree', `canonical' or t. See `org-show-context-detail' for more
14029 ;; Show current heading and possibly its entry, following headline
14030 ;; or all children.
14031 (if (and (org-at-heading-p) (not (eq detail 'local)))
14032 (org-flag-heading nil)
14034 ;; If point is hidden within a drawer or a block, make sure to
14036 (dolist (o (overlays-at (point)))
14037 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14038 (delete-overlay o)))
14039 (unless (org-before-first-heading-p)
14040 (org-with-limited-levels
14042 ((tree canonical t) (org-show-children))
14043 ((nil minimal ancestors))
14045 (outline-next-heading)
14046 (org-flag-heading nil)))))))
14047 ;; Show all siblings.
14048 (when (eq detail 'lineage) (org-show-siblings))
14049 ;; Show ancestors, possibly with their children.
14050 (when (memq detail '(ancestors lineage tree canonical t))
14052 (while (org-up-heading-safe)
14053 (org-flag-heading nil)
14054 (when (memq detail '(canonical t)) (org-show-entry))
14055 (when (memq detail '(tree canonical t)) (org-show-children))))))
14057 (defvar org-reveal-start-hook nil
14058 "Hook run before revealing a location.")
14060 (defun org-reveal (&optional siblings)
14061 "Show current entry, hierarchy above it, and the following headline.
14063 This can be used to show a consistent set of context around
14064 locations exposed with `org-show-context'.
14066 With optional argument SIBLINGS, on each level of the hierarchy all
14067 siblings are shown. This repairs the tree structure to what it would
14068 look like when opened with hierarchical calls to `org-cycle'.
14070 With a \\[universal-argument] \\[universal-argument] prefix, \
14071 go to the parent and show the entire tree."
14073 (run-hooks 'org-reveal-start-hook)
14074 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14075 ((equal siblings '(16))
14077 (when (org-up-heading-safe)
14079 (run-hook-with-args 'org-cycle-hook 'subtree))))
14080 (t (org-show-set-visibility 'lineage))))
14082 (defun org-highlight-new-match (beg end)
14083 "Highlight from BEG to END and mark the highlight is an occur headline."
14084 (let ((ov (make-overlay beg end)))
14085 (overlay-put ov 'face 'secondary-selection)
14086 (overlay-put ov 'org-type 'org-occur)
14087 (push ov org-occur-highlights)))
14089 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14090 "Remove the occur highlights from the buffer.
14091 BEG and END are ignored. If NOREMOVE is nil, remove this function
14092 from the `before-change-functions' in the current buffer."
14094 (unless org-inhibit-highlight-removal
14095 (mapc #'delete-overlay org-occur-highlights)
14096 (setq org-occur-highlights nil)
14097 (setq org-occur-parameters nil)
14099 (remove-hook 'before-change-functions
14100 'org-remove-occur-highlights 'local))))
14104 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14105 "Regular expression matching the priority indicator.")
14107 (defvar org-remove-priority-next-time nil)
14109 (defun org-priority-up ()
14110 "Increase the priority of the current item."
14112 (org-priority 'up))
14114 (defun org-priority-down ()
14115 "Decrease the priority of the current item."
14117 (org-priority 'down))
14119 (defun org-priority (&optional action _show)
14120 "Change the priority of an item.
14121 ACTION can be `set', `up', `down', or a character."
14123 (if (equal action '(4))
14124 (org-show-priority)
14125 (unless org-enable-priority-commands
14126 (user-error "Priority commands are disabled"))
14127 (setq action (or action 'set))
14128 (let (current new news have remove)
14130 (org-back-to-heading t)
14131 (when (looking-at org-priority-regexp)
14132 (setq current (string-to-char (match-string 2))
14135 ((eq action 'remove)
14136 (setq remove t new ?\ ))
14137 ((or (eq action 'set)
14139 (if (not (eq action 'set))
14141 (message "Priority %c-%c, SPC to remove: "
14142 org-highest-priority org-lowest-priority)
14144 (setq new (read-char-exclusive))))
14145 (when (and (= (upcase org-highest-priority) org-highest-priority)
14146 (= (upcase org-lowest-priority) org-lowest-priority))
14147 (setq new (upcase new)))
14148 (cond ((equal new ?\ ) (setq remove t))
14149 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14150 (user-error "Priority must be between `%c' and `%c'"
14151 org-highest-priority org-lowest-priority))))
14154 (1- current) ; normal cycling
14155 ;; last priority was empty
14156 (if (eq last-command this-command)
14157 org-lowest-priority ; wrap around empty to lowest
14159 (if org-priority-start-cycle-with-default
14160 org-default-priority
14161 (1- org-default-priority))))))
14164 (1+ current) ; normal cycling
14165 ;; last priority was empty
14166 (if (eq last-command this-command)
14167 org-highest-priority ; wrap around empty to highest
14169 (if org-priority-start-cycle-with-default
14170 org-default-priority
14171 (1+ org-default-priority))))))
14172 (t (user-error "Invalid action")))
14173 (when (or (< (upcase new) org-highest-priority)
14174 (> (upcase new) org-lowest-priority))
14175 (if (and (memq action '(up down))
14176 (not have) (not (eq last-command this-command)))
14177 ;; `new' is from default priority
14179 "The default can not be set, see `org-default-priority' why")
14180 ;; normal cycling: `new' is beyond highest/lowest priority
14181 ;; and is wrapped around to the empty priority
14183 (setq news (format "%c" new))
14186 (replace-match "" t t nil 1)
14187 (replace-match news t t nil 2))
14189 (user-error "No priority cookie found in line")
14190 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14193 (goto-char (match-end 2))
14194 (insert " [#" news "]"))
14195 (goto-char (match-beginning 3))
14196 (insert "[#" news "] "))))
14197 (org-set-tags nil 'align))
14199 (message "Priority removed")
14200 (message "Priority of current item set to %s" news)))))
14202 (defun org-show-priority ()
14203 "Show the priority of the current item.
14204 This priority is composed of the main priority given with the [#A] cookies,
14205 and by additional input from the age of a schedules or deadline entry."
14207 (let ((pri (if (eq major-mode 'org-agenda-mode)
14208 (org-get-at-bol 'priority)
14211 (beginning-of-line)
14212 (and (looking-at org-heading-regexp)
14213 (org-get-priority (match-string 0))))))))
14214 (message "Priority is %d" (if pri pri -1000))))
14216 (defun org-get-priority (s)
14217 "Find priority cookie and return priority."
14219 (if (functionp org-get-priority-function)
14220 (funcall org-get-priority-function)
14221 (if (not (string-match org-priority-regexp s))
14222 (* 1000 (- org-lowest-priority org-default-priority))
14223 (* 1000 (- org-lowest-priority
14224 (string-to-char (match-string 2 s))))))))
14228 (defvar org-agenda-archives-mode)
14229 (defvar org-map-continue-from nil
14230 "Position from where mapping should continue.
14231 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14233 (defvar org-scanner-tags nil
14234 "The current tag list while the tags scanner is running.")
14236 (defvar org-trust-scanner-tags nil
14237 "Should `org-get-tags-at' use the tags for the scanner.
14238 This is for internal dynamical scoping only.
14239 When this is non-nil, the function `org-get-tags-at' will return the value
14240 of `org-scanner-tags' instead of building the list by itself. This
14241 can lead to large speed-ups when the tags scanner is used in a file with
14242 many entries, and when the list of tags is retrieved, for example to
14243 obtain a list of properties. Building the tags list for each entry in such
14244 a file becomes an N^2 operation - but with this variable set, it scales
14247 (defvar org--matcher-tags-todo-only nil)
14249 (defun org-scan-tags (action matcher todo-only &optional start-level)
14250 "Scan headline tags with inheritance and produce output ACTION.
14252 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14253 or `agenda' to produce an entry list for an agenda view. It can also be
14254 a Lisp form or a function that should be called at each matched headline, in
14255 this case the return value is a list of all return values from these calls.
14257 MATCHER is a function accepting three arguments, returning
14258 a non-nil value whenever a given set of tags qualifies a headline
14259 for inclusion. See `org-make-tags-matcher' for more information.
14260 As a special case, it can also be set to t (respectively nil) in
14261 order to match all (respectively none) headline.
14263 When TODO-ONLY is non-nil, only lines with a not-done TODO
14264 keyword are included in the output.
14266 START-LEVEL can be a string with asterisks, reducing the scope to
14267 headlines matching this string."
14268 (require 'org-agenda)
14269 (let* ((re (concat "^"
14271 ;; Get the correct level to match
14272 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14273 org-outline-regexp)
14275 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14276 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14277 (props (list 'face 'default
14278 'done-face 'org-agenda-done
14279 'undone-face 'default
14280 'mouse-face 'highlight
14281 'org-not-done-regexp org-not-done-regexp
14282 'org-todo-regexp org-todo-regexp
14283 'org-complex-heading-regexp org-complex-heading-regexp
14285 (format "mouse-2 or RET jump to org file %s"
14286 (abbreviate-file-name
14287 (or (buffer-file-name (buffer-base-buffer))
14288 (buffer-name (buffer-base-buffer)))))))
14289 (org-map-continue-from nil)
14290 lspos tags tags-list
14291 (tags-alist (list (cons 0 org-file-tags)))
14292 (llast 0) rtn rtn1 level category i txt
14293 todo marker entry priority
14294 ts-date ts-date-type ts-date-pair)
14295 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14296 (setq action (list 'lambda nil action)))
14298 (goto-char (point-min))
14299 (when (eq action 'sparse-tree)
14301 (org-remove-occur-highlights))
14302 (while (let (case-fold-search)
14303 (re-search-forward re nil t))
14304 (setq org-map-continue-from nil)
14307 ;; TODO: is the 1-2 difference a bug?
14308 (when (match-end 1) (match-string-no-properties 2))
14309 tags (when (match-end 4) (match-string-no-properties 4)))
14310 (goto-char (setq lspos (match-beginning 0)))
14311 (setq level (org-reduced-level (org-outline-level))
14312 category (org-get-category))
14313 (when (eq action 'agenda)
14314 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14315 ts-date (car ts-date-pair)
14316 ts-date-type (cdr ts-date-pair)))
14317 (setq i llast llast level)
14318 ;; remove tag lists from same and sublevels
14319 (while (>= i level)
14320 (when (setq entry (assoc i tags-alist))
14321 (setq tags-alist (delete entry tags-alist)))
14323 ;; add the next tags
14325 (setq tags (org-split-string tags ":")
14327 (cons (cons level tags) tags-alist)))
14328 ;; compile tags for current headline
14330 (if org-use-tag-inheritance
14331 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14333 org-scanner-tags tags-list)
14334 (when org-use-tag-inheritance
14335 (setcdr (car tags-alist)
14336 (mapcar (lambda (x)
14337 (setq x (copy-sequence x))
14338 (org-add-prop-inherited x))
14339 (cdar tags-alist))))
14340 (when (and tags org-use-tag-inheritance
14341 (or (not (eq t org-use-tag-inheritance))
14342 org-tags-exclude-from-inheritance))
14343 ;; Selective inheritance, remove uninherited ones.
14344 (setcdr (car tags-alist)
14345 (org-remove-uninherited-tags (cdar tags-alist))))
14348 ;; eval matcher only when the todo condition is OK
14349 (and (or (not todo-only) (member todo org-not-done-keywords))
14350 (if (functionp matcher)
14351 (let ((case-fold-search t) (org-trust-scanner-tags t))
14352 (funcall matcher todo tags-list level))
14355 ;; Call the skipper, but return t if it does not
14356 ;; skip, so that the `and' form continues evaluating.
14358 (unless (eq action 'sparse-tree) (org-agenda-skip))
14361 ;; Check if timestamps are deselecting this entry
14362 (or (not todo-only)
14363 (and (member todo org-not-done-keywords)
14364 (or (not org-agenda-tags-todo-honor-ignore-options)
14365 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14367 ;; select this headline
14369 ((eq action 'sparse-tree)
14370 (and org-highlight-sparse-tree-matches
14371 (org-get-heading) (match-end 0)
14372 (org-highlight-new-match
14373 (match-beginning 1) (match-end 1)))
14374 (org-show-context 'tags-tree))
14375 ((eq action 'agenda)
14376 (setq txt (org-agenda-format-item
14379 (if (eq org-tags-match-list-sublevels 'indented)
14380 (make-string (1- level) ?.) "")
14382 (make-string level ?\s)
14385 priority (org-get-priority txt))
14387 (setq marker (org-agenda-new-marker))
14388 (org-add-props txt props
14389 'org-marker marker 'org-hd-marker marker 'org-category category
14393 'type (concat "tagsmatch" ts-date-type))
14395 ((functionp action)
14396 (setq org-map-continue-from nil)
14398 (setq rtn1 (funcall action))
14400 (t (user-error "Invalid action")))
14402 ;; if we are to skip sublevels, jump to end of subtree
14403 (unless org-tags-match-list-sublevels
14404 (org-end-of-subtree t)
14405 (backward-char 1))))
14406 ;; Get the correct position from where to continue
14407 (if org-map-continue-from
14408 (goto-char org-map-continue-from)
14409 (and (= (point) lspos) (end-of-line 1)))))
14410 (when (and (eq action 'sparse-tree)
14411 (not org-sparse-tree-open-archived-trees))
14412 (org-hide-archived-subtrees (point-min) (point-max)))
14415 (defun org-remove-uninherited-tags (tags)
14416 "Remove all tags that are not inherited from the list TAGS."
14418 ((eq org-use-tag-inheritance t)
14419 (if org-tags-exclude-from-inheritance
14420 (org-delete-all org-tags-exclude-from-inheritance tags)
14422 ((not org-use-tag-inheritance) nil)
14423 ((stringp org-use-tag-inheritance)
14426 (if (and (string-match org-use-tag-inheritance x)
14427 (not (member x org-tags-exclude-from-inheritance)))
14430 ((listp org-use-tag-inheritance)
14433 (if (member x org-use-tag-inheritance) x nil))
14436 (defun org-match-sparse-tree (&optional todo-only match)
14437 "Create a sparse tree according to tags string MATCH.
14439 MATCH is a string with match syntax. It can contain a selection
14440 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14441 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14442 those. See the manual for details.
14444 If optional argument TODO-ONLY is non-nil, only select lines that
14445 are also TODO tasks."
14447 (org-agenda-prepare-buffers (list (current-buffer)))
14448 (let ((org--matcher-tags-todo-only todo-only))
14449 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14450 org--matcher-tags-todo-only)))
14452 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14454 (defvar org-cached-props nil)
14455 (defun org-cached-entry-get (pom property)
14456 (if (or (eq t org-use-property-inheritance)
14457 (and (stringp org-use-property-inheritance)
14458 (let ((case-fold-search t))
14459 (string-match-p org-use-property-inheritance property)))
14460 (and (listp org-use-property-inheritance)
14461 (member-ignore-case property org-use-property-inheritance)))
14462 ;; Caching is not possible, check it directly.
14463 (org-entry-get pom property 'inherit)
14464 ;; Get all properties, so we can do complicated checks easily.
14465 (cdr (assoc-string property
14466 (or org-cached-props
14467 (setq org-cached-props (org-entry-properties pom)))
14470 (defun org-global-tags-completion-table (&optional files)
14471 "Return the list of all tags in all agenda buffer/files.
14472 Optional FILES argument is a list of files which can be used
14473 instead of the agenda files."
14480 (set-buffer (find-file-noselect file))
14481 (mapcar (lambda (x)
14482 (and (stringp (car-safe x))
14483 (list (car-safe x))))
14484 (or org-current-tag-alist (org-get-buffer-tags))))
14485 (if (car-safe files) files
14486 (org-agenda-files))))))))
14488 (defun org-make-tags-matcher (match)
14489 "Create the TAGS/TODO matcher form for the selection string MATCH.
14491 Returns a cons of the selection string MATCH and a function
14492 implementing the matcher.
14494 The matcher is to be called at an Org entry, with point on the
14495 headline, and returns non-nil if the entry matches the selection
14496 string MATCH. It must be called with three arguments: the TODO
14497 keyword at the entry (or nil if none), the list of all tags at
14498 the entry including inherited ones and the reduced level of the
14499 headline. Additionally, the category of the entry, if any, must
14500 be specified as the text property `org-category' on the headline.
14502 This function sets the variable `org--matcher-tags-todo-only' to
14503 a non-nil value if the matcher restricts matching to TODO
14504 entries, otherwise it is not touched.
14506 See also `org-scan-tags'."
14508 ;; Get a new match request, with completion against the global
14509 ;; tags table and the local tags in current buffer.
14510 (let ((org-last-tags-completion-table
14512 (delq nil (append (org-get-buffer-tags)
14513 (org-global-tags-completion-table))))))
14517 'org-tags-completion-function nil nil nil 'org-tags-history))))
14519 (let ((match0 match)
14520 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14522 tagsmatch todomatch tagsmatcher todomatcher)
14524 ;; Expand group tags.
14525 (setq match (org-tags-expand match))
14527 ;; Check if there is a TODO part of this match, which would be the
14528 ;; part after a "/". To make sure that this slash is not part of
14529 ;; a property value to be matched against, we also check that
14530 ;; there is no / after that slash. First, find the last slash.
14532 (while (string-match "/+" match s)
14533 (setq start (match-beginning 0))
14534 (setq s (match-end 0))))
14535 (if (and (string-match "/+" match start)
14536 (not (string-match-p "\"" match start)))
14537 ;; Match contains also a TODO-matching request.
14539 (setq tagsmatch (substring match 0 (match-beginning 0)))
14540 (setq todomatch (substring match (match-end 0)))
14541 (when (string-prefix-p "!" todomatch)
14542 (setq org--matcher-tags-todo-only t)
14543 (setq todomatch (substring todomatch 1)))
14544 (when (string-match "\\`\\s-*\\'" todomatch)
14545 (setq todomatch nil)))
14546 ;; Only matching tags.
14547 (setq tagsmatch match)
14548 (setq todomatch nil))
14550 ;; Make the tags matcher.
14551 (when (org-string-nw-p tagsmatch)
14553 (orterms (org-split-string tagsmatch "|"))
14555 (while (setq term (pop orterms))
14556 (while (and (equal (substring term -1) "\\") orterms)
14557 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14558 (while (string-match re term)
14559 (let* ((rest (substring term (match-end 0)))
14560 (minus (and (match-end 1)
14561 (equal (match-string 1 term) "-")))
14562 (tag (save-match-data
14563 (replace-regexp-in-string
14564 "\\\\-" "-" (match-string 2 term))))
14565 (regexp (eq (string-to-char tag) ?{))
14566 (levelp (match-end 4))
14567 (propp (match-end 5))
14570 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14572 `(,(org-op-to-function (match-string 3 term))
14574 ,(string-to-number (match-string 4 term))))
14576 (let* ((gv (pcase (upcase (match-string 5 term))
14578 '(get-text-property (point) 'org-category))
14580 (p `(org-cached-entry-get nil ,p))))
14581 (pv (match-string 7 term))
14582 (regexp (eq (string-to-char pv) ?{))
14583 (strp (eq (string-to-char pv) ?\"))
14584 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14585 (po (org-op-to-function (match-string 6 term)
14586 (if timep 'time strp))))
14587 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14588 (when timep (setq pv (org-matcher-time pv)))
14589 (cond ((and regexp (eq po 'org<>))
14590 `(not (string-match ,pv (or ,gv ""))))
14591 (regexp `(string-match ,pv (or ,gv "")))
14592 (strp `(,po (or ,gv "") ,pv))
14595 (string-to-number (or ,gv ""))
14596 ,(string-to-number pv))))))
14597 (t `(member ,tag tags-list)))))
14598 (push (if minus `(not ,mm) mm) tagsmatcher)
14600 (push `(and ,@tagsmatcher) orlist)
14601 (setq tagsmatcher nil))
14602 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14604 ;; Make the TODO matcher.
14605 (when (org-string-nw-p todomatch)
14606 (let ((orlist nil))
14607 (dolist (term (org-split-string todomatch "|"))
14608 (while (string-match re term)
14609 (let* ((minus (and (match-end 1)
14610 (equal (match-string 1 term) "-")))
14611 (kwd (match-string 2 term))
14612 (regexp (eq (string-to-char kwd) ?{))
14613 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14614 `(equal todo ,kwd))))
14615 (push (if minus `(not ,mm) mm) todomatcher))
14616 (setq term (substring term (match-end 0))))
14617 (push (if (> (length todomatcher) 1)
14618 (cons 'and todomatcher)
14621 (setq todomatcher nil))
14622 (setq todomatcher (cons 'or orlist))))
14624 ;; Return the string and function of the matcher. If no
14625 ;; tags-specific or todo-specific matcher exists, match
14627 (let ((matcher (if (and tagsmatcher todomatcher)
14628 `(and ,tagsmatcher ,todomatcher)
14629 (or tagsmatcher todomatcher t))))
14630 (when org--matcher-tags-todo-only
14631 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14632 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14634 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14635 "Expand group tags in MATCH.
14637 This replaces every group tag in MATCH with a regexp tag search.
14638 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14639 will be replaced like this:
14641 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14642 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14643 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14645 Replacing by a regexp preserves the structure of the match.
14646 E.g., this expansion
14648 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14650 will match anything tagged with \"Lab\" and \"Home\", or tagged
14651 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14653 A group tag in MATCH can contain regular expressions of its own.
14654 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14655 will be replaced like this:
14657 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14659 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14660 assumed to be a single group tag, and the function will return
14661 the list of tags in this group.
14663 When DOWNCASE is non-nil, expand downcased TAGS."
14665 (let* ((case-fold-search t)
14666 (stable org-mode-syntax-table)
14667 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14668 (taggroups (if downcased
14669 (mapcar (lambda (tg) (mapcar #'downcase tg))
14672 (taggroups-keys (mapcar #'car taggroups))
14673 (return-match (if downcased (downcase match) match))
14675 (work-already-expanded tags-already-expanded)
14676 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14677 ;; @ and _ are allowed as word-components in tags.
14678 (modify-syntax-entry ?@ "w" stable)
14679 (modify-syntax-entry ?_ "w" stable)
14680 ;; Temporarily replace regexp-expressions in the match-expression.
14681 (while (string-match "{.+?}" return-match)
14683 (push (match-string 0 return-match) regexps-in-match)
14684 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14685 (while (and taggroups-keys
14686 (with-syntax-table stable
14688 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14689 (regexp-opt taggroups-keys) "\\>\\)")
14691 (let* ((dir (match-string 1 return-match))
14692 (tag (match-string 2 return-match))
14693 (tag (if downcased (downcase tag) tag)))
14694 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14695 (member tag work-already-expanded))
14696 (setq tags-in-group (assoc tag taggroups))
14697 (push tag work-already-expanded)
14698 ;; Recursively expand each tag in the group, if the tag hasn't
14699 ;; already been expanded. Restore the match-data after all recursive calls.
14701 (let (tags-expanded)
14702 (dolist (x (cdr tags-in-group))
14703 (if (and (member x taggroups-keys)
14704 (not (member x work-already-expanded)))
14705 (setq tags-expanded
14708 (org-tags-expand x t downcased
14709 work-already-expanded)
14711 (setq tags-expanded
14712 (append (list x) tags-expanded)))
14713 (setq work-already-expanded
14715 (append tags-expanded
14716 work-already-expanded))))
14717 (setq tags-in-group
14718 (delete-dups (cons (car tags-in-group)
14720 ;; Filter tag-regexps from tags.
14721 (setq regexp-in-group-escaped
14722 (delq nil (mapcar (lambda (x)
14724 (and (equal "{" (substring x 0 1))
14725 (equal "}" (substring x -1))
14730 (mapcar (lambda (x)
14731 (substring x 1 -1))
14732 regexp-in-group-escaped)
14734 (delq nil (mapcar (lambda (x)
14736 (and (not (equal "{" (substring x 0 1)))
14737 (not (equal "}" (substring x -1)))
14741 ;; If single-as-list, do no more in the while-loop.
14742 (if (not single-as-list)
14744 (when regexp-in-group
14745 (setq regexp-in-group
14747 (mapconcat 'identity regexp-in-group
14749 (setq tags-in-group
14752 (regexp-opt tags-in-group)
14756 (when (stringp tags-in-group)
14757 (org-add-props tags-in-group '(grouptag t)))
14759 (replace-match tags-in-group t t return-match)))
14760 (setq tags-in-group
14761 (append regexp-in-group-escaped tags-in-group))))
14762 (setq taggroups-keys (delete tag taggroups-keys))))
14763 ;; Add the regular expressions back into the match-expression again.
14764 (while regexps-in-match
14765 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14766 (pop regexps-in-match)
14770 (if tags-in-group tags-in-group (list return-match))
14773 (list (if downcased (downcase match) match))
14776 (defun org-op-to-function (op &optional stringp)
14777 "Turn an operator into the appropriate function."
14780 ((equal op "<" ) '(< string< org-time<))
14781 ((equal op ">" ) '(> org-string> org-time>))
14782 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14783 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14784 ((member op '("=" "==")) '(= string= org-time=))
14785 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14786 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14788 (defun org<> (a b) (not (= a b)))
14789 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14790 (defun org-string>= (a b) (not (string< a b)))
14791 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14792 (defun org-string<> (a b) (not (string= a b)))
14793 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14794 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14795 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14796 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14797 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14798 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14800 "Convert S to a floating point time.
14801 If S is already a number, just return it. If it is a string, parse
14802 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14806 (condition-case nil
14807 (float-time (apply 'encode-time (org-parse-time-string s)))
14811 (defun org-time-today ()
14812 "Time in seconds today at 0:00.
14813 Returns the float number of seconds since the beginning of the
14814 epoch to the beginning of today (00:00)."
14815 (float-time (apply 'encode-time
14816 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14818 (defun org-matcher-time (s)
14819 "Interpret a time comparison value."
14822 ((string= s "<now>") (float-time))
14823 ((string= s "<today>") (org-time-today))
14824 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14825 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14826 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14827 (+ (org-time-today)
14828 (* (string-to-number (match-string 1 s))
14829 (cdr (assoc (match-string 2 s)
14830 '(("d" . 86400.0) ("w" . 604800.0)
14831 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14834 (defun org-match-any-p (re list)
14835 "Does re match any element of list?"
14836 (setq list (mapcar (lambda (x) (string-match re x)) list))
14839 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14840 (defvar org-tags-overlay (make-overlay 1 1))
14841 (delete-overlay org-tags-overlay)
14843 (defun org-get-local-tags-at (&optional pos)
14844 "Get a list of tags defined in the current headline."
14845 (org-get-tags-at pos 'local))
14847 (defun org-get-local-tags ()
14848 "Get a list of tags defined in the current headline."
14849 (org-get-tags-at nil 'local))
14851 (defun org-get-tags-at (&optional pos local)
14852 "Get a list of all headline tags applicable at POS.
14853 POS defaults to point. If tags are inherited, the list contains
14854 the targets in the same sequence as the headlines appear, i.e.
14855 the tags of the current headline come last.
14856 When LOCAL is non-nil, only return tags from the current headline,
14857 ignore inherited ones."
14859 (if (and org-trust-scanner-tags
14860 (or (not pos) (equal pos (point)))
14863 (let (tags ltags lastpos parent)
14867 (goto-char (or pos (point)))
14870 (condition-case nil
14872 (org-back-to-heading t)
14873 (while (not (equal lastpos (point)))
14874 (setq lastpos (point))
14875 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14876 (setq ltags (org-split-string
14877 (match-string-no-properties 1) ":"))
14879 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14882 (org-remove-uninherited-tags ltags)
14885 (or org-use-tag-inheritance (throw 'done t))
14886 (when local (throw 'done t))
14887 (or (org-up-heading-safe) (error nil))
14892 (reverse (delete-dups
14894 (org-remove-uninherited-tags
14898 (defun org-add-prop-inherited (s)
14899 (add-text-properties 0 (length s) '(inherited t) s)
14902 (defun org-toggle-tag (tag &optional onoff)
14903 "Toggle the tag TAG for the current line.
14904 If ONOFF is `on' or `off', don't toggle but set to this state."
14907 (org-back-to-heading t)
14908 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14911 (setq current (match-string 1))
14912 (replace-match ""))
14914 (setq current (nreverse (org-split-string current ":")))
14918 (or (member tag current) (push tag current)))
14920 (or (not (member tag current)) (setq current (delete tag current))))
14921 (t (if (member tag current)
14922 (setq current (delete tag current))
14924 (push tag current))))
14928 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14929 (org-set-tags nil t))
14930 (delete-horizontal-space))
14931 (run-hooks 'org-after-tags-change-hook))
14934 (defun org--align-tags-here (to-col)
14935 "Align tags on the current headline to TO-COL.
14936 Assume point is on a headline."
14937 (let ((pos (point)))
14938 (beginning-of-line)
14939 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14940 (>= pos (match-beginning 2)))
14941 ;; No tags or point within tags: do not align.
14943 (goto-char (match-beginning 1))
14944 (let ((shift (max (- (if (>= to-col 0) to-col
14945 (- (abs to-col) (string-width (match-string 2))))
14948 (replace-match (make-string shift ?\s) nil nil nil 1)
14949 ;; Preserve initial position, if possible. In any case, stop
14951 (when (< pos (point)) (goto-char pos))))))
14953 (defun org-set-tags-command (&optional arg just-align)
14954 "Call the set-tags command for the current entry."
14956 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14957 (org-set-tags arg just-align)
14959 (unless (and (org-region-active-p)
14960 org-loop-over-headlines-in-active-region)
14961 (org-back-to-heading t))
14962 (org-set-tags arg just-align))))
14964 (defun org-set-tags-to (data)
14965 "Set the tags of the current entry to DATA, replacing the current tags.
14966 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14967 If DATA is nil or the empty string, any tags will be removed."
14968 (interactive "sTags: ")
14972 ((equal data "") "")
14974 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14977 (concat ":" (mapconcat 'identity data ":") ":"))))
14980 (org-back-to-heading t)
14981 (when (let ((case-fold-search nil))
14982 (looking-at org-complex-heading-regexp))
14985 (goto-char (match-beginning 5))
14987 (delete-region (point) (point-at-eol))
14988 (org-set-tags nil 'align))
14989 (goto-char (point-at-eol))
14991 (org-set-tags nil 'align)))
14992 (beginning-of-line 1)
14993 (when (looking-at ".*?\\([ \t]+\\)$")
14994 (delete-region (match-beginning 1) (match-end 1))))))
14996 (defun org-align-all-tags ()
14997 "Align the tags in all headings."
15000 (or (ignore-errors (org-back-to-heading t))
15001 (outline-next-heading))
15002 (if (org-at-heading-p)
15004 (message "No headings"))))
15006 (defvar org-indent-indentation-per-level)
15007 (defun org-set-tags (&optional arg just-align)
15008 "Set the tags for the current headline.
15009 With prefix ARG, realign all tags in headings in the current buffer.
15010 When JUST-ALIGN is non-nil, only align tags."
15012 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15013 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15014 'region-start-level
15016 org-loop-over-headlines-in-active-region)
15018 ;; We don't use ARG and JUST-ALIGN here because these args
15019 ;; are not useful when looping over headlines.
15021 org-loop-over-headlines-in-active-region
15023 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15024 (let ((org-setting-tags t))
15027 (goto-char (point-min))
15028 (while (re-search-forward org-outline-regexp-bol nil t)
15029 (org-set-tags nil t)
15031 (message "All tags realigned to column %d" org-tags-column))
15032 (let* ((current (org-get-tags-string))
15034 (if just-align current
15035 ;; Get a new set of tags from the user.
15040 org-last-tags-completion-table
15041 ;; Uniquify tags in alists, yet preserve
15042 ;; structure (i.e., keywords).
15046 (let ((head (car pair)))
15047 (cond ((symbolp head) pair)
15048 ((member head seen) nil)
15049 (t (push head seen)
15052 (or org-current-tag-alist
15053 (org-get-buffer-tags))
15055 org-complete-tags-always-offer-all-agenda-tags
15056 (org-global-tags-completion-table
15057 (org-agenda-files))))))))
15058 (current-tags (org-split-string current ":"))
15060 (nreverse (nthcdr (length current-tags)
15061 (nreverse (org-get-tags-at))))))
15062 (replace-regexp-in-string
15065 (if (or (eq t org-use-fast-tag-selection)
15066 (and org-use-fast-tag-selection
15067 (delq nil (mapcar #'cdr table))))
15068 (org-fast-tag-selection
15069 current-tags inherited-tags table
15070 (and org-fast-tag-selection-include-todo
15071 org-todo-key-alist))
15072 (let ((org-add-colon-after-tag-completion
15073 (< 1 (length table))))
15077 #'org-tags-completion-function
15078 nil nil current 'org-tags-history))))))))))
15080 (when org-tags-sort-function
15084 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15085 org-tags-sort-function)
15088 (if (not (org-string-nw-p tags)) (setq tags "")
15089 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15090 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15092 ;; Insert new tags at the correct column.
15093 (unless (equal current tags)
15095 (beginning-of-line)
15096 (let ((case-fold-search nil))
15097 (looking-at org-complex-heading-regexp))
15098 ;; Remove current tags, if any.
15099 (when (match-end 5) (replace-match "" nil nil nil 5))
15100 ;; Insert new tags, if any. Otherwise, remove trailing
15103 (if (not (equal tags ""))
15104 ;; When text is being inserted on an invisible
15105 ;; region boundary, it can be inadvertently sucked
15106 ;; into invisibility.
15107 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
15108 (skip-chars-backward " \t")
15109 (delete-region (point) (line-end-position)))))
15110 ;; Align tags, if any. Fix tags column if `org-indent-mode'
15112 (unless (equal tags "")
15113 (let* ((level (save-excursion
15114 (beginning-of-line)
15115 (skip-chars-forward "\\*")))
15116 (offset (if (bound-and-true-p org-indent-mode)
15117 (* (1- org-indent-indentation-per-level)
15122 (if (> org-tags-column 0) (- offset) offset))))
15123 (org--align-tags-here tags-column))))
15124 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15126 (defun org-change-tag-in-region (beg end tag off)
15127 "Add or remove TAG for each entry in the region.
15128 This works in the agenda, and also in an Org buffer."
15130 (list (region-beginning) (region-end)
15131 (let ((org-last-tags-completion-table
15132 (if (derived-mode-p 'org-mode)
15134 (delq nil (append (org-get-buffer-tags)
15135 (org-global-tags-completion-table))))
15136 (org-global-tags-completion-table))))
15138 "Tag: " 'org-tags-completion-function nil nil nil
15139 'org-tags-history))
15141 (message "[s]et or
[r]emove? ")
15142 (equal (read-char-exclusive) ?r))))
15143 (when (fboundp 'deactivate-mark) (deactivate-mark))
15144 (let ((agendap (equal major-mode 'org-agenda-mode))
15145 l1 l2 m buf pos newhead (cnt 0))
15147 (setq l2 (1- (org-current-line)))
15149 (setq l1 (org-current-line))
15150 (cl-loop for l from l1 to l2 do
15152 (setq m (get-text-property (point) 'org-hd-marker))
15153 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15155 (setq buf (if agendap (marker-buffer m) (current-buffer))
15156 pos (if agendap m (point)))
15157 (with-current-buffer buf
15161 (setq cnt (1+ cnt))
15162 (org-toggle-tag tag (if off 'off 'on))
15163 (setq newhead (org-get-heading)))))
15164 (and agendap (org-agenda-change-all-lines newhead m))))
15165 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15167 (defun org-tags-completion-function (string _predicate &optional flag)
15168 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15169 (confirm (lambda (x) (stringp (car x)))))
15170 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15171 (setq s1 (match-string 1 string)
15172 s2 (match-string 2 string))
15173 (setq s1 "" s2 string))
15177 (setq rtn (try-completion s2 ctable confirm))
15178 (when (stringp rtn)
15180 (concat s1 s2 (substring rtn (length s2))
15181 (if (and org-add-colon-after-tag-completion
15182 (assoc rtn ctable))
15187 (all-completions s2 ctable confirm))
15190 (assoc s2 ctable)))))
15192 (defun org-fast-tag-insert (kwd tags face &optional end)
15193 "Insert KDW, and the TAGS, the latter with face FACE.
15195 (insert (format "%-12s" (concat kwd ":"))
15196 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15199 (defun org-fast-tag-show-exit (flag)
15202 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15203 (replace-match ""))
15206 (org-move-to-column (- (window-width) 19) t)
15207 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15209 (defun org-set-current-tags-overlay (current prefix)
15210 "Add an overlay to CURRENT tag with PREFIX."
15211 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15212 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15213 (org-overlay-display org-tags-overlay (concat prefix s))))
15215 (defvar org-last-tag-selection-key nil)
15216 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15217 "Fast tag selection with single keys.
15218 CURRENT is the current list of tags in the headline, INHERITED is the
15219 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15220 possibly with grouping information. TODO-TABLE is a similar table with
15221 TODO keywords, should these have keys assigned to them.
15222 If the keys are nil, a-z are automatically assigned.
15223 Returns the new tags string, or nil to not change the current settings."
15224 (let* ((fulltable (append table todo-table))
15225 (maxlen (apply 'max (mapcar
15227 (if (stringp (car x)) (string-width (car x)) 0))
15229 (buf (current-buffer))
15230 (expert (eq org-fast-tag-selection-single-key 'expert))
15232 (fwidth (+ maxlen 3 1 3))
15233 (ncol (/ (- (window-width) 4) fwidth))
15236 tg cnt e c char c1 c2 ntable tbl rtn
15237 ov-start ov-end ov-prefix
15238 (exit-after-next org-fast-tag-selection-single-key)
15239 (done-keywords org-done-keywords)
15240 groups ingroup intaggroup)
15242 (beginning-of-line 1)
15243 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15244 (setq ov-start (match-beginning 1)
15245 ov-end (match-end 1)
15247 (setq ov-start (1- (point-at-eol))
15248 ov-end (1+ ov-start))
15249 (skip-chars-forward "^\n\r")
15252 (buffer-substring (1- (point)) (point))
15253 (if (> (current-column) org-tags-column)
15255 (make-string (- org-tags-column (current-column)) ?\ ))))))
15256 (move-overlay org-tags-overlay ov-start ov-end)
15257 (save-window-excursion
15259 (set-buffer (get-buffer-create " *Org tags*"))
15260 (delete-other-windows)
15261 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15262 (org-switch-to-buffer-other-window " *Org tags*"))
15264 (setq-local org-done-keywords done-keywords)
15265 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15266 (org-fast-tag-insert "Current" current c-face "\n\n")
15267 (org-fast-tag-show-exit exit-after-next)
15268 (org-set-current-tags-overlay current ov-prefix)
15269 (setq tbl fulltable char ?a cnt 0)
15270 (while (setq e (pop tbl))
15272 ((eq (car e) :startgroup)
15273 (push '() groups) (setq ingroup t)
15274 (unless (zerop cnt)
15277 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15278 ((eq (car e) :endgroup)
15279 (setq ingroup nil cnt 0)
15280 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15281 ((eq (car e) :startgrouptag)
15282 (setq intaggroup t)
15283 (unless (zerop cnt)
15287 ((eq (car e) :endgrouptag)
15288 (setq intaggroup nil cnt 0)
15290 ((equal e '(:newline))
15291 (unless (zerop cnt)
15295 (while (equal (car tbl) '(:newline))
15297 (setq tbl (cdr tbl)))))
15298 ((equal e '(:grouptags)) (insert " : "))
15300 (setq tg (copy-sequence (car e)) c2 nil)
15303 ;; automatically assign a character.
15304 (setq c1 (string-to-char
15305 (downcase (substring
15306 tg (if (= (string-to-char tg) ?@) 1 0)))))
15307 (if (or (rassoc c1 ntable) (rassoc c1 table))
15308 (while (or (rassoc char ntable) (rassoc char table))
15309 (setq char (1+ char)))
15311 (setq c (or c2 char)))
15312 (when ingroup (push tg (car groups)))
15313 (setq tg (org-add-props tg nil 'face
15315 ((not (assoc tg table))
15316 (org-get-todo-face tg))
15317 ((member tg current) c-face)
15318 ((member tg inherited) i-face))))
15319 (when (equal (caar tbl) :grouptags)
15320 (org-add-props tg nil 'face 'org-tag-group))
15321 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15322 (insert "[" c "] " tg (make-string
15323 (- fwidth 4 (length tg)) ?\ ))
15324 (push (cons tg c) ntable)
15325 (when (= (cl-incf cnt) ncol)
15327 (when (or ingroup intaggroup) (insert " "))
15329 (setq ntable (nreverse ntable))
15331 (goto-char (point-min))
15332 (unless expert (org-fit-window-to-buffer))
15336 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15337 (if (not groups) "no " "")
15338 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15339 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15340 (setq org-last-tag-selection-key c)
15342 ((= c ?\r) (throw 'exit t))
15344 (setq groups (not groups))
15345 (goto-char (point-min))
15346 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15349 (org-fast-tag-show-exit
15350 (setq exit-after-next (not exit-after-next)))
15352 (delete-other-windows)
15353 (set-window-buffer (split-window-vertically) " *Org tags*")
15354 (org-switch-to-buffer-other-window " *Org tags*")
15355 (org-fit-window-to-buffer)))
15357 (and (= c ?q) (not (rassoc c ntable))))
15358 (delete-overlay org-tags-overlay)
15359 (setq quit-flag t))
15362 (when exit-after-next (setq exit-after-next 'now)))
15364 (condition-case nil
15365 (setq tg (completing-read
15368 (with-current-buffer buf
15370 (org-get-buffer-tags))))))
15371 (quit (setq tg "")))
15372 (when (string-match "\\S-" tg)
15373 (cl-pushnew (list tg) buffer-tags :test #'equal)
15374 (if (member tg current)
15375 (setq current (delete tg current))
15376 (push tg current)))
15377 (when exit-after-next (setq exit-after-next 'now)))
15378 ((setq e (rassoc c todo-table) tg (car e))
15379 (with-current-buffer buf
15380 (save-excursion (org-todo tg)))
15381 (when exit-after-next (setq exit-after-next 'now)))
15382 ((setq e (rassoc c ntable) tg (car e))
15383 (if (member tg current)
15384 (setq current (delete tg current))
15385 (cl-loop for g in groups do
15386 (when (member tg g)
15387 (dolist (x g) (setq current (delete x current)))))
15389 (when exit-after-next (setq exit-after-next 'now))))
15391 ;; Create a sorted list
15395 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15396 (when (eq exit-after-next 'now) (throw 'exit t))
15397 (goto-char (point-min))
15398 (beginning-of-line 2)
15399 (delete-region (point) (point-at-eol))
15400 (org-fast-tag-insert "Current" current c-face)
15401 (org-set-current-tags-overlay current ov-prefix)
15402 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15403 (setq tg (match-string 1))
15404 (add-text-properties
15405 (match-beginning 1) (match-end 1)
15408 ((member tg current) c-face)
15409 ((member tg inherited) i-face)
15410 (t (get-text-property (match-beginning 1) 'face))))))
15411 (goto-char (point-min)))))
15412 (delete-overlay org-tags-overlay)
15414 (mapconcat 'identity current ":")
15417 (defun org-get-tags-string ()
15418 "Get the TAGS string in the current headline."
15419 (unless (org-at-heading-p t)
15420 (user-error "Not on a heading"))
15422 (beginning-of-line 1)
15423 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15424 (match-string-no-properties 1)
15427 (defun org-get-tags ()
15428 "Get the list of tags specified in the current headline."
15429 (org-split-string (org-get-tags-string) ":"))
15431 (defun org-get-buffer-tags ()
15432 "Get a table of all tags used in the buffer, for completion."
15433 (org-with-wide-buffer
15434 (goto-char (point-min))
15435 (let ((tag-re (concat org-outline-regexp-bol
15436 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15438 (while (re-search-forward tag-re nil t)
15439 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15441 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15443 ;;;; The mapping API
15445 (defvar org-agenda-skip-comment-trees)
15446 (defvar org-agenda-skip-function)
15447 (defun org-map-entries (func &optional match scope &rest skip)
15448 "Call FUNC at each headline selected by MATCH in SCOPE.
15450 FUNC is a function or a lisp form. The function will be called without
15451 arguments, with the cursor positioned at the beginning of the headline.
15452 The return values of all calls to the function will be collected and
15453 returned as a list.
15455 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15456 does not need to preserve point. After evaluation, the cursor will be
15457 moved to the end of the line (presumably of the headline of the
15458 processed entry) and search continues from there. Under some
15459 circumstances, this may not produce the wanted results. For example,
15460 if you have removed (e.g. archived) the current (sub)tree it could
15461 mean that the next entry will be skipped entirely. In such cases, you
15462 can specify the position from where search should continue by making
15463 FUNC set the variable `org-map-continue-from' to the desired buffer
15466 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15467 Only headlines that are matched by this query will be considered during
15468 the iteration. When MATCH is nil or t, all headlines will be
15469 visited by the iteration.
15471 SCOPE determines the scope of this command. It can be any of:
15473 nil The current buffer, respecting the restriction if any
15474 tree The subtree started with the entry at point
15475 region The entries within the active region, if any
15477 The entries within the active region, but only those at
15478 the same level than the first one.
15479 file The current buffer, without restriction
15481 The current buffer, and any archives associated with it
15482 agenda All agenda files
15483 agenda-with-archives
15484 All agenda files with any archive files associated with them
15486 If this is a list, all files in the list will be scanned
15488 The remaining args are treated as settings for the skipping facilities of
15489 the scanner. The following items can be given here:
15491 archive skip trees with the archive tag
15492 comment skip trees with the COMMENT keyword
15493 function or Emacs Lisp form:
15494 will be used as value for `org-agenda-skip-function', so
15495 whenever the function returns a position, FUNC will not be
15496 called for that entry and search will continue from the
15499 If your function needs to retrieve the tags including inherited tags
15500 at the *current* entry, you can use the value of the variable
15501 `org-scanner-tags' which will be much faster than getting the value
15502 with `org-get-tags-at'. If your function gets properties with
15503 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15504 to t around the call to `org-entry-properties' to get the same speedup.
15505 Note that if your function moves around to retrieve tags and properties at
15506 a *different* entry, you cannot use these techniques."
15507 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15508 (not (org-region-active-p)))
15509 (let* ((org-agenda-archives-mode nil) ; just to make sure
15510 (org-agenda-skip-archived-trees (memq 'archive skip))
15511 (org-agenda-skip-comment-trees (memq 'comment skip))
15512 (org-agenda-skip-function
15513 (car (org-delete-all '(comment archive) skip)))
15514 (org-tags-match-list-sublevels t)
15515 (start-level (eq scope 'region-start-level))
15517 org-todo-keywords-for-agenda
15518 org-done-keywords-for-agenda
15519 org-todo-keyword-alist-for-agenda
15520 org-tag-alist-for-agenda
15521 org--matcher-tags-todo-only)
15524 ((eq match t) (setq matcher t))
15525 ((eq match nil) (setq matcher t))
15526 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15530 (cond ((eq scope 'tree)
15531 (org-back-to-heading t)
15532 (org-narrow-to-subtree)
15534 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15535 (org-region-active-p))
15536 ;; If needed, set start-level to a string like "2"
15539 (goto-char (region-beginning))
15540 (unless (org-at-heading-p) (outline-next-heading))
15541 (setq start-level (org-current-level))))
15542 (narrow-to-region (region-beginning)
15544 (goto-char (region-end))
15545 (unless (and (bolp) (org-at-heading-p))
15546 (outline-next-heading))
15552 (org-agenda-prepare-buffers
15553 (and buffer-file-name (list buffer-file-name)))
15556 func matcher org--matcher-tags-todo-only start-level)))
15557 ;; Get the right scope
15559 ((and scope (listp scope) (symbolp (car scope)))
15560 (setq scope (eval scope)))
15561 ((eq scope 'agenda)
15562 (setq scope (org-agenda-files t)))
15563 ((eq scope 'agenda-with-archives)
15564 (setq scope (org-agenda-files t))
15565 (setq scope (org-add-archive-files scope)))
15567 (setq scope (and buffer-file-name (list buffer-file-name))))
15568 ((eq scope 'file-with-archives)
15569 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15570 (org-agenda-prepare-buffers scope)
15571 (dolist (file scope)
15572 (with-current-buffer (org-find-base-buffer-visiting file)
15573 (org-with-wide-buffer
15574 (goto-char (point-min))
15579 func matcher org--matcher-tags-todo-only)))))))))
15584 (defconst org-special-properties
15585 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15586 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15587 "The special properties valid in Org mode.
15588 These are properties that are not defined in the property drawer,
15589 but in some other way.")
15591 (defconst org-default-properties
15592 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15593 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15594 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15595 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15596 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15597 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15598 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15599 "Some properties that are used by Org mode for various purposes.
15600 Being in this list makes sure that they are offered for completion.")
15602 (defun org--valid-property-p (property)
15603 "Non nil when string PROPERTY is a valid property name."
15605 (or (equal property "")
15606 (string-match-p "\\s-" property))))
15608 (defun org--update-property-plist (key val props)
15609 "Associate KEY to VAL in alist PROPS.
15610 Modifications are made by side-effect. Return new alist."
15611 (let* ((appending (string= (substring key -1) "+"))
15612 (key (if appending (substring key 0 -1) key))
15613 (old (assoc-string key props t)))
15614 (if (not old) (cons (cons key val) props)
15615 (setcdr old (if appending (concat (cdr old) " " val) val))
15618 (defun org-get-property-block (&optional beg force)
15619 "Return the (beg . end) range of the body of the property drawer.
15620 BEG is the beginning of the current subtree, or of the part
15621 before the first headline. If it is not given, it will be found.
15622 If the drawer does not exist, create it if FORCE is non-nil, or
15624 (org-with-wide-buffer
15625 (when beg (goto-char beg))
15626 (unless (org-before-first-heading-p)
15627 (let ((beg (cond (beg)
15628 ((or (not (featurep 'org-inlinetask))
15629 (org-inlinetask-in-task-p))
15630 (org-back-to-heading t))
15631 (t (org-with-limited-levels (org-back-to-heading t))))))
15633 (when (looking-at-p org-planning-line-re) (forward-line))
15634 (cond ((looking-at org-property-drawer-re)
15636 (cons (point) (progn (goto-char (match-end 0))
15637 (line-beginning-position))))
15640 (org-insert-property-drawer)
15641 (let ((pos (save-excursion (search-forward ":END:")
15642 (line-beginning-position))))
15643 (cons pos pos))))))))
15645 (defun org-at-property-p ()
15646 "Non-nil when point is inside a property drawer.
15647 See `org-property-re' for match data, if applicable."
15649 (beginning-of-line)
15650 (and (looking-at org-property-re)
15651 (let ((property-drawer (save-match-data (org-get-property-block))))
15652 (and property-drawer
15653 (>= (point) (car property-drawer))
15654 (< (point) (cdr property-drawer)))))))
15656 (defun org-property-action ()
15657 "Do an action on properties."
15659 (unless (org-at-property-p) (user-error "Not at a property"))
15660 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15661 (let ((c (read-char-exclusive)))
15663 (?s (call-interactively #'org-set-property))
15664 (?d (call-interactively #'org-delete-property))
15665 (?D (call-interactively #'org-delete-property-globally))
15666 (?c (call-interactively #'org-compute-property-at-point))
15667 (otherwise (user-error "No such property action %c" c)))))
15669 (defun org-inc-effort ()
15670 "Increment the value of the effort property in the current entry."
15672 (org-set-effort nil t))
15674 (defvar org-clock-effort) ; Defined in org-clock.el.
15675 (defvar org-clock-current-task) ; Defined in org-clock.el.
15676 (defun org-set-effort (&optional value increment)
15677 "Set the effort property of the current entry.
15678 With numerical prefix arg, use the nth allowed value, 0 stands for the
15679 10th allowed value.
15681 When INCREMENT is non-nil, set the property to the next allowed value."
15683 (when (equal value 0) (setq value 10))
15684 (let* ((completion-ignore-case t)
15685 (prop org-effort-property)
15686 (cur (org-entry-get nil prop))
15687 (allowed (org-property-get-allowed-values nil prop 'table))
15688 (existing (mapcar 'list (org-property-values prop)))
15689 (heading (nth 4 (org-heading-components)))
15692 ((stringp value) value)
15693 ((and allowed (integerp value))
15694 (or (car (nth (1- value) allowed))
15695 (car (org-last allowed))))
15696 ((and allowed increment)
15697 (or (cl-caadr (member (list cur) allowed))
15698 (user-error "Allowed effort values are not set")))
15700 (message "Select 1-9,0, [RET%s]: %s"
15701 (if cur (concat "=" cur) "")
15702 (mapconcat 'car allowed " "))
15703 (setq rpl (read-char-exclusive))
15704 (if (equal rpl ?\r)
15706 (setq rpl (- rpl ?0))
15707 (when (equal rpl 0) (setq rpl 10))
15708 (if (and (> rpl 0) (<= rpl (length allowed)))
15709 (car (nth (1- rpl) allowed))
15710 (org-completing-read "Effort: " allowed nil))))
15712 (org-completing-read
15713 (concat "Effort" (and cur (string-match "\\S-" cur)
15714 (concat " [" cur "]"))
15716 existing nil nil "" nil cur)))))
15717 (unless (equal (org-entry-get nil prop) val)
15718 (org-entry-put nil prop val))
15719 (org-refresh-property
15720 '((effort . identity)
15721 (effort-minutes . org-duration-string-to-minutes))
15723 (when (equal heading (bound-and-true-p org-clock-current-task))
15724 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15725 (org-clock-update-mode-line))
15726 (message "%s is now %s" prop val)))
15728 (defun org-entry-properties (&optional pom which)
15729 "Get all properties of the current entry.
15731 When POM is a buffer position, get all properties from the entry
15734 This includes the TODO keyword, the tags, time strings for
15735 deadline, scheduled, and clocking, and any additional properties
15736 defined in the entry.
15738 If WHICH is nil or `all', get all properties. If WHICH is
15739 `special' or `standard', only get that subclass. If WHICH is
15740 a string, only get that property.
15742 Return value is an alist. Keys are properties, as upcased
15744 (org-with-point-at pom
15745 (when (and (derived-mode-p 'org-mode)
15746 (ignore-errors (org-back-to-heading t)))
15748 (let* ((beg (point))
15749 (specific (and (stringp which) (upcase which)))
15750 (which (cond ((not specific) which)
15751 ((member specific org-special-properties) 'special)
15754 ;; Get the special properties, like TODO and TAGS.
15755 (when (memq which '(nil all special))
15756 (when (or (not specific) (string= specific "CLOCKSUM"))
15757 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15759 (push (cons "CLOCKSUM"
15760 (org-minutes-to-clocksum-string clocksum))
15762 (when specific (throw 'exit props)))
15763 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15764 (let ((clocksumt (get-text-property (point)
15765 :org-clock-minutes-today)))
15767 (push (cons "CLOCKSUM_T"
15768 (org-minutes-to-clocksum-string clocksumt))
15770 (when specific (throw 'exit props)))
15771 (when (or (not specific) (string= specific "ITEM"))
15772 (let ((case-fold-search nil))
15773 (when (looking-at org-complex-heading-regexp)
15775 (let ((title (match-string-no-properties 4)))
15776 (if (org-string-nw-p title)
15777 (org-remove-tabs title)
15780 (when specific (throw 'exit props)))
15781 (when (or (not specific) (string= specific "TODO"))
15782 (let ((case-fold-search nil))
15783 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15784 (push (cons "TODO" (match-string-no-properties 2)) props)))
15785 (when specific (throw 'exit props)))
15786 (when (or (not specific) (string= specific "PRIORITY"))
15787 (push (cons "PRIORITY"
15788 (if (looking-at org-priority-regexp)
15789 (match-string-no-properties 2)
15790 (char-to-string org-default-priority)))
15792 (when specific (throw 'exit props)))
15793 (when (or (not specific) (string= specific "FILE"))
15794 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15796 (when specific (throw 'exit props)))
15797 (when (or (not specific) (string= specific "TAGS"))
15798 (let ((value (org-string-nw-p (org-get-tags-string))))
15799 (when value (push (cons "TAGS" value) props)))
15800 (when specific (throw 'exit props)))
15801 (when (or (not specific) (string= specific "ALLTAGS"))
15802 (let ((value (org-get-tags-at)))
15804 (push (cons "ALLTAGS"
15805 (format ":%s:" (mapconcat #'identity value ":")))
15807 (when specific (throw 'exit props)))
15808 (when (or (not specific) (string= specific "BLOCKED"))
15809 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15810 (when specific (throw 'exit props)))
15811 (when (or (not specific)
15812 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15814 (when (looking-at-p org-planning-line-re)
15816 (let ((bol (line-beginning-position))
15817 ;; Backward compatibility: time keywords used to
15818 ;; be configurable (before 8.3). Make sure we
15819 ;; get the correct keyword.
15820 (key-assoc `(("CLOSED" . ,org-closed-string)
15821 ("DEADLINE" . ,org-deadline-string)
15822 ("SCHEDULED" . ,org-scheduled-string))))
15823 (dolist (pair (if specific (list (assoc specific key-assoc))
15826 (when (search-backward (cdr pair) bol t)
15827 (goto-char (match-end 0))
15828 (skip-chars-forward " \t")
15829 (and (looking-at org-ts-regexp-both)
15830 (push (cons (car pair)
15831 (match-string-no-properties 0))
15833 (when specific (throw 'exit props)))
15834 (when (or (not specific)
15835 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15838 ;; Fix next time-stamp before END. TS is the
15839 ;; list of time-stamps found so far.
15842 ((string= specific "TIMESTAMP")
15844 ((string= specific "TIMESTAMP_IA")
15845 org-ts-regexp-inactive)
15846 ((assoc "TIMESTAMP_IA" ts)
15848 ((assoc "TIMESTAMP" ts)
15849 org-ts-regexp-inactive)
15850 (t org-ts-regexp-both))))
15852 (while (re-search-forward regexp end t)
15854 (let ((object (org-element-context)))
15855 ;; Accept to match timestamps in node
15856 ;; properties, too.
15857 (when (memq (org-element-type object)
15858 '(node-property timestamp))
15860 (org-element-property :type object)))
15862 ((and (memq type '(active active-range))
15863 (not (equal specific "TIMESTAMP_IA")))
15864 (unless (assoc "TIMESTAMP" ts)
15865 (push (cons "TIMESTAMP"
15866 (org-element-property
15867 :raw-value object))
15869 (when specific (throw 'exit ts))))
15870 ((and (memq type '(inactive inactive-range))
15871 (not (string= specific "TIMESTAMP")))
15872 (unless (assoc "TIMESTAMP_IA" ts)
15873 (push (cons "TIMESTAMP_IA"
15874 (org-element-property
15875 :raw-value object))
15877 (when specific (throw 'exit ts))))))
15878 ;; Both timestamp types are found,
15879 ;; move to next part.
15880 (when (= (length ts) 2) (throw 'next ts)))))
15883 ;; First look for timestamps within headline.
15884 (let ((ts (funcall find-ts (line-end-position) nil)))
15885 (if (= (length ts) 2) (setq props (nconc ts props))
15887 ;; Then find timestamps in the section, skipping
15889 (when (looking-at-p org-planning-line-re)
15891 (let ((end (save-excursion (outline-next-heading))))
15892 (setq props (nconc (funcall find-ts end ts) props))))))))
15893 ;; Get the standard properties, like :PROP:.
15894 (when (memq which '(nil all standard))
15895 ;; If we are looking after a specific property, delegate
15896 ;; to `org-entry-get', which is faster. However, make an
15897 ;; exception for "CATEGORY", since it can be also set
15898 ;; through keywords (i.e. #+CATEGORY).
15899 (if (and specific (not (equal specific "CATEGORY")))
15900 (let ((value (org-entry-get beg specific nil t)))
15901 (throw 'exit (and value (list (cons specific value)))))
15902 (let ((range (org-get-property-block beg)))
15904 (let ((end (cdr range)) seen-base)
15905 (goto-char (car range))
15906 ;; Unlike to `org--update-property-plist', we
15907 ;; handle the case where base values is found
15908 ;; after its extension. We also forbid standard
15909 ;; properties to be named as special properties.
15910 (while (re-search-forward org-property-re end t)
15911 (let* ((key (upcase (match-string-no-properties 2)))
15912 (extendp (string-match-p "\\+\\'" key))
15913 (key-base (if extendp (substring key 0 -1) key))
15914 (value (match-string-no-properties 3)))
15916 ((member-ignore-case key-base org-special-properties))
15919 (org--update-property-plist key value props)))
15920 ((member key seen-base))
15921 (t (push key seen-base)
15922 (let ((p (assoc-string key props t)))
15923 (if p (setcdr p (concat value " " (cdr p)))
15924 (push (cons key value) props))))))))))))
15925 (unless (assoc "CATEGORY" props)
15926 (push (cons "CATEGORY" (org-get-category beg)) props)
15927 (when (string= specific "CATEGORY") (throw 'exit props)))
15931 (defun org-property--local-values (property literal-nil)
15932 "Return value for PROPERTY in current entry.
15933 Value is a list whose car is the base value for PROPERTY and cdr
15934 a list of accumulated values. Return nil if neither is found in
15935 the entry. Also return nil when PROPERTY is set to \"nil\",
15936 unless LITERAL-NIL is non-nil."
15937 (let ((range (org-get-property-block)))
15939 (goto-char (car range))
15940 (let* ((case-fold-search t)
15945 (let ((v (and (re-search-forward
15946 (org-re-property property nil t) end t)
15947 (match-string-no-properties 3))))
15948 (list (if literal-nil v (org-not-nil v)))))))
15949 ;; Find additional values.
15950 (let* ((property+ (org-re-property (concat property "+") nil t)))
15951 (while (re-search-forward property+ end t)
15952 (push (match-string-no-properties 3) value)))
15953 ;; Return final values.
15954 (and (not (equal value '(nil))) (nreverse value))))))
15956 (defun org-entry-get (pom property &optional inherit literal-nil)
15957 "Get value of PROPERTY for entry or content at point-or-marker POM.
15959 If INHERIT is non-nil and the entry does not have the property,
15960 then also check higher levels of the hierarchy. If INHERIT is
15961 the symbol `selective', use inheritance only if the setting in
15962 `org-use-property-inheritance' selects PROPERTY for inheritance.
15964 If the property is present but empty, the return value is the
15965 empty string. If the property is not present at all, nil is
15966 returned. In any other case, return the value as a string.
15967 Search is case-insensitive.
15969 If LITERAL-NIL is set, return the string value \"nil\" as
15970 a string, do not interpret it as the list atom nil. This is used
15971 for inheritance when a \"nil\" value can supersede a non-nil
15972 value higher up the hierarchy."
15973 (org-with-point-at pom
15975 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15976 ;; We need a special property. Use `org-entry-properties' to
15977 ;; retrieve it, but specify the wanted property.
15978 (cdr (assoc-string property (org-entry-properties nil property))))
15980 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15981 (org-entry-get-with-inheritance property literal-nil))
15983 (let* ((local (org-property--local-values property literal-nil))
15984 (value (and local (mapconcat #'identity (delq nil local) " "))))
15985 (if literal-nil value (org-not-nil value)))))))
15987 (defun org-property-or-variable-value (var &optional inherit)
15988 "Check if there is a property fixing the value of VAR.
15989 If yes, return this value. If not, return the current value of the variable."
15990 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15991 (if (and prop (stringp prop) (string-match "\\S-" prop))
15993 (symbol-value var))))
15995 (defun org-entry-delete (pom property)
15996 "Delete PROPERTY from entry at point-or-marker POM.
15997 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15998 non-nil when a property was removed."
15999 (unless (member property org-special-properties)
16000 (org-with-point-at pom
16001 (let ((range (org-get-property-block)))
16003 (let* ((begin (car range))
16004 (origin (cdr range))
16005 (end (copy-marker origin))
16006 (re (org-re-property
16007 (concat (regexp-quote property) "\\+?") t t)))
16009 (while (re-search-forward re end t)
16010 (delete-region (match-beginning 0) (line-beginning-position 2)))
16011 ;; If drawer is empty, remove it altogether.
16012 (when (= begin end)
16013 (delete-region (line-beginning-position 0)
16014 (line-beginning-position 2)))
16015 ;; Return non-nil if some property was removed.
16016 (prog1 (/= end origin) (set-marker end nil))))))))
16018 ;; Multi-values properties are properties that contain multiple values
16019 ;; These values are assumed to be single words, separated by whitespace.
16020 (defun org-entry-add-to-multivalued-property (pom property value)
16021 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16022 (let* ((old (org-entry-get pom property))
16023 (values (and old (org-split-string old "[ \t]"))))
16024 (setq value (org-entry-protect-space value))
16025 (unless (member value values)
16026 (setq values (append values (list value)))
16027 (org-entry-put pom property
16028 (mapconcat 'identity values " ")))))
16030 (defun org-entry-remove-from-multivalued-property (pom property value)
16031 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16032 (let* ((old (org-entry-get pom property))
16033 (values (and old (org-split-string old "[ \t]"))))
16034 (setq value (org-entry-protect-space value))
16035 (when (member value values)
16036 (setq values (delete value values))
16037 (org-entry-put pom property
16038 (mapconcat 'identity values " ")))))
16040 (defun org-entry-member-in-multivalued-property (pom property value)
16041 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16042 (let* ((old (org-entry-get pom property))
16043 (values (and old (org-split-string old "[ \t]"))))
16044 (setq value (org-entry-protect-space value))
16045 (member value values)))
16047 (defun org-entry-get-multivalued-property (pom property)
16048 "Return a list of values in a multivalued property."
16049 (let* ((value (org-entry-get pom property))
16050 (values (and value (org-split-string value "[ \t]"))))
16051 (mapcar 'org-entry-restore-space values)))
16053 (defun org-entry-put-multivalued-property (pom property &rest values)
16054 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16055 VALUES should be a list of strings. Spaces will be protected."
16056 (org-entry-put pom property
16057 (mapconcat 'org-entry-protect-space values " "))
16058 (let* ((value (org-entry-get pom property))
16059 (values (and value (org-split-string value "[ \t]"))))
16060 (mapcar 'org-entry-restore-space values)))
16062 (defun org-entry-protect-space (s)
16063 "Protect spaces and newline in string S."
16064 (while (string-match " " s)
16065 (setq s (replace-match "%20" t t s)))
16066 (while (string-match "\n" s)
16067 (setq s (replace-match "%0A" t t s)))
16070 (defun org-entry-restore-space (s)
16071 "Restore spaces and newline in string S."
16072 (while (string-match "%20" s)
16073 (setq s (replace-match " " t t s)))
16074 (while (string-match "%0A" s)
16075 (setq s (replace-match "\n" t t s)))
16078 (defvar org-entry-property-inherited-from (make-marker)
16079 "Marker pointing to the entry from where a property was inherited.
16080 Each call to `org-entry-get-with-inheritance' will set this marker to the
16081 location of the entry where the inheritance search matched. If there was
16082 no match, the marker will point nowhere.
16083 Note that also `org-entry-get' calls this function, if the INHERIT flag
16086 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16087 "Get PROPERTY of entry or content at point, search higher levels if needed.
16088 The search will stop at the first ancestor which has the property defined.
16089 If the value found is \"nil\", return nil to show that the property
16090 should be considered as undefined (this is the meaning of nil here).
16091 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16092 (move-marker org-entry-property-inherited-from nil)
16093 (org-with-wide-buffer
16097 (let ((v (org-property--local-values property literal-nil)))
16100 (concat (mapconcat #'identity (delq nil v) " ")
16105 (org-back-to-heading t)
16106 (move-marker org-entry-property-inherited-from (point))
16108 ((org-up-heading-safe))
16111 (cdr (or (assoc-string property org-file-properties t)
16112 (assoc-string property org-global-properties t)
16113 (assoc-string property org-global-properties-fixed t)))))
16114 (cond ((not global))
16115 (value (setq value (concat global " " value)))
16116 (t (setq value global))))
16117 (throw 'exit nil))))))
16118 (if literal-nil value (org-not-nil value)))))
16120 (defvar org-property-changed-functions nil
16121 "Hook called when the value of a property has changed.
16122 Each hook function should accept two arguments, the name of the property
16123 and the new value.")
16125 (defun org-entry-put (pom property value)
16126 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16128 If the value is nil, it is converted to the empty string. If it
16129 is not a string, an error is raised. Also raise an error on
16130 invalid property names.
16132 PROPERTY can be any regular property (see
16133 `org-special-properties'). It can also be \"TODO\",
16134 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16136 For the last two properties, VALUE may have any of the special
16137 values \"earlier\" and \"later\". The function then increases or
16138 decreases scheduled or deadline date by one day."
16139 (cond ((null value) (setq value ""))
16140 ((not (stringp value)) (error "Properties values should be strings"))
16141 ((not (org--valid-property-p property))
16142 (user-error "Invalid property name: \"%s\"" property)))
16143 (org-with-point-at pom
16144 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16145 (org-back-to-heading t)
16146 (org-with-limited-levels (org-back-to-heading t)))
16147 (let ((beg (point)))
16149 ((equal property "TODO")
16150 (cond ((not (org-string-nw-p value)) (setq value 'none))
16151 ((not (member value org-todo-keywords-1))
16152 (user-error "\"%s\" is not a valid TODO state" value)))
16154 (org-set-tags nil 'align))
16155 ((equal property "PRIORITY")
16156 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16157 (org-set-tags nil 'align))
16158 ((equal property "SCHEDULED")
16160 (if (and (looking-at-p org-planning-line-re)
16162 org-scheduled-time-regexp (line-end-position) t))
16163 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16164 ((string= value "later") (org-timestamp-change 1 'day))
16165 ((string= value "") (org-schedule '(4)))
16166 (t (org-schedule nil value)))
16167 (if (member value '("earlier" "later" ""))
16168 (call-interactively #'org-schedule)
16169 (org-schedule nil value))))
16170 ((equal property "DEADLINE")
16172 (if (and (looking-at-p org-planning-line-re)
16174 org-deadline-time-regexp (line-end-position) t))
16175 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16176 ((string= value "later") (org-timestamp-change 1 'day))
16177 ((string= value "") (org-deadline '(4)))
16178 (t (org-deadline nil value)))
16179 (if (member value '("earlier" "later" ""))
16180 (call-interactively #'org-deadline)
16181 (org-deadline nil value))))
16182 ((member property org-special-properties)
16183 (error "The %s property cannot be set with `org-entry-put'" property))
16185 (let* ((range (org-get-property-block beg 'force))
16187 (case-fold-search t))
16188 (goto-char (car range))
16189 (if (re-search-forward (org-re-property property nil t) end t)
16190 (progn (delete-region (match-beginning 0) (match-end 0))
16191 (goto-char (match-beginning 0)))
16195 (insert ":" property ":")
16196 (when value (insert " " value))
16197 (org-indent-line)))))
16198 (run-hook-with-args 'org-property-changed-functions property value)))
16200 (defun org-buffer-property-keys
16201 (&optional specials defaults columns ignore-malformed)
16202 "Get all property keys in the current buffer.
16204 When SPECIALS is non-nil, also list the special properties that
16205 reflect things like tags and TODO state.
16207 When DEFAULTS is non-nil, also include properties that has
16208 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16209 DESCRIPTION, LOCATION, and LOGGING and others.
16211 When COLUMNS in non-nil, also include property names given in
16212 COLUMN formats in the current buffer.
16214 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16215 automatically performed, such drawers will be silently ignored."
16216 (let ((case-fold-search t)
16218 (and specials org-special-properties)
16219 (and defaults (cons org-effort-property org-default-properties))
16221 (org-with-wide-buffer
16222 (goto-char (point-min))
16223 (while (re-search-forward org-property-start-re nil t)
16224 (let ((range (org-get-property-block)))
16227 (when (and (not ignore-malformed)
16228 (not (org-before-first-heading-p))
16229 (y-or-n-p (format "Malformed drawer at %d, repair?"
16230 (line-beginning-position))))
16231 (org-get-property-block nil t))
16233 (goto-char (car range))
16234 (let ((begin (car range))
16236 ;; Make sure that found property block is not located
16237 ;; before current point, as it would generate an infloop.
16238 ;; It can happen, for example, in the following
16245 ;; *************** Inlinetask
16250 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16251 (while (< (point) end)
16252 (let ((p (progn (looking-at org-property-re)
16253 (match-string-no-properties 2))))
16254 ;; Only add true property name, not extension symbol.
16255 (push (if (not (string-match-p "\\+\\'" p)) p
16256 (substring p 0 -1))
16259 (outline-next-heading)))
16261 (goto-char (point-min))
16262 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16263 (let ((element (org-element-at-point)))
16264 (when (memq (org-element-type element) '(keyword node-property))
16265 (let ((value (org-element-property :value element))
16267 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16268 (setq start (match-end 0))
16269 (let ((p (match-string-no-properties 1 value)))
16270 (unless (member-ignore-case p org-special-properties)
16271 (push p props))))))))))
16272 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16274 (defun org-property-values (key)
16275 "List all non-nil values of property KEY in current buffer."
16276 (org-with-wide-buffer
16277 (goto-char (point-min))
16278 (let ((case-fold-search t)
16279 (re (org-re-property key))
16281 (while (re-search-forward re nil t)
16282 (push (org-entry-get (point) key) values))
16283 (delete-dups values))))
16285 (defun org-insert-property-drawer ()
16286 "Insert a property drawer into the current entry."
16287 (org-with-wide-buffer
16288 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16289 (org-back-to-heading t)
16290 (org-with-limited-levels (org-back-to-heading t)))
16292 (when (looking-at-p org-planning-line-re) (forward-line))
16293 (unless (looking-at-p org-property-drawer-re)
16294 ;; Make sure we start editing a line from current entry, not from
16295 ;; next one. It prevents extending text properties or overlays
16296 ;; belonging to the latter.
16297 (when (bolp) (backward-char))
16298 (let ((begin (1+ (point)))
16299 (inhibit-read-only t))
16300 (insert "\n:PROPERTIES:\n:END:")
16301 (when (eobp) (insert "\n"))
16302 (org-indent-region begin (point))))))
16304 (defun org-insert-drawer (&optional arg drawer)
16305 "Insert a drawer at point.
16307 When optional argument ARG is non-nil, insert a property drawer.
16309 Optional argument DRAWER, when non-nil, is a string representing
16310 drawer's name. Otherwise, the user is prompted for a name.
16312 If a region is active, insert the drawer around that region
16315 Point is left between drawer's boundaries."
16317 (let* ((drawer (if arg "PROPERTIES"
16318 (or drawer (read-from-minibuffer "Drawer: ")))))
16320 ;; With C-u, fall back on `org-insert-property-drawer'
16321 (arg (org-insert-property-drawer))
16322 ;; Check validity of suggested drawer's name.
16323 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16324 (user-error "Invalid drawer name"))
16325 ;; With an active region, insert a drawer at point.
16326 ((not (org-region-active-p))
16328 (unless (bolp) (insert "\n"))
16329 (insert (format ":%s:\n\n:END:\n" drawer))
16330 (forward-line -2)))
16331 ;; Otherwise, insert the drawer at point
16333 (let ((rbeg (region-beginning))
16334 (rend (copy-marker (region-end))))
16338 (beginning-of-line)
16339 (when (save-excursion
16340 (re-search-forward org-outline-regexp-bol rend t))
16341 (user-error "Drawers cannot contain headlines"))
16342 ;; Position point at the beginning of the first
16343 ;; non-blank line in region. Insert drawer's opening
16344 ;; there, then indent it.
16345 (org-skip-whitespace)
16346 (beginning-of-line)
16347 (insert ":" drawer ":\n")
16349 (indent-for-tab-command)
16350 ;; Move point to the beginning of the first blank line
16351 ;; after the last non-blank line in region. Insert
16352 ;; drawer's closing, then indent it.
16354 (skip-chars-backward " \r\t\n")
16356 (deactivate-mark t)
16357 (indent-for-tab-command)
16358 (unless (eolp) (insert "\n")))
16359 ;; Clear marker, whatever the outcome of insertion is.
16360 (set-marker rend nil)))))))
16362 (defvar org-property-set-functions-alist nil
16363 "Property set function alist.
16364 Each entry should have the following format:
16366 (PROPERTY . READ-FUNCTION)
16368 The read function will be called with the same argument as
16369 `org-completing-read'.")
16371 (defun org-set-property-function (property)
16372 "Get the function that should be used to set PROPERTY.
16373 This is computed according to `org-property-set-functions-alist'."
16374 (or (cdr (assoc property org-property-set-functions-alist))
16375 'org-completing-read))
16377 (defun org-read-property-value (property)
16378 "Read PROPERTY value from user."
16379 (let* ((completion-ignore-case t)
16380 (allowed (org-property-get-allowed-values nil property 'table))
16381 (cur (org-entry-get nil property))
16382 (prompt (concat property " value"
16383 (if (and cur (string-match "\\S-" cur))
16384 (concat " [" cur "]") "") ": "))
16385 (set-function (org-set-property-function property))
16387 (funcall set-function prompt allowed nil
16388 (not (get-text-property 0 'org-unrestricted
16390 (funcall set-function prompt
16391 (mapcar 'list (org-property-values property))
16392 nil nil "" nil cur))))
16395 (defvar org-last-set-property nil)
16396 (defvar org-last-set-property-value nil)
16397 (defun org-read-property-name ()
16398 "Read a property name."
16399 (let ((completion-ignore-case t)
16400 (default-prop (or (and (org-at-property-p)
16401 (match-string-no-properties 2))
16402 org-last-set-property)))
16403 (org-completing-read
16405 (if default-prop (concat " [" default-prop "]") "")
16407 (mapcar #'list (org-buffer-property-keys nil t t))
16408 nil nil nil nil default-prop)))
16410 (defun org-set-property-and-value (use-last)
16411 "Allow to set [PROPERTY]: [value] direction from prompt.
16412 When use-default, don't even ask, just use the last
16413 \"[PROPERTY]: [value]\" string from the history."
16415 (let* ((completion-ignore-case t)
16416 (pv (or (and use-last org-last-set-property-value)
16417 (org-completing-read
16418 "Enter a \"[Property]: [value]\" pair: "
16419 nil nil nil nil nil
16420 org-last-set-property-value)))
16422 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16423 (setq prop (match-string 1 pv)
16424 val (match-string 2 pv))
16425 (org-set-property prop val))))
16427 (defun org-set-property (property value)
16428 "In the current entry, set PROPERTY to VALUE.
16430 When called interactively, this will prompt for a property name, offering
16431 completion on existing and default properties. And then it will prompt
16432 for a value, offering completion either on allowed values (via an inherited
16433 xxx_ALL property) or on existing values in other instances of this property
16434 in the current file.
16436 Throw an error when trying to set a property with an invalid name."
16437 (interactive (list nil nil))
16438 (let ((property (or property (org-read-property-name))))
16439 ;; `org-entry-put' also makes the following check, but this one
16440 ;; avoids polluting `org-last-set-property' and
16441 ;; `org-last-set-property-value' needlessly.
16442 (unless (org--valid-property-p property)
16443 (user-error "Invalid property name: \"%s\"" property))
16444 (let ((value (or value (org-read-property-value property)))
16445 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16446 (setq org-last-set-property property)
16447 (setq org-last-set-property-value (concat property ": " value))
16448 ;; Possibly postprocess the inserted value:
16449 (when fn (setq value (funcall fn value)))
16450 (unless (equal (org-entry-get nil property) value)
16451 (org-entry-put nil property value)))))
16453 (defun org-find-property (property &optional value)
16454 "Find first entry in buffer that sets PROPERTY.
16456 When optional argument VALUE is non-nil, only consider an entry
16457 if it contains PROPERTY set to this value. If PROPERTY should be
16458 explicitly set to nil, use string \"nil\" for VALUE.
16460 Return position where the entry begins, or nil if there is no
16461 such entry. If narrowing is in effect, only search the visible
16462 part of the buffer."
16464 (goto-char (point-min))
16465 (let ((case-fold-search t)
16466 (re (org-re-property property nil (not value) value)))
16468 (while (re-search-forward re nil t)
16469 (when (if value (org-at-property-p)
16470 (org-entry-get (point) property nil t))
16471 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16473 (defun org-delete-property (property)
16474 "In the current entry, delete PROPERTY."
16476 (let* ((completion-ignore-case t)
16477 (cat (org-entry-get (point) "CATEGORY"))
16478 (props0 (org-entry-properties nil 'standard))
16479 (props (if cat props0
16480 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16481 (prop (if (< 1 (length props))
16482 (completing-read "Property: " props nil t)
16486 (message "No property to delete in this entry")
16487 (org-entry-delete nil property)
16488 (message "Property \"%s\" deleted" property)))
16490 (defun org-delete-property-globally (property)
16491 "Remove PROPERTY globally, from all entries.
16492 This function ignores narrowing, if any."
16494 (let* ((completion-ignore-case t)
16495 (prop (completing-read
16496 "Globally remove property: "
16497 (mapcar #'list (org-buffer-property-keys)))))
16499 (org-with-wide-buffer
16500 (goto-char (point-min))
16502 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16503 (while (re-search-forward re nil t)
16504 (when (org-entry-delete (point) property) (cl-incf count)))
16505 (message "Property \"%s\" removed from %d entries" property count))))
16507 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16509 (defun org-compute-property-at-point ()
16510 "Compute the property at point.
16511 This looks for an enclosing column format, extracts the operator and
16512 then applies it to the property in the column format's scope."
16514 (unless (org-at-property-p)
16515 (user-error "Not at a property"))
16516 (let ((prop (match-string-no-properties 2)))
16517 (org-columns-get-format-and-top-level)
16518 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16519 (user-error "No operator defined for property %s" prop))
16520 (org-columns-compute prop)))
16522 (defvar org-property-allowed-value-functions nil
16523 "Hook for functions supplying allowed values for a specific property.
16524 The functions must take a single argument, the name of the property, and
16525 return a flat list of allowed values. If \":ETC\" is one of
16526 the values, this means that these values are intended as defaults for
16527 completion, but that other values should be allowed too.
16528 The functions must return nil if they are not responsible for this
16531 (defun org-property-get-allowed-values (pom property &optional table)
16532 "Get allowed values for the property PROPERTY.
16533 When TABLE is non-nil, return an alist that can directly be used for
16537 ((equal property "TODO")
16538 (setq vals (org-with-point-at pom
16539 (append org-todo-keywords-1 '("")))))
16540 ((equal property "PRIORITY")
16541 (let ((n org-lowest-priority))
16542 (while (>= n org-highest-priority)
16543 (push (char-to-string n) vals)
16545 ((equal property "CATEGORY"))
16546 ((member property org-special-properties))
16547 ((setq vals (run-hook-with-args-until-success
16548 'org-property-allowed-value-functions property)))
16550 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16551 (when (and vals (string-match "\\S-" vals))
16552 (setq vals (car (read-from-string (concat "(" vals ")"))))
16553 (setq vals (mapcar (lambda (x)
16554 (cond ((stringp x) x)
16555 ((numberp x) (number-to-string x))
16556 ((symbolp x) (symbol-name x))
16559 (when (member ":ETC" vals)
16560 (setq vals (remove ":ETC" vals))
16561 (org-add-props (car vals) '(org-unrestricted t)))
16562 (if table (mapcar 'list vals) vals)))
16564 (defun org-property-previous-allowed-value (&optional _previous)
16565 "Switch to the next allowed value for this property."
16567 (org-property-next-allowed-value t))
16569 (defun org-property-next-allowed-value (&optional previous)
16570 "Switch to the next allowed value for this property."
16572 (unless (org-at-property-p)
16573 (user-error "Not at a property"))
16574 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16575 (key (match-string 2))
16576 (value (match-string 3))
16577 (allowed (or (org-property-get-allowed-values (point) key)
16578 (and (member value '("[ ]" "[-]" "[X]"))
16580 (heading (save-match-data (nth 4 (org-heading-components))))
16583 (user-error "Allowed values for this property have not been defined"))
16584 (when previous (setq allowed (reverse allowed)))
16585 (when (member value allowed)
16586 (setq nval (car (cdr (member value allowed)))))
16587 (setq nval (or nval (car allowed)))
16588 (when (equal nval value)
16589 (user-error "Only one allowed value for this property"))
16590 (org-at-property-p)
16591 (replace-match (concat " :" key ": " nval) t t)
16593 (beginning-of-line 1)
16594 (skip-chars-forward " \t")
16595 (when (equal prop org-effort-property)
16596 (org-refresh-property
16597 '((effort . identity)
16598 (effort-minutes . org-duration-string-to-minutes))
16600 (when (string= org-clock-current-task heading)
16601 (setq org-clock-effort nval)
16602 (org-clock-update-mode-line)))
16603 (run-hook-with-args 'org-property-changed-functions key nval)))
16605 (defun org-find-olp (path &optional this-buffer)
16606 "Return a marker pointing to the entry at outline path OLP.
16607 If anything goes wrong, throw an error.
16608 You can wrap this call to catch the error like this:
16610 (condition-case msg
16611 (org-mobile-locate-entry (match-string 4))
16612 (error (nth 1 msg)))
16614 The return value will then be either a string with the error message,
16615 or a marker if everything is OK.
16617 If THIS-BUFFER is set, the outline path does not contain a file,
16619 (let* ((file (if this-buffer buffer-file-name (pop path)))
16620 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16625 (unless buffer (error "File not found :%s" file))
16626 (with-current-buffer buffer
16627 (org-with-wide-buffer
16628 (goto-char (point-min))
16629 (dolist (heading path)
16630 (let ((re (format org-complex-heading-regexp-format
16631 (regexp-quote heading)))
16633 (while (re-search-forward re end t)
16634 (setq level (- (match-end 1) (match-beginning 1)))
16635 (when (and (>= level lmin) (<= level lmax))
16636 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16638 (error "Heading not found on level %d: %s" lmax heading))
16640 (error "Heading not unique on level %d: %s" lmax heading))
16642 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16643 (setq end (save-excursion (org-end-of-subtree t t)))))
16644 (when (org-at-heading-p)
16645 (point-marker))))))
16647 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16648 "Find node HEADING in BUFFER.
16649 Return a marker to the heading if it was found, or nil if not.
16650 If POS-ONLY is set, return just the position instead of a marker.
16652 The heading text must match exact, but it may have a TODO keyword,
16653 a priority cookie and tags in the standard locations."
16654 (with-current-buffer (or buffer (current-buffer))
16655 (org-with-wide-buffer
16656 (goto-char (point-min))
16657 (let (case-fold-search)
16658 (when (re-search-forward
16659 (format org-complex-heading-regexp-format
16660 (regexp-quote heading)) nil t)
16662 (match-beginning 0)
16663 (move-marker (make-marker) (match-beginning 0))))))))
16665 (defun org-find-exact-heading-in-directory (heading &optional dir)
16666 "Find Org node headline HEADING in all .org files in directory DIR.
16667 When the target headline is found, return a marker to this location."
16668 (let ((files (directory-files (or dir default-directory)
16669 t "\\`[^.#].*\\.org\\'"))
16672 (dolist (file files)
16673 (message "trying %s" file)
16674 (setq visiting (org-find-base-buffer-visiting file))
16675 (setq buffer (or visiting (find-file-noselect file)))
16676 (setq m (org-find-exact-headline-in-buffer
16678 (when (and (not m) (not visiting)) (kill-buffer buffer))
16679 (and m (throw 'found m))))))
16681 (defun org-find-entry-with-id (ident)
16682 "Locate the entry that contains the ID property with exact value IDENT.
16683 IDENT can be a string, a symbol or a number, this function will search for
16684 the string representation of it.
16685 Return the position where this entry starts, or nil if there is no such entry."
16686 (interactive "sID: ")
16688 ((stringp ident) ident)
16689 ((symbolp ident) (symbol-name ident))
16690 ((numberp ident) (number-to-string ident))
16691 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16692 (org-with-wide-buffer (org-find-property "ID" id))))
16696 (defvar org-last-changed-timestamp nil)
16697 (defvar org-last-inserted-timestamp nil
16698 "The last time stamp inserted with `org-insert-time-stamp'.")
16699 (defvar org-ts-what) ; dynamically scoped parameter
16701 (defun org-time-stamp (arg &optional inactive)
16702 "Prompt for a date/time and insert a time stamp.
16704 If the user specifies a time like HH:MM or if this command is
16705 called with at least one prefix argument, the time stamp contains
16706 the date and the time. Otherwise, only the date is included.
16708 All parts of a date not specified by the user are filled in from
16709 the timestamp at point, if any, or the current date/time
16712 If there is already a timestamp at the cursor, it is replaced.
16714 With two universal prefix arguments, insert an active timestamp
16715 with the current time without prompting the user.
16717 When called from lisp, the timestamp is inactive if INACTIVE is
16721 ((org-at-date-range-p t)
16722 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16723 ((org-at-timestamp-p t) (match-string 0))))
16724 ;; Default time is either the timestamp at point or today.
16725 ;; When entering a range, only the range start is considered.
16726 (default-time (if (not ts) (current-time)
16727 (apply #'encode-time (org-parse-time-string ts))))
16728 (default-input (and ts (org-get-compact-tod ts)))
16730 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16731 (match-string 0 ts)))
16733 org-end-time-was-given
16735 (and (if (equal arg '(16)) (current-time)
16736 ;; Preserve `this-command' and `last-command'.
16737 (let ((this-command this-command)
16738 (last-command last-command))
16740 arg 'totime nil nil default-time default-input
16744 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16745 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16747 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16749 ;; Make sure we're on a timestamp. When in the middle of a date
16750 ;; range, move arbitrarily to range end.
16751 (unless (org-at-timestamp-p t)
16752 (skip-chars-forward "-")
16753 (org-at-timestamp-p t))
16755 (setq org-last-changed-timestamp
16756 (org-insert-time-stamp
16757 time (or org-time-was-given arg)
16758 inactive nil nil (list org-end-time-was-given)))
16761 (insert " " repeater)
16762 (setq org-last-changed-timestamp
16763 (concat (substring org-last-inserted-timestamp 0 -1)
16764 " " repeater ">")))
16765 (message "Timestamp updated"))
16766 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16767 (t (org-insert-time-stamp
16768 time (or org-time-was-given arg) inactive nil nil
16769 (list org-end-time-was-given))))))
16771 ;; FIXME: can we use this for something else, like computing time differences?
16772 (defun org-get-compact-tod (s)
16773 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16774 (let* ((t1 (match-string 1 s))
16775 (h1 (string-to-number (match-string 2 s)))
16776 (m1 (string-to-number (match-string 3 s)))
16777 (t2 (and (match-end 4) (match-string 5 s)))
16778 (h2 (and t2 (string-to-number (match-string 6 s))))
16779 (m2 (and t2 (string-to-number (match-string 7 s))))
16783 (setq dh (- h2 h1) dm (- m2 m1))
16784 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16785 (concat t1 "+" (number-to-string dh)
16786 (and (/= 0 dm) (format ":%02d" dm)))))))
16788 (defun org-time-stamp-inactive (&optional arg)
16789 "Insert an inactive time stamp.
16790 An inactive time stamp is enclosed in square brackets instead of angle
16791 brackets. It is inactive in the sense that it does not trigger agenda entries,
16792 does not link to the calendar and cannot be changed with the S-cursor keys.
16793 So these are more for recording a certain time/date."
16795 (org-time-stamp arg 'inactive))
16797 (defvar org-date-ovl (make-overlay 1 1))
16798 (overlay-put org-date-ovl 'face 'org-date-selected)
16799 (delete-overlay org-date-ovl)
16801 (defvar org-ans1) ; dynamically scoped parameter
16802 (defvar org-ans2) ; dynamically scoped parameter
16804 (defvar org-plain-time-of-day-regexp) ; defined below
16806 (defvar org-overriding-default-time nil) ; dynamically scoped
16807 (defvar org-read-date-overlay nil)
16808 (defvar org-dcst nil) ; dynamically scoped
16809 (defvar org-read-date-history nil)
16810 (defvar org-read-date-final-answer nil)
16811 (defvar org-read-date-analyze-futurep nil)
16812 (defvar org-read-date-analyze-forced-year nil)
16813 (defvar org-read-date-inactive)
16815 (defvar org-read-date-minibuffer-local-map
16816 (let* ((map (make-sparse-keymap)))
16817 (set-keymap-parent map minibuffer-local-map)
16818 (org-defkey map (kbd ".")
16819 (lambda () (interactive)
16820 ;; Are we at the beginning of the prompt?
16821 (if (looking-back "^[^:]+: "
16822 (let ((inhibit-field-text-motion t))
16823 (line-beginning-position)))
16824 (org-eval-in-calendar '(calendar-goto-today))
16826 (org-defkey map (kbd "C-.")
16827 (lambda () (interactive)
16828 (org-eval-in-calendar '(calendar-goto-today))))
16829 (org-defkey map [(meta shift left)]
16830 (lambda () (interactive)
16831 (org-eval-in-calendar '(calendar-backward-month 1))))
16832 (org-defkey map [(meta shift right)]
16833 (lambda () (interactive)
16834 (org-eval-in-calendar '(calendar-forward-month 1))))
16835 (org-defkey map [(meta shift up)]
16836 (lambda () (interactive)
16837 (org-eval-in-calendar '(calendar-backward-year 1))))
16838 (org-defkey map [(meta shift down)]
16839 (lambda () (interactive)
16840 (org-eval-in-calendar '(calendar-forward-year 1))))
16841 (org-defkey map [?\e (shift left)]
16842 (lambda () (interactive)
16843 (org-eval-in-calendar '(calendar-backward-month 1))))
16844 (org-defkey map [?\e (shift right)]
16845 (lambda () (interactive)
16846 (org-eval-in-calendar '(calendar-forward-month 1))))
16847 (org-defkey map [?\e (shift up)]
16848 (lambda () (interactive)
16849 (org-eval-in-calendar '(calendar-backward-year 1))))
16850 (org-defkey map [?\e (shift down)]
16851 (lambda () (interactive)
16852 (org-eval-in-calendar '(calendar-forward-year 1))))
16853 (org-defkey map [(shift up)]
16854 (lambda () (interactive)
16855 (org-eval-in-calendar '(calendar-backward-week 1))))
16856 (org-defkey map [(shift down)]
16857 (lambda () (interactive)
16858 (org-eval-in-calendar '(calendar-forward-week 1))))
16859 (org-defkey map [(shift left)]
16860 (lambda () (interactive)
16861 (org-eval-in-calendar '(calendar-backward-day 1))))
16862 (org-defkey map [(shift right)]
16863 (lambda () (interactive)
16864 (org-eval-in-calendar '(calendar-forward-day 1))))
16865 (org-defkey map "!"
16866 (lambda () (interactive)
16867 (org-eval-in-calendar '(diary-view-entries))
16869 (org-defkey map ">"
16870 (lambda () (interactive)
16871 (org-eval-in-calendar '(calendar-scroll-left 1))))
16872 (org-defkey map "<"
16873 (lambda () (interactive)
16874 (org-eval-in-calendar '(calendar-scroll-right 1))))
16875 (org-defkey map "\C-v"
16876 (lambda () (interactive)
16877 (org-eval-in-calendar
16878 '(calendar-scroll-left-three-months 1))))
16879 (org-defkey map "\M-v"
16880 (lambda () (interactive)
16881 (org-eval-in-calendar
16882 '(calendar-scroll-right-three-months 1))))
16884 "Keymap for minibuffer commands when using `org-read-date'.")
16887 (defvar org-defdecode)
16888 (defvar org-with-time)
16890 (defvar calendar-setup) ; Dynamically scoped.
16891 (defun org-read-date (&optional with-time to-time from-string prompt
16892 default-time default-input inactive)
16893 "Read a date, possibly a time, and make things smooth for the user.
16894 The prompt will suggest to enter an ISO date, but you can also enter anything
16895 which will at least partially be understood by `parse-time-string'.
16896 Unrecognized parts of the date will default to the current day, month, year,
16897 hour and minute. If this command is called to replace a timestamp at point,
16898 or to enter the second timestamp of a range, the default time is taken
16899 from the existing stamp. Furthermore, the command prefers the future,
16900 so if you are giving a date where the year is not given, and the day-month
16901 combination is already past in the current year, it will assume you
16902 mean next year. For details, see the manual. A few examples:
16904 3-2-5 --> 2003-02-05
16905 feb 15 --> currentyear-02-15
16906 2/15 --> currentyear-02-15
16907 sep 12 9 --> 2009-09-12
16908 12:45 --> today 12:45
16909 22 sept 0:34 --> currentyear-09-22 0:34
16910 12 --> currentyear-currentmonth-12
16911 Fri --> nearest Friday after today
16912 -Tue --> last Tuesday
16915 Furthermore you can specify a relative date by giving, as the *first* thing
16916 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16917 change in days weeks, months, years.
16918 With a single plus or minus, the date is relative to today. With a double
16919 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16920 +4d --> four days from today
16921 +4 --> same as above
16922 +2w --> two weeks from today
16923 ++5 --> five days from default date
16925 The function understands only English month and weekday abbreviations.
16927 While prompting, a calendar is popped up - you can also select the
16928 date with the mouse (button 1). The calendar shows a period of three
16929 months. To scroll it to other months, use the keys `>' and `<'.
16930 If you don't like the calendar, turn it off with
16931 (setq org-read-date-popup-calendar nil)
16933 With optional argument TO-TIME, the date will immediately be converted
16934 to an internal time.
16935 With an optional argument WITH-TIME, the prompt will suggest to
16936 also insert a time. Note that when WITH-TIME is not set, you can
16937 still enter a time, and this function will inform the calling routine
16938 about this change. The calling routine may then choose to change the
16939 format used to insert the time stamp into the buffer to include the time.
16940 With optional argument FROM-STRING, read from this string instead from
16941 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16942 the time/date that is used for everything that is not specified by the
16944 (require 'parse-time)
16945 (let* ((org-with-time with-time)
16946 (org-time-stamp-rounding-minutes
16947 (if (equal org-with-time '(16))
16949 org-time-stamp-rounding-minutes))
16950 (org-dcst org-display-custom-times)
16951 (ct (org-current-time))
16952 (org-def (or org-overriding-default-time default-time ct))
16953 (org-defdecode (decode-time org-def))
16954 (cur-frame (selected-frame))
16955 (mouse-autoselect-window nil) ; Don't let the mouse jump
16957 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16958 (calendar-move-hook nil)
16959 (calendar-view-diary-initially-flag nil)
16960 (calendar-view-holidays-initially-flag nil)
16961 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16962 ;; Rationalize `org-def' and `org-defdecode', if required.
16963 (when (< (nth 2 org-defdecode) org-extend-today-until)
16964 (setf (nth 2 org-defdecode) -1)
16965 (setf (nth 1 org-defdecode) 59)
16966 (setq org-def (apply #'encode-time org-defdecode))
16967 (setq org-defdecode (decode-time org-def)))
16968 (let* ((timestr (format-time-string
16969 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16971 (prompt (concat (if prompt (concat prompt " ") "")
16972 (format "Date+time [%s]: " timestr))))
16974 (from-string (setq ans from-string))
16975 (org-read-date-popup-calendar
16977 (save-window-excursion
16979 (when (eq calendar-setup 'calendar-only)
16981 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16982 (select-frame cal-frame))
16983 (org-eval-in-calendar '(setq cursor-type nil) t)
16986 (calendar-forward-day (- (time-to-days org-def)
16987 (calendar-absolute-from-gregorian
16988 (calendar-current-date))))
16989 (org-eval-in-calendar nil t)
16990 (let* ((old-map (current-local-map))
16991 (map (copy-keymap calendar-mode-map))
16992 (minibuffer-local-map
16993 (copy-keymap org-read-date-minibuffer-local-map)))
16994 (org-defkey map (kbd "RET") 'org-calendar-select)
16995 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16996 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16999 (use-local-map map)
17000 (setq org-read-date-inactive inactive)
17001 (add-hook 'post-command-hook 'org-read-date-display)
17003 (read-string prompt
17005 'org-read-date-history
17007 ;; org-ans0: from prompt
17008 ;; org-ans1: from mouse click
17009 ;; org-ans2: from calendar motion
17011 (concat org-ans0 " " (or org-ans1 org-ans2))))
17012 (remove-hook 'post-command-hook 'org-read-date-display)
17013 (use-local-map old-map)
17014 (when org-read-date-overlay
17015 (delete-overlay org-read-date-overlay)
17016 (setq org-read-date-overlay nil)))))
17017 (bury-buffer "*Calendar*")
17019 (delete-frame cal-frame)
17020 (select-frame-set-input-focus cur-frame))))))
17022 (t ; Naked prompt only
17024 (setq ans (read-string prompt default-input
17025 'org-read-date-history timestr))
17026 (when org-read-date-overlay
17027 (delete-overlay org-read-date-overlay)
17028 (setq org-read-date-overlay nil))))))
17030 (setq final (org-read-date-analyze ans org-def org-defdecode))
17032 (when org-read-date-analyze-forced-year
17033 (message "Year was forced into %s"
17034 (if org-read-date-force-compatible-dates
17035 "compatible range (1970-2037)"
17036 "range representable on this machine"))
17039 ;; One round trip to get rid of 34th of August and stuff like that....
17040 (setq final (decode-time (apply 'encode-time final)))
17042 (setq org-read-date-final-answer ans)
17045 (apply 'encode-time final)
17046 (if (and (boundp 'org-time-was-given) org-time-was-given)
17047 (format "%04d-%02d-%02d %02d:%02d"
17048 (nth 5 final) (nth 4 final) (nth 3 final)
17049 (nth 2 final) (nth 1 final))
17050 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17052 (defun org-read-date-display ()
17053 "Display the current date prompt interpretation in the minibuffer."
17054 (when org-read-date-display-live
17055 (when org-read-date-overlay
17056 (delete-overlay org-read-date-overlay))
17057 (when (minibufferp (current-buffer))
17060 (while (not (equal (buffer-substring
17061 (max (point-min) (- (point) 4)) (point))
17064 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17065 " " (or org-ans1 org-ans2)))
17066 (org-end-time-was-given nil)
17067 (f (org-read-date-analyze ans org-def org-defdecode))
17069 org-time-stamp-custom-formats
17070 org-time-stamp-formats))
17071 (fmt (if (or org-with-time
17072 (and (boundp 'org-time-was-given) org-time-was-given))
17075 (txt (format-time-string fmt (apply 'encode-time f)))
17076 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17077 (txt (concat "=> " txt)))
17078 (when (and org-end-time-was-given
17079 (string-match org-plain-time-of-day-regexp txt))
17080 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17081 org-end-time-was-given
17082 (substring txt (match-end 0)))))
17083 (when org-read-date-analyze-futurep
17084 (setq txt (concat txt " (=>F)")))
17085 (setq org-read-date-overlay
17086 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17087 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17089 (defun org-read-date-analyze (ans def defdecode)
17090 "Analyze the combined answer of the date prompt."
17091 ;; FIXME: cleanup and comment
17092 ;; Pass `current-time' result to `decode-time' (instead of calling
17093 ;; without arguments) so that only `current-time' has to be
17094 ;; overriden in tests.
17095 (let ((org-def def)
17096 (org-defdecode defdecode)
17097 (nowdecode (decode-time (current-time)))
17098 delta deltan deltaw deltadef year month day
17099 hour minute second wday pm h2 m2 tl wday1
17100 iso-year iso-weekday iso-week iso-date futurep kill-year)
17101 (setq org-read-date-analyze-futurep nil
17102 org-read-date-analyze-forced-year nil)
17103 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17106 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17107 (setq ans (replace-match "" t t ans)
17109 deltaw (nth 1 delta)
17110 deltadef (nth 2 delta)))
17112 ;; Check if there is an iso week date in there. If yes, store the
17113 ;; info and postpone interpreting it until the rest of the parsing
17115 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17116 (setq iso-year (when (match-end 1)
17117 (org-small-year-to-year
17118 (string-to-number (match-string 1 ans))))
17119 iso-weekday (when (match-end 3)
17120 (string-to-number (match-string 3 ans)))
17121 iso-week (string-to-number (match-string 2 ans)))
17122 (setq ans (replace-match "" t t ans)))
17124 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17125 (when (string-match
17126 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17127 (setq year (if (match-end 2)
17128 (string-to-number (match-string 2 ans))
17129 (progn (setq kill-year t)
17130 (string-to-number (format-time-string "%Y"))))
17131 month (string-to-number (match-string 3 ans))
17132 day (string-to-number (match-string 4 ans)))
17133 (setq year (org-small-year-to-year year))
17134 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17137 ;; Help matching dotted european dates
17138 (when (string-match
17139 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17140 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17142 (string-to-number (format-time-string "%Y")))
17143 day (string-to-number (match-string 1 ans))
17144 month (string-to-number (match-string 2 ans))
17145 ans (replace-match (format "%04d-%02d-%02d" year month day)
17148 ;; Help matching american dates, like 5/30 or 5/30/7
17149 (when (string-match
17150 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17151 (setq year (if (match-end 4)
17152 (string-to-number (match-string 4 ans))
17153 (progn (setq kill-year t)
17154 (string-to-number (format-time-string "%Y"))))
17155 month (string-to-number (match-string 1 ans))
17156 day (string-to-number (match-string 2 ans)))
17157 (setq year (org-small-year-to-year year))
17158 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17160 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17161 ;; If there is a time with am/pm, and *no* time without it, we convert
17162 ;; so that matching will be successful.
17163 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17164 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17165 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17166 (setq hour (string-to-number (match-string 1 ans))
17167 minute (if (match-end 3)
17168 (string-to-number (match-string 3 ans))
17171 (string-to-char (downcase (match-string 4 ans)))))
17172 (if (and (= hour 12) (not pm))
17174 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17175 (setq ans (replace-match (format "%02d:%02d" hour minute)
17178 ;; Check if a time range is given as a duration
17179 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17180 (setq hour (string-to-number (match-string 1 ans))
17181 h2 (+ hour (string-to-number (match-string 3 ans)))
17182 minute (string-to-number (match-string 2 ans))
17183 m2 (+ minute (if (match-end 5) (string-to-number
17184 (match-string 5 ans))0)))
17185 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17186 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17189 ;; Check if there is a time range
17190 (when (boundp 'org-end-time-was-given)
17191 (setq org-time-was-given nil)
17192 (when (and (string-match org-plain-time-of-day-regexp ans)
17194 (setq org-end-time-was-given (match-string 8 ans))
17195 (setq ans (concat (substring ans 0 (match-beginning 7))
17196 (substring ans (match-end 7))))))
17198 (setq tl (parse-time-string ans)
17199 day (or (nth 3 tl) (nth 3 org-defdecode))
17202 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17203 ;; Day was specified. Make sure DAY+MONTH
17204 ;; combination happens in the future.
17207 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17208 (nth 4 nowdecode)))
17209 (t (nth 4 org-defdecode)))
17211 (cond ((and (not kill-year) (nth 5 tl)))
17212 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17213 ;; Month was guessed in the future and is at least
17214 ;; equal to NOWDECODE's. Fix year accordingly.
17216 (if (or (> month (nth 4 nowdecode))
17217 (>= day (nth 3 nowdecode)))
17219 (1+ (nth 5 nowdecode))))
17220 ;; Month was specified. Make sure MONTH+YEAR
17221 ;; combination happens in the future.
17224 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17225 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17226 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17227 (t (nth 5 nowdecode))))
17228 (t (nth 5 org-defdecode)))
17229 hour (or (nth 2 tl) (nth 2 org-defdecode))
17230 minute (or (nth 1 tl) (nth 1 org-defdecode))
17231 second (or (nth 0 tl) 0)
17234 (when (and (eq org-read-date-prefer-future 'time)
17235 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17236 (equal day (nth 3 nowdecode))
17237 (equal month (nth 4 nowdecode))
17238 (equal year (nth 5 nowdecode))
17240 (or (< (nth 2 tl) (nth 2 nowdecode))
17241 (and (= (nth 2 tl) (nth 2 nowdecode))
17243 (< (nth 1 tl) (nth 1 nowdecode)))))
17247 ;; Special date definitions below
17250 ;; There was an iso week
17253 (setq year (or iso-year year)
17254 day (or iso-weekday wday 1)
17255 wday nil ; to make sure that the trigger below does not match
17256 iso-date (calendar-gregorian-from-absolute
17257 (calendar-iso-to-absolute
17258 (list iso-week day year))))
17259 ; FIXME: Should we also push ISO weeks into the future?
17260 ; (when (and org-read-date-prefer-future
17262 ; (< (calendar-absolute-from-gregorian iso-date)
17263 ; (time-to-days (current-time))))
17264 ; (setq year (1+ year)
17265 ; iso-date (calendar-gregorian-from-absolute
17266 ; (calendar-iso-to-absolute
17267 ; (list iso-week day year)))))
17268 (setq month (car iso-date)
17269 year (nth 2 iso-date)
17270 day (nth 1 iso-date)))
17274 ;; Pass `current-time' result to `decode-time' (instead of
17275 ;; calling without arguments) so that only `current-time' has
17276 ;; to be overriden in tests.
17277 (let ((now (decode-time (current-time))))
17278 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17279 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17280 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17281 ((equal deltaw "m") (setq month (+ month deltan)))
17282 ((equal deltaw "y") (setq year (+ year deltan)))))
17283 ((and wday (not (nth 3 tl)))
17284 ;; Weekday was given, but no day, so pick that day in the week
17285 ;; on or after the derived date.
17286 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17287 (unless (equal wday wday1)
17288 (setq day (+ day (% (- wday wday1 -7) 7))))))
17289 (when (and (boundp 'org-time-was-given)
17291 (setq org-time-was-given t))
17292 (when (< year 100) (setq year (+ 2000 year)))
17293 ;; Check of the date is representable
17294 (if org-read-date-force-compatible-dates
17296 (when (< year 1970)
17297 (setq year 1970 org-read-date-analyze-forced-year t))
17298 (when (> year 2037)
17299 (setq year 2037 org-read-date-analyze-forced-year t)))
17300 (condition-case nil
17301 (ignore (encode-time second minute hour day month year))
17303 (setq year (nth 5 org-defdecode))
17304 (setq org-read-date-analyze-forced-year t))))
17305 (setq org-read-date-analyze-futurep futurep)
17306 (list second minute hour day month year)))
17308 (defvar parse-time-weekdays)
17309 (defun org-read-date-get-relative (s today default)
17310 "Check string S for special relative date string.
17311 TODAY and DEFAULT are internal times, for today and for a default.
17312 Return shift list (N what def-flag)
17313 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17314 N is the number of WHATs to shift.
17315 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17316 the DEFAULT date rather than TODAY."
17317 (require 'parse-time)
17321 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17323 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17324 "\\([ \t]\\|$\\)") s)
17325 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17326 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17327 (string-to-char (substring (match-string 1 s) -1))
17329 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17330 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17331 (what (if (match-end 3) (match-string 3 s) "d"))
17332 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17333 (date (if rel default today))
17334 (wday (nth 6 (decode-time date)))
17338 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17339 (when (= delta 0) (setq delta 7))
17341 (setq delta (- delta 7))
17342 (when (= delta 0) (setq delta -7)))
17343 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17344 (list delta "d" rel))
17345 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17347 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17348 "Turn a user-specified date into the internal representation.
17349 The internal representation needed by the calendar is (month day year).
17350 This is a wrapper to handle the brain-dead convention in calendar that
17351 user function argument order change dependent on argument order."
17352 (pcase calendar-date-style
17353 (`american (list arg1 arg2 arg3))
17354 (`european (list arg2 arg1 arg3))
17355 (`iso (list arg2 arg3 arg1))))
17357 (defun org-eval-in-calendar (form &optional keepdate)
17358 "Eval FORM in the calendar window and return to current window.
17359 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17360 (let ((sf (selected-frame))
17361 (sw (selected-window)))
17362 (select-window (get-buffer-window "*Calendar*" t))
17364 (when (and (not keepdate) (calendar-cursor-to-date))
17365 (let* ((date (calendar-cursor-to-date))
17366 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17367 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17368 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17370 (select-frame-set-input-focus sf)))
17372 (defun org-calendar-select ()
17373 "Return to `org-read-date' with the date currently selected.
17374 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17376 (when (calendar-cursor-to-date)
17377 (let* ((date (calendar-cursor-to-date))
17378 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17379 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17380 (when (active-minibuffer-window) (exit-minibuffer))))
17382 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17383 "Insert a date stamp for the date given by the internal TIME.
17384 See `format-time-string' for the format of TIME.
17385 WITH-HM means use the stamp format that includes the time of the day.
17386 INACTIVE means use square brackets instead of angular ones, so that the
17387 stamp will not contribute to the agenda.
17388 PRE and POST are optional strings to be inserted before and after the
17390 The command returns the inserted time stamp."
17391 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17393 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17394 (insert-before-markers (or pre ""))
17395 (when (listp extra)
17396 (setq extra (car extra))
17397 (if (and (stringp extra)
17398 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17399 (setq extra (format "-%02d:%02d"
17400 (string-to-number (match-string 1 extra))
17401 (string-to-number (match-string 2 extra))))
17404 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17405 (insert-before-markers (setq stamp (format-time-string fmt time)))
17406 (insert-before-markers (or post ""))
17407 (setq org-last-inserted-timestamp stamp)))
17409 (defun org-toggle-time-stamp-overlays ()
17410 "Toggle the use of custom time stamp formats."
17412 (setq org-display-custom-times (not org-display-custom-times))
17413 (unless org-display-custom-times
17414 (let ((p (point-min)) (bmp (buffer-modified-p)))
17415 (while (setq p (next-single-property-change p 'display))
17416 (when (and (get-text-property p 'display)
17417 (eq (get-text-property p 'face) 'org-date))
17418 (remove-text-properties
17419 p (setq p (next-single-property-change p 'display))
17421 (set-buffer-modified-p bmp)))
17422 (org-restart-font-lock)
17423 (setq org-table-may-need-update t)
17424 (if org-display-custom-times
17425 (message "Time stamps are overlaid with custom format")
17426 (message "Time stamp overlays removed")))
17428 (defun org-display-custom-time (beg end)
17429 "Overlay modified time stamp format over timestamp between BEG and END."
17430 (let* ((ts (buffer-substring beg end))
17431 t1 w1 with-hm tf time str w2 (off 0))
17433 (setq t1 (org-parse-time-string ts t))
17434 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17435 (setq off (- (match-end 0) (match-beginning 0)))))
17436 (setq end (- end off))
17437 (setq w1 (- end beg)
17438 with-hm (and (nth 1 t1) (nth 2 t1))
17439 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17440 time (org-fix-decoded-time t1)
17442 (format-time-string
17443 (substring tf 1 -1) (apply 'encode-time time))
17444 nil 'mouse-face 'highlight)
17447 (add-text-properties (1+ beg) (+ 2 beg)
17448 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17449 (put-text-property beg end 'display str)))
17451 (defun org-fix-decoded-time (time)
17452 "Set 0 instead of nil for the first 6 elements of time.
17453 Don't touch the rest."
17455 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17457 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17458 "Difference between TIMESTAMP-STRING and now in days.
17459 If SECONDS is non-nil, return the difference in seconds."
17460 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17461 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17462 (funcall fdiff (current-time)))))
17464 (defun org-deadline-close-p (timestamp-string &optional ndays)
17465 "Is the time in TIMESTAMP-STRING close to the current date?"
17466 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17467 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17468 (not (org-entry-is-done-p))))
17470 (defun org-get-wdays (ts &optional delay zero-delay)
17471 "Get the deadline lead time appropriate for timestring TS.
17472 When DELAY is non-nil, get the delay time for scheduled items
17473 instead of the deadline lead time. When ZERO-DELAY is non-nil
17474 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17475 don't try to find the delay cookie in the scheduled timestamp."
17476 (let ((tv (if delay org-scheduled-delay-days
17477 org-deadline-warning-days)))
17479 ((or (and delay (< tv 0))
17480 (and delay zero-delay (<= tv 0))
17481 (and (not delay) (<= tv 0)))
17482 ;; Enforce this value no matter what
17484 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17485 ;; lead time is specified.
17486 (floor (* (string-to-number (match-string 1 ts))
17487 (cdr (assoc (match-string 2 ts)
17488 '(("d" . 1) ("w" . 7)
17489 ("m" . 30.4) ("y" . 365.25)
17490 ("h" . 0.041667)))))))
17491 ;; go for the default.
17494 (defun org-calendar-select-mouse (ev)
17495 "Return to `org-read-date' with the date currently selected.
17496 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17498 (mouse-set-point ev)
17499 (when (calendar-cursor-to-date)
17500 (let* ((date (calendar-cursor-to-date))
17501 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17502 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17503 (when (active-minibuffer-window) (exit-minibuffer))))
17505 (defun org-check-deadlines (ndays)
17506 "Check if there are any deadlines due or past due.
17507 A deadline is considered due if it happens within `org-deadline-warning-days'
17508 days from today's date. If the deadline appears in an entry marked DONE,
17509 it is not shown. A numeric prefix argument NDAYS can be used to test that
17510 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17513 (let* ((org-warn-days
17515 ((equal ndays '(4)) 100000)
17516 (ndays (prefix-numeric-value ndays))
17517 (t (abs org-deadline-warning-days))))
17518 (case-fold-search nil)
17519 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17521 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17522 (message "%d deadlines past-due or due within %d days"
17523 (org-occur regexp nil callback)
17526 (defsubst org-re-timestamp (type)
17527 "Return a regexp for timestamp TYPE.
17528 Allowed values for TYPE are:
17530 all: all timestamps
17531 active: only active timestamps (<...>)
17532 inactive: only inactive timestamps ([...])
17533 scheduled: only scheduled timestamps
17534 deadline: only deadline timestamps
17535 closed: only closed time-stamps
17537 When TYPE is nil, fall back on returning a regexp that matches
17538 both scheduled and deadline timestamps."
17540 (all org-ts-regexp-both)
17541 (active org-ts-regexp)
17542 (inactive org-ts-regexp-inactive)
17543 (scheduled org-scheduled-time-regexp)
17544 (deadline org-deadline-time-regexp)
17545 (closed org-closed-time-regexp)
17548 (regexp-opt (list org-deadline-string org-scheduled-string))
17549 " *<\\([^>]+\\)>"))))
17551 (defun org-check-before-date (d)
17552 "Check if there are deadlines or scheduled entries before date D."
17553 (interactive (list (org-read-date)))
17554 (let* ((case-fold-search nil)
17555 (regexp (org-re-timestamp org-ts-type))
17556 (ts-type org-ts-type)
17559 (let ((match (match-string 1)))
17560 (and (if (memq ts-type '(active inactive all))
17561 (eq (org-element-type (save-excursion
17563 (org-element-context)))
17565 (org-at-planning-p))
17567 (org-time-string-to-time match)
17568 (org-time-string-to-time d)))))))
17569 (message "%d entries before %s"
17570 (org-occur regexp nil callback)
17573 (defun org-check-after-date (d)
17574 "Check if there are deadlines or scheduled entries after date D."
17575 (interactive (list (org-read-date)))
17576 (let* ((case-fold-search nil)
17577 (regexp (org-re-timestamp org-ts-type))
17578 (ts-type org-ts-type)
17581 (let ((match (match-string 1)))
17582 (and (if (memq ts-type '(active inactive all))
17583 (eq (org-element-type (save-excursion
17585 (org-element-context)))
17587 (org-at-planning-p))
17589 (org-time-string-to-time match)
17590 (org-time-string-to-time d))))))))
17591 (message "%d entries after %s"
17592 (org-occur regexp nil callback)
17595 (defun org-check-dates-range (start-date end-date)
17596 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17597 (interactive (list (org-read-date nil nil nil "Range starts")
17598 (org-read-date nil nil nil "Range end")))
17599 (let ((case-fold-search nil)
17600 (regexp (org-re-timestamp org-ts-type))
17602 (let ((type org-ts-type))
17604 (let ((match (match-string 1)))
17606 (if (memq type '(active inactive all))
17607 (eq (org-element-type (save-excursion
17609 (org-element-context)))
17611 (org-at-planning-p))
17613 (org-time-string-to-time match)
17614 (org-time-string-to-time start-date)))
17616 (org-time-string-to-time match)
17617 (org-time-string-to-time end-date))))))))
17618 (message "%d entries between %s and %s"
17619 (org-occur regexp nil callback) start-date end-date)))
17621 (defun org-evaluate-time-range (&optional to-buffer)
17622 "Evaluate a time range by computing the difference between start and end.
17623 Normally the result is just printed in the echo area, but with prefix arg
17624 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17625 If the time range is actually in a table, the result is inserted into the
17627 For time difference computation, a year is assumed to be exactly 365
17628 days in order to avoid rounding problems."
17631 (org-clock-update-time-maybe)
17633 (unless (org-at-date-range-p t)
17634 (goto-char (point-at-bol))
17635 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17636 (unless (org-at-date-range-p t)
17637 (user-error "Not at a time-stamp range, and none found in current line")))
17638 (let* ((ts1 (match-string 1))
17639 (ts2 (match-string 2))
17640 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17641 (match-end (match-end 0))
17642 (time1 (org-time-string-to-time ts1))
17643 (time2 (org-time-string-to-time ts2))
17644 (t1 (float-time time1))
17645 (t2 (float-time time2))
17646 (diff (abs (- t2 t1)))
17647 (negative (< (- t2 t1) 0))
17648 ;; (ys (floor (* 365 24 60 60)))
17651 (fy "%dy %dd %02d:%02d")
17653 (fd "%dd %02d:%02d")
17658 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17660 d (floor (/ diff ds)) diff (mod diff ds)
17661 h (floor (/ diff hs)) diff (mod diff hs)
17662 m (floor (/ diff 60)))
17663 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17665 d (floor (+ (/ diff ds) 0.5))
17667 (if (not to-buffer)
17668 (message "%s" (org-make-tdiff-string y d h m))
17669 (if (org-at-table-p)
17671 (goto-char match-end)
17673 (and (looking-at " *|") (goto-char (match-end 0))))
17674 (goto-char match-end))
17676 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17677 (replace-match ""))
17678 (when negative (insert " -"))
17679 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17680 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17681 (insert " " (format fh h m))))
17682 (when align (org-table-align))
17683 (message "Time difference inserted")))))
17685 (defun org-make-tdiff-string (y d h m)
17689 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17692 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17695 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17698 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17700 (apply 'format fmt (nreverse l))))
17702 (defun org-time-string-to-time (s &optional buffer pos)
17703 "Convert a timestamp string into internal time."
17704 (condition-case errdata
17705 (apply 'encode-time (org-parse-time-string s))
17706 (error (error "Bad timestamp `%s'%s\nError was: %s"
17707 s (if (not (and buffer pos))
17709 (format-message " at %d in buffer `%s'" pos buffer))
17712 (defun org-time-string-to-seconds (s)
17713 "Convert a timestamp string to a number of seconds."
17714 (float-time (org-time-string-to-time s)))
17716 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17718 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17719 "Convert time stamp S to an absolute day number.
17721 If DAYNR in non-nil, and there is a specifier for a cyclic time
17722 stamp, get the closest date to DAYNR. If PREFER is
17723 `past' (respectively `future') return a date past (respectively
17724 after) or equal to DAYNR.
17726 POS is the location of time stamp S, as a buffer position in
17729 Diary sexp timestamps are matched against DAYNR, when non-nil.
17730 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17733 ((string-match "\\`%%\\((.*)\\)" s)
17734 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17735 ;; only able to match individual dates. If it fails, raise an
17738 (org-diary-sexp-entry
17739 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17741 (signal 'org-diary-sexp-no-match (list s))))
17742 (daynr (org-closest-date s daynr prefer))
17744 (condition-case errdata
17745 (apply #'encode-time (org-parse-time-string s))
17746 (error (error "Bad timestamp `%s'%s\nError was: %s"
17748 (if (not (and buffer pos)) ""
17749 (format-message " at %d in buffer `%s'" pos buffer))
17750 (cdr errdata))))))))
17752 (defun org-days-to-iso-week (days)
17753 "Return the iso week number."
17755 (car (calendar-iso-from-absolute days)))
17757 (defun org-small-year-to-year (year)
17758 "Convert 2-digit years into 4-digit years.
17759 YEAR is expanded into one of the 30 next years, if possible, or
17760 into a past one. Any year larger than 99 is returned unchanged."
17761 (if (>= year 100) year
17762 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17763 (century (/ current 100))
17764 (offset (- year (% current 100))))
17765 (cond ((> offset 30) (+ (* (1- century) 100) year))
17766 ((> offset -70) (+ (* century 100) year))
17767 (t (+ (* (1+ century) 100) year))))))
17769 (defun org-time-from-absolute (d)
17770 "Return the time corresponding to date D.
17771 D may be an absolute day number, or a calendar-type list (month day year)."
17772 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17773 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17775 (defvar org-agenda-current-date)
17776 (defun org-calendar-holiday ()
17777 "List of holidays, for Diary display in Org mode."
17778 (require 'holidays)
17779 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17780 (and hl (mapconcat #'identity hl "; "))))
17782 (defun org-diary-sexp-entry (sexp entry d)
17783 "Process a SEXP diary ENTRY for date D."
17784 (require 'diary-lib)
17785 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17787 (let* ((sexp `(let ((entry ,entry)
17789 ,(car (read-from-string sexp))))
17790 (result (if calendar-debug-sexp (eval sexp)
17791 (condition-case nil
17795 (message "Bad sexp at line %d in %s: %s"
17797 (buffer-file-name) sexp)
17799 (cond ((stringp result) (split-string result "; "))
17800 ((and (consp result)
17801 (not (consp (cdr result)))
17802 (stringp (cdr result))) (cdr result))
17803 ((and (consp result)
17804 (stringp (car result))) result)
17807 (defun org-diary-to-ical-string (frombuf)
17808 "Get iCalendar entries from diary entries in buffer FROMBUF.
17809 This uses the icalendar.el library."
17810 (let* ((tmpdir temporary-file-directory)
17811 (tmpfile (make-temp-name
17812 (expand-file-name "orgics" tmpdir)))
17814 (with-current-buffer frombuf
17815 (icalendar-export-region (point-min) (point-max) tmpfile)
17816 (setq buf (find-buffer-visiting tmpfile))
17818 (goto-char (point-min))
17819 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17820 (setq b (match-beginning 0)))
17821 (goto-char (point-max))
17822 (when (re-search-backward "^END:VEVENT" nil t)
17823 (setq e (match-end 0)))
17824 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17826 (delete-file tmpfile)
17829 (defun org-closest-date (start current prefer)
17830 "Return closest date to CURRENT starting from START.
17832 CURRENT and START are both time stamps.
17834 When PREFER is `past', return a date that is either CURRENT or
17835 past. When PREFER is `future', return a date that is either
17838 Only time stamps with a repeater are modified. Any other time
17839 stamp stay unchanged. In any case, return value is an absolute
17841 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17842 ;; No repeater. Do not shift time stamp.
17843 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17844 (let ((value (string-to-number (match-string 1 start)))
17845 (type (match-string 2 start)))
17847 ;; Repeater with a 0-value is considered as void.
17848 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17849 (let* ((base (org-date-to-gregorian start))
17850 (target (org-date-to-gregorian current))
17851 (sday (calendar-absolute-from-gregorian base))
17852 (cday (calendar-absolute-from-gregorian target))
17854 ;; If START is already past CURRENT, just return START.
17855 (if (<= cday sday) sday
17856 ;; Compute closest date before (N1) and closest date past
17860 (let ((missing-hours
17861 (mod (+ (- (* 24 (- cday sday))
17862 (nth 2 (org-parse-time-string start)))
17863 org-extend-today-until)
17865 (setf n1 (if (= missing-hours 0) cday
17866 (- cday (1+ (/ missing-hours 24)))))
17867 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17869 (let ((value (if (equal type "w") (* 7 value) value)))
17870 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17871 (setf n2 (+ n1 value))))
17875 ;; Add N months to gregorian date D, i.e.,
17876 ;; a list (MONTH DAY YEAR). Return a valid
17878 (let ((m (+ (nth 0 d) n)))
17881 (+ (/ m 12) (nth 2 d))))))
17882 (months ; Complete months to TARGET.
17883 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17884 (- (nth 0 target) (nth 0 base))
17885 ;; If START's day is greater than
17886 ;; TARGET's, remove incomplete month.
17887 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17890 (before (funcall add-months base months)))
17891 (setf n1 (calendar-absolute-from-gregorian before))
17893 (calendar-absolute-from-gregorian
17894 (funcall add-months before value)))))
17896 (let* ((d (nth 1 base))
17899 (years ; Complete years to TARGET.
17900 (* (/ (- (nth 2 target)
17902 ;; If START's month and day are
17903 ;; greater than TARGET's, remove
17904 ;; incomplete year.
17905 (if (or (> (nth 0 target) m)
17906 (and (= (nth 0 target) m)
17907 (> (nth 1 target) d)))
17912 (before (list m d (+ y years))))
17913 (setf n1 (calendar-absolute-from-gregorian before))
17914 (setf n2 (calendar-absolute-from-gregorian
17915 (list m d (+ (nth 2 before) value)))))))
17916 ;; Handle PREFER parameter, if any.
17918 ((eq prefer 'past) (if (= cday n2) n2 n1))
17919 ((eq prefer 'future) (if (= cday n1) n1 n2))
17920 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17922 (defun org-date-to-gregorian (d)
17923 "Turn any specification of date D into a Gregorian date for the calendar."
17924 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17925 ((and (listp d) (= (length d) 3)) d)
17927 (let ((d (org-parse-time-string d)))
17928 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17929 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17931 (defun org-parse-time-string (s &optional nodefault)
17932 "Parse the standard Org time string.
17933 This should be a lot faster than the normal `parse-time-string'.
17934 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17935 hour and minute fields will be nil if not given."
17936 (cond ((string-match org-ts-regexp0 s)
17938 (when (or (match-beginning 8) (not nodefault))
17939 (string-to-number (or (match-string 8 s) "0")))
17940 (when (or (match-beginning 7) (not nodefault))
17941 (string-to-number (or (match-string 7 s) "0")))
17942 (string-to-number (match-string 4 s))
17943 (string-to-number (match-string 3 s))
17944 (string-to-number (match-string 2 s))
17946 ((string-match "^<[^>]+>$" s)
17947 (decode-time (seconds-to-time (org-matcher-time s))))
17948 (t (error "Not a standard Org time string: %s" s))))
17950 (defun org-timestamp-up (&optional arg)
17951 "Increase the date item at the cursor by one.
17952 If the cursor is on the year, change the year. If it is on the month,
17953 the day or the time, change that.
17954 With prefix ARG, change by that many units."
17956 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17958 (defun org-timestamp-down (&optional arg)
17959 "Decrease the date item at the cursor by one.
17960 If the cursor is on the year, change the year. If it is on the month,
17961 the day or the time, change that.
17962 With prefix ARG, change by that many units."
17964 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17966 (defun org-timestamp-up-day (&optional arg)
17967 "Increase the date in the time stamp by one day.
17968 With prefix ARG, change that many days."
17970 (if (and (not (org-at-timestamp-p t))
17971 (org-at-heading-p))
17973 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17975 (defun org-timestamp-down-day (&optional arg)
17976 "Decrease the date in the time stamp by one day.
17977 With prefix ARG, change that many days."
17979 (if (and (not (org-at-timestamp-p t))
17980 (org-at-heading-p))
17982 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17984 (defun org-at-timestamp-p (&optional inactive-ok)
17985 "Non-nil if point is inside a timestamp.
17987 When optional argument INACTIVE-OK is non-nil, also consider
17988 inactive timestamps.
17990 When this function returns a non-nil value, match data is set
17991 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17994 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17996 (ans (or (looking-at tsr)
17998 (skip-chars-backward "^[<\n\r\t")
17999 (when (> (point) (point-min)) (backward-char 1))
18000 (and (looking-at tsr)
18001 (> (- (match-end 0) pos) -1))))))
18003 (boundp 'org-ts-what)
18006 ((= pos (match-beginning 0)) 'bracket)
18007 ;; Point is considered to be "on the bracket" whether
18008 ;; it's really on it or right after it.
18009 ((= pos (1- (match-end 0))) 'bracket)
18010 ((= pos (match-end 0)) 'after)
18011 ((org-pos-in-match-range pos 2) 'year)
18012 ((org-pos-in-match-range pos 3) 'month)
18013 ((org-pos-in-match-range pos 7) 'hour)
18014 ((org-pos-in-match-range pos 8) 'minute)
18015 ((or (org-pos-in-match-range pos 4)
18016 (org-pos-in-match-range pos 5)) 'day)
18017 ((and (> pos (or (match-end 8) (match-end 5)))
18018 (< pos (match-end 0)))
18019 (- pos (or (match-end 8) (match-end 5))))
18023 (defun org-toggle-timestamp-type ()
18024 "Toggle the type (<active> or [inactive]) of a time stamp."
18026 (when (org-at-timestamp-p t)
18027 (let ((beg (match-beginning 0)) (end (match-end 0))
18028 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18031 (while (re-search-forward "[][<>]" end t)
18032 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18034 (message "Timestamp is now %sactive"
18035 (if (equal (char-after beg) ?<) "" "in")))))
18037 (defun org-at-clock-log-p nil
18038 "Is the cursor on the clock log line?"
18040 (beginning-of-line)
18041 (looking-at org-clock-line-re)))
18043 (defvar org-clock-history) ; defined in org-clock.el
18044 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18045 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18046 "Change the date in the time stamp at point.
18047 The date will be changed by N times WHAT. WHAT can be `day', `month',
18048 `year', `minute', `second'. If WHAT is not given, the cursor position
18049 in the timestamp determines what will be changed.
18050 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18051 (let ((origin (point)) origin-cat
18053 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18056 ts time time0 fixnext clrgx)
18057 (unless (org-at-timestamp-p t)
18058 (user-error "Not at a timestamp"))
18059 (if (and (not what) (eq org-ts-what 'bracket))
18060 (org-toggle-timestamp-type)
18061 ;; Point isn't on brackets. Remember the part of the time-stamp
18062 ;; the point was in. Indeed, size of time-stamps may change,
18063 ;; but point must be kept in the same category nonetheless.
18064 (setq origin-cat org-ts-what)
18065 (when (and (not what) (not (eq org-ts-what 'day))
18066 org-display-custom-times
18067 (get-text-property (point) 'display)
18068 (not (get-text-property (1- (point)) 'display)))
18069 (setq org-ts-what 'day))
18070 (setq org-ts-what (or what org-ts-what)
18071 inactive (= (char-after (match-beginning 0)) ?\[)
18072 ts (match-string 0))
18074 (when (string-match
18075 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18077 (setq extra (match-string 1 ts))
18078 (when suppress-tmp-delay
18079 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18080 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18082 (setq time0 (org-parse-time-string ts))
18084 (eq org-ts-what 'minute)
18085 (not current-prefix-arg))
18086 ;; This looks like s-up and s-down. Change by one rounding step.
18087 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18088 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18089 (setcar (cdr time0) (+ (nth 1 time0)
18090 (if (> n 0) (- rem) (- dm rem))))))
18092 (apply #'encode-time
18094 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18095 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18096 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18097 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18098 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18100 (when (and (member org-ts-what '(hour minute))
18102 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18103 (setq extra (org-modify-ts-extra
18105 (if (eq org-ts-what 'hour) 2 5)
18107 (when (integerp org-ts-what)
18108 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18109 (when (eq what 'calendar)
18110 (let ((cal-date (org-get-date-from-calendar)))
18111 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18112 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18113 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18114 (setcar time0 (or (car time0) 0))
18115 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18116 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18117 (setq time (apply 'encode-time time0))))
18118 ;; Insert the new time-stamp, and ensure point stays in the same
18119 ;; category as before (i.e. not after the last position in that
18121 (let ((pos (point)))
18122 ;; Stay before inserted string. `save-excursion' is of no use.
18123 (setq org-last-changed-timestamp
18124 (org-insert-time-stamp time with-hm inactive nil nil extra))
18127 (looking-at org-ts-regexp3)
18130 ;; `day' category ends before `hour' if any, or at the end
18131 ;; of the day name.
18132 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18133 (`hour (min (match-end 7) origin))
18134 (`minute (min (1- (match-end 8)) origin))
18135 ((pred integerp) (min (1- (match-end 0)) origin))
18136 ;; Point was right after the time-stamp. However, the
18137 ;; time-stamp length might have changed, so refer to
18138 ;; (match-end 0) instead.
18139 (`after (match-end 0))
18140 ;; `year' and `month' have both fixed size: point couldn't
18141 ;; have moved into another part.
18143 ;; Update clock if on a CLOCK line.
18144 (org-clock-update-time-maybe)
18145 ;; Maybe adjust the closest clock in `org-clock-history'
18146 (when org-clock-adjust-closest
18147 (if (not (and (org-at-clock-log-p)
18148 (< 1 (length (delq nil (mapcar 'marker-position
18149 org-clock-history))))))
18150 (message "No clock to adjust")
18151 (cond ((save-excursion ; fix previous clock?
18152 (re-search-backward org-ts-regexp0 nil t)
18153 (looking-back (concat org-clock-string " \\[")
18154 (line-beginning-position)))
18155 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18156 ((save-excursion ; fix next clock?
18157 (re-search-backward org-ts-regexp0 nil t)
18158 (looking-at (concat org-ts-regexp0 "\\] =>")))
18159 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18160 (save-window-excursion
18161 ;; Find closest clock to point, adjust the previous/next one in history
18162 (let* ((p (save-excursion (org-back-to-heading t)))
18163 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18165 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18166 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18168 (message "No clock to adjust")
18170 (org-goto-marker-or-bmk clfixpos)
18172 (when (re-search-forward clrgx nil t)
18173 (goto-char (match-beginning 1))
18174 (let (org-clock-adjust-closest)
18175 (org-timestamp-change n org-ts-what updown))
18176 (message "Clock adjusted in %s for heading: %s"
18177 (file-name-nondirectory (buffer-file-name))
18178 (org-get-heading t t)))))))))
18179 ;; Try to recenter the calendar window, if any.
18180 (when (and org-calendar-follow-timestamp-change
18181 (get-buffer-window "*Calendar*" t)
18182 (memq org-ts-what '(day month year)))
18183 (org-recenter-calendar (time-to-days time))))))
18185 (defun org-modify-ts-extra (s pos n dm)
18186 "Change the different parts of the lead-time and repeat fields in timestamp."
18187 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18189 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18191 ((or (org-pos-in-match-range pos 2)
18192 (org-pos-in-match-range pos 3))
18193 (setq m (string-to-number (match-string 3 s))
18194 h (string-to-number (match-string 2 s)))
18195 (if (org-pos-in-match-range pos 2)
18197 (setq n (* dm (with-no-warnings (signum n))))
18198 (unless (= 0 (setq rem (% m dm)))
18199 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18201 (when (< m 0) (setq m (+ m 60) h (1- h)))
18202 (when (> m 59) (setq m (- m 60) h (1+ h)))
18203 (setq h (mod h 24))
18204 (setq ng 1 new (format "-%02d:%02d" h m)))
18205 ((org-pos-in-match-range pos 6)
18206 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18207 ((org-pos-in-match-range pos 5)
18208 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18210 ((org-pos-in-match-range pos 9)
18211 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18212 ((org-pos-in-match-range pos 8)
18213 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18217 (substring s 0 (match-beginning ng))
18219 (substring s (match-end ng))))))
18222 (defun org-recenter-calendar (d)
18223 "If the calendar is visible, recenter it to date D."
18224 (let ((cwin (get-buffer-window "*Calendar*" t)))
18226 (let ((calendar-move-hook nil))
18227 (with-selected-window cwin
18228 (calendar-goto-date
18229 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18231 (defun org-goto-calendar (&optional arg)
18232 "Go to the Emacs calendar at the current date.
18233 If there is a time stamp in the current line, go to that date.
18234 A prefix ARG can be used to force the current date."
18236 (let ((tsr org-ts-regexp) diff
18237 (calendar-move-hook nil)
18238 (calendar-view-holidays-initially-flag nil)
18239 (calendar-view-diary-initially-flag nil))
18240 (when (or (org-at-timestamp-p)
18242 (beginning-of-line 1)
18243 (looking-at (concat ".*" tsr))))
18244 (let ((d1 (time-to-days (current-time)))
18246 (org-time-string-to-time (match-string 1)))))
18247 (setq diff (- d2 d1))))
18249 (calendar-goto-today)
18250 (when (and diff (not arg)) (calendar-forward-day diff))))
18252 (defun org-get-date-from-calendar ()
18253 "Return a list (month day year) of date at point in calendar."
18254 (with-current-buffer "*Calendar*"
18256 (calendar-cursor-to-date))))
18258 (defun org-date-from-calendar ()
18259 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18260 If there is already a time stamp at the cursor position, update it."
18262 (if (org-at-timestamp-p t)
18263 (org-timestamp-change 0 'calendar)
18264 (let ((cal-date (org-get-date-from-calendar)))
18265 (org-insert-time-stamp
18266 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18268 (defcustom org-effort-durations
18272 ("w" . ,(* 60 8 5))
18273 ("m" . ,(* 60 8 5 4))
18274 ("y" . ,(* 60 8 5 40)))
18275 "Conversion factor to minutes for an effort modifier.
18277 Each entry has the form (MODIFIER . MINUTES).
18279 In an effort string, a number followed by MODIFIER is multiplied
18280 by the specified number of MINUTES to obtain an effort in
18283 For example, if the value of this variable is ((\"hours\" . 60)), then an
18284 effort string \"2hours\" is equivalent to 120 minutes."
18287 :package-version '(Org . "8.3")
18288 :type '(alist :key-type (string :tag "Modifier")
18289 :value-type (number :tag "Minutes")))
18291 (defun org-minutes-to-clocksum-string (m)
18292 "Format number of minutes as a clocksum string.
18293 The format is determined by `org-time-clocksum-format',
18294 `org-time-clocksum-use-fractional' and
18295 `org-time-clocksum-fractional-format' and
18296 `org-time-clocksum-use-effort-durations'."
18297 (let ((clocksum "")
18298 (m (round m)) ; Don't allow fractions of minutes
18300 (setq h (if org-time-clocksum-use-effort-durations
18301 (cdr (assoc "h" org-effort-durations)) 60)
18302 d (if org-time-clocksum-use-effort-durations
18303 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18304 w (if org-time-clocksum-use-effort-durations
18305 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18306 mo (if org-time-clocksum-use-effort-durations
18307 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18308 y (if org-time-clocksum-use-effort-durations
18309 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18310 ;; fractional format
18311 (if org-time-clocksum-use-fractional
18313 ;; single format string
18314 ((stringp org-time-clocksum-fractional-format)
18315 (format org-time-clocksum-fractional-format (/ m (float h))))
18316 ;; choice of fractional formats for different time units
18317 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18318 (> (/ (truncate m) (* y d h)) 0))
18319 (format fmt (/ m (* y d (float h)))))
18320 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18321 (> (/ (truncate m) (* mo d h)) 0))
18322 (format fmt (/ m (* mo d (float h)))))
18323 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18324 (> (/ (truncate m) (* w d h)) 0))
18325 (format fmt (/ m (* w d (float h)))))
18326 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18327 (> (/ (truncate m) (* d h)) 0))
18328 (format fmt (/ m (* d (float h)))))
18329 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18330 (> (/ (truncate m) h) 0))
18331 (format fmt (/ m (float h))))
18332 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18334 ;; fall back to smallest time unit with a format
18335 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18336 (format fmt (/ m (float h))))
18337 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18338 (format fmt (/ m (* d (float h)))))
18339 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18340 (format fmt (/ m (* w d (float h)))))
18341 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18342 (format fmt (/ m (* mo d (float h)))))
18343 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18344 (format fmt (/ m (* y d (float h))))))
18345 ;; standard (non-fractional) format, with single format string
18346 (if (stringp org-time-clocksum-format)
18347 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18348 ;; separate formats components
18349 (and (setq fmt (plist-get org-time-clocksum-format :years))
18350 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18351 (plist-get org-time-clocksum-format :require-years))
18352 (setq clocksum (concat clocksum (format fmt n))
18353 m (- m (* n y d h))))
18354 (and (setq fmt (plist-get org-time-clocksum-format :months))
18355 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18356 (plist-get org-time-clocksum-format :require-months))
18357 (setq clocksum (concat clocksum (format fmt n))
18358 m (- m (* n mo d h))))
18359 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18360 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18361 (plist-get org-time-clocksum-format :require-weeks))
18362 (setq clocksum (concat clocksum (format fmt n))
18363 m (- m (* n w d h))))
18364 (and (setq fmt (plist-get org-time-clocksum-format :days))
18365 (or (> (setq n (/ (truncate m) (* d h))) 0)
18366 (plist-get org-time-clocksum-format :require-days))
18367 (setq clocksum (concat clocksum (format fmt n))
18368 m (- m (* n d h))))
18369 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18370 (or (> (setq n (/ (truncate m) h)) 0)
18371 (plist-get org-time-clocksum-format :require-hours))
18372 (setq clocksum (concat clocksum (format fmt n))
18374 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18375 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18376 (setq clocksum (concat clocksum (format fmt m))))
18377 ;; return formatted time duration
18380 (defun org-hours-to-clocksum-string (n)
18381 (org-minutes-to-clocksum-string (* n 60)))
18383 (defun org-hh:mm-string-to-minutes (s)
18384 "Convert a string H:MM to a number of minutes.
18385 If the string is just a number, interpret it as minutes.
18386 In fact, the first hh:mm or number in the string will be taken,
18387 there can be extra stuff in the string.
18388 If no number is found, the return value is 0."
18391 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18392 (+ (* (string-to-number (match-string 1 s)) 60)
18393 (string-to-number (match-string 2 s))))
18394 ((string-match "\\([0-9]+\\)" s)
18395 (string-to-number (match-string 1 s)))
18398 (defcustom org-image-actual-width t
18399 "Should we use the actual width of images when inlining them?
18401 When set to t, always use the image width.
18403 When set to a number, use imagemagick (when available) to set
18404 the image's width to this value.
18406 When set to a number in a list, try to get the width from any
18407 #+ATTR.* keyword if it matches a width specification like
18409 #+ATTR_HTML: :width 300px
18411 and fall back on that number if none is found.
18413 When set to nil, try to get the width from an #+ATTR.* keyword
18414 and fall back on the original width if none is found.
18416 This requires Emacs >= 24.1, build with imagemagick support."
18417 :group 'org-appearance
18419 :package-version '(Org . "8.0")
18421 (const :tag "Use the image width" t)
18422 (integer :tag "Use a number of pixels")
18423 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18424 (const :tag "Use #+ATTR* or don't resize" nil)))
18426 (defcustom org-agenda-inhibit-startup nil
18427 "Inhibit startup when preparing agenda buffers.
18428 When this variable is t, the initialization of the Org agenda
18429 buffers is inhibited: e.g. the visibility state is not set, the
18430 tables are not re-aligned, etc."
18433 :group 'org-agenda)
18435 (defcustom org-agenda-ignore-properties nil
18436 "Avoid updating text properties when building the agenda.
18437 Properties are used to prepare buffers for effort estimates,
18438 appointments, statistics and subtree-local categories.
18439 If you don't use these in the agenda, you can add them to this
18440 list and agenda building will be a bit faster.
18441 The value is a list, with zero or more of the symbols `effort', `appt',
18442 `stats' or `category'."
18443 :type '(set :greedy t
18449 :package-version '(Org . "8.3")
18450 :group 'org-agenda)
18452 (defun org-duration-string-to-minutes (s &optional output-to-string)
18453 "Convert a duration string S to minutes.
18455 A bare number is interpreted as minutes, modifiers can be set by
18456 customizing `org-effort-durations' (which see).
18458 Entries containing a colon are interpreted as H:MM by
18459 `org-hh:mm-string-to-minutes'."
18461 (re (concat "\\([0-9.]+\\) *\\("
18462 (regexp-opt (mapcar 'car org-effort-durations))
18464 (while (string-match re s)
18465 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18466 (string-to-number (match-string 1 s))))
18467 (setq s (replace-match "" nil t s)))
18468 (setq result (floor result))
18469 (cl-incf result (org-hh:mm-string-to-minutes s))
18470 (if output-to-string (number-to-string result) result)))
18474 (defun org-save-all-org-buffers ()
18475 "Save all Org buffers without user confirmation."
18477 (message "Saving all Org buffers...")
18478 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18479 (when (featurep 'org-id) (org-id-locations-save))
18480 (message "Saving all Org buffers... done"))
18482 (defun org-revert-all-org-buffers ()
18483 "Revert all Org buffers.
18484 Prompt for confirmation when there are unsaved changes.
18485 Be sure you know what you are doing before letting this function
18486 overwrite your changes.
18488 This function is useful in a setup where one tracks org files
18489 with a version control system, to revert on one machine after pulling
18490 changes from another. I believe the procedure must be like this:
18492 1. M-x org-save-all-org-buffers
18493 2. Pull changes from the other machine, resolve conflicts
18494 3. M-x org-revert-all-org-buffers"
18496 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18497 (user-error "Abort"))
18499 (save-window-excursion
18500 (dolist (b (buffer-list))
18501 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18502 (with-current-buffer b buffer-file-name))
18503 (pop-to-buffer-same-window b)
18504 (revert-buffer t 'no-confirm)))
18505 (when (and (featurep 'org-id) org-id-track-globally)
18506 (org-id-locations-load)))))
18511 (defun org-switchb (&optional arg)
18512 "Switch between Org buffers.
18514 With `\\[universal-argument]' prefix, restrict available buffers to files.
18516 With `\\[universal-argument] \\[universal-argument]' \
18517 prefix, restrict available buffers to agenda files."
18519 (let ((blist (org-buffer-list
18520 (cond ((equal arg '(4)) 'files)
18521 ((equal arg '(16)) 'agenda)))))
18522 (pop-to-buffer-same-window
18523 (completing-read "Org buffer: "
18524 (mapcar #'list (mapcar #'buffer-name blist))
18527 (defun org-buffer-list (&optional predicate exclude-tmp)
18528 "Return a list of Org buffers.
18529 PREDICATE can be `export', `files' or `agenda'.
18531 export restrict the list to Export buffers.
18532 files restrict the list to buffers visiting Org files.
18533 agenda restrict the list to buffers visiting agenda files.
18535 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18537 (agenda-files (and (eq predicate 'agenda)
18538 (mapcar 'file-truename (org-agenda-files t))))
18541 ((eq predicate 'files)
18542 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18543 ((eq predicate 'export)
18544 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18545 ((eq predicate 'agenda)
18547 (with-current-buffer b
18548 (and (derived-mode-p 'org-mode)
18549 (setq bfn (buffer-file-name b))
18550 (member (file-truename bfn) agenda-files)))))
18551 (t (lambda (b) (with-current-buffer b
18552 (or (derived-mode-p 'org-mode)
18553 (string-match "\\*Org .*Export"
18554 (buffer-name b)))))))))
18558 (if (and (funcall filter b)
18559 (or (not exclude-tmp)
18560 (not (string-match "tmp" (buffer-name b)))))
18565 (defun org-agenda-files (&optional unrestricted archives)
18566 "Get the list of agenda files.
18567 Optional UNRESTRICTED means return the full list even if a restriction
18568 is currently in place.
18569 When ARCHIVES is t, include all archive files that are really being
18570 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18571 `org-agenda-archives-mode' is t."
18574 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18575 ((stringp org-agenda-files) (org-read-agenda-file-list))
18576 ((listp org-agenda-files) org-agenda-files)
18577 (t (error "Invalid value of `org-agenda-files'")))))
18578 (setq files (apply 'append
18579 (mapcar (lambda (f)
18580 (if (file-directory-p f)
18582 f t org-agenda-file-regexp)
18585 (when org-agenda-skip-unavailable-files
18586 (setq files (delq nil
18589 (and (file-readable-p file) file)))
18591 (when (or (eq archives t)
18592 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18593 (setq files (org-add-archive-files files)))
18596 (defun org-agenda-file-p (&optional file)
18597 "Return non-nil, if FILE is an agenda file.
18598 If FILE is omitted, use the file associated with the current
18600 (let ((fname (or file (buffer-file-name))))
18602 (member (file-truename fname)
18603 (mapcar #'file-truename (org-agenda-files t))))))
18605 (defun org-edit-agenda-file-list ()
18606 "Edit the list of agenda files.
18607 Depending on setup, this either uses customize to edit the variable
18608 `org-agenda-files', or it visits the file that is holding the list. In the
18609 latter case, the buffer is set up in a way that saving it automatically kills
18610 the buffer and restores the previous window configuration."
18612 (if (stringp org-agenda-files)
18613 (let ((cw (current-window-configuration)))
18614 (find-file org-agenda-files)
18615 (setq-local org-window-configuration cw)
18616 (add-hook 'after-save-hook
18618 (set-window-configuration
18619 (prog1 org-window-configuration
18620 (kill-buffer (current-buffer))))
18621 (org-install-agenda-files-menu)
18622 (message "New agenda file list installed"))
18624 (message "%s" (substitute-command-keys
18625 "Edit list and finish with \\[save-buffer]")))
18626 (customize-variable 'org-agenda-files)))
18628 (defun org-store-new-agenda-file-list (list)
18629 "Set new value for the agenda file list and save it correctly."
18630 (if (stringp org-agenda-files)
18631 (let ((fe (org-read-agenda-file-list t)) b u)
18632 (while (setq b (find-buffer-visiting org-agenda-files))
18634 (with-temp-file org-agenda-files
18637 (lambda (f) ;; Keep un-expanded entries.
18638 (if (setq u (assoc f fe))
18643 (let ((org-mode-hook nil) (org-inhibit-startup t)
18644 (org-insert-mode-line-in-empty-file nil))
18645 (setq org-agenda-files list)
18646 (customize-save-variable 'org-agenda-files org-agenda-files))))
18648 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18649 "Read the list of agenda files from a file.
18650 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18651 filenames, used by `org-store-new-agenda-file-list' to write back
18652 un-expanded file names."
18653 (when (file-directory-p org-agenda-files)
18654 (error "`org-agenda-files' cannot be a single directory"))
18655 (when (stringp org-agenda-files)
18657 (insert-file-contents org-agenda-files)
18660 (let ((e (expand-file-name (substitute-in-file-name f)
18662 (if pair-with-expansion
18665 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18668 (defun org-cycle-agenda-files ()
18669 "Cycle through the files in `org-agenda-files'.
18670 If the current buffer visits an agenda file, find the next one in the list.
18671 If the current buffer does not, find the first agenda file."
18673 (let* ((fs (or (org-agenda-files t)
18674 (user-error "No agenda files")))
18675 (files (copy-sequence fs))
18676 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18679 (while (and (setq file (pop files))
18680 (not (equal (file-truename file) tcf)))))
18681 (find-file (car (or files fs)))
18682 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18684 (defun org-agenda-file-to-front (&optional to-end)
18685 "Move/add the current file to the top of the agenda file list.
18686 If the file is not present in the list, it is added to the front. If it is
18687 present, it is moved there. With optional argument TO-END, add/move to the
18690 (let ((org-agenda-skip-unavailable-files nil)
18691 (file-alist (mapcar (lambda (x)
18692 (cons (file-truename x) x))
18693 (org-agenda-files t)))
18694 (ctf (file-truename
18695 (or buffer-file-name
18696 (user-error "Please save the current buffer to a file"))))
18698 (setq x (assoc ctf file-alist) had x)
18700 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18702 (setq file-alist (append (delq x file-alist) (list x)))
18703 (setq file-alist (cons x (delq x file-alist))))
18704 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18705 (org-install-agenda-files-menu)
18706 (message "File %s to %s of agenda file list"
18707 (if had "moved" "added") (if to-end "end" "front"))))
18709 (defun org-remove-file (&optional file)
18710 "Remove current file from the list of files in variable `org-agenda-files'.
18711 These are the files which are being checked for agenda entries.
18712 Optional argument FILE means use this file instead of the current."
18714 (let* ((org-agenda-skip-unavailable-files nil)
18715 (file (or file buffer-file-name
18716 (user-error "Current buffer does not visit a file")))
18717 (true-file (file-truename file))
18718 (afile (abbreviate-file-name file))
18719 (files (delq nil (mapcar
18721 (unless (equal true-file
18724 (org-agenda-files t)))))
18725 (if (not (= (length files) (length (org-agenda-files t))))
18727 (org-store-new-agenda-file-list files)
18728 (org-install-agenda-files-menu)
18729 (message "Removed from Org Agenda list: %s" afile))
18730 (message "File was not in list: %s (not removed)" afile))))
18732 (defun org-file-menu-entry (file)
18733 (vector file (list 'find-file file) t))
18735 (defun org-check-agenda-file (file)
18736 "Make sure FILE exists. If not, ask user what to do."
18737 (unless (file-exists-p file)
18738 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18739 (abbreviate-file-name file))
18740 (let ((r (downcase (read-char-exclusive))))
18743 (org-remove-file file)
18744 (throw 'nextfile t))
18745 (t (user-error "Abort"))))))
18747 (defun org-get-agenda-file-buffer (file)
18748 "Get an agenda buffer visiting FILE.
18749 If the buffer needs to be created, add it to the list of buffers
18750 which might be released later."
18751 (let ((buf (org-find-base-buffer-visiting file)))
18753 buf ; just return it
18754 ;; Make a new buffer and remember it
18755 (setq buf (find-file-noselect file))
18756 (when buf (push buf org-agenda-new-buffers))
18759 (defun org-release-buffers (blist)
18760 "Release all buffers in list, asking the user for confirmation when needed.
18761 When a buffer is unmodified, it is just killed. When modified, it is saved
18762 \(if the user agrees) and then killed."
18764 (dolist (buf blist)
18765 (setq file (buffer-file-name buf))
18766 (when (and (buffer-modified-p buf)
18768 (y-or-n-p (format "Save file %s? " file)))
18769 (with-current-buffer buf (save-buffer)))
18770 (kill-buffer buf))))
18772 (defun org-agenda-prepare-buffers (files)
18773 "Create buffers for all agenda files, protect archived trees and comments."
18775 (let ((pa '(:org-archived t))
18776 (pc '(:org-comment t))
18777 (pall '(:org-archived t :org-comment t))
18778 (inhibit-read-only t)
18779 (org-inhibit-startup org-agenda-inhibit-startup)
18780 (rea (concat ":" org-archive-tag ":"))
18782 (setq org-tag-alist-for-agenda nil
18783 org-tag-groups-alist-for-agenda nil)
18786 (dolist (file files)
18790 (org-check-agenda-file file)
18791 (set-buffer (org-get-agenda-file-buffer file)))
18793 (org-set-regexps-and-options 'tags-only)
18795 (or (memq 'category org-agenda-ignore-properties)
18796 (org-refresh-category-properties))
18797 (or (memq 'stats org-agenda-ignore-properties)
18798 (org-refresh-stats-properties))
18799 (or (memq 'effort org-agenda-ignore-properties)
18800 (org-refresh-effort-properties))
18801 (or (memq 'appt org-agenda-ignore-properties)
18802 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18803 (setq org-todo-keywords-for-agenda
18804 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18805 (setq org-done-keywords-for-agenda
18806 (append org-done-keywords-for-agenda org-done-keywords))
18807 (setq org-todo-keyword-alist-for-agenda
18808 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18809 (setq org-tag-alist-for-agenda
18811 (append org-tag-alist-for-agenda
18812 org-current-tag-alist)))
18813 ;; Merge current file's tag groups into global
18814 ;; `org-tag-groups-alist-for-agenda'.
18815 (when org-group-tags
18816 (dolist (alist org-tag-groups-alist)
18817 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18819 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18820 (push alist org-tag-groups-alist-for-agenda)))))
18821 (org-with-silent-modifications
18823 (remove-text-properties (point-min) (point-max) pall)
18824 (when org-agenda-skip-archived-trees
18825 (goto-char (point-min))
18826 (while (re-search-forward rea nil t)
18827 (when (org-at-heading-p t)
18828 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18829 (goto-char (point-min))
18830 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18831 (while (re-search-forward re nil t)
18832 (when (save-match-data (org-in-commented-heading-p t))
18833 (add-text-properties
18834 (match-beginning 0) (org-end-of-subtree t) pc)))))
18835 (goto-char pos)))))
18836 (setq org-todo-keywords-for-agenda
18837 (org-uniquify org-todo-keywords-for-agenda))
18838 (setq org-todo-keyword-alist-for-agenda
18839 (org-uniquify org-todo-keyword-alist-for-agenda))))
18842 ;;;; CDLaTeX minor mode
18844 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18845 "Keymap for the minor `org-cdlatex-mode'.")
18847 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18848 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18849 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18850 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18851 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18853 (defvar org-cdlatex-texmathp-advice-is-done nil
18854 "Flag remembering if we have applied the advice to texmathp already.")
18856 (define-minor-mode org-cdlatex-mode
18857 "Toggle the minor `org-cdlatex-mode'.
18858 This mode supports entering LaTeX environment and math in LaTeX fragments
18860 \\{org-cdlatex-mode-map}"
18862 (when org-cdlatex-mode
18864 (run-hooks 'cdlatex-mode-hook)
18865 (cdlatex-compute-tables))
18866 (unless org-cdlatex-texmathp-advice-is-done
18867 (setq org-cdlatex-texmathp-advice-is-done t)
18868 (defadvice texmathp (around org-math-always-on activate)
18869 "Always return t in Org buffers.
18870 This is because we want to insert math symbols without dollars even outside
18871 the LaTeX math segments. If Org mode thinks that point is actually inside
18872 an embedded LaTeX fragment, let `texmathp' do its job.
18873 `\\[org-cdlatex-mode-map]'"
18877 ((not (derived-mode-p 'org-mode)) ad-do-it)
18878 ((eq this-command 'cdlatex-math-symbol)
18879 (setq ad-return-value t
18880 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18882 (let ((p (org-inside-LaTeX-fragment-p)))
18883 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18884 (setq ad-return-value t
18885 texmathp-why '("Org mode embedded math" . 0))
18886 (when p ad-do-it)))))))))
18888 (defun turn-on-org-cdlatex ()
18889 "Unconditionally turn on `org-cdlatex-mode'."
18890 (org-cdlatex-mode 1))
18892 (defun org-try-cdlatex-tab ()
18893 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18894 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18895 - inside a LaTeX fragment, or
18896 - after the first word in a line, where an abbreviation expansion could
18897 insert a LaTeX environment."
18898 (when org-cdlatex-mode
18900 ;; Before any word on the line: No expansion possible.
18901 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18902 ;; Just after first word on the line: Expand it. Make sure it
18903 ;; cannot happen on headlines, though.
18905 (skip-chars-backward "a-zA-Z0-9*")
18906 (skip-chars-backward " \t")
18907 (and (bolp) (not (org-at-heading-p))))
18909 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18911 (defun org-cdlatex-underscore-caret (&optional _arg)
18912 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18913 Revert to the normal definition outside of these fragments."
18915 (if (org-inside-LaTeX-fragment-p)
18916 (call-interactively 'cdlatex-sub-superscript)
18917 (let (org-cdlatex-mode)
18918 (call-interactively (key-binding (vector last-input-event))))))
18920 (defun org-cdlatex-math-modify (&optional _arg)
18921 "Execute `cdlatex-math-modify' in LaTeX fragments.
18922 Revert to the normal definition outside of these fragments."
18924 (if (org-inside-LaTeX-fragment-p)
18925 (call-interactively 'cdlatex-math-modify)
18926 (let (org-cdlatex-mode)
18927 (call-interactively (key-binding (vector last-input-event))))))
18929 (defun org-cdlatex-environment-indent (&optional environment item)
18930 "Execute `cdlatex-environment' and indent the inserted environment.
18932 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18934 The inserted environment is indented to current indentation
18935 unless point is at the beginning of the line, in which the
18936 environment remains unintended."
18938 ;; cdlatex-environment always return nil. Therefore, capture output
18939 ;; first and determine if an environment was selected.
18940 (let* ((beg (point-marker))
18941 (end (copy-marker (point) t))
18943 (ignore-errors (cdlatex-environment environment item))
18945 ;; Figure out how many lines to move forward after the
18946 ;; environment has been inserted.
18947 (lines (when inserted
18949 (- (cl-loop while (< beg (point))
18951 do (forward-line -1)
18954 (if (progn (goto-char beg)
18955 (and (progn (skip-chars-forward " \t") (eolp))
18956 (progn (skip-chars-backward " \t") (bolp))))
18958 (env (org-trim (delete-and-extract-region beg end))))
18960 ;; Get indentation of next line unless at column 0.
18961 (let ((ind (if (bolp) 0
18963 (org-return-indent)
18964 (prog1 (org-get-indentation)
18965 (when (progn (skip-chars-forward " \t") (eolp))
18966 (delete-region beg (point)))))))
18967 (bol (progn (skip-chars-backward " \t") (bolp))))
18968 ;; Insert a newline before environment unless at column zero
18969 ;; to "escape" the current line. Insert a newline if
18970 ;; something is one the same line as \end{ENVIRONMENT}.
18972 (concat (unless bol "\n") env
18973 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18974 (unless (zerop ind)
18977 (while (< (point) end)
18978 (unless (eolp) (indent-line-to ind))
18981 (forward-line lines)
18982 (indent-line-to ind)))
18983 (set-marker beg nil)
18984 (set-marker end nil)))
18987 ;;;; LaTeX fragments
18989 (defun org-inside-LaTeX-fragment-p ()
18990 "Test if point is inside a LaTeX fragment.
18991 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18992 sequence appearing also before point.
18993 Even though the matchers for math are configurable, this function assumes
18994 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18995 delimiters are skipped when they have been removed by customization.
18996 The return value is nil, or a cons cell with the delimiter and the
18997 position of this delimiter.
18999 This function does a reasonably good job, but can locally be fooled by
19000 for example currency specifications. For example it will assume being in
19001 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19002 fragments that are properly closed, but during editing, we have to live
19003 with the uncertainty caused by missing closing delimiters. This function
19004 looks only before point, not after."
19006 (let ((pos (point))
19007 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19009 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19011 dd-on str (start 0) m re)
19014 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19015 re (nth 1 (assoc "$" org-latex-regexps)))
19016 (while (string-match re str start)
19018 ((= (match-end 0) (length str))
19019 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19020 ((= (match-end 0) (- (length str) 5))
19022 (t (setq start (match-end 0))))))
19023 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19025 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19026 (and (match-beginning 2) (throw 'exit nil))
19028 (while (re-search-backward "\\$\\$" lim t)
19029 (setq dd-on (not dd-on)))
19031 (when dd-on (cons "$$" m))))))
19033 (defun org-inside-latex-macro-p ()
19034 "Is point inside a LaTeX macro or its arguments?"
19037 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19039 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19040 "Build an overlay between BEG and END using IMAGE file.
19041 Argument IMAGETYPE is the extension of the displayed image,
19042 as a string. It defaults to \"png\"."
19043 (let ((ov (make-overlay beg end))
19044 (imagetype (or (intern imagetype) 'png)))
19045 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19046 (overlay-put ov 'evaporate t)
19048 'modification-hooks
19049 (list (lambda (o _flag _beg _end &optional _l)
19050 (delete-overlay o))))
19053 (list 'image :type imagetype :file image :ascent 'center))))
19055 (defun org--list-latex-overlays (&optional beg end)
19056 "List all Org LaTeX overlays in current buffer.
19057 Limit to overlays between BEG and END when those are provided."
19059 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19060 (overlays-in (or beg (point-min)) (or end (point-max)))))
19062 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19063 "Remove all overlays with LaTeX fragment images in current buffer.
19064 When optional arguments BEG and END are non-nil, remove all
19065 overlays between them instead. Return a non-nil value when some
19066 overlays were removed, nil otherwise."
19067 (let ((overlays (org--list-latex-overlays beg end)))
19068 (mapc #'delete-overlay overlays)
19071 (defun org-toggle-latex-fragment (&optional arg)
19072 "Preview the LaTeX fragment at point, or all locally or globally.
19074 If the cursor is on a LaTeX fragment, create the image and overlay
19075 it over the source code, if there is none. Remove it otherwise.
19076 If there is no fragment at point, display all fragments in the
19079 With prefix ARG, preview or clear image for all fragments in the
19080 current subtree or in the whole buffer when used before the first
19081 headline. With a prefix ARG `\\[universal-argument] \
19082 \\[universal-argument]' preview or clear images
19083 for all fragments in the buffer."
19085 (when (display-graphic-p)
19090 ((or (equal arg '(16))
19091 (and (equal arg '(4))
19092 (org-with-limited-levels (org-before-first-heading-p))))
19093 (if (org-remove-latex-fragment-image-overlays)
19094 (progn (message "LaTeX fragments images removed from buffer")
19096 (setq msg "Creating images for buffer...")))
19098 (org-with-limited-levels (org-back-to-heading t))
19100 (setq end (progn (org-end-of-subtree t) (point)))
19101 (if (org-remove-latex-fragment-image-overlays beg end)
19103 (message "LaTeX fragment images removed from subtree")
19105 (setq msg "Creating images for subtree...")))
19106 ((let ((datum (org-element-context)))
19107 (when (memq (org-element-type datum)
19108 '(latex-environment latex-fragment))
19109 (setq beg (org-element-property :begin datum))
19110 (setq end (org-element-property :end datum))
19111 (if (org-remove-latex-fragment-image-overlays beg end)
19112 (progn (message "LaTeX fragment image removed")
19114 (setq msg "Creating image...")))))
19116 (org-with-limited-levels
19117 (setq beg (if (org-at-heading-p) (line-beginning-position)
19118 (outline-previous-heading)
19120 (setq end (progn (outline-next-heading) (point)))
19121 (if (org-remove-latex-fragment-image-overlays beg end)
19123 (message "LaTeX fragment images removed from section")
19125 (setq msg "Creating images for section...")))))
19126 (let ((file (buffer-file-name (buffer-base-buffer))))
19128 (concat org-preview-latex-image-directory "org-ltximg")
19130 ;; Emacs cannot overlay images from remote hosts. Create
19131 ;; it in `temporary-file-directory' instead.
19132 (if (or (not file) (file-remote-p file))
19133 temporary-file-directory
19135 'overlays msg 'forbuffer org-preview-latex-default-process))
19136 (message (concat msg "done")))))))
19138 (defun org-format-latex
19139 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19140 "Replace LaTeX fragments with links to an image.
19142 The function takes care of creating the replacement image.
19144 Only consider fragments between BEG and END when those are
19147 When optional argument OVERLAYS is non-nil, display the image on
19148 top of the fragment instead of replacing it.
19150 PROCESSING-TYPE is the conversion method to use, as a symbol.
19152 Some of the options can be changed using the variable
19153 `org-format-latex-options', which see."
19154 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19155 (unless (eq processing-type 'verbatim)
19156 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19159 (goto-char (or beg (point-min)))
19160 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19161 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19162 (overlay-recenter (or end (point-max))))
19163 (while (re-search-forward math-regexp end t)
19164 (unless (and overlays
19165 (eq (get-char-property (point) 'org-overlay-type)
19166 'org-latex-overlay))
19167 (let* ((context (org-element-context))
19168 (type (org-element-type context)))
19169 (when (memq type '(latex-environment latex-fragment))
19170 (let ((block-type (eq type 'latex-environment))
19171 (value (org-element-property :value context))
19172 (beg (org-element-property :begin context))
19173 (end (save-excursion
19174 (goto-char (org-element-property :end context))
19175 (skip-chars-backward " \r\t\n")
19178 ((eq processing-type 'mathjax)
19179 ;; Prepare for MathJax processing.
19180 (if (not (string-match "\\`\\$\\$?" value))
19182 (delete-region beg end)
19183 (if (string= (match-string 0 value) "$$")
19184 (insert "\\[" (substring value 2 -2) "\\]")
19185 (insert "\\(" (substring value 1 -1) "\\)"))))
19186 ((assq processing-type org-preview-latex-process-alist)
19187 ;; Process to an image.
19190 (let* ((processing-info
19191 (cdr (assq processing-type org-preview-latex-process-alist)))
19192 (face (face-at-point))
19193 ;; Get the colors from the face at point.
19195 (let ((color (plist-get org-format-latex-options
19197 (if (and forbuffer (eq color 'auto))
19198 (face-attribute face :foreground nil 'default)
19201 (let ((color (plist-get org-format-latex-options
19203 (if (and forbuffer (eq color 'auto))
19204 (face-attribute face :background nil 'default)
19206 (hash (sha1 (prin1-to-string
19207 (list org-format-latex-header
19208 org-latex-default-packages-alist
19209 org-latex-packages-alist
19210 org-format-latex-options
19211 forbuffer value fg bg))))
19212 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19213 (absprefix (expand-file-name prefix dir))
19214 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19215 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19216 (sep (and block-type "\n\n"))
19217 (link (concat sep "[[file:" linkfile "]]" sep))
19219 (org-combine-plists
19220 org-format-latex-options
19221 `(:foreground ,fg :background ,bg))))
19222 (when msg (message msg cnt))
19223 (unless checkdir-flag ; Ensure the directory exists.
19224 (setq checkdir-flag t)
19225 (let ((todir (file-name-directory absprefix)))
19226 (unless (file-directory-p todir)
19227 (make-directory todir t))))
19228 (unless (file-exists-p movefile)
19229 (org-create-formula-image
19230 value movefile options forbuffer processing-type))
19233 (dolist (o (overlays-in beg end))
19234 (when (eq (overlay-get o 'org-overlay-type)
19235 'org-latex-overlay)
19236 (delete-overlay o)))
19237 (org--format-latex-make-overlay beg end movefile imagetype)
19239 (delete-region beg end)
19241 (org-add-props link
19242 (list 'org-latex-src
19243 (replace-regexp-in-string "\"" "" value)
19244 'org-latex-src-embed-type
19245 (if block-type 'paragraph 'character)))))))
19246 ((eq processing-type 'mathml)
19247 ;; Process to MathML.
19248 (unless (org-format-latex-mathml-available-p)
19249 (user-error "LaTeX to MathML converter not configured"))
19251 (when msg (message msg cnt))
19253 (delete-region beg end)
19254 (insert (org-format-latex-as-mathml
19255 value block-type prefix dir)))
19257 (error "Unknown conversion process %s for LaTeX fragments"
19258 processing-type)))))))))))
19260 (defun org-create-math-formula (latex-frag &optional mathml-file)
19261 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19262 Use `org-latex-to-mathml-convert-command'. If the conversion is
19263 sucessful, return the portion between \"<math...> </math>\"
19264 elements otherwise return nil. When MATHML-FILE is specified,
19265 write the results in to that file. When invoked as an
19266 interactive command, prompt for LATEX-FRAG, with initial value
19267 set to the current active region and echo the results for user
19269 (interactive (list (let ((frag (when (org-region-active-p)
19270 (buffer-substring-no-properties
19271 (region-beginning) (region-end)))))
19272 (read-string "LaTeX Fragment: " frag nil frag))))
19273 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19274 (let* ((tmp-in-file
19275 (let ((file (file-relative-name
19276 (make-temp-name (expand-file-name "ltxmathml-in")))))
19277 (write-region latex-frag nil file)
19279 (tmp-out-file (file-relative-name
19280 (make-temp-name (expand-file-name "ltxmathml-out"))))
19282 org-latex-to-mathml-convert-command
19283 `((?j . ,(and org-latex-to-mathml-jar-file
19284 (shell-quote-argument
19286 org-latex-to-mathml-jar-file))))
19287 (?I . ,(shell-quote-argument tmp-in-file))
19289 (?o . ,(shell-quote-argument tmp-out-file)))))
19290 mathml shell-command-output)
19291 (when (called-interactively-p 'any)
19292 (unless (org-format-latex-mathml-available-p)
19293 (user-error "LaTeX to MathML converter not configured")))
19294 (message "Running %s" cmd)
19295 (setq shell-command-output (shell-command-to-string cmd))
19297 (when (file-readable-p tmp-out-file)
19298 (with-current-buffer (find-file-noselect tmp-out-file t)
19299 (goto-char (point-min))
19300 (when (re-search-forward
19301 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19303 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19305 (prog1 (match-string 0) (kill-buffer))))))
19309 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19311 (write-region mathml nil mathml-file))
19312 (when (called-interactively-p 'any)
19314 ((message "LaTeX to MathML conversion failed")
19315 (message shell-command-output)))
19316 (delete-file tmp-in-file)
19317 (when (file-exists-p tmp-out-file)
19318 (delete-file tmp-out-file))
19321 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19322 prefix &optional dir)
19323 "Use `org-create-math-formula' but check local cache first."
19324 (let* ((absprefix (expand-file-name prefix dir))
19325 (print-length nil) (print-level nil)
19326 (formula-id (concat
19331 org-latex-to-mathml-convert-command)))))
19332 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19333 (formula-cache-dir (file-name-directory formula-cache)))
19335 (unless (file-directory-p formula-cache-dir)
19336 (make-directory formula-cache-dir t))
19338 (unless (file-exists-p formula-cache)
19339 (org-create-math-formula latex-frag formula-cache))
19341 (if (file-exists-p formula-cache)
19342 ;; Successful conversion. Return the link to MathML file.
19344 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19345 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19346 'org-latex-src-embed-type (if latex-frag-type
19347 'paragraph 'character)))
19348 ;; Failed conversion. Return the LaTeX fragment verbatim
19351 (declare-function org-export-get-backend "ox" (name))
19352 (declare-function org-export--get-global-options "ox" (&optional backend))
19353 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19354 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19355 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19356 (defun org-create-formula--latex-header ()
19357 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19358 (let ((info (org-combine-plists (org-export--get-global-options
19359 (org-export-get-backend 'latex))
19360 (org-export--get-inbuffer-options
19361 (org-export-get-backend 'latex)))))
19362 (org-latex-guess-babel-language
19363 (org-latex-guess-inputenc
19364 (org-splice-latex-header
19365 org-format-latex-header
19366 org-latex-default-packages-alist
19367 org-latex-packages-alist t
19368 (plist-get info :latex-header)))
19371 (defun org--get-display-dpi ()
19372 "Get the DPI of the display.
19373 The function assumes that the display has the same pixel width in
19374 the horizontal and vertical directions."
19375 (if (display-graphic-p)
19376 (round (/ (display-pixel-height)
19377 (/ (display-mm-height) 25.4)))
19378 (error "Attempt to calculate the dpi of a non-graphic display")))
19380 (defun org-create-formula-image
19381 (string tofile options buffer &optional processing-type)
19382 "Create an image from LaTeX source using external processes.
19384 The LaTeX STRING is saved to a temporary LaTeX file, then
19385 converted to an image file by process PROCESSING-TYPE defined in
19386 `org-preview-latex-process-alist'. A nil value defaults to
19387 `org-preview-latex-default-process'.
19389 The generated image file is eventually moved to TOFILE.
19391 The OPTIONS argument controls the size, foreground color and
19392 background color of the generated image.
19394 When BUFFER non-nil, this function is used for LaTeX previewing.
19395 Otherwise, it is used to deal with LaTeX snippets showed in
19397 (let* ((processing-type (or processing-type
19398 org-preview-latex-default-process))
19400 (cdr (assq processing-type org-preview-latex-process-alist)))
19401 (programs (plist-get processing-info :programs))
19402 (error-message (or (plist-get processing-info :message) ""))
19403 (use-xcolor (plist-get processing-info :use-xcolor))
19404 (image-input-type (plist-get processing-info :image-input-type))
19405 (image-output-type (plist-get processing-info :image-output-type))
19406 (post-clean (or (plist-get processing-info :post-clean)
19407 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19408 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19409 (latex-header (or (plist-get processing-info :latex-header)
19410 (org-create-formula--latex-header)))
19411 (latex-compiler (plist-get processing-info :latex-compiler))
19412 (image-converter (plist-get processing-info :image-converter))
19413 (tmpdir temporary-file-directory)
19414 (texfilebase (make-temp-name
19415 (expand-file-name "orgtex" tmpdir)))
19416 (texfile (concat texfilebase ".tex"))
19417 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19419 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19420 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19421 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19422 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19424 (bg (or (plist-get options (if buffer :background :html-background))
19426 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19427 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19428 (dolist (program programs)
19429 (org-check-external-command program error-message))
19431 (progn (if (eq fg 'default)
19432 (setq fg (org-latex-color :foreground))
19433 (setq fg (org-latex-color-format fg)))
19434 (if (eq bg 'default)
19435 (setq bg (org-latex-color :background))
19436 (setq bg (org-latex-color-format
19437 (if (string= bg "Transparent") "white" bg))))
19438 (with-temp-file texfile
19439 (insert latex-header)
19440 (insert "\n\\begin{document}\n"
19441 "\\definecolor{fg}{rgb}{" fg "}\n"
19442 "\\definecolor{bg}{rgb}{" bg "}\n"
19443 "\n\\pagecolor{bg}\n"
19447 "\n\\end{document}\n")))
19448 (if (eq fg 'default)
19449 (setq fg (org-dvipng-color :foreground))
19450 (unless (string= fg "Transparent")
19451 (setq fg (org-dvipng-color-format fg))))
19452 (if (eq bg 'default)
19453 (setq bg (org-dvipng-color :background))
19454 (unless (string= bg "Transparent")
19455 (setq bg (org-dvipng-color-format bg))))
19456 (with-temp-file texfile
19457 (insert latex-header)
19458 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19460 (let* ((err-msg (format "Please adjust '%s' part of \
19461 `org-preview-latex-process-alist'."
19465 texfile latex-compiler image-input-type err-msg log-buf))
19468 image-input-file image-converter image-output-type err-msg log-buf
19469 `((?F . ,(shell-quote-argument fg))
19470 (?B . ,(shell-quote-argument bg))
19471 (?D . ,(shell-quote-argument (format "%s" dpi)))
19472 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19473 (copy-file image-output-file tofile 'replace)
19474 (dolist (e post-clean)
19475 (when (file-exists-p (concat texfilebase e))
19476 (delete-file (concat texfilebase e))))
19477 image-output-file)))
19479 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19480 "Fill a LaTeX header template TPL.
19481 In the template, the following place holders will be recognized:
19483 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19484 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19485 [PACKAGES] \\usepackage statements for PKG
19486 [NO-PACKAGES] do not include PKG
19487 [EXTRA] the string EXTRA
19488 [NO-EXTRA] do not include EXTRA
19490 For backward compatibility, if both the positive and the negative place
19491 holder is missing, the positive one (without the \"NO-\") will be
19492 assumed to be present at the end of the template.
19493 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19495 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19496 (let (rpl (end ""))
19497 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19498 (setq rpl (if (or (match-end 1) (not def-pkg))
19499 "" (org-latex-packages-to-string def-pkg snippets-p t))
19500 tpl (replace-match rpl t t tpl))
19501 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19503 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19504 (setq rpl (if (or (match-end 1) (not pkg))
19505 "" (org-latex-packages-to-string pkg snippets-p t))
19506 tpl (replace-match rpl t t tpl))
19507 (when pkg (setq end
19509 (org-latex-packages-to-string pkg snippets-p)))))
19511 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19512 (setq rpl (if (or (match-end 1) (not extra))
19513 "" (concat extra "\n"))
19514 tpl (replace-match rpl t t tpl))
19515 (when (and extra (string-match "\\S-" extra))
19516 (setq end (concat end "\n" extra))))
19518 (if (string-match "\\S-" end)
19519 (concat tpl "\n" end)
19522 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19523 "Turn an alist of packages into a string with the \\usepackage macros."
19524 (setq pkg (mapconcat (lambda(p)
19527 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19528 (format "%% Package %s omitted" (cadr p)))
19529 ((equal "" (car p))
19530 (format "\\usepackage{%s}" (cadr p)))
19532 (format "\\usepackage[%s]{%s}"
19533 (car p) (cadr p)))))
19536 (if newline (concat pkg "\n") pkg))
19538 (defun org-dvipng-color (attr)
19539 "Return a RGB color specification for dvipng."
19540 (org-dvipng-color-format (face-attribute 'default attr nil)))
19542 (defun org-dvipng-color-format (color-name)
19543 "Convert COLOR-NAME to a RGB color value for dvipng."
19544 (apply #'format "rgb %s %s %s"
19545 (mapcar 'org-normalize-color
19546 (color-values color-name))))
19548 (defun org-latex-color (attr)
19549 "Return a RGB color for the LaTeX color package."
19550 (org-latex-color-format (face-attribute 'default attr nil)))
19552 (defun org-latex-color-format (color-name)
19553 "Convert COLOR-NAME to a RGB color value."
19554 (apply #'format "%s,%s,%s"
19555 (mapcar 'org-normalize-color
19556 (color-values color-name))))
19558 (defun org-normalize-color (value)
19559 "Return string to be used as color value for an RGB component."
19560 (format "%g" (/ value 65535.0)))
19566 (defvar-local org-inline-image-overlays nil)
19568 (defun org-toggle-inline-images (&optional include-linked)
19569 "Toggle the display of inline images.
19570 INCLUDE-LINKED is passed to `org-display-inline-images'."
19572 (if org-inline-image-overlays
19574 (org-remove-inline-images)
19575 (when (called-interactively-p 'interactive)
19576 (message "Inline image display turned off")))
19577 (org-display-inline-images include-linked)
19578 (when (called-interactively-p 'interactive)
19579 (message (if org-inline-image-overlays
19580 (format "%d images displayed inline"
19581 (length org-inline-image-overlays))
19582 "No images to display inline")))))
19584 (defun org-redisplay-inline-images ()
19585 "Refresh the display of inline images."
19587 (if (not org-inline-image-overlays)
19588 (org-toggle-inline-images)
19589 (org-toggle-inline-images)
19590 (org-toggle-inline-images)))
19592 (defun org-display-inline-images (&optional include-linked refresh beg end)
19593 "Display inline images.
19595 An inline image is a link which follows either of these
19598 1. Its path is a file with an extension matching return value
19599 from `image-file-name-regexp' and it has no contents.
19601 2. Its description consists in a single link of the previous
19604 When optional argument INCLUDE-LINKED is non-nil, also links with
19605 a text description part will be inlined. This can be nice for
19606 a quick look at those images, but it does not reflect what
19607 exported files will look like.
19609 When optional argument REFRESH is non-nil, refresh existing
19610 images between BEG and END. This will create new image displays
19611 only if necessary. BEG and END default to the buffer
19614 (when (display-graphic-p)
19616 (org-remove-inline-images)
19617 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19618 (org-with-wide-buffer
19619 (goto-char (or beg (point-min)))
19620 (let ((case-fold-search t)
19621 (file-extension-re (image-file-name-regexp)))
19622 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19623 (let ((link (save-match-data (org-element-context))))
19624 ;; Check if we're at an inline image.
19625 (when (and (equal (org-element-property :type link) "file")
19627 (not (org-element-property :contents-begin link)))
19628 (let ((parent (org-element-property :parent link)))
19629 (or (not (eq (org-element-type parent) 'link))
19630 (not (cdr (org-element-contents parent)))))
19631 (string-match-p file-extension-re
19632 (org-element-property :path link)))
19633 (let ((file (expand-file-name
19635 (org-element-property :path link)))))
19636 (when (file-exists-p file)
19638 ;; Apply `org-image-actual-width' specifications.
19640 ((not (image-type-available-p 'imagemagick)) nil)
19641 ((eq org-image-actual-width t) nil)
19642 ((listp org-image-actual-width)
19644 ;; First try to find a width among
19645 ;; attributes associated to the paragraph
19646 ;; containing link.
19649 (while (and (setq e (org-element-property
19651 (not (eq (org-element-type e)
19656 (goto-char (org-element-property :begin paragraph))
19659 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19660 (org-element-property
19661 :post-affiliated paragraph)
19663 (string-to-number (match-string 1))))))
19664 ;; Otherwise, fall-back to provided number.
19665 (car org-image-actual-width)))
19666 ((numberp org-image-actual-width)
19667 org-image-actual-width)))
19668 (old (get-char-property-and-overlay
19669 (org-element-property :begin link)
19670 'org-image-overlay)))
19671 (if (and (car-safe old) refresh)
19672 (image-refresh (overlay-get (cdr old) 'display))
19673 (let ((image (create-image file
19674 (and width 'imagemagick)
19679 ;; If inline image is the description
19680 ;; of another link, be sure to
19681 ;; consider the latter as the one to
19682 ;; apply the overlay on.
19684 (org-element-property :parent link)))
19685 (if (eq (org-element-type parent) 'link)
19689 (org-element-property :begin link)
19692 (org-element-property :end link))
19693 (skip-chars-backward " \t")
19695 (overlay-put ov 'display image)
19696 (overlay-put ov 'face 'default)
19697 (overlay-put ov 'org-image-overlay t)
19699 ov 'modification-hooks
19700 (list 'org-display-inline-remove-overlay))
19701 (push ov org-inline-image-overlays)))))))))))))))
19703 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19704 "Remove inline-display overlay if a corresponding region is modified."
19705 (let ((inhibit-modification-hooks t))
19706 (when (and ov after)
19707 (delete ov org-inline-image-overlays)
19708 (delete-overlay ov))))
19710 (defun org-remove-inline-images ()
19711 "Remove inline display of images."
19713 (mapc #'delete-overlay org-inline-image-overlays)
19714 (setq org-inline-image-overlays nil))
19718 ;; Outline functions from `outline-mode-prefix-map'
19719 ;; that can be remapped in Org:
19720 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19721 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19722 (define-key org-mode-map [remap outline-forward-same-level]
19723 'org-forward-heading-same-level)
19724 (define-key org-mode-map [remap outline-backward-same-level]
19725 'org-backward-heading-same-level)
19726 (define-key org-mode-map [remap outline-show-branches]
19727 'org-kill-note-or-show-branches)
19728 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19729 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19730 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19731 (define-key org-mode-map [remap outline-next-visible-heading]
19732 'org-next-visible-heading)
19733 (define-key org-mode-map [remap outline-previous-visible-heading]
19734 'org-previous-visible-heading)
19735 (define-key org-mode-map [remap show-children] 'org-show-children)
19737 ;; Outline functions from `outline-mode-prefix-map' that can not
19738 ;; be remapped in Org:
19740 ;; - the column "key binding" shows whether the Outline function is still
19741 ;; available in Org mode on the same key that it has been bound to in
19743 ;; - "overridden": key used for a different functionality in Org mode
19744 ;; - else: key still bound to the same Outline function in Org mode
19746 ;; | Outline function | key binding | Org replacement |
19747 ;; |------------------------------------+-------------+--------------------------|
19748 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19749 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19750 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19751 ;; | `show-entry' | overridden | no replacement |
19752 ;; | `show-branches' | `C-c C-k' | still same function |
19753 ;; | `show-subtree' | overridden | visibility cycling |
19754 ;; | `show-all' | overridden | no replacement |
19755 ;; | `hide-subtree' | overridden | visibility cycling |
19756 ;; | `hide-body' | overridden | no replacement |
19757 ;; | `hide-entry' | overridden | visibility cycling |
19758 ;; | `hide-leaves' | overridden | no replacement |
19759 ;; | `hide-sublevels' | overridden | no replacement |
19760 ;; | `hide-other' | overridden | no replacement |
19762 ;; Make `C-c C-x' a prefix key
19763 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19765 ;; TAB key with modifiers
19766 (org-defkey org-mode-map "\C-i" 'org-cycle)
19767 (org-defkey org-mode-map [(tab)] 'org-cycle)
19768 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19769 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19770 ;; The following line is necessary under Suse GNU/Linux
19771 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19772 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19773 (define-key org-mode-map [backtab] 'org-shifttab)
19775 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19776 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19777 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19779 ;; Cursor keys with modifiers
19780 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19781 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19782 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19783 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19785 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19786 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19787 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19788 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19789 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19790 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19792 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19793 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19794 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19795 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19797 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19798 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19799 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19800 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19803 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19804 (dolist (pair org-babel-key-bindings)
19805 (define-key org-babel-map (car pair) (cdr pair)))
19807 ;;; Extra keys for tty access.
19808 ;; We only set them when really needed because otherwise the
19809 ;; menus don't show the simple keys
19811 (when (or org-use-extra-keys (not window-system))
19812 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19813 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19814 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19815 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19816 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19817 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19818 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19819 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19820 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19821 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19822 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19823 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19824 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19825 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19826 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19827 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19828 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19829 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19830 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19831 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19832 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19833 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19834 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19835 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19836 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19837 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19838 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19839 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19841 ;; All the other keys
19843 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19844 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19845 (if (boundp 'narrow-map)
19846 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19847 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19848 (if (boundp 'narrow-map)
19849 (org-defkey narrow-map "b" 'org-narrow-to-block)
19850 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19851 (if (boundp 'narrow-map)
19852 (org-defkey narrow-map "e" 'org-narrow-to-element)
19853 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19854 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19855 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19856 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19857 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19858 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19859 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19860 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19861 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19862 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19863 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19864 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19865 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19866 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19867 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19868 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19869 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19870 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19871 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19872 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19873 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19874 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19875 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19876 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19877 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19878 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19879 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19880 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19881 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19882 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19883 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19884 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19885 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19886 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19887 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19888 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19889 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19890 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19891 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19892 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19893 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19894 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19895 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19896 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19897 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19898 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19899 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19900 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19901 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19902 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19903 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19904 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19905 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19906 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19907 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19908 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19909 (org-defkey org-mode-map "\C-c^" 'org-sort)
19910 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19911 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19912 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19913 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19914 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19915 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19916 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19917 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19918 (org-defkey org-mode-map "\C-m" 'org-return)
19919 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19920 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19921 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19922 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19923 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19924 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19925 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19926 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19927 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19928 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19929 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19930 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19931 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19932 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19933 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19934 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19935 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19936 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19937 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19938 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19939 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19940 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19941 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19942 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19943 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19945 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19946 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19947 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19949 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19950 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19951 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19952 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19953 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19954 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19955 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19956 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19957 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19958 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19959 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19960 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19961 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19962 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19963 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19964 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19965 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19966 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19967 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19968 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19969 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19970 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19972 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19973 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19974 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19975 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19976 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19978 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19980 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19982 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19983 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19985 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19988 (defconst org-speed-commands-default
19990 ("Outline Navigation")
19991 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19992 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19993 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19994 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19995 ("F" . org-next-block)
19996 ("B" . org-previous-block)
19997 ("u" . (org-speed-move-safe 'outline-up-heading))
19999 ("g" . (org-refile t))
20000 ("Outline Visibility")
20002 ("C" . org-shifttab)
20003 (" " . org-display-outline-path)
20004 ("s" . org-narrow-to-subtree)
20005 ("=" . org-columns)
20006 ("Outline Structure Editing")
20008 ("D" . org-metadown)
20009 ("r" . org-metaright)
20010 ("l" . org-metaleft)
20011 ("R" . org-shiftmetaright)
20012 ("L" . org-shiftmetaleft)
20013 ("i" . (progn (forward-char 1) (call-interactively
20014 'org-insert-heading-respect-content)))
20017 ("a" . org-archive-subtree-default-with-confirmation)
20018 ("@" . org-mark-subtree)
20019 ("#" . org-toggle-comment)
20021 ("I" . org-clock-in)
20022 ("O" . org-clock-out)
20023 ("Meta Data Editing")
20025 ("," . (org-priority))
20026 ("0" . (org-priority ?\ ))
20027 ("1" . (org-priority ?A))
20028 ("2" . (org-priority ?B))
20029 ("3" . (org-priority ?C))
20030 (":" . org-set-tags-command)
20031 ("e" . org-set-effort)
20032 ("E" . org-inc-effort)
20033 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20034 (org-entry-put (point) "APPT_WARNTIME" m)))
20035 ("Agenda Views etc")
20037 ("/" . org-sparse-tree)
20039 ("o" . org-open-at-point)
20040 ("?" . org-speed-command-help)
20041 ("<" . (org-agenda-set-restriction-lock 'subtree))
20042 (">" . (org-agenda-remove-restriction-lock))
20044 "The default speed commands.")
20046 (defun org-print-speed-command (e)
20047 (if (> (length (car e)) 1)
20052 (princ (make-string (length (car e)) ?-))
20056 (if (symbolp (cdr e))
20057 (princ (symbol-name (cdr e)))
20061 (defun org-speed-command-help ()
20062 "Show the available speed commands."
20064 (if (not org-use-speed-commands)
20065 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20066 (with-output-to-temp-buffer "*Help*"
20067 (princ "User-defined Speed commands\n===========================\n")
20068 (mapc #'org-print-speed-command org-speed-commands-user)
20070 (princ "Built-in Speed commands\n=======================\n")
20071 (mapc #'org-print-speed-command org-speed-commands-default))
20072 (with-current-buffer "*Help*"
20073 (setq truncate-lines t))))
20075 (defun org-speed-move-safe (cmd)
20076 "Execute CMD, but make sure that the cursor always ends up in a headline.
20077 If not, return to the original position and throw an error."
20079 (let ((pos (point)))
20080 (call-interactively cmd)
20081 (unless (and (bolp) (org-at-heading-p))
20083 (error "Boundary reached while executing %s" cmd))))
20085 (defvar org-self-insert-command-undo-counter 0)
20087 (defvar org-table-auto-blank-field) ; defined in org-table.el
20088 (defvar org-speed-command nil)
20090 (defun org-speed-command-activate (keys)
20091 "Hook for activating single-letter speed commands.
20092 `org-speed-commands-default' specifies a minimal command set.
20093 Use `org-speed-commands-user' for further customization."
20094 (when (or (and (bolp) (looking-at org-outline-regexp))
20095 (and (functionp org-use-speed-commands)
20096 (funcall org-use-speed-commands)))
20097 (cdr (assoc keys (append org-speed-commands-user
20098 org-speed-commands-default)))))
20100 (defun org-babel-speed-command-activate (keys)
20101 "Hook for activating single-letter code block commands."
20102 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20103 (cdr (assoc keys org-babel-key-bindings))))
20105 (defcustom org-speed-command-hook
20106 '(org-speed-command-activate org-babel-speed-command-activate)
20107 "Hook for activating speed commands at strategic locations.
20108 Hook functions are called in sequence until a valid handler is
20111 Each hook takes a single argument, a user-pressed command key
20112 which is also a `self-insert-command' from the global map.
20114 Within the hook, examine the cursor position and the command key
20115 and return nil or a valid handler as appropriate. Handler could
20116 be one of an interactive command, a function, or a form.
20118 Set `org-use-speed-commands' to non-nil value to enable this
20119 hook. The default setting is `org-speed-command-activate'."
20120 :group 'org-structure
20124 (defun org-self-insert-command (N)
20125 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20126 If the cursor is in a table looking at whitespace, the whitespace is
20127 overwritten, and the table is not marked as requiring realignment."
20129 (org-check-before-invisible-edit 'insert)
20131 ((and org-use-speed-commands
20132 (let ((kv (this-command-keys-vector)))
20133 (setq org-speed-command
20134 (run-hook-with-args-until-success
20135 'org-speed-command-hook
20136 (make-string 1 (aref kv (1- (length kv))))))))
20138 ((commandp org-speed-command)
20139 (setq this-command org-speed-command)
20140 (call-interactively org-speed-command))
20141 ((functionp org-speed-command)
20142 (funcall org-speed-command))
20143 ((and org-speed-command (listp org-speed-command))
20144 (eval org-speed-command))
20145 (t (let (org-use-speed-commands)
20146 (call-interactively 'org-self-insert-command)))))
20150 ;; Check if we blank the field, and if that triggers align.
20151 (and (featurep 'org-table) org-table-auto-blank-field
20153 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20154 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20155 ;; Got extra space, this field does not determine
20157 (let (org-table-may-need-update) (org-table-blank-field))
20158 ;; No extra space, this field may determine column
20160 (org-table-blank-field)))
20163 (looking-at "[^|\n]* \\( \\)|"))
20164 ;; There is room for insertion without re-aligning the table.
20165 (delete-region (match-beginning 1) (match-end 1))
20166 (self-insert-command N))
20168 (setq org-table-may-need-update t)
20169 (self-insert-command N)
20170 (org-fix-tags-on-the-fly)
20171 (when org-self-insert-cluster-for-undo
20172 (if (not (eq last-command 'org-self-insert-command))
20173 (setq org-self-insert-command-undo-counter 1)
20174 (if (>= org-self-insert-command-undo-counter 20)
20175 (setq org-self-insert-command-undo-counter 1)
20176 (and (> org-self-insert-command-undo-counter 0)
20177 buffer-undo-list (listp buffer-undo-list)
20178 (not (cadr buffer-undo-list)) ; remove nil entry
20179 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20180 (setq org-self-insert-command-undo-counter
20181 (1+ org-self-insert-command-undo-counter))))))))
20183 (defun org-check-before-invisible-edit (kind)
20184 "Check is editing if kind KIND would be dangerous with invisible text around.
20185 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20186 ;; First, try to get out of here as quickly as possible, to reduce overhead
20187 (when (and org-catch-invisible-edits
20188 (or (not (boundp 'visible-mode)) (not visible-mode))
20189 (or (get-char-property (point) 'invisible)
20190 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20191 ;; OK, we need to take a closer look
20192 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20193 (invisible-before-point (unless (bobp) (get-char-property
20194 (1- (point)) 'invisible)))
20195 (border-and-ok-direction
20197 ;; Check if we are acting predictably before invisible text
20198 (and invisible-at-point (not invisible-before-point)
20199 (memq kind '(insert delete-backward)))
20200 ;; Check if we are acting predictably after invisible text
20201 ;; This works not well, and I have turned it off. It seems
20202 ;; better to always show and stop after invisible text.
20203 ;; (and (not invisible-at-point) invisible-before-point
20204 ;; (memq kind '(insert delete)))
20206 (when (or (memq invisible-at-point '(outline org-hide-block t))
20207 (memq invisible-before-point '(outline org-hide-block t)))
20208 (when (eq org-catch-invisible-edits 'error)
20209 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20210 (if (and org-custom-properties-overlays
20211 (y-or-n-p "Display invisible properties in this buffer? "))
20212 (org-toggle-custom-properties-visibility)
20213 ;; Make the area visible
20215 (when invisible-before-point
20216 (goto-char (previous-single-char-property-change
20217 (point) 'invisible)))
20218 (outline-show-subtree))
20220 ((eq org-catch-invisible-edits 'show)
20221 ;; That's it, we do the edit after showing
20223 "Unfolding invisible region around point before editing")
20225 ((and (eq org-catch-invisible-edits 'smart)
20226 border-and-ok-direction)
20227 (message "Unfolding invisible region around point before editing"))
20229 ;; Don't do the edit, make the user repeat it in full visibility
20230 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20232 (defun org-fix-tags-on-the-fly ()
20233 "Align tags in headline at point.
20234 Unlike to `org-set-tags', it ignores region and sorting."
20235 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20236 (org-at-heading-p))
20237 (let ((org-ignore-region t)
20238 (org-tags-sort-function nil))
20239 (org-set-tags nil t))))
20241 (defun org-delete-backward-char (N)
20242 "Like `delete-backward-char', insert whitespace at field end in tables.
20243 When deleting backwards, in tables this function will insert whitespace in
20244 front of the next \"|\" separator, to keep the table aligned. The table will
20245 still be marked for re-alignment if the field did fill the entire column,
20246 because, in this case the deletion might narrow the column."
20249 (org-check-before-invisible-edit 'delete-backward)
20250 (if (and (org-at-table-p)
20252 (string-match "|" (buffer-substring (point-at-bol) (point)))
20253 (looking-at ".*?|"))
20254 (let ((pos (point))
20255 (noalign (looking-at "[^|\n\r]* |"))
20256 (c org-table-may-need-update))
20257 (backward-delete-char N)
20258 (unless overwrite-mode
20259 (skip-chars-forward "^|")
20261 (goto-char (1- pos)))
20262 ;; noalign: if there were two spaces at the end, this field
20263 ;; does not determine the width of the column.
20264 (when noalign (setq org-table-may-need-update c)))
20265 (backward-delete-char N)
20266 (org-fix-tags-on-the-fly))))
20268 (defun org-delete-char (N)
20269 "Like `delete-char', but insert whitespace at field end in tables.
20270 When deleting characters, in tables this function will insert whitespace in
20271 front of the next \"|\" separator, to keep the table aligned. The table will
20272 still be marked for re-alignment if the field did fill the entire column,
20273 because, in this case the deletion might narrow the column."
20276 (org-check-before-invisible-edit 'delete)
20277 (if (and (org-at-table-p)
20279 (not (= (char-after) ?|))
20281 (if (looking-at ".*?|")
20282 (let ((pos (point))
20283 (noalign (looking-at "[^|\n\r]* |"))
20284 (c org-table-may-need-update))
20286 (concat (substring (match-string 0) 1 -1) " |") nil t)
20288 ;; noalign: if there were two spaces at the end, this field
20289 ;; does not determine the width of the column.
20290 (when noalign (setq org-table-may-need-update c)))
20293 (org-fix-tags-on-the-fly))))
20295 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20296 (put 'org-self-insert-command 'delete-selection
20298 (not (run-hook-with-args-until-success
20299 'self-insert-uses-region-functions))))
20300 (put 'orgtbl-self-insert-command 'delete-selection
20302 (not (run-hook-with-args-until-success
20303 'self-insert-uses-region-functions))))
20304 (put 'org-delete-char 'delete-selection 'supersede)
20305 (put 'org-delete-backward-char 'delete-selection 'supersede)
20306 (put 'org-yank 'delete-selection 'yank)
20308 ;; Make `flyspell-mode' delay after some commands
20309 (put 'org-self-insert-command 'flyspell-delayed t)
20310 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20311 (put 'org-delete-char 'flyspell-delayed t)
20312 (put 'org-delete-backward-char 'flyspell-delayed t)
20314 ;; Make pabbrev-mode expand after Org mode commands
20315 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20316 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20318 (defun org-remap (map &rest commands)
20319 "In MAP, remap the functions given in COMMANDS.
20320 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20323 (setq old (pop commands) new (pop commands))
20324 (org-defkey map (vector 'remap old) new))))
20326 (defun org-transpose-words ()
20327 "Transpose words for Org.
20328 This uses the `org-mode-transpose-word-syntax-table' syntax
20329 table, which interprets characters in `org-emphasis-alist' as
20330 word constituents."
20332 (with-syntax-table org-mode-transpose-word-syntax-table
20333 (call-interactively 'transpose-words)))
20334 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20336 (when (eq org-enable-table-editor 'optimized)
20337 ;; If the user wants maximum table support, we need to hijack
20338 ;; some standard editing functions
20339 (org-remap org-mode-map
20340 'self-insert-command 'org-self-insert-command
20341 'delete-char 'org-delete-char
20342 'delete-backward-char 'org-delete-backward-char)
20343 (org-defkey org-mode-map "|" 'org-force-self-insert))
20345 (defvar org-ctrl-c-ctrl-c-hook nil
20346 "Hook for functions attaching themselves to `C-c C-c'.
20348 This can be used to add additional functionality to the C-c C-c
20349 key which executes context-dependent commands. This hook is run
20350 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20351 run after the last test.
20353 Each function will be called with no arguments. The function
20354 must check if the context is appropriate for it to act. If yes,
20355 it should do its thing and then return a non-nil value. If the
20356 context is wrong, just do nothing and return nil.")
20358 (defvar org-ctrl-c-ctrl-c-final-hook nil
20359 "Hook for functions attaching themselves to `C-c C-c'.
20361 This can be used to add additional functionality to the C-c C-c
20362 key which executes context-dependent commands. This hook is run
20363 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20364 before the first test.
20366 Each function will be called with no arguments. The function
20367 must check if the context is appropriate for it to act. If yes,
20368 it should do its thing and then return a non-nil value. If the
20369 context is wrong, just do nothing and return nil.")
20371 (defvar org-tab-first-hook nil
20372 "Hook for functions to attach themselves to TAB.
20373 See `org-ctrl-c-ctrl-c-hook' for more information.
20374 This hook runs as the first action when TAB is pressed, even before
20375 `org-cycle' messes around with the `outline-regexp' to cater for
20376 inline tasks and plain list item folding.
20377 If any function in this hook returns t, any other actions that
20378 would have been caused by TAB (such as table field motion or visibility
20379 cycling) will not occur.")
20381 (defvar org-tab-after-check-for-table-hook nil
20382 "Hook for functions to attach themselves to TAB.
20383 See `org-ctrl-c-ctrl-c-hook' for more information.
20384 This hook runs after it has been established that the cursor is not in a
20385 table, but before checking if the cursor is in a headline or if global cycling
20387 If any function in this hook returns t, not other actions like visibility
20388 cycling will be done.")
20390 (defvar org-tab-after-check-for-cycling-hook nil
20391 "Hook for functions to attach themselves to TAB.
20392 See `org-ctrl-c-ctrl-c-hook' for more information.
20393 This hook runs after it has been established that not table field motion and
20394 not visibility should be done because of current context. This is probably
20395 the place where a package like yasnippets can hook in.")
20397 (defvar org-tab-before-tab-emulation-hook nil
20398 "Hook for functions to attach themselves to TAB.
20399 See `org-ctrl-c-ctrl-c-hook' for more information.
20400 This hook runs after every other options for TAB have been exhausted, but
20401 before indentation and \t insertion takes place.")
20403 (defvar org-metaleft-hook nil
20404 "Hook for functions attaching themselves to `M-left'.
20405 See `org-ctrl-c-ctrl-c-hook' for more information.")
20406 (defvar org-metaright-hook nil
20407 "Hook for functions attaching themselves to `M-right'.
20408 See `org-ctrl-c-ctrl-c-hook' for more information.")
20409 (defvar org-metaup-hook nil
20410 "Hook for functions attaching themselves to `M-up'.
20411 See `org-ctrl-c-ctrl-c-hook' for more information.")
20412 (defvar org-metadown-hook nil
20413 "Hook for functions attaching themselves to `M-down'.
20414 See `org-ctrl-c-ctrl-c-hook' for more information.")
20415 (defvar org-shiftmetaleft-hook nil
20416 "Hook for functions attaching themselves to `M-S-left'.
20417 See `org-ctrl-c-ctrl-c-hook' for more information.")
20418 (defvar org-shiftmetaright-hook nil
20419 "Hook for functions attaching themselves to `M-S-right'.
20420 See `org-ctrl-c-ctrl-c-hook' for more information.")
20421 (defvar org-shiftmetaup-hook nil
20422 "Hook for functions attaching themselves to `M-S-up'.
20423 See `org-ctrl-c-ctrl-c-hook' for more information.")
20424 (defvar org-shiftmetadown-hook nil
20425 "Hook for functions attaching themselves to `M-S-down'.
20426 See `org-ctrl-c-ctrl-c-hook' for more information.")
20427 (defvar org-metareturn-hook nil
20428 "Hook for functions attaching themselves to `M-RET'.
20429 See `org-ctrl-c-ctrl-c-hook' for more information.")
20430 (defvar org-shiftup-hook nil
20431 "Hook for functions attaching themselves to `S-up'.
20432 See `org-ctrl-c-ctrl-c-hook' for more information.")
20433 (defvar org-shiftup-final-hook nil
20434 "Hook for functions attaching themselves to `S-up'.
20435 This one runs after all other options except shift-select have been excluded.
20436 See `org-ctrl-c-ctrl-c-hook' for more information.")
20437 (defvar org-shiftdown-hook nil
20438 "Hook for functions attaching themselves to `S-down'.
20439 See `org-ctrl-c-ctrl-c-hook' for more information.")
20440 (defvar org-shiftdown-final-hook nil
20441 "Hook for functions attaching themselves to `S-down'.
20442 This one runs after all other options except shift-select have been excluded.
20443 See `org-ctrl-c-ctrl-c-hook' for more information.")
20444 (defvar org-shiftleft-hook nil
20445 "Hook for functions attaching themselves to `S-left'.
20446 See `org-ctrl-c-ctrl-c-hook' for more information.")
20447 (defvar org-shiftleft-final-hook nil
20448 "Hook for functions attaching themselves to `S-left'.
20449 This one runs after all other options except shift-select have been excluded.
20450 See `org-ctrl-c-ctrl-c-hook' for more information.")
20451 (defvar org-shiftright-hook nil
20452 "Hook for functions attaching themselves to `S-right'.
20453 See `org-ctrl-c-ctrl-c-hook' for more information.")
20454 (defvar org-shiftright-final-hook nil
20455 "Hook for functions attaching themselves to `S-right'.
20456 This one runs after all other options except shift-select have been excluded.
20457 See `org-ctrl-c-ctrl-c-hook' for more information.")
20459 (defun org-modifier-cursor-error ()
20460 "Throw an error, a modified cursor command was applied in wrong context."
20461 (user-error "This command is active in special context like tables, headlines or items"))
20463 (defun org-shiftselect-error ()
20464 "Throw an error because Shift-Cursor command was applied in wrong context."
20465 (if (and (boundp 'shift-select-mode) shift-select-mode)
20466 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20467 (user-error "This command works only in special context like headlines or timestamps")))
20469 (defun org-call-for-shift-select (cmd)
20470 (let ((this-command-keys-shift-translated t))
20471 (call-interactively cmd)))
20473 (defun org-shifttab (&optional arg)
20474 "Global visibility cycling or move to previous table field.
20475 Call `org-table-previous-field' within a table.
20476 When ARG is nil, cycle globally through visibility states.
20477 When ARG is a numeric prefix, show contents of this level."
20480 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20482 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20483 (message "Content view to level: %d" arg)
20484 (org-content (prefix-numeric-value arg2))
20485 (org-cycle-show-empty-lines t)
20486 (setq org-cycle-global-status 'overview)))
20487 (t (call-interactively 'org-global-cycle))))
20489 (defun org-shiftmetaleft ()
20490 "Promote subtree or delete table column.
20491 Calls `org-promote-subtree', `org-outdent-item-tree', or
20492 `org-table-delete-column', depending on context. See the
20493 individual commands for more information."
20496 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20497 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20498 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20499 ((if (not (org-region-active-p)) (org-at-item-p)
20500 (save-excursion (goto-char (region-beginning))
20502 (call-interactively 'org-outdent-item-tree))
20503 (t (org-modifier-cursor-error))))
20505 (defun org-shiftmetaright ()
20506 "Demote subtree or insert table column.
20507 Calls `org-demote-subtree', `org-indent-item-tree', or
20508 `org-table-insert-column', depending on context. See the
20509 individual commands for more information."
20512 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20513 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20514 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20515 ((if (not (org-region-active-p)) (org-at-item-p)
20516 (save-excursion (goto-char (region-beginning))
20518 (call-interactively 'org-indent-item-tree))
20519 (t (org-modifier-cursor-error))))
20521 (defun org-shiftmetaup (&optional _arg)
20522 "Drag the line at point up.
20523 In a table, kill the current row.
20524 On a clock timestamp, update the value of the timestamp like `S-<up>'
20525 but also adjust the previous clocked item in the clock history.
20526 Everywhere else, drag the line at point up."
20529 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20530 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20531 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20532 (call-interactively 'org-timestamp-up)))
20533 (t (call-interactively 'org-drag-line-backward))))
20535 (defun org-shiftmetadown (&optional _arg)
20536 "Drag the line at point down.
20537 In a table, insert an empty row at the current line.
20538 On a clock timestamp, update the value of the timestamp like `S-<down>'
20539 but also adjust the previous clocked item in the clock history.
20540 Everywhere else, drag the line at point down."
20543 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20544 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20545 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20546 (call-interactively 'org-timestamp-down)))
20547 (t (call-interactively 'org-drag-line-forward))))
20549 (defsubst org-hidden-tree-error ()
20551 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20553 (defun org-metaleft (&optional _arg)
20554 "Promote heading, list item at point or move table column left.
20556 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20557 depending on context. With no specific context, calls the Emacs
20558 default `backward-word'. See the individual commands for more
20561 This function runs the hook `org-metaleft-hook' as a first step,
20562 and returns at first non-nil value."
20565 ((run-hook-with-args-until-success 'org-metaleft-hook))
20566 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20567 ((org-with-limited-levels
20568 (or (org-at-heading-p)
20569 (and (org-region-active-p)
20571 (goto-char (region-beginning))
20572 (org-at-heading-p)))))
20573 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20574 (call-interactively 'org-do-promote))
20575 ;; At an inline task.
20576 ((org-at-heading-p)
20577 (call-interactively 'org-inlinetask-promote))
20578 ((or (org-at-item-p)
20579 (and (org-region-active-p)
20581 (goto-char (region-beginning))
20583 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20584 (call-interactively 'org-outdent-item))
20585 (t (call-interactively 'backward-word))))
20587 (defun org-metaright (&optional _arg)
20588 "Demote heading, list item at point or move table column right.
20590 In front of a drawer or a block keyword, indent it correctly.
20592 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20593 `org-indent-drawer' or `org-indent-block' depending on context.
20594 With no specific context, calls the Emacs default `forward-word'.
20595 See the individual commands for more information.
20597 This function runs the hook `org-metaright-hook' as a first step,
20598 and returns at first non-nil value."
20601 ((run-hook-with-args-until-success 'org-metaright-hook))
20602 ((org-at-table-p) (call-interactively 'org-table-move-column))
20603 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20604 ((org-at-block-p) (call-interactively 'org-indent-block))
20605 ((org-with-limited-levels
20606 (or (org-at-heading-p)
20607 (and (org-region-active-p)
20609 (goto-char (region-beginning))
20610 (org-at-heading-p)))))
20611 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20612 (call-interactively 'org-do-demote))
20613 ;; At an inline task.
20614 ((org-at-heading-p)
20615 (call-interactively 'org-inlinetask-demote))
20616 ((or (org-at-item-p)
20617 (and (org-region-active-p)
20619 (goto-char (region-beginning))
20621 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20622 (call-interactively 'org-indent-item))
20623 (t (call-interactively 'forward-word))))
20625 (defun org-check-for-hidden (what)
20626 "Check if there are hidden headlines/items in the current visual line.
20627 WHAT can be either `headlines' or `items'. If the current line is
20628 an outline or item heading and it has a folded subtree below it,
20629 this function returns t, nil otherwise."
20631 ((eq what 'headlines) org-outline-regexp-bol)
20632 ((eq what 'items) (org-item-beginning-re))
20633 (t (error "This should not happen"))))
20637 (unless (org-region-active-p)
20638 (setq beg (point-at-bol))
20639 (beginning-of-line 2)
20640 (while (and (not (eobp)) ;; this is like `next-line'
20641 (get-char-property (1- (point)) 'invisible))
20642 (beginning-of-line 2))
20645 (goto-char (point-at-eol))
20646 (setq end (max end (point)))
20647 (while (re-search-forward re end t)
20648 (when (get-char-property (match-beginning 0) 'invisible)
20652 (defun org-metaup (&optional _arg)
20653 "Move subtree up or move table row up.
20654 Calls `org-move-subtree-up' or `org-table-move-row' or
20655 `org-move-item-up', depending on context. See the individual commands
20656 for more information."
20659 ((run-hook-with-args-until-success 'org-metaup-hook))
20660 ((org-region-active-p)
20661 (let* ((a (min (region-beginning) (region-end)))
20662 (b (1- (max (region-beginning) (region-end))))
20663 (c (save-excursion (goto-char a)
20664 (move-beginning-of-line 0)))
20665 (d (save-excursion (goto-char a)
20666 (move-end-of-line 0) (point))))
20667 (transpose-regions a b c d)
20669 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20670 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20671 ((org-at-item-p) (call-interactively 'org-move-item-up))
20672 (t (org-drag-element-backward))))
20674 (defun org-metadown (&optional _arg)
20675 "Move subtree down or move table row down.
20676 Calls `org-move-subtree-down' or `org-table-move-row' or
20677 `org-move-item-down', depending on context. See the individual
20678 commands for more information."
20681 ((run-hook-with-args-until-success 'org-metadown-hook))
20682 ((org-region-active-p)
20683 (let* ((a (min (region-beginning) (region-end)))
20684 (b (max (region-beginning) (region-end)))
20685 (c (save-excursion (goto-char b)
20686 (move-beginning-of-line 1)))
20687 (d (save-excursion (goto-char b)
20688 (move-end-of-line 1) (1+ (point)))))
20689 (transpose-regions a b c d)
20691 ((org-at-table-p) (call-interactively 'org-table-move-row))
20692 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20693 ((org-at-item-p) (call-interactively 'org-move-item-down))
20694 (t (org-drag-element-forward))))
20696 (defun org-shiftup (&optional arg)
20697 "Increase item in timestamp or increase priority of current headline.
20698 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20699 depending on context. See the individual commands for more information."
20702 ((run-hook-with-args-until-success 'org-shiftup-hook))
20703 ((and org-support-shift-select (org-region-active-p))
20704 (org-call-for-shift-select 'previous-line))
20705 ((org-at-timestamp-p t)
20706 (call-interactively (if org-edit-timestamp-down-means-later
20707 'org-timestamp-down 'org-timestamp-up)))
20708 ((and (not (eq org-support-shift-select 'always))
20709 org-enable-priority-commands
20710 (org-at-heading-p))
20711 (call-interactively 'org-priority-up))
20712 ((and (not org-support-shift-select) (org-at-item-p))
20713 (call-interactively 'org-previous-item))
20714 ((org-clocktable-try-shift 'up arg))
20715 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20716 (org-support-shift-select
20717 (org-call-for-shift-select 'previous-line))
20718 (t (org-shiftselect-error))))
20720 (defun org-shiftdown (&optional arg)
20721 "Decrease item in timestamp or decrease priority of current headline.
20722 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20723 depending on context. See the individual commands for more information."
20726 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20727 ((and org-support-shift-select (org-region-active-p))
20728 (org-call-for-shift-select 'next-line))
20729 ((org-at-timestamp-p t)
20730 (call-interactively (if org-edit-timestamp-down-means-later
20731 'org-timestamp-up 'org-timestamp-down)))
20732 ((and (not (eq org-support-shift-select 'always))
20733 org-enable-priority-commands
20734 (org-at-heading-p))
20735 (call-interactively 'org-priority-down))
20736 ((and (not org-support-shift-select) (org-at-item-p))
20737 (call-interactively 'org-next-item))
20738 ((org-clocktable-try-shift 'down arg))
20739 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20740 (org-support-shift-select
20741 (org-call-for-shift-select 'next-line))
20742 (t (org-shiftselect-error))))
20744 (defun org-shiftright (&optional arg)
20745 "Cycle the thing at point or in the current line, depending on context.
20746 Depending on context, this does one of the following:
20748 - switch a timestamp at point one day into the future
20749 - on a headline, switch to the next TODO keyword.
20750 - on an item, switch entire list to the next bullet type
20751 - on a property line, switch to the next allowed value
20752 - on a clocktable definition line, move time block into the future"
20755 ((run-hook-with-args-until-success 'org-shiftright-hook))
20756 ((and org-support-shift-select (org-region-active-p))
20757 (org-call-for-shift-select 'forward-char))
20758 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20759 ((and (not (eq org-support-shift-select 'always))
20760 (org-at-heading-p))
20761 (let ((org-inhibit-logging
20762 (not org-treat-S-cursor-todo-selection-as-state-change))
20763 (org-inhibit-blocking
20764 (not org-treat-S-cursor-todo-selection-as-state-change)))
20765 (org-call-with-arg 'org-todo 'right)))
20766 ((or (and org-support-shift-select
20767 (not (eq org-support-shift-select 'always))
20768 (org-at-item-bullet-p))
20769 (and (not org-support-shift-select) (org-at-item-p)))
20770 (org-call-with-arg 'org-cycle-list-bullet nil))
20771 ((and (not (eq org-support-shift-select 'always))
20772 (org-at-property-p))
20773 (call-interactively 'org-property-next-allowed-value))
20774 ((org-clocktable-try-shift 'right arg))
20775 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20776 (org-support-shift-select
20777 (org-call-for-shift-select 'forward-char))
20778 (t (org-shiftselect-error))))
20780 (defun org-shiftleft (&optional arg)
20781 "Cycle the thing at point or in the current line, depending on context.
20782 Depending on context, this does one of the following:
20784 - switch a timestamp at point one day into the past
20785 - on a headline, switch to the previous TODO keyword.
20786 - on an item, switch entire list to the previous bullet type
20787 - on a property line, switch to the previous allowed value
20788 - on a clocktable definition line, move time block into the past"
20791 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20792 ((and org-support-shift-select (org-region-active-p))
20793 (org-call-for-shift-select 'backward-char))
20794 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20795 ((and (not (eq org-support-shift-select 'always))
20796 (org-at-heading-p))
20797 (let ((org-inhibit-logging
20798 (not org-treat-S-cursor-todo-selection-as-state-change))
20799 (org-inhibit-blocking
20800 (not org-treat-S-cursor-todo-selection-as-state-change)))
20801 (org-call-with-arg 'org-todo 'left)))
20802 ((or (and org-support-shift-select
20803 (not (eq org-support-shift-select 'always))
20804 (org-at-item-bullet-p))
20805 (and (not org-support-shift-select) (org-at-item-p)))
20806 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20807 ((and (not (eq org-support-shift-select 'always))
20808 (org-at-property-p))
20809 (call-interactively 'org-property-previous-allowed-value))
20810 ((org-clocktable-try-shift 'left arg))
20811 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20812 (org-support-shift-select
20813 (org-call-for-shift-select 'backward-char))
20814 (t (org-shiftselect-error))))
20816 (defun org-shiftcontrolright ()
20817 "Switch to next TODO set."
20820 ((and org-support-shift-select (org-region-active-p))
20821 (org-call-for-shift-select 'forward-word))
20822 ((and (not (eq org-support-shift-select 'always))
20823 (org-at-heading-p))
20824 (org-call-with-arg 'org-todo 'nextset))
20825 (org-support-shift-select
20826 (org-call-for-shift-select 'forward-word))
20827 (t (org-shiftselect-error))))
20829 (defun org-shiftcontrolleft ()
20830 "Switch to previous TODO set."
20833 ((and org-support-shift-select (org-region-active-p))
20834 (org-call-for-shift-select 'backward-word))
20835 ((and (not (eq org-support-shift-select 'always))
20836 (org-at-heading-p))
20837 (org-call-with-arg 'org-todo 'previousset))
20838 (org-support-shift-select
20839 (org-call-for-shift-select 'backward-word))
20840 (t (org-shiftselect-error))))
20842 (defun org-shiftcontrolup (&optional n)
20843 "Change timestamps synchronously up in CLOCK log lines.
20844 Optional argument N tells to change by that many units."
20846 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20847 (let (org-support-shift-select)
20848 (org-clock-timestamps-up n))
20849 (user-error "Not at a clock log")))
20851 (defun org-shiftcontroldown (&optional n)
20852 "Change timestamps synchronously down in CLOCK log lines.
20853 Optional argument N tells to change by that many units."
20855 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20856 (let (org-support-shift-select)
20857 (org-clock-timestamps-down n))
20858 (user-error "Not at a clock log")))
20860 (defun org-increase-number-at-point (&optional inc)
20861 "Increment the number at point.
20862 With an optional prefix numeric argument INC, increment using
20863 this numeric value."
20865 (if (not (number-at-point))
20866 (user-error "Not on a number")
20867 (unless inc (setq inc 1))
20868 (let ((pos (point))
20869 (beg (skip-chars-backward "-+^/*0-9eE."))
20870 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20871 (setq nap (buffer-substring-no-properties
20872 (+ pos beg) (+ pos beg end)))
20873 (delete-region (+ pos beg) (+ pos beg end))
20874 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20875 (when (org-at-table-p)
20877 (org-table-end-of-field 1))))
20879 (defun org-decrease-number-at-point (&optional inc)
20880 "Decrement the number at point.
20881 With an optional prefix numeric argument INC, decrement using
20882 this numeric value."
20884 (org-increase-number-at-point (- (or inc 1))))
20886 (defun org-ctrl-c-ret ()
20887 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20890 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20891 (t (call-interactively 'org-insert-heading))))
20893 (defun org-find-visible ()
20895 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20896 (get-char-property s 'invisible)))
20898 (defun org-find-invisible ()
20900 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20901 (not (get-char-property s 'invisible))))
20904 (defun org-copy-visible (beg end)
20905 "Copy the visible parts of the region."
20910 (narrow-to-region beg end)
20911 (setq s (goto-char (point-min)))
20912 (while (not (= (point) (point-max)))
20913 (goto-char (org-find-invisible))
20914 (push (buffer-substring s (point)) snippets)
20915 (setq s (goto-char (org-find-visible))))))
20916 (kill-new (apply 'concat (nreverse snippets)))))
20918 (defun org-copy-special ()
20919 "Copy region in table or copy current subtree.
20920 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20921 context. See the individual commands for more information."
20923 (call-interactively
20924 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20926 (defun org-cut-special ()
20927 "Cut region in table or cut current subtree.
20928 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20929 context. See the individual commands for more information."
20931 (call-interactively
20932 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20934 (defun org-paste-special (arg)
20935 "Paste rectangular region into table, or past subtree relative to level.
20936 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20937 See the individual commands for more information."
20939 (if (org-at-table-p)
20940 (org-table-paste-rectangle)
20941 (org-paste-subtree arg)))
20943 (defun org-edit-special (&optional arg)
20944 "Call a special editor for the element at point.
20945 When at a table, call the formula editor with `org-table-edit-formulas'.
20946 When in a source code block, call `org-edit-src-code'.
20947 When in a fixed-width region, call `org-edit-fixed-width-region'.
20948 When in an export block, call `org-edit-export-block'.
20949 When at an #+INCLUDE keyword, visit the included file.
20950 When at a footnote reference, call `org-edit-footnote-reference'
20951 On a link, call `ffap' to visit the link at point.
20952 Otherwise, return a user error."
20954 (let ((element (org-element-at-point)))
20955 (barf-if-buffer-read-only)
20956 (pcase (org-element-type element)
20958 (if (not arg) (org-edit-src-code)
20959 (let* ((info (org-babel-get-src-block-info))
20960 (lang (nth 0 info))
20961 (params (nth 2 info))
20962 (session (cdr (assq :session params))))
20963 (if (not session) (org-edit-src-code)
20964 ;; At a src-block with a session and function called with
20965 ;; an ARG: switch to the buffer related to the inferior
20968 (funcall (intern (concat "org-babel-prep-session:" lang))
20969 session params))))))
20971 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20972 (org-open-link-from-string
20975 (let ((value (org-element-property :value element)))
20976 (cond ((not (org-string-nw-p value))
20977 (user-error "No file to edit"))
20978 ((string-match "\\`\"\\(.*?\\)\"" value)
20979 (match-string 1 value))
20980 ((string-match "\\`[^ \t\"]\\S-*" value)
20981 (match-string 0 value))
20982 (t (user-error "No valid file specified")))))))
20983 (user-error "No special environment to edit here")))
20985 (if (eq (org-element-property :type element) 'table.el)
20986 (org-edit-table.el)
20987 (call-interactively 'org-table-edit-formulas)))
20988 ;; Only Org tables contain `table-row' type elements.
20989 (`table-row (call-interactively 'org-table-edit-formulas))
20990 (`example-block (org-edit-src-code))
20991 (`export-block (org-edit-export-block))
20992 (`fixed-width (org-edit-fixed-width-region))
20994 ;; No notable element at point. Though, we may be at a link or
20995 ;; a footnote reference, which are objects. Thus, scan deeper.
20996 (let ((context (org-element-context element)))
20997 (pcase (org-element-type context)
20998 (`footnote-reference (org-edit-footnote-reference))
20999 (`inline-src-block (org-edit-inline-src-code))
21000 (`link (call-interactively #'ffap))
21001 (_ (user-error "No special environment to edit here"))))))))
21003 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21004 (defun org-ctrl-c-ctrl-c (&optional arg)
21005 "Set tags in headline, or update according to changed information at point.
21007 This command does many different things, depending on context:
21009 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21010 this is what we do.
21012 - If the cursor is on a statistics cookie, update it.
21014 - If the cursor is in a headline, prompt for tags and insert them
21015 into the current line, aligned to `org-tags-column'. When called
21016 with prefix arg, realign all tags in the current buffer.
21018 - If the cursor is in one of the special #+KEYWORD lines, this
21019 triggers scanning the buffer for these lines and updating the
21022 - If the cursor is inside a table, realign the table. This command
21023 works even if the automatic table editor has been turned off.
21025 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21028 - If the cursor is at a footnote reference or definition, jump to
21029 the corresponding definition or references, respectively.
21031 - If the cursor is a the beginning of a dynamic block, update it.
21033 - If the current buffer is a capture buffer, close note and file it.
21035 - If the cursor is on a <<<target>>>, update radio targets and
21036 corresponding links in this buffer.
21038 - If the cursor is on a numbered item in a plain list, renumber the
21041 - If the cursor is on a checkbox, toggle it.
21043 - If the cursor is on a code block, evaluate it. The variable
21044 `org-confirm-babel-evaluate' can be used to control prompting
21045 before code block evaluation, by default every code block
21046 evaluation requires confirmation. Code block evaluation can be
21047 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21050 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
21051 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21052 (org-remove-occur-highlights)
21053 (message "Temporary highlights/overlays removed from current buffer"))
21054 ((and (local-variable-p 'org-finish-function)
21055 (fboundp org-finish-function))
21056 (funcall org-finish-function))
21057 ((org-babel-hash-at-point))
21058 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21059 ((save-excursion (beginning-of-line) (looking-at-p "[ \t]*$"))
21060 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21062 (substitute-command-keys
21063 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
21066 (org-element-lineage
21067 (org-element-context)
21068 ;; Limit to supported contexts.
21069 '(babel-call clock dynamic-block footnote-definition
21070 footnote-reference inline-babel-call inline-src-block
21071 inlinetask item keyword node-property paragraph
21072 plain-list property-drawer radio-target src-block
21073 statistics-cookie table table-cell table-row
21076 (type (org-element-type context)))
21077 ;; For convenience: at the first line of a paragraph on the same
21078 ;; line as an item, apply function on that item instead.
21079 (when (eq type 'paragraph)
21080 (let ((parent (org-element-property :parent context)))
21081 (when (and (eq (org-element-type parent) 'item)
21082 (= (line-beginning-position)
21083 (org-element-property :begin parent)))
21084 (setq context parent)
21085 (setq type 'item))))
21086 ;; Act according to type of element or object at point.
21088 ((or `babel-call `inline-babel-call)
21089 (let ((info (org-babel-lob-get-info context)))
21090 (when info (org-babel-execute-src-block nil info))))
21091 (`clock (org-clock-update-time-maybe))
21094 (goto-char (org-element-property :post-affiliated context))
21095 (org-update-dblock)))
21096 (`footnote-definition
21097 (goto-char (org-element-property :post-affiliated context))
21098 (call-interactively 'org-footnote-action))
21099 (`footnote-reference (call-interactively #'org-footnote-action))
21100 ((or `headline `inlinetask)
21101 (save-excursion (goto-char (org-element-property :begin context))
21102 (call-interactively #'org-set-tags)))
21103 ((or `inline-src-block `src-block)
21104 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
21105 (org-babel-eval-wipe-error-buffer)
21106 (org-babel-execute-src-block
21107 current-prefix-arg (org-babel-get-src-block-info nil context))))
21109 ;; At an item: `C-u C-u' sets checkbox to "[-]"
21110 ;; unconditionally, whereas `C-u' will toggle its presence.
21111 ;; Without a universal argument, if the item has a checkbox,
21112 ;; toggle it. Otherwise repair the list.
21113 (let* ((box (org-element-property :checkbox context))
21114 (struct (org-element-property :structure context))
21115 (old-struct (copy-tree struct))
21116 (parents (org-list-parents-alist struct))
21117 (prevs (org-list-prevs-alist struct))
21118 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21119 (org-list-set-checkbox
21120 (org-element-property :begin context) struct
21121 (cond ((equal arg '(16)) "[-]")
21122 ((and (not box) (equal arg '(4))) "[ ]")
21123 ((or (not box) (equal arg '(4))) nil)
21124 ((eq box 'on) "[ ]")
21126 ;; Mimic `org-list-write-struct' but with grabbing a return
21127 ;; value from `org-list-struct-fix-box'.
21128 (org-list-struct-fix-ind struct parents 2)
21129 (org-list-struct-fix-item-end struct)
21130 (org-list-struct-fix-bul struct prevs)
21131 (org-list-struct-fix-ind struct parents)
21133 (org-list-struct-fix-box struct parents prevs orderedp)))
21134 (if (and box (equal struct old-struct))
21135 (if (equal arg '(16))
21136 (message "Checkboxes already reset")
21137 (user-error "Cannot toggle this checkbox: %s"
21139 "all subitems checked"
21140 "unchecked subitems")))
21141 (org-list-struct-apply-struct struct old-struct)
21142 (org-update-checkbox-count-maybe))
21144 (message "Checkboxes were removed due to empty box at line %d"
21145 (org-current-line block-item))))))
21147 (let ((org-inhibit-startup-visibility-stuff t)
21148 (org-startup-align-all-tables nil))
21149 (when (boundp 'org-table-coordinate-overlays)
21150 (mapc #'delete-overlay org-table-coordinate-overlays)
21151 (setq org-table-coordinate-overlays nil))
21152 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21153 (message "Local setup has been refreshed"))
21155 ;; At a plain list, with a double C-u argument, set
21156 ;; checkboxes of each item to "[-]", whereas a single one
21157 ;; will toggle their presence according to the state of the
21158 ;; first item in the list. Without an argument, repair the
21160 (let* ((begin (org-element-property :contents-begin context))
21161 (beginm (move-marker (make-marker) begin))
21162 (struct (org-element-property :structure context))
21163 (old-struct (copy-tree struct))
21164 (first-box (save-excursion
21166 (looking-at org-list-full-item-re)
21167 (match-string-no-properties 3)))
21168 (new-box (cond ((equal arg '(16)) "[-]")
21169 ((equal arg '(4)) (unless first-box "[ ]"))
21170 ((equal first-box "[X]") "[ ]")
21175 (org-list-get-all-items
21176 begin struct (org-list-prevs-alist struct)))
21177 (org-list-set-checkbox pos struct new-box)))
21178 ((and first-box (eq (point) begin))
21179 ;; For convenience, when point is at bol on the first
21180 ;; item of the list and no argument is provided, simply
21181 ;; toggle checkbox of that item, if any.
21182 (org-list-set-checkbox begin struct new-box)))
21183 (org-list-write-struct
21184 struct (org-list-parents-alist struct) old-struct)
21185 (org-update-checkbox-count-maybe)
21186 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21187 ((or `property-drawer `node-property)
21188 (call-interactively #'org-property-action))
21190 (call-interactively #'org-update-radio-target-regexp))
21191 (`statistics-cookie
21192 (call-interactively #'org-update-statistics-cookies))
21193 ((or `table `table-cell `table-row)
21194 ;; At a table, recalculate every field and align it. Also
21195 ;; send the table if necessary. If the table has
21196 ;; a `table.el' type, just give up. At a table row or cell,
21197 ;; maybe recalculate line but always align table.
21198 (if (eq (org-element-property :type context) 'table.el)
21199 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21200 Use `\\[org-edit-special]' to edit table.el tables"))
21201 (let ((org-enable-table-editor t))
21202 (if (or (eq type 'table)
21203 ;; Check if point is at a TBLFM line.
21204 (and (eq type 'table-row)
21205 (= (point) (org-element-property :end context))))
21207 (if (org-at-TBLFM-p)
21208 (progn (require 'org-table)
21209 (org-table-calc-current-TBLFM))
21210 (goto-char (org-element-property :contents-begin context))
21211 (org-call-with-arg 'org-table-recalculate (or arg t))
21212 (orgtbl-send-table 'maybe)))
21213 (org-table-maybe-eval-formula)
21214 (cond (arg (call-interactively #'org-table-recalculate))
21215 ((org-table-maybe-recalculate-line))
21216 (t (org-table-align)))))))
21217 (`timestamp (org-timestamp-change 0 'day))
21218 ((and `nil (guard (org-at-heading-p)))
21219 ;; When point is on an unsupported object type, we can miss
21220 ;; the fact that it also is at a heading. Handle it here.
21221 (call-interactively #'org-set-tags))
21223 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21226 (substitute-command-keys
21227 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21229 (defun org-mode-restart ()
21231 (let ((indent-status (bound-and-true-p org-indent-mode)))
21232 (funcall major-mode)
21233 (hack-local-variables)
21234 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21235 (org-indent-mode -1)))
21236 (message "%s restarted" major-mode))
21238 (defun org-kill-note-or-show-branches ()
21239 "Abort storing current note, or call `outline-show-branches'."
21241 (if (not org-finish-function)
21243 (outline-hide-subtree)
21244 (call-interactively 'outline-show-branches))
21245 (let ((org-note-abort t))
21246 (funcall org-finish-function))))
21248 (defun org-delete-indentation (&optional arg)
21249 "Join current line to previous and fix whitespace at join.
21251 If previous line is a headline add to headline title. Otherwise
21252 the function calls `delete-indentation'.
21254 With a non-nil optional argument, join it to the following one."
21256 (if (save-excursion
21257 (beginning-of-line (if arg 1 0))
21258 (let ((case-fold-search nil))
21259 (looking-at org-complex-heading-regexp)))
21261 (let ((tags-column (when (match-beginning 5)
21262 (save-excursion (goto-char (match-beginning 5))
21263 (current-column))))
21264 (string (concat " " (progn (when arg (forward-line 1))
21265 (org-trim (delete-and-extract-region
21266 (line-beginning-position)
21267 (line-end-position)))))))
21268 (unless (bobp) (delete-region (point) (1- (point))))
21269 (goto-char (or (match-end 4)
21270 (match-beginning 5)
21272 (skip-chars-backward " \t")
21273 (save-excursion (insert string))
21274 ;; Adjust alignment of tags.
21276 ((not tags-column)) ;no tags
21277 (org-auto-align-tags (org-set-tags nil t))
21278 (t (org--align-tags-here tags-column)))) ;preserve tags column
21279 (delete-indentation arg)))
21281 (defun org-open-line (n)
21282 "Insert a new row in tables, call `open-line' elsewhere.
21283 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21284 As a special case, when a document starts with a table, allow to
21285 call `open-line' on the very first character."
21287 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21288 (org-table-insert-row)
21291 (defun org-return (&optional indent)
21292 "Goto next table row or insert a newline.
21294 Calls `org-table-next-row' or `newline', depending on context.
21296 When optional INDENT argument is non-nil, call
21297 `newline-and-indent' instead of `newline'.
21299 When `org-return-follows-link' is non-nil and point is on
21300 a timestamp or a link, call `org-open-at-point'. However, it
21301 will not happen if point is in a table or on a \"dead\"
21302 object (e.g., within a comment). In these case, you need to use
21303 `org-open-at-point' directly."
21305 (let ((context (if org-return-follows-link (org-element-context)
21306 (org-element-at-point))))
21308 ;; In a table, call `org-table-next-row'.
21309 ((or (and (eq (org-element-type context) 'table)
21310 (>= (point) (org-element-property :contents-begin context))
21311 (< (point) (org-element-property :contents-end context)))
21312 (org-element-lineage context '(table-row table-cell) t))
21313 (org-table-justify-field-maybe)
21314 (call-interactively #'org-table-next-row))
21315 ;; On a link or a timestamp, call `org-open-at-point' if
21316 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21317 ;; locations, e.g., in a comment, as `org-open-at-point'.
21318 ((and org-return-follows-link
21319 (or (org-in-regexp org-ts-regexp-both nil t)
21320 (org-in-regexp org-tsr-regexp-both nil t)
21321 (org-in-regexp org-any-link-re nil t)))
21322 (call-interactively #'org-open-at-point))
21323 ;; Insert newline in heading, but preserve tags.
21325 (save-excursion (beginning-of-line)
21326 (let ((case-fold-search nil))
21327 (looking-at org-complex-heading-regexp))))
21328 ;; At headline. Split line. However, if point is on keyword,
21329 ;; priority cookie or tags, do not break any of them: add
21330 ;; a newline after the headline instead.
21331 (let ((tags-column (and (match-beginning 5)
21332 (save-excursion (goto-char (match-beginning 5))
21333 (current-column))))
21335 (when (and (match-end 4) (org-point-in-group (point) 4))
21336 (delete-and-extract-region (point) (match-end 4)))))
21337 ;; Adjust tag alignment.
21339 ((not (and tags-column string)))
21340 (org-auto-align-tags (org-set-tags nil t))
21341 (t (org--align-tags-here tags-column))) ;preserve tags column
21344 (if indent (newline-and-indent) (newline))
21345 (when string (save-excursion (insert (org-trim string))))))
21346 ;; In a list, make sure indenting keeps trailing text within.
21349 (org-element-lineage context '(item)))
21350 (let ((trailing-data
21351 (delete-and-extract-region (point) (line-end-position))))
21352 (newline-and-indent)
21353 (save-excursion (insert trailing-data))))
21354 (t (if indent (newline-and-indent) (newline))))))
21356 (defun org-return-indent ()
21357 "Goto next table row or insert a newline and indent.
21358 Calls `org-table-next-row' or `newline-and-indent', depending on
21359 context. See the individual commands for more information."
21363 (defun org-ctrl-c-star ()
21364 "Compute table, or change heading status of lines.
21365 Calls `org-table-recalculate' or `org-toggle-heading',
21366 depending on context."
21370 (call-interactively 'org-table-recalculate))
21372 ;; Convert all lines in region to list items
21373 (call-interactively 'org-toggle-heading))))
21375 (defun org-ctrl-c-minus ()
21376 "Insert separator line in table or modify bullet status of line.
21377 Also turns a plain line or a region of lines into list items.
21378 Calls `org-table-insert-hline', `org-toggle-item', or
21379 `org-cycle-list-bullet', depending on context."
21383 (call-interactively 'org-table-insert-hline))
21384 ((org-region-active-p)
21385 (call-interactively 'org-toggle-item))
21387 (call-interactively 'org-cycle-list-bullet))
21389 (call-interactively 'org-toggle-item))))
21391 (defun org-toggle-heading (&optional nstars)
21392 "Convert headings to normal text, or items or text to headings.
21393 If there is no active region, only convert the current line.
21395 With a `\\[universal-argument]' prefix, convert the whole list at
21396 point into heading.
21400 - If the first non blank line is a headline, remove the stars
21401 from all headlines in the region.
21403 - If it is a normal line, turn each and every normal line (i.e.,
21404 not an heading or an item) in the region into headings. If you
21405 want to convert only the first line of this region, use one
21406 universal prefix argument.
21408 - If it is a plain list item, turn all plain list items into headings.
21410 When converting a line into a heading, the number of stars is chosen
21411 such that the lines become children of the current entry. However,
21412 when a numeric prefix argument is given, its value determines the
21413 number of stars to add."
21417 ;; Return beginning of first non-blank line, starting from
21422 (while (org-at-comment-p) (forward-line))
21423 (skip-chars-forward " \r\t\n")
21426 ;; Determine boundaries of changes. If a universal prefix has
21427 ;; been given, put the list in a region. If region ends at a bol,
21428 ;; do not consider the last line to be in the region.
21430 (when (and current-prefix-arg (org-at-item-p))
21431 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21432 (org-mark-element))
21434 (if (org-region-active-p)
21435 (setq beg (funcall skip-blanks (region-beginning))
21436 end (copy-marker (save-excursion
21437 (goto-char (region-end))
21438 (if (bolp) (point) (point-at-eol)))))
21439 (setq beg (funcall skip-blanks (point-at-bol))
21440 end (copy-marker (point-at-eol))))
21441 ;; Ensure inline tasks don't count as headings.
21442 (org-with-limited-levels
21446 ;; Case 1. Started at an heading: de-star headings.
21447 ((org-at-heading-p)
21448 (while (< (point) end)
21449 (when (org-at-heading-p t)
21450 (looking-at org-outline-regexp) (replace-match "")
21453 ;; Case 2. Started at an item: change items into headlines.
21454 ;; One star will be added by `org-list-to-subtree'.
21456 (while (< (point) end)
21457 (when (org-at-item-p)
21458 ;; Pay attention to cases when region ends before list.
21459 (let* ((struct (org-list-struct))
21461 (min (org-list-get-bottom-point struct) (1+ end))))
21463 (narrow-to-region (point) list-end)
21464 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21467 ;; Case 3. Started at normal text: make every line an heading,
21468 ;; skipping headlines and items.
21471 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21473 (cond (nstars "") ; stars from prefix only
21474 ((equal stars "") "*") ; before first heading
21475 (org-odd-levels-only "**") ; inside heading, odd
21476 (t "*"))) ; inside heading, oddeven
21477 (rpl (concat stars add-stars " "))
21478 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21479 (while (< (point) (if (equal nstars '(4)) lend end))
21480 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21481 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21482 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21483 (forward-line)))))))
21484 (unless toggled (message "Cannot toggle heading from here"))))
21486 (defun org-meta-return (&optional arg)
21487 "Insert a new heading or wrap a region in a table.
21488 Calls `org-insert-heading', `org-insert-item' or
21489 `org-table-wrap-region', depending on context. When called with
21490 an argument, unconditionally call `org-insert-heading'."
21492 (org-check-before-invisible-edit 'insert)
21493 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21494 (call-interactively (cond (arg #'org-insert-heading)
21495 ((org-at-table-p) #'org-table-wrap-region)
21496 ((org-in-item-p) #'org-insert-item)
21497 (t #'org-insert-heading)))))
21501 (defsubst org-in-subtree-not-table-p ()
21502 "Are we in a subtree and not in a table?"
21503 (and (not (org-before-first-heading-p))
21504 (not (org-at-table-p))))
21506 ;; Define the Org mode menus
21507 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21509 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21510 ["Next Field" org-cycle (org-at-table-p)]
21511 ["Previous Field" org-shifttab (org-at-table-p)]
21512 ["Next Row" org-return (org-at-table-p)]
21514 ["Blank Field" org-table-blank-field (org-at-table-p)]
21515 ["Edit Field" org-table-edit-field (org-at-table-p)]
21516 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21519 ["Move Column Left" org-metaleft (org-at-table-p)]
21520 ["Move Column Right" org-metaright (org-at-table-p)]
21521 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21522 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21524 ["Move Row Up" org-metaup (org-at-table-p)]
21525 ["Move Row Down" org-metadown (org-at-table-p)]
21526 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21527 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21528 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21530 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21532 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21533 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21534 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21535 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21538 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21539 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21540 ["Edit Formulas" org-edit-special (org-at-table-p)]
21542 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21543 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21544 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21546 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21548 ["Sum Column/Rectangle" org-table-sum
21549 (or (org-at-table-p) (org-region-active-p))]
21550 ["Which Column?" org-table-current-column (org-at-table-p)])
21552 org-table-toggle-formula-debugger
21553 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21554 ["Show Col/Row Numbers"
21555 org-table-toggle-coordinate-overlays
21557 :selected (bound-and-true-p org-table-overlay-coordinates)]
21559 ["Create" org-table-create (and (not (org-at-table-p))
21560 org-enable-table-editor)]
21561 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21562 ["Import from File" org-table-import (not (org-at-table-p))]
21563 ["Export to File" org-table-export (org-at-table-p)]
21565 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21568 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21569 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21571 (easy-menu-define org-org-menu org-mode-map "Org menu"
21574 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21575 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21576 ["Sparse Tree..." org-sparse-tree t]
21577 ["Reveal Context" org-reveal t]
21578 ["Show All" outline-show-all t]
21580 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21582 ["New Heading" org-insert-heading t]
21583 ("Navigate Headings"
21584 ["Up" outline-up-heading t]
21585 ["Next" outline-next-visible-heading t]
21586 ["Previous" outline-previous-visible-heading t]
21587 ["Next Same Level" outline-forward-same-level t]
21588 ["Previous Same Level" outline-backward-same-level t]
21590 ["Jump" org-goto t])
21592 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21594 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21595 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21597 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21598 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21599 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21601 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21603 ["Copy visible text" org-copy-visible t]
21605 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21606 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21607 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21608 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21610 ["Sort Region/Children" org-sort t]
21612 ["Convert to odd levels" org-convert-to-odd-levels t]
21613 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21615 ["Emphasis..." org-emphasize t]
21616 ["Edit Source Example" org-edit-special t]
21618 ["Footnote new/jump" org-footnote-action t]
21619 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21621 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21623 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21624 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21625 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21629 ["Store Link (Global)" org-store-link t]
21630 ["Find existing link to here" org-occur-link-in-agenda-files t]
21631 ["Insert Link" org-insert-link t]
21632 ["Follow Link" org-open-at-point t]
21634 ["Next link" org-next-link t]
21635 ["Previous link" org-previous-link t]
21637 ["Descriptive Links"
21638 org-toggle-link-display
21640 :selected org-descriptive-links
21643 org-toggle-link-display
21645 :selected (not org-descriptive-links)])
21648 ["TODO/DONE/-" org-todo t]
21650 ["Next keyword" org-shiftright (org-at-heading-p)]
21651 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21652 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21653 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21654 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21655 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21656 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21658 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21659 :selected org-enforce-todo-dependencies :style toggle :active t]
21660 "Settings for tree at point"
21661 ["Do Children sequentially" org-toggle-ordered-property :style radio
21662 :selected (org-entry-get nil "ORDERED")
21663 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21664 ["Do Children parallel" org-toggle-ordered-property :style radio
21665 :selected (not (org-entry-get nil "ORDERED"))
21666 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21668 ["Set Priority" org-priority t]
21669 ["Priority Up" org-shiftup t]
21670 ["Priority Down" org-shiftdown t]
21672 ["Get news from all feeds" org-feed-update-all t]
21673 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21674 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21675 ("TAGS and Properties"
21676 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21677 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21679 ["Set property" org-set-property (not (org-before-first-heading-p))]
21680 ["Column view of properties" org-columns t]
21681 ["Insert Column View DBlock" org-columns-insert-dblock t])
21682 ("Dates and Scheduling"
21683 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21684 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21686 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21687 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21688 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21689 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21690 ["Compute Time Range" org-evaluate-time-range t]
21691 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21692 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21694 ["Custom time format" org-toggle-time-stamp-overlays
21695 :style radio :selected org-display-custom-times]
21697 ["Goto Calendar" org-goto-calendar t]
21698 ["Date from Calendar" org-date-from-calendar t]
21700 ["Start/Restart Timer" org-timer-start t]
21701 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21702 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21703 ["Insert Timer String" org-timer t]
21704 ["Insert Timer Item" org-timer-item t])
21706 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21707 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21708 ["Clock out" org-clock-out t]
21709 ["Clock cancel" org-clock-cancel t]
21711 ["Mark as default task" org-clock-mark-default-task t]
21712 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21713 ["Goto running clock" org-clock-goto t]
21715 ["Display times" org-clock-display t]
21716 ["Create clock table" org-clock-report t]
21718 ["Record DONE time"
21719 (progn (setq org-log-done (not org-log-done))
21720 (message "Switching to %s will %s record a timestamp"
21721 (car org-done-keywords)
21722 (if org-log-done "automatically" "not")))
21723 :style toggle :selected org-log-done])
21725 ["Agenda Command..." org-agenda t]
21726 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21727 ("File List for Agenda")
21728 ("Special views current file"
21729 ["TODO Tree" org-show-todo-tree t]
21730 ["Check Deadlines" org-check-deadlines t]
21731 ["Tags/Property tree" org-match-sparse-tree t])
21733 ["Export/Publish..." org-export-dispatch t]
21735 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21736 :selected org-cdlatex-mode]
21737 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21738 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21739 ["Modify math symbol" org-cdlatex-math-modify
21740 (org-inside-LaTeX-fragment-p)]
21741 ["Insert citation" org-reftex-citation t])
21744 ["Push Files and Views" org-mobile-push t]
21745 ["Get Captured and Flagged" org-mobile-pull t]
21746 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21748 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21751 ["Show Version" org-version t]
21752 ["Info Documentation" org-info t])
21754 ["Browse Org Group" org-customize t]
21756 ["Expand This Menu" org-create-customize-menu
21757 (fboundp 'customize-menu-create)])
21758 ["Send bug report" org-submit-bug-report t]
21761 ["Refresh setup current buffer" org-mode-restart t]
21762 ["Reload Org (after update)" org-reload t]
21763 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21766 (defun org-info (&optional node)
21767 "Read documentation for Org in the info system.
21768 With optional NODE, go directly to that node."
21770 (info (format "(org)%s" (or node ""))))
21773 (defun org-submit-bug-report ()
21774 "Submit a bug report on Org via mail.
21776 Don't hesitate to report any problems or inaccurate documentation.
21778 If you don't have setup sending mail from (X)Emacs, please copy the
21779 output buffer into your mail program, as it gives us important
21780 information about your Org version and configuration."
21782 (require 'reporter)
21783 (defvar reporter-prompt-for-summary-p)
21784 (org-load-modules-maybe)
21785 (org-require-autoloaded-modules)
21786 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21787 (reporter-submit-bug-report
21788 "emacs-orgmode@gnu.org"
21789 (org-version nil 'full)
21791 (save-window-excursion
21792 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21793 (delete-other-windows)
21795 (insert "You are about to submit a bug report to the Org mailing list.
21797 We would like to add your full Org and Outline configuration to the
21798 bug report. This greatly simplifies the work of the maintainer and
21799 other experts on the mailing list.
21801 HOWEVER, some variables you have customized may contain private
21802 information. The names of customers, colleagues, or friends, might
21803 appear in the form of file names, tags, todo states, or search strings.
21804 If you answer yes to the prompt, you might want to check and remove
21805 such private information before sending the email.")
21806 (add-text-properties (point-min) (point-max) '(face org-warning))
21807 (when (yes-or-no-p "Include your Org configuration ")
21811 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21812 (or (and (symbol-value v)
21813 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21815 (get v 'custom-type) (get v 'standard-value)
21816 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21818 (kill-buffer (get-buffer "*Warn about privacy*"))
21821 "Remember to cover the basics, that is, what you expected to happen and
21822 what in fact did happen. You don't know how to make a good report? See
21824 http://orgmode.org/manual/Feedback.html#Feedback
21826 Your bug report will be posted to the Org mailing list.
21827 ------------------------------------------------------------------------")
21829 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21830 (replace-match "\\1Bug: \\3 [\\2]")))))
21833 (defun org-install-agenda-files-menu ()
21834 (let ((bl (buffer-list)))
21837 (set-buffer (pop bl))
21838 (when (derived-mode-p 'org-mode) (setq bl nil)))
21839 (when (derived-mode-p 'org-mode)
21841 '("Org") "File List for Agenda"
21844 ["Edit File List" (org-edit-agenda-file-list) t]
21845 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21846 ["Remove Current File from List" org-remove-file t]
21847 ["Cycle through agenda files" org-cycle-agenda-files t]
21848 ["Occur in all agenda files" org-occur-in-agenda-files t]
21850 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21854 (defun org-require-autoloaded-modules ()
21857 '(org-agenda org-archive org-attach org-clock org-colview org-id
21858 org-table org-timer)))
21861 (defun org-reload (&optional uncompiled)
21862 "Reload all org lisp files.
21863 With prefix arg UNCOMPILED, load the uncompiled versions."
21865 (require 'loadhist)
21866 (let* ((org-dir (org-find-library-dir "org"))
21867 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21868 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21869 (remove-re (format "\\`%s\\'"
21870 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21871 (feats (delete-dups
21872 (mapcar 'file-name-sans-extension
21873 (mapcar 'file-name-nondirectory
21875 (mapcar 'feature-file
21882 (if (and (string-match feature-re f)
21883 (not (string-match remove-re f)))
21887 (list "org-version" "org")))
21888 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21889 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21890 load-uncore load-misses)
21893 (mapcar (lambda (f)
21894 (or (org-load-noerror-mustsuffix (concat org-dir f))
21895 (and (string= org-dir contrib-dir)
21896 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21897 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21898 (add-to-list 'load-uncore f 'append)
21903 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21904 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21906 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21907 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21908 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21911 (defun org-customize ()
21912 "Call the customize function with org as argument."
21914 (org-load-modules-maybe)
21915 (org-require-autoloaded-modules)
21916 (customize-browse 'org))
21918 (defun org-create-customize-menu ()
21919 "Create a full customization menu for Org mode, insert it into the menu."
21921 (org-load-modules-maybe)
21922 (org-require-autoloaded-modules)
21923 (if (fboundp 'customize-menu-create)
21926 '("Org") "Customize"
21927 `(["Browse Org group" org-customize t]
21929 ,(customize-menu-create 'org)
21930 ["Set" Custom-set t]
21931 ["Save" Custom-save t]
21932 ["Reset to Current" Custom-reset-current t]
21933 ["Reset to Saved" Custom-reset-saved t]
21934 ["Reset to Standard Settings" Custom-reset-standard t]))
21935 (message "\"Org\"-menu now contains full customization menu"))
21936 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21938 ;;;; Miscellaneous stuff
21940 ;;; Generally useful functions
21942 (defun org-get-at-eol (property n)
21943 "Get text property PROPERTY at the end of line less N characters."
21944 (get-text-property (- (point-at-eol) n) property))
21946 (defun org-find-text-property-in-string (prop s)
21947 "Return the first non-nil value of property PROP in string S."
21948 (or (get-text-property 0 prop s)
21949 (get-text-property (or (next-single-property-change 0 prop s) 0)
21952 (defun org-display-warning (message)
21953 "Display the given MESSAGE as a warning."
21954 (display-warning 'org message :warning))
21956 (defun org-eval (form)
21957 "Eval FORM and return result."
21958 (condition-case error
21960 (error (format "%%![Error: %s]" error))))
21962 (defun org-in-clocktable-p ()
21963 "Check if the cursor is in a clocktable."
21964 (let ((pos (point)) start)
21967 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21968 (setq start (match-beginning 0))
21969 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21970 (>= (match-end 0) pos)
21973 (defun org-in-verbatim-emphasis ()
21975 (and (org-in-regexp org-verbatim-re 2)
21976 (>= (point) (match-beginning 3))
21977 (<= (point) (match-end 4)))))
21979 (defun org-overlay-display (ovl text &optional face evap)
21980 "Make overlay OVL display TEXT with face FACE."
21981 (overlay-put ovl 'display text)
21982 (if face (overlay-put ovl 'face face))
21983 (if evap (overlay-put ovl 'evaporate t)))
21985 (defun org-overlay-before-string (ovl text &optional face evap)
21986 "Make overlay OVL display TEXT with face FACE."
21987 (if face (org-add-props text nil 'face face))
21988 (overlay-put ovl 'before-string text)
21989 (if evap (overlay-put ovl 'evaporate t)))
21991 (defun org-find-overlays (prop &optional pos delete)
21992 "Find all overlays specifying PROP at POS or point.
21993 If DELETE is non-nil, delete all those overlays."
21995 (dolist (ov (overlays-at (or pos (point))) found)
21996 (cond ((not (overlay-get ov prop)))
21997 (delete (delete-overlay ov))
21998 (t (push ov found))))))
22000 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22001 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22002 (if (and marker (marker-buffer marker)
22003 (buffer-live-p (marker-buffer marker)))
22005 (pop-to-buffer-same-window (marker-buffer marker))
22006 (when (or (> marker (point-max)) (< marker (point-min)))
22009 (org-show-context 'org-goto))
22011 (bookmark-jump bookmark)
22012 (error "Cannot find location"))))
22014 (defun org-quote-csv-field (s)
22015 "Quote field for inclusion in CSV material."
22016 (if (string-match "[\",]" s)
22017 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22020 (defun org-force-self-insert (N)
22021 "Needed to enforce self-insert under remapping."
22023 (self-insert-command N))
22025 (defun org-string-width (s)
22026 "Compute width of string, ignoring invisible characters.
22027 This ignores character with invisibility property `org-link', and also
22028 characters with property `org-cwidth', because these will become invisible
22029 upon the next fontification round."
22031 (when (or (eq t buffer-invisibility-spec)
22032 (assq 'org-link buffer-invisibility-spec))
22033 (while (setq b (text-property-any 0 (length s)
22034 'invisible 'org-link s))
22035 (setq s (concat (substring s 0 b)
22036 (substring s (or (next-single-property-change
22039 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22040 (setq s (concat (substring s 0 b)
22041 (substring s (or (next-single-property-change
22044 (setq l (string-width s) b -1)
22045 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22046 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22049 (defun org-shorten-string (s maxlength)
22050 "Shorten string S so that it is no longer than MAXLENGTH characters.
22051 If the string is shorter or has length MAXLENGTH, just return the
22052 original string. If it is longer, the functions finds a space in the
22053 string, breaks this string off at that locations and adds three dots
22054 as ellipsis. Including the ellipsis, the string will not be longer
22055 than MAXLENGTH. If finding a good breaking point in the string does
22056 not work, the string is just chopped off in the middle of a word
22058 (if (<= (length s) maxlength)
22060 (let* ((n (max (- maxlength 4) 1))
22061 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22062 (if (string-match re s)
22063 (concat (match-string 1 s) "...")
22064 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22066 (defun org-get-indentation (&optional line)
22067 "Get the indentation of the current line, interpreting tabs.
22068 When LINE is given, assume it represents a line and compute its indentation."
22070 (when (string-match "^ *" (org-remove-tabs line))
22073 (beginning-of-line 1)
22074 (skip-chars-forward " \t")
22075 (current-column))))
22077 (defun org-get-string-indentation (s)
22078 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22079 (let ((n -1) (i 0) (w tab-width) c)
22081 (while (< (setq n (1+ n)) (length s))
22082 (setq c (aref s n))
22083 (cond ((= c ?\ ) (setq i (1+ i)))
22084 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22085 (t (throw 'exit t)))))
22088 (defun org-remove-tabs (s &optional width)
22089 "Replace tabulators in S with spaces.
22090 Assumes that s is a single line, starting in column 0."
22091 (setq width (or width tab-width))
22092 (while (string-match "\t" s)
22093 (setq s (replace-match
22095 (- (* width (/ (+ (match-beginning 0) width) width))
22096 (match-beginning 0)) ?\ )
22100 (defun org-fix-indentation (line ind)
22101 "Fix indentation in LINE.
22102 IND is a cons cell with target and minimum indentation.
22103 If the current indentation in LINE is smaller than the minimum,
22104 leave it alone. If it is larger than ind, set it to the target."
22105 (let* ((l (org-remove-tabs line))
22106 (i (org-get-indentation l))
22107 (i1 (car ind)) (i2 (cdr ind)))
22108 (when (>= i i2) (setq l (substring line i2)))
22110 (concat (make-string i1 ?\ ) l)
22113 (defun org-remove-indentation (code &optional n)
22114 "Remove maximum common indentation in string CODE and return it.
22115 N may optionally be the number of columns to remove. Return CODE
22116 as-is if removal failed."
22119 (if (org-do-remove-indentation n) (buffer-string) code)))
22121 (defun org-do-remove-indentation (&optional n)
22122 "Remove the maximum common indentation from the buffer.
22123 When optional argument N is a positive integer, remove exactly
22124 that much characters from indentation, if possible. Return nil
22127 (goto-char (point-min))
22128 ;; Find maximum common indentation, if not specified.
22130 (let ((min-ind (point-max)))
22132 (while (re-search-forward "^[ \t]*\\S-" nil t)
22133 (let ((ind (1- (current-column))))
22134 (if (zerop ind) (throw :exit nil)
22135 (setq min-ind (min min-ind ind))))))
22137 (if (zerop n) (throw :exit nil)
22138 ;; Remove exactly N indentation, but give up if not possible.
22139 (while (not (eobp))
22140 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22141 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22142 ((< ind n) (throw :exit nil))
22143 (t (indent-line-to (- ind n))))
22148 (defun org-fill-template (template alist)
22149 "Find each %key of ALIST in TEMPLATE and replace it."
22150 (let ((case-fold-search nil))
22151 (dolist (entry (sort (copy-sequence alist)
22152 (lambda (a b) (< (length (car a)) (length (car b))))))
22154 (replace-regexp-in-string
22155 (concat "%" (regexp-quote (car entry)))
22156 (or (cdr entry) "") template t t)))
22159 (defun org-base-buffer (buffer)
22160 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22163 (or (buffer-base-buffer buffer)
22166 (defun org-wrap (string &optional width lines)
22167 "Wrap string to either a number of lines, or a width in characters.
22168 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22169 that costs. If there is a word longer than WIDTH, the text is actually
22170 wrapped to the length of that word.
22171 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22172 many lines, whatever width that takes.
22173 The return value is a list of lines, without newlines at the end."
22174 (let* ((words (org-split-string string "[ \t\n]+"))
22175 (maxword (apply 'max (mapcar 'org-string-width words)))
22178 (org-do-wrap words (max maxword width)))
22181 (setq ll (org-do-wrap words maxword))
22182 (if (<= (length ll) lines)
22185 (while (> (length ll) lines)
22187 (setq ll (org-do-wrap words w)))
22189 (t (error "Cannot wrap this")))))
22191 (defun org-do-wrap (words width)
22192 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22195 (setq line (pop words))
22196 (while (and words (< (+ (length line) (length (car words))) width))
22197 (setq line (concat line " " (pop words))))
22198 (setq lines (push line lines)))
22201 (defun org-split-string (string &optional separators)
22202 "Splits STRING into substrings at SEPARATORS.
22203 SEPARATORS is a regular expression.
22204 No empty strings are returned if there are matches at the beginning
22205 and end of string."
22206 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22207 (let ((start 0) notfirst list)
22208 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22210 (= start (match-beginning 0))
22211 (< start (length string)))
22213 (< (match-beginning 0) (length string)))
22215 (or (eq (match-beginning 0) 0)
22216 (and (eq (match-beginning 0) (match-end 0))
22217 (eq (match-beginning 0) start))
22218 (push (substring string start (match-beginning 0)) list))
22219 (setq start (match-end 0)))
22220 (or (eq start (length string))
22221 (push (substring string start) list))
22224 (defun org-quote-vert (s)
22225 "Replace \"|\" with \"\\vert\"."
22226 (while (string-match "|" s)
22227 (setq s (replace-match "\\vert" t t s)))
22230 (defun org-uuidgen-p (s)
22231 "Is S an ID created by UUIDGEN?"
22232 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22234 (defun org-in-src-block-p (&optional inside)
22235 "Whether point is in a code source block.
22236 When INSIDE is non-nil, don't consider we are within a src block
22237 when point is at #+BEGIN_SRC or #+END_SRC."
22238 (let ((case-fold-search t))
22239 (or (and (eq (get-char-property (point) 'src-block) t))
22243 (beginning-of-line)
22244 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22246 (defun org-context ()
22247 "Return a list of contexts of the current cursor position.
22248 If several contexts apply, all are returned.
22249 Each context entry is a list with a symbol naming the context, and
22250 two positions indicating start and end of the context. Possible
22253 :headline anywhere in a headline
22254 :headline-stars on the leading stars in a headline
22255 :todo-keyword on a TODO keyword (including DONE) in a headline
22256 :tags on the TAGS in a headline
22257 :priority on the priority cookie in a headline
22258 :item on the first line of a plain list item
22259 :item-bullet on the bullet/number of a plain list item
22260 :checkbox on the checkbox in a plain list item
22261 :table in an Org table
22262 :table-special on a special filed in a table
22263 :table-table in a table.el table
22264 :clocktable in a clocktable
22265 :src-block in a source block
22266 :link on a hyperlink
22267 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22268 :target on a <<target>>
22269 :radio-target on a <<<radio-target>>>
22270 :latex-fragment on a LaTeX fragment
22271 :latex-preview on a LaTeX fragment with overlaid preview image
22273 This function expects the position to be visible because it uses font-lock
22274 faces as a help to recognize the following contexts: :table-special, :link,
22276 (let* ((f (get-text-property (point) 'face))
22277 (faces (if (listp f) f (list f)))
22278 (case-fold-search t)
22279 (p (point)) clist o)
22280 ;; First the large context
22282 ((org-at-heading-p t)
22283 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22285 (beginning-of-line 1)
22286 (looking-at org-todo-line-tags-regexp))
22287 (push (org-point-in-group p 1 :headline-stars) clist)
22288 (push (org-point-in-group p 2 :todo-keyword) clist)
22289 (push (org-point-in-group p 4 :tags) clist))
22291 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22292 (when (looking-at "\\[#[A-Z0-9]\\]")
22293 (push (org-point-in-group p 0 :priority) clist)))
22296 (push (org-point-in-group p 2 :item-bullet) clist)
22297 (push (list :item (point-at-bol)
22298 (save-excursion (org-end-of-item) (point)))
22300 (and (org-at-item-checkbox-p)
22301 (push (org-point-in-group p 0 :checkbox) clist)))
22304 (push (list :table (org-table-begin) (org-table-end)) clist)
22305 (when (memq 'org-formula faces)
22306 (push (list :table-special
22307 (previous-single-property-change p 'face)
22308 (next-single-property-change p 'face)) clist)))
22309 ((org-at-table-p 'any)
22310 (push (list :table-table) clist)))
22313 (let ((case-fold-search t))
22314 ;; New the "medium" contexts: clocktables, source blocks
22315 (cond ((org-in-clocktable-p)
22316 (push (list :clocktable
22317 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22318 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22319 (match-beginning 1))
22320 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22321 (match-end 0))) clist))
22322 ((org-in-src-block-p)
22323 (push (list :src-block
22324 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22325 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22326 (match-beginning 1))
22327 (and (search-forward "#+END_SRC" nil t)
22328 (match-beginning 0))) clist))))
22331 ;; Now the small context
22333 ((org-at-timestamp-p)
22334 (push (org-point-in-group p 0 :timestamp) clist))
22335 ((memq 'org-link faces)
22337 (previous-single-property-change p 'face)
22338 (next-single-property-change p 'face)) clist))
22339 ((memq 'org-special-keyword faces)
22340 (push (list :keyword
22341 (previous-single-property-change p 'face)
22342 (next-single-property-change p 'face)) clist))
22344 (push (org-point-in-group p 0 :target) clist)
22345 (goto-char (1- (match-beginning 0)))
22346 (when (looking-at org-radio-target-regexp)
22347 (push (org-point-in-group p 0 :radio-target) clist))
22351 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22353 (overlays-at (point))))
22354 (push (list :latex-fragment
22355 (overlay-start o) (overlay-end o)) clist)
22356 (push (list :latex-preview
22357 (overlay-start o) (overlay-end o)) clist))
22358 ((org-inside-LaTeX-fragment-p)
22359 ;; FIXME: positions wrong.
22360 (push (list :latex-fragment (point) (point)) clist)))
22362 (setq clist (nreverse (delq nil clist)))
22365 (defun org-in-regexp (regexp &optional nlines visually)
22366 "Check if point is inside a match of REGEXP.
22368 Normally only the current line is checked, but you can include
22369 NLINES extra lines around point into the search. If VISUALLY is
22370 set, require that the cursor is not after the match but really
22371 on, so that the block visually is on the match.
22373 Return nil or a cons cell (BEG . END) where BEG and END are,
22374 respectively, the positions at the beginning and the end of the
22377 (let ((pos (point))
22378 (eol (line-end-position (if nlines (1+ nlines) 1))))
22380 (beginning-of-line (- 1 (or nlines 0)))
22381 (while (and (re-search-forward regexp eol t)
22382 (<= (match-beginning 0) pos))
22383 (let ((end (match-end 0)))
22384 (when (or (> end pos) (and (= end pos) (not visually)))
22385 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22387 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22388 "Non-nil when point is between matches of START-RE and END-RE.
22390 Also return a non-nil value when point is on one of the matches.
22392 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22393 buffer positions. Default values are the positions of headlines
22394 surrounding the point.
22396 The functions returns a cons cell whose car (resp. cdr) is the
22397 position before START-RE (resp. after END-RE)."
22399 (let ((pos (point))
22400 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22401 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22404 ;; Point is on a block when on START-RE or if START-RE can be
22405 ;; found before it...
22406 (and (or (org-in-regexp start-re)
22407 (re-search-backward start-re limit-up t))
22408 (setq beg (match-beginning 0))
22409 ;; ... and END-RE after it...
22410 (goto-char (match-end 0))
22411 (re-search-forward end-re limit-down t)
22412 (> (setq end (match-end 0)) pos)
22413 ;; ... without another START-RE in-between.
22414 (goto-char (match-beginning 0))
22415 (not (re-search-backward start-re (1+ beg) t))
22417 (cons beg end))))))
22419 (defun org-in-block-p (names)
22420 "Non-nil when point belongs to a block whose name belongs to NAMES.
22422 NAMES is a list of strings containing names of blocks.
22424 Return first block name matched, or nil. Beware that in case of
22425 nested blocks, the returned name may not belong to the closest
22429 (let ((case-fold-search t)
22430 (lim-up (save-excursion (outline-previous-heading)))
22431 (lim-down (save-excursion (outline-next-heading))))
22432 (dolist (name names)
22433 (let ((n (regexp-quote name)))
22434 (when (org-between-regexps-p
22435 (concat "^[ \t]*#\\+begin_" n)
22436 (concat "^[ \t]*#\\+end_" n)
22438 (throw 'exit n)))))
22441 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22442 "Call `multi-occur' with buffers for all agenda files."
22443 (interactive "sOrg-files matching: ")
22444 (let* ((files (org-agenda-files))
22445 (tnames (mapcar #'file-truename files))
22446 (extra org-agenda-text-search-extra-files))
22447 (when (eq (car extra) 'agenda-archives)
22448 (setq extra (cdr extra))
22449 (setq files (org-add-archive-files files)))
22451 (unless (member (file-truename f) tnames)
22452 (unless (member f files) (setq files (append files (list f))))
22453 (setq tnames (append tnames (list (file-truename f))))))
22455 (mapcar (lambda (x)
22456 (with-current-buffer
22457 ;; FIXME: Why not just (find-file-noselect x)?
22458 ;; Is it to avoid the "revert buffer" prompt?
22459 (or (get-file-buffer x) (find-file-noselect x))
22465 (add-hook 'occur-mode-find-occurrence-hook
22466 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22468 (defun org-occur-link-in-agenda-files ()
22469 "Create a link and search for it in the agendas.
22470 The link is not stored in `org-stored-links', it is just created
22471 for the search purpose."
22473 (let ((link (condition-case nil
22474 (org-store-link nil)
22475 (error "Unable to create a link to here"))))
22476 (org-occur-in-agenda-files (regexp-quote link))))
22478 (defun org-reverse-string (string)
22479 "Return the reverse of STRING."
22480 (apply 'string (reverse (string-to-list string))))
22482 ;; defsubst org-uniquify must be defined before first use
22484 (defun org-uniquify-alist (alist)
22485 "Merge elements of ALIST with the same key.
22487 For example, in this alist:
22489 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22490 => \\='((a 1 3) (b 2))
22492 merge (a 1) and (a 3) into (a 1 3).
22494 The function returns the new ALIST."
22496 (dolist (e alist rtn)
22498 (if (not (assoc (car e) rtn))
22500 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22501 (setq rtn (assq-delete-all (car e) rtn))
22504 (defun org-delete-all (elts list)
22505 "Remove all elements in ELTS from LIST.
22506 Comparison is done with `equal'. It is a destructive operation
22507 that may remove elements by altering the list structure."
22509 (setq list (delete (pop elts) list)))
22512 (defun org-back-over-empty-lines ()
22513 "Move backwards over whitespace, to the beginning of the first empty line.
22514 Returns the number of empty lines passed."
22515 (let ((pos (point)))
22516 (if (cdr (assq 'heading org-blank-before-new-entry))
22517 (skip-chars-backward " \t\n\r")
22519 (forward-line -1)))
22520 (beginning-of-line 2)
22521 (goto-char (min (point) pos))
22522 (count-lines (point) pos)))
22524 (defun org-skip-whitespace ()
22525 (skip-chars-forward " \t\n\r"))
22527 (defun org-point-in-group (point group &optional context)
22528 "Check if POINT is in match-group GROUP.
22529 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22530 match. If the match group does not exist or point is not inside it,
22532 (and (match-beginning group)
22533 (>= point (match-beginning group))
22534 (<= point (match-end group))
22536 (list context (match-beginning group) (match-end group))
22539 (defun org-switch-to-buffer-other-window (&rest args)
22540 "Switch to buffer in a second window on the current frame.
22541 In particular, do not allow pop-up frames.
22542 Returns the newly created buffer."
22544 (apply 'switch-to-buffer-other-window args)))
22546 (defun org-combine-plists (&rest plists)
22547 "Create a single property list from all plists in PLISTS.
22548 The process starts by copying the first list, and then setting properties
22549 from the other lists. Settings in the last list are the most significant
22550 ones and overrule settings in the other lists."
22551 (let ((rtn (copy-sequence (pop plists)))
22554 (setq ls (pop plists))
22556 (setq p (pop ls) v (pop ls))
22557 (setq rtn (plist-put rtn p v))))
22560 (defun org-replace-escapes (string table)
22561 "Replace %-escapes in STRING with values in TABLE.
22562 TABLE is an association list with keys like \"%a\" and string values.
22563 The sequences in STRING may contain normal field width and padding information,
22564 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22565 so values can contain further %-escapes if they are define later in TABLE."
22566 (let ((tbl (copy-alist table))
22567 (case-fold-search nil)
22571 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22572 (when (and (cdr e) (string-match re (cdr e)))
22573 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22575 (add-text-properties 0 3 (list 'sref sref) safe)
22576 (setcdr e (replace-match safe t t (cdr e)))))
22577 (while (string-match re string)
22578 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22580 (setq string (replace-match rpl t t string))))
22581 (while (setq pchg (next-property-change pchg string))
22582 (let ((sref (get-text-property pchg 'sref string)))
22583 (when (and sref (string-match "SREF" string pchg))
22584 (setq string (replace-match sref t t string)))))
22587 (defun org-find-base-buffer-visiting (file)
22588 "Like `find-buffer-visiting' but always return the base buffer and
22589 not an indirect buffer."
22590 (let ((buf (or (get-file-buffer file)
22591 (find-buffer-visiting file))))
22593 (or (buffer-base-buffer buf) buf)
22596 ;;; TODO: Only called once, from ox-odt which should probably use
22597 ;;; org-export-inline-image-p or something.
22598 (defun org-file-image-p (file)
22599 "Return non-nil if FILE is an image."
22601 (string-match (image-file-name-regexp) file)))
22603 (defun org-get-cursor-date (&optional with-time)
22604 "Return the date at cursor in as a time.
22605 This works in the calendar and in the agenda, anywhere else it just
22606 returns the current time.
22607 If WITH-TIME is non-nil, returns the time of the event at point (in
22608 the agenda) or the current time of the day."
22609 (let (date day defd tp hod mod)
22611 (setq tp (get-text-property (point) 'time))
22612 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22613 (setq hod (string-to-number (match-string 1 tp))
22614 mod (string-to-number (match-string 2 tp))))
22615 (or tp (let ((now (decode-time)))
22616 (setq hod (nth 2 now)
22617 mod (nth 1 now)))))
22619 ((eq major-mode 'calendar-mode)
22620 (setq date (calendar-cursor-to-date)
22621 defd (encode-time 0 (or mod 0) (or hod 0)
22622 (nth 1 date) (nth 0 date) (nth 2 date))))
22623 ((eq major-mode 'org-agenda-mode)
22624 (setq day (get-text-property (point) 'day))
22626 (setq date (calendar-gregorian-from-absolute day)
22627 defd (encode-time 0 (or mod 0) (or hod 0)
22628 (nth 1 date) (nth 0 date) (nth 2 date))))))
22629 (or defd (current-time))))
22631 (defun org-mark-subtree (&optional up)
22632 "Mark the current subtree.
22633 This puts point at the start of the current subtree, and mark at
22634 the end. If a numeric prefix UP is given, move up into the
22635 hierarchy of headlines by UP levels before marking the subtree."
22637 (org-with-limited-levels
22638 (cond ((org-at-heading-p) (beginning-of-line))
22639 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22640 (t (outline-previous-visible-heading 1))))
22641 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22642 (if (called-interactively-p 'any)
22643 (call-interactively 'org-mark-element)
22644 (org-mark-element)))
22646 (defun org-file-newer-than-p (file time)
22647 "Non-nil if FILE is newer than TIME.
22648 FILE is a filename, as a string, TIME is a list of integers, as
22649 returned by, e.g., `current-time'."
22650 (and (file-exists-p file)
22651 ;; Only compare times up to whole seconds as some file-systems
22652 ;; (e.g. HFS+) do not retain any finer granularity. As
22653 ;; a consequence, make sure we return non-nil when the two
22654 ;; times are equal.
22655 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22656 (cl-subseq time 0 2)))))
22658 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22659 "Compile a SOURCE file using PROCESS.
22661 PROCESS is either a function or a list of shell commands, as
22662 strings. EXT is a file extension, without the leading dot, as
22663 a string. It is used to check if the process actually succeeded.
22665 PROCESS must create a file with the same base name and directory
22666 as SOURCE, but ending with EXT. The function then returns its
22667 filename. Otherwise, it raises an error. The error message can
22668 then be refined by providing string ERR-MSG, which is appended to
22669 the standard message.
22671 If PROCESS is a function, it is called with a single argument:
22674 If it is a list of commands, each of them is called using
22675 `shell-command'. By default, in each command, %b, %f, %F, %o and
22676 %O are replaced with, respectively, SOURCE base name, name, full
22677 name, directory and absolute output file name. It is possible,
22678 however, to use more place-holders by specifying them in optional
22679 argument SPEC, as an alist following the pattern
22681 (CHARACTER . REPLACEMENT-STRING).
22683 When PROCESS is a list of commands, optional argument LOG-BUF can
22684 be set to a buffer or a buffer name. `shell-command' then uses
22686 (let* ((base-name (file-name-base source))
22687 (full-name (file-truename source))
22688 (out-dir (or (file-name-directory source) "./"))
22689 (output (expand-file-name (concat base-name "." ext) out-dir))
22690 (time (current-time))
22691 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22692 (save-window-excursion
22694 ((pred functionp) (funcall process (shell-quote-argument source)))
22696 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22698 `((?b . ,(shell-quote-argument base-name))
22699 (?f . ,(shell-quote-argument source))
22700 (?F . ,(shell-quote-argument full-name))
22701 (?o . ,(shell-quote-argument out-dir))
22702 (?O . ,(shell-quote-argument output))))))
22703 (dolist (command process)
22704 (shell-command (format-spec command spec) log-buf))))
22705 (_ (error "No valid command to process %S%s" source err-msg))))
22706 ;; Check for process failure. Output file is expected to be
22707 ;; located in the same directory as SOURCE.
22708 (unless (org-file-newer-than-p output time)
22709 (error (format "File %S wasn't produced%s" output err-msg)))
22714 (defun org--get-expected-indentation (element contentsp)
22715 "Expected indentation column for current line, according to ELEMENT.
22716 ELEMENT is an element containing point. CONTENTSP is non-nil
22717 when indentation is to be computed according to contents of
22719 (let ((type (org-element-type element))
22720 (start (org-element-property :begin element))
22721 (post-affiliated (org-element-property :post-affiliated element)))
22722 (org-with-wide-buffer
22726 ((diary-sexp footnote-definition) 0)
22727 ((headline inlinetask nil)
22728 (if (not org-adapt-indentation) 0
22729 (let ((level (org-current-level)))
22730 (if level (1+ level) 0))))
22731 ((item plain-list) (org-list-item-body-column post-affiliated))
22734 (org-get-indentation))))
22735 ((memq type '(headline inlinetask nil))
22736 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22737 (org--get-expected-indentation element t)
22739 ((memq type '(diary-sexp footnote-definition)) 0)
22740 ;; First paragraph of a footnote definition or an item.
22741 ;; Indent like parent.
22742 ((< (line-beginning-position) start)
22743 (org--get-expected-indentation
22744 (org-element-property :parent element) t))
22745 ;; At first line: indent according to previous sibling, if any,
22746 ;; ignoring footnote definitions and inline tasks, or parent's
22748 ((= (line-beginning-position) start)
22751 (if (= (point-min) start) (throw 'exit 0)
22752 (goto-char (1- start))
22753 (let* ((previous (org-element-at-point))
22755 (while (and parent (<= (org-element-property :end parent) start))
22756 (setq previous parent
22757 parent (org-element-property :parent parent)))
22759 ((not previous) (throw 'exit 0))
22760 ((> (org-element-property :end previous) start)
22761 (throw 'exit (org--get-expected-indentation previous t)))
22762 ((memq (org-element-type previous)
22763 '(footnote-definition inlinetask))
22764 (setq start (org-element-property :begin previous)))
22765 (t (goto-char (org-element-property :begin previous))
22767 (if (bolp) (org-get-indentation)
22768 ;; At first paragraph in an item or
22769 ;; a footnote definition.
22770 (org--get-expected-indentation
22771 (org-element-property :parent previous) t))))))))))
22772 ;; Otherwise, move to the first non-blank line above.
22774 (beginning-of-line)
22775 (let ((pos (point)))
22776 (skip-chars-backward " \r\t\n")
22778 ;; Two blank lines end a footnote definition or a plain
22779 ;; list. When we indent an empty line after them, the
22780 ;; containing list or footnote definition is over, so it
22781 ;; qualifies as a previous sibling. Therefore, we indent
22782 ;; like its first line.
22783 ((and (memq type '(footnote-definition plain-list))
22784 (> (count-lines (point) pos) 2))
22786 (org-get-indentation))
22787 ;; Line above is the first one of a paragraph at the
22788 ;; beginning of an item or a footnote definition. Indent
22790 ((< (line-beginning-position) start)
22791 (org--get-expected-indentation
22792 (org-element-property :parent element) t))
22793 ;; Line above is the beginning of an element, i.e., point
22794 ;; was originally on the blank lines between element's start
22796 ((= (line-beginning-position) post-affiliated)
22797 (org--get-expected-indentation element t))
22798 ;; POS is after contents in a greater element. Indent like
22799 ;; the beginning of the element.
22801 ;; As a special case, if point is at the end of a footnote
22802 ;; definition or an item, indent like the very last element
22803 ;; within. If that last element is an item, indent like its
22805 ((and (not (eq type 'paragraph))
22806 (let ((cend (org-element-property :contents-end element)))
22807 (and cend (<= cend pos))))
22808 (if (memq type '(footnote-definition item plain-list))
22809 (let ((last (org-element-at-point)))
22810 (org--get-expected-indentation
22811 last (eq (org-element-type last) 'item)))
22813 (org-get-indentation)))
22814 ;; In any other case, indent like the current line.
22815 (t (org-get-indentation)))))))))
22817 (defun org--align-node-property ()
22818 "Align node property at point.
22819 Alignment is done according to `org-property-format', which see."
22820 (when (save-excursion
22821 (beginning-of-line)
22822 (looking-at org-property-re))
22824 (concat (match-string 4)
22826 (format org-property-format (match-string 1) (match-string 3))))
22829 (defun org-indent-line ()
22830 "Indent line depending on context.
22832 Indentation is done according to the following rules:
22834 - Footnote definitions, diary sexps, headlines and inline tasks
22835 have to start at column 0.
22837 - On the very first line of an element, consider, in order, the
22838 next rules until one matches:
22840 1. If there's a sibling element before, ignoring footnote
22841 definitions and inline tasks, indent like its first line.
22843 2. If element has a parent, indent like its contents. More
22844 precisely, if parent is an item, indent after the
22845 description part, if any, or the bullet (see
22846 `org-list-description-max-indent'). Else, indent like
22847 parent's first line.
22849 3. Otherwise, indent relatively to current level, if
22850 `org-adapt-indentation' is non-nil, or to left margin.
22852 - On a blank line at the end of an element, indent according to
22853 the type of the element. More precisely
22855 1. If element is a plain list, an item, or a footnote
22856 definition, indent like the very last element within.
22858 2. If element is a paragraph, indent like its last non blank
22861 3. Otherwise, indent like its very first line.
22863 - In the code part of a source block, use language major mode
22864 to indent current line if `org-src-tab-acts-natively' is
22865 non-nil. If it is nil, do nothing.
22867 - Otherwise, indent like the first non-blank line above.
22869 The function doesn't indent an item as it could break the whole
22870 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22871 `\\[org-shiftmetaright]'.
22873 Also align node properties according to `org-property-format'."
22877 (let ((indent-line-function
22878 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22879 (indent-according-to-mode)))
22880 ((org-at-heading-p) 'noindent)
22882 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22883 (type (org-element-type element)))
22884 (cond ((and (memq type '(plain-list item))
22885 (= (line-beginning-position)
22886 (org-element-property :post-affiliated element)))
22888 ((and (eq type 'src-block)
22889 org-src-tab-acts-natively
22890 (> (line-beginning-position)
22891 (org-element-property :post-affiliated element))
22892 (< (line-beginning-position)
22893 (org-with-wide-buffer
22894 (goto-char (org-element-property :end element))
22895 (skip-chars-backward " \r\t\n")
22896 (line-beginning-position))))
22897 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22899 (let ((column (org--get-expected-indentation element nil)))
22900 ;; Preserve current column.
22901 (if (<= (current-column) (current-indentation))
22902 (indent-line-to column)
22903 (save-excursion (indent-line-to column))))
22904 ;; Align node property. Also preserve current column.
22905 (when (eq type 'node-property)
22906 (let ((column (current-column)))
22907 (org--align-node-property)
22908 (org-move-to-column column)))))))))
22910 (defun org-indent-region (start end)
22911 "Indent each non-blank line in the region.
22912 Called from a program, START and END specify the region to
22913 indent. The function will not indent contents of example blocks,
22914 verse blocks and export blocks as leading white spaces are
22915 assumed to be significant there."
22919 (skip-chars-forward " \r\t\n")
22920 (unless (eobp) (beginning-of-line))
22923 ;; Set IND as indentation for all lines between point and
22924 ;; POS. Blank lines are ignored. Leave point after POS
22926 (let ((limit (copy-marker pos)))
22927 (while (< (point) limit)
22928 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22930 (set-marker limit nil))))
22931 (end (copy-marker end)))
22932 (while (< (point) end)
22933 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22934 (let* ((element (org-element-at-point))
22935 (type (org-element-type element))
22936 (element-end (copy-marker (org-element-property :end element)))
22937 (ind (org--get-expected-indentation element nil)))
22939 ((or (memq type '(paragraph table table-row))
22940 (not (or (org-element-property :contents-begin element)
22942 '(example-block export-block src-block)))))
22943 ;; Elements here are indented as a single block. Also
22944 ;; align node properties.
22945 (when (eq type 'node-property)
22946 (org--align-node-property)
22947 (beginning-of-line))
22948 (funcall indent-to ind (min element-end end)))
22950 ;; Elements in this category consist of three parts:
22951 ;; before the contents, the contents, and after the
22952 ;; contents. The contents are treated specially,
22953 ;; according to the element type, or not indented at
22954 ;; all. Other parts are indented as a single block.
22955 (let* ((post (copy-marker
22956 (org-element-property :post-affiliated element)))
22960 ((not (org-element-property :contents-begin element))
22961 ;; Fake contents for source blocks.
22962 (org-with-wide-buffer
22966 ((memq type '(footnote-definition item plain-list))
22967 ;; Contents in these elements could start on
22968 ;; the same line as the beginning of the
22969 ;; element. Make sure we start indenting
22970 ;; from the second line.
22971 (org-with-wide-buffer
22974 (skip-chars-forward " \r\t\n")
22975 (if (eobp) (point) (line-beginning-position))))
22976 (t (org-element-property :contents-begin element)))))
22978 (or (org-element-property :contents-end element)
22979 ;; Fake contents for source blocks.
22980 (org-with-wide-buffer
22981 (goto-char element-end)
22982 (skip-chars-backward " \r\t\n")
22983 (line-beginning-position)))
22985 ;; Do not change items indentation individually as it
22986 ;; might break the list as a whole. On the other
22987 ;; hand, when at a plain list, indent it as a whole.
22988 (cond ((eq type 'plain-list)
22989 (let ((offset (- ind (org-get-indentation))))
22990 (unless (zerop offset)
22991 (indent-rigidly (org-element-property :begin element)
22992 (org-element-property :end element)
22995 ((eq type 'item) (goto-char cbeg))
22996 (t (funcall indent-to ind (min cbeg end))))
22997 (when (< (point) end)
22999 ((example-block export-block verse-block))
23001 ;; In a source block, indent source code
23002 ;; according to language major mode, but only if
23003 ;; `org-src-tab-acts-natively' is non-nil.
23004 (when (and (< (point) end) org-src-tab-acts-natively)
23006 (org-babel-do-in-edit-buffer
23007 (indent-region (point-min) (point-max))))))
23008 (t (org-indent-region (point) (min cend end))))
23009 (goto-char (min cend end))
23010 (when (< (point) end)
23011 (funcall indent-to ind (min element-end end))))
23012 (set-marker post nil)
23013 (set-marker cbeg nil)
23014 (set-marker cend nil))))
23015 (set-marker element-end nil))))
23016 (set-marker end nil))))
23018 (defun org-indent-drawer ()
23019 "Indent the drawer at point."
23021 (unless (save-excursion
23022 (beginning-of-line)
23023 (looking-at-p org-drawer-regexp))
23024 (user-error "Not at a drawer"))
23025 (let ((element (org-element-at-point)))
23026 (unless (memq (org-element-type element) '(drawer property-drawer))
23027 (user-error "Not at a drawer"))
23028 (org-with-wide-buffer
23029 (org-indent-region (org-element-property :begin element)
23030 (org-element-property :end element))))
23031 (message "Drawer at point indented"))
23033 (defun org-indent-block ()
23034 "Indent the block at point."
23036 (unless (save-excursion
23037 (beginning-of-line)
23038 (let ((case-fold-search t))
23039 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23040 (user-error "Not at a block"))
23041 (let ((element (org-element-at-point)))
23042 (unless (memq (org-element-type element)
23043 '(comment-block center-block dynamic-block example-block
23044 export-block quote-block special-block
23045 src-block verse-block))
23046 (user-error "Not at a block"))
23047 (org-with-wide-buffer
23048 (org-indent-region (org-element-property :begin element)
23049 (org-element-property :end element))))
23050 (message "Block at point indented"))
23055 ;; We use our own fill-paragraph and auto-fill functions.
23057 ;; `org-fill-paragraph' relies on adaptive filling and context
23058 ;; checking. Appropriate `fill-prefix' is computed with
23059 ;; `org-adaptive-fill-function'.
23061 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23062 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23063 ;; `org-adaptive-fill-function' value. Internally,
23064 ;; `org-comment-line-break-function' breaks the line.
23066 ;; `org-setup-filling' installs filling and auto-filling related
23067 ;; variables during `org-mode' initialization.
23069 (defvar org-element-paragraph-separate) ; org-element.el
23070 (defun org-setup-filling ()
23071 (require 'org-element)
23072 ;; Prevent auto-fill from inserting unwanted new items.
23073 (when (boundp 'fill-nobreak-predicate)
23075 fill-nobreak-predicate
23077 (append fill-nobreak-predicate
23078 '(org-fill-line-break-nobreak-p
23079 org-fill-paragraph-with-timestamp-nobreak-p)))))
23080 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23081 (setq-local paragraph-start paragraph-ending)
23082 (setq-local paragraph-separate paragraph-ending))
23083 (setq-local fill-paragraph-function 'org-fill-paragraph)
23084 (setq-local auto-fill-inhibit-regexp nil)
23085 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23086 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23087 (setq-local comment-line-break-function 'org-comment-line-break-function))
23089 (defun org-fill-line-break-nobreak-p ()
23090 "Non-nil when a new line at point would create an Org line break."
23092 (skip-chars-backward "[ \t]")
23093 (skip-chars-backward "\\\\")
23094 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23096 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23097 "Non-nil when a new line at point would split a timestamp."
23098 (and (org-at-timestamp-p t)
23099 (not (looking-at org-ts-regexp-both))))
23101 (declare-function message-in-body-p "message" ())
23102 (defvar orgtbl-line-start-regexp) ; From org-table.el
23103 (defun org-adaptive-fill-function ()
23104 "Compute a fill prefix for the current line.
23105 Return fill prefix, as a string, or nil if current line isn't
23106 meant to be filled. For convenience, if `adaptive-fill-regexp'
23107 matches in paragraphs or comments, use it."
23109 (when (derived-mode-p 'message-mode)
23111 (beginning-of-line)
23112 (cond ((not (message-in-body-p)) (throw 'exit nil))
23113 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23114 ((looking-at message-cite-prefix-regexp)
23115 (throw 'exit (match-string-no-properties 0)))
23116 ((looking-at org-outline-regexp)
23117 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23118 (org-with-wide-buffer
23119 (unless (org-at-heading-p)
23120 (let* ((p (line-beginning-position))
23121 (element (save-excursion
23122 (beginning-of-line)
23123 (org-element-at-point)))
23124 (type (org-element-type element))
23125 (post-affiliated (org-element-property :post-affiliated element)))
23126 (unless (< p post-affiliated)
23130 (beginning-of-line)
23131 (looking-at "[ \t]*")
23132 (concat (match-string 0) "# ")))
23133 (footnote-definition "")
23135 (make-string (org-list-item-body-column post-affiliated) ?\s))
23137 ;; Fill prefix is usually the same as the current line,
23138 ;; unless the paragraph is at the beginning of an item.
23139 (let ((parent (org-element-property :parent element)))
23141 (beginning-of-line)
23142 (cond ((eq (org-element-type parent) 'item)
23143 (make-string (org-list-item-body-column
23144 (org-element-property :begin parent))
23146 ((and adaptive-fill-regexp
23148 ;; `adaptive-fill-function' to let
23149 ;; `fill-context-prefix' handle
23150 ;; `adaptive-fill-regexp' variable.
23151 (let (adaptive-fill-function)
23152 (fill-context-prefix
23154 (org-element-property :end element)))))
23155 ((looking-at "[ \t]+") (match-string 0))
23158 ;; Only fill contents if P is within block boundaries.
23159 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23162 (cend (save-excursion
23163 (goto-char (org-element-property :end element))
23164 (skip-chars-backward " \r\t\n")
23165 (line-beginning-position))))
23166 (when (and (>= p cbeg) (< p cend))
23167 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23171 (declare-function message-goto-body "message" ())
23172 (defvar message-cite-prefix-regexp) ; From message.el
23173 (defun org-fill-paragraph (&optional justify)
23174 "Fill element at point, when applicable.
23176 This function only applies to comment blocks, comments, example
23177 blocks and paragraphs. Also, as a special case, re-align table
23178 when point is at one.
23180 If JUSTIFY is non-nil (interactively, with prefix argument),
23181 justify as well. If `sentence-end-double-space' is non-nil, then
23182 period followed by one space does not end a sentence, so don't
23183 break a line there. The variable `fill-column' controls the
23186 For convenience, when point is at a plain list, an item or
23187 a footnote definition, try to fill the first paragraph within."
23189 (if (and (derived-mode-p 'message-mode)
23190 (or (not (message-in-body-p))
23191 (save-excursion (move-beginning-of-line 1)
23192 (looking-at message-cite-prefix-regexp))))
23193 ;; First ensure filling is correct in message-mode.
23194 (let ((fill-paragraph-function
23195 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23196 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23197 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23198 (paragraph-separate
23199 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23200 (fill-paragraph nil))
23201 (with-syntax-table org-mode-transpose-word-syntax-table
23202 ;; Move to end of line in order to get the first paragraph
23203 ;; within a plain list or a footnote definition.
23204 (let ((element (save-excursion
23206 (or (ignore-errors (org-element-at-point))
23207 (user-error "An element cannot be parsed line %d"
23208 (line-number-at-pos (point)))))))
23209 ;; First check if point is in a blank line at the beginning of
23210 ;; the buffer. In that case, ignore filling.
23211 (cl-case (org-element-type element)
23212 ;; Use major mode filling function is src blocks.
23213 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23214 ;; Align Org tables, leave table.el tables as-is.
23215 (table-row (org-table-align) t)
23217 (when (eq (org-element-property :type element) 'org)
23219 (goto-char (org-element-property :post-affiliated element))
23220 (org-table-align)))
23223 ;; Paragraphs may contain `line-break' type objects.
23224 (let ((beg (max (point-min)
23225 (org-element-property :contents-begin element)))
23226 (end (min (point-max)
23227 (org-element-property :contents-end element))))
23228 ;; Do nothing if point is at an affiliated keyword.
23229 (if (< (line-end-position) beg) t
23230 (when (derived-mode-p 'message-mode)
23231 ;; In `message-mode', do not fill following citation
23232 ;; in current paragraph nor text before message body.
23233 (let ((body-start (save-excursion (message-goto-body))))
23234 (when body-start (setq beg (max body-start beg))))
23235 (when (save-excursion
23237 (concat "^" message-cite-prefix-regexp) end t))
23238 (setq end (match-beginning 0))))
23239 ;; Fill paragraph, taking line breaks into account.
23242 (let ((cuts (list beg)))
23243 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23244 (when (eq 'line-break
23246 (save-excursion (backward-char)
23247 (org-element-context))))
23248 (push (point) cuts)))
23249 (dolist (c (delq end cuts))
23250 (fill-region-as-paragraph c end justify)
23253 ;; Contents of `comment-block' type elements should be
23254 ;; filled as plain text, but only if point is within block
23257 (let* ((case-fold-search t)
23258 (beg (save-excursion
23259 (goto-char (org-element-property :begin element))
23260 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23263 (end (save-excursion
23264 (goto-char (org-element-property :end element))
23265 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23266 (line-beginning-position))))
23267 (if (or (< (point) beg) (> (point) end)) t
23268 (fill-region-as-paragraph
23269 (save-excursion (end-of-line)
23270 (re-search-backward "^[ \t]*$" beg 'move)
23271 (line-beginning-position))
23272 (save-excursion (beginning-of-line)
23273 (re-search-forward "^[ \t]*$" end 'move)
23274 (line-beginning-position))
23278 (let ((begin (org-element-property :post-affiliated element))
23279 (end (org-element-property :end element)))
23280 (when (and (>= (point) begin) (<= (point) end))
23281 (let ((begin (save-excursion
23283 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23284 (progn (forward-line) (point))
23286 (end (save-excursion
23288 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23289 (1- (line-beginning-position))
23290 (skip-chars-backward " \r\t\n")
23291 (line-end-position)))))
23292 ;; Do not fill comments when at a blank line.
23293 (when (> end begin)
23296 (beginning-of-line)
23297 (looking-at "[ \t]*#")
23298 (let ((comment-prefix (match-string 0)))
23299 (goto-char (match-end 0))
23300 (if (looking-at adaptive-fill-regexp)
23301 (concat comment-prefix (match-string 0))
23302 (concat comment-prefix " "))))))
23304 (fill-region-as-paragraph begin end justify))))))
23306 ;; Ignore every other element.
23309 (defun org-auto-fill-function ()
23310 "Auto-fill function."
23311 ;; Check if auto-filling is meaningful.
23312 (let ((fc (current-fill-column)))
23313 (when (and fc (> (current-column) fc))
23314 (let* ((fill-prefix (org-adaptive-fill-function))
23315 ;; Enforce empty fill prefix, if required. Otherwise, it
23316 ;; will be computed again.
23317 (adaptive-fill-mode (not (equal fill-prefix ""))))
23318 (when fill-prefix (do-auto-fill))))))
23320 (defun org-comment-line-break-function (&optional soft)
23321 "Break line at point and indent, continuing comment if within one.
23322 The inserted newline is marked hard if variable
23323 `use-hard-newlines' is true, unless optional argument SOFT is
23325 (if soft (insert-and-inherit ?\n) (newline 1))
23326 (save-excursion (forward-char -1) (delete-horizontal-space))
23327 (delete-horizontal-space)
23328 (indent-to-left-margin)
23329 (insert-before-markers-and-inherit fill-prefix))
23332 ;;; Fixed Width Areas
23334 (defun org-toggle-fixed-width ()
23335 "Toggle fixed-width markup.
23337 Add or remove fixed-width markup on current line, whenever it
23338 makes sense. Return an error otherwise.
23340 If a region is active and if it contains only fixed-width areas
23341 or blank lines, remove all fixed-width markup in it. If the
23342 region contains anything else, convert all non-fixed-width lines
23343 to fixed-width ones.
23345 Blank lines at the end of the region are ignored unless the
23346 region only contains such lines."
23348 (if (not (org-region-active-p))
23351 ;; Remove fixed width marker only in a fixed-with element.
23353 ;; Add fixed width maker in paragraphs, in blank lines after
23354 ;; elements or at the beginning of a headline or an inlinetask,
23355 ;; and before any one-line elements (e.g., a clock).
23357 (beginning-of-line)
23358 (let* ((element (org-element-at-point))
23359 (type (org-element-type element)))
23361 ((and (eq type 'fixed-width)
23362 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23364 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23365 ((and (memq type '(babel-call clock comment diary-sexp headline
23366 horizontal-rule keyword paragraph
23368 (<= (org-element-property :post-affiliated element) (point)))
23369 (skip-chars-forward " \t")
23371 ((and (looking-at-p "[ \t]*$")
23372 (or (eq type 'inlinetask)
23374 (skip-chars-forward " \r\t\n")
23375 (<= (org-element-property :end element) (point)))))
23376 (delete-region (point) (line-end-position))
23379 (t (user-error "Cannot insert a fixed-width line here")))))
23381 (let* ((begin (save-excursion
23382 (goto-char (region-beginning))
23383 (line-beginning-position)))
23386 (goto-char (region-end))
23387 (unless (eolp) (beginning-of-line))
23388 (if (save-excursion (re-search-backward "\\S-" begin t))
23389 (progn (skip-chars-backward " \r\t\n") (point))
23395 (skip-chars-forward " \r\t\n")
23396 (when (eobp) (throw 'not-all-p nil))
23397 (while (< (point) end)
23398 (let ((element (org-element-at-point)))
23399 (if (eq (org-element-type element) 'fixed-width)
23400 (goto-char (org-element-property :end element))
23401 (throw 'not-all-p nil))))
23403 (if all-fixed-width-p
23406 (while (< (point) end)
23407 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23410 (if (= (line-end-position) (match-end 0)) 0 1)))
23412 (let ((min-ind (point-max)))
23413 ;; Find minimum indentation across all lines.
23416 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23419 (while (< (point) end)
23420 (unless (looking-at-p "[ \t]*$")
23421 (let ((ind (org-get-indentation)))
23422 (setq min-ind (min min-ind ind))
23423 (when (zerop ind) (throw 'zerop t))))
23425 ;; Loop over all lines and add fixed-width markup everywhere
23426 ;; but in fixed-width lines.
23429 (while (< (point) end)
23431 ((org-at-heading-p)
23434 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23437 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23438 (let* ((element (org-element-at-point))
23439 (element-end (org-element-property :end element)))
23440 (if (eq (org-element-type element) 'fixed-width)
23441 (progn (goto-char element-end)
23442 (skip-chars-backward " \r\t\n")
23444 (let ((limit (min end element-end)))
23445 (while (< (point) limit)
23446 (org-move-to-column min-ind t)
23448 (forward-line))))))
23450 (org-move-to-column min-ind t)
23452 (forward-line)))))))
23453 (set-marker end nil))))
23458 ;; Org comments syntax is quite complex. It requires the entire line
23459 ;; to be just a comment. Also, even with the right syntax at the
23460 ;; beginning of line, some some elements (i.e. verse-block or
23461 ;; example-block) don't accept comments. Usual Emacs comment commands
23462 ;; cannot cope with those requirements. Therefore, Org replaces them.
23464 ;; Org still relies on `comment-dwim', but cannot trust
23465 ;; `comment-only-p'. So, `comment-region-function' and
23466 ;; `uncomment-region-function' both point
23467 ;; to`org-comment-or-uncomment-region'. Eventually,
23468 ;; `org-insert-comment' takes care of insertion of comments at the
23469 ;; beginning of line.
23471 ;; `org-setup-comments-handling' install comments related variables
23472 ;; during `org-mode' initialization.
23474 (defun org-setup-comments-handling ()
23476 (setq-local comment-use-syntax nil)
23477 (setq-local comment-start "# ")
23478 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23479 (setq-local comment-insert-comment-function 'org-insert-comment)
23480 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23481 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23483 (defun org-insert-comment ()
23484 "Insert an empty comment above current line.
23485 If the line is empty, insert comment at its beginning. When
23486 point is within a source block, comment according to the related
23488 (if (let ((element (org-element-at-point)))
23489 (and (eq (org-element-type element) 'src-block)
23491 (goto-char (org-element-property :post-affiliated element))
23492 (line-end-position))
23495 (goto-char (org-element-property :end element))
23496 (skip-chars-backward " \r\t\n")
23497 (line-beginning-position))
23499 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23500 (beginning-of-line)
23501 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23506 (defvar comment-empty-lines) ; From newcomment.el.
23507 (defun org-comment-or-uncomment-region (beg end &rest _)
23508 "Comment or uncomment each non-blank line in the region.
23509 Uncomment each non-blank line between BEG and END if it only
23510 contains commented lines. Otherwise, comment them. If region is
23511 strictly within a source block, use appropriate comment syntax."
23512 (if (let ((element (org-element-at-point)))
23513 (and (eq (org-element-type element) 'src-block)
23515 (goto-char (org-element-property :post-affiliated element))
23516 (line-end-position))
23518 (>= (save-excursion
23519 (goto-char (org-element-property :end element))
23520 (skip-chars-backward " \r\t\n")
23521 (line-beginning-position))
23523 ;; Translate region boundaries for the Org buffer to the source
23525 (let ((offset (- end beg)))
23528 (org-babel-do-in-edit-buffer
23529 (comment-or-uncomment-region (point) (+ offset (point))))))
23532 (narrow-to-region (save-excursion (goto-char beg)
23533 (skip-chars-forward " \r\t\n" end)
23534 (line-beginning-position))
23535 (save-excursion (goto-char end)
23536 (skip-chars-backward " \r\t\n" beg)
23537 (line-end-position)))
23539 ;; UNCOMMENTP is non-nil when every non blank line between
23540 ;; BEG and END is a comment.
23542 (goto-char (point-min))
23543 (while (and (not (eobp))
23544 (let ((element (org-element-at-point)))
23545 (and (eq (org-element-type element) 'comment)
23546 (goto-char (min (point-max)
23547 (org-element-property
23548 :end element)))))))
23551 ;; Only blank lines and comments in region: uncomment it.
23553 (goto-char (point-min))
23554 (while (not (eobp))
23555 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23556 (replace-match "" nil nil nil 1))
23558 ;; Comment each line in region.
23559 (let ((min-indent (point-max)))
23560 ;; First find the minimum indentation across all lines.
23562 (goto-char (point-min))
23563 (while (and (not (eobp)) (not (zerop min-indent)))
23564 (unless (looking-at "[ \t]*$")
23565 (setq min-indent (min min-indent (current-indentation))))
23567 ;; Then loop over all lines.
23569 (goto-char (point-min))
23570 (while (not (eobp))
23571 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23572 ;; Don't get fooled by invisible text (e.g. link path)
23573 ;; when moving to column MIN-INDENT.
23574 (let ((buffer-invisibility-spec nil))
23575 (org-move-to-column min-indent t))
23576 (insert comment-start))
23577 (forward-line)))))))))
23579 (defun org-comment-dwim (_arg)
23580 "Call `comment-dwim' within a source edit buffer if needed."
23582 (if (org-in-src-block-p)
23583 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23584 (call-interactively 'comment-dwim)))
23589 ;; This section contains tools to operate on timestamp objects, as
23590 ;; returned by, e.g. `org-element-context'.
23592 (defun org-timestamp--to-internal-time (timestamp &optional end)
23593 "Encode TIMESTAMP object into Emacs internal time.
23594 Use end of date range or time range when END is non-nil."
23595 (apply #'encode-time
23598 (lambda (prop) (or (org-element-property prop timestamp) 0))
23599 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23600 '(:minute-start :hour-start :day-start :month-start
23603 (defun org-timestamp-has-time-p (timestamp)
23604 "Non-nil when TIMESTAMP has a time specified."
23605 (org-element-property :hour-start timestamp))
23607 (defun org-timestamp-format (timestamp format &optional end utc)
23608 "Format a TIMESTAMP object into a string.
23610 FORMAT is a format specifier to be passed to
23611 `format-time-string'.
23613 When optional argument END is non-nil, use end of date-range or
23614 time-range, if possible.
23616 When optional argument UTC is non-nil, time will be expressed as
23618 (format-time-string
23619 format (org-timestamp--to-internal-time timestamp end)
23622 (defun org-timestamp-split-range (timestamp &optional end)
23623 "Extract a TIMESTAMP object from a date or time range.
23625 END, when non-nil, means extract the end of the range.
23626 Otherwise, extract its start.
23628 Return a new timestamp object."
23629 (let ((type (org-element-property :type timestamp)))
23630 (if (memq type '(active inactive diary)) timestamp
23631 (let ((split-ts (org-element-copy timestamp)))
23633 (org-element-put-property
23634 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23635 ;; Copy start properties over end properties if END is
23636 ;; non-nil. Otherwise, copy end properties over `start' ones.
23637 (let ((p-alist '((:minute-start . :minute-end)
23638 (:hour-start . :hour-end)
23639 (:day-start . :day-end)
23640 (:month-start . :month-end)
23641 (:year-start . :year-end))))
23642 (dolist (p-cell p-alist)
23643 (org-element-put-property
23645 (funcall (if end #'car #'cdr) p-cell)
23646 (org-element-property
23647 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23648 ;; Eventually refresh `:raw-value'.
23649 (org-element-put-property split-ts :raw-value nil)
23650 (org-element-put-property
23651 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23653 (defun org-timestamp-translate (timestamp &optional boundary)
23654 "Translate TIMESTAMP object to custom format.
23656 Format string is defined in `org-time-stamp-custom-formats',
23659 When optional argument BOUNDARY is non-nil, it is either the
23660 symbol `start' or `end'. In this case, only translate the
23661 starting or ending part of TIMESTAMP if it is a date or time
23662 range. Otherwise, translate both parts.
23664 Return timestamp as-is if `org-display-custom-times' is nil or if
23665 it has a `diary' type."
23666 (let ((type (org-element-property :type timestamp)))
23667 (if (or (not org-display-custom-times) (eq type 'diary))
23668 (org-element-interpret-data timestamp)
23669 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23670 org-time-stamp-custom-formats)))
23671 (if (and (not boundary) (memq type '(active-range inactive-range)))
23672 (concat (org-timestamp-format timestamp fmt)
23674 (org-timestamp-format timestamp fmt t))
23675 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23681 (defvar reftex-docstruct-symbol)
23684 (defun org-reftex-citation ()
23685 "Use reftex-citation to insert a citation into the buffer.
23686 This looks for a line like
23688 #+BIBLIOGRAPHY: foo plain option:-d
23690 and derives from it that foo.bib is the bibliography file relevant
23691 for this document. It then installs the necessary environment for RefTeX
23692 to work in this buffer and calls `reftex-citation' to insert a citation
23695 Export of such citations to both LaTeX and HTML is handled by the contributed
23696 package ox-bibtex by Taru Karttunen."
23698 (let ((reftex-docstruct-symbol 'org--rds)
23700 (org-with-wide-buffer
23701 (let ((case-fold-search t)
23702 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23703 (if (not (save-excursion
23704 (or (re-search-forward re nil t)
23705 (re-search-backward re nil t))))
23706 (user-error "No bibliography defined in file")
23707 (setq bib (concat (match-string 1) ".bib")
23708 org--rds (list (list 'bib bib))))))
23709 (call-interactively 'reftex-citation)))
23711 ;;;; Functions extending outline functionality
23713 (defun org-beginning-of-line (&optional n)
23714 "Go to the beginning of the current visible line.
23716 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23717 tags on the first attempt, and only move to after the tags when
23718 the cursor is already beyond the end of the headline.
23720 With argument N not nil or 1, move forward N - 1 lines first."
23722 (let ((origin (point))
23723 (special (pcase org-special-ctrl-a/e
23724 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23726 ;; First move to a visible line.
23727 (if (bound-and-true-p visual-line-mode)
23728 (beginning-of-visual-line n)
23729 (move-beginning-of-line n)
23730 ;; `move-beginning-of-line' may leave point after invisible
23731 ;; characters if line starts with such of these (e.g., with
23732 ;; a link at column 0). Really move to the beginning of the
23733 ;; current visible line.
23734 (beginning-of-line))
23736 ;; No special behavior. Point is already at the beginning of
23737 ;; a line, logical or visual.
23739 ;; `beginning-of-visual-line' left point before logical beginning
23740 ;; of line: point is at the beginning of a visual line. Bail
23742 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23743 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23744 ;; At a headline, special position is before the title, but
23745 ;; after any TODO keyword or priority cookie.
23746 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23747 (line-end-position)))
23749 (if (eq special 'reversed)
23750 (when (and (= origin bol) (eq last-command this-command))
23751 (goto-char refpos))
23752 (when (or (> origin refpos) (= origin bol))
23753 (goto-char refpos)))))
23754 ((and (looking-at org-list-full-item-re)
23755 (memq (org-element-type (save-match-data (org-element-at-point)))
23756 '(item plain-list)))
23757 ;; Set special position at first white space character after
23758 ;; bullet, and check-box, if any.
23759 (let ((after-bullet
23760 (let ((box (match-end 3)))
23761 (cond ((not box) (match-end 1))
23762 ((eq (char-after box) ?\s) (1+ box))
23764 (if (eq special 'reversed)
23765 (when (and (= (point) origin) (eq last-command this-command))
23766 (goto-char after-bullet))
23767 (when (or (> origin after-bullet) (= (point) origin))
23768 (goto-char after-bullet)))))
23769 ;; No special context. Point is already at beginning of line.
23772 (defun org-end-of-line (&optional n)
23773 "Go to the end of the line, but before ellipsis, if any.
23775 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23776 tags on the first attempt, and only move to after the tags when
23777 the cursor is already beyond the end of the headline.
23779 With argument N not nil or 1, move forward N - 1 lines first."
23781 (let ((origin (point))
23782 (special (pcase org-special-ctrl-a/e
23783 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23785 ;; First move to a visible line.
23786 (if (bound-and-true-p visual-line-mode)
23787 (beginning-of-visual-line n)
23788 (move-beginning-of-line n))
23790 ;; At a headline, with tags.
23793 (beginning-of-line)
23794 (let ((case-fold-search nil))
23795 (looking-at org-complex-heading-regexp)))
23797 (let ((tags (save-excursion
23798 (goto-char (match-beginning 5))
23799 (skip-chars-backward " \t")
23801 (visual-end (and (bound-and-true-p visual-line-mode)
23803 (end-of-visual-line)
23805 ;; If `end-of-visual-line' brings us before end of line or
23806 ;; even tags, i.e., the headline spans over multiple visual
23807 ;; lines, move there.
23808 (cond ((and visual-end
23809 (< visual-end tags)
23810 (<= origin visual-end))
23811 (goto-char visual-end))
23812 ((eq special 'reversed)
23813 (if (and (= origin (line-end-position))
23814 (eq this-command last-command))
23818 (if (or (< origin tags) (= origin (line-end-position)))
23821 ((bound-and-true-p visual-line-mode)
23822 (let ((bol (line-beginning-position)))
23823 (end-of-visual-line)
23824 ;; If `end-of-visual-line' gets us past the ellipsis at the
23825 ;; end of a line, backtrack and use `end-of-line' instead.
23826 (when (/= bol (line-beginning-position))
23829 (t (end-of-line)))))
23831 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23832 (define-key org-mode-map "\C-e" 'org-end-of-line)
23834 (defun org-backward-sentence (&optional _arg)
23835 "Go to beginning of sentence, or beginning of table field.
23836 This will call `backward-sentence' or `org-table-beginning-of-field',
23837 depending on context."
23839 (let* ((element (org-element-at-point))
23840 (contents-begin (org-element-property :contents-begin element))
23841 (table (org-element-lineage element '(table) t)))
23843 (> (point) contents-begin)
23844 (<= (point) (org-element-property :contents-end table)))
23845 (call-interactively #'org-table-beginning-of-field)
23847 (when (and contents-begin
23848 (< (point-min) contents-begin)
23849 (> (point) contents-begin))
23850 (narrow-to-region contents-begin
23851 (org-element-property :contents-end element)))
23852 (call-interactively #'backward-sentence)))))
23854 (defun org-forward-sentence (&optional _arg)
23855 "Go to end of sentence, or end of table field.
23856 This will call `forward-sentence' or `org-table-end-of-field',
23857 depending on context."
23859 (let* ((element (org-element-at-point))
23860 (contents-end (org-element-property :contents-end element))
23861 (table (org-element-lineage element '(table) t)))
23863 (>= (point) (org-element-property :contents-begin table))
23864 (< (point) contents-end))
23865 (call-interactively #'org-table-end-of-field)
23867 (when (and contents-end
23868 (> (point-max) contents-end)
23869 ;; Skip blank lines between elements.
23870 (< (org-element-property :end element)
23871 (save-excursion (goto-char contents-end)
23872 (skip-chars-forward " \r\t\n"))))
23873 (narrow-to-region (org-element-property :contents-begin element)
23875 (call-interactively #'forward-sentence)))))
23877 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23878 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23880 (defun org-kill-line (&optional _arg)
23881 "Kill line, to tags or end of line."
23884 ((or (not org-special-ctrl-k)
23886 (not (org-at-heading-p)))
23887 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23888 org-ctrl-k-protect-subtree
23889 (or (eq org-ctrl-k-protect-subtree 'error)
23890 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23891 (user-error "C-k aborted as it would kill a hidden subtree"))
23892 (call-interactively
23893 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23894 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23895 (kill-region (point) (match-beginning 1))
23896 (org-set-tags nil t))
23897 (t (kill-region (point) (point-at-eol)))))
23899 (define-key org-mode-map "\C-k" 'org-kill-line)
23901 (defun org-yank (&optional arg)
23902 "Yank. If the kill is a subtree, treat it specially.
23903 This command will look at the current kill and check if is a single
23904 subtree, or a series of subtrees[1]. If it passes the test, and if the
23905 cursor is at the beginning of a line or after the stars of a currently
23906 empty headline, then the yank is handled specially. How exactly depends
23907 on the value of the following variables.
23909 `org-yank-folded-subtrees'
23910 By default, this variable is non-nil, which results in
23911 subtree(s) being folded after insertion, except if doing so
23912 would swallow text after the yanked text.
23914 `org-yank-adjusted-subtrees'
23915 When non-nil (the default value is nil), the subtree will be
23916 promoted or demoted in order to fit into the local outline tree
23917 structure, which means that the level will be adjusted so that it
23918 becomes the smaller one of the two *visible* surrounding headings.
23920 Any prefix to this command will cause `yank' to be called directly with
23921 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23923 plainly yank the text as it is.
23925 \[1] The test checks if the first non-white line is a heading
23926 and if there are no other headings with fewer stars."
23928 (org-yank-generic 'yank arg))
23930 (defun org-yank-generic (command arg)
23931 "Perform some yank-like command.
23933 This function implements the behavior described in the `org-yank'
23934 documentation. However, it has been generalized to work for any
23935 interactive command with similar behavior."
23937 ;; pretend to be command COMMAND
23938 (setq this-command command)
23941 (call-interactively command)
23943 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23944 (and (org-kill-is-subtree-p)
23946 (and (looking-at "[ \t]*$")
23949 (buffer-substring (point-at-bol) (point)))))))
23952 ((and subtreep org-yank-folded-subtrees)
23953 (let ((beg (point))
23955 (if (and subtreep org-yank-adjusted-subtrees)
23956 (org-paste-subtree nil nil 'for-yank)
23957 (call-interactively command))
23961 (when (and (bolp) subtreep
23962 (not (setq swallowp
23963 (org-yank-folding-would-swallow-text beg end))))
23964 (org-with-limited-levels
23965 (or (looking-at org-outline-regexp)
23966 (re-search-forward org-outline-regexp-bol end t))
23967 (while (and (< (point) end) (looking-at org-outline-regexp))
23968 (outline-hide-subtree)
23969 (org-cycle-show-empty-lines 'folded)
23970 (condition-case nil
23971 (outline-forward-same-level 1)
23972 (error (goto-char end))))))
23975 "Inserted text not folded because that would swallow text"))
23978 (skip-chars-forward " \t\n\r")
23979 (beginning-of-line 1)
23980 (push-mark beg 'nomsg)))
23981 ((and subtreep org-yank-adjusted-subtrees)
23982 (let ((beg (point-at-bol)))
23983 (org-paste-subtree nil nil 'for-yank)
23984 (push-mark beg 'nomsg)))
23986 (call-interactively command))))))
23988 (defun org-yank-folding-would-swallow-text (beg end)
23989 "Would hide-subtree at BEG swallow any text after END?"
23991 (org-with-limited-levels
23994 (when (or (looking-at org-outline-regexp)
23995 (re-search-forward org-outline-regexp-bol end t))
23996 (setq level (org-outline-level)))
23998 (skip-chars-forward " \t\r\n\v\f")
24000 (and (bolp) (looking-at-p org-outline-regexp)
24001 (<= (org-outline-level) level))))))))
24003 (define-key org-mode-map "\C-y" 'org-yank)
24005 (defun org-truely-invisible-p ()
24006 "Check if point is at a character currently not visible.
24007 This version does not only check the character property, but also
24009 ;; Early versions of noutline don't have `outline-invisible-p'.
24010 (unless (bound-and-true-p visible-mode)
24011 (outline-invisible-p)))
24013 (defun org-invisible-p2 ()
24014 "Check if point is at a character currently not visible."
24016 (when (and (eolp) (not (bobp))) (backward-char 1))
24017 ;; Early versions of noutline don't have `outline-invisible-p'.
24018 (outline-invisible-p)))
24020 (defun org-back-to-heading (&optional invisible-ok)
24021 "Call `outline-back-to-heading', but provide a better error message."
24022 (condition-case nil
24023 (outline-back-to-heading invisible-ok)
24024 (error (error "Before first headline at position %d in buffer %s"
24025 (point) (current-buffer)))))
24027 (defun org-before-first-heading-p ()
24028 "Before first heading?"
24031 (null (re-search-backward org-outline-regexp-bol nil t))))
24033 (defun org-at-heading-p (&optional ignored)
24034 (outline-on-heading-p t))
24036 (defun org-in-commented-heading-p (&optional no-inheritance)
24037 "Non-nil if point is under a commented heading.
24038 This function also checks ancestors of the current headline,
24039 unless optional argument NO-INHERITANCE is non-nil."
24041 ((org-before-first-heading-p) nil)
24042 ((let ((headline (nth 4 (org-heading-components))))
24044 (let ((case-fold-search nil))
24045 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24047 (no-inheritance nil)
24049 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24051 (defun org-at-comment-p nil
24052 "Is cursor in a commented line?"
24055 (beginning-of-line)
24056 (looking-at "^[ \t]*# "))))
24058 (defun org-at-drawer-p nil
24059 "Is cursor at a drawer keyword?"
24061 (move-beginning-of-line 1)
24062 (looking-at org-drawer-regexp)))
24064 (defun org-at-block-p nil
24065 "Is cursor at a block keyword?"
24067 (move-beginning-of-line 1)
24068 (looking-at org-block-regexp)))
24070 (defun org-point-at-end-of-empty-headline ()
24071 "If point is at the end of an empty headline, return t, else nil.
24072 If the heading only contains a TODO keyword, it is still still considered
24074 (let ((case-fold-search nil))
24075 (and (looking-at "[ \t]*$")
24076 org-todo-line-regexp
24078 (beginning-of-line)
24079 (looking-at org-todo-line-regexp)
24080 (string= (match-string 3) "")))))
24082 (defun org-at-heading-or-item-p ()
24083 (or (org-at-heading-p) (org-at-item-p)))
24085 (defun org-at-target-p ()
24086 (or (org-in-regexp org-radio-target-regexp)
24087 (org-in-regexp org-target-regexp)))
24088 ;; Compatibility alias with Org versions < 7.8.03
24089 (defalias 'org-on-target-p 'org-at-target-p)
24091 (defun org-up-heading-all (arg)
24092 "Move to the heading line of which the present line is a subheading.
24093 This function considers both visible and invisible heading lines.
24094 With argument, move up ARG levels."
24095 (outline-up-heading arg t))
24097 (defun org-up-heading-safe ()
24098 "Move to the heading line of which the present line is a subheading.
24099 This version will not throw an error. It will return the level of the
24100 headline found, or nil if no higher level is found.
24102 Also, this function will be a lot faster than `outline-up-heading',
24103 because it relies on stars being the outline starters. This can really
24104 make a significant difference in outlines with very many siblings."
24105 (when (ignore-errors (org-back-to-heading t))
24106 (let ((level-up (1- (funcall outline-level))))
24107 (and (> level-up 0)
24108 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24109 (funcall outline-level)))))
24111 (defun org-first-sibling-p ()
24112 "Is this heading the first child of its parents?"
24114 (let ((re org-outline-regexp-bol)
24116 (unless (org-at-heading-p t)
24117 (user-error "Not at a heading"))
24118 (setq level (funcall outline-level))
24120 (if (not (re-search-backward re nil t))
24122 (setq l (funcall outline-level))
24125 (defun org-goto-sibling (&optional previous)
24126 "Goto the next sibling, even if it is invisible.
24127 When PREVIOUS is set, go to the previous sibling instead. Returns t
24128 when a sibling was found. When none is found, return nil and don't
24130 (let ((fun (if previous 're-search-backward 're-search-forward))
24132 (re org-outline-regexp-bol)
24134 (when (ignore-errors (org-back-to-heading t))
24135 (setq level (funcall outline-level))
24137 (or previous (forward-char 1))
24138 (while (funcall fun re nil t)
24139 (setq l (funcall outline-level))
24140 (when (< l level) (goto-char pos) (throw 'exit nil))
24141 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24145 (defun org-show-siblings ()
24146 "Show all siblings of the current headline."
24148 (while (org-goto-sibling) (org-flag-heading nil)))
24150 (while (org-goto-sibling 'previous)
24151 (org-flag-heading nil))))
24153 (defun org-goto-first-child ()
24154 "Goto the first child, even if it is invisible.
24155 Return t when a child was found. Otherwise don't move point and
24157 (let (level (pos (point)) (re org-outline-regexp-bol))
24158 (when (ignore-errors (org-back-to-heading t))
24159 (setq level (outline-level))
24161 (if (and (re-search-forward re nil t) (> (outline-level) level))
24162 (progn (goto-char (match-beginning 0)) t)
24163 (goto-char pos) nil))))
24165 (defun org-show-hidden-entry ()
24166 "Show an entry where even the heading is hidden."
24170 (defun org-flag-heading (flag &optional entry)
24171 "Flag the current heading. FLAG non-nil means make invisible.
24172 When ENTRY is non-nil, show the entire entry."
24174 (org-back-to-heading t)
24175 ;; Check if we should show the entire entry
24180 (and (outline-next-heading)
24181 (org-flag-heading nil))))
24182 (outline-flag-region (max (point-min) (1- (point)))
24183 (save-excursion (outline-end-of-heading) (point))
24186 (defun org-get-next-sibling ()
24187 "Move to next heading of the same level, and return point.
24188 If there is no such heading, return nil.
24189 This is like outline-next-sibling, but invisible headings are ok."
24190 (let ((level (funcall outline-level)))
24191 (outline-next-heading)
24192 (while (and (not (eobp)) (> (funcall outline-level) level))
24193 (outline-next-heading))
24194 (unless (or (eobp) (< (funcall outline-level) level))
24197 (defun org-get-last-sibling ()
24198 "Move to previous heading of the same level, and return point.
24199 If there is no such heading, return nil."
24200 (let ((opoint (point))
24201 (level (funcall outline-level)))
24202 (outline-previous-heading)
24203 (when (and (/= (point) opoint) (outline-on-heading-p t))
24204 (while (and (> (funcall outline-level) level)
24206 (outline-previous-heading))
24207 (unless (< (funcall outline-level) level)
24210 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24211 "Goto to the end of a subtree."
24212 ;; This contains an exact copy of the original function, but it uses
24213 ;; `org-back-to-heading', to make it work also in invisible
24214 ;; trees. And is uses an invisible-ok argument.
24215 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24216 ;; Furthermore, when used inside Org, finding the end of a large subtree
24217 ;; with many children and grandchildren etc, this can be much faster
24218 ;; than the outline version.
24219 (org-back-to-heading invisible-ok)
24221 (level (funcall outline-level)))
24222 (if (and (derived-mode-p 'org-mode) (< level 1000))
24223 ;; A true heading (not a plain list item), in Org
24224 ;; This means we can easily find the end by looking
24225 ;; only for the right number of stars. Using a regexp to do
24226 ;; this is so much faster than using a Lisp loop.
24227 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24229 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24230 ;; something else, do it the slow way
24231 (while (and (not (eobp))
24232 (or first (> (funcall outline-level) level)))
24234 (outline-next-heading)))
24236 (when (memq (preceding-char) '(?\n ?\^M))
24237 ;; Go to end of line before heading
24239 (when (memq (preceding-char) '(?\n ?\^M))
24240 ;; leave blank line before heading
24241 (forward-char -1)))))
24244 (defun org-end-of-meta-data (&optional full)
24245 "Skip planning line and properties drawer in current entry.
24246 When optional argument FULL is non-nil, also skip empty lines,
24247 clocking lines and regular drawers at the beginning of the
24249 (org-back-to-heading t)
24251 (when (looking-at-p org-planning-line-re) (forward-line))
24252 (when (looking-at org-property-drawer-re)
24253 (goto-char (match-end 0))
24255 (when (and full (not (org-at-heading-p)))
24257 (let ((end (save-excursion (outline-next-heading) (point)))
24258 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24259 (while (not (eobp))
24260 (cond ((looking-at-p org-drawer-regexp)
24261 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24264 ((looking-at-p re) (forward-line))
24265 (t (throw 'exit t))))))))
24267 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24268 "Move forward to the ARG'th subheading at same level as this one.
24269 Stop at the first and last subheadings of a superior heading.
24270 Normally this only looks at visible headings, but when INVISIBLE-OK is
24271 non-nil it will also look at invisible ones."
24273 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24274 (if (and arg (< arg 0))
24275 (goto-char (point-min))
24276 (outline-next-heading))
24278 (let ((level (- (match-end 0) (match-beginning 0) 1))
24279 (f (if (and arg (< arg 0))
24280 're-search-backward
24281 're-search-forward))
24282 (count (if arg (abs arg) 1))
24284 (while (and (prog1 (> count 0)
24285 (forward-char (if (and arg (< arg 0)) -1 1)))
24286 (funcall f org-outline-regexp-bol nil 'move))
24287 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24288 (cond ((< l level) (setq count 0))
24292 (goto-char (line-beginning-position))
24293 (not (outline-invisible-p)))))
24294 (setq count (1- count))
24296 (setq result (point)))))))
24297 (goto-char result))
24298 (beginning-of-line 1)))
24300 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24301 "Move backward to the ARG'th subheading at same level as this one.
24302 Stop at the first and last subheadings of a superior heading."
24304 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24306 (defun org-next-visible-heading (arg)
24307 "Move to the next visible heading.
24309 This function wraps `outline-next-visible-heading' with
24310 `org-with-limited-levels' in order to skip over inline tasks and
24311 respect customization of `org-odd-levels-only'."
24313 (org-with-limited-levels
24314 (outline-next-visible-heading arg)))
24316 (defun org-previous-visible-heading (arg)
24317 "Move to the previous visible heading.
24319 This function wraps `outline-previous-visible-heading' with
24320 `org-with-limited-levels' in order to skip over inline tasks and
24321 respect customization of `org-odd-levels-only'."
24323 (org-with-limited-levels
24324 (outline-previous-visible-heading arg)))
24326 (defun org-next-block (arg &optional backward block-regexp)
24327 "Jump to the next block.
24329 With a prefix argument ARG, jump forward ARG many blocks.
24331 When BACKWARD is non-nil, jump to the previous block.
24333 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24334 Match data is set according to this regexp when the function
24337 Return point at beginning of the opening line of found block.
24338 Throw an error if no block is found."
24340 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24341 (case-fold-search t)
24342 (search-fn (if backward #'re-search-backward #'re-search-forward))
24346 (if backward (beginning-of-line) (end-of-line))
24347 (while (and (> count 0) (funcall search-fn re nil t))
24348 (let ((element (save-excursion
24349 (goto-char (match-beginning 0))
24350 (save-match-data (org-element-at-point)))))
24351 (when (and (memq (org-element-type element)
24352 '(center-block comment-block dynamic-block
24353 example-block export-block quote-block
24354 special-block src-block verse-block))
24355 (<= (match-beginning 0)
24356 (org-element-property :post-affiliated element)))
24357 (setq last-element element)
24360 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24361 (save-match-data (org-show-context)))
24363 (user-error "No %s code blocks" (if backward "previous" "further")))))
24365 (defun org-previous-block (arg &optional block-regexp)
24366 "Jump to the previous block.
24367 With a prefix argument ARG, jump backward ARG many source blocks.
24368 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24370 (org-next-block arg t block-regexp))
24372 (defun org-forward-paragraph ()
24373 "Move forward to beginning of next paragraph or equivalent.
24375 The function moves point to the beginning of the next visible
24376 structural element, which can be a paragraph, a table, a list
24377 item, etc. It also provides some special moves for convenience:
24379 - On an affiliated keyword, jump to the beginning of the
24381 - On an item or a footnote definition, move to the second
24382 element inside, if any.
24383 - On a table or a property drawer, jump after it.
24384 - On a verse or source block, stop after blank lines."
24386 (when (eobp) (user-error "Cannot move further down"))
24387 (let* ((deactivate-mark nil)
24388 (element (org-element-at-point))
24389 (type (org-element-type element))
24390 (post-affiliated (org-element-property :post-affiliated element))
24391 (contents-begin (org-element-property :contents-begin element))
24392 (contents-end (org-element-property :contents-end element))
24393 (end (let ((end (org-element-property :end element)) (parent element))
24394 (while (and (setq parent (org-element-property :parent parent))
24395 (= (org-element-property :contents-end parent) end))
24396 (setq end (org-element-property :end parent)))
24398 (cond ((not element)
24399 (skip-chars-forward " \r\t\n")
24400 (or (eobp) (beginning-of-line)))
24401 ;; On affiliated keywords, move to element's beginning.
24402 ((< (point) post-affiliated)
24403 (goto-char post-affiliated))
24404 ;; At a table row, move to the end of the table. Similarly,
24405 ;; at a node property, move to the end of the property
24407 ((memq type '(node-property table-row))
24408 (goto-char (org-element-property
24409 :end (org-element-property :parent element))))
24410 ((memq type '(property-drawer table)) (goto-char end))
24411 ;; Consider blank lines as separators in verse and source
24412 ;; blocks to ease editing.
24413 ((memq type '(src-block verse-block))
24414 (when (eq type 'src-block)
24416 (save-excursion (goto-char end)
24417 (skip-chars-backward " \r\t\n")
24418 (line-beginning-position))))
24419 (beginning-of-line)
24420 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24421 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24423 (skip-chars-forward " \r\t\n")
24424 (if (= (point) contents-end) (goto-char end)
24425 (beginning-of-line))))
24426 ;; With no contents, just skip element.
24427 ((not contents-begin) (goto-char end))
24428 ;; If contents are invisible, skip the element altogether.
24429 ((outline-invisible-p (line-end-position))
24432 (org-with-limited-levels (outline-next-visible-heading 1)))
24433 ;; At a plain list, make sure we move to the next item
24434 ;; instead of skipping the whole list.
24435 (plain-list (forward-char)
24436 (org-forward-paragraph))
24437 (otherwise (goto-char end))))
24438 ((>= (point) contents-end) (goto-char end))
24439 ((>= (point) contents-begin)
24440 ;; This can only happen on paragraphs and plain lists.
24442 (paragraph (goto-char end))
24443 ;; At a plain list, try to move to second element in
24444 ;; first item, if possible.
24445 (plain-list (end-of-line)
24446 (org-forward-paragraph))))
24447 ;; When contents start on the middle of a line (e.g. in
24448 ;; items and footnote definitions), try to reach first
24449 ;; element starting after current line.
24450 ((> (line-end-position) contents-begin)
24452 (org-forward-paragraph))
24453 (t (goto-char contents-begin)))))
24455 (defun org-backward-paragraph ()
24456 "Move backward to start of previous paragraph or equivalent.
24458 The function moves point to the beginning of the current
24459 structural element, which can be a paragraph, a table, a list
24460 item, etc., or to the beginning of the previous visible one if
24461 point is already there. It also provides some special moves for
24464 - On an affiliated keyword, jump to the first one.
24465 - On a table or a property drawer, move to its beginning.
24466 - On a verse or source block, stop before blank lines."
24468 (when (bobp) (user-error "Cannot move further up"))
24469 (let* ((deactivate-mark nil)
24470 (element (org-element-at-point))
24471 (type (org-element-type element))
24472 (contents-begin (org-element-property :contents-begin element))
24473 (contents-end (org-element-property :contents-end element))
24474 (post-affiliated (org-element-property :post-affiliated element))
24475 (begin (org-element-property :begin element)))
24477 ((not element) (goto-char (point-min)))
24480 (org-backward-paragraph))
24481 ((<= (point) post-affiliated) (goto-char begin))
24482 ((memq type '(node-property table-row))
24483 (goto-char (org-element-property
24484 :post-affiliated (org-element-property :parent element))))
24485 ((memq type '(property-drawer table)) (goto-char begin))
24486 ((memq type '(src-block verse-block))
24487 (when (eq type 'src-block)
24488 (setq contents-begin
24489 (save-excursion (goto-char begin) (forward-line) (point))))
24490 (if (= (point) contents-begin) (goto-char post-affiliated)
24491 ;; Inside a verse block, see blank lines as paragraph
24493 (let ((origin (point)))
24494 (skip-chars-backward " \r\t\n" contents-begin)
24495 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24496 (skip-chars-forward " \r\t\n" origin)
24497 (if (= (point) origin) (goto-char contents-begin)
24498 (beginning-of-line))))))
24499 ((not contents-begin) (goto-char (or post-affiliated begin)))
24500 ((eq type 'paragraph)
24501 (goto-char contents-begin)
24502 ;; When at first paragraph in an item or a footnote definition,
24503 ;; move directly to beginning of line.
24504 (let ((parent-contents
24505 (org-element-property
24506 :contents-begin (org-element-property :parent element))))
24507 (when (and parent-contents (= parent-contents contents-begin))
24508 (beginning-of-line))))
24509 ;; At the end of a greater element, move to the beginning of the
24510 ;; last element within.
24511 ((>= (point) contents-end)
24512 (goto-char (1- contents-end))
24513 (org-backward-paragraph))
24514 (t (goto-char (or post-affiliated begin))))
24515 ;; Ensure we never leave point invisible.
24516 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24518 (defun org-forward-element ()
24519 "Move forward by one element.
24520 Move to the next element at the same level, when possible."
24522 (cond ((eobp) (user-error "Cannot move further down"))
24523 ((org-with-limited-levels (org-at-heading-p))
24524 (let ((origin (point)))
24525 (goto-char (org-end-of-subtree nil t))
24526 (unless (org-with-limited-levels (org-at-heading-p))
24528 (user-error "Cannot move further down"))))
24530 (let* ((elem (org-element-at-point))
24531 (end (org-element-property :end elem))
24532 (parent (org-element-property :parent elem)))
24533 (cond ((and parent (= (org-element-property :contents-end parent) end))
24534 (goto-char (org-element-property :end parent)))
24535 ((integer-or-marker-p end) (goto-char end))
24536 (t (message "No element at point")))))))
24538 (defun org-backward-element ()
24539 "Move backward by one element.
24540 Move to the previous element at the same level, when possible."
24542 (cond ((bobp) (user-error "Cannot move further up"))
24543 ((org-with-limited-levels (org-at-heading-p))
24544 ;; At a headline, move to the previous one, if any, or stay
24546 (let ((origin (point)))
24547 (org-with-limited-levels (org-backward-heading-same-level 1))
24548 ;; When current headline has no sibling above, move to its
24550 (when (= (point) origin)
24551 (or (org-with-limited-levels (org-up-heading-safe))
24552 (progn (goto-char origin)
24553 (user-error "Cannot move further up"))))))
24555 (let* ((elem (org-element-at-point))
24556 (beg (org-element-property :begin elem)))
24558 ;; Move to beginning of current element if point isn't
24560 ((null beg) (message "No element at point"))
24561 ((/= (point) beg) (goto-char beg))
24563 (skip-chars-backward " \r\t\n")
24565 (let ((prev (org-element-at-point)))
24566 (goto-char (org-element-property :begin prev))
24567 (while (and (setq prev (org-element-property :parent prev))
24568 (<= (org-element-property :end prev) beg))
24569 (goto-char (org-element-property :begin prev)))))))))))
24571 (defun org-up-element ()
24572 "Move to upper element."
24574 (if (org-with-limited-levels (org-at-heading-p))
24575 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24576 (let* ((elem (org-element-at-point))
24577 (parent (org-element-property :parent elem)))
24578 (if parent (goto-char (org-element-property :begin parent))
24579 (if (org-with-limited-levels (org-before-first-heading-p))
24580 (user-error "No surrounding element")
24581 (org-with-limited-levels (org-back-to-heading)))))))
24583 (defvar org-element-greater-elements)
24584 (defun org-down-element ()
24585 "Move to inner element."
24587 (let ((element (org-element-at-point)))
24589 ((memq (org-element-type element) '(plain-list table))
24590 (goto-char (org-element-property :contents-begin element))
24592 ((memq (org-element-type element) org-element-greater-elements)
24593 ;; If contents are hidden, first disclose them.
24594 (when (outline-invisible-p (line-end-position)) (org-cycle))
24595 (goto-char (or (org-element-property :contents-begin element)
24596 (user-error "No content for this element"))))
24597 (t (user-error "No inner element")))))
24599 (defun org-drag-element-backward ()
24600 "Move backward element at point."
24602 (let ((elem (or (org-element-at-point)
24603 (user-error "No element at point"))))
24604 (if (eq (org-element-type elem) 'headline)
24605 ;; Preserve point when moving a whole tree, even if point was
24606 ;; on blank lines below the headline.
24607 (let ((offset (skip-chars-backward " \t\n")))
24608 (unwind-protect (org-move-subtree-up)
24609 (forward-char (- offset))))
24612 (goto-char (org-element-property :begin elem))
24613 (skip-chars-backward " \r\t\n")
24615 (let* ((beg (org-element-property :begin elem))
24616 (prev (org-element-at-point))
24618 (while (and (setq up (org-element-property :parent up))
24619 (<= (org-element-property :end up) beg))
24622 ;; Error out if no previous element or previous element is
24623 ;; a parent of the current one.
24624 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24625 (user-error "Cannot drag element backward")
24626 (let ((pos (point)))
24627 (org-element-swap-A-B prev-elem elem)
24628 (goto-char (+ (org-element-property :begin prev-elem)
24629 (- pos (org-element-property :begin elem))))))))))
24631 (defun org-drag-element-forward ()
24632 "Move forward element at point."
24634 (let* ((pos (point))
24635 (elem (or (org-element-at-point)
24636 (user-error "No element at point"))))
24637 (when (= (point-max) (org-element-property :end elem))
24638 (user-error "Cannot drag element forward"))
24639 (goto-char (org-element-property :end elem))
24640 (let ((next-elem (org-element-at-point)))
24641 (when (or (org-element-nested-p elem next-elem)
24642 (and (eq (org-element-type next-elem) 'headline)
24643 (not (eq (org-element-type elem) 'headline))))
24645 (user-error "Cannot drag element forward"))
24646 ;; Compute new position of point: it's shifted by NEXT-ELEM
24647 ;; body's length (without final blanks) and by the length of
24648 ;; blanks between ELEM and NEXT-ELEM.
24649 (let ((size-next (- (save-excursion
24650 (goto-char (org-element-property :end next-elem))
24651 (skip-chars-backward " \r\t\n")
24653 ;; Small correction if buffer doesn't end
24654 ;; with a newline character.
24655 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24656 (org-element-property :begin next-elem)))
24657 (size-blank (- (org-element-property :end elem)
24659 (goto-char (org-element-property :end elem))
24660 (skip-chars-backward " \r\t\n")
24663 (org-element-swap-A-B elem next-elem)
24664 (goto-char (+ pos size-next size-blank))))))
24666 (defun org-drag-line-forward (arg)
24667 "Drag the line at point ARG lines forward."
24669 (dotimes (_ (abs arg))
24670 (let ((c (current-column)))
24673 (beginning-of-line 2)
24674 (transpose-lines 1)
24675 (beginning-of-line 0))
24676 (transpose-lines 1)
24677 (beginning-of-line -1))
24678 (org-move-to-column c))))
24680 (defun org-drag-line-backward (arg)
24681 "Drag the line at point ARG lines backward."
24683 (org-drag-line-forward (- arg)))
24685 (defun org-mark-element ()
24686 "Put point at beginning of this element, mark at end.
24688 Interactively, if this command is repeated or (in Transient Mark
24689 mode) if the mark is active, it marks the next element after the
24690 ones already marked."
24692 (let (deactivate-mark)
24693 (if (and (called-interactively-p 'any)
24694 (or (and (eq last-command this-command) (mark t))
24695 (and transient-mark-mode mark-active)))
24699 (goto-char (org-element-property :end (org-element-at-point)))))
24700 (let ((element (org-element-at-point)))
24702 (push-mark (org-element-property :end element) t t)
24703 (goto-char (org-element-property :begin element))))))
24705 (defun org-narrow-to-element ()
24706 "Narrow buffer to current element."
24708 (let ((elem (org-element-at-point)))
24710 ((eq (car elem) 'headline)
24712 (org-element-property :begin elem)
24713 (org-element-property :end elem)))
24714 ((memq (car elem) org-element-greater-elements)
24716 (org-element-property :contents-begin elem)
24717 (org-element-property :contents-end elem)))
24720 (org-element-property :begin elem)
24721 (org-element-property :end elem))))))
24723 (defun org-transpose-element ()
24724 "Transpose current and previous elements, keeping blank lines between.
24725 Point is moved after both elements."
24727 (org-skip-whitespace)
24728 (let ((end (org-element-property :end (org-element-at-point))))
24729 (org-drag-element-backward)
24732 (defun org-unindent-buffer ()
24733 "Un-indent the visible part of the buffer.
24734 Relative indentation (between items, inside blocks, etc.) isn't
24737 (unless (eq major-mode 'org-mode)
24738 (user-error "Cannot un-indent a buffer not in Org mode"))
24739 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24742 (dolist (element (reverse contents))
24743 (if (memq (org-element-type element) '(headline section))
24744 (funcall unindent-tree (org-element-contents element))
24748 (org-element-property :begin element)
24749 (org-element-property :end element))
24750 (org-do-remove-indentation))))))))
24751 (funcall unindent-tree (org-element-contents parse-tree))))
24753 (defun org-show-children (&optional level)
24754 "Show all direct subheadings of this heading.
24755 Prefix arg LEVEL is how many levels below the current level
24756 should be shown. Default is enough to cause the following
24757 heading to appear."
24759 ;; If `orgstruct-mode' is active, use the slower version.
24760 (if orgstruct-mode (call-interactively #'outline-show-children)
24762 (org-back-to-heading t)
24763 (let* ((current-level (funcall outline-level))
24764 (max-level (org-get-valid-level
24766 (if level (prefix-numeric-value level) 1)))
24767 (end (save-excursion (org-end-of-subtree t t)))
24768 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24769 (past-first-child nil)
24770 ;; Make sure to skip inlinetasks.
24771 (re (format regexp-fmt
24774 ((not (featurep 'org-inlinetask)) "")
24775 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24777 (t (1- org-inlinetask-min-level))))))
24778 ;; Display parent heading.
24779 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24781 ;; Display children. First child may be deeper than expected
24782 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24783 ;; MAX-LEVEL accordingly.
24784 (while (re-search-forward re end t)
24785 (unless past-first-child
24786 (setq re (format regexp-fmt
24788 (max (funcall outline-level) max-level)))
24789 (setq past-first-child t))
24790 (outline-flag-region
24791 (line-end-position 0) (line-end-position) nil))))))
24793 (defun org-show-subtree ()
24794 "Show everything after this heading at deeper levels."
24796 (outline-flag-region
24799 (org-end-of-subtree t t))
24802 (defun org-show-entry ()
24803 "Show the body directly following this heading.
24804 Show the heading too, if it is currently invisible."
24808 (org-back-to-heading t)
24809 (outline-flag-region
24810 (max (point-min) (1- (point)))
24812 (if (re-search-forward
24813 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24814 (match-beginning 1)
24817 (org-cycle-hide-drawers 'children))))
24819 (defun org-make-options-regexp (kwds &optional extra)
24820 "Make a regular expression for keyword lines.
24821 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24822 when non-nil, is a regexp matching keywords names."
24823 (concat "^[ \t]*#\\+\\("
24825 (and extra (concat (and kwds "\\|") extra))
24826 "\\):[ \t]*\\(.*\\)"))
24828 ;;;; Integration with and fixes for other packages
24832 (defvar-local org-imenu-markers nil
24833 "All markers currently used by Imenu.")
24835 (defun org-imenu-new-marker (&optional pos)
24836 "Return a new marker for use by Imenu, and remember the marker."
24837 (let ((m (make-marker)))
24838 (move-marker m (or pos (point)))
24839 (push m org-imenu-markers)
24842 (defun org-imenu-get-tree ()
24843 "Produce the index for Imenu."
24844 (dolist (x org-imenu-markers) (move-marker x nil))
24845 (setq org-imenu-markers nil)
24846 (let* ((case-fold-search nil)
24847 (n org-imenu-depth)
24848 (re (concat "^" (org-get-limited-outline-regexp)))
24849 (subs (make-vector (1+ n) nil))
24851 m level head0 head)
24852 (org-with-wide-buffer
24853 (goto-char (point-max))
24854 (while (re-search-backward re nil t)
24855 (setq level (org-reduced-level (funcall outline-level)))
24856 (when (and (<= level n)
24857 (looking-at org-complex-heading-regexp)
24858 (setq head0 (match-string-no-properties 4)))
24859 (setq head (org-link-display-format head0)
24860 m (org-imenu-new-marker))
24861 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24862 (if (>= level last-level)
24863 (push (cons head m) (aref subs level))
24864 (push (cons head (aref subs (1+ level))) (aref subs level))
24865 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24866 (setq last-level level))))
24869 (eval-after-load "imenu"
24871 (add-hook 'imenu-after-jump-hook
24873 (when (derived-mode-p 'org-mode)
24874 (org-show-context 'org-goto))))))
24876 (defun org-link-display-format (s)
24877 "Replace links in string S with their description.
24878 If there is no description, use the link target."
24880 (replace-regexp-in-string
24881 org-bracket-link-analytic-regexp
24883 (if (match-end 5) (match-string 5 m)
24884 (concat (match-string 1 m) (match-string 3 m))))
24887 (defun org-toggle-link-display ()
24888 "Toggle the literal or descriptive display of links."
24890 (if org-descriptive-links
24891 (progn (org-remove-from-invisibility-spec '(org-link))
24892 (org-restart-font-lock)
24893 (setq org-descriptive-links nil))
24894 (progn (add-to-invisibility-spec '(org-link))
24895 (org-restart-font-lock)
24896 (setq org-descriptive-links t))))
24898 ;; Speedbar support
24900 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24901 "Overlay marking the agenda restriction line in speedbar.")
24902 (overlay-put org-speedbar-restriction-lock-overlay
24903 'face 'org-agenda-restriction-lock)
24904 (overlay-put org-speedbar-restriction-lock-overlay
24905 'help-echo "Agendas are currently limited to this item.")
24906 (delete-overlay org-speedbar-restriction-lock-overlay)
24908 (defun org-speedbar-set-agenda-restriction ()
24909 "Restrict future agenda commands to the location at point in speedbar.
24910 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24912 (require 'org-agenda)
24913 (let (p m tp np dir txt)
24915 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24917 (setq m (get-text-property p 'org-imenu-marker))
24918 (with-current-buffer (marker-buffer m)
24920 (org-agenda-set-restriction-lock 'subtree)))
24921 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24922 'speedbar-function 'speedbar-find-file))
24923 (setq tp (previous-single-property-change
24924 (1+ p) 'speedbar-function)
24925 np (next-single-property-change
24926 tp 'speedbar-function)
24927 dir (speedbar-line-directory)
24928 txt (buffer-substring-no-properties (or tp (point-min))
24929 (or np (point-max))))
24930 (with-current-buffer (find-file-noselect
24931 (let ((default-directory dir))
24932 (expand-file-name txt)))
24933 (unless (derived-mode-p 'org-mode)
24934 (user-error "Cannot restrict to non-Org mode file"))
24935 (org-agenda-set-restriction-lock 'file)))
24936 (t (user-error "Don't know how to restrict Org mode agenda")))
24937 (move-overlay org-speedbar-restriction-lock-overlay
24938 (point-at-bol) (point-at-eol))
24939 (setq current-prefix-arg nil)
24940 (org-agenda-maybe-redo)))
24942 (defvar speedbar-file-key-map)
24943 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24944 (eval-after-load "speedbar"
24946 (speedbar-add-supported-extension ".org")
24947 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24948 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24949 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24950 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24951 (add-hook 'speedbar-visiting-tag-hook
24952 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24954 ;;; Fixes and Hacks for problems with other packages
24956 (defun org--flyspell-object-check-p (element)
24957 "Non-nil when Flyspell can check object at point.
24958 ELEMENT is the element at point."
24959 (let ((object (save-excursion
24960 (when (looking-at-p "\\>") (backward-char))
24961 (org-element-context element))))
24962 (cl-case (org-element-type object)
24963 ;; Prevent checks in links due to keybinding conflict with
24965 ((code entity export-snippet inline-babel-call
24966 inline-src-block line-break latex-fragment link macro
24967 statistics-cookie target timestamp verbatim)
24969 (footnote-reference
24970 ;; Only in inline footnotes, within the definition.
24971 (and (eq (org-element-property :type object) 'inline)
24973 (goto-char (org-element-property :begin object))
24974 (search-forward ":" nil t 2))
24978 (defun org-mode-flyspell-verify ()
24979 "Function used for `flyspell-generic-check-word-predicate'."
24980 (if (org-at-heading-p)
24981 ;; At a headline or an inlinetask, check title only. This is
24982 ;; faster than relying on `org-element-at-point'.
24983 (and (save-excursion (beginning-of-line)
24984 (and (let ((case-fold-search t))
24985 (not (looking-at-p "\\*+ END[ \t]*$")))
24986 (let ((case-fold-search nil))
24987 (looking-at org-complex-heading-regexp))))
24988 (match-beginning 4)
24989 (>= (point) (match-beginning 4))
24990 (or (not (match-beginning 5))
24991 (< (point) (match-beginning 5))))
24992 (let* ((element (org-element-at-point))
24993 (post-affiliated (org-element-property :post-affiliated element)))
24995 ;; Ignore checks in all affiliated keywords but captions.
24996 ((< (point) post-affiliated)
24997 (and (save-excursion
24998 (beginning-of-line)
24999 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25000 (> (point) (match-end 0))
25001 (org--flyspell-object-check-p element)))
25002 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25003 ((let ((log (org-log-into-drawer)))
25005 (let ((drawer (org-element-lineage element '(drawer))))
25007 (eq (compare-strings
25009 (org-element-property :drawer-name drawer) nil nil t)
25013 (cl-case (org-element-type element)
25014 ((comment quote-section) t)
25016 ;; Allow checks between block markers, not on them.
25017 (and (> (line-beginning-position) post-affiliated)
25020 (skip-chars-forward " \r\t\n")
25021 (< (point) (org-element-property :end element)))))
25022 ;; Arbitrary list of keywords where checks are meaningful.
25023 ;; Make sure point is on the value part of the element.
25025 (and (member (org-element-property :key element)
25026 '("DESCRIPTION" "TITLE"))
25028 (search-backward ":" (line-beginning-position) t))))
25029 ;; Check is globally allowed in paragraphs verse blocks and
25030 ;; table rows (after affiliated keywords) but some objects
25031 ;; must not be affected.
25032 ((paragraph table-row verse-block)
25033 (let ((cbeg (org-element-property :contents-begin element))
25034 (cend (org-element-property :contents-end element)))
25035 (and cbeg (>= (point) cbeg) (< (point) cend)
25036 (org--flyspell-object-check-p element))))))))))
25037 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25039 (defun org-remove-flyspell-overlays-in (beg end)
25040 "Remove flyspell overlays in region."
25041 (and (bound-and-true-p flyspell-mode)
25042 (fboundp 'flyspell-delete-region-overlays)
25043 (flyspell-delete-region-overlays beg end)))
25045 (defvar flyspell-delayed-commands)
25046 (eval-after-load "flyspell"
25047 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25049 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25050 (eval-after-load "bookmark"
25051 '(if (boundp 'bookmark-after-jump-hook)
25052 ;; We can use the hook
25053 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25054 ;; Hook not available, use advice
25055 (defadvice bookmark-jump (after org-make-visible activate)
25056 "Make the position visible."
25057 (org-bookmark-jump-unhide))))
25059 ;; Make sure saveplace shows the location if it was hidden
25060 (eval-after-load "saveplace"
25061 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25062 "Make the position visible."
25063 (org-bookmark-jump-unhide)))
25065 ;; Make sure ecb shows the location if it was hidden
25066 (eval-after-load "ecb"
25067 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25068 "Make hierarchy visible when jumping into location from ECB tree buffer."
25069 (when (derived-mode-p 'org-mode)
25070 (org-show-context))))
25072 (defun org-bookmark-jump-unhide ()
25073 "Unhide the current position, to show the bookmark location."
25074 (and (derived-mode-p 'org-mode)
25075 (or (outline-invisible-p)
25076 (save-excursion (goto-char (max (point-min) (1- (point))))
25077 (outline-invisible-p)))
25078 (org-show-context 'bookmark-jump)))
25080 (defun org-mark-jump-unhide ()
25081 "Make the point visible with `org-show-context' after jumping to the mark."
25082 (when (and (derived-mode-p 'org-mode)
25083 (outline-invisible-p))
25084 (org-show-context 'mark-goto)))
25086 (eval-after-load "simple"
25087 '(defadvice pop-to-mark-command (after org-make-visible activate)
25088 "Make the point visible with `org-show-context'."
25089 (org-mark-jump-unhide)))
25091 (eval-after-load "simple"
25092 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25093 "Make the point visible with `org-show-context'."
25094 (org-mark-jump-unhide)))
25096 (eval-after-load "simple"
25097 '(defadvice pop-global-mark (after org-make-visible activate)
25098 "Make the point visible with `org-show-context'."
25099 (org-mark-jump-unhide)))
25101 ;; Make session.el ignore our circular variable
25102 (defvar session-globals-exclude)
25103 (eval-after-load "session"
25104 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25110 (run-hooks 'org-load-hook)
25112 ;;; org.el ends here