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 <https://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" (&optional arg start-day span with-hour
))
119 (declare-function org-agenda-redo
"org-agenda" (&optional all
))
120 (declare-function org-babel-do-in-edit-buffer
"ob-core" (&rest body
) t
)
121 (declare-function org-babel-tangle-file
"ob-tangle" (file &optional target-file lang
))
122 (declare-function org-beamer-mode
"ox-beamer" (&optional prefix
) t
)
123 (declare-function org-clock-get-last-clock-out-time
"org-clock" ())
124 (declare-function org-clock-out
"org-clock" (&optional switch-to-state fail-quietly at-time
))
125 (declare-function org-clock-remove-overlays
"org-clock" (&optional beg end noremove
))
126 (declare-function org-clock-sum
"org-clock" (&optional tstart tend headline-filter propname
))
127 (declare-function org-clock-sum-current-item
"org-clock" (&optional tstart
))
128 (declare-function org-clock-timestamps-down
"org-clock" (&optional n
))
129 (declare-function org-clock-timestamps-up
"org-clock" (&optional n
))
130 (declare-function org-clock-update-time-maybe
"org-clock" ())
131 (declare-function org-clocking-buffer
"org-clock" ())
132 (declare-function org-clocktable-shift
"org-clock" (dir n
))
134 org-duration-from-minutes
"org-duration" (minutes &optional fmt canonical
))
135 (declare-function org-element-at-point
"org-element" ())
136 (declare-function org-element-cache-refresh
"org-element" (pos))
137 (declare-function org-element-cache-reset
"org-element" (&optional all
))
138 (declare-function org-element-contents
"org-element" (element))
139 (declare-function org-element-context
"org-element" (&optional element
))
140 (declare-function org-element-copy
"org-element" (datum))
141 (declare-function org-element-interpret-data
"org-element" (data))
142 (declare-function org-element-lineage
"org-element" (blob &optional types with-self
))
143 (declare-function org-element-link-parser
"org-element" ())
144 (declare-function org-element-nested-p
"org-element" (elem-a elem-b
))
145 (declare-function org-element-parse-buffer
"org-element" (&optional granularity visible-only
))
146 (declare-function org-element-property
"org-element" (property element
))
147 (declare-function org-element-put-property
"org-element" (element property value
))
148 (declare-function org-element-swap-A-B
"org-element" (elem-a elem-b
))
149 (declare-function org-element-type
"org-element" (element))
150 (declare-function org-element-update-syntax
"org-element" ())
151 (declare-function org-id-find-id-file
"org-id" (id))
152 (declare-function org-id-get-create
"org-id" (&optional force
))
153 (declare-function org-inlinetask-at-task-p
"org-inlinetask" ())
154 (declare-function org-inlinetask-outline-regexp
"org-inlinetask" ())
155 (declare-function org-inlinetask-toggle-visibility
"org-inlinetask" ())
156 (declare-function org-plot
/gnuplot
"org-plot" (&optional params
))
157 (declare-function org-table-align
"org-table" ())
158 (declare-function org-table-begin
"org-table" (&optional table-type
))
159 (declare-function org-table-beginning-of-field
"org-table" (&optional n
))
160 (declare-function org-table-blank-field
"org-table" ())
161 (declare-function org-table-calc-current-TBLFM
"org-table" (&optional arg
))
162 (declare-function org-table-copy-region
"org-table" (beg end
&optional cut
))
163 (declare-function org-table-cut-region
"org-table" (beg end
))
164 (declare-function org-table-edit-field
"org-table" (arg))
165 (declare-function org-table-end
"org-table" (&optional table-type
))
166 (declare-function org-table-end-of-field
"org-table" (&optional n
))
167 (declare-function org-table-insert-row
"org-table" (&optional arg
))
168 (declare-function org-table-justify-field-maybe
"org-table" (&optional new
))
169 (declare-function org-table-maybe-eval-formula
"org-table" ())
170 (declare-function org-table-maybe-recalculate-line
"org-table" ())
171 (declare-function org-table-next-row
"org-table" ())
172 (declare-function org-table-paste-rectangle
"org-table" ())
173 (declare-function org-table-recalculate
"org-table" (&optional all noalign
))
175 org-table-sort-lines
"org-table"
176 (&optional with-case sorting-type getkey-func compare-func interactive?
))
177 (declare-function org-table-wrap-region
"org-table" (arg))
178 (declare-function org-tags-view
"org-agenda" (&optional todo-only match
))
179 (declare-function orgtbl-ascii-plot
"org-table" (&optional ask
))
180 (declare-function orgtbl-mode
"org-table" (&optional arg
))
181 (declare-function org-export-get-backend
"ox" (name))
182 (declare-function org-export-get-environment
"ox" (&optional backend subtreep ext-plist
))
183 (declare-function org-latex-make-preamble
"ox-latex" (info &optional template snippet?
))
185 (defvar ffap-url-regexp
)
186 (defvar org-element-paragraph-separate
)
188 (defsubst org-uniquify
(list)
189 "Non-destructively remove duplicate elements from LIST."
190 (let ((res (copy-sequence list
))) (delete-dups res
)))
192 (defsubst org-get-at-bol
(property)
193 "Get text property PROPERTY at the beginning of line."
194 (get-text-property (point-at-bol) property
))
196 (defsubst org-trim
(s &optional keep-lead
)
197 "Remove whitespace at the beginning and the end of string S.
198 When optional argument KEEP-LEAD is non-nil, removing blank lines
199 at the beginning of the string does not affect leading indentation."
200 (replace-regexp-in-string
201 (if keep-lead
"\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
202 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s
)))
204 ;; load languages based on value of `org-babel-load-languages'
205 (defvar org-babel-load-languages
)
208 (defun org-babel-do-load-languages (sym value
)
209 "Load the languages defined in `org-babel-load-languages'."
210 (set-default sym value
)
211 (dolist (pair org-babel-load-languages
)
212 (let ((active (cdr pair
)) (lang (symbol-name (car pair
))))
214 (require (intern (concat "ob-" lang
)))
215 (funcall 'fmakunbound
216 (intern (concat "org-babel-execute:" lang
)))
217 (funcall 'fmakunbound
218 (intern (concat "org-babel-expand-body:" lang
)))))))
220 (declare-function org-babel-tangle-file
"ob-tangle" (file &optional target-file lang
))
222 (defun org-babel-load-file (file &optional compile
)
223 "Load Emacs Lisp source code blocks in the Org FILE.
224 This function exports the source code using `org-babel-tangle'
225 and then loads the resulting file using `load-file'. With prefix
226 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
227 file to byte-code before it is loaded."
228 (interactive "fFile to load: \nP")
229 (let* ((age (lambda (file)
231 (time-subtract (current-time)
232 (nth 5 (or (file-attributes (file-truename file
))
233 (file-attributes file
)))))))
234 (base-name (file-name-sans-extension file
))
235 (exported-file (concat base-name
".el")))
236 ;; tangle if the Org file is newer than the elisp file
237 (unless (and (file-exists-p exported-file
)
238 (> (funcall age file
) (funcall age exported-file
)))
239 ;; Tangle-file traversal returns reversed list of tangled files
240 ;; and we want to evaluate the first target.
242 (car (last (org-babel-tangle-file file exported-file
"emacs-lisp")))))
245 (progn (byte-compile-file exported-file
'load
)
246 "Compiled and loaded")
247 (progn (load-file exported-file
) "Loaded"))
250 (defcustom org-babel-load-languages
'((emacs-lisp . t
))
251 "Languages which can be evaluated in Org buffers.
252 This list can be used to load support for any of the languages
253 below, note that each language will depend on a different set of
254 system executables and/or Emacs modes. When a language is
255 \"loaded\", then code blocks in that language can be evaluated
256 with `org-babel-execute-src-block' bound by default to C-c
257 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
258 be set to remove code block evaluation from the C-c C-c
259 keybinding. By default only Emacs Lisp (which has no
260 requirements) is loaded."
262 :set
'org-babel-do-load-languages
264 :type
'(alist :tag
"Babel Languages"
267 (const :tag
"Awk" awk
)
270 (const :tag
"Asymptote" asymptote
)
271 (const :tag
"Calc" calc
)
272 (const :tag
"Clojure" clojure
)
273 (const :tag
"CSS" css
)
274 (const :tag
"Ditaa" ditaa
)
275 (const :tag
"Dot" dot
)
276 (const :tag
"Ebnf2ps" ebnf2ps
)
277 (const :tag
"Emacs Lisp" emacs-lisp
)
278 (const :tag
"Forth" forth
)
279 (const :tag
"Fortran" fortran
)
280 (const :tag
"Gnuplot" gnuplot
)
281 (const :tag
"Haskell" haskell
)
282 (const :tag
"hledger" hledger
)
285 (const :tag
"Java" java
)
286 (const :tag
"Javascript" js
)
287 (const :tag
"LaTeX" latex
)
288 (const :tag
"Ledger" ledger
)
289 (const :tag
"Lilypond" lilypond
)
290 (const :tag
"Lisp" lisp
)
291 (const :tag
"Makefile" makefile
)
292 (const :tag
"Maxima" maxima
)
293 (const :tag
"Matlab" matlab
)
294 (const :tag
"Mscgen" mscgen
)
295 (const :tag
"Ocaml" ocaml
)
296 (const :tag
"Octave" octave
)
297 (const :tag
"Org" org
)
298 (const :tag
"Perl" perl
)
299 (const :tag
"Pico Lisp" picolisp
)
300 (const :tag
"PlantUML" plantuml
)
301 (const :tag
"Python" python
)
302 (const :tag
"Ruby" ruby
)
303 (const :tag
"Sass" sass
)
304 (const :tag
"Scala" scala
)
305 (const :tag
"Scheme" scheme
)
306 (const :tag
"Screen" screen
)
307 (const :tag
"Shell Script" shell
)
308 (const :tag
"Shen" shen
)
309 (const :tag
"Sql" sql
)
310 (const :tag
"Sqlite" sqlite
)
311 (const :tag
"Stan" stan
)
312 (const :tag
"Vala" vala
))
313 :value-type
(boolean :tag
"Activate" :value t
)))
315 ;;;; Customization variables
316 (defcustom org-clone-delete-id nil
317 "Remove ID property of clones of a subtree.
318 When non-nil, clones of a subtree don't inherit the ID property.
319 Otherwise they inherit the ID property with a new unique
329 (defun org-version (&optional here full message
)
330 "Show the Org version.
331 Interactively, or when MESSAGE is non-nil, show it in echo area.
332 With prefix argument, or when HERE is non-nil, insert it at point.
333 In non-interactive uses, a reduced version string is output unless
335 (interactive (list current-prefix-arg t
(not current-prefix-arg
)))
336 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
337 (save-load-suffixes (when (boundp 'load-suffixes
) load-suffixes
))
338 (load-suffixes (list ".el"))
340 (ignore-errors (org-find-library-dir "org-loaddefs"))))
341 (unless (and (fboundp 'org-release
) (fboundp 'org-git-version
))
342 (org-load-noerror-mustsuffix (concat org-dir
"org-version")))
343 (let* ((load-suffixes save-load-suffixes
)
344 (release (org-release))
345 (git-version (org-git-version))
346 (version (format "Org mode version %s (%s @ %s)"
350 (if (string= org-dir org-install-dir
)
352 (concat "mixed installation! "
356 "org-loaddefs.el can not be found!")))
357 (version1 (if full version release
)))
358 (when here
(insert version1
))
359 (when message
(message "%s" version1
))
362 (defconst org-version
(org-version))
369 (defconst org-block-regexp
370 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
371 "Regular expression for hiding blocks.")
373 (defconst org-dblock-start-re
374 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
375 "Matches the start line of a dynamic block, with parameters.")
377 (defconst org-dblock-end-re
"^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
378 "Matches the end of a dynamic block.")
380 ;;;; Clock and Planning
382 (defconst org-clock-string
"CLOCK:"
383 "String used as prefix for timestamps clocking work hours on an item.")
385 (defvar org-closed-string
"CLOSED:"
386 "String used as the prefix for timestamps logging closing a TODO entry.")
388 (defvar org-deadline-string
"DEADLINE:"
389 "String to mark deadline entries.
391 A deadline is this string, followed by a time stamp. It must be
392 a word, terminated by a colon. You can insert a schedule keyword
393 and a timestamp with `\\[org-deadline]'.")
395 (defvar org-scheduled-string
"SCHEDULED:"
396 "String to mark scheduled TODO entries.
398 A schedule is this string, followed by a time stamp. It must be
399 a word, terminated by a colon. You can insert a schedule keyword
400 and a timestamp with `\\[org-schedule]'.")
402 (defconst org-ds-keyword-length
406 (list org-deadline-string org-scheduled-string
407 org-clock-string org-closed-string
))))
408 "Maximum length of the DEADLINE and SCHEDULED keywords.")
410 (defconst org-planning-line-re
413 (list org-closed-string org-deadline-string org-scheduled-string
)
415 "Matches a line with planning info.
416 Matched keyword is in group 1.")
418 (defconst org-clock-line-re
419 (concat "^[ \t]*" org-clock-string
)
420 "Matches a line with clock info.")
422 (defconst org-deadline-regexp
(concat "\\<" org-deadline-string
)
423 "Matches the DEADLINE keyword.")
425 (defconst org-deadline-time-regexp
426 (concat "\\<" org-deadline-string
" *<\\([^>]+\\)>")
427 "Matches the DEADLINE keyword together with a time stamp.")
429 (defconst org-deadline-time-hour-regexp
430 (concat "\\<" org-deadline-string
431 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
432 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
434 (defconst org-deadline-line-regexp
435 (concat "\\<\\(" org-deadline-string
"\\).*")
436 "Matches the DEADLINE keyword and the rest of the line.")
438 (defconst org-scheduled-regexp
(concat "\\<" org-scheduled-string
)
439 "Matches the SCHEDULED keyword.")
441 (defconst org-scheduled-time-regexp
442 (concat "\\<" org-scheduled-string
" *<\\([^>]+\\)>")
443 "Matches the SCHEDULED keyword together with a time stamp.")
445 (defconst org-scheduled-time-hour-regexp
446 (concat "\\<" org-scheduled-string
447 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
448 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
450 (defconst org-closed-time-regexp
451 (concat "\\<" org-closed-string
" *\\[\\([^]]+\\)\\]")
452 "Matches the CLOSED keyword together with a time stamp.")
454 (defconst org-keyword-time-regexp
457 (list org-scheduled-string org-deadline-string org-closed-string
460 " *[[<]\\([^]>]+\\)[]>]")
461 "Matches any of the 4 keywords, together with the time stamp.")
463 (defconst org-keyword-time-not-clock-regexp
467 (list org-scheduled-string org-deadline-string org-closed-string
) t
)
468 " *[[<]\\([^]>]+\\)[]>]")
469 "Matches any of the 3 keywords, together with the time stamp.")
471 (defconst org-maybe-keyword-time-regexp
474 (list org-scheduled-string org-deadline-string org-closed-string
478 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
481 "Matches a timestamp, possibly preceded by a keyword.")
483 (defconst org-all-time-keywords
484 (mapcar (lambda (w) (substring w
0 -
1))
485 (list org-scheduled-string org-deadline-string
486 org-clock-string org-closed-string
))
487 "List of time keywords.")
491 (defconst org-drawer-regexp
"^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
492 "Matches first or last line of a hidden block.
493 Group 1 contains drawer's name or \"END\".")
495 (defconst org-property-start-re
"^[ \t]*:PROPERTIES:[ \t]*$"
496 "Regular expression matching the first line of a property drawer.")
498 (defconst org-property-end-re
"^[ \t]*:END:[ \t]*$"
499 "Regular expression matching the last line of a property drawer.")
501 (defconst org-clock-drawer-start-re
"^[ \t]*:CLOCK:[ \t]*$"
502 "Regular expression matching the first line of a clock drawer.")
504 (defconst org-clock-drawer-end-re
"^[ \t]*:END:[ \t]*$"
505 "Regular expression matching the last line of a clock drawer.")
507 (defconst org-property-drawer-re
508 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
509 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
510 "[ \t]*:END:[ \t]*$")
511 "Matches an entire property drawer.")
513 (defconst org-clock-drawer-re
514 (concat "\\(" org-clock-drawer-start-re
"\\)[^\000]*?\\("
515 org-clock-drawer-end-re
"\\)\n?")
516 "Matches an entire clock drawer.")
520 (defconst org-heading-keyword-regexp-format
521 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
522 "Printf format for a regexp matching a headline with some keyword.
523 This regexp will match the headline of any node which has the
524 exact keyword that is put into the format. The keyword isn't in
525 any group by default, but the stars and the body are.")
527 (defconst org-heading-keyword-maybe-regexp-format
528 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
529 "Printf format for a regexp matching a headline, possibly with some keyword.
530 This regexp can match any headline with the specified keyword, or
531 without a keyword. The keyword isn't in any group by default,
532 but the stars and the body are.")
534 (defconst org-archive-tag
"ARCHIVE"
535 "The tag that marks a subtree as archived.
536 An archived subtree does not open during visibility cycling, and does
537 not contribute to the agenda listings.")
540 (defconst org-comment-string
"COMMENT"
541 "Entries starting with this keyword will never be exported.
543 An entry can be toggled between COMMENT and normal with
544 `\\[org-toggle-comment]'."))
547 ;;;; LaTeX Environments and Fragments
549 (defconst org-latex-regexps
550 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t
)
551 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
552 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
553 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil
)
554 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil
)
555 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil
)
556 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil
)
557 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil
))
558 "Regular expressions for matching embedded LaTeX.")
562 (defconst org-effort-property
"Effort"
563 "The property that is being used to keep track of effort estimates.
564 Effort estimates given in this property need to have the format H:MM.")
568 (defconst org-table-any-line-regexp
"^[ \t]*\\(|\\|\\+-[-+]\\)"
569 "Detect an org-type or table-type table.")
571 (defconst org-table-line-regexp
"^[ \t]*|"
572 "Detect an org-type table line.")
574 (defconst org-table-dataline-regexp
"^[ \t]*|[^-]"
575 "Detect an org-type table line.")
577 (defconst org-table-hline-regexp
"^[ \t]*|-"
578 "Detect an org-type table hline.")
580 (defconst org-table1-hline-regexp
"^[ \t]*\\+-[-+]"
581 "Detect a table-type table hline.")
583 (defconst org-table-any-border-regexp
"^[ \t]*[^|+ \t]"
584 "Detect the first line outside a table when searching from within it.
585 This works for both table types.")
587 (defconst org-TBLFM-regexp
"^[ \t]*#\\+TBLFM: "
588 "Detect a #+TBLFM line.")
592 (defconst org-ts-regexp
"<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
593 "Regular expression for fast time stamp matching.")
595 (defconst org-ts-regexp-inactive
596 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
597 "Regular expression for fast inactive time stamp matching.")
599 (defconst org-ts-regexp-both
"[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
600 "Regular expression for fast time stamp matching.")
602 (defconst org-ts-regexp0
603 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
604 "Regular expression matching time strings for analysis.
605 This one does not require the space after the date, so it can be used
606 on a string that terminates immediately after the date.")
608 (defconst org-ts-regexp1
"\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
609 "Regular expression matching time strings for analysis.")
611 (defconst org-ts-regexp2
(concat "<" org-ts-regexp1
"[^>\n]\\{0,16\\}>")
612 "Regular expression matching time stamps, with groups.")
614 (defconst org-ts-regexp3
(concat "[[<]" org-ts-regexp1
"[^]>\n]\\{0,16\\}[]>]")
615 "Regular expression matching time stamps (also [..]), with groups.")
617 (defconst org-tr-regexp
(concat org-ts-regexp
"--?-?" org-ts-regexp
)
618 "Regular expression matching a time stamp range.")
620 (defconst org-tr-regexp-both
621 (concat org-ts-regexp-both
"--?-?" org-ts-regexp-both
)
622 "Regular expression matching a time stamp range.")
624 (defconst org-tsr-regexp
(concat org-ts-regexp
"\\(--?-?"
625 org-ts-regexp
"\\)?")
626 "Regular expression matching a time stamp or time stamp range.")
628 (defconst org-tsr-regexp-both
629 (concat org-ts-regexp-both
"\\(--?-?"
630 org-ts-regexp-both
"\\)?")
631 "Regular expression matching a time stamp or time stamp range.
632 The time stamps may be either active or inactive.")
634 (defconst org-repeat-re
635 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
636 "Regular expression for specifying repeated events.
637 After a match, group 1 contains the repeat expression.")
639 (defconst org-time-stamp-formats
'("<%Y-%m-%d %a>" .
"<%Y-%m-%d %a %H:%M>")
640 "Formats for `format-time-string' which are used for time stamps.")
643 ;;; The custom variables
646 "Outline-based notes management and organizer."
651 (defcustom org-mode-hook nil
652 "Mode hook for Org mode, run after the mode was turned on."
656 (defcustom org-load-hook nil
657 "Hook that is run after org.el has been loaded."
661 (defcustom org-log-buffer-setup-hook nil
662 "Hook that is run after an Org log buffer is created."
667 (defvar org-modules
) ; defined below
668 (defvar org-modules-loaded nil
669 "Have the modules been loaded already?")
671 (defun org-load-modules-maybe (&optional force
)
672 "Load all extensions listed in `org-modules'."
673 (when (or force
(not org-modules-loaded
))
674 (dolist (ext org-modules
)
675 (condition-case nil
(require ext
)
676 (error (message "Problems while trying to load feature `%s'" ext
))))
677 (setq org-modules-loaded t
)))
679 (defun org-set-modules (var value
)
680 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
682 (when (featurep 'org
)
683 (org-load-modules-maybe 'force
)
684 (org-element-cache-reset 'all
)))
686 (defcustom org-modules
'(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail
)
687 "Modules that should always be loaded together with org.el.
689 If a description starts with <C>, the file is not part of Emacs
690 and loading it will require that you have downloaded and properly
691 installed the Org mode distribution.
693 You can also use this system to load external packages (i.e. neither Org
694 core modules, nor modules from the CONTRIB directory). Just add symbols
695 to the end of the list. If the package is called org-xyz.el, then you need
696 to add the symbol `xyz', and the package must have a call to:
698 (provide \\='org-xyz)
700 For export specific modules, see also `org-export-backends'."
702 :set
'org-set-modules
704 :package-version
'(Org .
"8.0")
707 (const :tag
" bbdb: Links to BBDB entries" org-bbdb
)
708 (const :tag
" bibtex: Links to BibTeX entries" org-bibtex
)
709 (const :tag
" crypt: Encryption of subtrees" org-crypt
)
710 (const :tag
" ctags: Access to Emacs tags with links" org-ctags
)
711 (const :tag
" docview: Links to doc-view buffers" org-docview
)
712 (const :tag
" eww: Store link to url of eww" org-eww
)
713 (const :tag
" gnus: Links to GNUS folders/messages" org-gnus
)
714 (const :tag
" habit: Track your consistency with habits" org-habit
)
715 (const :tag
" id: Global IDs for identifying entries" org-id
)
716 (const :tag
" info: Links to Info nodes" org-info
)
717 (const :tag
" inlinetask: Tasks independent of outline hierarchy" org-inlinetask
)
718 (const :tag
" irc: Links to IRC/ERC chat sessions" org-irc
)
719 (const :tag
" mhe: Links to MHE folders/messages" org-mhe
)
720 (const :tag
" mouse: Additional mouse support" org-mouse
)
721 (const :tag
" protocol: Intercept calls from emacsclient" org-protocol
)
722 (const :tag
" rmail: Links to RMAIL folders/messages" org-rmail
)
723 (const :tag
" w3m: Special cut/paste from w3m to Org mode." org-w3m
)
725 (const :tag
"C annotate-file: Annotate a file with org syntax" org-annotate-file
)
726 (const :tag
"C bookmark: Org links to bookmarks" org-bookmark
)
727 (const :tag
"C checklist: Extra functions for checklists in repeated tasks" org-checklist
)
728 (const :tag
"C choose: Use TODO keywords to mark decisions states" org-choose
)
729 (const :tag
"C collector: Collect properties into tables" org-collector
)
730 (const :tag
"C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend
)
731 (const :tag
"C drill: Flashcards and spaced repetition for Org mode" org-drill
)
732 (const :tag
"C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol
)
733 (const :tag
"C eshell Support for links to working directories in eshell" org-eshell
)
734 (const :tag
"C eval-light: Evaluate inbuffer-code on demand" org-eval-light
)
735 (const :tag
"C eval: Include command output as text" org-eval
)
736 (const :tag
"C expiry: Expiry mechanism for Org entries" org-expiry
)
737 (const :tag
"C favtable: Lookup table of favorite references and links" org-favtable
)
738 (const :tag
"C git-link: Provide org links to specific file version" org-git-link
)
739 (const :tag
"C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query
)
740 (const :tag
"C invoice: Help manage client invoices in Org mode" org-invoice
)
741 (const :tag
"C learn: SuperMemo's incremental learning algorithm" org-learn
)
742 (const :tag
"C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal
)
743 (const :tag
"C mac-link: Grab links and url from various mac Applications" org-mac-link
)
744 (const :tag
"C mairix: Hook mairix search into Org for different MUAs" org-mairix
)
745 (const :tag
"C man: Support for links to manpages in Org mode" org-man
)
746 (const :tag
"C mew: Links to Mew folders/messages" org-mew
)
747 (const :tag
"C mtags: Support for muse-like tags" org-mtags
)
748 (const :tag
"C notmuch: Provide org links to notmuch searches or messages" org-notmuch
)
749 (const :tag
"C panel: Simple routines for us with bad memory" org-panel
)
750 (const :tag
"C registry: A registry for Org links" org-registry
)
751 (const :tag
"C screen: Visit screen sessions through Org links" org-screen
)
752 (const :tag
"C secretary: Team management with org-mode" org-secretary
)
753 (const :tag
"C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert
)
754 (const :tag
"C toc: Table of contents for Org buffer" org-toc
)
755 (const :tag
"C track: Keep up with Org mode development" org-track
)
756 (const :tag
"C velocity Something like Notational Velocity for Org" org-velocity
)
757 (const :tag
"C vm: Links to VM folders/messages" org-vm
)
758 (const :tag
"C wikinodes: CamelCase wiki-like links" org-wikinodes
)
759 (const :tag
"C wl: Links to Wanderlust folders/messages" org-wl
)
760 (repeat :tag
"External packages" :inline t
(symbol :tag
"Package"))))
762 (defvar org-export-registered-backends
) ; From ox.el.
763 (declare-function org-export-derived-backend-p
"ox" (backend &rest backends
))
764 (declare-function org-export-backend-name
"ox" (backend) t
)
765 (defcustom org-export-backends
'(ascii html icalendar latex odt
)
766 "List of export back-ends that should be always available.
768 If a description starts with <C>, the file is not part of Emacs
769 and loading it will require that you have downloaded and properly
770 installed the Org mode distribution.
772 Unlike to `org-modules', libraries in this list will not be
773 loaded along with Org, but only once the export framework is
776 This variable needs to be set before org.el is loaded. If you
777 need to make a change while Emacs is running, use the customize
778 interface or run the following code, where VAL stands for the new
779 value of the variable, after updating it:
782 (setq org-export-registered-backends
785 (let ((name (org-export-backend-name backend)))
789 (and (org-export-derived-backend-p b name)
790 (throw \\='parentp t)))))))
791 org-export-registered-backends))
792 (let ((new-list (mapcar #\\='org-export-backend-name
793 org-export-registered-backends)))
794 (dolist (backend val)
796 ((not (load (format \"ox-%s\" backend) t t))
797 (message \"Problems while trying to load export back-end \\=`%s\\='\"
799 ((not (memq backend new-list)) (push backend new-list))))
800 (set-default \\='org-export-backends new-list)))
802 Adding a back-end to this list will also pull the back-end it
807 :package-version
'(Org .
"9.0")
808 :initialize
'custom-initialize-set
809 :set
(lambda (var val
)
810 (if (not (featurep 'ox
)) (set-default var val
)
811 ;; Any back-end not required anymore (not present in VAL and not
812 ;; a parent of any back-end in the new value) is removed from the
813 ;; list of registered back-ends.
814 (setq org-export-registered-backends
817 (let ((name (org-export-backend-name backend
)))
821 (and (org-export-derived-backend-p b name
)
822 (throw 'parentp t
)))))))
823 org-export-registered-backends
))
824 ;; Now build NEW-LIST of both new back-ends and required
826 (let ((new-list (mapcar #'org-export-backend-name
827 org-export-registered-backends
)))
828 (dolist (backend val
)
830 ((not (load (format "ox-%s" backend
) t t
))
831 (message "Problems while trying to load export back-end `%s'"
833 ((not (memq backend new-list
)) (push backend new-list
))))
834 ;; Set VAR to that list with fixed dependencies.
835 (set-default var new-list
))))
836 :type
'(set :greedy t
837 (const :tag
" ascii Export buffer to ASCII format" ascii
)
838 (const :tag
" beamer Export buffer to Beamer presentation" beamer
)
839 (const :tag
" html Export buffer to HTML format" html
)
840 (const :tag
" icalendar Export buffer to iCalendar format" icalendar
)
841 (const :tag
" latex Export buffer to LaTeX format" latex
)
842 (const :tag
" man Export buffer to MAN format" man
)
843 (const :tag
" md Export buffer to Markdown format" md
)
844 (const :tag
" odt Export buffer to ODT format" odt
)
845 (const :tag
" org Export buffer to Org format" org
)
846 (const :tag
" texinfo Export buffer to Texinfo format" texinfo
)
847 (const :tag
"C confluence Export buffer to Confluence Wiki format" confluence
)
848 (const :tag
"C deck Export buffer to deck.js presentations" deck
)
849 (const :tag
"C freemind Export buffer to Freemind mindmap format" freemind
)
850 (const :tag
"C groff Export buffer to Groff format" groff
)
851 (const :tag
"C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter
)
852 (const :tag
"C RSS 2.0 Export buffer to RSS 2.0 format" rss
)
853 (const :tag
"C s5 Export buffer to s5 presentations" s5
)
854 (const :tag
"C taskjuggler Export buffer to TaskJuggler format" taskjuggler
)))
857 '(dolist (backend org-export-backends
)
858 (condition-case nil
(require (intern (format "ox-%s" backend
)))
859 (error (message "Problems while trying to load export back-end `%s'"
862 (defcustom org-support-shift-select nil
863 "Non-nil means make shift-cursor commands select text when possible.
866 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
867 start selecting a region, or enlarge regions started in this way.
868 In Org mode, in special contexts, these same keys are used for
869 other purposes, important enough to compete with shift selection.
870 Org tries to balance these needs by supporting `shift-select-mode'
871 outside these special contexts, under control of this variable.
873 The default of this variable is nil, to avoid confusing behavior. Shifted
874 cursor keys will then execute Org commands in the following contexts:
875 - on a headline, changing TODO state (left/right) and priority (up/down)
876 - on a time stamp, changing the time
877 - in a plain list item, changing the bullet type
878 - in a property definition line, switching between allowed values
879 - in the BEGIN line of a clock table (changing the time block).
880 Outside these contexts, the commands will throw an error.
882 When this variable is t and the cursor is not in a special
883 context, Org mode will support shift-selection for making and
884 enlarging regions. To make this more effective, the bullet
885 cycling will no longer happen anywhere in an item line, but only
886 if the cursor is exactly on the bullet.
888 If you set this variable to the symbol `always', then the keys
889 will not be special in headlines, property lines, and item lines,
890 to make shift selection work there as well. If this is what you
891 want, you can use the following alternative commands:
892 `\\[org-todo]' and `\\[org-priority]' \
893 to change TODO state and priority,
894 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
895 can be used to switch TODO sets,
896 `\\[org-ctrl-c-minus]' to cycle item bullet types,
897 and properties can be edited by hand or in column view.
899 However, when the cursor is on a timestamp, shift-cursor commands
900 will still edit the time stamp - this is just too good to give up."
903 (const :tag
"Never" nil
)
904 (const :tag
"When outside special context" t
)
905 (const :tag
"Everywhere except timestamps" always
)))
907 (defcustom org-loop-over-headlines-in-active-region nil
908 "Shall some commands act upon headlines in the active region?
910 When set to t, some commands will be performed in all headlines
911 within the active region.
913 When set to `start-level', some commands will be performed in all
914 headlines within the active region, provided that these headlines
915 are of the same level than the first one.
917 When set to a string, those commands will be performed on the
918 matching headlines within the active region. Such string must be
919 a tags/property/todo match as it is used in the agenda tags view.
921 The list of commands is: `org-schedule', `org-deadline',
922 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
923 `org-archive-to-archive-sibling'. The archiving commands skip
924 already archived entries."
925 :type
'(choice (const :tag
"Don't loop" nil
)
926 (const :tag
"All headlines in active region" t
)
927 (const :tag
"In active region, headlines at the same level than the first one" start-level
)
928 (string :tag
"Tags/Property/Todo matcher"))
933 (defgroup org-startup nil
934 "Options concerning startup of Org mode."
938 (defcustom org-startup-folded t
939 "Non-nil means entering Org mode will switch to OVERVIEW.
941 This can also be configured on a per-file basis by adding one of
942 the following lines anywhere in the buffer:
944 #+STARTUP: fold (or `overview', this is equivalent)
945 #+STARTUP: nofold (or `showall', this is equivalent)
947 #+STARTUP: showeverything
949 Set `org-agenda-inhibit-startup' to a non-nil value if you want
950 to ignore this option when Org opens agenda files for the first
954 (const :tag
"nofold: show all" nil
)
955 (const :tag
"fold: overview" t
)
956 (const :tag
"content: all headlines" content
)
957 (const :tag
"show everything, even drawers" showeverything
)))
959 (defcustom org-startup-truncated t
960 "Non-nil means entering Org mode will set `truncate-lines'.
961 This is useful since some lines containing links can be very long and
962 uninteresting. Also tables look terrible when wrapped.
964 The variable `org-startup-truncated' allows to configure
965 truncation for Org mode different to the other modes that use the
966 variable `truncate-lines' and as a shortcut instead of putting
967 the variable `truncate-lines' into the `org-mode-hook'. If one
968 wants to configure truncation for Org mode not statically but
969 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
970 the variable `truncate-lines' has to be used because in such a
971 case it is too late to set the variable `org-startup-truncated'."
975 (defcustom org-startup-indented nil
976 "Non-nil means turn on `org-indent-mode' on startup.
977 This can also be configured on a per-file basis by adding one of
978 the following lines anywhere in the buffer:
982 :group
'org-structure
984 (const :tag
"Not" nil
)
985 (const :tag
"Globally (slow on startup in large files)" t
)))
987 (defcustom org-use-sub-superscripts t
988 "Non-nil means interpret \"_\" and \"^\" for display.
990 If you want to control how Org exports those characters, see
991 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
992 used to be an alias for `org-export-with-sub-superscripts' in
993 Org <8.0, it is not anymore.
995 When this option is turned on, you can use TeX-like syntax for
996 sub- and superscripts within the buffer. Several characters after
997 \"_\" or \"^\" will be considered as a single item - so grouping
998 with {} is normally not needed. For example, the following things
999 will be parsed as single sub- or superscripts:
1001 10^24 or 10^tau several digits will be considered 1 item.
1002 10^-12 or 10^-tau a leading sign with digits or a word
1003 x^2-y^3 will be read as x^2 - y^3, because items are
1004 terminated by almost any nonword/nondigit char.
1005 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1007 Still, ambiguity is possible. So when in doubt, use {} to enclose
1008 the sub/superscript. If you set this variable to the symbol `{}',
1009 the braces are *required* in order to trigger interpretations as
1010 sub/superscript. This can be helpful in documents that need \"_\"
1011 frequently in plain text."
1014 :package-version
'(Org .
"8.0")
1016 (const :tag
"Always interpret" t
)
1017 (const :tag
"Only with braces" {})
1018 (const :tag
"Never interpret" nil
)))
1020 (defcustom org-startup-with-beamer-mode nil
1021 "Non-nil means turn on `org-beamer-mode' on startup.
1022 This can also be configured on a per-file basis by adding one of
1023 the following lines anywhere in the buffer:
1030 (defcustom org-startup-align-all-tables nil
1031 "Non-nil means align all tables when visiting a file.
1032 This is useful when the column width in tables is forced with <N> cookies
1033 in table fields. Such tables will look correct only after the first re-align.
1034 This can also be configured on a per-file basis by adding one of
1035 the following lines anywhere in the buffer:
1041 (defcustom org-startup-with-inline-images nil
1042 "Non-nil means show inline images when loading a new Org file.
1043 This can also be configured on a per-file basis by adding one of
1044 the following lines anywhere in the buffer:
1045 #+STARTUP: inlineimages
1046 #+STARTUP: noinlineimages"
1051 (defcustom org-startup-with-latex-preview nil
1052 "Non-nil means preview LaTeX fragments when loading a new Org file.
1054 This can also be configured on a per-file basis by adding one of
1055 the following lines anywhere in the buffer:
1056 #+STARTUP: latexpreview
1057 #+STARTUP: nolatexpreview"
1060 :package-version
'(Org .
"8.0")
1063 (defcustom org-insert-mode-line-in-empty-file nil
1064 "Non-nil means insert the first line setting Org mode in empty files.
1065 When the function `org-mode' is called interactively in an empty file, this
1066 normally means that the file name does not automatically trigger Org mode.
1067 To ensure that the file will always be in Org mode in the future, a
1068 line enforcing Org mode will be inserted into the buffer, if this option
1073 (defcustom org-replace-disputed-keys nil
1074 "Non-nil means use alternative key bindings for some keys.
1075 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1076 These keys are also used by other packages like shift-selection-mode'
1077 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1078 If you want to use Org mode together with one of these other modes,
1079 or more generally if you would like to move some Org mode commands to
1080 other keys, set this variable and configure the keys with the variable
1081 `org-disputed-keys'.
1083 This option is only relevant at load-time of Org mode, and must be set
1084 *before* org.el is loaded. Changing it requires a restart of Emacs to
1089 (defcustom org-use-extra-keys nil
1090 "Non-nil means use extra key sequence definitions for certain commands.
1091 This happens automatically if `window-system' is nil. This
1092 variable lets you do the same manually. You must set it before
1097 (defvaralias 'org-CUA-compatible
'org-replace-disputed-keys
)
1099 (defcustom org-disputed-keys
1100 '(([(shift up
)] .
[(meta p
)])
1101 ([(shift down
)] .
[(meta n
)])
1102 ([(shift left
)] .
[(meta -
)])
1103 ([(shift right
)] .
[(meta +)])
1104 ([(control shift right
)] .
[(meta shift
+)])
1105 ([(control shift left
)] .
[(meta shift -
)]))
1106 "Keys for which Org mode and other modes compete.
1107 This is an alist, cars are the default keys, second element specifies
1108 the alternative to use when `org-replace-disputed-keys' is t.
1110 Keys can be specified in any syntax supported by `define-key'.
1111 The value of this option takes effect only at Org mode startup,
1112 therefore you'll have to restart Emacs to apply it after changing."
1116 (defun org-key (key)
1117 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1118 Or return the original if not disputed."
1119 (when org-replace-disputed-keys
1120 (let* ((nkey (key-description key
))
1121 (x (cl-find-if (lambda (x) (equal (key-description (car x
)) nkey
))
1122 org-disputed-keys
)))
1123 (setq key
(if x
(cdr x
) key
))))
1126 (defun org-defkey (keymap key def
)
1127 "Define a key, possibly translated, as returned by `org-key'."
1128 (define-key keymap
(org-key key
) def
))
1130 (defcustom org-ellipsis nil
1131 "The ellipsis to use in the Org mode outline.
1133 When nil, just use the standard three dots. When a non-empty string,
1134 use that string instead.
1136 The change affects only Org mode (which will then use its own display table).
1137 Changing this requires executing `\\[org-mode]' in a buffer to become
1140 :type
'(choice (const :tag
"Default" nil
)
1141 (string :tag
"String" :value
"...#"))
1142 :safe
(lambda (v) (and (string-or-null-p v
) (not (equal "" v
)))))
1144 (defvar org-display-table nil
1145 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1147 (defgroup org-keywords nil
1148 "Keywords in Org mode."
1152 (defcustom org-closed-keep-when-no-todo nil
1153 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1155 :group
'org-keywords
1157 :package-version
'(Org .
"8.0")
1160 (defgroup org-structure nil
1161 "Options concerning the general structure of Org files."
1162 :tag
"Org Structure"
1165 (defgroup org-reveal-location nil
1166 "Options about how to make context of a location visible."
1167 :tag
"Org Reveal Location"
1168 :group
'org-structure
)
1170 (defcustom org-show-context-detail
'((agenda . local
)
1171 (bookmark-jump . lineage
)
1173 (default . ancestors
))
1174 "Alist between context and visibility span when revealing a location.
1176 \\<org-mode-map>Some actions may move point into invisible
1177 locations. As a consequence, Org always expose a neighborhood
1178 around point. How much is shown depends on the initial action,
1179 or context. Valid contexts are
1181 agenda when exposing an entry from the agenda
1182 org-goto when using the command `org-goto' (`\\[org-goto]')
1183 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1184 tags-tree when constructing a sparse tree based on tags matches
1185 link-search when exposing search matches associated with a link
1186 mark-goto when exposing the jump goal of a mark
1187 bookmark-jump when exposing a bookmark location
1188 isearch when exiting from an incremental search
1189 default default for all contexts not set explicitly
1191 Allowed visibility spans are
1193 minimal show current headline; if point is not on headline,
1196 local show current headline, entry and next headline
1198 ancestors show current headline and its direct ancestors; if
1199 point is not on headline, also show entry
1201 lineage show current headline, its direct ancestors and all
1202 their children; if point is not on headline, also show
1203 entry and first child
1205 tree show current headline, its direct ancestors and all
1206 their children; if point is not on headline, also show
1207 entry and all children
1209 canonical show current headline, its direct ancestors along with
1210 their entries and children; if point is not located on
1211 the headline, also show current entry and all children
1213 As special cases, a nil or t value means show all contexts in
1214 `minimal' or `canonical' view, respectively.
1216 Some views can make displayed information very compact, but also
1217 make it harder to edit the location of the match. In such
1218 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1220 :group
'org-reveal-location
1222 :package-version
'(Org .
"9.0")
1224 (const :tag
"Canonical" t
)
1225 (const :tag
"Minimal" nil
)
1226 (repeat :greedy t
:tag
"Individual contexts"
1228 (choice :tag
"Context"
1235 (const bookmark-jump
)
1238 (choice :tag
"Detail level"
1244 (const canonical
))))))
1246 (defcustom org-indirect-buffer-display
'other-window
1247 "How should indirect tree buffers be displayed?
1249 This applies to indirect buffers created with the commands
1250 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1253 current-window Display in the current window
1254 other-window Just display in another window.
1255 dedicated-frame Create one new frame, and re-use it each time.
1256 new-frame Make a new frame each time. Note that in this case
1257 previously-made indirect buffers are kept, and you need to
1258 kill these buffers yourself."
1259 :group
'org-structure
1260 :group
'org-agenda-windows
1262 (const :tag
"In current window" current-window
)
1263 (const :tag
"In current frame, other window" other-window
)
1264 (const :tag
"Each time a new frame" new-frame
)
1265 (const :tag
"One dedicated frame" dedicated-frame
)))
1267 (defcustom org-use-speed-commands nil
1268 "Non-nil means activate single letter commands at beginning of a headline.
1269 This may also be a function to test for appropriate locations where speed
1270 commands should be active.
1272 For example, to activate speed commands when the point is on any
1273 star at the beginning of the headline, you can do this:
1275 (setq org-use-speed-commands
1276 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1277 :group
'org-structure
1279 (const :tag
"Never" nil
)
1280 (const :tag
"At beginning of headline stars" t
)
1283 (defcustom org-speed-commands-user nil
1284 "Alist of additional speed commands.
1285 This list will be checked before `org-speed-commands-default'
1286 when the variable `org-use-speed-commands' is non-nil
1287 and when the cursor is at the beginning of a headline.
1288 The car of each entry is a string with a single letter, which must
1289 be assigned to `self-insert-command' in the global map.
1290 The cdr is either a command to be called interactively, a function
1291 to be called, or a form to be evaluated.
1292 An entry that is just a list with a single string will be interpreted
1293 as a descriptive headline that will be added when listing the speed
1294 commands in the Help buffer using the `?' speed command."
1295 :group
'org-structure
1296 :type
'(repeat :value
("k" . ignore
)
1297 (choice :value
("k" . ignore
)
1298 (list :tag
"Descriptive Headline" (string :tag
"Headline"))
1299 (cons :tag
"Letter and Command"
1300 (string :tag
"Command letter")
1305 (defcustom org-bookmark-names-plist
1306 '(:last-capture
"org-capture-last-stored"
1307 :last-refile
"org-refile-last-stored"
1308 :last-capture-marker
"org-capture-last-stored-marker")
1309 "Names for bookmarks automatically set by some Org commands.
1310 This can provide strings as names for a number of bookmarks Org sets
1311 automatically. The following keys are currently implemented:
1313 :last-capture-marker
1315 When a key does not show up in the property list, the corresponding bookmark
1317 :group
'org-structure
1320 (defgroup org-cycle nil
1321 "Options concerning visibility cycling in Org mode."
1323 :group
'org-structure
)
1325 (defcustom org-cycle-skip-children-state-if-no-children t
1326 "Non-nil means skip CHILDREN state in entries that don't have any."
1330 (defcustom org-cycle-max-level nil
1331 "Maximum level which should still be subject to visibility cycling.
1332 Levels higher than this will, for cycling, be treated as text, not a headline.
1333 When `org-odd-levels-only' is set, a value of N in this variable actually
1334 means 2N-1 stars as the limiting headline.
1335 When nil, cycle all levels.
1336 Note that the limiting level of cycling is also influenced by
1337 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1338 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1342 (const :tag
"No limit" nil
)
1343 (integer :tag
"Maximum level")))
1345 (defcustom org-hide-block-startup nil
1346 "Non-nil means entering Org mode will fold all blocks.
1347 This can also be set in on a per-file basis with
1349 #+STARTUP: hideblocks
1350 #+STARTUP: showblocks"
1355 (defcustom org-cycle-global-at-bob nil
1356 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1358 This makes it possible to do global cycling without having to use `S-TAB'
1359 or `\\[universal-argument] TAB'. For this special case to work, the first \
1361 must not be a headline -- it may be empty or some other text.
1363 When used in this way, `org-cycle-hook' is disabled temporarily to make
1364 sure the cursor stays at the beginning of the buffer.
1366 When this option is nil, don't do anything special at the beginning of
1371 (defcustom org-cycle-level-after-item
/entry-creation t
1372 "Non-nil means cycle entry level or item indentation in new empty entries.
1374 When the cursor is at the end of an empty headline, i.e., with only stars
1375 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1376 and then all possible ancestor states, before returning to the original state.
1377 This makes data entry extremely fast: M-RET to create a new headline,
1378 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1380 When the cursor is at the end of an empty plain list item, one TAB will
1381 make it a subitem, two or more tabs will back up to make this an item
1382 higher up in the item hierarchy."
1386 (defcustom org-cycle-emulate-tab t
1387 "Where should `org-cycle' emulate TAB.
1389 white Only in completely white lines
1390 whitestart Only at the beginning of lines, before the first non-white char
1391 t Everywhere except in headlines
1392 exc-hl-bol Everywhere except at the start of a headline
1393 If TAB is used in a place where it does not emulate TAB, the current subtree
1394 visibility is cycled."
1396 :type
'(choice (const :tag
"Never" nil
)
1397 (const :tag
"Only in completely white lines" white
)
1398 (const :tag
"Before first char in a line" whitestart
)
1399 (const :tag
"Everywhere except in headlines" t
)
1400 (const :tag
"Everywhere except at bol in headlines" exc-hl-bol
)))
1402 (defcustom org-cycle-separator-lines
2
1403 "Number of empty lines needed to keep an empty line between collapsed trees.
1404 If you leave an empty line between the end of a subtree and the following
1405 headline, this empty line is hidden when the subtree is folded.
1406 Org mode will leave (exactly) one empty line visible if the number of
1407 empty lines is equal or larger to the number given in this variable.
1408 So the default 2 means at least 2 empty lines after the end of a subtree
1409 are needed to produce free space between a collapsed subtree and the
1412 If the number is negative, and the number of empty lines is at least -N,
1413 all empty lines are shown.
1415 Special case: when 0, never leave empty lines in collapsed view."
1418 (put 'org-cycle-separator-lines
'safe-local-variable
'integerp
)
1420 (defcustom org-pre-cycle-hook nil
1421 "Hook that is run before visibility cycling is happening.
1422 The function(s) in this hook must accept a single argument which indicates
1423 the new state that will be set right after running this hook. The
1424 argument is a symbol. Before a global state change, it can have the values
1425 `overview', `content', or `all'. Before a local state change, it can have
1426 the values `folded', `children', or `subtree'."
1430 (defcustom org-cycle-hook
'(org-cycle-hide-archived-subtrees
1431 org-cycle-hide-drawers
1432 org-cycle-show-empty-lines
1433 org-optimize-window-after-visibility-change
)
1434 "Hook that is run after `org-cycle' has changed the buffer visibility.
1435 The function(s) in this hook must accept a single argument which indicates
1436 the new state that was set by the most recent `org-cycle' command. The
1437 argument is a symbol. After a global state change, it can have the values
1438 `overview', `contents', or `all'. After a local state change, it can have
1439 the values `folded', `children', or `subtree'."
1443 :package-version
'(Org .
"8.3"))
1445 (defgroup org-edit-structure nil
1446 "Options concerning structure editing in Org mode."
1447 :tag
"Org Edit Structure"
1448 :group
'org-structure
)
1450 (defcustom org-odd-levels-only nil
1451 "Non-nil means skip even levels and only use odd levels for the outline.
1452 This has the effect that two stars are being added/taken away in
1453 promotion/demotion commands. It also influences how levels are
1454 handled by the exporters.
1455 Changing it requires restart of `font-lock-mode' to become effective
1456 for fontification also in regions already fontified.
1457 You may also set this on a per-file basis by adding one of the following
1458 lines to the buffer:
1462 :group
'org-edit-structure
1463 :group
'org-appearance
1466 (defcustom org-adapt-indentation t
1467 "Non-nil means adapt indentation to outline node level.
1469 When this variable is set, Org assumes that you write outlines by
1470 indenting text in each node to align with the headline (after the
1471 stars). The following issues are influenced by this variable:
1473 - The indentation is increased by one space in a demotion
1474 command, and decreased by one in a promotion command. However,
1475 in the latter case, if shifting some line in the entry body
1476 would alter document structure (e.g., insert a new headline),
1477 indentation is not changed at all.
1479 - Property drawers and planning information is inserted indented
1480 when this variable is set. When nil, they will not be indented.
1482 - TAB indents a line relative to current level. The lines below
1483 a headline will be indented when this variable is set.
1485 Note that this is all about true indentation, by adding and
1486 removing space characters. See also `org-indent.el' which does
1487 level-dependent indentation in a virtual way, i.e. at display
1489 :group
'org-edit-structure
1492 (defcustom org-special-ctrl-a
/e nil
1493 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1495 When t, `C-a' will bring back the cursor to the beginning of the
1496 headline text, i.e. after the stars and after a possible TODO
1497 keyword. In an item, this will be the position after bullet and
1498 check-box, if any. When the cursor is already at that position,
1499 another `C-a' will bring it to the beginning of the line.
1501 `C-e' will jump to the end of the headline, ignoring the presence
1502 of tags in the headline. A second `C-e' will then jump to the
1503 true end of the line, after any tags. This also means that, when
1504 this variable is non-nil, `C-e' also will never jump beyond the
1505 end of the heading of a folded section, i.e. not after the
1508 When set to the symbol `reversed', the first `C-a' or `C-e' works
1509 normally, going to the true line boundary first. Only a directly
1510 following, identical keypress will bring the cursor to the
1513 This may also be a cons cell where the behavior for `C-a' and
1514 `C-e' is set separately."
1515 :group
'org-edit-structure
1517 (const :tag
"off" nil
)
1518 (const :tag
"on: after stars/bullet and before tags first" t
)
1519 (const :tag
"reversed: true line boundary first" reversed
)
1520 (cons :tag
"Set C-a and C-e separately"
1521 (choice :tag
"Special C-a"
1522 (const :tag
"off" nil
)
1523 (const :tag
"on: after stars/bullet first" t
)
1524 (const :tag
"reversed: before stars/bullet first" reversed
))
1525 (choice :tag
"Special C-e"
1526 (const :tag
"off" nil
)
1527 (const :tag
"on: before tags first" t
)
1528 (const :tag
"reversed: after tags first" reversed
)))))
1529 (defvaralias 'org-special-ctrl-a
'org-special-ctrl-a
/e
)
1531 (defcustom org-special-ctrl-k nil
1532 "Non-nil means `C-k' will behave specially in headlines.
1533 When nil, `C-k' will call the default `kill-line' command.
1534 When t, the following will happen while the cursor is in the headline:
1536 - When the cursor is at the beginning of a headline, kill the entire
1537 line and possible the folded subtree below the line.
1538 - When in the middle of the headline text, kill the headline up to the tags.
1539 - When after the headline text, kill the tags."
1540 :group
'org-edit-structure
1543 (defcustom org-ctrl-k-protect-subtree nil
1544 "Non-nil means, do not delete a hidden subtree with C-k.
1545 When set to the symbol `error', simply throw an error when C-k is
1546 used to kill (part-of) a headline that has hidden text behind it.
1547 Any other non-nil value will result in a query to the user, if it is
1548 OK to kill that hidden subtree. When nil, kill without remorse."
1549 :group
'org-edit-structure
1552 (const :tag
"Do not protect hidden subtrees" nil
)
1553 (const :tag
"Protect hidden subtrees with a security query" t
)
1554 (const :tag
"Never kill a hidden subtree with C-k" error
)))
1556 (defcustom org-special-ctrl-o t
1557 "Non-nil means, make `C-o' insert a row in tables."
1558 :group
'org-edit-structure
1561 (defcustom org-catch-invisible-edits nil
1562 "Check if in invisible region before inserting or deleting a character.
1565 nil Do not check, so just do invisible edits.
1566 error Throw an error and do nothing.
1567 show Make point visible, and do the requested edit.
1568 show-and-error Make point visible, then throw an error and abort the edit.
1569 smart Make point visible, and do insertion/deletion if it is
1570 adjacent to visible text and the change feels predictable.
1571 Never delete a previously invisible character or add in the
1572 middle or right after an invisible region. Basically, this
1573 allows insertion and backward-delete right before ellipses.
1574 FIXME: maybe in this case we should not even show?"
1575 :group
'org-edit-structure
1578 (const :tag
"Do not check" nil
)
1579 (const :tag
"Throw error when trying to edit" error
)
1580 (const :tag
"Unhide, but do not do the edit" show-and-error
)
1581 (const :tag
"Show invisible part and do the edit" show
)
1582 (const :tag
"Be smart and do the right thing" smart
)))
1584 (defcustom org-yank-folded-subtrees t
1585 "Non-nil means when yanking subtrees, fold them.
1586 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1587 it starts with a heading and all other headings in it are either children
1588 or siblings, then fold all the subtrees. However, do this only if no
1589 text after the yank would be swallowed into a folded tree by this action."
1590 :group
'org-edit-structure
1593 (defcustom org-yank-adjusted-subtrees nil
1594 "Non-nil means when yanking subtrees, adjust the level.
1595 With this setting, `org-paste-subtree' is used to insert the subtree, see
1596 this function for details."
1597 :group
'org-edit-structure
1600 (defcustom org-M-RET-may-split-line
'((default . t
))
1601 "Non-nil means M-RET will split the line at the cursor position.
1602 When nil, it will go to the end of the line before making a
1604 You may also set this option in a different way for different
1605 contexts. Valid contexts are:
1607 headline when creating a new headline
1608 item when creating a new item
1609 table in a table field
1610 default the value to be used for all contexts not explicitly
1612 :group
'org-structure
1615 (const :tag
"Always" t
)
1616 (const :tag
"Never" nil
)
1617 (repeat :greedy t
:tag
"Individual contexts"
1619 (choice :tag
"Context"
1627 (defcustom org-insert-heading-respect-content nil
1628 "Non-nil means insert new headings after the current subtree.
1630 When nil, the new heading is created directly after the current line.
1631 The commands `\\[org-insert-heading-respect-content]' and \
1632 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1633 for the duration of the command."
1634 :group
'org-structure
1637 (defcustom org-blank-before-new-entry
'((heading . auto
)
1638 (plain-list-item . auto
))
1639 "Should `org-insert-heading' leave a blank line before new heading/item?
1640 The value is an alist, with `heading' and `plain-list-item' as CAR,
1641 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1642 which case Org will look at the surrounding headings/items and try to
1643 make an intelligent decision whether to insert a blank line or not."
1644 :group
'org-edit-structure
1646 (cons (const heading
)
1647 (choice (const :tag
"Never" nil
)
1648 (const :tag
"Always" t
)
1649 (const :tag
"Auto" auto
)))
1650 (cons (const plain-list-item
)
1651 (choice (const :tag
"Never" nil
)
1652 (const :tag
"Always" t
)
1653 (const :tag
"Auto" auto
)))))
1655 (defcustom org-insert-heading-hook nil
1656 "Hook being run after inserting a new heading."
1657 :group
'org-edit-structure
1660 (defcustom org-enable-fixed-width-editor t
1661 "Non-nil means lines starting with \":\" are treated as fixed-width.
1662 This currently only means they are never auto-wrapped.
1663 When nil, such lines will be treated like ordinary lines."
1664 :group
'org-edit-structure
1667 (defcustom org-goto-auto-isearch t
1668 "Non-nil means typing characters in `org-goto' starts incremental search.
1669 When nil, you can use these keybindings to navigate the buffer:
1671 q Quit the org-goto interface
1672 n Go to the next visible heading
1673 p Go to the previous visible heading
1674 f Go one heading forward on same level
1675 b Go one heading backward on same level
1676 u Go one heading up"
1677 :group
'org-edit-structure
1680 (defgroup org-sparse-trees nil
1681 "Options concerning sparse trees in Org mode."
1682 :tag
"Org Sparse Trees"
1683 :group
'org-structure
)
1685 (defcustom org-highlight-sparse-tree-matches t
1686 "Non-nil means highlight all matches that define a sparse tree.
1687 The highlights will automatically disappear the next time the buffer is
1688 changed by an edit command."
1689 :group
'org-sparse-trees
1692 (defcustom org-remove-highlights-with-change t
1693 "Non-nil means any change to the buffer will remove temporary highlights.
1695 Such highlights are created by `org-occur' and `org-clock-display'.
1696 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1697 to get rid of the highlights.
1698 The highlights created by `org-toggle-latex-fragment' always need
1699 `\\[org-toggle-latex-fragment]' to be removed."
1700 :group
'org-sparse-trees
1704 (defcustom org-occur-case-fold-search t
1705 "Non-nil means `org-occur' should be case-insensitive.
1706 If set to `smart' the search will be case-insensitive only if it
1707 doesn't specify any upper case character."
1708 :group
'org-sparse-trees
1711 (const :tag
"Case-sensitive" nil
)
1712 (const :tag
"Case-insensitive" t
)
1713 (const :tag
"Case-insensitive for lower case searches only" 'smart
)))
1715 (defcustom org-occur-hook
'(org-first-headline-recenter)
1716 "Hook that is run after `org-occur' has constructed a sparse tree.
1717 This can be used to recenter the window to show as much of the structure
1719 :group
'org-sparse-trees
1722 (defgroup org-imenu-and-speedbar nil
1723 "Options concerning imenu and speedbar in Org mode."
1724 :tag
"Org Imenu and Speedbar"
1725 :group
'org-structure
)
1727 (defcustom org-imenu-depth
2
1728 "The maximum level for Imenu access to Org headlines.
1729 This also applied for speedbar access."
1730 :group
'org-imenu-and-speedbar
1733 (defgroup org-table nil
1734 "Options concerning tables in Org mode."
1738 (defcustom org-self-insert-cluster-for-undo nil
1739 "Non-nil means cluster self-insert commands for undo when possible.
1740 If this is set, then, like in the Emacs command loop, 20 consecutive
1741 characters will be undone together.
1742 This is configurable, because there is some impact on typing performance."
1746 (defcustom org-table-tab-recognizes-table.el t
1747 "Non-nil means TAB will automatically notice a table.el table.
1748 When it sees such a table, it moves point into it and - if necessary -
1749 calls `table-recognize-table'."
1750 :group
'org-table-editing
1753 (defgroup org-link nil
1754 "Options concerning links in Org mode."
1758 (defvar-local org-link-abbrev-alist-local nil
1759 "Buffer-local version of `org-link-abbrev-alist', which see.
1760 The value of this is taken from the #+LINK lines.")
1762 (defcustom org-link-parameters
1763 '(("doi" :follow org--open-doi-link
)
1764 ("elisp" :follow org--open-elisp-link
)
1765 ("file" :complete org-file-complete-link
)
1766 ("ftp" :follow
(lambda (path) (browse-url (concat "ftp:" path
))))
1767 ("help" :follow org--open-help-link
)
1768 ("http" :follow
(lambda (path) (browse-url (concat "http:" path
))))
1769 ("https" :follow
(lambda (path) (browse-url (concat "https:" path
))))
1770 ("mailto" :follow
(lambda (path) (browse-url (concat "mailto:" path
))))
1771 ("news" :follow
(lambda (path) (browse-url (concat "news:" path
))))
1772 ("shell" :follow org--open-shell-link
))
1773 "An alist of properties that defines all the links in Org mode.
1774 The key in each association is a string of the link type.
1775 Subsequent optional elements make up a p-list of link properties.
1777 :follow - A function that takes the link path as an argument.
1779 :export - A function that takes the link path, description and
1780 export-backend as arguments.
1782 :store - A function responsible for storing the link. See the
1783 function `org-store-link-functions'.
1785 :complete - A function that inserts a link with completion. The
1786 function takes one optional prefix arg.
1788 :face - A face for the link, or a function that returns a face.
1789 The function takes one argument which is the link path. The
1790 default face is `org-link'.
1792 :mouse-face - The mouse-face. The default is `highlight'.
1794 :display - `full' will not fold the link in descriptive
1795 display. Default is `org-link'.
1797 :help-echo - A string or function that takes (window object position)
1798 as arguments and returns a string.
1800 :keymap - A keymap that is active on the link. The default is
1803 :htmlize-link - A function for the htmlize-link. Defaults
1804 to (list :uri \"type:path\")
1806 :activate-func - A function to run at the end of font-lock
1807 activation. The function must accept (link-start link-end path bracketp)
1810 :type
'(alist :tag
"Link display parameters"
1813 :package-version
'(Org .
"9.1"))
1815 (defun org-link-get-parameter (type key
)
1816 "Get TYPE link property for KEY.
1817 TYPE is a string and KEY is a plist keyword."
1819 (cdr (assoc type org-link-parameters
))
1822 (defun org-link-set-parameters (type &rest parameters
)
1823 "Set link TYPE properties to PARAMETERS.
1824 PARAMETERS should be :key val pairs."
1825 (let ((data (assoc type org-link-parameters
)))
1826 (if data
(setcdr data
(org-combine-plists (cdr data
) parameters
))
1827 (push (cons type parameters
) org-link-parameters
)
1828 (org-make-link-regexps)
1829 (org-element-update-syntax))))
1831 (defun org-link-types ()
1832 "Return a list of known link types."
1833 (mapcar #'car org-link-parameters
))
1835 (defcustom org-link-abbrev-alist nil
1836 "Alist of link abbreviations.
1837 The car of each element is a string, to be replaced at the start of a link.
1838 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1839 links in Org buffers can have an optional tag after a double colon, e.g.,
1841 [[linkkey:tag][description]]
1843 The `linkkey' must be a single word, starting with a letter, followed
1844 by letters, numbers, `-' or `_'.
1846 If REPLACE is a string, the tag will simply be appended to create the link.
1847 If the string contains \"%s\", the tag will be inserted there. If the string
1848 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1849 at that point (see the function `url-hexify-string'). If the string contains
1850 the specifier \"%(my-function)\", then the custom function `my-function' will
1851 be invoked: this function takes the tag as its only argument and must return
1854 REPLACE may also be a function that will be called with the tag as the
1855 only argument to create the link, which should be returned as a string.
1857 See the manual for examples."
1861 (string :tag
"Protocol")
1863 (string :tag
"Format")
1866 (defcustom org-descriptive-links t
1867 "Non-nil means Org will display descriptive links.
1868 E.g. [[http://orgmode.org][Org website]] will be displayed as
1869 \"Org Website\", hiding the link itself and just displaying its
1870 description. When set to nil, Org will display the full links
1873 You can interactively set the value of this variable by calling
1874 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1878 (defcustom org-link-file-path-type
'adaptive
1879 "How the path name in file links should be stored.
1882 relative Relative to the current directory, i.e. the directory of the file
1883 into which the link is being inserted.
1884 absolute Absolute path, if possible with ~ for home directory.
1885 noabbrev Absolute path, no abbreviation of home directory.
1886 adaptive Use relative path for files in the current directory and sub-
1887 directories of it. For other files, use an absolute path."
1895 (defvaralias 'org-activate-links
'org-highlight-links
)
1896 (defcustom org-highlight-links
'(bracket angle plain radio tag date footnote
)
1897 "Types of links that should be highlighted in Org files.
1899 This is a list of symbols, each one of them leading to the
1900 highlighting of a certain link type.
1902 You can still open links that are not highlighted.
1904 In principle, it does not hurt to turn on highlighting for all
1905 link types. There may be a small gain when turning off unused
1906 link types. The types are:
1908 bracket The recommended [[link][description]] or [[link]] links with hiding.
1909 angle Links in angular brackets that may contain whitespace like
1910 <bbdb:Carsten Dominik>.
1911 plain Plain links in normal text, no whitespace, like http://google.com.
1912 radio Text that is matched by a radio target, see manual for details.
1913 tag Tag settings in a headline (link to tag search).
1914 date Time stamps (link to calendar).
1915 footnote Footnote labels.
1917 If you set this variable during an Emacs session, use `org-mode-restart'
1918 in the Org buffer so that the change takes effect."
1920 :group
'org-appearance
1921 :type
'(set :greedy t
1922 (const :tag
"Double bracket links" bracket
)
1923 (const :tag
"Angular bracket links" angle
)
1924 (const :tag
"Plain text links" plain
)
1925 (const :tag
"Radio target matches" radio
)
1926 (const :tag
"Tags" tag
)
1927 (const :tag
"Timestamps" date
)
1928 (const :tag
"Footnotes" footnote
)))
1930 (defcustom org-make-link-description-function nil
1931 "Function to use for generating link descriptions from links.
1932 This function must take two parameters: the first one is the
1933 link, the second one is the description generated by
1934 `org-insert-link'. The function should return the description to
1937 :type
'(choice (const nil
) (function)))
1939 (defgroup org-link-store nil
1940 "Options concerning storing links in Org mode."
1941 :tag
"Org Store Link"
1944 (defcustom org-url-hexify-p t
1945 "When non-nil, hexify URL when creating a link."
1948 :group
'org-link-store
)
1950 (defcustom org-email-link-description-format
"Email %c: %.30s"
1951 "Format of the description part of a link to an email or usenet message.
1952 The following %-escapes will be replaced by corresponding information:
1954 %F full \"From\" field
1955 %f name, taken from \"From\" field, address if no name
1956 %T full \"To\" field
1957 %t first name in \"To\" field, address if no name
1958 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1959 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1964 You may use normal field width specification between the % and the letter.
1965 This is for example useful to limit the length of the subject.
1967 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1968 :group
'org-link-store
1971 (defcustom org-from-is-user-regexp
1973 (when (and user-mail-address
(not (string= user-mail-address
"")))
1974 (setq r1
(concat "\\<" (regexp-quote user-mail-address
) "\\>")))
1975 (when (and user-full-name
(not (string= user-full-name
"")))
1976 (setq r2
(concat "\\<" (regexp-quote user-full-name
) "\\>")))
1977 (if (and r1 r2
) (concat r1
"\\|" r2
) (or r1 r2
)))
1978 "Regexp matched against the \"From:\" header of an email or usenet message.
1979 It should match if the message is from the user him/herself."
1980 :group
'org-link-store
1983 (defcustom org-context-in-file-links t
1984 "Non-nil means file links from `org-store-link' contain context.
1986 A search string will be added to the file name with :: as separator
1987 and used to find the context when the link is activated by the command
1988 `org-open-at-point'. When this option is t, the entire active region
1989 will be placed in the search string of the file link. If set to a
1990 positive integer, only the first n lines of context will be stored.
1992 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1993 \\[org-store-link]')
1994 negates this setting for the duration of the command."
1995 :group
'org-link-store
1996 :type
'(choice boolean integer
))
1998 (defcustom org-keep-stored-link-after-insertion nil
1999 "Non-nil means keep link in list for entire session.
2001 The command `org-store-link' adds a link pointing to the current
2002 location to an internal list. These links accumulate during a session.
2003 The command `org-insert-link' can be used to insert links into any
2004 Org file (offering completion for all stored links).
2006 When this option is nil, every link which has been inserted once using
2007 `\\[org-insert-link]' will be removed from the list, to make completing the \
2009 links more efficient."
2010 :group
'org-link-store
2013 (defgroup org-link-follow nil
2014 "Options concerning following links in Org mode."
2015 :tag
"Org Follow Link"
2018 (defcustom org-link-translation-function nil
2019 "Function to translate links with different syntax to Org syntax.
2020 This can be used to translate links created for example by the Planner
2021 or emacs-wiki packages to Org syntax.
2022 The function must accept two parameters, a TYPE containing the link
2023 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2024 which is everything after the link protocol. It should return a cons
2025 with possibly modified values of type and path.
2026 Org contains a function for this, so if you set this variable to
2027 `org-translate-link-from-planner', you should be able follow many
2028 links created by planner."
2029 :group
'org-link-follow
2030 :type
'(choice (const nil
) (function)))
2032 (defcustom org-follow-link-hook nil
2033 "Hook that is run after a link has been followed."
2034 :group
'org-link-follow
2037 (defcustom org-tab-follows-link nil
2038 "Non-nil means on links TAB will follow the link.
2039 Needs to be set before org.el is loaded.
2040 This really should not be used, it does not make sense, and the
2041 implementation is bad."
2042 :group
'org-link-follow
2045 (defcustom org-return-follows-link nil
2046 "Non-nil means on links RET will follow the link.
2047 In tables, the special behavior of RET has precedence."
2048 :group
'org-link-follow
2051 (defcustom org-mouse-1-follows-link
2052 (if (boundp 'mouse-1-click-follows-link
) mouse-1-click-follows-link t
)
2053 "Non-nil means mouse-1 on a link will follow the link.
2054 A longer mouse click will still set point. Needs to be set
2055 before org.el is loaded."
2056 :group
'org-link-follow
2058 :package-version
'(Org .
"8.3")
2060 (const :tag
"A double click follows the link" double
)
2061 (const :tag
"Unconditionally follow the link with mouse-1" t
)
2062 (integer :tag
"mouse-1 click does not follow the link if longer than N ms" 450)))
2064 (defcustom org-mark-ring-length
4
2065 "Number of different positions to be recorded in the ring.
2066 Changing this requires a restart of Emacs to work correctly."
2067 :group
'org-link-follow
2070 (defcustom org-link-search-must-match-exact-headline
'query-to-create
2071 "Non-nil means internal fuzzy links can only match headlines.
2073 When nil, the a fuzzy link may point to a target or a named
2074 construct in the document. When set to the special value
2075 `query-to-create', offer to create a new headline when none
2078 Spaces and statistics cookies are ignored during heading searches."
2079 :group
'org-link-follow
2082 (const :tag
"Use fuzzy text search" nil
)
2083 (const :tag
"Match only exact headline" t
)
2084 (const :tag
"Match exact headline or query to create it"
2088 (defcustom org-link-frame-setup
2089 '((vm . vm-visit-folder-other-frame
)
2090 (vm-imap . vm-visit-imap-folder-other-frame
)
2091 (gnus . org-gnus-no-new-news
)
2092 (file . find-file-other-window
)
2093 (wl . wl-other-frame
))
2094 "Setup the frame configuration for following links.
2095 When following a link with Emacs, it may often be useful to display
2096 this link in another window or frame. This variable can be used to
2097 set this up for the different types of links.
2100 `vm-visit-folder-other-window'
2101 `vm-visit-folder-other-frame'
2102 For Gnus, use any of
2105 `org-gnus-no-new-news'
2106 For FILE, use any of
2108 `find-file-other-window'
2109 `find-file-other-frame'
2110 For Wanderlust use any of
2113 For the calendar, use the variable `calendar-setup'.
2114 For BBDB, it is currently only possible to display the matches in
2116 :group
'org-link-follow
2120 (const vm-visit-folder
)
2121 (const vm-visit-folder-other-window
)
2122 (const vm-visit-folder-other-frame
)))
2123 (cons (const vm-imap
)
2125 (const vm-visit-imap-folder
)
2126 (const vm-visit-imap-folder-other-window
)
2127 (const vm-visit-imap-folder-other-frame
)))
2131 (const gnus-other-frame
)
2132 (const org-gnus-no-new-news
)))
2136 (const find-file-other-window
)
2137 (const find-file-other-frame
)))
2141 (const wl-other-frame
)))))
2143 (defcustom org-display-internal-link-with-indirect-buffer nil
2144 "Non-nil means use indirect buffer to display infile links.
2145 Activating internal links (from one location in a file to another location
2146 in the same file) normally just jumps to the location. When the link is
2147 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2149 another window. When this option is set, the other window actually displays
2150 an indirect buffer clone of the current buffer, to avoid any visibility
2151 changes to the current buffer."
2152 :group
'org-link-follow
2155 (defcustom org-open-non-existing-files nil
2156 "Non-nil means `org-open-file' will open non-existing files.
2157 When nil, an error will be generated.
2158 This variable applies only to external applications because they
2159 might choke on non-existing files. If the link is to a file that
2160 will be opened in Emacs, the variable is ignored."
2161 :group
'org-link-follow
2164 (defcustom org-open-directory-means-index-dot-org nil
2165 "Non-nil means a link to a directory really means to index.org.
2166 When nil, following a directory link will run dired or open a finder/explorer
2167 window on that directory."
2168 :group
'org-link-follow
2171 (defcustom org-confirm-shell-link-function
'yes-or-no-p
2172 "Non-nil means ask for confirmation before executing shell links.
2173 Shell links can be dangerous: just think about a link
2175 [[shell:rm -rf ~/*][Google Search]]
2177 This link would show up in your Org document as \"Google Search\",
2178 but really it would remove your entire home directory.
2179 Therefore we advise against setting this variable to nil.
2180 Just change it to `y-or-n-p' if you want to confirm with a
2181 single keystroke rather than having to type \"yes\"."
2182 :group
'org-link-follow
2184 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
2185 (const :tag
"with y-or-n (faster)" y-or-n-p
)
2186 (const :tag
"no confirmation (dangerous)" nil
)))
2187 (put 'org-confirm-shell-link-function
2188 'safe-local-variable
2189 (lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
2191 (defcustom org-confirm-shell-link-not-regexp
""
2192 "A regexp to skip confirmation for shell links."
2193 :group
'org-link-follow
2197 (defcustom org-confirm-elisp-link-function
'yes-or-no-p
2198 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2199 Elisp links can be dangerous: just think about a link
2201 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2203 This link would show up in your Org document as \"Google Search\",
2204 but really it would remove your entire home directory.
2205 Therefore we advise against setting this variable to nil.
2206 Just change it to `y-or-n-p' if you want to confirm with a
2207 single keystroke rather than having to type \"yes\"."
2208 :group
'org-link-follow
2210 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
2211 (const :tag
"with y-or-n (faster)" y-or-n-p
)
2212 (const :tag
"no confirmation (dangerous)" nil
)))
2213 (put 'org-confirm-shell-link-function
2214 'safe-local-variable
2215 (lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
2217 (defcustom org-confirm-elisp-link-not-regexp
""
2218 "A regexp to skip confirmation for Elisp links."
2219 :group
'org-link-follow
2223 (defconst org-file-apps-defaults-gnu
2227 "Default file applications on a UNIX or GNU/Linux system.
2228 See `org-file-apps'.")
2230 (defconst org-file-apps-defaults-macosx
2232 (system .
"open %s")
2234 ("eps.gz" .
"gv %s")
2238 "Default file applications on a macOS system.
2239 The system \"open\" is known as a default, but we use X11 applications
2240 for some files for which the OS does not have a good default.
2241 See `org-file-apps'.")
2243 (defconst org-file-apps-defaults-windowsnt
2244 (list '(remote . emacs
)
2245 (cons 'system
(lambda (file _path
)
2246 (with-no-warnings (w32-shell-execute "open" file
))))
2247 (cons t
(lambda (file _path
)
2248 (with-no-warnings (w32-shell-execute "open" file
)))))
2249 "Default file applications on a Windows NT system.
2250 The system \"open\" is used for most files.
2251 See `org-file-apps'.")
2253 (defcustom org-file-apps
2254 '((auto-mode . emacs
)
2255 ("\\.mm\\'" . default
)
2256 ("\\.x?html?\\'" . default
)
2257 ("\\.pdf\\'" . default
))
2258 "External applications for opening `file:path' items in a document.
2261 Org mode uses system defaults for different file types, but
2262 you can use this variable to set the application for a given file
2263 extension. The entries in this list are cons cells where the car identifies
2264 files and the cdr the corresponding command.
2266 Possible values for the file identifier are:
2268 \"string\" A string as a file identifier can be interpreted in different
2269 ways, depending on its contents:
2271 - Alphanumeric characters only:
2272 Match links with this file extension.
2273 Example: (\"pdf\" . \"evince %s\")
2274 to open PDFs with evince.
2276 - Regular expression: Match links where the
2277 filename matches the regexp. If you want to
2278 use groups here, use shy groups.
2280 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2281 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2282 to open *.html and *.xhtml with firefox.
2284 - Regular expression which contains (non-shy) groups:
2285 Match links where the whole link, including \"::\", and
2286 anything after that, matches the regexp.
2287 In a custom command string, %1, %2, etc. are replaced with
2288 the parts of the link that were matched by the groups.
2289 For backwards compatibility, if a command string is given
2290 that does not use any of the group matches, this case is
2291 handled identically to the second one (i.e. match against
2293 In a custom function, you can access the group matches with
2294 (match-string n link).
2296 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2297 \"evince -p %1 %s\")
2298 to open [[file:document.pdf::5]] with evince at page 5.
2300 `directory' Matches a directory
2301 `remote' Matches a remote file, accessible through tramp or efs.
2302 Remote files most likely should be visited through Emacs
2303 because external applications cannot handle such paths.
2304 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2305 so all files Emacs knows how to handle. Using this with
2306 command `emacs' will open most files in Emacs. Beware that this
2307 will also open html files inside Emacs, unless you add
2308 (\"html\" . default) to the list as well.
2309 `system' The system command to open files, like `open' on Windows
2310 and macOS, and mailcap under GNU/Linux. This is the command
2311 that will be selected if you call `org-open-at-point' with a
2312 double prefix argument (`\\[universal-argument] \
2313 \\[universal-argument] \\[org-open-at-point]').
2314 t Default for files not matched by any of the other options.
2316 Possible values for the command are:
2318 `emacs' The file will be visited by the current Emacs process.
2319 `default' Use the default application for this file type, which is the
2320 association for t in the list, most likely in the system-specific
2321 part. This can be used to overrule an unwanted setting in the
2322 system-specific variable.
2323 `system' Use the system command for opening files, like \"open\".
2324 This command is specified by the entry whose car is `system'.
2325 Most likely, the system-specific version of this variable
2326 does define this command, but you can overrule/replace it
2328 `mailcap' Use command specified in the mailcaps.
2329 string A command to be executed by a shell; %s will be replaced
2330 by the path to the file.
2331 function A Lisp function, which will be called with two arguments:
2332 the file path and the original link string, without the
2335 For more examples, see the system specific constants
2336 `org-file-apps-defaults-macosx'
2337 `org-file-apps-defaults-windowsnt'
2338 `org-file-apps-defaults-gnu'."
2339 :group
'org-link-follow
2341 (cons (choice :value
""
2342 (string :tag
"Extension")
2343 (const :tag
"System command to open files" system
)
2344 (const :tag
"Default for unrecognized files" t
)
2345 (const :tag
"Remote file" remote
)
2346 (const :tag
"Links to a directory" directory
)
2347 (const :tag
"Any files that have Emacs modes"
2350 (const :tag
"Visit with Emacs" emacs
)
2351 (const :tag
"Use default" default
)
2352 (const :tag
"Use the system command" system
)
2353 (string :tag
"Command")
2354 (function :tag
"Function")))))
2356 (defcustom org-doi-server-url
"http://dx.doi.org/"
2357 "The URL of the DOI server."
2360 :group
'org-link-follow
)
2362 (defgroup org-refile nil
2363 "Options concerning refiling entries in Org mode."
2367 (defcustom org-directory
"~/org"
2368 "Directory with Org files.
2369 This is just a default location to look for Org files. There is no need
2370 at all to put your files into this directory. It is used in the
2371 following situations:
2373 1. When a capture template specifies a target file that is not an
2374 absolute path. The path will then be interpreted relative to
2376 2. When the value of variable `org-agenda-files' is a single file, any
2377 relative paths in this file will be taken as relative to
2383 (defcustom org-default-notes-file
(convert-standard-filename "~/.notes")
2384 "Default target for storing notes.
2385 Used as a fall back file for org-capture.el, for templates that
2386 do not specify a target file."
2391 (defcustom org-goto-interface
'outline
2392 "The default interface to be used for `org-goto'.
2394 outline The interface shows an outline of the relevant file
2395 and the correct heading is found by moving through
2396 the outline or by searching with incremental search.
2397 outline-path-completion Headlines in the current buffer are offered via
2398 completion. This is the interface also used by
2399 the refile command."
2402 (const :tag
"Outline" outline
)
2403 (const :tag
"Outline-path-completion" outline-path-completion
)))
2405 (defcustom org-goto-max-level
5
2406 "Maximum target level when running `org-goto' with refile interface."
2410 (defcustom org-reverse-note-order nil
2411 "Non-nil means store new notes at the beginning of a file or entry.
2412 When nil, new notes will be filed to the end of a file or entry.
2413 This can also be a list with cons cells of regular expressions that
2414 are matched against file names, and values."
2418 (const :tag
"Reverse always" t
)
2419 (const :tag
"Reverse never" nil
)
2420 (repeat :tag
"By file name regexp"
2421 (cons regexp boolean
))))
2423 (defcustom org-log-refile nil
2424 "Information to record when a task is refiled.
2426 Possible values are:
2428 nil Don't add anything
2429 time Add a time stamp to the task
2430 note Prompt for a note and add it with template `org-log-note-headings'
2432 This option can also be set with on a per-file-basis with
2434 #+STARTUP: nologrefile
2435 #+STARTUP: logrefile
2436 #+STARTUP: lognoterefile
2438 You can have local logging settings for a subtree by setting the LOGGING
2439 property to one or more of these keywords.
2441 When bulk-refiling from the agenda, the value `note' is forbidden and
2442 will temporarily be changed to `time'."
2444 :group
'org-progress
2447 (const :tag
"No logging" nil
)
2448 (const :tag
"Record timestamp" time
)
2449 (const :tag
"Record timestamp with note." note
)))
2451 (defcustom org-refile-targets nil
2452 "Targets for refiling entries with `\\[org-refile]'.
2453 This is a list of cons cells. Each cell contains:
2454 - a specification of the files to be considered, either a list of files,
2455 or a symbol whose function or variable value will be used to retrieve
2456 a file name or a list of file names. If you use `org-agenda-files' for
2457 that, all agenda files will be scanned for targets. Nil means consider
2458 headings in the current buffer.
2459 - A specification of how to find candidate refile targets. This may be
2461 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2462 This tag has to be present in all target headlines, inheritance will
2464 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2466 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2467 headlines that are refiling targets.
2468 - a cons cell (:level . N). Any headline of level N is considered a target.
2469 Note that, when `org-odd-levels-only' is set, level corresponds to
2470 order in hierarchy, not to the number of stars.
2471 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2472 Note that, when `org-odd-levels-only' is set, level corresponds to
2473 order in hierarchy, not to the number of stars.
2475 Each element of this list generates a set of possible targets.
2476 The union of these sets is presented (with completion) to
2477 the user by `org-refile'.
2479 You can set the variable `org-refile-target-verify-function' to a function
2480 to verify each headline found by the simple criteria above.
2482 When this variable is nil, all top-level headlines in the current buffer
2483 are used, equivalent to the value `((nil . (:level . 1))'."
2487 (choice :value org-agenda-files
2488 (const :tag
"All agenda files" org-agenda-files
)
2489 (const :tag
"Current buffer" nil
)
2490 (function) (variable) (file))
2491 (choice :tag
"Identify target headline by"
2492 (cons :tag
"Specific tag" (const :value
:tag
) (string))
2493 (cons :tag
"TODO keyword" (const :value
:todo
) (string))
2494 (cons :tag
"Regular expression" (const :value
:regexp
) (regexp))
2495 (cons :tag
"Level number" (const :value
:level
) (integer))
2496 (cons :tag
"Max Level number" (const :value
:maxlevel
) (integer))))))
2498 (defcustom org-refile-target-verify-function nil
2499 "Function to verify if the headline at point should be a refile target.
2500 The function will be called without arguments, with point at the
2501 beginning of the headline. It should return t and leave point
2502 where it is if the headline is a valid target for refiling.
2504 If the target should not be selected, the function must return nil.
2505 In addition to this, it may move point to a place from where the search
2506 should be continued. For example, the function may decide that the entire
2507 subtree of the current entry should be excluded and move point to the end
2514 (defcustom org-refile-use-cache nil
2515 "Non-nil means cache refile targets to speed up the process.
2517 The cache for a particular file will be updated automatically when
2518 the buffer has been killed, or when any of the marker used for flagging
2519 refile targets no longer points at a live buffer.
2520 If you have added new entries to a buffer that might themselves be targets,
2521 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2522 if you find that easier, \
2523 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2529 (defcustom org-refile-use-outline-path nil
2530 "Non-nil means provide refile targets as paths.
2531 So a level 3 headline will be available as level1/level2/level3.
2533 When the value is `file', also include the file name (without directory)
2534 into the path. In this case, you can also stop the completion after
2535 the file name, to get entries inserted as top level in the file.
2537 When `full-file-path', include the full file path.
2539 When `buffer-name', use the buffer name."
2542 (const :tag
"Not" nil
)
2543 (const :tag
"Yes" t
)
2544 (const :tag
"Start with file name" file
)
2545 (const :tag
"Start with full file path" full-file-path
)
2546 (const :tag
"Start with buffer name" buffer-name
)))
2548 (defcustom org-outline-path-complete-in-steps t
2549 "Non-nil means complete the outline path in hierarchical steps.
2550 When Org uses the refile interface to select an outline path (see
2551 `org-refile-use-outline-path'), the completion of the path can be
2552 done in a single go, or it can be done in steps down the headline
2553 hierarchy. Going in steps is probably the best if you do not use
2554 a special completion package like `ido' or `icicles'. However,
2555 when using these packages, going in one step can be very fast,
2556 while still showing the whole path to the entry."
2560 (defcustom org-refile-allow-creating-parent-nodes nil
2561 "Non-nil means allow the creation of new nodes as refile targets.
2562 New nodes are then created by adding \"/new node name\" to the completion
2563 of an existing node. When the value of this variable is `confirm',
2564 new node creation must be confirmed by the user (recommended).
2565 When nil, the completion must match an existing entry.
2567 Note that, if the new heading is not seen by the criteria
2568 listed in `org-refile-targets', multiple instances of the same
2569 heading would be created by trying again to file under the new
2573 (const :tag
"Never" nil
)
2574 (const :tag
"Always" t
)
2575 (const :tag
"Prompt for confirmation" confirm
)))
2577 (defcustom org-refile-active-region-within-subtree nil
2578 "Non-nil means also refile active region within a subtree.
2580 By default `org-refile' doesn't allow refiling regions if they
2581 don't contain a set of subtrees, but it might be convenient to
2582 do so sometimes: in that case, the first line of the region is
2583 converted to a headline before refiling."
2588 (defgroup org-todo nil
2589 "Options concerning TODO items in Org mode."
2593 (defgroup org-progress nil
2594 "Options concerning Progress logging in Org mode."
2598 (defvar org-todo-interpretation-widgets
2599 '((:tag
"Sequence (cycling hits every state)" sequence
)
2600 (:tag
"Type (cycling directly to DONE)" type
))
2601 "The available interpretation symbols for customizing `org-todo-keywords'.
2602 Interested libraries should add to this list.")
2604 (defcustom org-todo-keywords
'((sequence "TODO" "DONE"))
2605 "List of TODO entry keyword sequences and their interpretation.
2606 \\<org-mode-map>This is a list of sequences.
2608 Each sequence starts with a symbol, either `sequence' or `type',
2609 indicating if the keywords should be interpreted as a sequence of
2610 action steps, or as different types of TODO items. The first
2611 keywords are states requiring action - these states will select a headline
2612 for inclusion into the global TODO list Org produces. If one of the
2613 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2614 signify that no further action is necessary. If \"|\" is not found,
2615 the last keyword is treated as the only DONE state of the sequence.
2617 The command `\\[org-todo]' cycles an entry through these states, and one
2618 additional state where no keyword is present. For details about this
2619 cycling, see the manual.
2621 TODO keywords and interpretation can also be set on a per-file basis with
2622 the special #+SEQ_TODO and #+TYP_TODO lines.
2624 Each keyword can optionally specify a character for fast state selection
2625 \(in combination with the variable `org-use-fast-todo-selection')
2626 and specifiers for state change logging, using the same syntax that
2627 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2628 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2629 indicates to record a time stamp each time this state is selected.
2631 Each keyword may also specify if a timestamp or a note should be
2632 recorded when entering or leaving the state, by adding additional
2633 characters in the parenthesis after the keyword. This looks like this:
2634 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2635 record only the time of the state change. With X and Y being either
2636 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2637 Y when leaving the state if and only if the *target* state does not
2638 define X. You may omit any of the fast-selection key or X or /Y,
2639 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2641 For backward compatibility, this variable may also be just a list
2642 of keywords. In this case the interpretation (sequence or type) will be
2643 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2645 :group
'org-keywords
2647 (repeat :tag
"Old syntax, just keywords"
2648 (string :tag
"Keyword"))
2649 (repeat :tag
"New syntax"
2652 :tag
"Interpretation"
2653 ;;Quick and dirty way to see
2654 ;;`org-todo-interpretations'. This takes the
2655 ;;place of item arguments
2663 org-todo-interpretation-widgets
))
2666 (string :tag
"Keyword"))))))
2668 (defvar-local org-todo-keywords-1 nil
2669 "All TODO and DONE keywords active in a buffer.")
2670 (defvar org-todo-keywords-for-agenda nil
)
2671 (defvar org-done-keywords-for-agenda nil
)
2672 (defvar org-todo-keyword-alist-for-agenda nil
)
2673 (defvar org-tag-alist-for-agenda nil
2674 "Alist of all tags from all agenda files.")
2675 (defvar org-tag-groups-alist-for-agenda nil
2676 "Alist of all groups tags from all current agenda files.")
2677 (defvar-local org-tag-groups-alist nil
)
2678 (defvar org-agenda-contributing-files nil
)
2679 (defvar-local org-current-tag-alist nil
2680 "Alist of all tag groups in current buffer.
2681 This variable takes into consideration `org-tag-alist',
2682 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2683 (defvar-local org-not-done-keywords nil
)
2684 (defvar-local org-done-keywords nil
)
2685 (defvar-local org-todo-heads nil
)
2686 (defvar-local org-todo-sets nil
)
2687 (defvar-local org-todo-log-states nil
)
2688 (defvar-local org-todo-kwd-alist nil
)
2689 (defvar-local org-todo-key-alist nil
)
2690 (defvar-local org-todo-key-trigger nil
)
2692 (defcustom org-todo-interpretation
'sequence
2693 "Controls how TODO keywords are interpreted.
2694 This variable is in principle obsolete and is only used for
2695 backward compatibility, if the interpretation of todo keywords is
2696 not given already in `org-todo-keywords'. See that variable for
2699 :group
'org-keywords
2700 :type
'(choice (const sequence
)
2703 (defcustom org-use-fast-todo-selection t
2705 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2706 This variable describes if and under what circumstances the cycling
2707 mechanism for TODO keywords will be replaced by a single-key, direct
2710 When nil, fast selection is never used.
2712 When the symbol `prefix', it will be used when `org-todo' is called
2713 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2714 in an Org buffer, and
2715 `\\[universal-argument] t' in an agenda buffer.
2717 When t, fast selection is used by default. In this case, the prefix
2718 argument forces cycling instead.
2720 In all cases, the special interface is only used if access keys have
2721 actually been assigned by the user, i.e. if keywords in the configuration
2722 are followed by a letter in parenthesis, like TODO(t)."
2725 (const :tag
"Never" nil
)
2726 (const :tag
"By default" t
)
2727 (const :tag
"Only with C-u C-c C-t" prefix
)))
2729 (defcustom org-provide-todo-statistics t
2730 "Non-nil means update todo statistics after insert and toggle.
2731 ALL-HEADLINES means update todo statistics by including headlines
2732 with no TODO keyword as well, counting them as not done.
2733 A list of TODO keywords means the same, but skip keywords that are
2735 When set to a list of two lists, the first list contains keywords
2736 to consider as TODO keywords, the second list contains keywords
2737 to consider as DONE keywords.
2739 When this is set, todo statistics is updated in the parent of the
2740 current entry each time a todo state is changed."
2743 (const :tag
"Yes, only for TODO entries" t
)
2744 (const :tag
"Yes, including all entries" all-headlines
)
2745 (repeat :tag
"Yes, for TODOs in this list"
2746 (string :tag
"TODO keyword"))
2747 (list :tag
"Yes, for TODOs and DONEs in these lists"
2748 (repeat (string :tag
"TODO keyword"))
2749 (repeat (string :tag
"DONE keyword")))
2750 (other :tag
"No TODO statistics" nil
)))
2752 (defcustom org-hierarchical-todo-statistics t
2753 "Non-nil means TODO statistics covers just direct children.
2754 When nil, all entries in the subtree are considered.
2755 This has only an effect if `org-provide-todo-statistics' is set.
2756 To set this to nil for only a single subtree, use a COOKIE_DATA
2757 property and include the word \"recursive\" into the value."
2761 (defcustom org-after-todo-state-change-hook nil
2762 "Hook which is run after the state of a TODO item was changed.
2763 The new state (a string with a TODO keyword, or nil) is available in the
2764 Lisp variable `org-state'."
2768 (defvar org-blocker-hook nil
2769 "Hook for functions that are allowed to block a state change.
2771 Functions in this hook should not modify the buffer.
2772 Each function gets as its single argument a property list,
2773 see `org-trigger-hook' for more information about this list.
2775 If any of the functions in this hook returns nil, the state change
2778 (defvar org-trigger-hook nil
2779 "Hook for functions that are triggered by a state change.
2781 Each function gets as its single argument a property list with at
2782 least the following elements:
2784 (:type type-of-change :position pos-at-entry-start
2785 :from old-state :to new-state)
2787 Depending on the type, more properties may be present.
2789 This mechanism is currently implemented for:
2793 :type todo-state-change
2794 :from previous state (keyword as a string), or nil, or a symbol
2795 `todo' or `done', to indicate the general type of state.
2796 :to new state, like in :from")
2798 (defcustom org-enforce-todo-dependencies nil
2799 "Non-nil means undone TODO entries will block switching the parent to DONE.
2800 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2801 be blocked if any prior sibling is not yet done.
2802 Finally, if the parent is blocked because of ordered siblings of its own,
2803 the child will also be blocked."
2804 :set
(lambda (var val
)
2807 (add-hook 'org-blocker-hook
2808 'org-block-todo-from-children-or-siblings-or-parent
)
2809 (remove-hook 'org-blocker-hook
2810 'org-block-todo-from-children-or-siblings-or-parent
)))
2814 (defcustom org-enforce-todo-checkbox-dependencies nil
2815 "Non-nil means unchecked boxes will block switching the parent to DONE.
2816 When this is nil, checkboxes have no influence on switching TODO states.
2817 When non-nil, you first need to check off all check boxes before the TODO
2818 entry can be switched to DONE.
2819 This variable needs to be set before org.el is loaded, and you need to
2820 restart Emacs after a change to make the change effective. The only way
2821 to change is while Emacs is running is through the customize interface."
2822 :set
(lambda (var val
)
2825 (add-hook 'org-blocker-hook
2826 'org-block-todo-from-checkboxes
)
2827 (remove-hook 'org-blocker-hook
2828 'org-block-todo-from-checkboxes
)))
2832 (defcustom org-treat-insert-todo-heading-as-state-change nil
2833 "Non-nil means inserting a TODO heading is treated as state change.
2834 So when the command `\\[org-insert-todo-heading]' is used, state change
2835 logging will apply if appropriate. When nil, the new TODO item will
2836 be inserted directly, and no logging will take place."
2840 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2841 "Non-nil means switching TODO states with S-cursor counts as state change.
2842 This is the default behavior. However, setting this to nil allows a
2843 convenient way to select a TODO state and bypass any logging associated
2848 (defcustom org-todo-state-tags-triggers nil
2849 "Tag changes that should be triggered by TODO state changes.
2850 This is a list. Each entry is
2852 (state-change (tag . flag) .......)
2854 State-change can be a string with a state, and empty string to indicate the
2855 state that has no TODO keyword, or it can be one of the symbols `todo'
2856 or `done', meaning any not-done or done state, respectively."
2860 (cons (choice :tag
"When changing to"
2861 (const :tag
"Not-done state" todo
)
2862 (const :tag
"Done state" done
)
2863 (string :tag
"State"))
2865 (cons :tag
"Tag action"
2867 (choice (const :tag
"Add" t
) (const :tag
"Remove" nil
)))))))
2869 (defcustom org-log-done nil
2870 "Information to record when a task moves to the DONE state.
2872 Possible values are:
2874 nil Don't add anything, just change the keyword
2875 time Add a time stamp to the task
2876 note Prompt for a note and add it with template `org-log-note-headings'
2878 This option can also be set with on a per-file-basis with
2880 #+STARTUP: nologdone
2882 #+STARTUP: lognotedone
2884 You can have local logging settings for a subtree by setting the LOGGING
2885 property to one or more of these keywords."
2887 :group
'org-progress
2889 (const :tag
"No logging" nil
)
2890 (const :tag
"Record CLOSED timestamp" time
)
2891 (const :tag
"Record CLOSED timestamp with note." note
)))
2893 ;; Normalize old uses of org-log-done.
2895 ((eq org-log-done t
) (setq org-log-done
'time
))
2896 ((and (listp org-log-done
) (memq 'done org-log-done
))
2897 (setq org-log-done
'note
)))
2899 (defcustom org-log-reschedule nil
2900 "Information to record when the scheduling date of a tasks is modified.
2902 Possible values are:
2904 nil Don't add anything, just change the date
2905 time Add a time stamp to the task
2906 note Prompt for a note and add it with template `org-log-note-headings'
2908 This option can also be set with on a per-file-basis with
2910 #+STARTUP: nologreschedule
2911 #+STARTUP: logreschedule
2912 #+STARTUP: lognotereschedule"
2914 :group
'org-progress
2916 (const :tag
"No logging" nil
)
2917 (const :tag
"Record timestamp" time
)
2918 (const :tag
"Record timestamp with note." note
)))
2920 (defcustom org-log-redeadline nil
2921 "Information to record when the deadline date of a tasks is modified.
2923 Possible values are:
2925 nil Don't add anything, just change the date
2926 time Add a time stamp to the task
2927 note Prompt for a note and add it with template `org-log-note-headings'
2929 This option can also be set with on a per-file-basis with
2931 #+STARTUP: nologredeadline
2932 #+STARTUP: logredeadline
2933 #+STARTUP: lognoteredeadline
2935 You can have local logging settings for a subtree by setting the LOGGING
2936 property to one or more of these keywords."
2938 :group
'org-progress
2940 (const :tag
"No logging" nil
)
2941 (const :tag
"Record timestamp" time
)
2942 (const :tag
"Record timestamp with note." note
)))
2944 (defcustom org-log-note-clock-out nil
2945 "Non-nil means record a note when clocking out of an item.
2946 This can also be configured on a per-file basis by adding one of
2947 the following lines anywhere in the buffer:
2949 #+STARTUP: lognoteclock-out
2950 #+STARTUP: nolognoteclock-out"
2952 :group
'org-progress
2955 (defcustom org-log-done-with-time t
2956 "Non-nil means the CLOSED time stamp will contain date and time.
2957 When nil, only the date will be recorded."
2958 :group
'org-progress
2961 (defcustom org-log-note-headings
2962 '((done .
"CLOSING NOTE %t")
2963 (state .
"State %-12s from %-12S %t")
2964 (note .
"Note taken on %t")
2965 (reschedule .
"Rescheduled from %S on %t")
2966 (delschedule .
"Not scheduled, was %S on %t")
2967 (redeadline .
"New deadline from %S on %t")
2968 (deldeadline .
"Removed deadline, was %S on %t")
2969 (refile .
"Refiled on %t")
2971 "Headings for notes added to entries.
2973 The value is an alist, with the car being a symbol indicating the
2974 note context, and the cdr is the heading to be used. The heading
2975 may also be the empty string. The following placeholders can be
2979 %T an active time stamp instead the default inactive one
2980 %d a short-format time stamp.
2981 %D an active short-format time stamp.
2982 %s the new TODO state or time stamp (inactive), in double quotes.
2983 %S the old TODO state or time stamp (inactive), in double quotes.
2987 In fact, it is not a good idea to change the `state' entry,
2988 because Agenda Log mode depends on the format of these entries."
2990 :group
'org-progress
2991 :type
'(list :greedy t
2992 (cons (const :tag
"Heading when closing an item" done
) string
)
2994 "Heading when changing todo state (todo sequence only)"
2996 (cons (const :tag
"Heading when just taking a note" note
) string
)
2997 (cons (const :tag
"Heading when rescheduling" reschedule
) string
)
2998 (cons (const :tag
"Heading when an item is no longer scheduled" delschedule
) string
)
2999 (cons (const :tag
"Heading when changing deadline" redeadline
) string
)
3000 (cons (const :tag
"Heading when deleting a deadline" deldeadline
) string
)
3001 (cons (const :tag
"Heading when refiling" refile
) string
)
3002 (cons (const :tag
"Heading when clocking out" clock-out
) string
)))
3004 (unless (assq 'note org-log-note-headings
)
3005 (push '(note .
"%t") org-log-note-headings
))
3007 (defcustom org-log-into-drawer nil
3008 "Non-nil means insert state change notes and time stamps into a drawer.
3009 When nil, state changes notes will be inserted after the headline and
3010 any scheduling and clock lines, but not inside a drawer.
3012 The value of this variable should be the name of the drawer to use.
3013 LOGBOOK is proposed as the default drawer for this purpose, you can
3014 also set this to a string to define the drawer of your choice.
3016 A value of t is also allowed, representing \"LOGBOOK\".
3018 A value of t or nil can also be set with on a per-file-basis with
3020 #+STARTUP: logdrawer
3021 #+STARTUP: nologdrawer
3023 If this variable is set, `org-log-state-notes-insert-after-drawers'
3026 You can set the property LOG_INTO_DRAWER to overrule this setting for
3029 Do not check directly this variable in a Lisp program. Call
3030 function `org-log-into-drawer' instead."
3032 :group
'org-progress
3034 (const :tag
"Not into a drawer" nil
)
3035 (const :tag
"LOGBOOK" t
)
3036 (string :tag
"Other")))
3038 (defvaralias 'org-log-state-notes-into-drawer
'org-log-into-drawer
)
3040 (defun org-log-into-drawer ()
3041 "Name of the log drawer, as a string, or nil.
3042 This is the value of `org-log-into-drawer'. However, if the
3043 current entry has or inherits a LOG_INTO_DRAWER property, it will
3044 be used instead of the default value."
3045 (let ((p (org-entry-get nil
"LOG_INTO_DRAWER" 'inherit t
)))
3046 (cond ((equal p
"nil") nil
)
3047 ((equal p
"t") "LOGBOOK")
3050 ((stringp org-log-into-drawer
) org-log-into-drawer
)
3051 (org-log-into-drawer "LOGBOOK"))))
3053 (defcustom org-log-state-notes-insert-after-drawers nil
3054 "Non-nil means insert state change notes after any drawers in entry.
3055 Only the drawers that *immediately* follow the headline and the
3056 deadline/scheduled line are skipped.
3057 When nil, insert notes right after the heading and perhaps the line
3058 with deadline/scheduling if present.
3060 This variable will have no effect if `org-log-into-drawer' is
3063 :group
'org-progress
3066 (defcustom org-log-states-order-reversed t
3067 "Non-nil means the latest state note will be directly after heading.
3068 When nil, the state change notes will be ordered according to time.
3070 This option can also be set with on a per-file-basis with
3072 #+STARTUP: logstatesreversed
3073 #+STARTUP: nologstatesreversed"
3075 :group
'org-progress
3078 (defcustom org-todo-repeat-to-state nil
3079 "The TODO state to which a repeater should return the repeating task.
3080 By default this is the first task in a TODO sequence, or the previous state
3081 in a TODO_TYP set. But you can specify another task here.
3082 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3085 :type
'(choice (const :tag
"Head of sequence" nil
)
3086 (string :tag
"Specific state")))
3088 (defcustom org-log-repeat
'time
3089 "Non-nil means record moving through the DONE state when triggering repeat.
3090 An auto-repeating task is immediately switched back to TODO when
3091 marked DONE. If you are not logging state changes (by adding \"@\"
3092 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3093 record a closing note, there will be no record of the task moving
3094 through DONE. This variable forces taking a note anyway.
3096 nil Don't force a record
3097 time Record a time stamp
3098 note Prompt for a note and add it with template `org-log-note-headings'
3100 This option can also be set with on a per-file-basis with
3102 #+STARTUP: nologrepeat
3103 #+STARTUP: logrepeat
3104 #+STARTUP: lognoterepeat
3106 You can have local logging settings for a subtree by setting the LOGGING
3107 property to one or more of these keywords."
3109 :group
'org-progress
3111 (const :tag
"Don't force a record" nil
)
3112 (const :tag
"Force recording the DONE state" time
)
3113 (const :tag
"Force recording a note with the DONE state" note
)))
3116 (defgroup org-priorities nil
3117 "Priorities in Org mode."
3118 :tag
"Org Priorities"
3121 (defcustom org-enable-priority-commands t
3122 "Non-nil means priority commands are active.
3123 When nil, these commands will be disabled, so that you never accidentally
3125 :group
'org-priorities
3128 (defcustom org-highest-priority ?A
3129 "The highest priority of TODO items. A character like ?A, ?B etc.
3130 Must have a smaller ASCII number than `org-lowest-priority'."
3131 :group
'org-priorities
3134 (defcustom org-lowest-priority ?C
3135 "The lowest priority of TODO items. A character like ?A, ?B etc.
3136 Must have a larger ASCII number than `org-highest-priority'."
3137 :group
'org-priorities
3140 (defcustom org-default-priority ?B
3141 "The default priority of TODO items.
3142 This is the priority an item gets if no explicit priority is given.
3143 When starting to cycle on an empty priority the first step in the cycle
3144 depends on `org-priority-start-cycle-with-default'. The resulting first
3145 step priority must not exceed the range from `org-highest-priority' to
3146 `org-lowest-priority' which means that `org-default-priority' has to be
3147 in this range exclusive or inclusive the range boundaries. Else the
3148 first step refuses to set the default and the second will fall back
3149 to (depending on the command used) the highest or lowest priority."
3150 :group
'org-priorities
3153 (defcustom org-priority-start-cycle-with-default t
3154 "Non-nil means start with default priority when starting to cycle.
3155 When this is nil, the first step in the cycle will be (depending on the
3156 command used) one higher or lower than the default priority.
3157 See also `org-default-priority'."
3158 :group
'org-priorities
3161 (defcustom org-get-priority-function nil
3162 "Function to extract the priority from a string.
3163 The string is normally the headline. If this is nil Org computes the
3164 priority from the priority cookie like [#A] in the headline. It returns
3165 an integer, increasing by 1000 for each priority level.
3166 The user can set a different function here, which should take a string
3167 as an argument and return the numeric priority."
3168 :group
'org-priorities
3174 (defgroup org-time nil
3175 "Options concerning time stamps and deadlines in Org mode."
3179 (defcustom org-time-stamp-rounding-minutes
'(0 5)
3180 "Number of minutes to round time stamps to.
3182 These are two values, the first applies when first creating a time stamp.
3183 The second applies when changing it with the commands `S-up' and `S-down'.
3184 When changing the time stamp, this means that it will change in steps
3185 of N minutes, as given by the second value.
3187 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3188 numbers should be factors of 60, so for example 5, 10, 15.
3190 When this is larger than 1, you can still force an exact time stamp by using
3191 a double prefix argument to a time stamp command like \
3192 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3193 and by using a prefix arg to `S-up/down' to specify the exact number
3194 of minutes to shift."
3196 :get
(lambda (var) ; Make sure both elements are there
3197 (if (integerp (default-value var
))
3198 (list (default-value var
) 5)
3199 (default-value var
)))
3201 (integer :tag
"when inserting times")
3202 (integer :tag
"when modifying times")))
3204 ;; Normalize old customizations of this variable.
3205 (when (integerp org-time-stamp-rounding-minutes
)
3206 (setq org-time-stamp-rounding-minutes
3207 (list org-time-stamp-rounding-minutes
3208 org-time-stamp-rounding-minutes
)))
3210 (defcustom org-display-custom-times nil
3211 "Non-nil means overlay custom formats over all time stamps.
3212 The formats are defined through the variable `org-time-stamp-custom-formats'.
3213 To turn this on on a per-file basis, insert anywhere in the file:
3214 #+STARTUP: customtime"
3218 (make-variable-buffer-local 'org-display-custom-times
)
3220 (defcustom org-time-stamp-custom-formats
3221 '("<%m/%d/%y %a>" .
"<%m/%d/%y %a %H:%M>") ; american
3222 "Custom formats for time stamps. See `format-time-string' for the syntax.
3223 These are overlaid over the default ISO format if the variable
3224 `org-display-custom-times' is set. Time like %H:%M should be at the
3225 end of the second format. The custom formats are also honored by export
3226 commands, if custom time display is turned on at the time of export."
3230 (defun org-time-stamp-format (&optional long inactive
)
3231 "Get the right format for a time string."
3232 (let ((f (if long
(cdr org-time-stamp-formats
)
3233 (car org-time-stamp-formats
))))
3235 (concat "[" (substring f
1 -
1) "]")
3238 (defcustom org-deadline-warning-days
14
3239 "Number of days before expiration during which a deadline becomes active.
3240 This variable governs the display in sparse trees and in the agenda.
3241 When 0 or negative, it means use this number (the absolute value of it)
3242 even if a deadline has a different individual lead time specified.
3244 Custom commands can set this variable in the options section."
3246 :group
'org-agenda-daily
/weekly
3249 (defcustom org-scheduled-delay-days
0
3250 "Number of days before a scheduled item becomes active.
3251 This variable governs the display in sparse trees and in the agenda.
3252 The default value (i.e. 0) means: don't delay scheduled item.
3253 When negative, it means use this number (the absolute value of it)
3254 even if a scheduled item has a different individual delay time
3257 Custom commands can set this variable in the options section."
3259 :group
'org-agenda-daily
/weekly
3261 :package-version
'(Org .
"8.0")
3264 (defcustom org-read-date-prefer-future t
3265 "Non-nil means assume future for incomplete date input from user.
3266 This affects the following situations:
3267 1. The user gives a month but not a year.
3268 For example, if it is April and you enter \"feb 2\", this will be read
3269 as Feb 2, *next* year. \"May 5\", however, will be this year.
3270 2. The user gives a day, but no month.
3271 For example, if today is the 15th, and you enter \"3\", Org will read
3272 this as the third of *next* month. However, if you enter \"17\",
3273 it will be considered as *this* month.
3275 If you set this variable to the symbol `time', then also the following
3278 3. If the user gives a time.
3279 If the time is before now, it will be interpreted as tomorrow.
3281 Currently none of this works for ISO week specifications.
3283 When this option is nil, the current day, month and year will always be
3286 See also `org-agenda-jump-prefer-future'."
3289 (const :tag
"Never" nil
)
3290 (const :tag
"Check month and day" t
)
3291 (const :tag
"Check month, day, and time" time
)))
3293 (defcustom org-agenda-jump-prefer-future
'org-read-date-prefer-future
3294 "Should the agenda jump command prefer the future for incomplete dates?
3295 The default is to do the same as configured in `org-read-date-prefer-future'.
3296 But you can also set a deviating value here.
3297 This may t or nil, or the symbol `org-read-date-prefer-future'."
3302 (const :tag
"Use org-read-date-prefer-future"
3303 org-read-date-prefer-future
)
3304 (const :tag
"Never" nil
)
3305 (const :tag
"Always" t
)))
3307 (defcustom org-read-date-force-compatible-dates t
3308 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3310 Depending on the system Emacs is running on, certain dates cannot
3311 be represented with the type used internally to represent time.
3312 Dates between 1970-1-1 and 2038-1-1 can always be represented
3313 correctly. Some systems allow for earlier dates, some for later,
3314 some for both. One way to find out it to insert any date into an
3315 Org buffer, putting the cursor on the year and hitting S-up and
3316 S-down to test the range.
3318 When this variable is set to t, the date/time prompt will not let
3319 you specify dates outside the 1970-2037 range, so it is certain that
3320 these dates will work in whatever version of Emacs you are
3321 running, and also that you can move a file from one Emacs implementation
3322 to another. WHenever Org is forcing the year for you, it will display
3325 When this variable is nil, Org will check if the date is
3326 representable in the specific Emacs implementation you are using.
3327 If not, it will force a year, usually the current year, and beep
3328 to remind you. Currently this setting is not recommended because
3329 the likelihood that you will open your Org files in an Emacs that
3330 has limited date range is not negligible.
3332 A workaround for this problem is to use diary sexp dates for time
3333 stamps outside of this range."
3338 (defcustom org-read-date-display-live t
3339 "Non-nil means display current interpretation of date prompt live.
3340 This display will be in an overlay, in the minibuffer."
3344 (defcustom org-read-date-popup-calendar t
3345 "Non-nil means pop up a calendar when prompting for a date.
3346 In the calendar, the date can be selected with mouse-1. However, the
3347 minibuffer will also be active, and you can simply enter the date as well.
3348 When nil, only the minibuffer will be available."
3351 (defvaralias 'org-popup-calendar-for-date-prompt
3352 'org-read-date-popup-calendar
)
3354 (defcustom org-extend-today-until
0
3355 "The hour when your day really ends. Must be an integer.
3356 This has influence for the following applications:
3357 - When switching the agenda to \"today\". It it is still earlier than
3358 the time given here, the day recognized as TODAY is actually yesterday.
3359 - When a date is read from the user and it is still before the time given
3360 here, the current date and time will be assumed to be yesterday, 23:59.
3361 Also, timestamps inserted in capture templates follow this rule.
3363 IMPORTANT: This is a feature whose implementation is and likely will
3364 remain incomplete. Really, it is only here because past midnight seems to
3365 be the favorite working time of John Wiegley :-)"
3369 (defcustom org-use-effective-time nil
3370 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3371 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3372 \"effective time\" of any timestamps between midnight and 8am will be
3373 23:59 of the previous day."
3378 (defcustom org-use-last-clock-out-time-as-effective-time nil
3379 "When non-nil, use the last clock out time for `org-todo'.
3380 Note that this option has precedence over the combined use of
3381 `org-use-effective-time' and `org-extend-today-until'."
3384 :package-version
'(Org .
"8.0")
3387 (defcustom org-edit-timestamp-down-means-later nil
3388 "Non-nil means S-down will increase the time in a time stamp.
3389 When nil, S-up will increase."
3393 (defcustom org-calendar-follow-timestamp-change t
3394 "Non-nil means make the calendar window follow timestamp changes.
3395 When a timestamp is modified and the calendar window is visible, it will be
3396 moved to the new date."
3400 (defgroup org-tags nil
3401 "Options concerning tags in Org mode."
3405 (defcustom org-tag-alist nil
3406 "Default tags available in Org files.
3408 The value of this variable is an alist. Associations either:
3414 where TAG is a tag as a string, SELECT is character, used to
3415 select that tag through the fast tag selection interface, and
3416 SPECIAL is one of the following keywords: `:startgroup',
3417 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3418 `:newline'. These keywords are used to define a hierarchy of
3419 tags. See manual for details.
3421 When this variable is nil, Org mode bases tag input on what is
3422 already in the buffer. The value can be overridden locally by
3423 using a TAGS keyword, e.g.,
3427 See also `org-tag-persistent-alist' to sidestep this behavior."
3431 (cons :tag
"Tag with key"
3432 (string :tag
"Tag name")
3433 (character :tag
"Access char"))
3434 (list :tag
"Tag" (string :tag
"Tag name"))
3435 (const :tag
"Start radio group" (:startgroup
))
3436 (const :tag
"Start tag group, non distinct" (:startgrouptag
))
3437 (const :tag
"Group tags delimiter" (:grouptags
))
3438 (const :tag
"End radio group" (:endgroup
))
3439 (const :tag
"End tag group, non distinct" (:endgrouptag
))
3440 (const :tag
"New line" (:newline
)))))
3442 (defcustom org-tag-persistent-alist nil
3443 "Tags always available in Org files.
3445 The value of this variable is an alist. Associations either:
3451 where TAG is a tag as a string, SELECT is a character, used to
3452 select that tag through the fast tag selection interface, and
3453 SPECIAL is one of the following keywords: `:startgroup',
3454 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3455 `:newline'. These keywords are used to define a hierarchy of
3456 tags. See manual for details.
3458 Unlike to `org-tag-alist', tags defined in this variable do not
3459 depend on a local TAGS keyword. Instead, to disable these tags
3460 on a per-file basis, insert anywhere in the file:
3466 (cons :tag
"Tag with key"
3467 (string :tag
"Tag name")
3468 (character :tag
"Access char"))
3469 (list :tag
"Tag" (string :tag
"Tag name"))
3470 (const :tag
"Start radio group" (:startgroup
))
3471 (const :tag
"Start tag group, non distinct" (:startgrouptag
))
3472 (const :tag
"Group tags delimiter" (:grouptags
))
3473 (const :tag
"End radio group" (:endgroup
))
3474 (const :tag
"End tag group, non distinct" (:endgrouptag
))
3475 (const :tag
"New line" (:newline
)))))
3477 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3478 "If non-nil, always offer completion for all tags of all agenda files.
3479 Instead of customizing this variable directly, you might want to
3480 set it locally for capture buffers, because there no list of
3481 tags in that file can be created dynamically (there are none).
3483 (add-hook \\='org-capture-mode-hook
3485 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3490 (defvar org-file-tags nil
3491 "List of tags that can be inherited by all entries in the file.
3492 The tags will be inherited if the variable `org-use-tag-inheritance'
3493 says they should be.
3494 This variable is populated from #+FILETAGS lines.")
3496 (defcustom org-use-fast-tag-selection
'auto
3497 "Non-nil means use fast tag selection scheme.
3498 This is a special interface to select and deselect tags with single keys.
3499 When nil, fast selection is never used.
3500 When the symbol `auto', fast selection is used if and only if selection
3501 characters for tags have been configured, either through the variable
3502 `org-tag-alist' or through a #+TAGS line in the buffer.
3503 When t, fast selection is always used and selection keys are assigned
3504 automatically if necessary."
3507 (const :tag
"Always" t
)
3508 (const :tag
"Never" nil
)
3509 (const :tag
"When selection characters are configured" auto
)))
3511 (defcustom org-fast-tag-selection-single-key nil
3512 "Non-nil means fast tag selection exits after first change.
3513 When nil, you have to press RET to exit it.
3514 During fast tag selection, you can toggle this flag with `C-c'.
3515 This variable can also have the value `expert'. In this case, the window
3516 displaying the tags menu is not even shown, until you press C-c again."
3519 (const :tag
"No" nil
)
3520 (const :tag
"Yes" t
)
3521 (const :tag
"Expert" expert
)))
3523 (defvar org-fast-tag-selection-include-todo nil
3524 "Non-nil means fast tags selection interface will also offer TODO states.
3525 This is an undocumented feature, you should not rely on it.")
3527 (defcustom org-tags-column -
77
3528 "The column to which tags should be indented in a headline.
3529 If this number is positive, it specifies the column. If it is negative,
3530 it means that the tags should be flushright to that column. For example,
3531 -80 works well for a normal 80 character screen.
3532 When 0, place tags directly after headline text, with only one space in
3537 (defcustom org-auto-align-tags t
3538 "Non-nil keeps tags aligned when modifying headlines.
3539 Some operations (i.e. demoting) change the length of a headline and
3540 therefore shift the tags around. With this option turned on, after
3541 each such operation the tags are again aligned to `org-tags-column'."
3545 (defcustom org-use-tag-inheritance t
3546 "Non-nil means tags in levels apply also for sublevels.
3547 When nil, only the tags directly given in a specific line apply there.
3548 This may also be a list of tags that should be inherited, or a regexp that
3549 matches tags that should be inherited. Additional control is possible
3550 with the variable `org-tags-exclude-from-inheritance' which gives an
3551 explicit list of tags to be excluded from inheritance, even if the value of
3552 `org-use-tag-inheritance' would select it for inheritance.
3554 If this option is t, a match early-on in a tree can lead to a large
3555 number of matches in the subtree when constructing the agenda or creating
3556 a sparse tree. If you only want to see the first match in a tree during
3557 a search, check out the variable `org-tags-match-list-sublevels'."
3560 (const :tag
"Not" nil
)
3561 (const :tag
"Always" t
)
3562 (repeat :tag
"Specific tags" (string :tag
"Tag"))
3563 (regexp :tag
"Tags matched by regexp")))
3565 (defcustom org-tags-exclude-from-inheritance nil
3566 "List of tags that should never be inherited.
3567 This is a way to exclude a few tags from inheritance. For way to do
3568 the opposite, to actively allow inheritance for selected tags,
3569 see the variable `org-use-tag-inheritance'."
3571 :type
'(repeat (string :tag
"Tag")))
3573 (defun org-tag-inherit-p (tag)
3574 "Check if TAG is one that should be inherited."
3576 ((member tag org-tags-exclude-from-inheritance
) nil
)
3577 ((eq org-use-tag-inheritance t
) t
)
3578 ((not org-use-tag-inheritance
) nil
)
3579 ((stringp org-use-tag-inheritance
)
3580 (string-match org-use-tag-inheritance tag
))
3581 ((listp org-use-tag-inheritance
)
3582 (member tag org-use-tag-inheritance
))
3583 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3585 (defcustom org-tags-match-list-sublevels t
3586 "Non-nil means list also sublevels of headlines matching a search.
3587 This variable applies to tags/property searches, and also to stuck
3588 projects because this search is based on a tags match as well.
3590 When set to the symbol `indented', sublevels are indented with
3593 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3594 the sublevels of a headline matching a tag search often also match
3595 the same search. Listing all of them can create very long lists.
3596 Setting this variable to nil causes subtrees of a match to be skipped.
3598 This variable is semi-obsolete and probably should always be true. It
3599 is better to limit inheritance to certain tags using the variables
3600 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3603 (const :tag
"No, don't list them" nil
)
3604 (const :tag
"Yes, do list them" t
)
3605 (const :tag
"List them, indented with leading dots" indented
)))
3607 (defcustom org-tags-sort-function nil
3608 "When set, tags are sorted using this function as a comparator."
3611 (const :tag
"No sorting" nil
)
3612 (const :tag
"Alphabetical" string
<)
3613 (const :tag
"Reverse alphabetical" string
>)
3614 (function :tag
"Custom function" nil
)))
3616 (defvar org-tags-history nil
3617 "History of minibuffer reads for tags.")
3618 (defvar org-last-tags-completion-table nil
3619 "The last used completion table for tags.")
3620 (defvar org-after-tags-change-hook nil
3621 "Hook that is run after the tags in a line have changed.")
3623 (defgroup org-properties nil
3624 "Options concerning properties in Org mode."
3625 :tag
"Org Properties"
3628 (defcustom org-property-format
"%-10s %s"
3629 "How property key/value pairs should be formatted by `indent-line'.
3630 When `indent-line' hits a property definition, it will format the line
3631 according to this format, mainly to make sure that the values are
3632 lined-up with respect to each other."
3633 :group
'org-properties
3636 (defcustom org-properties-postprocess-alist nil
3637 "Alist of properties and functions to adjust inserted values.
3638 Elements of this alist must be of the form
3640 ([string] [function])
3642 where [string] must be a property name and [function] must be a
3643 lambda expression: this lambda expression must take one argument,
3644 the value to adjust, and return the new value as a string.
3646 For example, this element will allow the property \"Remaining\"
3647 to be updated wrt the relation between the \"Effort\" property
3648 and the clock summary:
3650 ((\"Remaining\" (lambda(value)
3651 (let ((clocksum (org-clock-sum-current-item))
3652 (effort (org-duration-to-minutes
3653 (org-entry-get (point) \"Effort\"))))
3654 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3655 :group
'org-properties
3657 :type
'(alist :key-type
(string :tag
"Property")
3658 :value-type
(function :tag
"Function")))
3660 (defcustom org-use-property-inheritance nil
3661 "Non-nil means properties apply also for sublevels.
3663 This setting is chiefly used during property searches. Turning it on can
3664 cause significant overhead when doing a search, which is why it is not
3667 When nil, only the properties directly given in the current entry count.
3668 When t, every property is inherited. The value may also be a list of
3669 properties that should have inheritance, or a regular expression matching
3670 properties that should be inherited.
3672 However, note that some special properties use inheritance under special
3673 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3674 and the properties ending in \"_ALL\" when they are used as descriptor
3675 for valid values of a property.
3677 Note for programmers:
3678 When querying an entry with `org-entry-get', you can control if inheritance
3679 should be used. By default, `org-entry-get' looks only at the local
3680 properties. You can request inheritance by setting the inherit argument
3681 to t (to force inheritance) or to `selective' (to respect the setting
3683 :group
'org-properties
3685 (const :tag
"Not" nil
)
3686 (const :tag
"Always" t
)
3687 (repeat :tag
"Specific properties" (string :tag
"Property"))
3688 (regexp :tag
"Properties matched by regexp")))
3690 (defun org-property-inherit-p (property)
3691 "Return a non-nil value if PROPERTY should be inherited."
3693 ((eq org-use-property-inheritance t
) t
)
3694 ((not org-use-property-inheritance
) nil
)
3695 ((stringp org-use-property-inheritance
)
3696 (string-match org-use-property-inheritance property
))
3697 ((listp org-use-property-inheritance
)
3698 (member-ignore-case property org-use-property-inheritance
))
3699 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3701 (defcustom org-columns-default-format
"%25ITEM %TODO %3PRIORITY %TAGS"
3702 "The default column format, if no other format has been defined.
3703 This variable can be set on the per-file basis by inserting a line
3705 #+COLUMNS: %25ITEM ....."
3706 :group
'org-properties
3709 (defcustom org-columns-ellipses
".."
3710 "The ellipses to be used when a field in column view is truncated.
3711 When this is the empty string, as many characters as possible are shown,
3712 but then there will be no visual indication that the field has been truncated.
3713 When this is a string of length N, the last N characters of a truncated
3714 field are replaced by this string. If the column is narrower than the
3715 ellipses string, only part of the ellipses string will be shown."
3716 :group
'org-properties
3719 (defconst org-global-properties-fixed
3720 '(("VISIBILITY_ALL" .
"folded children content all")
3721 ("CLOCK_MODELINE_TOTAL_ALL" .
"current today repeat all auto"))
3722 "List of property/value pairs that can be inherited by any entry.
3724 These are fixed values, for the preset properties. The user variable
3725 that can be used to add to this list is `org-global-properties'.
3727 The entries in this list are cons cells where the car is a property
3728 name and cdr is a string with the value. If the value represents
3729 multiple items like an \"_ALL\" property, separate the items by
3732 (defcustom org-global-properties nil
3733 "List of property/value pairs that can be inherited by any entry.
3735 This list will be combined with the constant `org-global-properties-fixed'.
3737 The entries in this list are cons cells where the car is a property
3738 name and cdr is a string with the value.
3740 You can set buffer-local values for the same purpose in the variable
3741 `org-file-properties' this by adding lines like
3743 #+PROPERTY: NAME VALUE"
3744 :group
'org-properties
3746 (cons (string :tag
"Property")
3747 (string :tag
"Value"))))
3749 (defvar-local org-file-properties nil
3750 "List of property/value pairs that can be inherited by any entry.
3751 Valid for the current buffer.
3752 This variable is populated from #+PROPERTY lines.")
3754 (defgroup org-agenda nil
3755 "Options concerning agenda views in Org mode."
3759 (defvar-local org-category nil
3760 "Variable used by org files to set a category for agenda display.
3761 Such files should use a file variable to set it, for example
3763 # -*- mode: org; org-category: \"ELisp\"
3765 or contain a special line
3769 If the file does not specify a category, then file's base name
3771 (put 'org-category
'safe-local-variable
(lambda (x) (or (symbolp x
) (stringp x
))))
3773 (defcustom org-agenda-files nil
3774 "The files to be used for agenda display.
3776 If an entry is a directory, all files in that directory that are matched
3777 by `org-agenda-file-regexp' will be part of the file list.
3779 If the value of the variable is not a list but a single file name, then
3780 the list of agenda files is actually stored and maintained in that file,
3781 one agenda file per line. In this file paths can be given relative to
3782 `org-directory'. Tilde expansion and environment variable substitution
3785 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3786 and removed with `\\[org-remove-file]'."
3789 (repeat :tag
"List of files and directories" file
)
3790 (file :tag
"Store list in a file\n" :value
"~/.agenda_files")))
3792 (defcustom org-agenda-file-regexp
"\\`[^.].*\\.org\\'"
3793 "Regular expression to match files for `org-agenda-files'.
3794 If any element in the list in that variable contains a directory instead
3795 of a normal file, all files in that directory that are matched by this
3796 regular expression will be included."
3800 (defcustom org-agenda-text-search-extra-files nil
3801 "List of extra files to be searched by text search commands.
3802 These files will be searched in addition to the agenda files by the
3803 commands `org-search-view' (`\\[org-agenda] s') \
3804 and `org-occur-in-agenda-files'.
3805 Note that these files will only be searched for text search commands,
3806 not for the other agenda views like todo lists, tag searches or the weekly
3807 agenda. This variable is intended to list notes and possibly archive files
3808 that should also be searched by these two commands.
3809 In fact, if the first element in the list is the symbol `agenda-archives',
3810 then all archive files of all agenda files will be added to the search
3813 :type
'(set :greedy t
3814 (const :tag
"Agenda Archives" agenda-archives
)
3815 (repeat :inline t
(file))))
3817 (defvaralias 'org-agenda-multi-occur-extra-files
3818 'org-agenda-text-search-extra-files
)
3820 (defcustom org-agenda-skip-unavailable-files nil
3821 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3822 A nil value means to remove them, after a query, from the list."
3826 (defcustom org-calendar-to-agenda-key
[?c
]
3827 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3828 The command `org-calendar-goto-agenda' will be bound to this key. The
3829 default is the character `c' because then `c' can be used to switch back and
3830 forth between agenda and calendar."
3834 (defcustom org-calendar-insert-diary-entry-key
[?i
]
3835 "The key to be installed in `calendar-mode-map' for adding diary entries.
3836 This option is irrelevant until `org-agenda-diary-file' has been configured
3837 to point to an Org file. When that is the case, the command
3838 `org-agenda-diary-entry' will be bound to the key given here, by default
3839 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3840 if you want to continue doing this, you need to change this to a different
3845 (defcustom org-agenda-diary-file
'diary-file
3846 "File to which to add new entries with the `i' key in agenda and calendar.
3847 When this is the symbol `diary-file', the functionality in the Emacs
3848 calendar will be used to add entries to the `diary-file'. But when this
3849 points to a file, `org-agenda-diary-entry' will be used instead."
3852 (const :tag
"The standard Emacs diary file" diary-file
)
3853 (file :tag
"Special Org file diary entries")))
3855 (eval-after-load "calendar"
3857 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3858 'org-calendar-goto-agenda
)
3859 (add-hook 'calendar-mode-hook
3861 (unless (eq org-agenda-diary-file
'diary-file
)
3862 (define-key calendar-mode-map
3863 org-calendar-insert-diary-entry-key
3864 'org-agenda-diary-entry
))))))
3866 (defgroup org-latex nil
3867 "Options for embedding LaTeX code into Org mode."
3871 (defcustom org-format-latex-options
3872 '(:foreground default
:background default
:scale
1.0
3873 :html-foreground
"Black" :html-background
"Transparent"
3874 :html-scale
1.0 :matchers
("begin" "$1" "$" "$$" "\\(" "\\["))
3875 "Options for creating images from LaTeX fragments.
3876 This is a property list with the following properties:
3877 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3878 `default' means use the foreground of the default face.
3879 `auto' means use the foreground from the text face.
3880 :background the background color, or \"Transparent\".
3881 `default' means use the background of the default face.
3882 `auto' means use the background from the text face.
3883 :scale a scaling factor for the size of the images, to get more pixels
3884 :html-foreground, :html-background, :html-scale
3885 the same numbers for HTML export.
3886 :matchers a list indicating which matchers should be used to
3887 find LaTeX fragments. Valid members of this list are:
3888 \"begin\" find environments
3889 \"$1\" find single characters surrounded by $.$
3890 \"$\" find math expressions surrounded by $...$
3891 \"$$\" find math expressions surrounded by $$....$$
3892 \"\\(\" find math expressions surrounded by \\(...\\)
3893 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3897 (defcustom org-format-latex-signal-error t
3898 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3899 When nil, just push out a message."
3904 (defcustom org-latex-to-mathml-jar-file nil
3905 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3906 Use this to specify additional executable file say a jar file.
3908 When using MathToWeb as the converter, specify the full-path to
3909 your mathtoweb.jar file."
3913 (const :tag
"None" nil
)
3914 (file :tag
"JAR file" :must-match t
)))
3916 (defcustom org-latex-to-mathml-convert-command nil
3917 "Command to convert LaTeX fragments to MathML.
3918 Replace format-specifiers in the command as noted below and use
3919 `shell-command' to convert LaTeX to MathML.
3920 %j: Executable file in fully expanded form as specified by
3921 `org-latex-to-mathml-jar-file'.
3922 %I: Input LaTeX file in fully expanded form.
3923 %i: The latex fragment to be converted.
3924 %o: Output MathML file.
3926 This command is used by `org-create-math-formula'.
3928 When using MathToWeb as the converter, set this option to
3929 \"java -jar %j -unicode -force -df %o %I\".
3931 When using LaTeXML set this option to
3932 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3936 (const :tag
"None" nil
)
3937 (string :tag
"\nShell command")))
3939 (defcustom org-preview-latex-default-process
'dvipng
3940 "The default process to convert LaTeX fragments to image files.
3941 All available processes and theirs documents can be found in
3942 `org-preview-latex-process-alist', which see."
3945 :package-version
'(Org .
"9.0")
3948 (defcustom org-preview-latex-process-alist
3950 :programs
("latex" "dvipng")
3951 :description
"dvi > png"
3952 :message
"you need to install the programs: latex and dvipng."
3953 :image-input-type
"dvi"
3954 :image-output-type
"png"
3955 :image-size-adjust
(1.0 .
1.0)
3956 :latex-compiler
("latex -interaction nonstopmode -output-directory %o %f")
3957 :image-converter
("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3959 :programs
("latex" "dvisvgm")
3960 :description
"dvi > svg"
3961 :message
"you need to install the programs: latex and dvisvgm."
3963 :image-input-type
"dvi"
3964 :image-output-type
"svg"
3965 :image-size-adjust
(1.7 .
1.5)
3966 :latex-compiler
("latex -interaction nonstopmode -output-directory %o %f")
3967 :image-converter
("dvisvgm %f -n -b min -c %S -o %O"))
3969 :programs
("latex" "convert")
3970 :description
"pdf > png"
3971 :message
"you need to install the programs: latex and imagemagick."
3973 :image-input-type
"pdf"
3974 :image-output-type
"png"
3975 :image-size-adjust
(1.0 .
1.0)
3976 :latex-compiler
("pdflatex -interaction nonstopmode -output-directory %o %f")
3978 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3979 "Definitions of external processes for LaTeX previewing.
3980 Org mode can use some external commands to generate TeX snippet's images for
3981 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3982 `org-create-formula-image' how to call them.
3984 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3985 PROPERTIES accepts the following attributes:
3987 :programs list of strings, required programs.
3988 :description string, describe the process.
3989 :message string, message it when required programs cannot be found.
3990 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3991 :image-output-type string, output file type of image converter (e.g., \"png\").
3992 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3993 deal with background and foreground color of image.
3994 Otherwise, dvipng style background and foreground color
3995 format are generated. You may then refer to them in
3996 command options with \"%F\" and \"%B\".
3997 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3998 image size showed in buffer and the cdr element is for
3999 HTML file. This option is only useful for process
4000 developers, users should use variable
4001 `org-format-latex-options' instead.
4002 :post-clean list of strings, files matched are to be cleaned up once
4003 the image is generated. When nil, the files with \".dvi\",
4004 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4005 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4007 :latex-header list of strings, the LaTeX header of the snippet file.
4008 When nil, the fallback value is used instead, which is
4009 controlled by `org-format-latex-header',
4010 `org-latex-default-packages-alist' and
4011 `org-latex-packages-alist', which see.
4012 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4013 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4014 replaced with values defined below.
4015 :image-converter list of image converter commands strings. Each of them is
4016 given to the shell and supports any of the following
4017 place-holders defined below.
4019 Place-holders used by `:image-converter' and `:latex-compiler':
4022 %b base name of input file
4023 %o base directory of input file
4024 %O absolute output file name
4026 Place-holders only used by `:image-converter':
4028 %F foreground of image
4029 %B background of image
4030 %D dpi, which is used to adjust image size by some processing commands.
4031 %S the image size scale ratio, which is used to adjust image size by some
4032 processing commands."
4035 :package-version
'(Org .
"9.0")
4036 :type
'(alist :tag
"LaTeX to image backends"
4037 :value-type
(plist)))
4039 (defcustom org-preview-latex-image-directory
"ltximg/"
4040 "Path to store latex preview images.
4041 A relative path here creates many directories relative to the
4042 processed org files paths. An absolute path puts all preview
4043 images at the same place."
4046 :package-version
'(Org .
"9.0")
4049 (defun org-format-latex-mathml-available-p ()
4050 "Return t if `org-latex-to-mathml-convert-command' is usable."
4052 (when (and (boundp 'org-latex-to-mathml-convert-command
)
4053 org-latex-to-mathml-convert-command
)
4054 (let ((executable (car (split-string
4055 org-latex-to-mathml-convert-command
))))
4056 (when (executable-find executable
)
4058 "%j" org-latex-to-mathml-convert-command
)
4059 (file-readable-p org-latex-to-mathml-jar-file
)
4062 (defcustom org-format-latex-header
"\\documentclass{article}
4063 \\usepackage[usenames]{color}
4066 \\pagestyle{empty} % do not remove
4067 % The settings below are copied from fullpage.sty
4068 \\setlength{\\textwidth}{\\paperwidth}
4069 \\addtolength{\\textwidth}{-3cm}
4070 \\setlength{\\oddsidemargin}{1.5cm}
4071 \\addtolength{\\oddsidemargin}{-2.54cm}
4072 \\setlength{\\evensidemargin}{\\oddsidemargin}
4073 \\setlength{\\textheight}{\\paperheight}
4074 \\addtolength{\\textheight}{-\\headheight}
4075 \\addtolength{\\textheight}{-\\headsep}
4076 \\addtolength{\\textheight}{-\\footskip}
4077 \\addtolength{\\textheight}{-3cm}
4078 \\setlength{\\topmargin}{1.5cm}
4079 \\addtolength{\\topmargin}{-2.54cm}"
4080 "The document header used for processing LaTeX fragments.
4081 It is imperative that this header make sure that no page number
4082 appears on the page. The package defined in the variables
4083 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4084 will either replace the placeholder \"[PACKAGES]\" in this
4085 header, or they will be appended."
4089 (defun org-set-packages-alist (var val
)
4090 "Set the packages alist and make sure it has 3 elements per entry."
4091 (set var
(mapcar (lambda (x)
4092 (if (and (consp x
) (= (length x
) 2))
4093 (list (car x
) (nth 1 x
) t
)
4097 (defun org-get-packages-alist (var)
4098 "Get the packages alist and make sure it has 3 elements per entry."
4100 (if (and (consp x
) (= (length x
) 2))
4101 (list (car x
) (nth 1 x
) t
)
4103 (default-value var
)))
4105 (defcustom org-latex-default-packages-alist
4106 '(("AUTO" "inputenc" t
("pdflatex"))
4107 ("T1" "fontenc" t
("pdflatex"))
4110 ("" "longtable" nil
)
4113 ("normalem" "ulem" t
)
4118 ("" "hyperref" nil
))
4119 "Alist of default packages to be inserted in the header.
4121 Change this only if one of the packages here causes an
4122 incompatibility with another package you are using.
4124 The packages in this list are needed by one part or another of
4125 Org mode to function properly:
4127 - inputenc, fontenc: for basic font and character selection
4128 - graphicx: for including images
4129 - grffile: allow periods and spaces in graphics file names
4130 - longtable: For multipage tables
4131 - wrapfig: for figure placement
4132 - rotating: for sideways figures and tables
4133 - ulem: for underline and strike-through
4134 - amsmath: for subscript and superscript and math environments
4135 - textcomp, amssymb: for various symbols used
4136 for interpreting the entities in `org-entities'. You can skip
4137 some of these packages if you don't use any of their symbols.
4138 - capt-of: for captions outside of floats
4139 - hyperref: for cross references
4141 Therefore you should not modify this variable unless you know
4142 what you are doing. The one reason to change it anyway is that
4143 you might be loading some other package that conflicts with one
4144 of the default packages. Each element is either a cell or
4147 A cell is of the format
4149 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4151 If SNIPPET-FLAG is non-nil, the package also needs to be included
4152 when compiling LaTeX snippets into images for inclusion into
4153 non-LaTeX output. COMPILERS is a list of compilers that should
4154 include the package, see `org-latex-compiler'. If the document
4155 compiler is not in the list, and the list is non-nil, the package
4156 will not be inserted in the final document.
4158 A string will be inserted as-is in the header of the document."
4160 :group
'org-export-latex
4161 :set
'org-set-packages-alist
4162 :get
'org-get-packages-alist
4164 :package-version
'(Org .
"8.3")
4167 (list :tag
"options/package pair"
4168 (string :tag
"options")
4169 (string :tag
"package")
4170 (boolean :tag
"Snippet"))
4171 (string :tag
"A line of LaTeX"))))
4173 (defcustom org-latex-packages-alist nil
4174 "Alist of packages to be inserted in every LaTeX header.
4176 These will be inserted after `org-latex-default-packages-alist'.
4177 Each element is either a cell or a string.
4179 A cell is of the format:
4181 (\"options\" \"package\" SNIPPET-FLAG)
4183 SNIPPET-FLAG, when non-nil, indicates that this package is also
4184 needed when turning LaTeX snippets into images for inclusion into
4187 A string will be inserted as-is in the header of the document.
4189 Make sure that you only list packages here which:
4191 - you want in every file;
4192 - do not conflict with the setup in `org-format-latex-header';
4193 - do not conflict with the default packages in
4194 `org-latex-default-packages-alist'."
4196 :group
'org-export-latex
4197 :set
'org-set-packages-alist
4198 :get
'org-get-packages-alist
4201 (list :tag
"options/package pair"
4202 (string :tag
"options")
4203 (string :tag
"package")
4204 (boolean :tag
"Snippet"))
4205 (string :tag
"A line of LaTeX"))))
4207 (defgroup org-appearance nil
4208 "Settings for Org mode appearance."
4209 :tag
"Org Appearance"
4212 (defcustom org-level-color-stars-only nil
4213 "Non-nil means fontify only the stars in each headline.
4214 When nil, the entire headline is fontified.
4215 Changing it requires restart of `font-lock-mode' to become effective
4216 also in regions already fontified."
4217 :group
'org-appearance
4220 (defcustom org-hide-leading-stars nil
4221 "Non-nil means hide the first N-1 stars in a headline.
4222 This works by using the face `org-hide' for these stars. This
4223 face is white for a light background, and black for a dark
4224 background. You may have to customize the face `org-hide' to
4226 Changing it requires restart of `font-lock-mode' to become effective
4227 also in regions already fontified.
4228 You may also set this on a per-file basis by adding one of the following
4229 lines to the buffer:
4231 #+STARTUP: hidestars
4232 #+STARTUP: showstars"
4233 :group
'org-appearance
4236 (defcustom org-hidden-keywords nil
4237 "List of symbols corresponding to keywords to be hidden the org buffer.
4238 For example, a value \\='(title) for this list will make the document's title
4239 appear in the buffer without the initial #+TITLE: keyword."
4240 :group
'org-appearance
4242 :type
'(set (const :tag
"#+AUTHOR" author
)
4243 (const :tag
"#+DATE" date
)
4244 (const :tag
"#+EMAIL" email
)
4245 (const :tag
"#+TITLE" title
)))
4247 (defcustom org-custom-properties nil
4248 "List of properties (as strings) with a special meaning.
4249 The default use of these custom properties is to let the user
4250 hide them with `org-toggle-custom-properties-visibility'."
4251 :group
'org-properties
4252 :group
'org-appearance
4254 :type
'(repeat (string :tag
"Property Name")))
4256 (defcustom org-fontify-done-headline nil
4257 "Non-nil means change the face of a headline if it is marked DONE.
4258 Normally, only the TODO/DONE keyword indicates the state of a headline.
4259 When this is non-nil, the headline after the keyword is set to the
4260 `org-headline-done' as an additional indication."
4261 :group
'org-appearance
4264 (defcustom org-fontify-emphasized-text t
4265 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4266 Changing this variable requires a restart of Emacs to take effect."
4267 :group
'org-appearance
4270 (defcustom org-fontify-whole-heading-line nil
4271 "Non-nil means fontify the whole line for headings.
4272 This is useful when setting a background color for the
4274 :group
'org-appearance
4277 (defcustom org-highlight-latex-and-related nil
4278 "Non-nil means highlight LaTeX related syntax in the buffer.
4279 When non nil, the value should be a list containing any of the
4281 `latex' Highlight LaTeX snippets and environments.
4282 `script' Highlight subscript and superscript.
4283 `entities' Highlight entities."
4284 :group
'org-appearance
4286 :package-version
'(Org .
"8.0")
4288 (const :tag
"No highlighting" nil
)
4289 (set :greedy t
:tag
"Highlight"
4290 (const :tag
"LaTeX snippets and environments" latex
)
4291 (const :tag
"Subscript and superscript" script
)
4292 (const :tag
"Entities" entities
))))
4294 (defcustom org-hide-emphasis-markers nil
4295 "Non-nil mean font-lock should hide the emphasis marker characters."
4296 :group
'org-appearance
4299 (defcustom org-hide-macro-markers nil
4300 "Non-nil mean font-lock should hide the brackets marking macro calls."
4301 :group
'org-appearance
4304 (defcustom org-pretty-entities nil
4305 "Non-nil means show entities as UTF8 characters.
4306 When nil, the \\name form remains in the buffer."
4307 :group
'org-appearance
4311 (defcustom org-pretty-entities-include-sub-superscripts t
4312 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4313 :group
'org-appearance
4317 (defvar org-emph-re nil
4318 "Regular expression for matching emphasis.
4319 After a match, the match groups contain these elements:
4320 0 The match of the full regular expression, including the characters
4321 before and after the proper match
4322 1 The character before the proper match, or empty at beginning of line
4323 2 The proper match, including the leading and trailing markers
4324 3 The leading marker like * or /, indicating the type of highlighting
4325 4 The text between the emphasis markers, not including the markers
4326 5 The character after the match, empty at the end of a line")
4328 (defvar org-verbatim-re nil
4329 "Regular expression for matching verbatim text.")
4331 (defvar org-emphasis-regexp-components
) ; defined just below
4332 (defvar org-emphasis-alist
) ; defined just below
4333 (defun org-set-emph-re (var val
)
4334 "Set variable and compute the emphasis regular expression."
4336 (when (and (boundp 'org-emphasis-alist
)
4337 (boundp 'org-emphasis-regexp-components
)
4338 org-emphasis-alist org-emphasis-regexp-components
)
4340 ((`(,pre
,post
,border
,body
,nl
) org-emphasis-regexp-components
)
4341 (body (if (<= nl
0) body
4342 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl
)))
4344 (format (concat "\\([%s]\\|^\\)" ;before markers
4345 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4346 "\\([%s]\\|$\\)") ;after markers
4347 pre border border body border post
)))
4348 (setq org-emph-re
(format template
"*/_+"))
4349 (setq org-verbatim-re
(format template
"=~")))))
4351 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4352 ;; set this option proved cumbersome. See this message/thread:
4353 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4354 (defvar org-emphasis-regexp-components
4355 '("- \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4356 "Components used to build the regular expression for emphasis.
4357 This is a list with five entries. Terminology: In an emphasis string
4358 like \" *strong word* \", we call the initial space PREMATCH, the final
4359 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4360 and \"trong wor\" is the body. The different components in this variable
4361 specify what is allowed/forbidden in each part:
4363 pre Chars allowed as prematch. Beginning of line will be allowed too.
4364 post Chars allowed as postmatch. End of line will be allowed too.
4365 border The chars *forbidden* as border characters.
4366 body-regexp A regexp like \".\" to match a body character. Don't use
4367 non-shy groups here, and don't allow newline here.
4368 newline The maximum number of newlines allowed in an emphasis exp.
4370 You need to reload Org or to restart Emacs after customizing this.")
4372 (defcustom org-emphasis-alist
4376 ("=" org-verbatim verbatim
)
4377 ("~" org-code verbatim
)
4378 ("+" (:strike-through t
)))
4379 "Alist of characters and faces to emphasize text.
4380 Text starting and ending with a special character will be emphasized,
4381 for example *bold*, _underlined_ and /italic/. This variable sets the
4382 marker characters and the face to be used by font-lock for highlighting
4385 You need to reload Org or to restart Emacs after customizing this."
4386 :group
'org-appearance
4387 :set
'org-set-emph-re
4389 :package-version
'(Org .
"8.0")
4392 (string :tag
"Marker character")
4394 (face :tag
"Font-lock-face")
4395 (plist :tag
"Face property list"))
4396 (option (const verbatim
)))))
4398 (defvar org-protecting-blocks
'("src" "example" "export")
4399 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4400 This is needed for font-lock setup.")
4402 ;;; Functions and variables from their packages
4403 ;; Declared here to avoid compiler warnings
4404 (defvar mark-active
)
4407 (declare-function calc-eval
"calc" (str &optional separator
&rest args
))
4408 (declare-function calendar-forward-day
"cal-move" (arg))
4409 (declare-function calendar-goto-date
"cal-move" (date))
4410 (declare-function calendar-goto-today
"cal-move" ())
4411 (declare-function calendar-iso-from-absolute
"cal-iso" (date))
4412 (declare-function calendar-iso-to-absolute
"cal-iso" (date))
4413 (declare-function cdlatex-compute-tables
"ext:cdlatex" ())
4414 (declare-function cdlatex-tab
"ext:cdlatex" ())
4415 (declare-function dired-get-filename
4417 (&optional localp no-error-if-not-filep
))
4418 (declare-function iswitchb-read-buffer
4421 default require-match _predicate start matches-set
))
4422 (declare-function org-agenda-change-all-lines
4424 (newhead hdmarker
&optional fixface just-this
))
4425 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4428 (declare-function org-agenda-copy-local-variable
"org-agenda" (var))
4429 (declare-function org-agenda-format-item
4431 (extra txt
&optional level category tags dotime
4433 (declare-function org-agenda-maybe-redo
"org-agenda" ())
4434 (declare-function org-agenda-new-marker
"org-agenda" (&optional pos
))
4435 (declare-function org-agenda-save-markers-for-cut-and-paste
4438 (declare-function org-agenda-set-restriction-lock
"org-agenda" (&optional type
))
4439 (declare-function org-agenda-skip
"org-agenda" ())
4440 (declare-function org-attach-reveal
"org-attach" (&optional if-exists
))
4441 (declare-function org-gnus-follow-link
"org-gnus" (&optional group article
))
4442 (declare-function org-indent-mode
"org-indent" (&optional arg
))
4443 (declare-function org-inlinetask-goto-beginning
"org-inlinetask" ())
4444 (declare-function org-inlinetask-goto-end
"org-inlinetask" ())
4445 (declare-function org-inlinetask-in-task-p
"org-inlinetask" ())
4446 (declare-function org-inlinetask-remove-END-maybe
"org-inlinetask" ())
4447 (declare-function orgtbl-send-table
"org-table" (&optional maybe
))
4448 (declare-function parse-time-string
"parse-time" (string))
4449 (declare-function speedbar-line-directory
"speedbar" (&optional depth
))
4451 (defvar align-mode-rules-list
)
4452 (defvar calc-embedded-close-formula
)
4453 (defvar calc-embedded-open-formula
)
4454 (defvar calc-embedded-open-mode
)
4455 (defvar font-lock-unfontify-region-function
)
4456 (defvar iswitchb-temp-buflist
)
4457 (defvar org-agenda-tags-todo-honor-ignore-options
)
4458 (defvar remember-data-file
)
4459 (defvar texmathp-why
)
4462 (defun turn-on-orgtbl ()
4463 "Unconditionally turn on `orgtbl-mode'."
4464 (require 'org-table
)
4467 (defun org-at-table-p (&optional table-type
)
4468 "Non-nil if the cursor is inside an Org table.
4469 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4470 (and (org-match-line (if table-type
"[ \t]*[|+]" "[ \t]*|"))
4471 (or (not (derived-mode-p 'org-mode
))
4472 (let ((e (org-element-lineage (org-element-at-point) '(table) t
)))
4473 (and e
(or table-type
4474 (eq 'org
(org-element-property :type e
))))))))
4476 (defun org-at-table.el-p
()
4477 "Non-nil when point is at a table.el table."
4478 (and (org-match-line "[ \t]*[|+]")
4479 (let ((element (org-element-at-point)))
4480 (and (eq (org-element-type element
) 'table
)
4481 (eq (org-element-property :type element
) 'table.el
)))))
4483 (defun org-at-table-hline-p ()
4484 "Non-nil when point is inside a hline in a table.
4485 Assume point is already in a table."
4486 (org-match-line org-table-hline-regexp
))
4488 (defun org-table-map-tables (function &optional quietly
)
4489 "Apply FUNCTION to the start of all tables in the buffer."
4490 (org-with-wide-buffer
4491 (goto-char (point-min))
4492 (while (re-search-forward org-table-any-line-regexp nil t
)
4494 (message "Mapping tables: %d%%"
4495 (floor (* 100.0 (point)) (buffer-size))))
4496 (beginning-of-line 1)
4497 (when (and (looking-at org-table-line-regexp
)
4498 ;; Exclude tables in src/example/verbatim/clocktable blocks
4499 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4500 (save-excursion (funcall function
))
4501 (or (looking-at org-table-line-regexp
)
4503 (re-search-forward org-table-any-border-regexp nil
1)))
4504 (unless quietly
(message "Mapping tables: done")))
4506 (declare-function org-clock-save-markers-for-cut-and-paste
"org-clock" (beg end
))
4507 (declare-function org-clock-update-mode-line
"org-clock" ())
4508 (declare-function org-resolve-clocks
"org-clock"
4509 (&optional also-non-dangling-p prompt last-valid
))
4511 (defun org-at-TBLFM-p (&optional pos
)
4512 "Non-nil when point (or POS) is in #+TBLFM line."
4514 (goto-char (or pos
(point)))
4516 (and (let ((case-fold-search t
)) (looking-at org-TBLFM-regexp
))
4517 (eq (org-element-type (org-element-at-point)) 'table
))))
4519 (defvar org-clock-start-time
)
4520 (defvar org-clock-marker
(make-marker)
4521 "Marker recording the last clock-in.")
4522 (defvar org-clock-hd-marker
(make-marker)
4523 "Marker recording the last clock-in, but the headline position.")
4524 (defvar org-clock-heading
""
4525 "The heading of the current clock entry.")
4526 (defun org-clock-is-active ()
4527 "Return the buffer where the clock is currently running.
4528 Return nil if no clock is running."
4529 (marker-buffer org-clock-marker
))
4531 (defun org-check-running-clock ()
4532 "Check if the current buffer contains the running clock.
4533 If yes, offer to stop it and to save the buffer with the changes."
4534 (when (and (equal (marker-buffer org-clock-marker
) (current-buffer))
4535 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4538 (when (y-or-n-p "Save changed buffer?")
4541 (defun org-clocktable-try-shift (dir n
)
4542 "Check if this line starts a clock table, if yes, shift the time block."
4543 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4544 (org-clocktable-shift dir n
)))
4547 (defun org-clock-persistence-insinuate ()
4548 "Set up hooks for clock persistence."
4549 (require 'org-clock
)
4550 (add-hook 'org-mode-hook
'org-clock-load
)
4551 (add-hook 'kill-emacs-hook
'org-clock-save
))
4553 (defgroup org-archive nil
4554 "Options concerning archiving in Org mode."
4556 :group
'org-structure
)
4558 (defcustom org-archive-location
"%s_archive::"
4559 "The location where subtrees should be archived.
4561 The value of this variable is a string, consisting of two parts,
4562 separated by a double-colon. The first part is a filename and
4563 the second part is a headline.
4565 When the filename is omitted, archiving happens in the same file.
4566 %s in the filename will be replaced by the current file
4567 name (without the directory part). Archiving to a different file
4568 is useful to keep archived entries from contributing to the
4571 The archived entries will be filed as subtrees of the specified
4572 headline. When the headline is omitted, the subtrees are simply
4573 filed away at the end of the file, as top-level entries. Also in
4574 the heading you can use %s to represent the file name, this can be
4575 useful when using the same archive for a number of different files.
4577 Here are a few examples:
4579 If the current file is Projects.org, archive in file
4580 Projects.org_archive, as top-level trees. This is the default.
4582 \"::* Archived Tasks\"
4583 Archive in the current file, under the top-level headline
4584 \"* Archived Tasks\".
4586 \"~/org/archive.org::\"
4587 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4589 \"~/org/archive.org::* From %s\"
4590 Archive in file ~/org/archive.org (absolute path), under headlines
4591 \"From FILENAME\" where file name is the current file name.
4593 \"~/org/datetree.org::datetree/* Finished Tasks\"
4594 The \"datetree/\" string is special, signifying to archive
4595 items to the datetree. Items are placed in either the CLOSED
4596 date of the item, or the current date if there is no CLOSED date.
4597 The heading will be a subentry to the current date. There doesn't
4598 need to be a heading, but there always needs to be a slash after
4599 datetree. For example, to store archived items directly in the
4600 datetree, use \"~/org/datetree.org::datetree/\".
4602 \"basement::** Finished Tasks\"
4603 Archive in file ./basement (relative path), as level 3 trees
4604 below the level 2 heading \"** Finished Tasks\".
4606 You may set this option on a per-file basis by adding to the buffer a
4609 #+ARCHIVE: basement::** Finished Tasks
4611 You may also define it locally for a subtree by setting an ARCHIVE property
4612 in the entry. If such a property is found in an entry, or anywhere up
4613 the hierarchy, it will be used."
4617 (defcustom org-agenda-skip-archived-trees t
4618 "Non-nil means the agenda will skip any items located in archived trees.
4619 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4620 variable is no longer recommended, you should leave it at the value t.
4621 Instead, use the key `v' to cycle the archives-mode in the agenda."
4623 :group
'org-agenda-skip
4626 (defcustom org-columns-skip-archived-trees t
4627 "Non-nil means ignore archived trees when creating column view."
4629 :group
'org-properties
4632 (defcustom org-cycle-open-archived-trees nil
4633 "Non-nil means `org-cycle' will open archived trees.
4634 An archived tree is a tree marked with the tag ARCHIVE.
4635 When nil, archived trees will stay folded. You can still open them with
4636 normal outline commands like `show-all', but not with the cycling commands."
4641 (defcustom org-sparse-tree-open-archived-trees nil
4642 "Non-nil means sparse tree construction shows matches in archived trees.
4643 When nil, matches in these trees are highlighted, but the trees are kept in
4646 :group
'org-sparse-trees
4649 (defcustom org-sparse-tree-default-date-type nil
4650 "The default date type when building a sparse tree.
4651 When this is nil, a date is a scheduled or a deadline timestamp.
4652 Otherwise, these types are allowed:
4655 active: only active timestamps (<...>)
4656 inactive: only inactive timestamps ([...])
4657 scheduled: only scheduled timestamps
4658 deadline: only deadline timestamps"
4659 :type
'(choice (const :tag
"Scheduled or deadline" nil
)
4660 (const :tag
"All timestamps" all
)
4661 (const :tag
"Only active timestamps" active
)
4662 (const :tag
"Only inactive timestamps" inactive
)
4663 (const :tag
"Only scheduled timestamps" scheduled
)
4664 (const :tag
"Only deadline timestamps" deadline
)
4665 (const :tag
"Only closed timestamps" closed
))
4667 :package-version
'(Org .
"8.3")
4668 :group
'org-sparse-trees
)
4670 (defun org-cycle-hide-archived-subtrees (state)
4671 "Re-hide all archived subtrees after a visibility state change.
4672 STATE should be one of the symbols listed in the docstring of
4674 (when (and (not org-cycle-open-archived-trees
)
4675 (not (memq state
'(overview folded
))))
4677 (let* ((globalp (memq state
'(contents all
)))
4678 (beg (if globalp
(point-min) (point)))
4679 (end (if globalp
(point-max) (org-end-of-subtree t
))))
4680 (org-hide-archived-subtrees beg end
)
4682 (when (looking-at-p (concat ".*:" org-archive-tag
":"))
4683 (message "%s" (substitute-command-keys
4684 "Subtree is archived and stays closed. Use \
4685 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4687 (defun org-force-cycle-archived ()
4688 "Cycle subtree even if it is archived."
4690 (setq this-command
'org-cycle
)
4691 (let ((org-cycle-open-archived-trees t
))
4692 (call-interactively 'org-cycle
)))
4694 (defun org-hide-archived-subtrees (beg end
)
4695 "Re-hide all archived subtrees after a visibility state change."
4696 (org-with-wide-buffer
4697 (let ((case-fold-search nil
)
4698 (re (concat org-outline-regexp-bol
".*:" org-archive-tag
":")))
4700 ;; Include headline point is currently on.
4702 (while (and (< (point) end
) (re-search-forward re end t
))
4703 (when (member org-archive-tag
(org-get-tags))
4704 (org-flag-subtree t
)
4705 (org-end-of-subtree t
))))))
4707 (declare-function outline-end-of-heading
"outline" ())
4708 (declare-function outline-flag-region
"outline" (from to flag
))
4709 (defun org-flag-subtree (flag)
4711 (org-back-to-heading t
)
4712 (outline-end-of-heading)
4713 (outline-flag-region (point)
4714 (progn (org-end-of-subtree t
) (point))
4717 (defalias 'org-advertized-archive-subtree
'org-archive-subtree
)
4719 ;; Declare Column View Code
4721 (declare-function org-columns-get-format-and-top-level
"org-colview" ())
4722 (declare-function org-columns-compute
"org-colview" (property))
4726 (declare-function org-id-store-link
"org-id")
4727 (declare-function org-id-locations-load
"org-id")
4728 (declare-function org-id-locations-save
"org-id")
4729 (defvar org-id-track-globally
)
4731 ;;; Variables for pre-computed regular expressions, all buffer local
4733 (defvar-local org-todo-regexp nil
4734 "Matches any of the TODO state keywords.
4735 Since TODO keywords are case-sensitive, `case-fold-search' is
4736 expected to be bound to nil when matching against this regexp.")
4738 (defvar-local org-not-done-regexp nil
4739 "Matches any of the TODO state keywords except the last one.
4740 Since TODO keywords are case-sensitive, `case-fold-search' is
4741 expected to be bound to nil when matching against this regexp.")
4743 (defvar-local org-not-done-heading-regexp nil
4744 "Matches a TODO headline that is not done.
4745 Since TODO keywords are case-sensitive, `case-fold-search' is
4746 expected to be bound to nil when matching against this regexp.")
4748 (defvar-local org-todo-line-regexp nil
4749 "Matches a headline and puts TODO state into group 2 if present.
4750 Since TODO keywords are case-sensitive, `case-fold-search' is
4751 expected to be bound to nil when matching against this regexp.")
4753 (defvar-local org-complex-heading-regexp nil
4754 "Matches a headline and puts everything into groups:
4757 group 2: The TODO keyword, maybe
4758 group 3: Priority cookie
4759 group 4: True headline
4762 Since TODO keywords are case-sensitive, `case-fold-search' is
4763 expected to be bound to nil when matching against this regexp.")
4765 (defvar-local org-complex-heading-regexp-format nil
4766 "Printf format to make regexp to match an exact headline.
4767 This regexp will match the headline of any node which has the
4768 exact headline text that is put into the format, but may have any
4769 TODO state, priority and tags.")
4771 (defvar-local org-todo-line-tags-regexp nil
4772 "Matches a headline and puts TODO state into group 2 if present.
4773 Also put tags into group 4 if tags are present.")
4775 (defconst org-plain-time-of-day-regexp
4778 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4781 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4783 "Regular expression to match a plain time or time range.
4784 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4785 groups carry important information:
4787 1 the first time, range or not
4788 8 the second time, if it is a range.")
4790 (defconst org-plain-time-extension-regexp
4793 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4794 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4795 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4796 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4797 groups carry important information:
4800 9 minutes of duration")
4802 (defconst org-stamp-time-of-day-regexp
4804 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4805 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4807 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4808 "Regular expression to match a timestamp time or time range.
4809 After a match, the following groups carry important information:
4811 1 date plus weekday, for back referencing to make sure both times are on the same day
4812 2 the first time, range or not
4813 4 the second time, if it is a range.")
4815 (defconst org-startup-options
4816 '(("fold" org-startup-folded t
)
4817 ("overview" org-startup-folded t
)
4818 ("nofold" org-startup-folded nil
)
4819 ("showall" org-startup-folded nil
)
4820 ("showeverything" org-startup-folded showeverything
)
4821 ("content" org-startup-folded content
)
4822 ("indent" org-startup-indented t
)
4823 ("noindent" org-startup-indented nil
)
4824 ("hidestars" org-hide-leading-stars t
)
4825 ("showstars" org-hide-leading-stars nil
)
4826 ("odd" org-odd-levels-only t
)
4827 ("oddeven" org-odd-levels-only nil
)
4828 ("align" org-startup-align-all-tables t
)
4829 ("noalign" org-startup-align-all-tables nil
)
4830 ("inlineimages" org-startup-with-inline-images t
)
4831 ("noinlineimages" org-startup-with-inline-images nil
)
4832 ("latexpreview" org-startup-with-latex-preview t
)
4833 ("nolatexpreview" org-startup-with-latex-preview nil
)
4834 ("customtime" org-display-custom-times t
)
4835 ("logdone" org-log-done time
)
4836 ("lognotedone" org-log-done note
)
4837 ("nologdone" org-log-done nil
)
4838 ("lognoteclock-out" org-log-note-clock-out t
)
4839 ("nolognoteclock-out" org-log-note-clock-out nil
)
4840 ("logrepeat" org-log-repeat state
)
4841 ("lognoterepeat" org-log-repeat note
)
4842 ("logdrawer" org-log-into-drawer t
)
4843 ("nologdrawer" org-log-into-drawer nil
)
4844 ("logstatesreversed" org-log-states-order-reversed t
)
4845 ("nologstatesreversed" org-log-states-order-reversed nil
)
4846 ("nologrepeat" org-log-repeat nil
)
4847 ("logreschedule" org-log-reschedule time
)
4848 ("lognotereschedule" org-log-reschedule note
)
4849 ("nologreschedule" org-log-reschedule nil
)
4850 ("logredeadline" org-log-redeadline time
)
4851 ("lognoteredeadline" org-log-redeadline note
)
4852 ("nologredeadline" org-log-redeadline nil
)
4853 ("logrefile" org-log-refile time
)
4854 ("lognoterefile" org-log-refile note
)
4855 ("nologrefile" org-log-refile nil
)
4856 ("fninline" org-footnote-define-inline t
)
4857 ("nofninline" org-footnote-define-inline nil
)
4858 ("fnlocal" org-footnote-section nil
)
4859 ("fnauto" org-footnote-auto-label t
)
4860 ("fnprompt" org-footnote-auto-label nil
)
4861 ("fnconfirm" org-footnote-auto-label confirm
)
4862 ("fnplain" org-footnote-auto-label plain
)
4863 ("fnadjust" org-footnote-auto-adjust t
)
4864 ("nofnadjust" org-footnote-auto-adjust nil
)
4865 ("constcgs" constants-unit-system cgs
)
4866 ("constSI" constants-unit-system SI
)
4867 ("noptag" org-tag-persistent-alist nil
)
4868 ("hideblocks" org-hide-block-startup t
)
4869 ("nohideblocks" org-hide-block-startup nil
)
4870 ("beamer" org-startup-with-beamer-mode t
)
4871 ("entitiespretty" org-pretty-entities t
)
4872 ("entitiesplain" org-pretty-entities nil
))
4873 "Variable associated with STARTUP options for org-mode.
4874 Each element is a list of three items: the startup options (as written
4875 in the #+STARTUP line), the corresponding variable, and the value to set
4876 this variable to if the option is found. An optional forth element PUSH
4877 means to push this value onto the list in the variable.")
4879 (defcustom org-group-tags t
4880 "When non-nil (the default), use group tags.
4881 This can be turned on/off through `org-toggle-tags-groups'."
4886 (defvar org-inhibit-startup nil
) ; Dynamically-scoped param.
4888 (defun org-toggle-tags-groups ()
4889 "Toggle support for group tags.
4890 Support for group tags is controlled by the option
4891 `org-group-tags', which is non-nil by default."
4893 (setq org-group-tags
(not org-group-tags
))
4894 (cond ((and (derived-mode-p 'org-agenda-mode
)
4897 ((derived-mode-p 'org-mode
)
4898 (let ((org-inhibit-startup t
)) (org-mode))))
4899 (message "Groups tags support has been turned %s"
4900 (if org-group-tags
"on" "off")))
4902 (defun org-set-regexps-and-options (&optional tags-only
)
4903 "Precompute regular expressions used in the current buffer.
4904 When optional argument TAGS-ONLY is non-nil, only compute tags
4905 related expressions."
4906 (when (derived-mode-p 'org-mode
)
4907 (let ((alist (org--setup-collect-keywords
4908 (org-make-options-regexp
4909 (append '("FILETAGS" "TAGS" "SETUPFILE")
4910 (and (not tags-only
)
4911 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4912 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4913 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4914 ;; Startup options. Get this early since it does change
4915 ;; behavior for other options (e.g., tags).
4916 (let ((startup (cdr (assq 'startup alist
))))
4917 (dolist (option startup
)
4918 (let ((entry (assoc-string option org-startup-options t
)))
4920 (let ((var (nth 1 entry
))
4921 (val (nth 2 entry
)))
4922 (if (not (nth 3 entry
)) (set (make-local-variable var
) val
)
4923 (unless (listp (symbol-value var
))
4924 (set (make-local-variable var
) nil
))
4925 (add-to-list var val
)))))))
4926 (setq-local org-file-tags
4927 (mapcar #'org-add-prop-inherited
4928 (cdr (assq 'filetags alist
))))
4929 (setq org-current-tag-alist
4930 (append org-tag-persistent-alist
4931 (let ((tags (cdr (assq 'tags alist
))))
4932 (if tags
(org-tag-string-to-alist tags
)
4934 (setq org-tag-groups-alist
4935 (org-tag-alist-to-groups org-current-tag-alist
))
4938 (setq-local org-file-properties
(cdr (assq 'property alist
)))
4939 ;; Archive location.
4940 (let ((archive (cdr (assq 'archive alist
))))
4941 (when archive
(setq-local org-archive-location archive
)))
4943 (let ((cat (org-string-nw-p (cdr (assq 'category alist
)))))
4945 (setq-local org-category
(intern cat
))
4946 (setq-local org-file-properties
4947 (org--update-property-plist
4948 "CATEGORY" cat org-file-properties
))))
4950 (let ((column (cdr (assq 'columns alist
))))
4951 (when column
(setq-local org-columns-default-format column
)))
4953 (setq org-table-formula-constants-local
(cdr (assq 'constants alist
)))
4954 ;; Link abbreviations.
4955 (let ((links (cdr (assq 'link alist
))))
4956 (when links
(setq org-link-abbrev-alist-local
(nreverse links
))))
4958 (let ((priorities (cdr (assq 'priorities alist
))))
4960 (setq-local org-highest-priority
(nth 0 priorities
))
4961 (setq-local org-lowest-priority
(nth 1 priorities
))
4962 (setq-local org-default-priority
(nth 2 priorities
))))
4964 (let ((scripts (assq 'scripts alist
)))
4966 (setq-local org-use-sub-superscripts
(cdr scripts
))))
4968 (setq-local org-todo-kwd-alist nil
)
4969 (setq-local org-todo-key-alist nil
)
4970 (setq-local org-todo-key-trigger nil
)
4971 (setq-local org-todo-keywords-1 nil
)
4972 (setq-local org-done-keywords nil
)
4973 (setq-local org-todo-heads nil
)
4974 (setq-local org-todo-sets nil
)
4975 (setq-local org-todo-log-states nil
)
4976 (let ((todo-sequences
4977 (or (nreverse (cdr (assq 'todo alist
)))
4978 (let ((d (default-value 'org-todo-keywords
)))
4979 (if (not (stringp (car d
))) d
4980 ;; XXX: Backward compatibility code.
4981 (list (cons org-todo-interpretation d
)))))))
4982 (dolist (sequence todo-sequences
)
4983 (let* ((sequence (or (run-hook-with-args-until-success
4984 'org-todo-setup-filter-hook sequence
)
4986 (sequence-type (car sequence
))
4987 (keywords (cdr sequence
))
4988 (sep (member "|" keywords
))
4990 (dolist (k (remove "|" keywords
))
4991 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4993 (error "Invalid TODO keyword %s" k
))
4994 (let ((name (match-string 1 k
))
4995 (key (match-string 2 k
))
4996 (log (org-extract-log-state-settings k
)))
4998 (push (cons name
(and key
(string-to-char key
))) alist
)
4999 (when log
(push log org-todo-log-states
))))
5000 (let* ((names (nreverse names
))
5001 (done (if sep
(org-remove-keyword-keys (cdr sep
))
5004 (tail (list sequence-type head
(car done
) (org-last done
))))
5005 (add-to-list 'org-todo-heads head
'append
)
5006 (push names org-todo-sets
)
5007 (setq org-done-keywords
(append org-done-keywords done nil
))
5008 (setq org-todo-keywords-1
(append org-todo-keywords-1 names nil
))
5009 (setq org-todo-key-alist
5010 (append org-todo-key-alist
5012 (append '((:startgroup
))
5015 (dolist (k names
) (push (cons k tail
) org-todo-kwd-alist
))))))
5016 (setq org-todo-sets
(nreverse org-todo-sets
)
5017 org-todo-kwd-alist
(nreverse org-todo-kwd-alist
)
5018 org-todo-key-trigger
(delq nil
(mapcar #'cdr org-todo-key-alist
))
5019 org-todo-key-alist
(org-assign-fast-keys org-todo-key-alist
))
5020 ;; Compute the regular expressions and other local variables.
5021 ;; Using `org-outline-regexp-bol' would complicate them much,
5022 ;; because of the fixed white space at the end of that string.
5023 (unless org-done-keywords
5024 (setq org-done-keywords
5025 (and org-todo-keywords-1
(last org-todo-keywords-1
))))
5026 (setq org-not-done-keywords
5027 (org-delete-all org-done-keywords
5028 (copy-sequence org-todo-keywords-1
))
5029 org-todo-regexp
(regexp-opt org-todo-keywords-1 t
)
5030 org-not-done-regexp
(regexp-opt org-not-done-keywords t
)
5031 org-not-done-heading-regexp
5032 (format org-heading-keyword-regexp-format org-not-done-regexp
)
5033 org-todo-line-regexp
5034 (format org-heading-keyword-maybe-regexp-format org-todo-regexp
)
5035 org-complex-heading-regexp
5036 (concat "^\\(\\*+\\)"
5037 "\\(?: +" org-todo-regexp
"\\)?"
5038 "\\(?: +\\(\\[#.\\]\\)\\)?"
5039 "\\(?: +\\(.*?\\)\\)??"
5040 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5042 org-complex-heading-regexp-format
5043 (concat "^\\(\\*+\\)"
5044 "\\(?: +" org-todo-regexp
"\\)?"
5045 "\\(?: +\\(\\[#.\\]\\)\\)?"
5047 ;; Stats cookies can be stuck to body.
5048 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5050 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5052 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5054 org-todo-line-tags-regexp
5055 (concat "^\\(\\*+\\)"
5056 "\\(?: +" org-todo-regexp
"\\)?"
5057 "\\(?: +\\(.*?\\)\\)??"
5058 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5060 (org-compute-latex-and-related-regexp)))))
5062 (defun org--setup-collect-keywords (regexp &optional files alist
)
5063 "Return setup keywords values as an alist.
5065 REGEXP matches a subset of setup keywords. FILES is a list of
5066 file names already visited. It is used to avoid circular setup
5067 files. ALIST, when non-nil, is the alist computed so far.
5069 Return value contains the following keys: `archive', `category',
5070 `columns', `constants', `filetags', `link', `priorities',
5071 `property', `scripts', `startup', `tags' and `todo'."
5072 (org-with-wide-buffer
5073 (goto-char (point-min))
5074 (let ((case-fold-search t
))
5075 (while (re-search-forward regexp nil t
)
5076 (let ((element (org-element-at-point)))
5077 (when (eq (org-element-type element
) 'keyword
)
5078 (let ((key (org-element-property :key element
))
5079 (value (org-element-property :value element
)))
5081 ((equal key
"ARCHIVE")
5082 (when (org-string-nw-p value
)
5083 (push (cons 'archive value
) alist
)))
5084 ((equal key
"CATEGORY") (push (cons 'category value
) alist
))
5085 ((equal key
"COLUMNS") (push (cons 'columns value
) alist
))
5086 ((equal key
"CONSTANTS")
5087 (let* ((constants (assq 'constants alist
))
5088 (store (cdr constants
)))
5089 (dolist (pair (split-string value
))
5090 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5092 (let* ((name (match-string 1 pair
))
5093 (value (match-string 2 pair
))
5094 (old (assoc name store
)))
5095 (if old
(setcdr old value
)
5096 (push (cons name value
) store
)))))
5097 (if constants
(setcdr constants store
)
5098 (push (cons 'constants store
) alist
))))
5099 ((equal key
"FILETAGS")
5100 (when (org-string-nw-p value
)
5101 (let ((old (assq 'filetags alist
))
5103 (mapcar (lambda (x) (org-split-string x
":"))
5104 (split-string value
)))))
5105 (if old
(setcdr old
(append new
(cdr old
)))
5106 (push (cons 'filetags new
) alist
)))))
5108 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value
)
5109 (let ((links (assq 'link alist
))
5110 (pair (cons (match-string-no-properties 1 value
)
5111 (match-string-no-properties 2 value
))))
5112 (if links
(push pair
(cdr links
))
5113 (push (list 'link pair
) alist
)))))
5114 ((equal key
"OPTIONS")
5115 (when (and (org-string-nw-p value
)
5116 (string-match "\\^:\\(t\\|nil\\|{}\\)" value
))
5117 (push (cons 'scripts
(read (match-string 1 value
))) alist
)))
5118 ((equal key
"PRIORITIES")
5119 (push (cons 'priorities
5120 (let ((prio (split-string value
)))
5121 (if (< (length prio
) 3) '(?A ?C ?B
)
5122 (mapcar #'string-to-char prio
))))
5124 ((equal key
"PROPERTY")
5125 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value
)
5126 (let* ((property (assq 'property alist
))
5127 (value (org--update-property-plist
5128 (match-string-no-properties 1 value
)
5129 (match-string-no-properties 2 value
)
5131 (if property
(setcdr property value
)
5132 (push (cons 'property value
) alist
)))))
5133 ((equal key
"STARTUP")
5134 (let ((startup (assq 'startup alist
)))
5137 (append (cdr startup
) (split-string value
)))
5138 (push (cons 'startup
(split-string value
)) alist
))))
5140 (let ((tag-cell (assq 'tags alist
)))
5142 (setcdr tag-cell
(concat (cdr tag-cell
) "\n" value
))
5143 (push (cons 'tags value
) alist
))))
5144 ((member key
'("TODO" "SEQ_TODO" "TYP_TODO"))
5145 (let ((todo (assq 'todo alist
))
5146 (value (cons (if (equal key
"TYP_TODO") 'type
'sequence
)
5147 (split-string value
))))
5148 (if todo
(push value
(cdr todo
))
5149 (push (list 'todo value
) alist
))))
5150 ((equal key
"SETUPFILE")
5151 (unless buffer-read-only
; Do not check in Gnus messages.
5152 (let ((f (and (org-string-nw-p value
)
5154 (org-unbracket-string "\"" "\"" value
)))))
5155 (when (and f
(file-readable-p f
) (not (member f files
)))
5157 (setq default-directory
(file-name-directory f
))
5158 (insert-file-contents f
)
5160 ;; Fake Org mode to benefit from cache
5161 ;; without recurring needlessly.
5162 (let ((major-mode 'org-mode
))
5163 (org--setup-collect-keywords
5164 regexp
(cons f files
) alist
)))))))))))))))
5167 (defun org-tag-string-to-alist (s)
5168 "Return tag alist associated to string S.
5169 S is a value for TAGS keyword or produced with
5170 `org-tag-alist-to-string'. Return value is an alist suitable for
5171 `org-tag-alist' or `org-tag-persistent-alist'."
5172 (let ((lines (mapcar #'split-string
(split-string s
"\n" t
)))
5173 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5174 "\\|{.+?}\\)" ; regular expression
5175 "\\(?:(\\(.\\))\\)?\\'"))
5177 (dolist (tokens lines
(cdr (nreverse alist
)))
5178 (push '(:newline
) alist
)
5180 (let ((token (pop tokens
)))
5183 (push '(:startgroup
) alist
)
5184 (when (equal (nth 1 tokens
) ":") (setq group-flag t
)))
5186 (push '(:endgroup
) alist
)
5187 (setq group-flag nil
))
5189 (push '(:startgrouptag
) alist
)
5190 (when (equal (nth 1 tokens
) ":") (setq group-flag t
)))
5192 (push '(:endgrouptag
) alist
)
5193 (setq group-flag nil
))
5195 (push '(:grouptags
) alist
))
5196 ((guard (string-match tag-re token
))
5197 (let ((tag (match-string 1 token
))
5198 (key (and (match-beginning 2)
5199 (string-to-char (match-string 2 token
)))))
5200 ;; Push all tags in groups, no matter if they already
5201 ;; appear somewhere else in the list.
5202 (when (or group-flag
(not (assoc tag alist
)))
5203 (push (cons tag key
) alist
))))))))))
5205 (defun org-tag-alist-to-string (alist &optional skip-key
)
5206 "Return tag string associated to ALIST.
5208 ALIST is an alist, as defined in `org-tag-alist' or
5209 `org-tag-persistent-alist', or produced with
5210 `org-tag-string-to-alist'.
5212 Return value is a string suitable as a value for \"TAGS\"
5215 When optional argument SKIP-KEY is non-nil, skip selection keys
5217 (mapconcat (lambda (token)
5219 (`(:startgroup
) "{")
5221 (`(:startgrouptag
) "[")
5222 (`(:endgrouptag
) "]")
5226 (guard (not skip-key
))
5227 `(,(and tag
(pred stringp
)) .
,(and key
(pred characterp
))))
5228 (format "%s(%c)" tag key
))
5229 (`(,(and tag
(pred stringp
)) .
,_
) tag
)
5230 (_ (user-error "Invalid tag token: %S" token
))))
5234 (defun org-tag-alist-to-groups (alist)
5235 "Return group alist from tag ALIST.
5236 ALIST is an alist, as defined in `org-tag-alist' or
5237 `org-tag-persistent-alist', or produced with
5238 `org-tag-string-to-alist'. Return value is an alist following
5239 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5240 a string, summarizing TAGS, as a list of strings."
5241 (let (groups group-status current-group
)
5242 (dolist (token alist
(nreverse groups
))
5244 (`(,(or :startgroup
:startgrouptag
)) (setq group-status t
))
5245 (`(,(or :endgroup
:endgrouptag
))
5246 (when (eq group-status
'append
)
5247 (push (nreverse current-group
) groups
))
5248 (setq group-status nil
))
5249 (`(:grouptags
) (setq group-status
'append
))
5250 ((and `(,tag .
,_
) (guard group-status
))
5251 (if (eq group-status
'append
) (push tag current-group
)
5252 (setq current-group
(list tag
))))
5255 (defvar org--file-cache
(make-hash-table :test
#'equal
)
5256 "Hash table to store contents of files referenced via a URL.
5257 This is the cache of file URLs read using `org-file-contents'.")
5259 (defun org-reset-file-cache ()
5260 "Reset the cache of files downloaded by `org-file-contents'."
5261 (clrhash org--file-cache
))
5263 (defun org-file-url-p (file)
5264 "Non-nil if FILE is a URL."
5266 (string-match-p ffap-url-regexp file
))
5268 (defun org-file-contents (file &optional noerror nocache
)
5269 "Return the contents of FILE, as a string.
5271 FILE can be a file name or URL.
5273 If FILE is a URL, download the contents. If the URL contents are
5274 already cached in the `org--file-cache' hash table, the download step
5277 If NOERROR is non-nil, ignore the error when unable to read the FILE
5280 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5281 is available. This option applies only if FILE is a URL."
5282 (let* ((is-url (org-file-url-p file
))
5285 (gethash file org--file-cache
))))
5289 (with-current-buffer (url-retrieve-synchronously file
)
5290 (goto-char (point-min))
5291 ;; Move point to after the url-retrieve header.
5292 (search-forward "\n\n" nil
:move
)
5293 ;; Search for the success code only in the url-retrieve header.
5295 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil
:noerror
))
5296 ;; Update the cache `org--file-cache' and return contents.
5298 (buffer-substring-no-properties (point) (point-max))
5300 (funcall (if noerror
#'message
#'user-error
)
5301 "Unable to fetch file from %S"
5307 (insert-file-contents file
)
5310 (funcall (if noerror
#'message
#'user-error
)
5311 "Unable to read file %S"
5314 (defun org-extract-log-state-settings (x)
5315 "Extract the log state setting from a TODO keyword string.
5316 This will extract info from a string like \"WAIT(w@/!)\"."
5317 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x
)
5318 (let ((kw (match-string 1 x
))
5319 (log1 (and (match-end 3) (match-string 3 x
)))
5320 (log2 (and (match-end 4) (match-string 4 x
))))
5323 (and log1
(if (equal log1
"!") 'time
'note
))
5324 (and log2
(if (equal log2
"!") 'time
'note
)))))))
5326 (defun org-remove-keyword-keys (list)
5327 "Remove a pair of parenthesis at the end of each string in LIST."
5329 (if (string-match "(.*)$" x
)
5330 (substring x
0 (match-beginning 0))
5334 (defun org-assign-fast-keys (alist)
5335 "Assign fast keys to a keyword-key alist.
5336 Respect keys that are already there."
5337 (let (new e
(alt ?
0))
5338 (while (setq e
(pop alist
))
5339 (if (or (memq (car e
) '(:newline
:grouptags
:endgroup
:startgroup
))
5340 (cdr e
)) ;; Key already assigned.
5342 (let ((clist (string-to-list (downcase (car e
))))
5343 (used (append new alist
)))
5344 (when (= (car clist
) ?
@)
5346 (while (and clist
(rassoc (car clist
) used
))
5349 (while (rassoc alt used
)
5351 (push (cons (car e
) (or (car clist
) alt
)) new
))))
5354 ;;; Some variables used in various places
5356 (defvar org-window-configuration nil
5357 "Used in various places to store a window configuration.")
5358 (defvar org-selected-window nil
5359 "Used in various places to store a window configuration.")
5360 (defvar org-finish-function nil
5361 "Function to be called when `C-c C-c' is used.
5362 This is for getting out of special buffers like capture.")
5363 (defvar org-last-state
)
5365 ;; Defined somewhere in this file, but used before definition.
5366 (defvar org-entities
) ;; defined in org-entities.el
5367 (defvar org-struct-menu
)
5368 (defvar org-org-menu
)
5369 (defvar org-tbl-menu
)
5371 ;;;; Define the Org mode
5373 ;; We use a before-change function to check if a table might need
5375 (defvar org-table-may-need-update t
5376 "Indicates that a table might need an update.
5377 This variable is set by `org-before-change-function'.
5378 `org-table-align' sets it back to nil.")
5379 (defun org-before-change-function (_beg _end
)
5380 "Every change indicates that a table might need an update."
5381 (setq org-table-may-need-update t
))
5382 (defvar org-mode-map
)
5383 (defvar org-inhibit-startup-visibility-stuff nil
) ; Dynamically-scoped param.
5384 (defvar org-agenda-keep-modes nil
) ; Dynamically-scoped param.
5385 (defvar org-inhibit-logging nil
) ; Dynamically-scoped param.
5386 (defvar org-inhibit-blocking nil
) ; Dynamically-scoped param.
5387 (defvar org-table-buffer-is-an nil
)
5389 (defvar bidi-paragraph-direction
)
5390 (defvar buffer-face-mode-face
)
5394 ;; Other stuff we need.
5395 (require 'time-date
)
5396 (unless (fboundp 'time-subtract
) (defalias 'time-subtract
'subtract-time
))
5398 (autoload 'easy-menu-add
"easymenu")
5401 ;; (require 'org-macs) moved higher up in the file before it is first used
5402 (require 'org-entities
)
5403 ;; (require 'org-compat) moved higher up in the file before it is first used
5404 (require 'org-faces
)
5406 (require 'org-pcomplete
)
5408 (require 'org-footnote
)
5409 (require 'org-macro
)
5415 (define-derived-mode org-mode outline-mode
"Org"
5416 "Outline-based notes management and organizer, alias
5417 \"Carsten's outline-mode for keeping track of everything.\"
5419 Org mode develops organizational tasks around a NOTES file which
5420 contains information about projects as plain text. Org mode is
5421 implemented on top of Outline mode, which is ideal to keep the content
5422 of large files well structured. It supports ToDo items, deadlines and
5423 time stamps, which magically appear in the diary listing of the Emacs
5424 calendar. Tables are easily created with a built-in table editor.
5425 Plain text URL-like links connect to websites, emails (VM), Usenet
5426 messages (Gnus), BBDB entries, and any files related to the project.
5427 For printing and sharing of notes, an Org file (or a part of it)
5428 can be exported as a structured ASCII or HTML file.
5430 The following commands are available:
5434 ;; Get rid of Outline menus, they are not needed
5435 ;; Need to do this here because define-derived-mode sets up
5436 ;; the keymap so late. Still, it is a waste to call this each time
5437 ;; we switch another buffer into Org mode.
5438 (define-key org-mode-map
[menu-bar headings
] 'undefined
)
5439 (define-key org-mode-map
[menu-bar hide
] 'undefined
)
5440 (define-key org-mode-map
[menu-bar show
] 'undefined
)
5442 (org-load-modules-maybe)
5443 (org-install-agenda-files-menu)
5444 (when org-descriptive-links
(add-to-invisibility-spec '(org-link)))
5445 (add-to-invisibility-spec '(org-cwidth))
5446 (add-to-invisibility-spec '(org-hide-block . t
))
5447 (setq-local outline-regexp org-outline-regexp
)
5448 (setq-local outline-level
'org-outline-level
)
5449 (setq bidi-paragraph-direction
'left-to-right
)
5450 (when (and (stringp org-ellipsis
) (not (equal "" org-ellipsis
)))
5451 (unless org-display-table
5452 (setq org-display-table
(make-display-table)))
5453 (set-display-table-slot
5455 (vconcat (mapcar (lambda (c) (make-glyph-code c
'org-ellipsis
))
5457 (setq buffer-display-table org-display-table
))
5458 (org-set-regexps-and-options)
5459 (org-set-font-lock-defaults)
5460 (when (and org-tag-faces
(not org-tags-special-faces-re
))
5461 ;; tag faces set outside customize.... force initialization.
5462 (org-set-tag-faces 'org-tag-faces org-tag-faces
))
5464 (setq-local calc-embedded-open-mode
"# ")
5465 ;; Modify a few syntax entries
5466 (modify-syntax-entry ?
@ "w")
5467 (modify-syntax-entry ?
\" "\"")
5468 (modify-syntax-entry ?
\\ "_")
5469 (modify-syntax-entry ?~
"_")
5470 (setq-local font-lock-unfontify-region-function
'org-unfontify-region
)
5471 ;; Activate before-change-function
5472 (setq-local org-table-may-need-update t
)
5473 (add-hook 'before-change-functions
'org-before-change-function nil
'local
)
5474 ;; Check for running clock before killing a buffer
5475 (add-hook 'kill-buffer-hook
'org-check-running-clock nil
'local
)
5476 ;; Initialize macros templates.
5477 (org-macro-initialize-templates)
5478 ;; Initialize radio targets.
5479 (org-update-radio-target-regexp)
5481 (setq-local indent-line-function
'org-indent-line
)
5482 (setq-local indent-region-function
'org-indent-region
)
5483 ;; Filling and auto-filling.
5486 (org-setup-comments-handling)
5487 ;; Initialize cache.
5488 (org-element-cache-reset)
5489 ;; Beginning/end of defun
5490 (setq-local beginning-of-defun-function
'org-backward-element
)
5491 (setq-local end-of-defun-function
5493 (if (not (org-at-heading-p))
5494 (org-forward-element)
5495 (org-forward-element)
5496 (forward-char -
1))))
5497 ;; Next error for sparse trees
5498 (setq-local next-error-function
'org-occur-next-match
)
5499 ;; Make sure dependence stuff works reliably, even for users who set it
5501 (if org-enforce-todo-dependencies
5502 (add-hook 'org-blocker-hook
5503 'org-block-todo-from-children-or-siblings-or-parent
)
5504 (remove-hook 'org-blocker-hook
5505 'org-block-todo-from-children-or-siblings-or-parent
))
5506 (if org-enforce-todo-checkbox-dependencies
5507 (add-hook 'org-blocker-hook
5508 'org-block-todo-from-checkboxes
)
5509 (remove-hook 'org-blocker-hook
5510 'org-block-todo-from-checkboxes
))
5512 ;; Align options lines
5514 align-mode-rules-list
5515 '((org-in-buffer-settings
5516 (regexp .
"^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5517 (modes .
'(org-mode)))))
5520 (setq-local imenu-create-index-function
'org-imenu-get-tree
)
5522 ;; Make isearch reveal context
5523 (setq-local outline-isearch-open-invisible-function
5524 (lambda (&rest _
) (org-show-context 'isearch
)))
5526 ;; Setup the pcomplete hooks
5527 (setq-local pcomplete-command-completion-function
'org-pcomplete-initial
)
5528 (setq-local pcomplete-command-name-function
'org-command-at-point
)
5529 (setq-local pcomplete-default-completion-function
'ignore
)
5530 (setq-local pcomplete-parse-arguments-function
'org-parse-arguments
)
5531 (setq-local pcomplete-termination-string
"")
5532 (setq-local buffer-face-mode-face
'org-default
)
5534 ;; If empty file that did not turn on Org mode automatically, make
5536 (when (and org-insert-mode-line-in-empty-file
5537 (called-interactively-p 'any
)
5538 (= (point-min) (point-max)))
5539 (insert "# -*- mode: org -*-\n\n"))
5540 (unless org-inhibit-startup
5542 (when org-startup-with-beamer-mode
(org-beamer-mode))
5543 (when org-startup-align-all-tables
5544 (org-table-map-tables #'org-table-align t
))
5545 (when org-startup-with-inline-images
(org-display-inline-images))
5546 (when org-startup-with-latex-preview
(org-toggle-latex-fragment '(16)))
5547 (unless org-inhibit-startup-visibility-stuff
(org-set-startup-visibility))
5548 (when org-startup-truncated
(setq truncate-lines t
))
5549 (when org-startup-indented
(require 'org-indent
) (org-indent-mode 1))
5550 (org-refresh-effort-properties)))
5551 ;; Try to set `org-hide' face correctly.
5552 (let ((foreground (org-find-invisible-foreground)))
5554 (set-face-foreground 'org-hide foreground
))))
5556 ;; Update `customize-package-emacs-version-alist'
5557 (add-to-list 'customize-package-emacs-version-alist
5558 '(Org ("8.0" .
"24.4")
5566 (defvar org-mode-transpose-word-syntax-table
5567 (let ((st (make-syntax-table text-mode-syntax-table
)))
5568 (dolist (c org-emphasis-alist st
)
5569 (modify-syntax-entry (string-to-char (car c
)) "w p" st
))))
5571 (when (fboundp 'abbrev-table-put
)
5572 (abbrev-table-put org-mode-abbrev-table
5573 :parents
(list text-mode-abbrev-table
)))
5575 (defun org-find-invisible-foreground ()
5576 (let ((candidates (remove
5579 (list (face-background 'default
)
5580 (face-background 'org-default
))
5583 (when (boundp alist
)
5584 (cdr (assq 'background-color
(symbol-value alist
)))))
5585 '(default-frame-alist initial-frame-alist window-system-default-frame-alist
))
5586 (list (face-foreground 'org-hide
))))))
5587 (car (remove nil candidates
))))
5589 (defun org-current-time (&optional rounding-minutes past
)
5590 "Current time, possibly rounded to ROUNDING-MINUTES.
5591 When ROUNDING-MINUTES is not an integer, fall back on the car of
5592 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5593 the rounding returns a past time."
5594 (let ((r (or (and (integerp rounding-minutes
) rounding-minutes
)
5595 (car org-time-stamp-rounding-minutes
)))
5596 (time (decode-time)) res
)
5601 (append (list 0 (* r
(floor (+ .5 (/ (float (nth 1 time
)) r
)))))
5603 (if (and past
(< (float-time (time-subtract (current-time) res
)) 0))
5604 (seconds-to-time (- (float-time res
) (* r
60)))
5608 "Return today date, considering `org-extend-today-until'."
5610 (time-subtract (current-time)
5611 (list 0 (* 3600 org-extend-today-until
) 0))))
5613 ;;;; Font-Lock stuff, including the activators
5615 (defvar org-mouse-map
(make-sparse-keymap))
5616 (org-defkey org-mouse-map
[mouse-2
] 'org-open-at-mouse
)
5617 (org-defkey org-mouse-map
[mouse-3
] 'org-find-file-at-mouse
)
5618 (when org-mouse-1-follows-link
5619 (org-defkey org-mouse-map
[follow-link
] 'mouse-face
))
5620 (when org-tab-follows-link
5621 (org-defkey org-mouse-map
[(tab)] 'org-open-at-point
)
5622 (org-defkey org-mouse-map
"\C-i" 'org-open-at-point
))
5624 (require 'font-lock
)
5626 (defconst org-non-link-chars
"]\t\n\r<>")
5627 (defvar org-link-types-re nil
5628 "Matches a link that has a url-like prefix like \"http:\"")
5629 (defvar org-link-re-with-space nil
5630 "Matches a link with spaces, optional angular brackets around it.")
5631 (defvar org-link-re-with-space2 nil
5632 "Matches a link with spaces, optional angular brackets around it.")
5633 (defvar org-link-re-with-space3 nil
5634 "Matches a link with spaces, only for internal part in bracket links.")
5635 (defvar org-angle-link-re nil
5636 "Matches link with angular brackets, spaces are allowed.")
5637 (defvar org-plain-link-re nil
5638 "Matches plain link, without spaces.")
5639 (defvar org-bracket-link-regexp nil
5640 "Matches a link in double brackets.")
5641 (defvar org-bracket-link-analytic-regexp nil
5642 "Regular expression used to analyze links.
5643 Here is what the match groups contain after a match:
5649 (defvar org-bracket-link-analytic-regexp
++ nil
5650 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5651 (defvar org-any-link-re nil
5652 "Regular expression matching any link.")
5654 (defconst org-match-sexp-depth
3
5655 "Number of stacked braces for sub/superscript matching.")
5657 (defun org-create-multibrace-regexp (left right n
)
5658 "Create a regular expression which will match a balanced sexp.
5659 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5660 as single character strings.
5661 The regexp returned will match the entire expression including the
5662 delimiters. It will also define a single group which contains the
5663 match except for the outermost delimiters. The maximum depth of
5664 stacked delimiters is N. Escaping delimiters is not possible."
5665 (let* ((nothing (concat "[^" left right
"]*?"))
5668 (next (concat "\\(?:" nothing left nothing right
"\\)+" nothing
)))
5671 re
(concat re or next
)
5672 next
(concat "\\(?:" nothing left next right
"\\)+" nothing
)))
5673 (concat left
"\\(" re
"\\)" right
)))
5675 (defconst org-match-substring-regexp
5677 "\\(\\S-\\)\\([_^]\\)\\("
5678 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)"
5680 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth
) "\\)"
5682 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5683 "The regular expression matching a sub- or superscript.")
5685 (defconst org-match-substring-with-braces-regexp
5687 "\\(\\S-\\)\\([_^]\\)"
5688 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)")
5689 "The regular expression matching a sub- or superscript, forcing braces.")
5691 (defun org-make-link-regexps ()
5692 "Update the link regular expressions.
5693 This should be called after the variable `org-link-parameters' has changed."
5694 (let ((types-re (regexp-opt (org-link-types) t
)))
5695 (setq org-link-types-re
5696 (concat "\\`" types-re
":")
5697 org-link-re-with-space
5698 (concat "<?" types-re
":"
5699 "\\([^" org-non-link-chars
" ]"
5700 "[^" org-non-link-chars
"]*"
5701 "[^" org-non-link-chars
" ]\\)>?")
5702 org-link-re-with-space2
5703 (concat "<?" types-re
":"
5704 "\\([^" org-non-link-chars
" ]"
5706 "[^" org-non-link-chars
" ]\\)>?")
5707 org-link-re-with-space3
5708 (concat "<?" types-re
":"
5709 "\\([^" org-non-link-chars
" ]"
5712 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5717 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5718 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5719 org-bracket-link-regexp
5720 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5721 org-bracket-link-analytic-regexp
5724 "\\(" types-re
":\\)?"
5727 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5729 org-bracket-link-analytic-regexp
++
5732 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t
) ":\\)?"
5735 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5738 (concat "\\(" org-bracket-link-regexp
"\\)\\|\\("
5739 org-angle-link-re
"\\)\\|\\("
5740 org-plain-link-re
"\\)"))))
5742 (org-make-link-regexps)
5744 (defvar org-emph-face nil
)
5746 (defun org-do-emphasis-faces (limit)
5747 "Run through the buffer and emphasize strings."
5748 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5749 (car org-emphasis-regexp-components
))))
5751 (while (re-search-forward quick-re limit t
)
5752 (let* ((marker (match-string 2))
5753 (verbatim?
(member marker
'("~" "="))))
5754 (when (save-excursion
5755 (goto-char (match-beginning 0))
5757 ;; Do not match table hlines.
5758 (not (and (equal marker
"+")
5760 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5761 ;; Do not match headline stars. Do not consider
5762 ;; stars of a headline as closing marker for bold
5764 (not (and (equal marker
"*")
5767 (skip-chars-backward "*")
5768 (looking-at-p org-outline-regexp-bol
))))
5769 ;; Match full emphasis markup regexp.
5770 (looking-at (if verbatim? org-verbatim-re org-emph-re
))
5771 ;; Do not span over paragraph boundaries.
5772 (not (string-match-p org-element-paragraph-separate
5774 ;; Do not span over cells in table rows.
5775 (not (and (save-match-data (org-match-line "[ \t]*|"))
5776 (string-match-p "|" (match-string 4))))))
5777 (pcase-let ((`(,_
,face
,_
) (assoc marker org-emphasis-alist
)))
5778 (font-lock-prepend-text-property
5779 (match-beginning 2) (match-end 2) 'face face
)
5781 (org-remove-flyspell-overlays-in
5782 (match-beginning 0) (match-end 0)))
5783 (add-text-properties (match-beginning 2) (match-end 2)
5784 '(font-lock-multiline t org-emphasis t
))
5785 (when org-hide-emphasis-markers
5786 (add-text-properties (match-end 4) (match-beginning 5)
5787 '(invisible org-link
))
5788 (add-text-properties (match-beginning 3) (match-end 3)
5789 '(invisible org-link
)))
5790 (throw :exit t
))))))))
5792 (defun org-emphasize (&optional char
)
5793 "Insert or change an emphasis, i.e. a font like bold or italic.
5794 If there is an active region, change that region to a new emphasis.
5795 If there is no region, just insert the marker characters and position
5796 the cursor between them.
5797 CHAR should be the marker character. If it is a space, it means to
5798 remove the emphasis of the selected region.
5799 If CHAR is not given (for example in an interactive call) it will be
5802 (let ((erc org-emphasis-regexp-components
)
5803 (string "") beg end move s
)
5804 (if (org-region-active-p)
5805 (setq beg
(region-beginning)
5807 string
(buffer-substring beg end
))
5811 (message "Emphasis marker or tag: [%s]"
5812 (mapconcat #'car org-emphasis-alist
""))
5813 (setq char
(read-char-exclusive)))
5814 (if (equal char ?\s
)
5817 (unless (assoc (char-to-string char
) org-emphasis-alist
)
5818 (user-error "No such emphasis marker: \"%c\"" char
))
5819 (setq s
(char-to-string char
)))
5820 (while (and (> (length string
) 1)
5821 (equal (substring string
0 1) (substring string -
1))
5822 (assoc (substring string
0 1) org-emphasis-alist
))
5823 (setq string
(substring string
1 -
1)))
5824 (setq string
(concat s string s
))
5825 (when beg
(delete-region beg end
))
5827 (string-match (concat "[" (nth 0 erc
) "\n]")
5828 (char-to-string (char-before (point)))))
5831 (string-match (concat "[" (nth 1 erc
) "\n]")
5832 (char-to-string (char-after (point)))))
5833 (insert " ") (backward-char 1))
5835 (and move
(backward-char 1))))
5837 (defconst org-nonsticky-props
5838 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link
))
5840 (defsubst org-rear-nonsticky-at
(pos)
5841 (add-text-properties (1- pos
) pos
(list 'rear-nonsticky org-nonsticky-props
)))
5843 (defun org-activate-links (limit)
5844 "Add link properties to links.
5845 This includes angle, plain, and bracket links."
5847 (while (re-search-forward org-any-link-re limit t
)
5848 (let* ((start (match-beginning 0))
5850 (style (cond ((eq ?
< (char-after start
)) 'angle
)
5851 ((eq ?\
[ (char-after (1+ start
))) 'bracket
)
5853 (when (and (memq style org-highlight-links
)
5854 ;; Do not confuse plain links with tags.
5855 (not (and (eq style
'plain
)
5856 (let ((face (get-text-property
5857 (max (1- start
) (point-min)) 'face
)))
5858 (if (consp face
) (memq 'org-tag face
)
5859 (eq 'org-tag face
))))))
5860 (let* ((link-object (save-excursion
5862 (save-match-data (org-element-link-parser))))
5863 (link (org-element-property :raw-link link-object
))
5864 (type (org-element-property :type link-object
))
5865 (path (org-element-property :path link-object
))
5866 (properties ;for link's visible part
5868 'face
(pcase (org-link-get-parameter type
:face
)
5869 ((and (pred functionp
) face
) (funcall face path
))
5870 ((and (pred facep
) face
) face
)
5871 ((and (pred consp
) face
) face
) ;anonymous
5873 'mouse-face
(or (org-link-get-parameter type
:mouse-face
)
5875 'keymap
(or (org-link-get-parameter type
:keymap
)
5877 'help-echo
(pcase (org-link-get-parameter type
:help-echo
)
5878 ((and (pred stringp
) echo
) echo
)
5879 ((and (pred functionp
) echo
) echo
)
5880 (_ (concat "LINK: " link
)))
5881 'htmlize-link
(pcase (org-link-get-parameter type
5883 ((and (pred functionp
) f
) (funcall f
))
5885 'font-lock-multiline t
)))
5886 (org-remove-flyspell-overlays-in start end
)
5887 (org-rear-nonsticky-at end
)
5888 (if (not (eq 'bracket style
))
5889 (add-text-properties start end properties
)
5890 ;; Handle invisible parts in bracket links.
5891 (remove-text-properties start end
'(invisible nil
))
5894 ,(or (org-link-get-parameter type
:display
)
5897 (visible-start (or (match-beginning 4) (match-beginning 2)))
5898 (visible-end (or (match-end 4) (match-end 2))))
5899 (add-text-properties start visible-start hidden
)
5900 (add-text-properties visible-start visible-end properties
)
5901 (add-text-properties visible-end end hidden
)
5902 (org-rear-nonsticky-at visible-start
)
5903 (org-rear-nonsticky-at visible-end
)))
5904 (let ((f (org-link-get-parameter type
:activate-func
)))
5906 (funcall f start end path
(eq style
'bracket
))))
5907 (throw :exit t
))))) ;signal success
5910 (defun org-activate-code (limit)
5911 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t
)
5912 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5913 (remove-text-properties (match-beginning 0) (match-end 0)
5914 '(display t invisible t intangible t
))
5917 (defcustom org-src-fontify-natively t
5918 "When non-nil, fontify code in code blocks.
5919 See also the `org-block' face."
5922 :package-version
'(Org .
"8.3")
5923 :group
'org-appearance
5926 (defcustom org-allow-promoting-top-level-subtree nil
5927 "When non-nil, allow promoting a top level subtree.
5928 The leading star of the top level headline will be replaced
5932 :group
'org-appearance
)
5934 (defun org-fontify-meta-lines-and-blocks (limit)
5936 (org-fontify-meta-lines-and-blocks-1 limit
)
5937 (error (message "org-mode fontification error in %S at %d"
5939 (line-number-at-pos)))))
5941 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5942 "Fontify #+ lines and blocks."
5943 (let ((case-fold-search t
))
5944 (when (re-search-forward
5945 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5947 (let ((beg (match-beginning 0))
5948 (block-start (match-end 0))
5950 (lang (match-string 7))
5951 (beg1 (line-beginning-position 2))
5952 (dc1 (downcase (match-string 2)))
5953 (dc3 (downcase (match-string 3)))
5954 end end1 quoting block-type
)
5956 ((and (match-end 4) (equal dc3
"+begin"))
5958 (setq block-type
(downcase (match-string 5))
5959 quoting
(member block-type org-protecting-blocks
))
5960 (when (re-search-forward
5961 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5962 nil t
) ;; on purpose, we look further than LIMIT
5963 (setq end
(min (point-max) (match-end 0))
5964 end1
(min (point-max) (1- (match-beginning 0))))
5965 (setq block-end
(match-beginning 0))
5967 (org-remove-flyspell-overlays-in beg1 end1
)
5968 (remove-text-properties beg end
5969 '(display t invisible t intangible t
)))
5970 (add-text-properties
5971 beg end
'(font-lock-fontified t font-lock-multiline t
))
5972 (add-text-properties beg beg1
'(face org-meta-line
))
5973 (org-remove-flyspell-overlays-in beg beg1
)
5974 (add-text-properties ; For end_src
5975 end1
(min (point-max) (1+ end
)) '(face org-meta-line
))
5976 (org-remove-flyspell-overlays-in end1 end
)
5978 ((and lang
(not (string= lang
"")) org-src-fontify-natively
)
5979 (org-src-font-lock-fontify-block lang block-start block-end
)
5980 (add-text-properties beg1 block-end
'(src-block t
)))
5982 (add-text-properties beg1
(min (point-max) (1+ end1
))
5986 (intern (format "org-block-%s" lang
))))
5987 (append (and (facep face-name
) (list face-name
))
5988 '(org-block))))))) ; end of source block
5989 ((not org-fontify-quote-and-verse-blocks
))
5990 ((string= block-type
"quote")
5991 (add-face-text-property
5992 beg1
(min (point-max) (1+ end1
)) 'org-quote t
))
5993 ((string= block-type
"verse")
5994 (add-face-text-property
5995 beg1
(min (point-max) (1+ end1
)) 'org-verse t
)))
5996 (add-text-properties beg beg1
'(face org-block-begin-line
))
5997 (add-text-properties (min (point-max) (1+ end
)) (min (point-max) (1+ end1
))
5998 '(face org-block-end-line
))
6000 ((member dc1
'("+title:" "+author:" "+email:" "+date:"))
6001 (org-remove-flyspell-overlays-in
6003 (if (equal "+title:" dc1
) (match-end 2) (match-end 0)))
6004 (add-text-properties
6006 (if (member (intern (substring dc1
1 -
1)) org-hidden-keywords
)
6007 '(font-lock-fontified t invisible t
)
6008 '(font-lock-fontified t face org-document-info-keyword
)))
6009 (add-text-properties
6010 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6011 (if (string-equal dc1
"+title:")
6012 '(font-lock-fontified t face org-document-title
)
6013 '(font-lock-fontified t face org-document-info
))))
6014 ((string-prefix-p "+caption" dc1
)
6015 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6016 (remove-text-properties (match-beginning 0) (match-end 0)
6017 '(display t invisible t intangible t
))
6018 ;; Handle short captions.
6021 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6022 (add-text-properties (line-beginning-position) (match-end 1)
6023 '(font-lock-fontified t face org-meta-line
))
6024 (add-text-properties (match-end 0) (line-end-position)
6025 '(font-lock-fontified t face org-block
))
6027 ((member dc3
'(" " ""))
6028 (org-remove-flyspell-overlays-in beg
(match-end 0))
6029 (add-text-properties
6031 '(font-lock-fontified t face font-lock-comment-face
)))
6032 (t ;; just any other in-buffer setting, but not indented
6033 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6034 (remove-text-properties (match-beginning 0) (match-end 0)
6035 '(display t invisible t intangible t
))
6036 (add-text-properties beg
(match-end 0)
6037 '(font-lock-fontified t face org-meta-line
))
6040 (defun org-fontify-drawers (limit)
6042 (when (re-search-forward org-drawer-regexp limit t
)
6043 (add-text-properties
6044 (match-beginning 0) (match-end 0)
6045 '(font-lock-fontified t face org-special-keyword
))
6046 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6049 (defun org-fontify-macros (limit)
6051 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t
)
6052 (add-text-properties
6053 (match-beginning 0) (match-end 0)
6054 '(font-lock-fontified t face org-macro
))
6055 (when org-hide-macro-markers
6056 (add-text-properties (match-end 2) (match-beginning 2)
6058 (add-text-properties (match-beginning 1) (match-end 1)
6060 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6063 (defun org-activate-footnote-links (limit)
6064 "Add text properties for footnotes."
6065 (let ((fn (org-footnote-next-reference-or-definition limit
)))
6067 (let* ((beg (nth 1 fn
))
6070 (referencep (/= (line-beginning-position) beg
)))
6071 (when (and referencep
(nth 3 fn
))
6074 (search-forward (or label
"fn:"))
6075 (org-remove-flyspell-overlays-in beg
(match-end 0))))
6076 (add-text-properties beg end
6077 (list 'mouse-face
'highlight
6078 'keymap org-mouse-map
6080 (if referencep
"Footnote reference"
6081 "Footnote definition")
6082 'font-lock-fontified t
6083 'font-lock-multiline t
6084 'face
'org-footnote
))))))
6086 (defun org-activate-dates (limit)
6087 "Add text properties for dates."
6088 (when (and (re-search-forward org-tsr-regexp-both limit t
)
6089 (not (equal (char-before (match-beginning 0)) 91)))
6090 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6091 (add-text-properties (match-beginning 0) (match-end 0)
6092 (list 'mouse-face
'highlight
6093 'keymap org-mouse-map
))
6094 (org-rear-nonsticky-at (match-end 0))
6095 (when org-display-custom-times
6096 ;; If it's a date range, activate custom time for second date.
6098 (org-display-custom-time (match-beginning 3) (match-end 3)))
6099 (org-display-custom-time (match-beginning 1) (match-end 1)))
6102 (defvar-local org-target-link-regexp nil
6103 "Regular expression matching radio targets in plain text.")
6105 (defconst org-target-regexp
(let ((border "[^<>\n\r \t]"))
6106 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6107 border border border
))
6108 "Regular expression matching a link target.")
6110 (defconst org-radio-target-regexp
(format "<%s>" org-target-regexp
)
6111 "Regular expression matching a radio target.")
6113 (defconst org-any-target-regexp
6114 (format "%s\\|%s" org-radio-target-regexp org-target-regexp
)
6115 "Regular expression matching any target.")
6117 (defun org-activate-target-links (limit)
6118 "Add text properties for target matches."
6119 (when org-target-link-regexp
6120 (let ((case-fold-search t
))
6121 (when (re-search-forward org-target-link-regexp limit t
)
6122 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6123 (add-text-properties (match-beginning 1) (match-end 1)
6124 (list 'mouse-face
'highlight
6125 'keymap org-mouse-map
6126 'help-echo
"Radio target link"
6127 'org-linked-text t
))
6128 (org-rear-nonsticky-at (match-end 1))
6131 (defun org-update-radio-target-regexp ()
6132 "Find all radio targets in this file and update the regular expression.
6133 Also refresh fontification if needed."
6135 (let ((old-regexp org-target-link-regexp
)
6136 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6137 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6139 (org-with-wide-buffer
6140 (goto-char (point-min))
6142 (while (re-search-forward org-radio-target-regexp nil t
)
6143 ;; Make sure point is really within the object.
6145 (let ((obj (org-element-context)))
6146 (when (eq (org-element-type obj
) 'radio-target
)
6147 (cl-pushnew (org-element-property :value obj
) rtn
6150 (setq org-target-link-regexp
6155 (replace-regexp-in-string
6156 " +" "\\s-+" (regexp-quote x
) t t
))
6160 (unless (equal old-regexp org-target-link-regexp
)
6162 (let ((regexp (cond ((not old-regexp
) org-target-link-regexp
)
6163 ((not org-target-link-regexp
) old-regexp
)
6168 (substring re
(length before-re
)
6169 (- (length after-re
))))
6170 (list old-regexp org-target-link-regexp
)
6173 (org-with-wide-buffer
6174 (goto-char (point-min))
6175 (while (re-search-forward regexp nil t
)
6176 (org-element-cache-refresh (match-beginning 1)))))
6177 ;; Re fontify buffer.
6178 (when (memq 'radio org-highlight-links
)
6179 (org-restart-font-lock)))))
6181 (defun org-hide-wide-columns (limit)
6183 (setq s
(text-property-any (point) (or limit
(point-max))
6186 (setq e
(next-single-property-change s
'org-cwidth
))
6187 (add-text-properties s e
'(invisible org-cwidth
))
6191 (defvar org-latex-and-related-regexp nil
6192 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6194 (defun org-compute-latex-and-related-regexp ()
6195 "Compute regular expression for LaTeX, entities and sub/superscript.
6196 Result depends on variable `org-highlight-latex-and-related'."
6198 org-latex-and-related-regexp
6200 (cond ((not (memq 'script org-highlight-latex-and-related
)) nil
)
6201 ((eq org-use-sub-superscripts
'{})
6202 (list org-match-substring-with-braces-regexp
))
6203 (org-use-sub-superscripts (list org-match-substring-regexp
))))
6205 (when (memq 'latex org-highlight-latex-and-related
)
6206 (let ((matchers (plist-get org-format-latex-options
:matchers
)))
6209 (and (member (car x
) matchers
) (nth 1 x
)))
6210 org-latex-regexps
)))))
6212 (when (memq 'entities org-highlight-latex-and-related
)
6213 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6214 (mapconcat 'identity
(append re-latex re-entities re-sub
) "\\|"))))
6216 (defun org-do-latex-and-related (limit)
6217 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6218 LIMIT bounds the search for syntax to highlight. Stop at first
6219 highlighted object, if any. Return t if some highlighting was
6220 done, nil otherwise."
6221 (when (org-string-nw-p org-latex-and-related-regexp
)
6223 (while (re-search-forward org-latex-and-related-regexp limit t
)
6227 (memq f
'(org-code org-verbatim underline org-special-keyword
)))
6229 (goto-char (1+ (match-beginning 0)))
6230 (face-at-point nil t
)))
6231 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6235 (font-lock-prepend-text-property
6236 (+ offset
(match-beginning 0)) (match-end 0)
6237 'face
'org-latex-and-related
)
6238 (add-text-properties (+ offset
(match-beginning 0)) (match-end 0)
6239 '(font-lock-multiline t
)))
6243 (defun org-restart-font-lock ()
6244 "Restart `font-lock-mode', to force refontification."
6245 (when (and (boundp 'font-lock-mode
) font-lock-mode
)
6247 (font-lock-mode 1)))
6249 (defun org-activate-tags (limit)
6250 (when (re-search-forward
6251 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t
)
6252 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6253 (add-text-properties (match-beginning 1) (match-end 1)
6254 (list 'mouse-face
'highlight
6255 'keymap org-mouse-map
))
6256 (org-rear-nonsticky-at (match-end 1))
6259 (defun org-outline-level ()
6260 "Compute the outline level of the heading at point.
6262 If this is called at a normal headline, the level is the number
6263 of stars. Use `org-reduced-level' to remove the effect of
6264 `org-odd-levels'. Unlike to `org-current-level', this function
6265 takes into consideration inlinetasks."
6266 (org-with-wide-buffer
6268 (if (re-search-backward org-outline-regexp-bol nil t
)
6269 (1- (- (match-end 0) (match-beginning 0)))
6272 (defvar org-font-lock-keywords nil
)
6274 (defsubst org-re-property
(property &optional literal allow-null value
)
6275 "Return a regexp matching a PROPERTY line.
6277 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6278 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6279 non-nil, match properties even without a value.
6281 Match group 3 is set to the value when it exists. If there is no
6282 value and ALLOW-NULL is non-nil, it is set to the empty string.
6284 With optional argument VALUE, match only property lines with
6285 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6286 unless LITERAL is non-nil."
6289 (format "\\(?1::\\(?2:%s\\):\\)"
6290 (if literal property
(regexp-quote property
)))
6292 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6293 (if literal value
(regexp-quote value
))))
6295 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6297 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6299 (defconst org-property-re
6300 (org-re-property "\\S-+" 'literal t
)
6301 "Regular expression matching a property line.
6302 There are four matching groups:
6303 1: :PROPKEY: including the leading and trailing colon,
6304 2: PROPKEY without the leading and trailing colon,
6305 3: PROPVAL without leading or trailing spaces,
6306 4: the indentation of the current line,
6307 5: trailing whitespace.")
6309 (defvar org-font-lock-hook nil
6310 "Functions to be called for special font lock stuff.")
6312 (defvar org-font-lock-extra-keywords nil
) ;Dynamically scoped.
6314 (defvar org-font-lock-set-keywords-hook nil
6315 "Functions that can manipulate `org-font-lock-extra-keywords'.
6316 This is called after `org-font-lock-extra-keywords' is defined, but before
6317 it is installed to be used by font lock. This can be useful if something
6318 needs to be inserted at a specific position in the font-lock sequence.")
6320 (defun org-font-lock-hook (limit)
6321 "Run `org-font-lock-hook' within LIMIT."
6322 (run-hook-with-args 'org-font-lock-hook limit
))
6324 (defun org-set-font-lock-defaults ()
6325 "Set font lock defaults for the current buffer."
6326 (let* ((em org-fontify-emphasized-text
)
6327 (lk org-highlight-links
)
6328 (org-font-lock-extra-keywords
6331 '(org-font-lock-hook)
6333 `(,(if org-fontify-whole-heading-line
6334 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6335 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6336 (1 (org-get-level-face 1))
6337 (2 (org-get-level-face 2))
6338 (3 (org-get-level-face 3)))
6340 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6343 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t
))
6344 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t
))
6345 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t
))
6346 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t
))
6348 '(org-fontify-drawers)
6350 (list org-property-re
6351 '(1 'org-special-keyword t
)
6352 '(3 'org-property-value t
))
6353 ;; Link related fontification.
6354 '(org-activate-links)
6355 (when (memq 'tag lk
) '(org-activate-tags (1 'org-tag prepend
)))
6356 (when (memq 'radio lk
) '(org-activate-target-links (1 'org-link t
)))
6357 (when (memq 'date lk
) '(org-activate-dates (0 'org-date t
)))
6358 (when (memq 'footnote lk
) '(org-activate-footnote-links))
6360 (list org-any-target-regexp
'(0 'org-target t
))
6362 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t
))
6364 '(org-fontify-macros)
6365 '(org-hide-wide-columns (0 nil append
))
6367 (list (format org-heading-keyword-regexp-format
6369 '(2 (org-get-todo-face 2) t
))
6371 (if org-fontify-done-headline
6372 (list (format org-heading-keyword-regexp-format
6375 (mapconcat 'regexp-quote org-done-keywords
"\\|")
6377 '(2 'org-headline-done t
))
6380 '(org-font-lock-add-priority-faces)
6382 '(org-font-lock-add-tag-faces)
6384 (when (and org-group-tags org-tag-groups-alist
)
6385 (list (concat org-outline-regexp-bol
".+\\(:"
6386 (regexp-opt (mapcar 'car org-tag-groups-alist
))
6388 '(1 'org-tag-group prepend
)))
6390 (list (concat "\\<" org-deadline-string
) '(0 'org-special-keyword t
))
6391 (list (concat "\\<" org-scheduled-string
) '(0 'org-special-keyword t
))
6392 (list (concat "\\<" org-closed-string
) '(0 'org-special-keyword t
))
6393 (list (concat "\\<" org-clock-string
) '(0 'org-special-keyword t
))
6395 (when em
'(org-do-emphasis-faces))
6397 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6398 1 'org-checkbox prepend
)
6399 (when (cdr (assq 'checkbox org-list-automatic-rules
))
6400 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6401 (0 (org-get-checkbox-statistics-face) t
)))
6402 ;; Description list items
6403 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6404 1 'org-list-dt prepend
)
6405 ;; ARCHIVEd headings
6407 org-outline-regexp-bol
6408 "\\(.*:" org-archive-tag
":.*\\)")
6409 '(1 'org-archived prepend
))
6411 '(org-do-latex-and-related)
6412 '(org-fontify-entities)
6413 '(org-raise-scripts)
6415 '(org-activate-code (1 'org-code t
))
6418 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6421 '(9 'org-special-keyword t
))
6422 ;; Blocks and meta lines
6423 '(org-fontify-meta-lines-and-blocks))))
6424 (setq org-font-lock-extra-keywords
(delq nil org-font-lock-extra-keywords
))
6425 (run-hooks 'org-font-lock-set-keywords-hook
)
6426 ;; Now set the full font-lock-keywords
6427 (setq-local org-font-lock-keywords org-font-lock-extra-keywords
)
6428 (setq-local font-lock-defaults
6429 '(org-font-lock-keywords t nil nil backward-paragraph
))
6430 (kill-local-variable 'font-lock-keywords
)
6433 (defun org-toggle-pretty-entities ()
6434 "Toggle the composition display of entities as UTF8 characters."
6436 (setq-local org-pretty-entities
(not org-pretty-entities
))
6437 (org-restart-font-lock)
6438 (if org-pretty-entities
6439 (message "Entities are now displayed as UTF8 characters")
6442 (decompose-region (point-min) (point-max))
6443 (message "Entities are now displayed as plain text"))))
6445 (defvar-local org-custom-properties-overlays nil
6446 "List of overlays used for custom properties.")
6448 (defun org-toggle-custom-properties-visibility ()
6449 "Display or hide properties in `org-custom-properties'."
6451 (if org-custom-properties-overlays
6452 (progn (mapc #'delete-overlay org-custom-properties-overlays
)
6453 (setq org-custom-properties-overlays nil
))
6454 (when org-custom-properties
6455 (org-with-wide-buffer
6456 (goto-char (point-min))
6457 (let ((regexp (org-re-property (regexp-opt org-custom-properties
) t t
)))
6458 (while (re-search-forward regexp nil t
)
6459 (let ((end (cdr (save-match-data (org-get-property-block)))))
6460 (when (and end
(< (point) end
))
6461 ;; Hide first custom property in current drawer.
6462 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6463 (overlay-put o
'invisible t
)
6464 (overlay-put o
'org-custom-property t
)
6465 (push o org-custom-properties-overlays
))
6466 ;; Hide additional custom properties in the same drawer.
6467 (while (re-search-forward regexp end t
)
6468 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6469 (overlay-put o
'invisible t
)
6470 (overlay-put o
'org-custom-property t
)
6471 (push o org-custom-properties-overlays
)))))
6472 ;; Each entry is limited to a single property drawer.
6473 (outline-next-heading)))))))
6475 (defun org-fontify-entities (limit)
6476 "Find an entity to fontify."
6478 (when org-pretty-entities
6480 ;; "\_ "-family is left out on purpose. Only the first one,
6481 ;; i.e., "\_ ", could be fontified anyway, and it would be
6482 ;; confusing when adding a second white space character.
6483 (while (re-search-forward
6484 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6486 (when (and (not (org-at-comment-p))
6487 (setq ee
(org-entity-get (match-string 1)))
6488 (= (length (nth 6 ee
)) 1))
6489 (let* ((end (if (equal (match-string 2) "{}")
6492 (add-text-properties
6493 (match-beginning 0) end
6494 (list 'font-lock-fontified t
))
6495 (compose-region (match-beginning 0) end
6501 (defun org-fontify-like-in-org-mode (s &optional odd-levels
)
6502 "Fontify string S like in Org mode."
6505 (let ((org-odd-levels-only odd-levels
))
6507 (org-font-lock-ensure)
6513 (defun org-get-level-face (n)
6514 "Get the right face for match N in font-lock matching of headlines."
6515 (setq org-l
(- (match-end 2) (match-beginning 1) 1))
6516 (when org-odd-levels-only
(setq org-l
(1+ (/ org-l
2))))
6517 (if org-cycle-level-faces
6518 (setq org-f
(nth (%
(1- org-l
) org-n-level-faces
) org-level-faces
))
6519 (setq org-f
(nth (1- (min org-l org-n-level-faces
)) org-level-faces
)))
6521 ((eq n
1) (if org-hide-leading-stars
'org-hide org-f
))
6523 (t (unless org-level-color-stars-only org-f
))))
6525 (defun org-face-from-face-or-color (context inherit face-or-color
)
6526 "Create a face list that inherits INHERIT, but sets the foreground color.
6527 When FACE-OR-COLOR is not a string, just return it."
6528 (if (stringp face-or-color
)
6529 (list :inherit inherit
6530 (cdr (assoc context org-faces-easy-properties
))
6534 (defun org-get-todo-face (kwd)
6535 "Get the right face for a TODO keyword KWD.
6536 If KWD is a number, get the corresponding match group."
6537 (when (numberp kwd
) (setq kwd
(match-string kwd
)))
6538 (or (org-face-from-face-or-color
6539 'todo
'org-todo
(cdr (assoc kwd org-todo-keyword-faces
)))
6540 (and (member kwd org-done-keywords
) 'org-done
)
6543 (defun org-get-priority-face (priority)
6544 "Get the right face for PRIORITY.
6545 PRIORITY is a character."
6546 (or (org-face-from-face-or-color
6547 'priority
'org-priority
(cdr (assq priority org-priority-faces
)))
6550 (defun org-get-tag-face (tag)
6551 "Get the right face for TAG.
6552 If TAG is a number, get the corresponding match group."
6553 (let ((tag (if (wholenump tag
) (match-string tag
) tag
)))
6554 (or (org-face-from-face-or-color
6555 'tag
'org-tag
(cdr (assoc tag org-tag-faces
)))
6558 (defun org-font-lock-add-priority-faces (limit)
6559 "Add the special priority faces."
6560 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t
)
6561 (add-text-properties
6562 (match-beginning 1) (match-end 1)
6563 (list 'face
(org-get-priority-face (string-to-char (match-string 2)))
6564 'font-lock-fontified t
))))
6566 (defun org-font-lock-add-tag-faces (limit)
6567 "Add the special tag faces."
6568 (when (and org-tag-faces org-tags-special-faces-re
)
6569 (while (re-search-forward org-tags-special-faces-re limit t
)
6570 (add-text-properties (match-beginning 1) (match-end 1)
6571 (list 'face
(org-get-tag-face 1)
6572 'font-lock-fontified t
))
6573 (backward-char 1))))
6575 (defun org-unfontify-region (beg end
&optional _maybe_loudly
)
6576 "Remove fontification and activation overlays from links."
6577 (font-lock-default-unfontify-region beg end
)
6578 (let* ((buffer-undo-list t
)
6579 (inhibit-read-only t
) (inhibit-point-motion-hooks t
)
6580 (inhibit-modification-hooks t
)
6581 deactivate-mark buffer-file-name buffer-file-truename
)
6582 (decompose-region beg end
)
6583 (remove-text-properties beg end
6584 '(mouse-face t keymap t org-linked-text t
6585 invisible t intangible t
6587 (org-remove-font-lock-display-properties beg end
)))
6589 (defconst org-script-display
'(((raise -
0.3) (height 0.7))
6590 ((raise 0.3) (height 0.7))
6593 "Display properties for showing superscripts and subscripts.")
6595 (defun org-remove-font-lock-display-properties (beg end
)
6596 "Remove specific display properties that have been added by font lock.
6597 The will remove the raise properties that are used to show superscripts
6601 (setq next
(next-single-property-change beg
'display nil end
)
6602 prop
(get-text-property beg
'display
))
6603 (when (member prop org-script-display
)
6604 (put-text-property beg next
'display nil
))
6607 (defun org-raise-scripts (limit)
6608 "Add raise properties to sub/superscripts."
6609 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6611 (if (eq org-use-sub-superscripts t
)
6612 org-match-substring-regexp
6613 org-match-substring-with-braces-regexp
)
6615 (let* ((pos (point)) table-p comment-p
6616 (mpos (match-beginning 3))
6617 (emph-p (get-text-property mpos
'org-emphasis
))
6618 (link-p (get-text-property mpos
'mouse-face
))
6619 (keyw-p (eq 'org-special-keyword
(get-text-property mpos
'face
))))
6620 (goto-char (point-at-bol))
6621 (setq table-p
(looking-at-p org-table-dataline-regexp
)
6622 comment-p
(looking-at-p "^[ \t]*#[ +]"))
6625 (when (member (char-after) '(?_ ?^
)) (goto-char (1- pos
)))
6626 (unless (or comment-p emph-p link-p keyw-p
)
6627 (put-text-property (match-beginning 3) (match-end 0)
6629 (if (equal (char-after (match-beginning 2)) ?^
)
6630 (nth (if table-p
3 1) org-script-display
)
6631 (nth (if table-p
2 0) org-script-display
)))
6632 (add-text-properties (match-beginning 2) (match-end 2)
6633 (list 'invisible t
))
6634 (when (and (eq (char-after (match-beginning 3)) ?
{)
6635 (eq (char-before (match-end 3)) ?
}))
6636 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6637 (list 'invisible t
))
6638 (add-text-properties (1- (match-end 3)) (match-end 3)
6639 (list 'invisible t
))))
6642 ;;;; Visibility cycling, including org-goto and indirect buffer
6646 (defvar-local org-cycle-global-status nil
)
6647 (put 'org-cycle-global-status
'org-state t
)
6648 (defvar-local org-cycle-subtree-status nil
)
6649 (put 'org-cycle-subtree-status
'org-state t
)
6651 (defvar org-inlinetask-min-level
)
6653 (defun org-unlogged-message (&rest args
)
6654 "Display a message, but avoid logging it in the *Messages* buffer."
6655 (let ((message-log-max nil
))
6656 (apply 'message args
)))
6659 (defun org-cycle (&optional arg
)
6660 "TAB-action and visibility cycling for Org mode.
6662 This is the command invoked in Org mode by the `TAB' key. Its main
6663 purpose is outline visibility cycling, but it also invokes other actions
6664 in special contexts.
6666 When this function is called with a `\\[universal-argument]' prefix, rotate \
6668 buffer through 3 states (global cycling)
6669 1. OVERVIEW: Show only top-level headlines.
6670 2. CONTENTS: Show all headlines of all levels, but no body text.
6671 3. SHOW ALL: Show everything.
6673 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6674 switch to the startup visibility,
6675 determined by the variable `org-startup-folded', and by any VISIBILITY
6676 properties in the buffer.
6678 With a `\\[universal-argument] \\[universal-argument] \
6679 \\[universal-argument]' prefix argument, show the entire buffer, including
6682 When inside a table, re-align the table and move to the next field.
6684 When point is at the beginning of a headline, rotate the subtree started
6685 by this line through 3 different states (local cycling)
6686 1. FOLDED: Only the main headline is shown.
6687 2. CHILDREN: The main headline and the direct children are shown.
6688 From this state, you can move to one of the children
6689 and zoom in further.
6690 3. SUBTREE: Show the entire subtree, including body text.
6691 If there is no subtree, switch directly from CHILDREN to FOLDED.
6693 When point is at the beginning of an empty headline and the variable
6694 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6695 of the headline by demoting and promoting it to likely levels. This
6696 speeds up creation document structure by pressing `TAB' once or several
6697 times right after creating a new headline.
6699 When there is a numeric prefix, go up to a heading with level ARG, do
6700 a `show-subtree' and return to the previous cursor position. If ARG
6701 is negative, go up that many levels.
6703 When point is not at the beginning of a headline, execute the global
6704 binding for `TAB', which is re-indenting the line. See the option
6705 `org-cycle-emulate-tab' for details.
6707 As a special case, if point is at the beginning of the buffer and there is
6708 no headline in line 1, this function will act as if called with prefix arg
6709 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6710 prefix arg, but only
6711 if the variable `org-cycle-global-at-bob' is t."
6713 (org-load-modules-maybe)
6714 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook
)
6715 (and org-cycle-level-after-item
/entry-creation
6716 (or (org-cycle-level)
6717 (org-cycle-item-indentation))))
6719 (or org-cycle-max-level
6720 (and (boundp 'org-inlinetask-min-level
)
6721 org-inlinetask-min-level
6722 (1- org-inlinetask-min-level
))))
6723 (nstars (and limit-level
6724 (if org-odd-levels-only
6725 (and limit-level
(1- (* limit-level
2)))
6728 (if (not (derived-mode-p 'org-mode
))
6730 (concat "\\*" (if nstars
(format "\\{1,%d\\} " nstars
) "+ "))))
6731 (bob-special (and org-cycle-global-at-bob
(not arg
) (bobp)
6732 (not (looking-at org-outline-regexp
))))
6735 (delq 'org-optimize-window-after-visibility-change
6736 (copy-sequence org-cycle-hook
))
6743 (setq last-command
'dummy
)
6744 (org-set-startup-visibility)
6745 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6749 (org-unlogged-message "Entire buffer visible, including drawers"))
6751 ((equal arg
'(4)) (org-cycle-internal-global))
6753 ;; Try hiding block at point.
6754 ((org-hide-block-toggle-maybe))
6756 ;; Try cdlatex TAB completion
6757 ((org-try-cdlatex-tab))
6759 ;; Table: enter it or move to the next field.
6760 ((org-at-table-p 'any
)
6761 (if (org-at-table.el-p
)
6762 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6763 Use `\\[org-edit-special]' to edit table.el tables"))
6764 (if arg
(org-table-edit-field t
)
6765 (org-table-justify-field-maybe)
6766 (call-interactively 'org-table-next-field
))))
6768 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook
))
6770 ;; Global cycling: delegate to `org-cycle-internal-global'.
6771 (bob-special (org-cycle-internal-global))
6773 ;; Drawers: delegate to `org-flag-drawer'.
6775 (beginning-of-line 1)
6776 (looking-at org-drawer-regexp
))
6777 (org-flag-drawer ; toggle block visibility
6778 (not (get-char-property (match-end 0) 'invisible
))))
6780 ;; Show-subtree, ARG levels up from here.
6783 (org-back-to-heading)
6784 (outline-up-heading (if (< arg
0) (- arg
)
6785 (- (funcall outline-level
) arg
)))
6786 (org-show-subtree)))
6788 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6789 ((and (featurep 'org-inlinetask
)
6790 (org-inlinetask-at-task-p)
6791 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6792 (org-inlinetask-toggle-visibility))
6794 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6795 ((and (or (and org-cycle-include-plain-lists
(org-at-item-p))
6796 (save-excursion (move-beginning-of-line 1)
6797 (looking-at org-outline-regexp
)))
6798 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6799 (org-cycle-internal-local))
6801 ;; From there: TAB emulation and template completion.
6802 (buffer-read-only (org-back-to-heading))
6804 ((run-hook-with-args-until-success
6805 'org-tab-after-check-for-cycling-hook
))
6807 ((org-try-structure-completion))
6809 ((run-hook-with-args-until-success
6810 'org-tab-before-tab-emulation-hook
))
6812 ((and (eq org-cycle-emulate-tab
'exc-hl-bol
)
6814 (not (looking-at org-outline-regexp
))))
6815 (call-interactively (global-key-binding "\t")))
6817 ((if (and (memq org-cycle-emulate-tab
'(white whitestart
))
6818 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6819 (or (and (eq org-cycle-emulate-tab
'white
)
6820 (= (match-end 0) (point-at-eol)))
6821 (and (eq org-cycle-emulate-tab
'whitestart
)
6822 (>= (match-end 0) pos
))))
6824 (eq org-cycle-emulate-tab t
))
6825 (call-interactively (global-key-binding "\t")))
6828 (org-back-to-heading)
6831 (defun org-cycle-internal-global ()
6832 "Do the global cycling action."
6833 ;; Hack to avoid display of messages for .org attachments in Gnus
6834 (let ((ga (string-match "\\*fontification" (buffer-name))))
6836 ((and (eq last-command this-command
)
6837 (eq org-cycle-global-status
'overview
))
6838 ;; We just created the overview - now do table of contents
6839 ;; This can be slow in very large buffers, so indicate action
6840 (run-hook-with-args 'org-pre-cycle-hook
'contents
)
6841 (unless ga
(org-unlogged-message "CONTENTS..."))
6843 (unless ga
(org-unlogged-message "CONTENTS...done"))
6844 (setq org-cycle-global-status
'contents
)
6845 (run-hook-with-args 'org-cycle-hook
'contents
))
6847 ((and (eq last-command this-command
)
6848 (eq org-cycle-global-status
'contents
))
6849 ;; We just showed the table of contents - now show everything
6850 (run-hook-with-args 'org-pre-cycle-hook
'all
)
6852 (unless ga
(org-unlogged-message "SHOW ALL"))
6853 (setq org-cycle-global-status
'all
)
6854 (run-hook-with-args 'org-cycle-hook
'all
))
6857 ;; Default action: go to overview
6858 (run-hook-with-args 'org-pre-cycle-hook
'overview
)
6860 (unless ga
(org-unlogged-message "OVERVIEW"))
6861 (setq org-cycle-global-status
'overview
)
6862 (run-hook-with-args 'org-cycle-hook
'overview
)))))
6864 (defvar org-called-with-limited-levels nil
6865 "Non-nil when `org-with-limited-levels' is currently active.")
6867 (defun org-invisible-p (&optional pos
)
6868 "Non-nil if the character after POS is invisible.
6869 If POS is nil, use `point' instead."
6870 (get-char-property (or pos
(point)) 'invisible
))
6872 (defun org-cycle-internal-local ()
6873 "Do the local cycling action."
6874 (let ((goal-column 0) eoh eol eos has-children children-skipped struct
)
6875 ;; First, determine end of headline (EOH), end of subtree or item
6876 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6881 (setq struct
(org-list-struct))
6882 (setq eoh
(point-at-eol))
6883 (setq eos
(org-list-get-item-end-before-blank (point) struct
))
6884 (setq has-children
(org-list-has-child-p (point) struct
)))
6885 (org-back-to-heading)
6886 (setq eoh
(save-excursion (outline-end-of-heading) (point)))
6887 (setq eos
(save-excursion (org-end-of-subtree t t
)
6888 (when (bolp) (backward-char)) (point)))
6891 (let ((level (funcall outline-level
)))
6892 (outline-next-heading)
6893 (and (org-at-heading-p t
)
6894 (> (funcall outline-level
) level
))))
6896 (org-list-search-forward (org-item-beginning-re) eos t
)))))
6897 ;; Determine end invisible part of buffer (EOL)
6898 (beginning-of-line 2)
6899 (while (and (not (eobp)) ;This is like `next-line'.
6900 (get-char-property (1- (point)) 'invisible
))
6901 (goto-char (next-single-char-property-change (point) 'invisible
))
6902 (and (eolp) (beginning-of-line 2)))
6904 ;; Find out what to do next and set `this-command'
6907 ;; Nothing is hidden behind this heading
6908 (unless (org-before-first-heading-p)
6909 (run-hook-with-args 'org-pre-cycle-hook
'empty
))
6910 (org-unlogged-message "EMPTY ENTRY")
6911 (setq org-cycle-subtree-status nil
)
6914 (outline-next-heading)
6915 (when (org-invisible-p) (org-flag-heading nil
))))
6916 ((and (or (>= eol eos
)
6917 (not (string-match "\\S-" (buffer-substring eol eos
))))
6919 (not (setq children-skipped
6920 org-cycle-skip-children-state-if-no-children
))))
6921 ;; Entire subtree is hidden in one line: children view
6922 (unless (org-before-first-heading-p)
6923 (run-hook-with-args 'org-pre-cycle-hook
'children
))
6925 (org-list-set-item-visibility (point-at-bol) struct
'children
)
6927 (org-with-limited-levels (org-show-children))
6928 ;; FIXME: This slows down the func way too much.
6929 ;; How keep drawers hidden in subtree anyway?
6930 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6931 ;; (org-cycle-hide-drawers 'subtree))
6933 ;; Fold every list in subtree to top-level items.
6934 (when (eq org-cycle-include-plain-lists
'integrate
)
6936 (org-back-to-heading)
6937 (while (org-list-search-forward (org-item-beginning-re) eos t
)
6938 (beginning-of-line 1)
6939 (let* ((struct (org-list-struct))
6940 (prevs (org-list-prevs-alist struct
))
6941 (end (org-list-get-bottom-point struct
)))
6942 (dolist (e (org-list-get-all-items (point) struct prevs
))
6943 (org-list-set-item-visibility e struct
'folded
))
6944 (goto-char (if (< end eos
) end eos
)))))))
6945 (org-unlogged-message "CHILDREN")
6948 (outline-next-heading)
6949 (when (org-invisible-p) (org-flag-heading nil
)))
6950 (setq org-cycle-subtree-status
'children
)
6951 (unless (org-before-first-heading-p)
6952 (run-hook-with-args 'org-cycle-hook
'children
)))
6953 ((or children-skipped
6954 (and (eq last-command this-command
)
6955 (eq org-cycle-subtree-status
'children
)))
6956 ;; We just showed the children, or no children are there,
6957 ;; now show everything.
6958 (unless (org-before-first-heading-p)
6959 (run-hook-with-args 'org-pre-cycle-hook
'subtree
))
6960 (outline-flag-region eoh eos nil
)
6961 (org-unlogged-message
6962 (if children-skipped
"SUBTREE (NO CHILDREN)" "SUBTREE"))
6963 (setq org-cycle-subtree-status
'subtree
)
6964 (unless (org-before-first-heading-p)
6965 (run-hook-with-args 'org-cycle-hook
'subtree
)))
6967 ;; Default action: hide the subtree.
6968 (run-hook-with-args 'org-pre-cycle-hook
'folded
)
6969 (outline-flag-region eoh eos t
)
6970 (org-unlogged-message "FOLDED")
6971 (setq org-cycle-subtree-status
'folded
)
6972 (unless (org-before-first-heading-p)
6973 (run-hook-with-args 'org-cycle-hook
'folded
))))))
6976 (defun org-global-cycle (&optional arg
)
6977 "Cycle the global visibility. For details see `org-cycle'.
6978 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6979 With a numeric prefix, show all headlines up to that level."
6981 (let ((org-cycle-include-plain-lists
6982 (if (derived-mode-p 'org-mode
) org-cycle-include-plain-lists nil
)))
6986 (outline-hide-sublevels arg
)
6987 (setq org-cycle-global-status
'contents
))
6989 (org-set-startup-visibility)
6990 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6992 (org-cycle '(4))))))
6994 (defun org-set-startup-visibility ()
6995 "Set the visibility required by startup options and properties."
6997 ((eq org-startup-folded t
)
6999 ((eq org-startup-folded
'content
)
7001 ((or (eq org-startup-folded
'showeverything
)
7002 (eq org-startup-folded nil
))
7003 (outline-show-all)))
7004 (unless (eq org-startup-folded
'showeverything
)
7005 (when org-hide-block-startup
(org-hide-block-all))
7006 (org-set-visibility-according-to-property 'no-cleanup
)
7007 (org-cycle-hide-archived-subtrees 'all
)
7008 (org-cycle-hide-drawers 'all
)
7009 (org-cycle-show-empty-lines t
)))
7011 (defun org-set-visibility-according-to-property (&optional no-cleanup
)
7012 "Switch subtree visibilities according to :VISIBILITY: property."
7014 (org-with-wide-buffer
7015 (goto-char (point-min))
7016 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t
)
7017 (if (not (org-at-property-p)) (outline-next-heading)
7018 (let ((state (match-string 3)))
7020 (org-back-to-heading t
)
7021 (outline-hide-subtree)
7024 ((equal state
"folded")
7025 (outline-hide-subtree))
7026 ((equal state
"children")
7027 (org-show-hidden-entry)
7028 (org-show-children))
7029 ((equal state
"content")
7032 (org-narrow-to-subtree)
7034 ((member state
'("all" "showall"))
7035 (outline-show-subtree)))))))
7037 (org-cycle-hide-archived-subtrees 'all
)
7038 (org-cycle-hide-drawers 'all
)
7039 (org-cycle-show-empty-lines 'all
))))
7041 ;; This function uses outline-regexp instead of the more fundamental
7042 ;; org-outline-regexp so that org-cycle-global works outside of Org
7043 ;; buffers, where outline-regexp is needed.
7044 (defun org-overview ()
7045 "Switch to overview mode, showing only top-level headlines.
7046 This shows all headlines with a level equal or greater than the level
7047 of the first headline in the buffer. This is important, because if the
7048 first headline is not level one, then (hide-sublevels 1) gives confusing
7054 (goto-char (point-min))
7055 (when (re-search-forward (concat "^" outline-regexp
) nil t
)
7056 (goto-char (match-beginning 0))
7057 (funcall outline-level
)))))
7058 (and level
(outline-hide-sublevels level
)))))
7060 (defun org-content (&optional arg
)
7061 "Show all headlines in the buffer, like a table of contents.
7062 With numerical argument N, show content up to level N."
7066 ;; Visit all headings and show their offspring
7067 (and (integerp arg
) (org-overview))
7068 (goto-char (point-max))
7070 (while (and (progn (condition-case nil
7071 (outline-previous-visible-heading 1)
7072 (error (goto-char (point-min))))
7074 (looking-at org-outline-regexp
))
7076 (org-show-children (1- arg
))
7077 (outline-show-branches))
7078 (when (bobp) (throw 'exit nil
))))))
7080 (defun org-optimize-window-after-visibility-change (state)
7081 "Adjust the window after a change in outline visibility.
7082 This function is the default value of the hook `org-cycle-hook'."
7083 (when (get-buffer-window (current-buffer))
7085 ((eq state
'content
) nil
)
7086 ((eq state
'all
) nil
)
7087 ((eq state
'folded
) nil
)
7088 ((eq state
'children
) (or (org-subtree-end-visible-p) (recenter 1)))
7089 ((eq state
'subtree
) (or (org-subtree-end-visible-p) (recenter 1))))))
7091 (defun org-remove-empty-overlays-at (pos)
7092 "Remove outline overlays that do not contain non-white stuff."
7093 (dolist (o (overlays-at pos
))
7094 (and (eq 'outline
(overlay-get o
'invisible
))
7095 (not (string-match "\\S-" (buffer-substring (overlay-start o
)
7097 (delete-overlay o
))))
7099 (defun org-clean-visibility-after-subtree-move ()
7100 "Fix visibility issues after moving a subtree."
7101 ;; First, find a reasonable region to look at:
7102 ;; Start two siblings above, end three below
7103 (let* ((beg (save-excursion
7104 (and (org-get-last-sibling)
7105 (org-get-last-sibling))
7107 (end (save-excursion
7108 (and (org-get-next-sibling)
7109 (org-get-next-sibling)
7110 (org-get-next-sibling))
7111 (if (org-at-heading-p)
7114 (level (looking-at "\\*+"))
7115 (re (when level
(concat "^" (regexp-quote (match-string 0)) " "))))
7118 (narrow-to-region beg end
)
7120 ;; Properly fold already folded siblings
7121 (goto-char (point-min))
7122 (while (re-search-forward re nil t
)
7123 (when (and (not (org-invisible-p))
7125 (goto-char (point-at-eol)) (org-invisible-p)))
7126 (outline-hide-entry))))
7127 (org-cycle-show-empty-lines 'overview
)
7128 (org-cycle-hide-drawers 'overview
)))))
7130 (defun org-cycle-show-empty-lines (state)
7131 "Show empty lines above all visible headlines.
7132 The region to be covered depends on STATE when called through
7133 `org-cycle-hook'. Lisp program can use t for STATE to get the
7134 entire buffer covered. Note that an empty line is only shown if there
7135 are at least `org-cycle-separator-lines' empty lines before the headline."
7136 (when (/= org-cycle-separator-lines
0)
7138 (let* ((n (abs org-cycle-separator-lines
))
7140 ((= n
1) "\\(\n[ \t]*\n\\*+\\) ")
7141 ((= n
2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7142 (t (let ((ns (number-to-string (- n
2))))
7143 (concat "^\\(?:[ \t]*\n\\)\\{" ns
"," ns
"\\}"
7144 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7147 ((memq state
'(overview contents t
))
7148 (setq beg
(point-min) end
(point-max)))
7149 ((memq state
'(children folded
))
7151 end
(progn (org-end-of-subtree t t
)
7152 (line-beginning-position 2)))))
7155 (while (re-search-forward re end t
)
7156 (unless (get-char-property (match-end 1) 'invisible
)
7157 (let ((e (match-end 1))
7158 (b (if (>= org-cycle-separator-lines
0)
7161 (goto-char (match-beginning 0))
7162 (skip-chars-backward " \t\n")
7163 (line-end-position)))))
7164 (outline-flag-region b e nil
))))))))
7165 ;; Never hide empty lines at the end of the file.
7167 (goto-char (point-max))
7168 (outline-previous-heading)
7169 (outline-end-of-heading)
7170 (when (and (looking-at "[ \t\n]+")
7171 (= (match-end 0) (point-max)))
7172 (outline-flag-region (point) (match-end 0) nil
))))
7174 (defun org-show-empty-lines-in-parent ()
7175 "Move to the parent and re-show empty lines before visible headlines."
7177 (let ((context (if (org-up-heading-safe) 'children
'overview
)))
7178 (org-cycle-show-empty-lines context
))))
7180 (defun org-files-list ()
7181 "Return `org-agenda-files' list, plus all open Org files.
7182 This is useful for operations that need to scan all of a user's
7183 open and agenda-wise Org files."
7184 (let ((files (mapcar 'expand-file-name
(org-agenda-files))))
7185 (dolist (buf (buffer-list))
7186 (with-current-buffer buf
7187 (when (and (derived-mode-p 'org-mode
) (buffer-file-name))
7188 (cl-pushnew (expand-file-name (buffer-file-name)) files
))))
7191 (defsubst org-entry-beginning-position
()
7192 "Return the beginning position of the current entry."
7193 (save-excursion (org-back-to-heading t
) (point)))
7195 (defsubst org-entry-end-position
()
7196 "Return the end position of the current entry."
7197 (save-excursion (outline-next-heading) (point)))
7199 (defun org-cycle-hide-drawers (state &optional exceptions
)
7200 "Re-hide all drawers after a visibility state change.
7201 STATE should be one of the symbols listed in the docstring of
7202 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7203 a list of strings specifying which drawers should not be hidden."
7204 (when (and (derived-mode-p 'org-mode
)
7205 (not (memq state
'(overview folded contents
))))
7207 (let* ((globalp (eq state
'all
))
7208 (beg (if globalp
(point-min) (point)))
7209 (end (if globalp
(point-max)
7210 (if (eq state
'children
)
7211 (save-excursion (outline-next-heading) (point))
7212 (org-end-of-subtree t
)))))
7214 (while (re-search-forward org-drawer-regexp
(max end
(point)) t
)
7215 (unless (member-ignore-case (match-string 1) exceptions
)
7216 (let ((drawer (org-element-at-point)))
7217 (when (memq (org-element-type drawer
) '(drawer property-drawer
))
7218 (org-flag-drawer t drawer
)
7219 ;; Make sure to skip drawer entirely or we might flag
7220 ;; it another time when matching its ending line with
7221 ;; `org-drawer-regexp'.
7222 (goto-char (org-element-property :end drawer
))))))))))
7224 (defun org-flag-drawer (flag &optional element
)
7225 "When FLAG is non-nil, hide the drawer we are at.
7226 Otherwise make it visible. When optional argument ELEMENT is
7227 a parsed drawer, as returned by `org-element-at-point', hide or
7228 show that drawer instead."
7229 (let ((drawer (or element
7230 (and (save-excursion
7232 (looking-at-p org-drawer-regexp
))
7233 (org-element-at-point)))))
7234 (when (memq (org-element-type drawer
) '(drawer property-drawer
))
7235 (let ((post (org-element-property :post-affiliated drawer
)))
7237 (outline-flag-region
7238 (progn (goto-char post
) (line-end-position))
7239 (progn (goto-char (org-element-property :end drawer
))
7240 (skip-chars-backward " \r\t\n")
7241 (line-end-position))
7243 ;; When the drawer is hidden away, make sure point lies in
7244 ;; a visible part of the buffer.
7245 (when (and flag
(> (line-beginning-position) post
))
7246 (goto-char post
))))))
7248 (defun org-subtree-end-visible-p ()
7249 "Is the end of the current subtree visible?"
7250 (pos-visible-in-window-p
7251 (save-excursion (org-end-of-subtree t
) (point))))
7253 (defun org-first-headline-recenter ()
7254 "Move cursor to the first headline and recenter the headline."
7255 (let ((window (get-buffer-window)))
7257 (goto-char (point-min))
7258 (when (re-search-forward (concat "^\\(" org-outline-regexp
"\\)") nil t
)
7259 (set-window-start window
(line-beginning-position))))))
7261 ;;; Saving and restoring visibility
7263 (defun org-outline-overlay-data (&optional use-markers
)
7264 "Return a list of the locations of all outline overlays.
7265 These are overlays with the `invisible' property value `outline'.
7266 The return value is a list of cons cells, with start and stop
7267 positions for each overlay.
7268 If USE-MARKERS is set, return the positions as markers."
7270 (org-with-wide-buffer
7273 (when (eq (overlay-get o
'invisible
) 'outline
)
7274 (setq beg
(overlay-start o
)
7275 end
(overlay-end o
))
7276 (and beg end
(> end beg
)
7278 (cons (copy-marker beg
)
7279 (copy-marker end t
))
7281 (overlays-in (point-min) (point-max)))))))
7283 (defun org-set-outline-overlay-data (data)
7284 "Create visibility overlays for all positions in DATA.
7285 DATA should have been made by `org-outline-overlay-data'."
7286 (org-with-wide-buffer
7288 (dolist (c data
) (outline-flag-region (car c
) (cdr c
) t
))))
7290 ;;; Folding of blocks
7292 (defvar-local org-hide-block-overlays nil
7293 "Overlays hiding blocks.")
7295 (defun org-block-map (function &optional start end
)
7296 "Call FUNCTION at the head of all source blocks in the current buffer.
7297 Optional arguments START and END can be used to limit the range."
7298 (let ((start (or start
(point-min)))
7299 (end (or end
(point-max))))
7302 (while (and (< (point) end
) (re-search-forward org-block-regexp end t
))
7305 (goto-char (match-beginning 0))
7306 (funcall function
)))))))
7308 (defun org-hide-block-toggle-all ()
7309 "Toggle the visibility of all blocks in the current buffer."
7310 (org-block-map 'org-hide-block-toggle
))
7312 (defun org-hide-block-all ()
7313 "Fold all blocks in the current buffer."
7315 (org-show-block-all)
7316 (org-block-map 'org-hide-block-toggle-maybe
))
7318 (defun org-show-block-all ()
7319 "Unfold all blocks in the current buffer."
7321 (mapc #'delete-overlay org-hide-block-overlays
)
7322 (setq org-hide-block-overlays nil
))
7324 (defun org-hide-block-toggle-maybe ()
7325 "Toggle visibility of block at point.
7326 Unlike to `org-hide-block-toggle', this function does not throw
7327 an error. Return a non-nil value when toggling is successful."
7329 (ignore-errors (org-hide-block-toggle)))
7331 (defun org-hide-block-toggle (&optional force
)
7332 "Toggle the visibility of the current block.
7333 When optional argument FORCE is `off', make block visible. If it
7334 is non-nil, hide it unconditionally. Throw an error when not at
7335 a block. Return a non-nil value when toggling is successful."
7337 (let ((element (org-element-at-point)))
7338 (unless (memq (org-element-type element
)
7339 '(center-block comment-block dynamic-block example-block
7340 export-block quote-block special-block
7341 src-block verse-block
))
7342 (user-error "Not at a block"))
7343 (let* ((start (save-excursion
7344 (goto-char (org-element-property :post-affiliated element
))
7345 (line-end-position)))
7346 (end (save-excursion
7347 (goto-char (org-element-property :end element
))
7348 (skip-chars-backward " \r\t\n")
7349 (line-end-position)))
7350 (overlays (overlays-at start
)))
7352 ;; Do nothing when not before or at the block opening line or
7353 ;; at the block closing line.
7354 ((let ((eol (line-end-position))) (and (> eol start
) (/= eol end
))) nil
)
7355 ((and (not (eq force
'off
))
7356 (not (memq t
(mapcar
7358 (eq (overlay-get o
'invisible
) 'org-hide-block
))
7360 (let ((ov (make-overlay start end
)))
7361 (overlay-put ov
'invisible
'org-hide-block
)
7362 ;; Make the block accessible to `isearch'.
7364 ov
'isearch-open-invisible
7366 (when (memq ov org-hide-block-overlays
)
7367 (setq org-hide-block-overlays
(delq ov org-hide-block-overlays
)))
7368 (when (eq (overlay-get ov
'invisible
) 'org-hide-block
)
7369 (delete-overlay ov
))))
7370 (push ov org-hide-block-overlays
)
7371 ;; When the block is hidden away, make sure point is left in
7372 ;; a visible part of the buffer.
7373 (when (> (line-beginning-position) start
)
7375 (beginning-of-line))
7376 ;; Signal successful toggling.
7378 ((or (not force
) (eq force
'off
))
7379 (dolist (ov overlays t
)
7380 (when (memq ov org-hide-block-overlays
)
7381 (setq org-hide-block-overlays
(delq ov org-hide-block-overlays
)))
7382 (when (eq (overlay-get ov
'invisible
) 'org-hide-block
)
7383 (delete-overlay ov
))))))))
7385 ;; Remove overlays when changing major mode
7386 (add-hook 'org-mode-hook
7387 (lambda () (add-hook 'change-major-mode-hook
7388 'org-show-block-all
'append
'local
)))
7392 (defvar org-goto-window-configuration nil
)
7393 (defvar org-goto-marker nil
)
7394 (defvar org-goto-map
)
7395 (defun org-goto-map ()
7396 "Set the keymap `org-goto'."
7398 (let ((map (make-sparse-keymap)))
7399 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7400 mouse-drag-region universal-argument org-occur
)))
7402 (substitute-key-definition cmd cmd map global-map
)))
7403 (suppress-keymap map
)
7404 (org-defkey map
"\C-m" 'org-goto-ret
)
7405 (org-defkey map
[(return)] 'org-goto-ret
)
7406 (org-defkey map
[(left)] 'org-goto-left
)
7407 (org-defkey map
[(right)] 'org-goto-right
)
7408 (org-defkey map
[(control ?g
)] 'org-goto-quit
)
7409 (org-defkey map
"\C-i" 'org-cycle
)
7410 (org-defkey map
[(tab)] 'org-cycle
)
7411 (org-defkey map
[(down)] 'outline-next-visible-heading
)
7412 (org-defkey map
[(up)] 'outline-previous-visible-heading
)
7413 (if org-goto-auto-isearch
7414 (if (fboundp 'define-key-after
)
7415 (define-key-after map
[t] 'org-goto-local-auto-isearch)
7417 (org-defkey map "q" 'org-goto-quit)
7418 (org-defkey map "n" 'outline-next-visible-heading)
7419 (org-defkey map "p" 'outline-previous-visible-heading)
7420 (org-defkey map "f" 'outline-forward-same-level)
7421 (org-defkey map "b" 'outline-backward-same-level)
7422 (org-defkey map "u" 'outline-up-heading))
7423 (org-defkey map "/" 'org-occur)
7424 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7425 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7426 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7427 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7428 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7431 (defconst org-goto-help
7432 "Browse buffer copy, to find location or copy text.%s
7433 RET=jump to location C-g=quit and return to previous location
7434 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7436 (defvar org-goto-start-pos) ; dynamically scoped parameter
7438 (defun org-goto (&optional alternative-interface)
7439 "Look up a different location in the current file, keeping current visibility.
7441 When you want look-up or go to a different location in a
7442 document, the fastest way is often to fold the entire buffer and
7443 then dive into the tree. This method has the disadvantage, that
7444 the previous location will be folded, which may not be what you
7447 This command works around this by showing a copy of the current
7448 buffer in an indirect buffer, in overview mode. You can dive
7449 into the tree in that copy, use org-occur and incremental search
7450 to find a location. When pressing RET or `Q', the command
7451 returns to the original buffer in which the visibility is still
7452 unchanged. After RET it will also jump to the location selected
7453 in the indirect buffer and expose the headline hierarchy above.
7455 With a prefix argument, use the alternative interface: e.g., if
7456 `org-goto-interface' is `outline' use `outline-path-completion'."
7459 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7460 (org-refile-use-outline-path t)
7461 (org-refile-target-verify-function nil)
7463 (if (not alternative-interface)
7465 (if (eq org-goto-interface 'outline)
7466 'outline-path-completion
7468 (org-goto-start-pos (point))
7470 (if (eq interface 'outline)
7471 (car (org-get-location (current-buffer) org-goto-help))
7472 (let ((pa (org-refile-get-location "Goto")))
7473 (org-refile-check-position pa)
7477 (org-mark-ring-push org-goto-start-pos)
7478 (goto-char selected-point)
7479 (when (or (org-invisible-p) (org-invisible-p2))
7480 (org-show-context 'org-goto)))
7483 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7484 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7485 (defvar org-goto-local-auto-isearch-map) ; defined below
7487 (defun org-get-location (_buf help)
7488 "Let the user select a location in current buffer.
7489 This function uses a recursive edit. It returns the selected position
7492 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7493 (isearch-hide-immediately nil)
7494 (isearch-search-fun-function
7495 (lambda () 'org-goto-local-search-headings))
7496 (org-goto-selected-point org-goto-exit-command))
7498 (save-window-excursion
7499 (delete-other-windows)
7500 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7501 (pop-to-buffer-same-window
7503 (make-indirect-buffer (current-buffer) "*org-goto*")
7504 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7505 (with-output-to-temp-buffer "*Org Help*"
7506 (princ (format help (if org-goto-auto-isearch
7507 " Just type for auto-isearch."
7508 " n/p/f/b/u to navigate, q to quit."))))
7509 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7510 (setq buffer-read-only nil)
7511 (let ((org-startup-truncated t)
7512 (org-startup-folded nil)
7513 (org-startup-align-all-tables nil))
7516 (setq buffer-read-only t)
7517 (if (and (boundp 'org-goto-start-pos)
7518 (integer-or-marker-p org-goto-start-pos))
7519 (progn (goto-char org-goto-start-pos)
7520 (when (org-invisible-p)
7521 (org-show-set-visibility 'lineage)))
7522 (goto-char (point-min)))
7523 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7524 (message "Select location and press RET")
7525 (use-local-map org-goto-map)
7527 (kill-buffer "*org-goto*")
7528 (cons org-goto-selected-point org-goto-exit-command))))
7530 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7531 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7532 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7533 (if (fboundp 'isearch-other-control-char)
7535 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7536 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7537 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7538 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7539 (define-key org-goto-local-auto-isearch-map [return] nil))
7541 (defun org-goto-local-search-headings (string bound noerror)
7542 "Search and make sure that any matches are in headlines."
7544 (while (if isearch-forward
7545 (search-forward string bound noerror)
7546 (search-backward string bound noerror))
7547 (when (save-match-data
7548 (and (save-excursion
7550 (looking-at org-complex-heading-regexp))
7551 (or (not (match-beginning 5))
7552 (< (point) (match-beginning 5)))))
7553 (throw 'return (point))))))
7555 (defun org-goto-local-auto-isearch ()
7558 (goto-char (point-min))
7559 (let ((keys (this-command-keys)))
7560 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7562 (isearch-process-search-char (string-to-char keys)))))
7564 (defun org-goto-ret (&optional _arg)
7565 "Finish `org-goto' by going to the new location."
7567 (setq org-goto-selected-point (point))
7568 (setq org-goto-exit-command 'return)
7571 (defun org-goto-left ()
7572 "Finish `org-goto' by going to the new location."
7574 (if (org-at-heading-p)
7576 (beginning-of-line 1)
7577 (setq org-goto-selected-point (point)
7578 org-goto-exit-command 'left)
7580 (user-error "Not on a heading")))
7582 (defun org-goto-right ()
7583 "Finish `org-goto' by going to the new location."
7585 (if (org-at-heading-p)
7587 (setq org-goto-selected-point (point)
7588 org-goto-exit-command 'right)
7590 (user-error "Not on a heading")))
7592 (defun org-goto-quit ()
7593 "Finish `org-goto' without cursor motion."
7595 (setq org-goto-selected-point nil)
7596 (setq org-goto-exit-command 'quit)
7599 ;;; Indirect buffer display of subtrees
7601 (defvar org-indirect-dedicated-frame nil
7602 "This is the frame being used for indirect tree display.")
7603 (defvar org-last-indirect-buffer nil)
7605 (defun org-tree-to-indirect-buffer (&optional arg)
7606 "Create indirect buffer and narrow it to current subtree.
7608 With a numerical prefix ARG, go up to this level and then take that tree.
7609 If ARG is negative, go up that many levels.
7611 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7612 indirect buffer previously made with this command, to avoid proliferation of
7613 indirect buffers. However, when you call the command with a \
7614 `\\[universal-argument]' prefix, or
7615 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7616 so that you can work with several indirect buffers at the same time. If
7617 `org-indirect-buffer-display' is `dedicated-frame', the \
7618 `\\[universal-argument]' prefix also
7619 requests that a new frame be made for the new buffer, so that the dedicated
7620 frame is not changed."
7622 (let ((cbuf (current-buffer))
7623 (cwin (selected-window))
7625 beg end level heading ibuf)
7627 (org-back-to-heading t)
7629 (setq level (org-outline-level))
7630 (when (< arg 0) (setq arg (+ level arg)))
7631 (while (> (setq level (org-outline-level)) arg)
7632 (org-up-heading-safe)))
7634 heading (org-get-heading 'no-tags))
7635 (org-end-of-subtree t t)
7636 (when (org-at-heading-p) (backward-char 1))
7638 (when (and (buffer-live-p org-last-indirect-buffer)
7639 (not (eq org-indirect-buffer-display 'new-frame))
7641 (kill-buffer org-last-indirect-buffer))
7642 (setq ibuf (org-get-indirect-buffer cbuf heading)
7643 org-last-indirect-buffer ibuf)
7645 ((or (eq org-indirect-buffer-display 'new-frame)
7646 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7647 (select-frame (make-frame))
7648 (delete-other-windows)
7649 (pop-to-buffer-same-window ibuf)
7650 (org-set-frame-title heading))
7651 ((eq org-indirect-buffer-display 'dedicated-frame)
7653 (select-frame (or (and org-indirect-dedicated-frame
7654 (frame-live-p org-indirect-dedicated-frame)
7655 org-indirect-dedicated-frame)
7656 (setq org-indirect-dedicated-frame (make-frame)))))
7657 (delete-other-windows)
7658 (pop-to-buffer-same-window ibuf)
7659 (org-set-frame-title (concat "Indirect: " heading)))
7660 ((eq org-indirect-buffer-display 'current-window)
7661 (pop-to-buffer-same-window ibuf))
7662 ((eq org-indirect-buffer-display 'other-window)
7663 (pop-to-buffer ibuf))
7664 (t (error "Invalid value")))
7665 (narrow-to-region beg end)
7668 (run-hook-with-args 'org-cycle-hook 'all)
7669 (and (window-live-p cwin) (select-window cwin))))
7671 (defun org-get-indirect-buffer (&optional buffer heading)
7672 (setq buffer (or buffer (current-buffer)))
7673 (let ((n 1) (base (buffer-name buffer)) bname)
7674 (while (buffer-live-p
7678 (if heading (concat heading "-" (number-to-string n))
7679 (number-to-string n))))))
7682 (make-indirect-buffer buffer bname 'clone)
7683 (error (make-indirect-buffer buffer bname)))))
7685 (defun org-set-frame-title (title)
7686 "Set the title of the current frame to the string TITLE."
7687 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7689 ;;;; Structure editing
7691 ;;; Inserting headlines
7693 (defun org--line-empty-p (n)
7694 "Is the Nth next line empty?
7696 Counts the current line as N = 1 and the previous line as N = 0;
7697 see `beginning-of-line'."
7700 (or (beginning-of-line n) t)
7702 (looking-at "[ \t]*$")))))
7704 (defun org-previous-line-empty-p ()
7705 "Is the previous line a blank line?
7706 When NEXT is non-nil, check the next line instead."
7707 (org--line-empty-p 0))
7709 (defun org-next-line-empty-p ()
7710 "Is the previous line a blank line?
7711 When NEXT is non-nil, check the next line instead."
7712 (org--line-empty-p 2))
7714 (defun org--blank-before-heading-p (&optional parent)
7715 "Non-nil when an empty line should precede a new heading here.
7716 When optional argument PARENT is non-nil, consider parent
7717 headline instead of current one."
7718 (pcase (assq 'heading org-blank-before-new-entry)
7721 (org-with-limited-levels
7722 (unless (and (org-before-first-heading-p)
7723 (not (outline-next-heading)))
7724 (org-back-to-heading t)
7725 (when parent (org-up-heading-safe))
7727 (org-previous-line-empty-p))
7728 ((outline-next-heading)
7729 (org-previous-line-empty-p))
7730 ;; Ignore trailing spaces on last buffer line.
7731 ((progn (skip-chars-backward " \t") (bolp))
7732 (org-previous-line-empty-p))
7734 (`(heading . ,value) value)
7737 (defun org-insert-heading (&optional arg invisible-ok top)
7738 "Insert a new heading or an item with the same depth at point.
7740 If point is at the beginning of a heading, insert a new heading
7741 or a new headline above the current one. When at the beginning
7742 of a regular line of text, turn it into a heading.
7744 If point is in the middle of a line, split it and create a new
7745 headline with the text in the current line after point (see
7746 `org-M-RET-may-split-line' on how to modify this behavior). As
7747 a special case, on a headline, splitting can only happen on the
7748 title itself. E.g., this excludes breaking stars or tags.
7750 With a `\\[universal-argument]' prefix, set \
7751 `org-insert-heading-respect-content' to
7752 a non-nil value for the duration of the command. This forces the
7753 insertion of a heading after the current subtree, independently
7754 on the location of point.
7756 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7757 insert the heading at the end of the tree
7758 above the current heading. For example, if point is within a
7759 2nd-level heading, then it will insert a 2nd-level heading at
7760 the end of the 1st-level parent subtree.
7762 When INVISIBLE-OK is set, stop at invisible headlines when going
7763 back. This is important for non-interactive uses of the
7766 When optional argument TOP is non-nil, insert a level 1 heading,
7769 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7770 (level (org-current-level))
7771 (stars (make-string (if (and level (not top)) level 1) ?*)))
7773 ((or org-insert-heading-respect-content
7774 (member arg '((4) (16)))
7775 (and (not invisible-ok)
7776 (invisible-p (max (1- (point)) (point-min)))))
7777 ;; Position point at the location of insertion.
7778 (if (not level) ;before first headline
7779 (org-with-limited-levels (outline-next-heading))
7780 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7782 (org-with-limited-levels (org-back-to-heading invisible-ok))
7783 (cond ((equal arg '(16))
7784 (org-up-heading-safe)
7785 (org-end-of-subtree t t))
7787 (org-end-of-subtree t t))))
7788 (unless (bolp) (insert "\n")) ;ensure final newline
7789 (unless (and blank? (org-previous-line-empty-p))
7790 (org-N-empty-lines-before-current (if blank? 1 0)))
7791 (insert stars " \n")
7796 (when blank? (save-excursion (insert "\n")))
7797 (save-excursion (insert stars " \n"))
7798 (unless (and blank? (org-previous-line-empty-p))
7799 (org-N-empty-lines-before-current (if blank? 1 0)))
7801 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7802 (org-match-line org-complex-heading-regexp)
7803 (org-pos-in-match-range (point) 4))
7804 ;; Grab the text that should moved to the new headline.
7806 (let ((split (delete-and-extract-region (point) (match-end 4))))
7807 (if (looking-at "[ \t]*$") (replace-match "")
7808 (org-set-tags nil t))
7810 (when blank? (insert "\n"))
7811 (insert "\n" stars " ")
7812 (when (org-string-nw-p split) (insert split))
7813 (when (eobp) (save-excursion (insert "\n")))))
7816 (when blank? (insert "\n"))
7817 (insert "\n" stars " ")
7818 (when (eobp) (save-excursion (insert "\n"))))))
7819 ;; On regular text, turn line into a headline or split, if
7823 (unless (and blank? (org-previous-line-empty-p))
7824 (org-N-empty-lines-before-current (if blank? 1 0))))
7826 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7828 (insert "\n" stars " ")
7829 (unless (and blank? (org-previous-line-empty-p))
7830 (org-N-empty-lines-before-current (if blank? 1 0))))))
7831 (run-hooks 'org-insert-heading-hook))
7833 (defun org-N-empty-lines-before-current (n)
7834 "Make the number of empty lines before current exactly N.
7835 So this will delete or add empty lines."
7836 (let ((column (current-column)))
7839 (let ((start (save-excursion
7840 (skip-chars-backward " \r\t\n")
7841 (line-end-position))))
7842 (delete-region start (line-end-position 0))))
7843 (insert (make-string n ?\n))
7844 (move-to-column column)))
7846 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7847 "Return the heading of the current entry, without the stars.
7848 When NO-TAGS is non-nil, don't include tags.
7849 When NO-TODO is non-nil, don't include TODO keywords.
7850 When NO-PRIORITY is non-nil, don't include priority cookie.
7851 When NO-COMMENT is non-nil, don't include COMMENT string."
7853 (org-back-to-heading t)
7854 (let ((case-fold-search nil))
7855 (looking-at org-complex-heading-regexp)
7856 (let ((todo (and (not no-todo) (match-string 2)))
7857 (priority (and (not no-priority) (match-string 3)))
7858 (headline (pcase (match-string 4)
7860 ((and (guard no-comment) h)
7861 (replace-regexp-in-string
7863 (format "\\`%s[ \t]+" org-comment-string))
7866 (tags (and (not no-tags) (match-string 5))))
7867 (mapconcat #'identity
7868 (delq nil (list todo priority headline tags))
7871 (defvar orgstruct-mode) ; defined below
7873 (defun org-heading-components ()
7874 "Return the components of the current heading.
7875 This is a list with the following elements:
7876 - the level as an integer
7877 - the reduced level, different if `org-odd-levels-only' is set.
7878 - the TODO keyword, or nil
7879 - the priority character, like ?A, or nil if no priority is given
7880 - the headline text itself, or the tags string if no headline text
7881 - the tags string, or nil."
7883 (org-back-to-heading t)
7884 (when (let (case-fold-search)
7888 org-complex-heading-regexp)))
7890 (list (length (match-string 1))
7891 (org-reduced-level (length (match-string 1)))
7896 (list (length (match-string 1))
7897 (org-reduced-level (length (match-string 1)))
7898 (match-string-no-properties 2)
7899 (and (match-end 3) (aref (match-string 3) 2))
7900 (match-string-no-properties 4)
7901 (match-string-no-properties 5))))))
7903 (defun org-get-entry ()
7904 "Get the entry text, after heading, entire subtree."
7906 (org-back-to-heading t)
7907 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7909 (defun org-edit-headline (&optional heading)
7910 "Edit the current headline.
7911 Set it to HEADING when provided."
7913 (org-with-wide-buffer
7914 (org-back-to-heading t)
7915 (let ((case-fold-search nil))
7916 (when (looking-at org-complex-heading-regexp)
7917 (let* ((old (match-string-no-properties 4))
7918 (new (save-match-data
7919 (org-trim (or heading (read-string "Edit: " old))))))
7920 (unless (equal old new)
7921 (if old (replace-match new t t nil 4)
7922 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7924 (org-set-tags nil t)
7925 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7927 (defun org-insert-heading-after-current ()
7928 "Insert a new heading with same level as current, after current subtree."
7930 (org-back-to-heading)
7931 (org-insert-heading)
7932 (org-move-subtree-down)
7935 (defun org-insert-heading-respect-content (&optional invisible-ok)
7936 "Insert heading with `org-insert-heading-respect-content' set to t."
7938 (org-insert-heading '(4) invisible-ok))
7940 (defun org-insert-todo-heading-respect-content (&optional force-state)
7941 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7943 (org-insert-todo-heading force-state '(4)))
7945 (defun org-insert-todo-heading (arg &optional force-heading)
7946 "Insert a new heading with the same level and TODO state as current heading.
7948 If the heading has no TODO state, or if the state is DONE, use
7949 the first state (TODO by default). Also with one prefix arg,
7950 force first state. With two prefix args, force inserting at the
7951 end of the parent subtree.
7953 When called at a plain list item, insert a new item with an
7954 unchecked check box."
7956 (when (or force-heading (not (org-insert-item 'checkbox)))
7957 (org-insert-heading (or (and (equal arg '(16)) '(16))
7960 (org-forward-heading-same-level -1)
7961 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7963 (if (or (equal arg '(4))
7964 (not (match-beginning 2))
7965 (member (match-string 2) org-done-keywords))
7966 (car org-todo-keywords-1)
7970 (run-hook-with-args-until-success
7971 'org-todo-get-default-hook new-mark-x nil)
7973 (beginning-of-line 1)
7974 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7975 (if org-treat-insert-todo-heading-as-state-change
7977 (insert new-mark " "))))
7978 (when org-provide-todo-statistics
7979 (org-update-parent-todo-statistics))))
7981 (defun org-insert-subheading (arg)
7982 "Insert a new subheading and demote it.
7983 Works for outline headings and for plain lists alike."
7985 (org-insert-heading arg)
7987 ((org-at-heading-p) (org-do-demote))
7988 ((org-at-item-p) (org-indent-item))))
7990 (defun org-insert-todo-subheading (arg)
7991 "Insert a new subheading with TODO keyword or checkbox and demote it.
7992 Works for outline headings and for plain lists alike."
7994 (org-insert-todo-heading arg)
7996 ((org-at-heading-p) (org-do-demote))
7997 ((org-at-item-p) (org-indent-item))))
7999 ;;; Promotion and Demotion
8001 (defvar org-after-demote-entry-hook nil
8002 "Hook run after an entry has been demoted.
8003 The cursor will be at the beginning of the entry.
8004 When a subtree is being demoted, the hook will be called for each node.")
8006 (defvar org-after-promote-entry-hook nil
8007 "Hook run after an entry has been promoted.
8008 The cursor will be at the beginning of the entry.
8009 When a subtree is being promoted, the hook will be called for each node.")
8011 (defun org-promote-subtree ()
8012 "Promote the entire subtree.
8013 See also `org-promote'."
8016 (org-with-limited-levels (org-map-tree 'org-promote)))
8017 (org-fix-position-after-promote))
8019 (defun org-demote-subtree ()
8020 "Demote the entire subtree.
8021 See `org-demote' and `org-promote'."
8024 (org-with-limited-levels (org-map-tree 'org-demote)))
8025 (org-fix-position-after-promote))
8027 (defun org-do-promote ()
8028 "Promote the current heading higher up the tree.
8029 If the region is active in `transient-mark-mode', promote all
8030 headings in the region."
8033 (if (org-region-active-p)
8034 (org-map-region 'org-promote (region-beginning) (region-end))
8036 (org-fix-position-after-promote))
8038 (defun org-do-demote ()
8039 "Demote the current heading lower down the tree.
8040 If the region is active in `transient-mark-mode', demote all
8041 headings in the region."
8044 (if (org-region-active-p)
8045 (org-map-region 'org-demote (region-beginning) (region-end))
8047 (org-fix-position-after-promote))
8049 (defun org-fix-position-after-promote ()
8050 "Fix cursor position and indentation after demoting/promoting."
8051 (let ((pos (point)))
8052 (when (save-excursion
8054 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8055 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8056 (cond ((eobp) (insert " "))
8057 ((eolp) (insert " "))
8058 ((equal (char-after) ?\s) (forward-char 1))))))
8060 (defun org-current-level ()
8061 "Return the level of the current entry, or nil if before the first headline.
8062 The level is the number of stars at the beginning of the
8063 headline. Use `org-reduced-level' to remove the effect of
8064 `org-odd-levels'. Unlike to `org-outline-level', this function
8065 ignores inlinetasks."
8066 (let ((level (org-with-limited-levels (org-outline-level))))
8067 (and (> level 0) level)))
8069 (defun org-get-previous-line-level ()
8070 "Return the outline depth of the last headline before the current line.
8071 Returns 0 for the first headline in the buffer, and nil if before the
8073 (and (org-current-level)
8074 (or (and (/= (line-beginning-position) (point-min))
8075 (save-excursion (beginning-of-line 0) (org-current-level)))
8078 (defun org-reduced-level (l)
8079 "Compute the effective level of a heading.
8080 This takes into account the setting of `org-odd-levels-only'."
8083 (org-odd-levels-only (1+ (floor (/ l 2))))
8086 (defun org-level-increment ()
8087 "Return the number of stars that will be added or removed at a
8088 time to headlines when structure editing, based on the value of
8089 `org-odd-levels-only'."
8090 (if org-odd-levels-only 2 1))
8092 (defun org-get-valid-level (level &optional change)
8093 "Rectify a level change under the influence of `org-odd-levels-only'.
8094 LEVEL is a current level, CHANGE is by how much the level should
8095 be modified. Even if CHANGE is nil, LEVEL may be returned
8096 modified because even level numbers will become the next higher
8097 odd number. Returns values greater than 0."
8098 (if org-odd-levels-only
8099 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8100 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8101 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8102 (max 1 (+ level (or change 0)))))
8104 (defun org-promote ()
8105 "Promote the current heading higher up the tree."
8106 (org-with-wide-buffer
8107 (org-back-to-heading t)
8108 (let* ((after-change-functions (remq 'flyspell-after-change-function
8109 after-change-functions))
8110 (level (save-match-data (funcall outline-level)))
8111 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8112 (diff (abs (- level (length up-head) -1))))
8114 ((and (= level 1) org-allow-promoting-top-level-subtree)
8115 (replace-match "# " nil t))
8117 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8118 (t (replace-match up-head nil t)))
8120 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8121 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8122 (run-hooks 'org-after-promote-entry-hook))))
8124 (defun org-demote ()
8125 "Demote the current heading lower down the tree."
8126 (org-with-wide-buffer
8127 (org-back-to-heading t)
8128 (let* ((after-change-functions (remq 'flyspell-after-change-function
8129 after-change-functions))
8130 (level (save-match-data (funcall outline-level)))
8131 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8132 (diff (abs (- level (length down-head) -1))))
8133 (replace-match down-head nil t)
8134 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8135 (when org-adapt-indentation (org-fixup-indentation diff))
8136 (run-hooks 'org-after-demote-entry-hook))))
8138 (defun org-cycle-level ()
8139 "Cycle the level of an empty headline through possible states.
8140 This goes first to child, then to parent, level, then up the hierarchy.
8141 After top level, it switches back to sibling level."
8143 (let ((org-adapt-indentation nil))
8144 (when (org-point-at-end-of-empty-headline)
8145 (setq this-command 'org-cycle-level) ; Only needed for caching
8146 (let ((cur-level (org-current-level))
8147 (prev-level (org-get-previous-line-level)))
8149 ;; If first headline in file, promote to top-level.
8151 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8152 do (org-do-promote)))
8153 ;; If same level as prev, demote one.
8154 ((= prev-level cur-level)
8156 ;; If parent is top-level, promote to top level if not already.
8158 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8159 do (org-do-promote)))
8160 ;; If top-level, return to prev-level.
8162 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8163 do (org-do-demote)))
8164 ;; If less than prev-level, promote one.
8165 ((< cur-level prev-level)
8167 ;; If deeper than prev-level, promote until higher than
8169 ((> cur-level prev-level)
8170 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8171 do (org-do-promote))))
8174 (defun org-map-tree (fun)
8175 "Call FUN for every heading underneath the current one."
8176 (org-back-to-heading t)
8177 (let ((level (funcall outline-level)))
8181 (outline-next-heading)
8182 (> (funcall outline-level) level))
8186 (defun org-map-region (fun beg end)
8187 "Call FUN for every heading between BEG and END."
8188 (let ((org-ignore-region t))
8190 (setq end (copy-marker end))
8192 (when (and (re-search-forward org-outline-regexp-bol nil t)
8196 (outline-next-heading)
8201 (defun org-fixup-indentation (diff)
8202 "Change the indentation in the current entry by DIFF.
8204 DIFF is an integer. Indentation is done according to the
8207 - Planning information and property drawers are always indented
8208 according to the new level of the headline;
8210 - Footnote definitions and their contents are ignored;
8212 - Inlinetasks' boundaries are not shifted;
8214 - Empty lines are ignored;
8216 - Other lines' indentation are shifted by DIFF columns, unless
8217 it would introduce a structural change in the document, in
8218 which case no shifting is done at all.
8220 Assume point is at a heading or an inlinetask beginning."
8221 (org-with-wide-buffer
8222 (narrow-to-region (line-beginning-position)
8224 (if (org-with-limited-levels (org-at-heading-p))
8225 (org-with-limited-levels (outline-next-heading))
8226 (org-inlinetask-goto-end))
8229 ;; Indent properly planning info and property drawer.
8230 (when (looking-at-p org-planning-line-re)
8233 (when (looking-at org-property-drawer-re)
8234 (goto-char (match-end 0))
8236 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8238 (when (zerop diff) (throw 'no-shift nil))
8239 ;; If DIFF is negative, first check if a shift is possible at all
8240 ;; (e.g., it doesn't break structure). This can only happen if
8241 ;; some contents are not properly indented.
8242 (let ((case-fold-search t))
8244 (let ((diff (- diff))
8245 (forbidden-re (concat org-outline-regexp
8247 (substring org-footnote-definition-re 1))))
8251 ((looking-at-p "[ \t]*$") (forward-line))
8252 ((and (looking-at-p org-footnote-definition-re)
8253 (let ((e (org-element-at-point)))
8254 (and (eq (org-element-type e) 'footnote-definition)
8255 (goto-char (org-element-property :end e))))))
8256 ((looking-at-p org-outline-regexp) (forward-line))
8257 ;; Give up if shifting would move before column 0 or
8258 ;; if it would introduce a headline or a footnote
8261 (skip-chars-forward " \t")
8262 (let ((ind (current-column)))
8263 (when (or (< ind diff)
8264 (and (= ind diff) (looking-at-p forbidden-re)))
8265 (throw 'no-shift nil)))
8266 ;; Ignore contents of example blocks and source
8267 ;; blocks if their indentation is meant to be
8268 ;; preserved. Jump to block's closing line.
8270 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8271 (let ((e (org-element-at-point)))
8272 (and (memq (org-element-type e)
8273 '(example-block src-block))
8274 (or org-src-preserve-indentation
8275 (org-element-property :preserve-indent e))
8276 (goto-char (org-element-property :end e))
8277 (progn (skip-chars-backward " \r\t\n")
8280 (forward-line))))))))
8281 ;; Shift lines but footnote definitions, inlinetasks boundaries
8282 ;; by DIFF. Also skip contents of source or example blocks
8283 ;; when indentation is meant to be preserved.
8286 ((and (looking-at-p org-footnote-definition-re)
8287 (let ((e (org-element-at-point)))
8288 (and (eq (org-element-type e) 'footnote-definition)
8289 (goto-char (org-element-property :end e))))))
8290 ((looking-at-p org-outline-regexp) (forward-line))
8291 ((looking-at-p "[ \t]*$") (forward-line))
8293 (indent-line-to (+ (org-get-indentation) diff))
8295 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8296 (let ((e (org-element-at-point)))
8297 (and (memq (org-element-type e)
8298 '(example-block src-block))
8299 (or org-src-preserve-indentation
8300 (org-element-property :preserve-indent e))
8301 (goto-char (org-element-property :end e))
8302 (progn (skip-chars-backward " \r\t\n")
8305 (forward-line)))))))))
8307 (defun org-convert-to-odd-levels ()
8308 "Convert an Org file with all levels allowed to one with odd levels.
8309 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8312 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8313 (let ((outline-level 'org-outline-level)
8314 (org-odd-levels-only nil) n)
8316 (goto-char (point-min))
8317 (while (re-search-forward "^\\*\\*+ " nil t)
8318 (setq n (- (length (match-string 0)) 2))
8319 (while (>= (setq n (1- n)) 0)
8321 (end-of-line 1))))))
8323 (defun org-convert-to-oddeven-levels ()
8324 "Convert an Org file with only odd levels to one with odd/even levels.
8325 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8326 file contains a section with an even level, conversion would
8327 destroy the structure of the file. An error is signaled in this
8330 (goto-char (point-min))
8331 ;; First check if there are no even levels
8332 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8333 (org-show-set-visibility 'canonical)
8334 (error "Not all levels are odd in this file. Conversion not possible"))
8335 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8336 (let ((outline-regexp org-outline-regexp)
8337 (outline-level 'org-outline-level)
8338 (org-odd-levels-only nil) n)
8340 (goto-char (point-min))
8341 (while (re-search-forward "^\\*\\*+ " nil t)
8342 (setq n (/ (1- (length (match-string 0))) 2))
8343 (while (>= (setq n (1- n)) 0)
8345 (end-of-line 1))))))
8347 (defun org-tr-level (n)
8348 "Make N odd if required."
8349 (if org-odd-levels-only (1+ (/ n 2)) n))
8351 ;;; Vertical tree motion, cutting and pasting of subtrees
8353 (defun org-move-subtree-up (&optional arg)
8354 "Move the current subtree up past ARG headlines of the same level."
8356 (org-move-subtree-down (- (prefix-numeric-value arg))))
8358 (defun org-move-subtree-down (&optional arg)
8359 "Move the current subtree down past ARG headlines of the same level."
8361 (setq arg (prefix-numeric-value arg))
8362 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8363 'org-get-last-sibling))
8364 (ins-point (make-marker))
8366 (col (current-column))
8367 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8369 (org-back-to-heading)
8372 (setq ne-beg (org-back-over-empty-lines))
8375 (save-excursion (outline-end-of-heading)
8376 (setq folded (org-invisible-p)))
8377 (progn (org-end-of-subtree nil t)
8378 (unless (eobp) (backward-char))))
8379 (outline-next-heading)
8380 (setq ne-end (org-back-over-empty-lines))
8383 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8384 ;; include less whitespace
8387 (forward-line (- ne-beg ne-end))
8388 (setq beg (point))))
8389 ;; Find insertion point, with error handling
8391 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8392 (progn (goto-char beg0)
8393 (user-error "Cannot move past superior level or buffer limit")))
8394 (setq cnt (1- cnt)))
8396 ;; Moving forward - still need to move over subtree
8397 (org-end-of-subtree t t)
8399 (org-back-over-empty-lines)
8400 (or (bolp) (newline))))
8401 (setq ne-ins (org-back-over-empty-lines))
8402 (move-marker ins-point (point))
8403 (setq txt (buffer-substring beg end))
8404 (org-save-markers-in-region beg end)
8405 (delete-region beg end)
8406 (org-remove-empty-overlays-at beg)
8407 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8408 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8409 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8410 (let ((bbb (point)))
8411 (insert-before-markers txt)
8412 (org-reinstall-markers-in-region bbb)
8413 (move-marker ins-point bbb))
8414 (or (bolp) (insert "\n"))
8415 (setq ins-end (point))
8416 (goto-char ins-point)
8417 (org-skip-whitespace)
8418 (when (and (< arg 0)
8419 (org-first-sibling-p)
8421 ;; Move whitespace back to beginning
8424 (let ((kill-whole-line t))
8425 (kill-line (- ne-ins ne-beg)) (point)))
8426 (insert (make-string (- ne-ins ne-beg) ?\n)))
8427 (move-marker ins-point nil)
8429 (outline-hide-subtree)
8432 (org-cycle-hide-drawers 'children))
8433 (org-clean-visibility-after-subtree-move)
8434 ;; move back to the initial column we were at
8435 (move-to-column col)))
8437 (defvar org-subtree-clip ""
8438 "Clipboard for cut and paste of subtrees.
8439 This is actually only a copy of the kill, because we use the normal kill
8440 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8442 (defvar org-subtree-clip-folded nil
8443 "Was the last copied subtree folded?
8444 This is used to fold the tree back after pasting.")
8446 (defun org-cut-subtree (&optional n)
8447 "Cut the current subtree into the clipboard.
8448 With prefix arg N, cut this many sequential subtrees.
8449 This is a short-hand for marking the subtree and then cutting it."
8451 (org-copy-subtree n 'cut))
8453 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8454 "Copy the current subtree it in the clipboard.
8455 With prefix arg N, copy this many sequential subtrees.
8456 This is a short-hand for marking the subtree and then copying it.
8457 If CUT is non-nil, actually cut the subtree.
8458 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8459 of some markers in the region, even if CUT is non-nil. This is
8460 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8462 (let (beg end folded (beg0 (point)))
8463 (if (called-interactively-p 'any)
8464 (org-back-to-heading nil) ; take what looks like a subtree
8465 (org-back-to-heading t)) ; take what is really there
8467 (skip-chars-forward " \t\r\n")
8470 (outline-next-heading)
8471 (save-excursion (outline-end-of-heading)
8472 (setq folded (org-invisible-p)))
8473 (ignore-errors (org-forward-heading-same-level (1- n) t))
8474 (org-end-of-subtree t t)))
8475 ;; Include the end of an inlinetask
8476 (when (and (featurep 'org-inlinetask)
8477 (looking-at-p (concat (org-inlinetask-outline-regexp)
8483 (setq org-subtree-clip-folded folded)
8484 (when (or cut force-store-markers)
8485 (org-save-markers-in-region beg end))
8486 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8487 (setq org-subtree-clip (current-kill 0))
8488 (message "%s: Subtree(s) with %d characters"
8489 (if cut "Cut" "Copied")
8490 (length org-subtree-clip)))))
8492 (defun org-paste-subtree (&optional level tree for-yank remove)
8493 "Paste the clipboard as a subtree, with modification of headline level.
8494 The entire subtree is promoted or demoted in order to match a new headline
8497 If the cursor is at the beginning of a headline, the same level as
8498 that headline is used to paste the tree.
8500 If not, the new level is derived from the *visible* headings
8501 before and after the insertion point, and taken to be the inferior headline
8502 level of the two. So if the previous visible heading is level 3 and the
8503 next is level 4 (or vice versa), level 4 will be used for insertion.
8504 This makes sure that the subtree remains an independent subtree and does
8505 not swallow low level entries.
8507 You can also force a different level, either by using a numeric prefix
8508 argument, or by inserting the heading marker by hand. For example, if the
8509 cursor is after \"*****\", then the tree will be shifted to level 5.
8511 If optional TREE is given, use this text instead of the kill ring.
8513 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8514 move back over whitespace before inserting, and move point to the end of
8515 the inserted text when done.
8517 When REMOVE is non-nil, remove the subtree from the clipboard."
8519 (setq tree (or tree (and kill-ring (current-kill 0))))
8520 (unless (org-kill-is-subtree-p tree)
8522 (substitute-command-keys
8523 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8524 (org-with-limited-levels
8525 (let* ((visp (not (org-invisible-p)))
8527 (^re_ "\\(\\*+\\)[ \t]*")
8528 (old-level (if (string-match org-outline-regexp-bol txt)
8529 (- (match-end 0) (match-beginning 0) 1)
8531 (force-level (cond (level (prefix-numeric-value level))
8532 ((and (looking-at "[ \t]*$")
8534 "^\\*+$" (buffer-substring
8535 (point-at-bol) (point))))
8536 (- (match-end 0) (match-beginning 0)))
8538 (looking-at org-outline-regexp))
8539 (- (match-end 0) (point) 1))))
8540 (previous-level (save-excursion
8543 (outline-previous-visible-heading 1)
8544 (if (looking-at ^re_)
8545 (- (match-end 0) (match-beginning 0) 1)
8548 (next-level (save-excursion
8551 (or (looking-at org-outline-regexp)
8552 (outline-next-visible-heading 1))
8553 (if (looking-at ^re_)
8554 (- (match-end 0) (match-beginning 0) 1)
8557 (new-level (or force-level (max previous-level next-level)))
8558 (shift (if (or (= old-level -1)
8560 (= old-level new-level))
8562 (- new-level old-level)))
8563 (delta (if (> shift 0) -1 1))
8564 (func (if (> shift 0) 'org-demote 'org-promote))
8565 (org-odd-levels-only nil)
8567 ;; Remove the forced level indicator
8569 (delete-region (point-at-bol) (point)))
8571 (beginning-of-line (if (bolp) 1 2))
8573 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8574 (insert-before-markers txt)
8575 (unless (string-suffix-p "\n" txt) (insert "\n"))
8576 (setq newend (point))
8577 (org-reinstall-markers-in-region beg)
8580 (skip-chars-forward " \t\n\r")
8582 (when (and (org-invisible-p) visp)
8583 (save-excursion (outline-show-heading)))
8584 ;; Shift if necessary
8587 (narrow-to-region beg end)
8588 (while (not (= shift 0))
8589 (org-map-region func (point-min) (point-max))
8590 (setq shift (+ delta shift)))
8591 (goto-char (point-min))
8592 (setq newend (point-max))))
8593 (when (or (called-interactively-p 'interactive) for-yank)
8594 (message "Clipboard pasted as level %d subtree" new-level))
8595 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8597 (eq org-subtree-clip (current-kill 0))
8598 org-subtree-clip-folded)
8599 ;; The tree was folded before it was killed/copied
8600 (outline-hide-subtree))
8601 (and for-yank (goto-char newend))
8602 (and remove (setq kill-ring (cdr kill-ring))))))
8604 (defun org-kill-is-subtree-p (&optional txt)
8605 "Check if the current kill is an outline subtree, or a set of trees.
8606 Returns nil if kill does not start with a headline, or if the first
8607 headline level is not the largest headline level in the tree.
8608 So this will actually accept several entries of equal levels as well,
8609 which is OK for `org-paste-subtree'.
8610 If optional TXT is given, check this string instead of the current kill."
8611 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8612 (re (org-get-limited-outline-regexp))
8613 (^re (concat "^" re))
8614 (start-level (and kill
8616 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8618 (- (match-end 2) (match-beginning 2) 1)))
8619 (start (1+ (or (match-beginning 2) -1))))
8620 (if (not start-level)
8622 nil) ;; does not even start with a heading
8624 (while (setq start (string-match ^re kill (1+ start)))
8625 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8629 (defvar org-markers-to-move nil
8630 "Markers that should be moved with a cut-and-paste operation.
8631 Those markers are stored together with their positions relative to
8632 the start of the region.")
8634 (defun org-save-markers-in-region (beg end)
8635 "Check markers in region.
8636 If these markers are between BEG and END, record their position relative
8637 to BEG, so that after moving the block of text, we can put the markers back
8639 This function gets called just before an entry or tree gets cut from the
8640 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8641 called immediately, to move the markers with the entries."
8642 (setq org-markers-to-move nil)
8643 (when (featurep 'org-clock)
8644 (org-clock-save-markers-for-cut-and-paste beg end))
8645 (when (featurep 'org-agenda)
8646 (org-agenda-save-markers-for-cut-and-paste beg end)))
8648 (defun org-check-and-save-marker (marker beg end)
8649 "Check if MARKER is between BEG and END.
8650 If yes, remember the marker and the distance to BEG."
8651 (when (and (marker-buffer marker)
8652 (equal (marker-buffer marker) (current-buffer))
8653 (>= marker beg) (< marker end))
8654 (push (cons marker (- marker beg)) org-markers-to-move)))
8656 (defun org-reinstall-markers-in-region (beg)
8657 "Move all remembered markers to their position relative to BEG."
8658 (dolist (x org-markers-to-move)
8659 (move-marker (car x) (+ beg (cdr x))))
8660 (setq org-markers-to-move nil))
8662 (defun org-narrow-to-subtree ()
8663 "Narrow buffer to the current subtree."
8667 (org-with-limited-levels
8669 (progn (org-back-to-heading t) (point))
8670 (progn (org-end-of-subtree t t)
8671 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8674 (defun org-narrow-to-block ()
8675 "Narrow buffer to the current block."
8677 (let* ((case-fold-search t)
8678 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8679 "^[ \t]*#\\+end_.*")))
8681 (narrow-to-region (car blockp) (cdr blockp))
8682 (user-error "Not in a block"))))
8684 (defun org-clone-subtree-with-time-shift (n &optional shift)
8685 "Clone the task (subtree) at point N times.
8686 The clones will be inserted as siblings.
8688 In interactive use, the user will be prompted for the number of
8689 clones to be produced. If the entry has a timestamp, the user
8690 will also be prompted for a time shift, which may be a repeater
8691 as used in time stamps, for example `+3d'. To disable this,
8692 you can call the function with a universal prefix argument.
8694 When a valid repeater is given and the entry contains any time
8695 stamps, the clones will become a sequence in time, with time
8696 stamps in the subtree shifted for each clone produced. If SHIFT
8697 is nil or the empty string, time stamps will be left alone. The
8698 ID property of the original subtree is removed.
8700 In each clone, all the CLOCK entries will be removed. This
8701 prevents Org from considering that the clocked times overlap.
8703 If the original subtree did contain time stamps with a repeater,
8704 the following will happen:
8705 - the repeater will be removed in each clone
8706 - an additional clone will be produced, with the current, unshifted
8707 date(s) in the entry.
8708 - the original entry will be placed *after* all the clones, with
8710 - the start days in the repeater in the original entry will be shifted
8711 to past the last clone.
8712 In this way you can spell out a number of instances of a repeating task,
8713 and still retain the repeater to cover future instances of the task.
8715 As described above, N+1 clones are produced when the original
8716 subtree has a repeater. Setting N to 0, then, can be used to
8717 remove the repeater from a subtree and create a shifted clone
8718 with the original repeater."
8719 (interactive "nNumber of clones to produce: ")
8720 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8721 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8722 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8723 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8726 (if (and (not (equal current-prefix-arg '(4)))
8729 (re-search-forward org-ts-regexp-both end-of-tree t)))
8730 (read-from-minibuffer
8731 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8732 ""))) ;No time shift
8734 (and (org-string-nw-p shift)
8735 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8737 (user-error "Invalid shift specification %s" shift)))))
8738 (goto-char end-of-tree)
8739 (unless (bolp) (insert "\n"))
8740 (let* ((end (point))
8741 (template (buffer-substring beg end))
8742 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8743 (shift-what (pcase (and doshift (match-string 2 shift))
8746 ("w" (setq shift-n (* 7 shift-n)) 'day)
8749 (_ (error "Unsupported time unit"))))
8753 (idprop (org-entry-get nil "ID")))
8755 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8757 (delete-region beg end)
8760 (setq nmax (1+ nmax))
8761 (setq n-no-remove nmax))
8763 (cl-loop for n from nmin to nmax do
8769 (goto-char (point-min))
8771 (and idprop (if org-clone-delete-id
8772 (org-entry-delete nil "ID")
8773 (org-id-get-create t)))
8775 (while (re-search-forward org-clock-line-re nil t)
8776 (delete-region (line-beginning-position)
8777 (line-beginning-position 2)))
8778 (goto-char (point-min))
8779 (while (re-search-forward org-drawer-regexp nil t)
8780 (org-remove-empty-drawer-at (point))))
8781 (goto-char (point-min))
8783 (while (re-search-forward org-ts-regexp-both nil t)
8784 (org-timestamp-change (* n shift-n) shift-what))
8785 (unless (= n n-no-remove)
8786 (goto-char (point-min))
8787 (while (re-search-forward org-ts-regexp nil t)
8789 (goto-char (match-beginning 0))
8790 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8791 (delete-region (match-beginning 1) (match-end 1)))))))
8797 (defun org-sort (&optional with-case)
8798 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8799 Optional argument WITH-CASE means sort case-sensitively."
8802 (cond ((org-at-table-p) #'org-table-sort-lines)
8803 ((org-at-item-p) #'org-sort-list)
8804 (t #'org-sort-entries))
8807 (defun org-sort-remove-invisible (s)
8808 "Remove invisible part of links and emphasis markers from string S."
8809 (remove-text-properties 0 (length s) org-rm-props s)
8810 (replace-regexp-in-string
8811 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8812 (replace-regexp-in-string
8813 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8814 (org-link-display-format s)
8817 (defvar org-priority-regexp) ; defined later in the file
8819 (defvar org-after-sorting-entries-or-items-hook nil
8820 "Hook that is run after a bunch of entries or items have been sorted.
8821 When children are sorted, the cursor is in the parent line when this
8822 hook gets called. When a region or a plain list is sorted, the cursor
8823 will be in the first entry of the sorted region/list.")
8825 (defun org-sort-entries
8826 (&optional with-case sorting-type getkey-func compare-func property
8828 "Sort entries on a certain level of an outline tree.
8829 If there is an active region, the entries in the region are sorted.
8830 Else, if the cursor is before the first entry, sort the top-level items.
8831 Else, the children of the entry at point are sorted.
8833 Sorting can be alphabetically, numerically, by date/time as given by
8834 a time stamp, by a property, by priority order, or by a custom function.
8836 The command prompts for the sorting type unless it has been given to the
8837 function through the SORTING-TYPE argument, which needs to be a character,
8838 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8839 the precise meaning of each character:
8841 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8842 c By creation time, which is assumed to be the first inactive time stamp
8843 at the beginning of a line.
8844 d By deadline date/time.
8846 n Numerically, by converting the beginning of the entry/item to a number.
8847 o By order of TODO keywords.
8848 p By priority according to the cookie.
8849 r By the value of a property.
8850 s By scheduled date/time.
8851 t By date/time, either the first active time stamp in the entry, or, if
8852 none exist, by the first inactive one.
8854 Capital letters will reverse the sort order.
8856 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8857 called with point at the beginning of the record. It must return a
8858 value that is compatible with COMPARE-FUNC, the function used to
8861 Comparing entries ignores case by default. However, with an optional argument
8862 WITH-CASE, the sorting considers case as well.
8864 Sorting is done against the visible part of the headlines, it ignores hidden
8867 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8869 A non-nil value for INTERACTIVE? is used to signal that this
8870 function is being called interactively."
8871 (interactive (list current-prefix-arg nil nil nil nil t))
8872 (let ((case-func (if with-case 'identity 'downcase))
8873 start beg end stars re re2
8875 ;; Find beginning and end of region to sort
8877 ((org-region-active-p)
8878 ;; we will sort the region
8879 (setq end (region-end)
8881 (goto-char (region-beginning))
8882 (unless (org-at-heading-p) (outline-next-heading))
8883 (setq start (point)))
8884 ((or (org-at-heading-p)
8885 (ignore-errors (progn (org-back-to-heading) t)))
8886 ;; we will sort the children of the current headline
8887 (org-back-to-heading)
8889 end (progn (org-end-of-subtree t t)
8890 (or (bolp) (insert "\n"))
8891 (when (>= (org-back-over-empty-lines) 1)
8896 (outline-show-subtree)
8897 (outline-next-heading))
8899 ;; we will sort the top-level entries in this file
8900 (goto-char (point-min))
8901 (or (org-at-heading-p) (outline-next-heading))
8902 (setq start (point))
8903 (goto-char (point-max))
8904 (beginning-of-line 1)
8905 (when (looking-at ".*?\\S-")
8906 ;; File ends in a non-white line
8909 (setq end (point-max))
8910 (setq what "top-level")
8912 (outline-show-all)))
8915 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8917 (looking-at "\\(\\*+\\)")
8918 (setq stars (match-string 1)
8919 re (concat "^" (regexp-quote stars) " +")
8920 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8921 txt (buffer-substring beg end))
8922 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8923 (when (and (not (equal stars "*")) (string-match re2 txt))
8924 (user-error "Region to sort contains a level above the first entry"))
8926 (unless sorting-type
8928 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8929 [t]ime
[s]cheduled [d]eadline [c]reated cloc[k]ing
8930 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8932 (setq sorting-type (read-char-exclusive)))
8935 (and (= (downcase sorting-type) ?f)
8937 (or (and interactive?
8939 "Function for extracting keys: "))
8940 (error "Missing key extractor")))))
8942 (and (= (downcase sorting-type) ?r)
8945 (completing-read "Property: "
8946 (mapcar #'list (org-buffer-property-keys t))
8949 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8950 (message "Sorting entries...")
8953 (narrow-to-region start end)
8954 (let ((restore-clock?
8955 ;; The clock marker is lost when using `sort-subr'; mark
8956 ;; the clock with temporary `:org-clock-marker-backup'
8958 (when (and (eq (org-clock-is-active) (current-buffer))
8959 (<= start (marker-position org-clock-marker))
8960 (>= end (marker-position org-clock-marker)))
8961 (org-with-silent-modifications
8962 (put-text-property (1- org-clock-marker) org-clock-marker
8963 :org-clock-marker-backup t))
8965 (dcst (downcase sorting-type))
8966 (case-fold-search nil)
8967 (now (current-time)))
8969 (/= dcst sorting-type)
8970 ;; This function moves to the beginning character of the "record" to
8973 (if (re-search-forward re nil t)
8974 (goto-char (match-beginning 0))
8975 (goto-char (point-max))))
8976 ;; This function moves to the last character of the "record" being
8981 (outline-forward-same-level 1)
8983 (goto-char (point-max))))))
8984 ;; This function returns the value that gets sorted against.
8988 (if (looking-at org-complex-heading-regexp)
8989 (string-to-number (org-sort-remove-invisible (match-string 4)))
8992 (if (looking-at org-complex-heading-regexp)
8993 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8996 (or (get-text-property (point) :org-clock-minutes) 0))
8998 (let ((end (save-excursion (outline-next-heading) (point))))
8999 (if (or (re-search-forward org-ts-regexp end t)
9000 (re-search-forward org-ts-regexp-both end t))
9001 (org-time-string-to-seconds (match-string 0))
9004 (let ((end (save-excursion (outline-next-heading) (point))))
9005 (if (re-search-forward
9006 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9008 (org-time-string-to-seconds (match-string 0))
9011 (let ((end (save-excursion (outline-next-heading) (point))))
9012 (if (re-search-forward org-scheduled-time-regexp end t)
9013 (org-time-string-to-seconds (match-string 1))
9016 (let ((end (save-excursion (outline-next-heading) (point))))
9017 (if (re-search-forward org-deadline-time-regexp end t)
9018 (org-time-string-to-seconds (match-string 1))
9021 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9022 (string-to-char (match-string 2))
9023 org-default-priority))
9025 (or (org-entry-get nil property) ""))
9027 (when (looking-at org-complex-heading-regexp)
9028 (let* ((m (match-string 2))
9029 (s (if (member m org-done-keywords) '- '+)))
9030 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9034 (setq tmp (funcall getkey-func))
9035 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9037 (error "Invalid key function `%s'" getkey-func)))
9038 (t (error "Invalid sorting type `%c'" sorting-type))))
9041 ((= dcst ?a) 'string<)
9046 (concat "Function for comparing keys "
9047 "(empty for default `sort-subr' predicate): ")
9049 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
9050 (when restore-clock?
9051 (move-marker org-clock-marker
9052 (1+ (next-single-property-change
9053 start :org-clock-marker-backup)))
9054 (remove-text-properties (1- org-clock-marker) org-clock-marker
9055 '(:org-clock-marker-backup t)))))
9056 (run-hooks 'org-after-sorting-entries-or-items-hook)
9057 (message "Sorting entries...done")))
9059 ;;; The orgstruct minor mode
9061 ;; Define a minor mode which can be used in other modes in order to
9062 ;; integrate the Org mode structure editing commands.
9064 ;; This is really a hack, because the Org mode structure commands use
9065 ;; keys which normally belong to the major mode. Here is how it
9066 ;; works: The minor mode defines all the keys necessary to operate the
9067 ;; structure commands, but wraps the commands into a function which
9068 ;; tests if the cursor is currently at a headline or a plain list
9069 ;; item. If that is the case, the structure command is used,
9070 ;; temporarily setting many Org mode variables like regular
9071 ;; expressions for filling etc. However, when any of those keys is
9072 ;; used at a different location, function uses `key-binding' to look
9073 ;; up if the key has an associated command in another currently active
9074 ;; keymap (minor modes, major mode, global), and executes that
9075 ;; command. There might be problems if any of the keys is otherwise
9076 ;; used as a prefix key.
9078 (defcustom orgstruct-heading-prefix-regexp ""
9079 "Regexp that matches the custom prefix of Org headlines in
9080 orgstruct(++)-mode."
9083 :package-version '(Org . "8.3")
9085 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9087 (defcustom orgstruct-setup-hook nil
9088 "Hook run after orgstruct-mode-map is filled."
9091 :package-version '(Org . "8.0")
9094 (defvar orgstruct-initialized nil)
9096 (defvar org-local-vars nil
9097 "List of local variables, for use by `orgstruct-mode'.")
9100 (define-minor-mode orgstruct-mode
9101 "Toggle the minor mode `orgstruct-mode'.
9102 This mode is for using Org mode structure commands in other
9103 modes. The following keys behave as if Org mode were active, if
9104 the cursor is on a headline, or on a plain list item (both as
9105 defined by Org mode)."
9106 nil " OrgStruct" (make-sparse-keymap)
9107 (funcall (if orgstruct-mode
9108 'add-to-invisibility-spec
9109 'remove-from-invisibility-spec)
9111 (when orgstruct-mode
9112 (org-load-modules-maybe)
9113 (unless orgstruct-initialized
9115 (setq orgstruct-initialized t))))
9118 (defun turn-on-orgstruct ()
9119 "Unconditionally turn on `orgstruct-mode'."
9122 (defvar-local orgstruct-is-++ nil
9123 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9124 (defvar-local org-fb-vars nil)
9125 (defun orgstruct++-mode (&optional arg)
9126 "Toggle `orgstruct-mode', the enhanced version of it.
9127 In addition to setting orgstruct-mode, this also exports all
9128 indentation and autofilling variables from Org mode into the
9129 buffer. It will also recognize item context in multiline items."
9131 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9133 (progn (orgstruct-mode -1)
9134 (dolist (v org-fb-vars)
9135 (set (make-local-variable (car v))
9136 (if (eq (car-safe (cadr v)) 'quote)
9140 (setq org-fb-vars nil)
9141 (unless org-local-vars
9142 (setq org-local-vars (org-get-local-variables)))
9144 (dolist (x org-local-vars)
9146 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9147 \\|fill-prefix\\|indent-\\)"
9148 (symbol-name (car x)))
9149 (setq var (car x) val (nth 1 x))
9150 (push (list var `(quote ,(eval var))) org-fb-vars)
9151 (set (make-local-variable var)
9152 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9153 (setq-local orgstruct-is-++ t))))
9156 (defun turn-on-orgstruct++ ()
9157 "Unconditionally turn on `orgstruct++-mode'."
9158 (orgstruct++-mode 1))
9160 (defun orgstruct-error ()
9161 "Error when there is no default binding for a structure key."
9163 (funcall (if (fboundp 'user-error)
9166 "This key has no function outside structure elements"))
9168 (defun orgstruct-setup ()
9169 "Setup orgstruct keymap."
9170 (dolist (cell '((org-demote . t)
9174 (org-shiftmetaleft . t)
9175 (org-shiftmetaright . t)
9176 org-backward-element
9177 org-backward-heading-same-level
9182 org-force-cycle-archived
9183 org-forward-heading-same-level
9185 org-insert-heading-respect-content
9186 org-kill-note-or-show-branches
9191 org-narrow-to-subtree
9207 outline-next-visible-heading
9208 outline-previous-visible-heading
9210 outline-up-heading))
9211 (let ((f (or (car-safe cell) cell))
9212 (disable-when-heading-prefix (cdr-safe cell)))
9214 (let ((new-bindings))
9215 (dolist (binding (nconc (where-is-internal f org-mode-map)
9216 (where-is-internal f outline-mode-map)))
9217 (push binding new-bindings)
9218 ;; TODO use local-function-key-map
9219 (dolist (rep '(("<tab>" . "TAB")
9220 ("<return>" . "RET")
9221 ("<escape>" . "ESC")
9222 ("<delete>" . "DEL")))
9223 (setq binding (read-kbd-macro
9224 (let ((case-fold-search))
9225 (replace-regexp-in-string
9226 (regexp-quote (cdr rep))
9228 (key-description binding)))))
9229 (cl-pushnew binding new-bindings :test 'equal)))
9230 (dolist (binding new-bindings)
9231 (let ((key (lookup-key orgstruct-mode-map binding)))
9232 (when (or (not key) (numberp key))
9234 (org-defkey orgstruct-mode-map
9236 (orgstruct-make-binding
9237 f binding disable-when-heading-prefix))))))))))
9238 (run-hooks 'orgstruct-setup-hook))
9240 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9241 "Create a function for binding in the structure minor mode.
9242 FUN is the command to call inside a table. KEY is the key that
9243 should be checked in for a command to execute outside of tables.
9244 Non-nil `disable-when-heading-prefix' means to disable the command
9245 if `orgstruct-heading-prefix-regexp' is not empty."
9246 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9249 (while (fboundp (intern nname))
9250 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9251 (setq name (intern nname)))
9253 (let ((bindings '((org-heading-regexp
9255 orgstruct-heading-prefix-regexp
9256 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9258 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9259 (org-outline-regexp-bol
9260 (concat "^" org-outline-regexp))
9261 (outline-regexp org-outline-regexp)
9262 (outline-heading-end-regexp "\n")
9263 (outline-level 'org-outline-level)
9264 (outline-heading-alist))))
9266 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9267 "Outside of structure, run the binding of `"
9268 (key-description key) "'."
9269 (when disable-when-heading-prefix
9271 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9272 "back to the default binding due to limitations of Org's implementation of\n"
9273 "`" (symbol-name fun) "'.")))
9276 ,(and disable-when-heading-prefix
9277 '(not (string= orgstruct-heading-prefix-regexp ""))))
9282 (org-context-p 'headline 'item
9284 '(org-insert-heading
9285 org-insert-heading-respect-content
9287 '(when orgstruct-is-++
9290 (let* ((orgstruct-mode)
9297 ("<\\([^>]*\\)tab>" . "\\1TAB")
9298 ("<\\([^>]*\\)return>" . "\\1RET")
9299 ("<\\([^>]*\\)escape>" . "\\1ESC")
9300 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9303 (setq key (read-kbd-macro
9304 (let ((case-fold-search))
9305 (replace-regexp-in-string
9308 (key-description key))))))
9309 (when (key-binding key)
9310 (throw 'exit (key-binding key))))))))
9311 (if (keymapp binding)
9312 (org-set-transient-map binding)
9313 (let ((func (or binding
9315 'orgstruct-error))))
9317 (call-interactively func)))))
9318 (org-run-like-in-org-mode
9322 (call-interactively ',fun)))))))))
9325 (defun org-contextualize-keys (alist contexts)
9326 "Return valid elements in ALIST depending on CONTEXTS.
9328 `org-agenda-custom-commands' or `org-capture-templates' are the
9329 values used for ALIST, and `org-agenda-custom-commands-contexts'
9330 or `org-capture-templates-contexts' are the associated contexts
9333 ;; normalize contexts
9335 (lambda(c) (cond ((listp (cadr c))
9336 (list (car c) (car c) (nth 1 c)))
9337 ((string= "" (cadr c))
9338 (list (car c) (car c) (nth 2 c)))
9342 ;; loop over all commands or templates
9346 ((not (assoc (car c) contexts))
9348 ((and (assoc (car c) contexts)
9349 (setq vrules (org-contextualize-validate-key
9352 (unless (equal (car vr) (cadr vr))
9355 (if (not repl) (push c r)
9356 (push (cadr repl) s)
9359 (cdr (or (assoc (cadr repl) alist)
9360 (error "Undefined key `%s' as contextual replacement for `%s'"
9361 (cadr repl) (car c)))))
9363 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9368 (let ((tpl (car x)))
9377 (defun org-contextualize-validate-key (key contexts)
9378 "Check CONTEXTS for agenda or capture KEY."
9380 (dolist (r contexts)
9381 (dolist (rr (car (last r)))
9383 (and (equal key (car r))
9384 (if (functionp rr) (funcall rr)
9385 (or (and (eq (car rr) 'in-file)
9387 (string-match (cdr rr) (buffer-file-name)))
9388 (and (eq (car rr) 'in-mode)
9389 (string-match (cdr rr) (symbol-name major-mode)))
9390 (and (eq (car rr) 'in-buffer)
9391 (string-match (cdr rr) (buffer-name)))
9392 (when (and (eq (car rr) 'not-in-file)
9394 (not (string-match (cdr rr) (buffer-file-name))))
9395 (when (eq (car rr) 'not-in-mode)
9396 (not (string-match (cdr rr) (symbol-name major-mode))))
9397 (when (eq (car rr) 'not-in-buffer)
9398 (not (string-match (cdr rr) (buffer-name)))))))
9400 (delete-dups (delq nil res))))
9402 (defun org-context-p (&rest contexts)
9403 "Check if local context is any of CONTEXTS.
9404 Possible values in the list of contexts are `table', `headline', and `item'."
9405 (let ((pos (point)))
9406 (goto-char (point-at-bol))
9407 (prog1 (or (and (memq 'table contexts)
9408 (looking-at "[ \t]*|"))
9409 (and (memq 'headline contexts)
9410 (looking-at org-outline-regexp))
9411 (and (memq 'item contexts)
9412 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9413 (and (memq 'item-body contexts)
9418 (defun org-run-like-in-org-mode (cmd)
9419 "Run a command, pretending that the current buffer is in Org mode.
9420 This will temporarily bind local variables that are typically bound in
9421 Org mode to the values they have in Org mode, and then interactively
9423 (org-load-modules-maybe)
9424 (unless org-local-vars
9425 (setq org-local-vars (org-get-local-variables)))
9427 (dolist (var org-local-vars)
9428 (when (or (not (boundp (car var)))
9429 (eq (symbol-value (car var))
9430 (default-value (car var))))
9431 (push (list (car var) `(quote ,(cadr var))) binds)))
9433 (call-interactively (quote ,cmd))))))
9435 (defun org-get-category (&optional pos force-refresh)
9436 "Get the category applying to position POS."
9438 (when force-refresh (org-refresh-category-properties))
9439 (let ((pos (or pos (point))))
9440 (or (get-text-property pos 'org-category)
9441 (progn (org-refresh-category-properties)
9442 (get-text-property pos 'org-category))))))
9444 ;;; Refresh properties
9446 (defun org-refresh-properties (dprop tprop)
9447 "Refresh buffer text properties.
9448 DPROP is the drawer property and TPROP is either the
9449 corresponding text property to set, or an alist with each element
9450 being a text property (as a symbol) and a function to apply to
9451 the value of the drawer property."
9452 (let* ((case-fold-search t)
9453 (inhibit-read-only t)
9454 (inherit? (org-property-inherit-p dprop))
9455 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9456 (global (and inherit? (org--property-global-value dprop nil))))
9457 (org-with-silent-modifications
9458 (org-with-point-at 1
9459 ;; Set global values (e.g., values defined through
9460 ;; "#+PROPERTY:" keywords) to the whole buffer.
9461 (when global (put-text-property (point-min) (point-max) tprop global))
9462 ;; Set local values.
9463 (while (re-search-forward property-re nil t)
9464 (when (org-at-property-p)
9465 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9466 (outline-next-heading))))))
9468 (defun org-refresh-property (tprop p &optional inherit)
9469 "Refresh the buffer text property TPROP from the drawer property P.
9470 The refresh happens only for the current headline, or the whole
9471 sub-tree if optional argument INHERIT is non-nil."
9472 (unless (org-before-first-heading-p)
9474 (org-back-to-heading t)
9475 (let ((start (point))
9476 (end (save-excursion
9477 (if inherit (org-end-of-subtree t t)
9478 (or (outline-next-heading) (point-max))))))
9480 ;; TPROP is a text property symbol.
9481 (put-text-property start end tprop p)
9482 ;; TPROP is an alist with (property . function) elements.
9483 (pcase-dolist (`(,prop . ,f) tprop)
9484 (put-text-property start end prop (funcall f p))))))))
9486 (defun org-refresh-category-properties ()
9487 "Refresh category text properties in the buffer."
9488 (let ((case-fold-search t)
9489 (inhibit-read-only t)
9491 (cond ((null org-category)
9492 (if buffer-file-name
9493 (file-name-sans-extension
9494 (file-name-nondirectory buffer-file-name))
9496 ((symbolp org-category) (symbol-name org-category))
9498 (org-with-silent-modifications
9499 (org-with-wide-buffer
9500 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9501 ;; This is the default category for the buffer. If none is
9502 ;; found, fall-back to `org-category' or buffer file name.
9504 (point-min) (point-max)
9506 (catch 'buffer-category
9507 (goto-char (point-max))
9508 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9509 (let ((element (org-element-at-point)))
9510 (when (eq (org-element-type element) 'keyword)
9511 (throw 'buffer-category
9512 (org-element-property :value element)))))
9514 ;; Set sub-tree specific categories.
9515 (goto-char (point-min))
9516 (let ((regexp (org-re-property "CATEGORY")))
9517 (while (re-search-forward regexp nil t)
9518 (let ((value (match-string-no-properties 3)))
9519 (when (org-at-property-p)
9521 (save-excursion (org-back-to-heading t) (point))
9522 (save-excursion (org-end-of-subtree t t) (point))
9526 (defun org-refresh-stats-properties ()
9527 "Refresh stats text properties in the buffer."
9528 (org-with-silent-modifications
9529 (org-with-point-at 1
9530 (let ((regexp (concat org-outline-regexp-bol
9531 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9532 (while (re-search-forward regexp nil t)
9533 (let* ((numerator (string-to-number (match-string 1)))
9534 (denominator (and (match-end 2)
9535 (string-to-number (match-string 2))))
9536 (stats (cond ((not denominator) numerator) ;percent
9537 ((= denominator 0) 0)
9538 (t (/ (* numerator 100) denominator)))))
9539 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9540 'org-stats stats)))))))
9542 (defun org-refresh-effort-properties ()
9543 "Refresh effort properties"
9544 (org-refresh-properties
9546 '((effort . identity)
9547 (effort-minutes . org-duration-to-minutes))))
9551 ;;; Link abbreviations
9553 (defun org-link-expand-abbrev (link)
9554 "Apply replacements as defined in `org-link-abbrev-alist'."
9555 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9556 (let* ((key (match-string 1 link))
9557 (as (or (assoc key org-link-abbrev-alist-local)
9558 (assoc key org-link-abbrev-alist)))
9559 (tag (and (match-end 2) (match-string 3 link)))
9565 ((symbolp rpl) (funcall rpl tag))
9566 ((string-match "%(\\([^)]+\\))" rpl)
9569 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9570 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9571 ((string-match "%h" rpl)
9572 (replace-match (url-hexify-string (or tag "")) t t rpl))
9573 (t (concat rpl tag)))))
9576 ;;; Storing and inserting links
9578 (defvar org-insert-link-history nil
9579 "Minibuffer history for links inserted with `org-insert-link'.")
9581 (defvar org-stored-links nil
9582 "Contains the links stored with `org-store-link'.")
9584 (defvar org-store-link-plist nil
9585 "Plist with info about the most recently link created with `org-store-link'.")
9587 (defun org-store-link-functions ()
9588 "Return a list of functions that are called to create and store a link.
9589 The functions defined in the :store property of
9590 `org-link-parameters'.
9592 Each function will be called in turn until one returns a non-nil
9593 value. Each function should check if it is responsible for
9594 creating this link (for example by looking at the major mode).
9595 If not, it must exit and return nil. If yes, it should return
9596 a non-nil value after calling `org-store-link-props' with a list
9597 of properties and values. Special properties are:
9599 :type The link prefix, like \"http\". This must be given.
9600 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9601 This is obligatory as well.
9602 :description Optional default description for the second pair
9603 of brackets in an Org mode link. The user can still change
9604 this when inserting this link into an Org mode buffer.
9606 In addition to these, any additional properties can be specified
9607 and then used in capture templates."
9608 (cl-loop for link in org-link-parameters
9610 do (setq store-func (org-link-get-parameter (car link) :store))
9612 collect store-func))
9614 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9615 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9618 (defun org-store-link (arg)
9619 "Store an org-link to the current location.
9621 This link is added to `org-stored-links' and can later be inserted
9622 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9624 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9626 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9627 `org-gnus-prefer-web-links' for links to Usenet articles.
9629 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9630 skipping storing functions that are not
9633 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9634 prefix ARG forces storing a link for each line in the
9637 (org-load-modules-maybe)
9638 (if (and (equal arg '(64)) (org-region-active-p))
9640 (let ((end (region-end)))
9641 (goto-char (region-beginning))
9643 (while (< (point-at-eol) end)
9644 (move-end-of-line 1) (activate-mark)
9645 (let (current-prefix-arg)
9646 (call-interactively 'org-store-link))
9647 (move-beginning-of-line 2)
9648 (set-mark (point)))))
9649 (setq org-store-link-plist nil)
9650 (let (link cpltxt desc description search txt custom-id agenda-link)
9652 ;; Store a link using an external link type, if any function is
9653 ;; available. If more than one can generate a link from current
9654 ;; location, ask which one to use.
9655 ((and (not (equal arg '(16)))
9656 (let ((results-alist nil))
9657 (dolist (f (org-store-link-functions))
9659 ;; XXX: return value is not link's plist, so we
9660 ;; store the new value before it is modified. It
9661 ;; would be cleaner to ask store link functions to
9662 ;; return the plist instead.
9663 (push (cons f (copy-sequence org-store-link-plist))
9665 (pcase results-alist
9667 (`((,_ . ,_)) t) ;single choice: nothing to do
9668 (`((,name . ,_) . ,_)
9669 ;; Reinstate link plist associated to the chosen
9671 (apply #'org-store-link-props
9674 "Which function for creating the link? "
9675 (mapcar #'car results-alist) nil t name)
9678 (setq link (plist-get org-store-link-plist :link))
9679 (setq desc (or (plist-get org-store-link-plist :description)
9682 ;; Store a link from a source code buffer.
9683 ((org-src-edit-buffer-p)
9684 (let ((coderef-format (org-src-coderef-format)))
9685 (cond ((save-excursion
9687 (looking-at (org-src-coderef-regexp coderef-format)))
9688 (setq link (format "(%s)" (match-string-no-properties 3))))
9689 ((called-interactively-p 'any)
9690 (let ((label (read-string "Code line label: ")))
9692 (setq link (format coderef-format label))
9693 (let ((gc (- 79 (length link))))
9694 (if (< (current-column) gc)
9695 (org-move-to-column gc t)
9698 (setq link (concat "(" label ")"))
9700 (t (setq link nil)))))
9702 ;; We are in the agenda, link to referenced location
9703 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9704 (let ((m (or (get-text-property (point) 'org-hd-marker)
9705 (get-text-property (point) 'org-marker))))
9707 (org-with-point-at m
9709 (if (called-interactively-p 'any)
9710 (call-interactively 'org-store-link)
9711 (org-store-link nil)))))))
9713 ((eq major-mode 'calendar-mode)
9714 (let ((cd (calendar-cursor-to-date)))
9717 (car org-time-stamp-formats)
9719 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9721 (org-store-link-props :type "calendar" :date cd)))
9723 ((eq major-mode 'help-mode)
9724 (setq link (concat "help:" (save-excursion
9725 (goto-char (point-min))
9726 (looking-at "^[^ ]+")
9728 (org-store-link-props :type "help"))
9730 ((eq major-mode 'w3-mode)
9731 (setq cpltxt (if (and (buffer-name)
9732 (not (string-match "Untitled" (buffer-name))))
9735 link (url-view-url t))
9736 (org-store-link-props :type "w3" :url (url-view-url t)))
9738 ((eq major-mode 'image-mode)
9739 (setq cpltxt (concat "file:"
9740 (abbreviate-file-name buffer-file-name))
9742 (org-store-link-props :type "image" :file buffer-file-name))
9744 ;; In dired, store a link to the file of the current line
9745 ((derived-mode-p 'dired-mode)
9746 (let ((file (dired-get-filename nil t)))
9748 (abbreviate-file-name
9749 (expand-file-name (dired-get-filename nil t)))
9750 ;; otherwise, no file so use current directory.
9752 (setq cpltxt (concat "file:" file)
9755 ((setq search (run-hook-with-args-until-success
9756 'org-create-file-search-functions))
9757 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9759 (setq cpltxt (or description link)))
9761 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9762 (org-with-limited-levels
9763 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9765 ;; Store a link using the target at point
9766 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9769 (abbreviate-file-name
9770 (buffer-file-name (buffer-base-buffer)))
9771 "::" (match-string 1))
9773 ((and (featurep 'org-id)
9774 (or (eq org-id-link-to-org-use-id t)
9775 (and (called-interactively-p 'any)
9776 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9777 (and (eq org-id-link-to-org-use-id
9778 'create-if-interactive-and-no-custom-id)
9780 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9781 ;; Store a link using the ID at point
9782 (setq link (condition-case nil
9783 (prog1 (org-id-store-link)
9784 (setq desc (or (plist-get org-store-link-plist
9788 ;; Probably before first headline, link only to file
9790 (abbreviate-file-name
9791 (buffer-file-name (buffer-base-buffer))))))))
9793 ;; Just link to current headline
9794 (setq cpltxt (concat "file:"
9795 (abbreviate-file-name
9796 (buffer-file-name (buffer-base-buffer)))))
9797 ;; Add a context search string
9798 (when (org-xor org-context-in-file-links
9800 (let* ((element (org-element-at-point))
9801 (name (org-element-property :name element)))
9803 ((org-at-heading-p) nil)
9805 ((org-region-active-p)
9806 (buffer-substring (region-beginning) (region-end)))))
9807 (when (or (null txt) (string-match "\\S-" txt))
9811 (org-make-org-heading-search-string txt)
9814 (nth 4 (ignore-errors (org-heading-components)))
9816 (when (string-match "::\\'" cpltxt)
9817 (setq cpltxt (substring cpltxt 0 -2)))
9818 (setq link cpltxt)))))
9820 ((buffer-file-name (buffer-base-buffer))
9821 ;; Just link to this file here.
9822 (setq cpltxt (concat "file:"
9823 (abbreviate-file-name
9824 (buffer-file-name (buffer-base-buffer)))))
9825 ;; Add a context string.
9826 (when (org-xor org-context-in-file-links
9828 (setq txt (if (org-region-active-p)
9829 (buffer-substring (region-beginning) (region-end))
9830 (buffer-substring (point-at-bol) (point-at-eol))))
9831 ;; Only use search option if there is some text.
9832 (when (string-match "\\S-" txt)
9834 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9838 ((called-interactively-p 'interactive)
9839 (user-error "No method for storing a link from this buffer"))
9841 (t (setq link nil)))
9843 ;; We're done setting link and desc, clean up
9844 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9845 (setq link (or link cpltxt)
9846 desc (or desc cpltxt))
9848 ((equal desc "NONE") (setq desc nil))
9850 (replace-regexp-in-string
9851 org-bracket-link-analytic-regexp
9852 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9855 (if (not (and (or (called-interactively-p 'any)
9856 executing-kbd-macro)
9858 (or agenda-link (and link (org-make-link-string link desc)))
9859 (push (list link desc) org-stored-links)
9860 (message "Stored: %s" (or desc link))
9862 (setq link (concat "file:" (abbreviate-file-name
9863 (buffer-file-name)) "::#" custom-id))
9864 (push (list link desc) org-stored-links))
9865 (car org-stored-links)))))
9867 (defun org-store-link-props (&rest plist)
9868 "Store link properties.
9869 The properties are pre-processed by extracting names, addresses
9871 (let ((x (plist-get plist :from)))
9873 (let ((adr (mail-extract-address-components x)))
9874 (setq plist (plist-put plist :fromname (car adr)))
9875 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9876 (let ((x (plist-get plist :to)))
9878 (let ((adr (mail-extract-address-components x)))
9879 (setq plist (plist-put plist :toname (car adr)))
9880 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9881 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9883 (setq plist (plist-put plist :date-timestamp
9885 (org-time-stamp-format t) x)))
9886 (setq plist (plist-put plist :date-timestamp-inactive
9888 (org-time-stamp-format t t) x)))))
9889 (let ((from (plist-get plist :from))
9890 (to (plist-get plist :to)))
9891 (when (and from to org-from-is-user-regexp)
9893 (plist-put plist :fromto
9894 (if (string-match org-from-is-user-regexp from)
9896 (concat "from %f"))))))
9897 (setq org-store-link-plist plist))
9899 (defun org-add-link-props (&rest plist)
9900 "Add these properties to the link property list."
9903 (setq key (pop plist) value (pop plist))
9904 (setq org-store-link-plist
9905 (plist-put org-store-link-plist key value)))))
9907 (defun org-email-link-description (&optional fmt)
9908 "Return the description part of an email link.
9909 This takes information from `org-store-link-plist' and formats it
9910 according to FMT (default from `org-email-link-description-format')."
9911 (setq fmt (or fmt org-email-link-description-format))
9912 (let* ((p org-store-link-plist)
9913 (to (plist-get p :toaddress))
9914 (from (plist-get p :fromaddress))
9917 (cons "%c" (plist-get p :fromto))
9918 (cons "%F" (plist-get p :from))
9919 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9920 (cons "%T" (plist-get p :to))
9921 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9922 (cons "%s" (plist-get p :subject))
9923 (cons "%d" (plist-get p :date))
9924 (cons "%m" (plist-get p :message-id)))))
9925 (when (string-match "%c" fmt)
9926 ;; Check if the user wrote this message
9927 (if (and org-from-is-user-regexp from to
9928 (save-match-data (string-match org-from-is-user-regexp from)))
9929 (setq fmt (replace-match "to %t" t t fmt))
9930 (setq fmt (replace-match "from %f" t t fmt))))
9931 (org-replace-escapes fmt table)))
9933 (defun org-make-org-heading-search-string (&optional string)
9934 "Make search string for the current headline or STRING."
9936 (and (derived-mode-p 'org-mode)
9938 (org-back-to-heading t)
9939 (org-element-property :raw-value (org-element-at-point))))))
9940 (lines org-context-in-file-links))
9941 (unless string (setq s (concat "*" s))) ;Add * for headlines
9942 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9943 (when (and string (integerp lines) (> lines 0))
9944 (let ((slines (org-split-string s "\n")))
9945 (when (< lines (length slines))
9948 (reverse (nthcdr (- (length slines) lines)
9949 (reverse slines))) "\n")))))
9950 (mapconcat #'identity (split-string s) " ")))
9952 (defun org-make-link-string (link &optional description)
9953 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9954 (unless (org-string-nw-p link) (error "Empty link"))
9955 (let ((uri (cond ((string-match org-link-types-re link)
9956 (concat (match-string 1 link)
9957 (org-link-escape (substring link (match-end 1)))))
9958 ;; For readability, url-encode internal links only
9959 ;; when absolutely needed (i.e, when they contain
9960 ;; square brackets). File links however, are
9961 ;; encoded since, e.g., spaces are significant.
9962 ((or (file-name-absolute-p link)
9963 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9964 (org-link-escape link))
9967 (and (org-string-nw-p description)
9968 ;; Remove brackets from description, as they are fatal.
9969 (replace-regexp-in-string
9970 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9971 (org-trim description)))))
9974 (if description (format "[%s]" description) ""))))
9976 (defconst org-link-escape-chars
9979 "List of characters that should be escaped in a link when stored to Org.
9980 This is the list that is used for internal purposes.")
9982 (defun org-link-escape (text &optional table merge)
9983 "Return percent escaped representation of TEXT.
9984 TEXT is a string with the text to escape.
9985 Optional argument TABLE is a list with characters that should be
9986 escaped. When nil, `org-link-escape-chars' is used.
9987 If optional argument MERGE is set, merge TABLE into
9988 `org-link-escape-chars'."
9989 (let ((characters-to-encode
9990 (cond ((null table) org-link-escape-chars)
9991 (merge (append org-link-escape-chars table))
9995 (if (or (memq c characters-to-encode)
9996 (and org-url-hexify-p (or (< c 32) (> c 126))))
9997 (mapconcat (lambda (e) (format "%%%.2X" e))
9998 (or (encode-coding-char c 'utf-8)
9999 (error "Unable to percent escape character: %c" c))
10001 (char-to-string c)))
10004 (defun org-link-unescape (str)
10005 "Unhex hexified Unicode parts in string STR.
10006 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10007 reciprocal of `org-link-escape', which see."
10008 (if (org-string-nw-p str)
10009 (replace-regexp-in-string
10010 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10013 (defun org-link-unescape-compound (hex)
10014 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10015 Note: this function also decodes single byte encodings like
10016 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10018 (let* ((bytes (cdr (split-string hex "%")))
10023 (let* ((val (string-to-number (pop bytes) 16))
10027 ((>= val 252) (cons 6 252))
10028 ((>= val 248) (cons 5 248))
10029 ((>= val 240) (cons 4 240))
10030 ((>= val 224) (cons 3 224))
10031 ((>= val 192) (cons 2 192))
10034 (when (>= val 192) (setq eat (car shift-xor)))
10035 (setq val (logxor val (cdr shift-xor)))
10036 (setq sum (+ (lsh sum (car shift-xor)) val))
10037 (when (> eat 0) (setq eat (- eat 1)))
10039 ((= 0 eat) ;multi byte
10040 (setq ret (concat ret (char-to-string sum)))
10042 ((not bytes) ; single byte(s)
10043 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10046 (defun org-link-unescape-single-byte-sequence (hex)
10047 "Unhexify hex-encoded single byte character sequences."
10048 (mapconcat (lambda (byte)
10049 (char-to-string (string-to-number byte 16)))
10050 (cdr (split-string hex "%")) ""))
10052 (defun org-xor (a b)
10056 (defun org-fixup-message-id-for-http (s)
10057 "Replace special characters in a message id, so it can be used in an http query."
10058 (when (string-match "%" s)
10059 (setq s (mapconcat (lambda (c)
10062 (char-to-string c)))
10064 (while (string-match "<" s)
10065 (setq s (replace-match "%3C" t t s)))
10066 (while (string-match ">" s)
10067 (setq s (replace-match "%3E" t t s)))
10068 (while (string-match "@" s)
10069 (setq s (replace-match "%40" t t s)))
10072 (defun org-link-prettify (link)
10073 "Return a human-readable representation of LINK.
10074 The car of LINK must be a raw link.
10075 The cdr of LINK must be either a link description or nil."
10076 (let ((desc (or (cadr link) "<no description>")))
10077 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10078 "<" (car link) ">")))
10081 (defun org-insert-link-global ()
10082 "Insert a link like Org mode does.
10083 This command can be called in any mode to insert a link in Org syntax."
10085 (org-load-modules-maybe)
10086 (org-run-like-in-org-mode 'org-insert-link))
10088 (defun org-insert-all-links (arg &optional pre post)
10089 "Insert all links in `org-stored-links'.
10090 When a universal prefix, do not delete the links from `org-stored-links'.
10091 When `ARG' is a number, insert the last N link(s).
10092 `PRE' and `POST' are optional arguments to define a string to
10093 prepend or to append."
10095 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10096 (links (copy-sequence org-stored-links))
10098 (po (or post "\n"))
10100 (if (null org-stored-links)
10101 (message "No link to insert")
10102 (while (and (or (listp arg) (>= arg cnt))
10103 (setq l (if (listp arg)
10105 (pop org-stored-links))))
10106 (setq cnt (1+ cnt))
10108 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10111 (defun org-insert-last-stored-link (arg)
10112 "Insert the last link stored in `org-stored-links'."
10114 (org-insert-all-links arg "" "\n"))
10116 (defun org-link-fontify-links-to-this-file ()
10117 "Fontify links to the current file in `org-stored-links'."
10118 (let ((f (buffer-file-name)) a b)
10119 (setq a (mapcar (lambda(l)
10120 (let ((ll (car l)))
10121 (when (and (string-match "^file:\\(.+\\)::" ll)
10122 (equal f (expand-file-name (match-string 1 ll))))
10125 (when (featurep 'org-id)
10126 (setq b (mapcar (lambda(l)
10127 (let ((ll (car l)))
10128 (when (and (string-match "^id:\\(.+\\)$" ll)
10129 (equal f (expand-file-name
10130 (or (org-id-find-id-file
10131 (match-string 1 ll)) ""))))
10133 org-stored-links)))
10135 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10136 (delq nil (append a b)))))
10138 (defvar org--links-history nil)
10139 (defun org-insert-link (&optional complete-file link-location default-description)
10140 "Insert a link. At the prompt, enter the link.
10142 Completion can be used to insert any of the link protocol prefixes in use.
10144 The history can be used to select a link previously stored with
10145 `org-store-link'. When the empty string is entered (i.e. if you just
10146 press `RET' at the prompt), the link defaults to the most recently
10147 stored link. As `SPC' triggers completion in the minibuffer, you need to
10148 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10150 You will also be prompted for a description, and if one is given, it will
10151 be displayed in the buffer instead of the link.
10153 If there is already a link at point, this command will allow you to edit
10154 link and description parts.
10156 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10158 selected using completion. The path to the file will be relative to the
10159 current directory if the file is in the current directory or a subdirectory.
10160 Otherwise, the link will be the absolute path as completed in the minibuffer
10161 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10162 option `org-link-file-path-type'.
10164 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10165 absolute path even if the file is in
10166 the current directory or below.
10168 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10169 prefix negates `org-keep-stored-link-after-insertion'.
10171 If the LINK-LOCATION parameter is non-nil, this value will be used as
10172 the link location instead of reading one interactively.
10174 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10175 be used as the default description. Otherwise, if
10176 `org-make-link-description-function' is non-nil, this function
10177 will be called with the link target, and the result will be the
10178 default link description."
10180 (let* ((wcf (current-window-configuration))
10181 (origbuf (current-buffer))
10182 (region (when (org-region-active-p)
10183 (buffer-substring (region-beginning) (region-end))))
10184 (remove (and region (list (region-beginning) (region-end))))
10186 (link link-location)
10187 (abbrevs org-link-abbrev-alist-local)
10188 entry all-prefixes auto-desc)
10190 (link-location) ; specified by arg, just use it.
10191 ((org-in-regexp org-bracket-link-regexp 1)
10192 ;; We do have a link at point, and we are going to edit it.
10193 (setq remove (list (match-beginning 0) (match-end 0)))
10194 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10195 (setq link (read-string "Link: "
10197 (match-string-no-properties 1)))))
10198 ((or (org-in-regexp org-angle-link-re)
10199 (org-in-regexp org-plain-link-re))
10200 ;; Convert to bracket link
10201 (setq remove (list (match-beginning 0) (match-end 0))
10202 link (read-string "Link: "
10203 (org-unbracket-string "<" ">" (match-string 0)))))
10204 ((member complete-file '((4) (16)))
10205 ;; Completing read for file names.
10206 (setq link (org-file-complete-link complete-file)))
10208 ;; Read link, with completion for stored links.
10209 (org-link-fontify-links-to-this-file)
10210 (org-switch-to-buffer-other-window "*Org Links*")
10211 (with-current-buffer "*Org Links*"
10213 (insert "Insert a link.
10214 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10215 (when org-stored-links
10216 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10217 (insert (mapconcat 'org-link-prettify
10218 (reverse org-stored-links) "\n")))
10219 (goto-char (point-min)))
10220 (let ((cw (selected-window)))
10221 (select-window (get-buffer-window "*Org Links*" 'visible))
10222 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10223 (unless (pos-visible-in-window-p (point-max))
10224 (org-fit-window-to-buffer))
10225 (and (window-live-p cw) (select-window cw)))
10226 (setq all-prefixes (append (mapcar 'car abbrevs)
10227 (mapcar 'car org-link-abbrev-alist)
10230 ;; Fake a link history, containing the stored links.
10231 (let ((org--links-history
10232 (append (mapcar #'car org-stored-links)
10233 org-insert-link-history)))
10235 (org-completing-read
10238 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10239 (mapcar #'car org-stored-links))
10241 'org--links-history
10242 (caar org-stored-links)))
10243 (unless (org-string-nw-p link) (user-error "No link selected"))
10244 (dolist (l org-stored-links)
10245 (when (equal link (cadr l))
10246 (setq link (car l))
10247 (setq auto-desc t)))
10248 (when (or (member link all-prefixes)
10249 (and (equal ":" (substring link -1))
10250 (member (substring link 0 -1) all-prefixes)
10251 (setq link (substring link 0 -1))))
10252 (setq link (with-current-buffer origbuf
10253 (org-link-try-special-completion link)))))
10254 (set-window-configuration wcf)
10255 (kill-buffer "*Org Links*"))
10256 (setq entry (assoc link org-stored-links))
10257 (or entry (push link org-insert-link-history))
10258 (setq desc (or desc (nth 1 entry)))))
10260 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10261 (not org-keep-stored-link-after-insertion))
10262 (setq org-stored-links (delq (assoc link org-stored-links)
10263 org-stored-links)))
10265 (when (and (string-match org-plain-link-re link)
10266 (not (string-match org-ts-regexp link)))
10267 ;; URL-like link, normalize the use of angular brackets.
10268 (setq link (org-unbracket-string "<" ">" link)))
10270 ;; Check if we are linking to the current file with a search
10271 ;; option If yes, simplify the link by using only the search
10273 (when (and buffer-file-name
10274 (let ((case-fold-search nil))
10275 (string-match "\\`file:\\(.+?\\)::" link)))
10276 (let ((path (match-string-no-properties 1 link))
10277 (search (substring-no-properties link (match-end 0))))
10279 (when (equal (file-truename buffer-file-name) (file-truename path))
10280 ;; We are linking to this same file, with a search option
10281 (setq link search)))))
10283 ;; Check if we can/should use a relative path. If yes, simplify the link
10284 (let ((case-fold-search nil))
10285 (when (string-match "\\`\\(file\\|docview\\):" link)
10286 (let* ((type (match-string-no-properties 0 link))
10287 (path (substring-no-properties link (match-end 0)))
10290 ((or (eq org-link-file-path-type 'absolute)
10291 (equal complete-file '(16)))
10292 (setq path (abbreviate-file-name (expand-file-name path))))
10293 ((eq org-link-file-path-type 'noabbrev)
10294 (setq path (expand-file-name path)))
10295 ((eq org-link-file-path-type 'relative)
10296 (setq path (file-relative-name path)))
10299 (if (string-match (concat "^" (regexp-quote
10301 (file-name-as-directory
10302 default-directory))))
10303 (expand-file-name path))
10304 ;; We are linking a file with relative path name.
10305 (setq path (substring (expand-file-name path)
10307 (setq path (abbreviate-file-name (expand-file-name path)))))))
10308 (setq link (concat type path))
10309 (when (equal desc origpath)
10310 (setq desc path)))))
10313 (let ((initial-input
10315 (default-description)
10316 ((not org-make-link-description-function) desc)
10317 (t (condition-case nil
10318 (funcall org-make-link-description-function link desc)
10320 (message "Can't get link description from `%s'"
10321 (symbol-name org-make-link-description-function))
10324 (setq desc (read-string "Description: " initial-input))))
10326 (unless (string-match "\\S-" desc) (setq desc nil))
10327 (when remove (apply 'delete-region remove))
10328 (insert (org-make-link-string link desc))
10329 ;; Redisplay so as the new link has proper invisible characters.
10332 (defun org-link-try-special-completion (type)
10333 "If there is completion support for link type TYPE, offer it."
10334 (let ((fun (org-link-get-parameter type :complete)))
10335 (if (functionp fun)
10337 (read-string "Link (no completion support): " (concat type ":")))))
10339 (defun org-file-complete-link (&optional arg)
10340 "Create a file link using completion."
10341 (let ((file (read-file-name "File: "))
10342 (pwd (file-name-as-directory (expand-file-name ".")))
10343 (pwd1 (file-name-as-directory (abbreviate-file-name
10344 (expand-file-name ".")))))
10345 (cond ((equal arg '(16))
10347 (abbreviate-file-name (expand-file-name file))))
10349 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10350 (concat "file:" (match-string 1 file)))
10352 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10353 (expand-file-name file))
10355 (match-string 1 (expand-file-name file))))
10356 (t (concat "file:" file)))))
10358 (defun org-completing-read (&rest args)
10359 "Completing-read with SPACE being a normal character."
10360 (let ((enable-recursive-minibuffers t)
10361 (minibuffer-local-completion-map
10362 (copy-keymap minibuffer-local-completion-map)))
10363 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10364 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10365 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10366 'org-time-stamp-inactive)
10367 (apply #'completing-read args)))
10369 ;;; Opening/following a link
10371 (defvar org-link-search-failed nil)
10373 (defvar org-open-link-functions nil
10374 "Hook for functions finding a plain text link.
10375 These functions must take a single argument, the link content.
10376 They will be called for links that look like [[link text][description]]
10377 when LINK TEXT does not have a protocol like \"http:\" and does not look
10378 like a filename (e.g. \"./blue.png\").
10380 These functions will be called *before* Org attempts to resolve the
10381 link by doing text searches in the current buffer - so if you want a
10382 link \"[[target]]\" to still find \"<<target>>\", your function should
10383 handle this as a special case.
10385 When the function does handle the link, it must return a non-nil value.
10386 If it decides that it is not responsible for this link, it must return
10387 nil to indicate that that Org can continue with other options like
10388 exact and fuzzy text search.")
10390 (defun org-next-link (&optional search-backward)
10391 "Move forward to the next link.
10392 If the link is in hidden text, expose it."
10394 (when (and org-link-search-failed (eq this-command last-command))
10395 (goto-char (point-min))
10396 (message "Link search wrapped back to beginning of buffer"))
10397 (setq org-link-search-failed nil)
10398 (let* ((pos (point))
10400 (a (assq :link ct))
10401 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10402 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10403 ((looking-at org-any-link-re)
10404 ;; Don't stay stuck at link without an org-link face
10405 (forward-char (if search-backward -1 1))))
10406 (if (funcall srch-fun org-any-link-re nil t)
10408 (goto-char (match-beginning 0))
10409 (when (org-invisible-p) (org-show-context)))
10411 (setq org-link-search-failed t)
10412 (message "No further link found"))))
10414 (defun org-previous-link ()
10415 "Move backward to the previous link.
10416 If the link is in hidden text, expose it."
10418 (funcall 'org-next-link t))
10420 (defun org-translate-link (s)
10421 "Translate a link string if a translation function has been defined."
10423 (insert (org-trim s))
10424 (org-trim (org-element-interpret-data (org-element-context)))))
10426 (defun org-translate-link-from-planner (type path)
10427 "Translate a link from Emacs Planner syntax so that Org can follow it.
10428 This is still an experimental function, your mileage may vary."
10430 ((member type '("http" "https" "news" "ftp"))
10431 ;; standard Internet links are the same.
10433 ((and (equal type "irc") (string-match "^//" path))
10434 ;; Planner has two / at the beginning of an irc link, we have 1.
10435 ;; We should have zero, actually....
10436 (setq path (substring path 1)))
10437 ((and (equal type "lisp") (string-match "^/" path))
10438 ;; Planner has a slash, we do not.
10439 (setq type "elisp" path (substring path 1)))
10440 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10441 ;; A typical message link. Planner has the id after the final slash,
10442 ;; we separate it with a hash mark
10443 (setq path (concat (match-string 1 path) "#"
10444 (org-unbracket-string "<" ">" (match-string 2 path))))))
10447 (defun org-find-file-at-mouse (ev)
10448 "Open file link or URL at mouse."
10450 (mouse-set-point ev)
10451 (org-open-at-point 'in-emacs))
10453 (defun org-open-at-mouse (ev)
10454 "Open file link or URL at mouse.
10455 See the docstring of `org-open-file' for details."
10457 (mouse-set-point ev)
10458 (when (eq major-mode 'org-agenda-mode)
10459 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10460 (org-open-at-point))
10462 (defvar org-window-config-before-follow-link nil
10463 "The window configuration before following a link.
10464 This is saved in case the need arises to restore it.")
10467 (defun org-open-at-point-global ()
10468 "Follow a link or time-stamp like Org mode does.
10469 This command can be called in any mode to follow an external link
10470 or a time-stamp that has Org mode syntax. Its behavior is
10471 undefined when called on internal links (e.g., fuzzy links).
10472 Raise an error when there is nothing to follow. "
10474 (cond ((org-in-regexp org-any-link-re)
10475 (org-open-link-from-string (match-string-no-properties 0)))
10476 ((or (org-in-regexp org-ts-regexp-both nil t)
10477 (org-in-regexp org-tsr-regexp-both nil t))
10478 (org-follow-timestamp-link))
10479 (t (user-error "No link found"))))
10482 (defun org-open-link-from-string (s &optional arg reference-buffer)
10483 "Open a link in the string S, as if it was in Org mode."
10484 (interactive "sLink: \nP")
10485 (let ((reference-buffer (or reference-buffer (current-buffer))))
10487 (let ((org-inhibit-startup (not reference-buffer)))
10490 (goto-char (point-min))
10491 (when reference-buffer
10492 (setq org-link-abbrev-alist-local
10493 (with-current-buffer reference-buffer
10494 org-link-abbrev-alist-local)))
10495 (org-open-at-point arg reference-buffer)))))
10497 (defvar org-open-at-point-functions nil
10498 "Hook that is run when following a link at point.
10500 Functions in this hook must return t if they identify and follow
10501 a link at point. If they don't find anything interesting at point,
10502 they must return nil.")
10504 (defvar org-link-search-inhibit-query nil)
10505 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10506 (defun org--open-doi-link (path)
10507 "Open a \"doi\" type link.
10508 PATH is a the path to search for, as a string."
10509 (browse-url (url-encode-url (concat org-doi-server-url path))))
10511 (defun org--open-elisp-link (path)
10512 "Open a \"elisp\" type link.
10513 PATH is the sexp to evaluate, as a string."
10515 (if (or (and (org-string-nw-p
10516 org-confirm-elisp-link-not-regexp)
10517 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10518 (not org-confirm-elisp-link-function)
10519 (funcall org-confirm-elisp-link-function
10520 (format "Execute \"%s\" as elisp? "
10521 (org-add-props cmd nil 'face 'org-warning))))
10522 (message "%s => %s" cmd
10523 (if (eq (string-to-char cmd) ?\()
10525 (call-interactively (read cmd))))
10526 (user-error "Abort"))))
10528 (defun org--open-help-link (path)
10529 "Open a \"help\" type link.
10530 PATH is a symbol name, as a string."
10531 (pcase (intern path)
10532 ((and (pred fboundp) variable) (describe-function variable))
10533 ((and (pred boundp) function) (describe-variable function))
10534 (name (user-error "Unknown function or variable: %s" name))))
10536 (defun org--open-shell-link (path)
10537 "Open a \"shell\" type link.
10538 PATH is the command to execute, as a string."
10539 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10541 (if (or (and (org-string-nw-p
10542 org-confirm-shell-link-not-regexp)
10544 org-confirm-shell-link-not-regexp cmd))
10545 (not org-confirm-shell-link-function)
10546 (funcall org-confirm-shell-link-function
10547 (format "Execute \"%s\" in shell? "
10548 (org-add-props cmd nil
10549 'face 'org-warning))))
10551 (message "Executing %s" cmd)
10552 (shell-command cmd buf)
10553 (when (featurep 'midnight)
10554 (setq clean-buffer-list-kill-buffer-names
10555 (cons (buffer-name buf)
10556 clean-buffer-list-kill-buffer-names))))
10557 (user-error "Abort"))))
10559 (defun org-open-at-point (&optional arg reference-buffer)
10560 "Open link, timestamp, footnote or tags at point.
10562 When point is on a link, follow it. Normally, files will be
10563 opened by an appropriate application. If the optional prefix
10564 argument ARG is non-nil, Emacs will visit the file. With
10565 a double prefix argument, try to open outside of Emacs, in the
10566 application the system uses for this file type.
10568 When point is on a timestamp, open the agenda at the day
10571 When point is a footnote definition, move to the first reference
10572 found. If it is on a reference, move to the associated
10575 When point is on a headline, display a list of every link in the
10576 entry, so it is possible to pick one, or all, of them. If point
10577 is on a tag, call `org-tags-view' instead.
10579 When optional argument REFERENCE-BUFFER is non-nil, it should
10580 specify a buffer from where the link search should happen. This
10581 is used internally by `org-open-link-from-string'.
10583 On top of syntactically correct links, this function will also
10584 try to open links and time-stamps in comments, example
10585 blocks... i.e., whenever point is on something looking like
10586 a timestamp or a link."
10588 ;; On a code block, open block's results.
10589 (unless (call-interactively 'org-babel-open-src-block-result)
10590 (org-load-modules-maybe)
10591 (setq org-window-config-before-follow-link (current-window-configuration))
10592 (org-remove-occur-highlights nil nil t)
10593 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10595 ;; Only consider supported types, even if they are not
10596 ;; the closest one.
10597 (org-element-lineage
10598 (org-element-context)
10599 '(clock footnote-definition footnote-reference headline
10600 inlinetask link timestamp)
10602 (type (org-element-type context))
10603 (value (org-element-property :value context)))
10605 ;; On a headline or an inlinetask, but not on a timestamp,
10606 ;; a link, a footnote reference.
10607 ((memq type '(headline inlinetask))
10608 (org-match-line org-complex-heading-regexp)
10609 (if (and (match-beginning 5)
10610 (>= (point) (match-beginning 5))
10611 (< (point) (match-end 5)))
10613 (org-tags-view arg (substring (match-string 5) 0 -1))
10615 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10617 (require 'org-attach)
10618 (org-attach-reveal 'if-exists))
10619 (`(,links . ,links-end)
10620 (dolist (link (if (stringp links) (list links) links))
10621 (search-forward link nil links-end)
10622 (goto-char (match-beginning 0))
10623 (org-open-at-point))))))
10624 ;; On a footnote reference or at definition's label.
10625 ((or (eq type 'footnote-reference)
10626 (and (eq type 'footnote-definition)
10628 ;; Do not validate action when point is on the
10629 ;; spaces right after the footnote label, in
10630 ;; order to be on par with behaviour on links.
10631 (skip-chars-forward " \t")
10633 (org-element-property :contents-begin context)))
10634 (if begin (< (point) begin)
10635 (= (org-element-property :post-affiliated context)
10636 (line-beginning-position)))))))
10637 (org-footnote-action))
10638 ;; No valid context. Ignore catch-all types like `headline'.
10639 ;; If point is on something looking like a link or
10640 ;; a time-stamp, try opening it. It may be useful in
10641 ;; comments, example blocks...
10642 ((memq type '(footnote-definition headline inlinetask nil))
10643 (call-interactively #'org-open-at-point-global))
10644 ;; On a clock line, make sure point is on the timestamp
10645 ;; before opening it.
10646 ((and (eq type 'clock)
10648 (>= (point) (org-element-property :begin value))
10649 (<= (point) (org-element-property :end value)))
10650 (org-follow-timestamp-link))
10651 ;; Do nothing on white spaces after an object.
10654 (goto-char (org-element-property :end context))
10655 (skip-chars-backward " \t")
10657 (user-error "No link found"))
10658 ((eq type 'timestamp) (org-follow-timestamp-link))
10660 (let ((type (org-element-property :type context))
10661 (path (org-link-unescape (org-element-property :path context))))
10662 ;; Switch back to REFERENCE-BUFFER needed when called in
10663 ;; a temporary buffer through `org-open-link-from-string'.
10664 (with-current-buffer (or reference-buffer (current-buffer))
10666 ((equal type "file")
10667 (if (string-match "[*?{]" (file-name-nondirectory path))
10669 ;; Look into `org-link-parameters' in order to find
10670 ;; a DEDICATED-FUNCTION to open file. The function
10671 ;; will be applied on raw link instead of parsed
10672 ;; link due to the limitation in `org-add-link-type'
10673 ;; ("open" function called with a single argument).
10674 ;; If no such function is found, fallback to
10675 ;; `org-open-file'.
10676 (let* ((option (org-element-property :search-option context))
10677 (app (org-element-property :application context))
10678 (dedicated-function
10679 (org-link-get-parameter
10680 (if app (concat type "+" app) type)
10682 (if dedicated-function
10683 (funcall dedicated-function
10685 (and option (concat "::" option))))
10686 (apply #'org-open-file
10689 ((equal app "emacs") 'emacs)
10690 ((equal app "sys") 'system))
10691 (cond ((not option) nil)
10692 ((string-match-p "\\`[0-9]+\\'" option)
10693 (list (string-to-number option)))
10695 (org-link-unescape option)))))))))
10696 ((functionp (org-link-get-parameter type :follow))
10697 (funcall (org-link-get-parameter type :follow) path))
10698 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10699 (unless (run-hook-with-args-until-success
10700 'org-open-link-functions path)
10701 (if (not arg) (org-mark-ring-push)
10702 (switch-to-buffer-other-window
10703 (org-get-buffer-for-internal-link (current-buffer))))
10705 (org-with-wide-buffer
10706 (if (equal type "radio")
10707 (org-search-radio-target
10708 (org-element-property :path context))
10710 (if (member type '("custom-id" "coderef"))
10711 (org-element-property :raw-link context)
10713 ;; Prevent fuzzy links from matching
10715 (and (equal type "fuzzy")
10716 (+ 2 (org-element-property :begin context)))))
10718 (unless (and (<= (point-min) destination)
10719 (>= (point-max) destination))
10721 (goto-char destination))))
10722 (t (browse-url-at-point))))))
10723 (t (user-error "No link found")))))
10724 (run-hook-with-args 'org-follow-link-hook)))
10726 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10727 "Offer links in the current entry and return the selected link.
10728 If there is only one link, return it.
10729 If NTH is an integer, return the NTH link found.
10730 If ZERO is a string, check also this string for a link, and if
10731 there is one, return it."
10732 (with-current-buffer buffer
10733 (org-with-wide-buffer
10736 have-zero end links link c)
10737 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10738 (push (match-string 0 zero) links)
10739 (setq cnt (1- cnt) have-zero t))
10741 (org-back-to-heading t)
10742 (setq end (save-excursion (outline-next-heading) (point)))
10743 (while (re-search-forward org-any-link-re end t)
10744 (push (match-string 0) links))
10745 (setq links (org-uniquify (reverse links))))
10748 (message "No links"))
10749 ((equal (length links) 1)
10750 (setq link (car links)))
10751 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10752 (setq link (nth (if have-zero nth (1- nth)) links)))
10753 (t ; we have to select a link
10755 (save-window-excursion
10756 (delete-other-windows)
10757 (with-output-to-temp-buffer "*Select Link*"
10760 ((not (string-match org-bracket-link-regexp l))
10761 (princ (format "[%c] %s\n" (cl-incf cnt)
10762 (org-unbracket-string "<" ">" l))))
10764 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10765 (match-string 3 l) (match-string 1 l))))
10766 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10767 (match-string 1 l)))))))
10768 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10769 (message "Select link to open, RET to open all:")
10770 (setq c (read-char-exclusive))
10771 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10772 (when (equal c ?q) (user-error "Abort"))
10773 (if (equal c ?\C-m)
10775 (setq nth (- c ?0))
10776 (when have-zero (setq nth (1+ nth)))
10777 (unless (and (integerp nth) (>= (length links) nth))
10778 (user-error "Invalid link selection"))
10779 (setq link (nth (1- nth) links)))))
10780 (cons link end)))))
10782 ;; TODO: These functions are deprecated since `org-open-at-point'
10783 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10784 (defun org-open-file-with-system (path)
10785 "Open file at PATH using the system way of opening it."
10786 (org-open-file path 'system))
10787 (defun org-open-file-with-emacs (path)
10788 "Open file at PATH in Emacs."
10789 (org-open-file path 'emacs))
10794 (defvar org-create-file-search-functions nil
10795 "List of functions to construct the right search string for a file link.
10796 These functions are called in turn with point at the location to
10797 which the link should point.
10799 A function in the hook should first test if it would like to
10800 handle this file type, for example by checking the `major-mode'
10801 or the file extension. If it decides not to handle this file, it
10802 should just return nil to give other functions a chance. If it
10803 does handle the file, it must return the search string to be used
10804 when following the link. The search string will be part of the
10805 file link, given after a double colon, and `org-open-at-point'
10806 will automatically search for it. If special measures must be
10807 taken to make the search successful, another function should be
10808 added to the companion hook `org-execute-file-search-functions',
10811 A function in this hook may also use `setq' to set the variable
10812 `description' to provide a suggestion for the descriptive text to
10813 be used for this link when it gets inserted into an Org buffer
10814 with \\[org-insert-link].")
10816 (defvar org-execute-file-search-functions nil
10817 "List of functions to execute a file search triggered by a link.
10819 Functions added to this hook must accept a single argument, the
10820 search string that was part of the file link, the part after the
10821 double colon. The function must first check if it would like to
10822 handle this search, for example by checking the `major-mode' or
10823 the file extension. If it decides not to handle this search, it
10824 should just return nil to give other functions a chance. If it
10825 does handle the search, it must return a non-nil value to keep
10826 other functions from trying.
10828 Each function can access the current prefix argument through the
10829 variable `current-prefix-arg'. Note that a single prefix is used
10830 to force opening a link in Emacs, so it may be good to only use a
10831 numeric or double prefix to guide the search function.
10833 In case this is needed, a function in this hook can also restore
10834 the window configuration before `org-open-at-point' was called using:
10836 (set-window-configuration org-window-config-before-follow-link)")
10838 (defun org-search-radio-target (target)
10839 "Search a radio target matching TARGET in current buffer.
10840 White spaces are not significant."
10841 (let ((re (format "<<<%s>>>"
10842 (mapconcat #'regexp-quote
10843 (split-string target)
10844 "[ \t]+\\(?:\n[ \t]*\\)?")))
10846 (goto-char (point-min))
10847 (catch :radio-match
10848 (while (re-search-forward re nil t)
10850 (let ((object (org-element-context)))
10851 (when (eq (org-element-type object) 'radio-target)
10852 (goto-char (org-element-property :begin object))
10853 (org-show-context 'link-search)
10854 (throw :radio-match nil))))
10856 (user-error "No match for radio target: %s" target))))
10858 (defun org-link-search (s &optional avoid-pos stealth)
10859 "Search for a search string S.
10861 If S starts with \"#\", it triggers a custom ID search.
10863 If S is enclosed within parenthesis, it initiates a coderef
10866 If S is surrounded by forward slashes, it is interpreted as
10867 a regular expression. In Org mode files, this will create an
10868 `org-occur' sparse tree. In ordinary files, `occur' will be used
10869 to list matches. If the current buffer is in `dired-mode', grep
10870 will be used to search in all files.
10872 When AVOID-POS is given, ignore matches near that position.
10874 When optional argument STEALTH is non-nil, do not modify
10875 visibility around point, thus ignoring `org-show-context-detail'
10878 Search is case-insensitive and ignores white spaces. Return type
10879 of matched result, which is either `dedicated' or `fuzzy'."
10880 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10881 (let* ((case-fold-search t)
10883 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10884 (starred (eq (string-to-char normalized) ?*))
10885 (words (split-string (if starred (substring s 1) s)))
10886 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10887 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10890 ;; Check if there are any special search functions.
10891 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10892 ((eq (string-to-char s) ?#)
10893 ;; Look for a custom ID S if S starts with "#".
10894 (let* ((id (substring normalized 1))
10895 (match (org-find-property "CUSTOM_ID" id)))
10896 (if match (progn (goto-char match) (setf type 'dedicated))
10897 (error "No match for custom ID: %s" id))))
10898 ((string-match "\\`(\\(.*\\))\\'" normalized)
10899 ;; Look for coderef targets if S is enclosed within parenthesis.
10900 (let ((coderef (match-string-no-properties 1 normalized))
10901 (re (substring s-single-re 1 -1)))
10902 (goto-char (point-min))
10903 (catch :coderef-match
10904 (while (re-search-forward re nil t)
10905 (let ((element (org-element-at-point)))
10906 (when (and (memq (org-element-type element)
10907 '(example-block src-block))
10908 ;; Build proper regexp according to current
10909 ;; block's label format.
10912 (or (org-element-property :label-fmt element)
10913 org-coderef-label-format))))
10915 (beginning-of-line)
10916 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10917 (format label-fmt coderef))))))
10918 (setq type 'dedicated)
10919 (goto-char (match-beginning 1))
10920 (throw :coderef-match nil))))
10922 (error "No match for coderef: %s" coderef))))
10923 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10924 ;; Look for a regular expression.
10925 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10926 (match-string 1 s)))
10927 ;; From here, we handle fuzzy links.
10929 ;; Look for targets, only if not in a headline search.
10930 ((and (not starred)
10931 (let ((target (format "<<%s>>" s-multi-re)))
10932 (catch :target-match
10933 (goto-char (point-min))
10934 (while (re-search-forward target nil t)
10936 (let ((context (org-element-context)))
10937 (when (eq (org-element-type context) 'target)
10938 (setq type 'dedicated)
10939 (goto-char (org-element-property :begin context))
10940 (throw :target-match t))))
10942 ;; Look for elements named after S, only if not in a headline
10944 ((and (not starred)
10945 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10947 (goto-char (point-min))
10948 (while (re-search-forward name nil t)
10949 (let ((element (org-element-at-point)))
10952 (org-element-property :name element)))
10953 (setq type 'dedicated)
10954 (beginning-of-line)
10955 (throw :name-match t))))
10957 ;; Regular text search. Prefer headlines in Org mode buffers.
10958 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10959 ;; statistics cookies and tags.
10960 ((and (derived-mode-p 'org-mode)
10962 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10963 org-outline-regexp-bol
10965 (mapconcat #'regexp-quote words ".+")))
10966 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10967 (comment-re (eval-when-compile
10968 (format "\\`%s[ \t]+" org-comment-string))))
10969 (goto-char (point-min))
10971 (while (re-search-forward title-re nil t)
10974 (replace-regexp-in-string
10976 (replace-regexp-in-string
10977 comment-re "" (org-get-heading t t t)))))
10980 (beginning-of-line)
10981 (setq type 'dedicated))
10982 ;; Offer to create non-existent headline depending on
10983 ;; `org-link-search-must-match-exact-headline'.
10984 ((and (derived-mode-p 'org-mode)
10985 (not org-link-search-inhibit-query)
10986 (eq org-link-search-must-match-exact-headline 'query-to-create)
10987 (yes-or-no-p "No match - create this as a new heading? "))
10988 (goto-char (point-max))
10989 (unless (bolp) (newline))
10990 (org-insert-heading nil t t)
10992 (beginning-of-line 0))
10993 ;; Only headlines are looked after. No need to process
10994 ;; further: throw an error.
10995 ((and (derived-mode-p 'org-mode)
10996 (or starred org-link-search-must-match-exact-headline))
10998 (error "No match for fuzzy expression: %s" normalized))
10999 ;; Regular text search.
11000 ((catch :fuzzy-match
11001 (goto-char (point-min))
11002 (while (re-search-forward s-multi-re nil t)
11003 ;; Skip match if it contains AVOID-POS or it is included in
11004 ;; a link with a description but outside the description.
11005 (unless (or (and avoid-pos
11006 (<= (match-beginning 0) avoid-pos)
11007 (> (match-end 0) avoid-pos))
11008 (and (save-match-data
11009 (org-in-regexp org-bracket-link-regexp))
11010 (match-beginning 3)
11011 (or (> (match-beginning 3) (point))
11012 (<= (match-end 3) (point)))
11013 (org-element-lineage
11014 (save-match-data (org-element-context))
11016 (goto-char (match-beginning 0))
11018 (throw :fuzzy-match t)))
11020 ;; All failed. Throw an error.
11021 (t (goto-char origin)
11022 (error "No match for fuzzy expression: %s" normalized)))
11023 ;; Disclose surroundings of match, if appropriate.
11024 (when (and (derived-mode-p 'org-mode) (not stealth))
11025 (org-show-context 'link-search))
11028 (defun org-get-buffer-for-internal-link (buffer)
11029 "Return a buffer to be used for displaying the link target of internal links."
11031 ((not org-display-internal-link-with-indirect-buffer)
11033 ((string-suffix-p "(Clone)" (buffer-name buffer))
11034 (message "Buffer is already a clone, not making another one")
11035 ;; we also do not modify visibility in this case
11037 (t ; make a new indirect buffer for displaying the link
11038 (let* ((bn (buffer-name buffer))
11039 (ibn (concat bn "(Clone)"))
11040 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11041 (with-current-buffer ib (org-overview))
11044 (defun org-do-occur (regexp &optional cleanup)
11045 "Call the Emacs command `occur'.
11046 If CLEANUP is non-nil, remove the printout of the regular expression
11047 in the *Occur* buffer. This is useful if the regex is long and not useful
11051 (let ((cwin (selected-window)) win beg end)
11052 (when (setq win (get-buffer-window "*Occur*"))
11053 (select-window win))
11054 (goto-char (point-min))
11055 (when (re-search-forward "match[a-z]+" nil t)
11056 (setq beg (match-end 0))
11057 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11058 (setq end (1- (match-beginning 0)))))
11059 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11060 (goto-char (point-min))
11061 (select-window cwin))))
11063 ;;; The mark ring for links jumps
11065 (defvar org-mark-ring nil
11066 "Mark ring for positions before jumps in Org mode.")
11067 (defvar org-mark-ring-last-goto nil
11068 "Last position in the mark ring used to go back.")
11069 ;; Fill and close the ring
11070 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11071 (dotimes (_ org-mark-ring-length)
11072 (push (make-marker) org-mark-ring))
11073 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11076 (defun org-mark-ring-push (&optional pos buffer)
11077 "Put the current position or POS into the mark ring and rotate it."
11079 (setq pos (or pos (point)))
11080 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11081 (move-marker (car org-mark-ring)
11083 (or buffer (current-buffer)))
11085 (substitute-command-keys
11086 "Position saved to mark ring, go back with \
11087 `\\[org-mark-ring-goto]'.")))
11089 (defun org-mark-ring-goto (&optional n)
11090 "Jump to the previous position in the mark ring.
11091 With prefix arg N, jump back that many stored positions. When
11092 called several times in succession, walk through the entire ring.
11093 Org mode commands jumping to a different position in the current file,
11094 or to another Org file, automatically push the old position onto the ring."
11097 (if (eq last-command this-command)
11098 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11099 (setq p org-mark-ring))
11100 (setq org-mark-ring-last-goto p)
11102 (pop-to-buffer-same-window (marker-buffer m))
11104 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11106 (defun org-add-angle-brackets (s)
11107 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11108 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11111 ;;; Following specific links
11113 (defvar org-agenda-buffer-tmp-name)
11114 (defvar org-agenda-start-on-weekday)
11115 (defun org-follow-timestamp-link ()
11116 "Open an agenda view for the time-stamp date/range at point."
11118 ((org-at-date-range-p t)
11119 (let ((org-agenda-start-on-weekday)
11120 (t1 (match-string 1))
11121 (t2 (match-string 2)) tt1 tt2)
11122 (setq tt1 (time-to-days (org-time-string-to-time t1))
11123 tt2 (time-to-days (org-time-string-to-time t2)))
11124 (let ((org-agenda-buffer-tmp-name
11125 (format "*Org Agenda(a:%s)"
11126 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11127 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11128 ((org-at-timestamp-p 'lax)
11129 (let ((org-agenda-buffer-tmp-name
11130 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11131 (org-agenda-list nil (time-to-days (org-time-string-to-time
11132 (substring (match-string 1) 0 10)))
11134 (t (error "This should not happen"))))
11137 ;;; Following file links
11138 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11139 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11140 (declare-function mailcap-mime-info
11141 "mailcap" (string &optional request no-decode))
11142 (defvar org-wait nil)
11143 (defun org-open-file (path &optional in-emacs line search)
11144 "Open the file at PATH.
11145 First, this expands any special file name abbreviations. Then the
11146 configuration variable `org-file-apps' is checked if it contains an
11147 entry for this file type, and if yes, the corresponding command is launched.
11149 If no application is found, Emacs simply visits the file.
11151 With optional prefix argument IN-EMACS, Emacs will visit the file.
11152 With a double \\[universal-argument] \\[universal-argument] \
11153 prefix arg, Org tries to avoid opening in Emacs
11154 and to use an external application to visit the file.
11156 Optional LINE specifies a line to go to, optional SEARCH a string
11157 to search for. If LINE or SEARCH is given, the file will be
11158 opened in Emacs, unless an entry from org-file-apps that makes
11159 use of groups in a regexp matches.
11161 If you want to change the way frames are used when following a
11162 link, please customize `org-link-frame-setup'.
11164 If the file does not exist, an error is thrown."
11165 (let* ((file (if (equal path "")
11167 (substitute-in-file-name (expand-file-name path))))
11168 (file-apps (append org-file-apps (org-default-apps)))
11169 (apps (cl-remove-if
11170 'org-file-apps-entry-match-against-dlink-p file-apps))
11171 (apps-dlink (cl-remove-if-not
11172 'org-file-apps-entry-match-against-dlink-p file-apps))
11173 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11174 (dirp (unless remp (file-directory-p file)))
11175 (file (if (and dirp org-open-directory-means-index-dot-org)
11176 (concat (file-name-as-directory file) "index.org")
11178 (a-m-a-p (assq 'auto-mode apps))
11179 (dfile (downcase file))
11180 ;; Reconstruct the original link from the PATH, LINE and
11182 (link (cond (line (concat file "::" (number-to-string line)))
11183 (search (concat file "::" search))
11185 (dlink (downcase link))
11187 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11188 (match-string 1 dfile)))
11189 (save-position-maybe
11190 (let ((old-buffer (current-buffer))
11192 (old-mode major-mode))
11194 (and (derived-mode-p 'org-mode)
11195 (eq old-mode 'org-mode)
11196 (or (not (eq old-buffer (current-buffer)))
11197 (not (eq old-pos (point))))
11198 (org-mark-ring-push old-pos old-buffer)))))
11199 cmd link-match-data)
11201 ((member in-emacs '((16) system))
11202 (setq cmd (cdr (assq 'system apps))))
11203 (in-emacs (setq cmd 'emacs))
11205 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11206 (and dirp (cdr (assq 'directory apps)))
11207 ;; First, try matching against apps-dlink if we
11208 ;; get a match here, store the match data for
11210 (let ((match (assoc-default dlink apps-dlink
11213 (progn (setq link-match-data (match-data))
11215 (progn (setq in-emacs (or in-emacs line search))
11216 nil))) ; if we have no match in apps-dlink,
11217 ; always open the file in emacs if line or search
11218 ; is given (for backwards compatibility)
11219 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11221 (cdr (assoc ext apps))
11222 (cdr (assq t apps))))))
11223 (when (eq cmd 'system)
11224 (setq cmd (cdr (assq 'system apps))))
11225 (when (eq cmd 'default)
11226 (setq cmd (cdr (assoc t apps))))
11227 (when (eq cmd 'mailcap)
11229 (mailcap-parse-mailcaps)
11230 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11231 (command (mailcap-mime-info mime-type)))
11232 (if (stringp command)
11234 (setq cmd 'emacs))))
11235 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11236 (not (file-exists-p file))
11237 (not org-open-non-existing-files))
11238 (user-error "No such file: %s" file))
11240 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11241 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11242 (while (string-match "['\"]%s['\"]" cmd)
11243 (setq cmd (replace-match "%s" t t cmd)))
11244 (setq cmd (replace-regexp-in-string
11246 (shell-quote-argument (convert-standard-filename file))
11250 ;; Replace "%1", "%2" etc. in command with group matches from regex
11252 (let ((match-index 1)
11253 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11254 (set-match-data link-match-data)
11255 (while (<= match-index number-of-groups)
11256 (let ((regex (concat "%" (number-to-string match-index)))
11257 (replace-with (match-string match-index dlink)))
11258 (while (string-match regex cmd)
11259 (setq cmd (replace-match replace-with t t cmd))))
11260 (setq match-index (+ match-index 1)))))
11262 (save-window-excursion
11263 (message "Running %s...done" cmd)
11264 (start-process-shell-command cmd nil cmd)
11265 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11268 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11270 (cond (line (org-goto-line line)
11271 (when (derived-mode-p 'org-mode) (org-reveal)))
11272 (search (condition-case err
11273 (org-link-search search)
11274 ;; Save position before error-ing out so user
11275 ;; can easily move back to the original buffer.
11276 (error (funcall save-position-maybe)
11277 (error (nth 1 err)))))))
11280 (set-match-data link-match-data)
11281 (condition-case nil
11282 (funcall cmd file link)
11283 ;; FIXME: Remove this check when most default installations
11284 ;; of Emacs have at least Org 9.0.
11285 ((debug wrong-number-of-arguments wrong-type-argument
11287 (user-error "Please see Org News for version 9.0 about \
11288 `org-file-apps'--Lisp error: %S" cmd)))))
11290 ;; FIXME: Remove this check when most default installations of
11291 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11292 ;; fall back to `org-link-frame-setup' for an old usage of
11293 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11294 (user-error "Please see Org News for version 9.0 about \
11295 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11296 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11297 (funcall save-position-maybe)))
11299 (defun org-file-apps-entry-match-against-dlink-p (entry)
11300 "This function returns non-nil if `entry' uses a regular
11301 expression which should be matched against the whole link by
11304 It assumes that is the case when the entry uses a regular
11305 expression which has at least one grouping construct and the
11306 action is either a lisp form or a command string containing
11307 `%1', i.e. using at least one subexpression match as a
11309 (let ((selector (car entry))
11310 (action (cdr entry)))
11311 (if (stringp selector)
11312 (and (> (regexp-opt-depth selector) 0)
11313 (or (and (stringp action)
11314 (string-match "%[0-9]" action))
11318 (defun org-default-apps ()
11319 "Return the default applications for this operating system."
11321 ((eq system-type 'darwin)
11322 org-file-apps-defaults-macosx)
11323 ((eq system-type 'windows-nt)
11324 org-file-apps-defaults-windowsnt)
11325 (t org-file-apps-defaults-gnu)))
11327 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11328 "Convert extensions to regular expressions in the cars of LIST.
11329 Also, weed out any non-string entries, because the return value is used
11330 only for regexp matching.
11331 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11332 point to the symbol `emacs', indicating that the file should
11333 be opened in Emacs."
11336 (mapcar (lambda (x)
11337 (unless (not (stringp (car x)))
11338 (if (string-match "\\W" (car x))
11340 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11342 (when add-auto-mode
11343 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11345 (defvar ange-ftp-name-format)
11346 (defun org-file-remote-p (file)
11347 "Test whether FILE specifies a location on a remote system.
11348 Return non-nil if the location is indeed remote.
11350 For example, the filename \"/user@host:/foo\" specifies a location
11351 on the system \"/user@host:\"."
11352 (cond ((fboundp 'file-remote-p)
11353 (file-remote-p file))
11354 ((fboundp 'tramp-handle-file-remote-p)
11355 (tramp-handle-file-remote-p file))
11356 ((and (boundp 'ange-ftp-name-format)
11357 (string-match (car ange-ftp-name-format) file))
11363 (defun org-get-org-file ()
11364 "Read a filename, with default directory `org-directory'."
11365 (let ((default (or org-default-notes-file remember-data-file)))
11366 (read-file-name (format "File name [%s]: " default)
11367 (file-name-as-directory org-directory)
11370 (defun org-notes-order-reversed-p ()
11371 "Check if the current file should receive notes in reversed order."
11373 ((not org-reverse-note-order) nil)
11374 ((eq t org-reverse-note-order) t)
11375 ((not (listp org-reverse-note-order)) nil)
11377 (dolist (entry org-reverse-note-order)
11378 (when (string-match (car entry) buffer-file-name)
11379 (throw 'exit (cdr entry))))))))
11381 (defvar org-refile-target-table nil
11382 "The list of refile targets, created by `org-refile'.")
11384 (defvar org-agenda-new-buffers nil
11385 "Buffers created to visit agenda files.")
11387 (defvar org-refile-cache nil
11388 "Cache for refile targets.")
11390 (defvar org-refile-markers nil
11391 "All the markers used for caching refile locations.")
11393 (defun org-refile-marker (pos)
11394 "Get a new refile marker, but only if caching is in use."
11395 (if (not org-refile-use-cache)
11397 (let ((m (make-marker)))
11398 (move-marker m pos)
11399 (push m org-refile-markers)
11402 (defun org-refile-cache-clear ()
11403 "Clear the refile cache and disable all the markers."
11404 (dolist (m org-refile-markers) (move-marker m nil))
11405 (setq org-refile-markers nil)
11406 (setq org-refile-cache nil)
11407 (message "Refile cache has been cleared"))
11409 (defun org-refile-cache-check-set (set)
11410 "Check if all the markers in the cache still have live buffers."
11413 (while (and set (setq marker (nth 3 (pop set))))
11414 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11415 (when (and marker (null (marker-buffer marker)))
11416 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11418 (throw 'exit nil)))
11421 (defun org-refile-cache-put (set &rest identifiers)
11422 "Push the refile targets SET into the cache, under IDENTIFIERS."
11423 (let* ((key (sha1 (prin1-to-string identifiers)))
11424 (entry (assoc key org-refile-cache)))
11427 (push (cons key set) org-refile-cache))))
11429 (defun org-refile-cache-get (&rest identifiers)
11430 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11432 ((not org-refile-cache) nil)
11433 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11435 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11436 org-refile-cache))))
11437 (and set (org-refile-cache-check-set set) set)))))
11439 (defvar org-outline-path-cache nil
11440 "Alist between buffer positions and outline paths.
11441 It value is an alist (POSITION . PATH) where POSITION is the
11442 buffer position at the beginning of an entry and PATH is a list
11443 of strings describing the outline path for that entry, in reverse
11446 (defun org-refile-get-targets (&optional default-buffer)
11447 "Produce a table with refile targets."
11448 (let ((case-fold-search nil)
11449 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11450 (entries (or org-refile-targets '((nil . (:level . 1)))))
11451 targets tgs files desc descre)
11452 (message "Getting targets...")
11453 (with-current-buffer (or default-buffer (current-buffer))
11454 (dolist (entry entries)
11455 (setq files (car entry) desc (cdr entry))
11457 ((null files) (setq files (list (current-buffer))))
11458 ((eq files 'org-agenda-files)
11459 (setq files (org-agenda-files 'unrestricted)))
11460 ((and (symbolp files) (fboundp files))
11461 (setq files (funcall files)))
11462 ((and (symbolp files) (boundp files))
11463 (setq files (symbol-value files))))
11464 (when (stringp files) (setq files (list files)))
11466 ((eq (car desc) :tag)
11467 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11468 ((eq (car desc) :todo)
11469 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11470 ((eq (car desc) :regexp)
11471 (setq descre (cdr desc)))
11472 ((eq (car desc) :level)
11473 (setq descre (concat "^\\*\\{" (number-to-string
11474 (if org-odd-levels-only
11475 (1- (* 2 (cdr desc)))
11478 ((eq (car desc) :maxlevel)
11479 (setq descre (concat "^\\*\\{1," (number-to-string
11480 (if org-odd-levels-only
11481 (1- (* 2 (cdr desc)))
11484 (t (error "Bad refiling target description %s" desc)))
11486 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11488 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11491 (setq f (buffer-file-name (buffer-base-buffer f))))
11492 (setq f (and f (expand-file-name f)))
11493 (when (eq org-refile-use-outline-path 'file)
11494 (push (list (file-name-nondirectory f) f nil nil) tgs))
11495 (when (eq org-refile-use-outline-path 'buffer-name)
11496 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11497 (when (eq org-refile-use-outline-path 'full-file-path)
11498 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11499 (org-with-wide-buffer
11500 (goto-char (point-min))
11501 (setq org-outline-path-cache nil)
11502 (while (re-search-forward descre nil t)
11503 (beginning-of-line)
11504 (let ((case-fold-search nil))
11505 (looking-at org-complex-heading-regexp))
11506 (let ((begin (point))
11507 (heading (match-string-no-properties 4)))
11509 org-refile-target-verify-function
11511 (funcall org-refile-target-verify-function)))
11513 (let ((re (format org-complex-heading-regexp-format
11514 (regexp-quote heading)))
11516 (if (not org-refile-use-outline-path) heading
11520 (pcase org-refile-use-outline-path
11521 (`file (list (file-name-nondirectory
11523 (buffer-base-buffer)))))
11525 (list (buffer-file-name
11526 (buffer-base-buffer))))
11529 (buffer-base-buffer))))
11531 (mapcar (lambda (s) (replace-regexp-in-string
11532 "/" "\\/" s nil t))
11533 (org-get-outline-path t t)))
11535 (push (list target f re (org-refile-marker (point)))
11537 (when (= (point) begin)
11538 ;; Verification function has not moved point.
11539 (end-of-line)))))))
11540 (when org-refile-use-cache
11541 (org-refile-cache-put tgs (buffer-file-name) descre))
11542 (setq targets (append tgs targets))))))
11543 (message "Getting targets...done")
11544 (delete-dups (nreverse targets))))
11546 (defun org--get-outline-path-1 (&optional use-cache)
11547 "Return outline path to current headline.
11549 Outline path is a list of strings, in reverse order. When
11550 optional argument USE-CACHE is non-nil, make use of a cache. See
11551 `org-get-outline-path' for details.
11553 Assume buffer is widened and point is on a headline."
11554 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11556 (heading (let ((case-fold-search nil))
11557 (looking-at org-complex-heading-regexp)
11558 (if (not (match-end 4)) ""
11559 ;; Remove statistics cookies.
11561 (org-link-display-format
11562 (replace-regexp-in-string
11563 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11564 (match-string-no-properties 4))))))))
11565 (if (org-up-heading-safe)
11566 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11568 (push (cons p path) org-outline-path-cache))
11570 ;; This is a new root node. Since we assume we are moving
11571 ;; forward, we can drop previous cache so as to limit number
11572 ;; of associations there.
11573 (let ((path (list heading)))
11574 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11577 (defun org-get-outline-path (&optional with-self use-cache)
11578 "Return the outline path to the current entry.
11580 An outline path is a list of ancestors for current headline, as
11581 a list of strings. Statistics cookies are removed and links are
11582 replaced with their description, if any, or their path otherwise.
11584 When optional argument WITH-SELF is non-nil, the path also
11585 includes the current headline.
11587 When optional argument USE-CACHE is non-nil, cache outline paths
11588 between calls to this function so as to avoid backtracking. This
11589 argument is useful when planning to find more than one outline
11590 path in the same document. In that case, there are two
11591 conditions to satisfy:
11592 - `org-outline-path-cache' is set to nil before starting the
11594 - outline paths are computed by increasing buffer positions."
11595 (org-with-wide-buffer
11596 (and (or (and with-self (org-back-to-heading t))
11597 (org-up-heading-safe))
11598 (reverse (org--get-outline-path-1 use-cache)))))
11600 (defun org-format-outline-path (path &optional width prefix separator)
11601 "Format the outline path PATH for display.
11602 WIDTH is the maximum number of characters that is available.
11603 PREFIX is a prefix to be included in the returned string,
11604 such as the file name.
11605 SEPARATOR is inserted between the different parts of the path,
11606 the default is \"/\"."
11607 (setq width (or width 79))
11608 (setq path (delq nil path))
11609 (unless (> width 0)
11610 (user-error "Argument `width' must be positive"))
11611 (setq separator (or separator "/"))
11612 (let* ((org-odd-levels-only nil)
11614 prefix (and prefix path separator)
11616 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11617 (cl-loop for head in path
11619 collect (org-add-props
11621 (nth (% n org-n-level-faces) org-level-faces)))
11623 (when (> (length fpath) width)
11625 ;; It's unlikely that `width' will be this small, but don't
11626 ;; waste characters by adding ".." if it is.
11627 (setq fpath (substring fpath 0 width))
11628 (setf (substring fpath (- width 2)) "..")))
11631 (defun org-display-outline-path (&optional file current separator just-return-string)
11632 "Display the current outline path in the echo area.
11634 If FILE is non-nil, prepend the output with the file name.
11635 If CURRENT is non-nil, append the current heading to the output.
11636 SEPARATOR is passed through to `org-format-outline-path'. It separates
11637 the different parts of the path and defaults to \"/\".
11638 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11640 (let* (case-fold-search
11641 (bfn (buffer-file-name (buffer-base-buffer)))
11642 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11644 (when current (setq path (append path
11646 (org-back-to-heading t)
11647 (when (looking-at org-complex-heading-regexp)
11648 (list (match-string 4)))))))
11650 (org-format-outline-path
11653 (and file bfn (concat (file-name-nondirectory bfn) separator))
11655 (if just-return-string
11656 (org-no-properties res)
11657 (org-unlogged-message "%s" res))))
11659 (defvar org-refile-history nil
11660 "History for refiling operations.")
11662 (defvar org-after-refile-insert-hook nil
11663 "Hook run after `org-refile' has inserted its stuff at the new location.
11664 Note that this is still *before* the stuff will be removed from
11665 the *old* location.")
11667 (defvar org-capture-last-stored-marker)
11668 (defvar org-refile-keep nil
11669 "Non-nil means `org-refile' will copy instead of refile.")
11672 "Like `org-refile', but copy."
11674 (let ((org-refile-keep t))
11675 (funcall 'org-refile nil nil nil "Copy")))
11677 (defun org-refile (&optional arg default-buffer rfloc msg)
11678 "Move the entry or entries at point to another heading.
11680 The list of target headings is compiled using the information in
11681 `org-refile-targets', which see.
11683 At the target location, the entry is filed as a subitem of the
11684 target heading. Depending on `org-reverse-note-order', the new
11685 subitem will either be the first or the last subitem.
11687 If there is an active region, all entries in that region will be
11688 refiled. However, the region must fulfill the requirement that
11689 the first heading sets the top-level of the moved text.
11691 With a `\\[universal-argument]' ARG, the command will only visit the target \
11693 and not actually move anything.
11695 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11696 location where the last
11697 refiling operation has put the subtree.
11699 With a numeric prefix argument of `2', refile to the running clock.
11701 With a numeric prefix argument of `3', emulate `org-refile-keep'
11702 being set to t and copy to the target location, don't move it.
11703 Beware that keeping refiled entries may result in duplicated ID
11706 RFLOC can be a refile location obtained in a different way.
11708 MSG is a string to replace \"Refile\" in the default prompt with
11709 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11711 See also `org-refile-use-outline-path'.
11713 If you are using target caching (see `org-refile-use-cache'), you
11714 have to clear the target cache in order to find new targets.
11715 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11716 prefix argument (`C-u C-u C-u C-c C-w')."
11718 (if (member arg '(0 (64)))
11719 (org-refile-cache-clear)
11720 (let* ((actionmsg (cond (msg msg)
11721 ((equal arg 3) "Refile (and keep)")
11723 (regionp (org-region-active-p))
11724 (region-start (and regionp (region-beginning)))
11725 (region-end (and regionp (region-end)))
11726 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11727 pos it nbuf file level reversed)
11728 (setq last-command nil)
11730 (goto-char region-start)
11731 (or (bolp) (goto-char (point-at-bol)))
11732 (setq region-start (point))
11733 (unless (or (org-kill-is-subtree-p
11734 (buffer-substring region-start region-end))
11735 (prog1 org-refile-active-region-within-subtree
11736 (let ((s (point-at-eol)))
11737 (org-toggle-heading)
11738 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11739 (user-error "The region is not a (sequence of) subtree(s)")))
11740 (if (equal arg '(16))
11741 (org-refile-goto-last-stored)
11744 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11746 (setq it (list (or org-clock-heading "running clock")
11748 (marker-buffer org-clock-hd-marker))
11750 (marker-position org-clock-hd-marker)))
11754 (let (heading-text)
11756 (unless (and arg (listp arg))
11757 (org-back-to-heading t)
11759 (replace-regexp-in-string
11760 org-bracket-link-regexp
11762 (or (nth 4 (org-heading-components))
11764 (org-refile-get-location
11765 (cond ((and arg (listp arg)) "Goto")
11766 (regionp (concat actionmsg " region to"))
11767 (t (concat actionmsg " subtree \""
11768 heading-text "\" to")))
11770 (and (not (equal '(4) arg))
11771 org-refile-allow-creating-parent-nodes)))))))
11772 (setq file (nth 1 it)
11774 (when (and (not arg)
11776 (equal (buffer-file-name) file)
11778 (and (>= pos region-start)
11779 (<= pos region-end))
11780 (and (>= pos (point))
11781 (< pos (save-excursion
11782 (org-end-of-subtree t t))))))
11783 (error "Cannot refile to position inside the tree or region"))
11784 (setq nbuf (or (find-buffer-visiting file)
11785 (find-file-noselect file)))
11786 (if (and arg (not (equal arg 3)))
11788 (pop-to-buffer-same-window nbuf)
11789 (goto-char (cond (pos)
11790 ((org-notes-order-reversed-p) (point-min))
11792 (org-show-context 'org-goto))
11795 (org-kill-new (buffer-substring region-start region-end))
11796 (org-save-markers-in-region region-start region-end))
11797 (org-copy-subtree 1 nil t))
11798 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11799 (find-file-noselect file)))
11800 (setq reversed (org-notes-order-reversed-p))
11801 (org-with-wide-buffer
11805 (setq level (org-get-valid-level (funcall outline-level) 1))
11808 (or (outline-next-heading) (point-max))
11809 (or (save-excursion (org-get-next-sibling))
11810 (org-end-of-subtree t t)
11814 (goto-char (point-max))
11815 (goto-char (point-min))
11816 (or (outline-next-heading) (goto-char (point-max)))))
11817 (unless (bolp) (newline))
11818 (org-paste-subtree level nil nil t)
11819 (when org-log-refile
11820 (org-add-log-setup 'refile nil nil org-log-refile)
11821 (unless (eq org-log-refile 'note)
11822 (save-excursion (org-add-log-note))))
11823 (and org-auto-align-tags
11824 (let ((org-loop-over-headlines-in-active-region nil))
11825 (org-set-tags nil t)))
11826 (let ((bookmark-name (plist-get org-bookmark-names-plist
11828 (when bookmark-name
11829 (with-demoted-errors
11830 (bookmark-set bookmark-name))))
11831 ;; If we are refiling for capture, make sure that the
11832 ;; last-capture pointers point here
11833 (when (bound-and-true-p org-capture-is-refiling)
11834 (let ((bookmark-name (plist-get org-bookmark-names-plist
11835 :last-capture-marker)))
11836 (when bookmark-name
11837 (with-demoted-errors
11838 (bookmark-set bookmark-name))))
11839 (move-marker org-capture-last-stored-marker (point)))
11840 (when (fboundp 'deactivate-mark) (deactivate-mark))
11841 (run-hooks 'org-after-refile-insert-hook)))
11842 (unless org-refile-keep
11844 (delete-region (point) (+ (point) (- region-end region-start)))
11846 (and (org-back-to-heading t) (point))
11847 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11848 (when (featurep 'org-inlinetask)
11849 (org-inlinetask-remove-END-maybe))
11850 (setq org-markers-to-move nil)
11851 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11853 (defun org-refile-goto-last-stored ()
11854 "Go to the location where the last refile was stored."
11856 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11857 (message "This is the location of the last refile"))
11859 (defun org-refile--get-location (refloc tbl)
11860 "When user refile to REFLOC, find the associated target in TBL.
11861 Also check `org-refile-target-table'."
11865 (lambda (r) (or (assoc r tbl)
11866 (assoc r org-refile-target-table)))
11867 (list (replace-regexp-in-string "/$" "" refloc)
11868 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11870 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11871 "Prompt the user for a refile location, using PROMPT.
11872 PROMPT should not be suffixed with a colon and a space, because
11873 this function appends the default value from
11874 `org-refile-history' automatically, if that is not empty."
11875 (let ((org-refile-targets org-refile-targets)
11876 (org-refile-use-outline-path org-refile-use-outline-path))
11877 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11878 (unless org-refile-target-table
11879 (user-error "No refile targets"))
11880 (let* ((cbuf (current-buffer))
11881 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11882 (cfunc (if (and org-refile-use-outline-path
11883 org-outline-path-complete-in-steps)
11884 #'org-olpath-completing-read
11885 #'completing-read))
11886 (extra (if org-refile-use-outline-path "/" ""))
11887 (cbnex (concat (buffer-name) extra))
11888 (filename (and cfn (expand-file-name cfn)))
11891 (if (and (not (member org-refile-use-outline-path
11892 '(file full-file-path)))
11893 (not (equal filename (nth 1 x))))
11894 (cons (concat (car x) extra " ("
11895 (file-name-nondirectory (nth 1 x)) ")")
11897 (cons (concat (car x) extra) (cdr x))))
11898 org-refile-target-table))
11899 (completion-ignore-case t)
11901 (prompt (concat prompt
11902 (or (and (car org-refile-history)
11903 (concat " (default " (car org-refile-history) ")"))
11904 (and (assoc cbnex tbl) (setq cdef cbnex)
11905 (concat " (default " cbnex ")"))) ": "))
11906 pa answ parent-target child parent old-hist)
11907 (setq old-hist org-refile-history)
11908 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11909 nil 'org-refile-history (or cdef (car org-refile-history))))
11910 (if (setq pa (org-refile--get-location answ tbl))
11912 (org-refile-check-position pa)
11913 (when (or (not org-refile-history)
11914 (not (eq old-hist org-refile-history))
11915 (not (equal (car pa) (car org-refile-history))))
11916 (setq org-refile-history
11917 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11919 (cdr org-refile-history))))
11920 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11921 (pop org-refile-history)))
11923 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11925 (setq parent (match-string 1 answ)
11926 child (match-string 2 answ))
11927 (setq parent-target (org-refile--get-location parent tbl))
11928 (when (and parent-target
11929 (or (eq new-nodes t)
11930 (and (eq new-nodes 'confirm)
11931 (y-or-n-p (format "Create new node \"%s\"? "
11933 (org-refile-new-child parent-target child)))
11934 (user-error "Invalid target location")))))
11936 (declare-function org-string-nw-p "org-macs" (s))
11937 (defun org-refile-check-position (refile-pointer)
11938 "Check if the refile pointer matches the headline to which it points."
11939 (let* ((file (nth 1 refile-pointer))
11940 (re (nth 2 refile-pointer))
11941 (pos (nth 3 refile-pointer))
11943 (if (and (not (markerp pos)) (not file))
11944 (user-error "Please indicate a target file in the refile path")
11945 (when (org-string-nw-p re)
11946 (setq buffer (if (markerp pos)
11947 (marker-buffer pos)
11948 (or (find-buffer-visiting file)
11949 (find-file-noselect file))))
11950 (with-current-buffer buffer
11951 (org-with-wide-buffer
11953 (beginning-of-line 1)
11954 (unless (looking-at-p re)
11955 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11957 (defun org-refile-new-child (parent-target child)
11958 "Use refile target PARENT-TARGET to add new CHILD below it."
11959 (unless parent-target
11960 (error "Cannot find parent for new node"))
11961 (let ((file (nth 1 parent-target))
11962 (pos (nth 3 parent-target))
11964 (with-current-buffer (or (find-buffer-visiting file)
11965 (find-file-noselect file))
11966 (org-with-wide-buffer
11969 (goto-char (point-max))
11970 (unless (bolp) (newline)))
11971 (when (looking-at org-outline-regexp)
11972 (setq level (funcall outline-level))
11973 (org-end-of-subtree t t))
11974 (org-back-over-empty-lines)
11975 (insert "\n" (make-string
11976 (if pos (org-get-valid-level level 1) 1) ?*)
11978 (beginning-of-line 0)
11979 (list (concat (car parent-target) "/" child) file "" (point))))))
11981 (defun org-olpath-completing-read (prompt collection &rest args)
11982 "Read an outline path like a file name."
11983 (let ((thetable collection))
11984 (apply #'completing-read
11986 (lambda (string predicate &optional flag)
11988 ((eq flag nil) (try-completion string thetable))
11990 (let ((l (length string)))
11991 (mapcar (lambda (x)
11992 (let ((r (substring x l))
11993 (f (if (string-match " ([^)]*)$" x)
11996 (if (string-match "/" r)
11997 (concat string (substring r 0 (match-end 0)) f)
11999 (all-completions string thetable predicate))))
12001 ((eq flag 'lambda) (assoc string thetable))))
12004 ;;;; Dynamic blocks
12006 (defun org-find-dblock (name)
12007 "Find the first dynamic block with name NAME in the buffer.
12008 If not found, stay at current position and return nil."
12009 (let ((case-fold-search t) pos)
12011 (goto-char (point-min))
12012 (setq pos (and (re-search-forward
12013 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12014 (match-beginning 0))))
12015 (when pos (goto-char pos))
12018 (defun org-create-dblock (plist)
12019 "Create a dynamic block section, with parameters taken from PLIST.
12020 PLIST must contain a :name entry which is used as the name of the block."
12021 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12024 (let ((col (current-column))
12025 (name (plist-get plist :name)))
12026 (insert "#+BEGIN: " name)
12028 (if (eq (car plist) :name)
12029 (setq plist (cddr plist))
12030 (insert " " (prin1-to-string (pop plist)))))
12031 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12032 (beginning-of-line -2)))
12034 (defun org-prepare-dblock ()
12035 "Prepare dynamic block for refresh.
12036 This empties the block, puts the cursor at the insert position and returns
12037 the property list including an extra property :name with the block name."
12038 (unless (looking-at org-dblock-start-re)
12039 (user-error "Not at a dynamic block"))
12040 (let* ((begdel (1+ (match-end 0)))
12041 (name (org-no-properties (match-string 1)))
12042 (params (append (list :name name)
12043 (read (concat "(" (match-string 3) ")")))))
12045 (beginning-of-line 1)
12046 (skip-chars-forward " \t")
12047 (setq params (plist-put params :indentation-column (current-column))))
12048 (unless (re-search-forward org-dblock-end-re nil t)
12049 (error "Dynamic block not terminated"))
12052 (list :content (buffer-substring
12053 begdel (match-beginning 0)))))
12054 (delete-region begdel (match-beginning 0))
12059 (defun org-map-dblocks (&optional command)
12060 "Apply COMMAND to all dynamic blocks in the current buffer.
12061 If COMMAND is not given, use `org-update-dblock'."
12062 (let ((cmd (or command 'org-update-dblock)))
12064 (goto-char (point-min))
12065 (while (re-search-forward org-dblock-start-re nil t)
12066 (goto-char (match-beginning 0))
12068 (condition-case nil
12070 (error (message "Error during update of dynamic block"))))
12071 (unless (re-search-forward org-dblock-end-re nil t)
12072 (error "Dynamic block not terminated"))))))
12074 (defun org-dblock-update (&optional arg)
12075 "User command for updating dynamic blocks.
12076 Update the dynamic block at point. With prefix ARG, update all dynamic
12077 blocks in the buffer."
12080 (org-update-all-dblocks)
12081 (or (looking-at org-dblock-start-re)
12082 (org-beginning-of-dblock))
12083 (org-update-dblock)))
12085 (defun org-update-dblock ()
12086 "Update the dynamic block at point.
12087 This means to empty the block, parse for parameters and then call
12088 the correct writing function."
12091 (let* ((win (selected-window))
12093 (line (org-current-line))
12094 (params (org-prepare-dblock))
12095 (name (plist-get params :name))
12096 (indent (plist-get params :indentation-column))
12097 (cmd (intern (concat "org-dblock-write:" name))))
12098 (message "Updating dynamic block `%s' at line %d..." name line)
12099 (funcall cmd params)
12100 (message "Updating dynamic block `%s' at line %d...done" name line)
12102 (when (and indent (> indent 0))
12103 (setq indent (make-string indent ?\ ))
12105 (select-window win)
12106 (org-beginning-of-dblock)
12108 (while (not (looking-at org-dblock-end-re))
12110 (beginning-of-line 2))
12111 (when (looking-at org-dblock-end-re)
12112 (and (looking-at "[ \t]+")
12113 (replace-match ""))
12114 (insert indent)))))))
12116 (defun org-beginning-of-dblock ()
12117 "Find the beginning of the dynamic block at point.
12118 Error if there is no such block at point."
12119 (let ((pos (point))
12122 (if (and (re-search-backward org-dblock-start-re nil t)
12123 (setq beg (match-beginning 0))
12124 (re-search-forward org-dblock-end-re nil t)
12125 (> (match-end 0) pos))
12128 (error "Not in a dynamic block"))))
12130 (defun org-update-all-dblocks ()
12131 "Update all dynamic blocks in the buffer.
12132 This function can be used in a hook."
12134 (when (derived-mode-p 'org-mode)
12135 (org-map-dblocks 'org-update-dblock)))
12140 (declare-function org-export-backend-options "ox" (cl-x) t)
12141 (defun org-get-export-keywords ()
12142 "Return a list of all currently understood export keywords.
12143 Export keywords include options, block names, attributes and
12144 keywords relative to each registered export back-end."
12147 (bound-and-true-p org-export-registered-backends)
12148 (delq nil keywords))
12149 ;; Back-end name (for keywords, like #+LATEX:)
12150 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12151 (dolist (option-entry (org-export-backend-options backend))
12152 ;; Back-end options.
12153 (push (nth 1 option-entry) keywords)))))
12155 (defconst org-options-keywords
12156 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12157 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12158 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12159 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12160 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12162 (defcustom org-structure-template-alist
12163 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12164 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12165 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12166 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12167 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12168 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12169 ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
12170 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12172 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12174 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12177 ("I" "#+INCLUDE: %file ?"))
12178 "Structure completion elements.
12179 This is a list of abbreviation keys and values. The value gets inserted
12180 if you type `<' followed by the key and then press the completion key,
12181 usually `TAB'. %file will be replaced by a file name after prompting
12182 for the file using completion. The cursor will be placed at the position
12183 of the `?' in the template.
12184 There are two templates for each key, the first uses the original Org syntax,
12185 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12186 the default when the /org-mtags.el/ module has been loaded. See also the
12187 variable `org-mtags-prefer-muse-templates'."
12188 :group 'org-completion
12191 (string :tag "Key")
12192 (string :tag "Template")))
12194 :package-version '(Org . "8.3"))
12196 (defun org-try-structure-completion ()
12197 "Try to complete a structure template before point.
12198 This looks for strings like \"<e\" on an otherwise empty line and
12200 (let ((l (buffer-substring (point-at-bol) (point)))
12202 (when (and (looking-at "[ \t]*$")
12203 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12204 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12205 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12206 (match-beginning 1)) a)
12209 (defun org-complete-expand-structure-template (start cell)
12210 "Expand a structure template."
12211 (let ((rpl (nth 1 cell))
12213 (delete-region start (point))
12214 (when (string-match "\\`[ \t]*#\\+" rpl)
12217 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12218 (setq ind (buffer-substring (point-at-bol) (point))))
12220 (setq start (point))
12221 (when (string-match "%file" rpl)
12222 (setq rpl (replace-match
12226 (abbreviate-file-name (read-file-name "Include file: ")))
12229 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12230 (concat "\n" ind)))
12232 (when (re-search-backward "\\?" start t) (delete-char 1))))
12234 ;;;; TODO, DEADLINE, Comments
12236 (defun org-toggle-comment ()
12237 "Change the COMMENT state of an entry."
12240 (org-back-to-heading)
12241 (let ((case-fold-search nil))
12242 (looking-at org-complex-heading-regexp))
12243 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12244 (skip-chars-forward " \t")
12245 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12246 (if (org-in-commented-heading-p t)
12247 (delete-region (point)
12248 (progn (search-forward " " (line-end-position) 'move)
12249 (skip-chars-forward " \t")
12251 (insert org-comment-string)
12252 (unless (eolp) (insert " ")))))
12254 (defvar org-last-todo-state-is-todo nil
12255 "This is non-nil when the last TODO state change led to a TODO state.
12256 If the last change removed the TODO tag or switched to DONE, then
12259 (defvar org-setting-tags nil) ; dynamically skipped
12261 (defvar org-todo-setup-filter-hook nil
12262 "Hook for functions that pre-filter todo specs.
12263 Each function takes a todo spec and returns either nil or the spec
12264 transformed into canonical form." )
12266 (defvar org-todo-get-default-hook nil
12267 "Hook for functions that get a default item for todo.
12268 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12269 nil or a string to be used for the todo mark." )
12271 (defvar org-agenda-headline-snapshot-before-repeat)
12273 (defun org-current-effective-time ()
12274 "Return current time adjusted for `org-extend-today-until' variable."
12275 (let* ((ct (org-current-time))
12276 (dct (decode-time ct))
12279 (org-use-last-clock-out-time-as-effective-time
12280 (or (org-clock-get-last-clock-out-time) ct))
12281 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12282 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12286 (defun org-todo-yesterday (&optional arg)
12287 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12289 (if (eq major-mode 'org-agenda-mode)
12290 (apply 'org-agenda-todo-yesterday arg)
12291 (let* ((org-use-effective-time t)
12292 (hour (nth 2 (decode-time (org-current-time))))
12293 (org-extend-today-until (1+ hour)))
12296 (defvar org-block-entry-blocking ""
12297 "First entry preventing the TODO state change.")
12299 (defun org-cancel-repeater ()
12300 "Cancel a repeater by setting its numeric value to zero."
12303 (org-back-to-heading t)
12304 (let ((bound1 (point))
12305 (bound0 (save-excursion (outline-next-heading) (point))))
12306 (when (and (re-search-forward
12307 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12308 org-deadline-time-regexp "\\)\\|\\("
12309 org-ts-regexp "\\)")
12311 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12313 (replace-match "0" t nil nil 1)))))
12316 (defvar org-blocked-by-checkboxes)
12317 (defun org-todo (&optional arg)
12318 "Change the TODO state of an item.
12320 The state of an item is given by a keyword at the start of the heading,
12322 *** TODO Write paper
12325 The different keywords are specified in the variable `org-todo-keywords'.
12326 By default the available states are \"TODO\" and \"DONE\". So, for this
12327 example: when the item starts with TODO, it is changed to DONE.
12328 When it starts with DONE, the DONE is removed. And when neither TODO nor
12329 DONE are present, add TODO at the beginning of the heading.
12331 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12333 With numeric prefix ARG, switch to that state.
12334 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12336 keywords (nextset).
12337 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12338 prefix, circumvent any state blocking.
12339 With a numeric prefix arg of 0, inhibit note taking for the change.
12340 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12342 When called through ELisp, arg is also interpreted in the following way:
12343 `none' -> empty state
12344 \"\" -> switch to empty state
12345 `done' -> switch to DONE
12346 `nextset' -> switch to the next set of keywords
12347 `previousset' -> switch to the previous set of keywords
12348 \"WAITING\" -> switch to the specified keyword, but only if it
12349 really is a member of `org-todo-keywords'."
12351 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12352 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12353 'region-start-level 'region))
12354 org-loop-over-headlines-in-active-region)
12357 org-loop-over-headlines-in-active-region
12358 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12359 (when (equal arg '(16)) (setq arg 'nextset))
12360 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12361 (let ((org-blocker-hook org-blocker-hook)
12364 (when (equal arg '(64))
12365 (setq arg nil org-blocker-hook nil))
12366 (when (and org-blocker-hook
12367 (or org-inhibit-blocking
12368 (org-entry-get nil "NOBLOCKING")))
12369 (setq org-blocker-hook nil))
12372 (org-back-to-heading t)
12373 (when (org-in-commented-heading-p t)
12374 (org-toggle-comment)
12376 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12377 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12378 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12379 (let* ((match-data (match-data))
12380 (startpos (point-at-bol))
12381 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12382 (org-log-done org-log-done)
12383 (org-log-repeat org-log-repeat)
12384 (org-todo-log-states org-todo-log-states)
12385 (org-inhibit-logging
12387 (progn (setq arg nil) 'note) org-inhibit-logging))
12388 (this (match-string 1))
12389 (hl-pos (match-beginning 0))
12390 (head (org-get-todo-sequence-head this))
12391 (ass (assoc head org-todo-kwd-alist))
12392 (interpret (nth 1 ass))
12393 (done-word (nth 3 ass))
12394 (final-done-word (nth 4 ass))
12395 (org-last-state (or this ""))
12396 (completion-ignore-case t)
12397 (member (member this org-todo-keywords-1))
12398 (tail (cdr member))
12400 ((and org-todo-key-trigger
12401 (or (and (equal arg '(4))
12402 (eq org-use-fast-todo-selection 'prefix))
12403 (and (not arg) org-use-fast-todo-selection
12404 (not (eq org-use-fast-todo-selection
12406 ;; Use fast selection.
12407 (org-fast-todo-selection))
12408 ((and (equal arg '(4))
12409 (or (not org-use-fast-todo-selection)
12410 (not org-todo-key-trigger)))
12411 ;; Read a state with completion.
12413 "State: " (mapcar #'list org-todo-keywords-1)
12417 (if tail (car tail) nil)
12418 (car org-todo-keywords-1)))
12420 (unless (equal member org-todo-keywords-1)
12422 (nth (- (length org-todo-keywords-1)
12424 org-todo-keywords-1)
12425 (org-last org-todo-keywords-1))))
12426 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12427 (setq arg nil))) ;hack to fall back to cycling
12429 ;; User or caller requests a specific state.
12431 ((equal arg "") nil)
12432 ((eq arg 'none) nil)
12433 ((eq arg 'done) (or done-word (car org-done-keywords)))
12435 (or (car (cdr (member head org-todo-heads)))
12436 (car org-todo-heads)))
12437 ((eq arg 'previousset)
12438 (let ((org-todo-heads (reverse org-todo-heads)))
12439 (or (car (cdr (member head org-todo-heads)))
12440 (car org-todo-heads))))
12441 ((car (member arg org-todo-keywords-1)))
12443 (user-error "State `%s' not valid in this file" arg))
12444 ((nth (1- (prefix-numeric-value arg))
12445 org-todo-keywords-1))))
12446 ((null member) (or head (car org-todo-keywords-1)))
12447 ((equal this final-done-word) nil) ;-> make empty
12448 ((null tail) nil) ;-> first entry
12449 ((memq interpret '(type priority))
12450 (if (eq this-command last-command)
12452 (if (> (length tail) 0)
12453 (or done-word (car org-done-keywords))
12458 (run-hook-with-args-until-success
12459 'org-todo-get-default-hook org-state org-last-state)
12461 (next (if org-state (concat " " org-state " ") " "))
12462 (change-plist (list :type 'todo-state-change :from this :to org-state
12463 :position startpos))
12465 (when org-blocker-hook
12466 (let (org-blocked-by-checkboxes block-reason)
12467 (setq org-last-todo-state-is-todo
12468 (not (member this org-done-keywords)))
12469 (unless (save-excursion
12471 (org-with-wide-buffer
12472 (run-hook-with-args-until-failure
12473 'org-blocker-hook change-plist))))
12474 (setq block-reason (if org-blocked-by-checkboxes
12475 "contained checkboxes"
12476 (format "\"%s\"" org-block-entry-blocking)))
12477 (if (called-interactively-p 'interactive)
12478 (user-error "TODO state change from %s to %s blocked (by %s)"
12479 this org-state block-reason)
12481 (message "TODO state change from %s to %s blocked (by %s)"
12482 this org-state block-reason)
12483 (throw 'exit nil)))))
12484 (store-match-data match-data)
12485 (replace-match next t t)
12486 (cond ((equal this org-state)
12487 (message "TODO state was already %s" (org-trim next)))
12488 ((not (pos-visible-in-window-p hl-pos))
12489 (message "TODO state changed to %s" (org-trim next))))
12491 (setq head (org-get-todo-sequence-head org-state)
12492 ass (assoc head org-todo-kwd-alist)
12493 interpret (nth 1 ass)
12494 done-word (nth 3 ass)
12495 final-done-word (nth 4 ass)))
12496 (when (memq arg '(nextset previousset))
12497 (message "Keyword-Set %d/%d: %s"
12498 (- (length org-todo-sets) -1
12499 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12500 (length org-todo-sets)
12501 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12502 (setq org-last-todo-state-is-todo
12503 (not (member org-state org-done-keywords)))
12504 (setq now-done-p (and (member org-state org-done-keywords)
12505 (not (member this org-done-keywords))))
12506 (and logging (org-local-logging logging))
12507 (when (and (or org-todo-log-states org-log-done)
12508 (not (eq org-inhibit-logging t))
12509 (not (memq arg '(nextset previousset))))
12510 ;; We need to look at recording a time and note.
12511 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12512 (nth 2 (assoc this org-todo-log-states))))
12513 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12514 (setq dolog 'time))
12515 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12517 (member org-state org-not-done-keywords)
12518 (not (member this org-not-done-keywords))))
12519 ;; This is now a todo state and was not one before
12520 ;; If there was a CLOSED time stamp, get rid of it.
12521 (org-add-planning-info nil nil 'closed))
12522 (when (and now-done-p org-log-done)
12523 ;; It is now done, and it was not done before.
12524 (org-add-planning-info 'closed (org-current-effective-time))
12525 (when (and (not dolog) (eq 'note org-log-done))
12526 (org-add-log-setup 'done org-state this 'note)))
12527 (when (and org-state dolog)
12528 ;; This is a non-nil state, and we need to log it.
12529 (org-add-log-setup 'state org-state this dolog)))
12530 ;; Fixup tag positioning.
12531 (org-todo-trigger-tag-changes org-state)
12532 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12533 (when org-provide-todo-statistics
12534 (org-update-parent-todo-statistics))
12535 (run-hooks 'org-after-todo-state-change-hook)
12536 (when (and arg (not (member org-state org-done-keywords)))
12537 (setq head (org-get-todo-sequence-head org-state)))
12538 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12539 ;; Do we need to trigger a repeat?
12541 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12542 ;; This is for the agenda, take a snapshot of the headline.
12544 (setq org-agenda-headline-snapshot-before-repeat
12545 (org-get-heading))))
12546 (org-auto-repeat-maybe org-state))
12547 ;; Fixup cursor location if close to the keyword.
12548 (when (and (outline-on-heading-p)
12550 (save-excursion (beginning-of-line 1)
12551 (looking-at org-todo-line-regexp))
12552 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12553 (goto-char (or (match-end 2) (match-end 1)))
12554 (and (looking-at " ") (just-one-space)))
12555 (when org-trigger-hook
12557 (run-hook-with-args 'org-trigger-hook change-plist)))
12558 (when commentp (org-toggle-comment))))))))
12560 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12561 "Block turning an entry into a TODO, using the hierarchy.
12562 This checks whether the current task should be blocked from state
12563 changes. Such blocking occurs when:
12565 1. The task has children which are not all in a completed state.
12567 2. A task has a parent with the property :ORDERED:, and there
12568 are siblings prior to the current task with incomplete
12571 3. The parent of the task is blocked because it has siblings that should
12572 be done first, or is child of a block grandparent TODO entry."
12574 (if (not org-enforce-todo-dependencies)
12575 t ; if locally turned off don't block
12577 ;; If this is not a todo state change, or if this entry is already DONE,
12579 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12580 (member (plist-get change-plist :from)
12581 (cons 'done org-done-keywords))
12582 (member (plist-get change-plist :to)
12583 (cons 'todo org-not-done-keywords))
12584 (not (plist-get change-plist :to)))
12585 (throw 'dont-block t))
12586 ;; If this task has children, and any are undone, it's blocked
12588 (org-back-to-heading t)
12589 (let ((this-level (funcall outline-level)))
12590 (outline-next-heading)
12591 (let ((child-level (funcall outline-level)))
12592 (while (and (not (eobp))
12593 (> child-level this-level))
12594 ;; this todo has children, check whether they are all
12596 (when (and (not (org-entry-is-done-p))
12597 (org-entry-is-todo-p))
12598 (setq org-block-entry-blocking (org-get-heading))
12599 (throw 'dont-block nil))
12600 (outline-next-heading)
12601 (setq child-level (funcall outline-level))))))
12602 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12603 ;; any previous siblings are undone, it's blocked
12605 (org-back-to-heading t)
12606 (let* ((pos (point))
12607 (parent-pos (and (org-up-heading-safe) (point)))
12608 (case-fold-search nil))
12609 (unless parent-pos (throw 'dont-block t)) ; no parent
12610 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12612 (re-search-forward org-not-done-heading-regexp pos t))
12613 (setq org-block-entry-blocking (match-string 0))
12614 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12615 ;; Search further up the hierarchy, to see if an ancestor is blocked
12617 (goto-char parent-pos)
12618 (unless (looking-at org-not-done-heading-regexp)
12619 (throw 'dont-block t)) ; do not block, parent is not a TODO
12621 (setq parent-pos (and (org-up-heading-safe) (point)))
12622 (unless parent-pos (throw 'dont-block t)) ; no parent
12623 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12625 (re-search-forward org-not-done-heading-regexp pos t)
12626 (setq org-block-entry-blocking (org-get-heading)))
12627 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12629 (defcustom org-track-ordered-property-with-tag nil
12630 "Should the ORDERED property also be shown as a tag?
12631 The ORDERED property decides if an entry should require subtasks to be
12632 completed in sequence. Since a property is not very visible, setting
12633 this option means that toggling the ORDERED property with the command
12634 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12635 not relevant for the behavior, but it makes things more visible.
12637 Note that toggling the tag with tags commands will not change the property
12638 and therefore not influence behavior!
12640 This can be t, meaning the tag ORDERED should be used, It can also be a
12641 string to select a different tag for this task."
12644 (const :tag "No tracking" nil)
12645 (const :tag "Track with ORDERED tag" t)
12646 (string :tag "Use other tag")))
12648 (defun org-toggle-ordered-property ()
12649 "Toggle the ORDERED property of the current entry.
12650 For better visibility, you can track the value of this property with a tag.
12651 See variable `org-track-ordered-property-with-tag'."
12653 (let* ((t1 org-track-ordered-property-with-tag)
12654 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12656 (org-back-to-heading)
12657 (if (org-entry-get nil "ORDERED")
12659 (org-delete-property "ORDERED")
12660 (and tag (org-toggle-tag tag 'off))
12661 (message "Subtasks can be completed in arbitrary order"))
12662 (org-entry-put nil "ORDERED" "t")
12663 (and tag (org-toggle-tag tag 'on))
12664 (message "Subtasks must be completed in sequence")))))
12666 (defun org-block-todo-from-checkboxes (change-plist)
12667 "Block turning an entry into a TODO, using checkboxes.
12668 This checks whether the current task should be blocked from state
12669 changes because there are unchecked boxes in this entry."
12670 (if (not org-enforce-todo-checkbox-dependencies)
12671 t ; if locally turned off don't block
12673 ;; If this is not a todo state change, or if this entry is already DONE,
12675 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12676 (member (plist-get change-plist :from)
12677 (cons 'done org-done-keywords))
12678 (member (plist-get change-plist :to)
12679 (cons 'todo org-not-done-keywords))
12680 (not (plist-get change-plist :to)))
12681 (throw 'dont-block t))
12682 ;; If this task has checkboxes that are not checked, it's blocked
12684 (org-back-to-heading t)
12685 (let ((beg (point)) end)
12686 (outline-next-heading)
12689 (when (org-list-search-forward
12690 (concat (org-item-beginning-re)
12691 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12694 (when (boundp 'org-blocked-by-checkboxes)
12695 (setq org-blocked-by-checkboxes t))
12696 (throw 'dont-block nil))))
12697 t))) ; do not block
12699 (defun org-entry-blocked-p ()
12700 "Non-nil if entry at point is blocked."
12701 (and (not (org-entry-get nil "NOBLOCKING"))
12702 (member (org-entry-get nil "TODO") org-not-done-keywords)
12703 (not (run-hook-with-args-until-failure
12705 (list :type 'todo-state-change
12710 (defun org-update-statistics-cookies (all)
12711 "Update the statistics cookie, either from TODO or from checkboxes.
12712 This should be called with the cursor in a line with a statistics
12713 cookie. When called with a \\[universal-argument] prefix, update
12714 all statistics cookies in the buffer."
12718 (org-update-checkbox-count 'all)
12719 (org-map-entries 'org-update-parent-todo-statistics))
12720 (if (not (org-at-heading-p))
12721 (org-update-checkbox-count)
12722 (let ((pos (point-marker))
12724 (ignore-errors (org-back-to-heading t))
12725 (if (not (org-at-heading-p))
12726 (org-update-checkbox-count)
12727 (setq l1 (org-outline-level))
12728 (setq end (save-excursion
12729 (outline-next-heading)
12730 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12732 (if (and (save-excursion
12734 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12735 (not (save-excursion (re-search-forward
12736 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12737 (org-update-checkbox-count)
12738 (if (and l2 (> l2 l1))
12741 (org-update-parent-todo-statistics))
12743 (beginning-of-line 1)
12744 (while (re-search-forward
12745 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12747 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12749 (move-marker pos nil)))))
12751 (defvar org-entry-property-inherited-from) ;; defined below
12752 (defun org-update-parent-todo-statistics ()
12753 "Update any statistics cookie in the parent of the current headline.
12754 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12755 the entire subtree and this will travel up the hierarchy and update
12756 statistics everywhere."
12757 (let* ((prop (save-excursion (org-up-heading-safe)
12758 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12759 (recursive (or (not org-hierarchical-todo-statistics)
12760 (and prop (string-match "\\<recursive\\>" prop))))
12761 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12764 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12765 level ltoggle l1 new ndel
12766 (cnt-all 0) (cnt-done 0) is-percent kwd
12767 checkbox-beg cookie-present)
12770 (beginning-of-line 1)
12771 (setq ltoggle (funcall outline-level))
12772 ;; Three situations are to consider:
12774 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12775 ;; to the top-level ancestor on the headline;
12777 ;; 2. If parent has "recursive" property, repeat up to the
12778 ;; headline setting that property, taking inheritance into
12781 ;; 3. Else, move up to direct parent and proceed only once.
12782 (while (and (setq level (org-up-heading-safe))
12783 (or recursive first)
12785 (setq first nil cookie-present nil)
12789 (downcase (or (org-entry-get nil "COOKIE_DATA")
12792 (while (re-search-forward box-re (point-at-eol) t)
12793 (setq cnt-all 0 cnt-done 0 cookie-present t)
12794 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12796 (unless (outline-next-heading) (throw 'exit nil))
12797 (while (and (looking-at org-complex-heading-regexp)
12798 (> (setq l1 (length (match-string 1))) level))
12799 (setq kwd (and (or recursive (= l1 ltoggle))
12801 (if (or (eq org-provide-todo-statistics 'all-headlines)
12802 (and (eq org-provide-todo-statistics t)
12803 (or (member kwd org-done-keywords)))
12804 (and (listp org-provide-todo-statistics)
12805 (stringp (car org-provide-todo-statistics))
12806 (or (member kwd org-provide-todo-statistics)
12807 (member kwd org-done-keywords)))
12808 (and (listp org-provide-todo-statistics)
12809 (listp (car org-provide-todo-statistics))
12810 (or (member kwd (car org-provide-todo-statistics))
12811 (and (member kwd org-done-keywords)
12812 (member kwd (cadr org-provide-todo-statistics))))))
12813 (setq cnt-all (1+ cnt-all))
12814 (and (eq org-provide-todo-statistics t)
12816 (setq cnt-all (1+ cnt-all))))
12817 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12818 (member kwd org-done-keywords))
12819 (and (listp org-provide-todo-statistics)
12820 (listp (car org-provide-todo-statistics))
12821 (member kwd org-done-keywords)
12822 (member kwd (cadr org-provide-todo-statistics)))
12823 (and (listp org-provide-todo-statistics)
12824 (stringp (car org-provide-todo-statistics))
12825 (member kwd org-done-keywords)))
12826 (setq cnt-done (1+ cnt-done)))
12827 (outline-next-heading)))
12830 (format "[%d%%]" (floor (* 100.0 cnt-done)
12832 (format "[%d/%d]" cnt-done cnt-all))
12833 ndel (- (match-end 0) checkbox-beg))
12834 (goto-char checkbox-beg)
12836 (delete-region (point) (+ (point) ndel))
12837 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12838 (when cookie-present
12839 (run-hook-with-args 'org-after-todo-statistics-hook
12840 cnt-done (- cnt-all cnt-done))))))
12841 (run-hooks 'org-todo-statistics-hook)))
12843 (defvar org-after-todo-statistics-hook nil
12844 "Hook that is called after a TODO statistics cookie has been updated.
12845 Each function is called with two arguments: the number of not-done entries
12846 and the number of done entries.
12848 For example, the following function, when added to this hook, will switch
12849 an entry to DONE when all children are done, and back to TODO when new
12850 entries are set to a TODO status. Note that this hook is only called
12851 when there is a statistics cookie in the headline!
12853 (defun org-summary-todo (n-done n-not-done)
12854 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12855 (let (org-log-done org-log-states) ; turn off logging
12856 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12859 (defvar org-todo-statistics-hook nil
12860 "Hook that is run whenever Org thinks TODO statistics should be updated.
12861 This hook runs even if there is no statistics cookie present, in which case
12862 `org-after-todo-statistics-hook' would not run.")
12864 (defun org-todo-trigger-tag-changes (state)
12865 "Apply the changes defined in `org-todo-state-tags-triggers'."
12866 (let ((l org-todo-state-tags-triggers)
12868 (when (or (not state) (equal state ""))
12869 (setq changes (append changes (cdr (assoc "" l)))))
12870 (when (and (stringp state) (> (length state) 0))
12871 (setq changes (append changes (cdr (assoc state l)))))
12872 (when (member state org-not-done-keywords)
12873 (setq changes (append changes (cdr (assq 'todo l)))))
12874 (when (member state org-done-keywords)
12875 (setq changes (append changes (cdr (assq 'done l)))))
12876 (dolist (c changes)
12877 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12879 (defun org-local-logging (value)
12880 "Get logging settings from a property VALUE."
12881 ;; Directly set the variables, they are already local.
12882 (setq org-log-done nil
12884 org-todo-log-states nil)
12885 (dolist (w (split-string value))
12888 ((setq a (assoc w org-startup-options))
12889 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12890 (set (nth 1 a) (nth 2 a))))
12891 ((setq a (org-extract-log-state-settings w))
12892 (and (member (car a) org-todo-keywords-1)
12893 (push a org-todo-log-states)))))))
12895 (defun org-get-todo-sequence-head (kwd)
12896 "Return the head of the TODO sequence to which KWD belongs.
12897 If KWD is not set, check if there is a text property remembering the
12902 (or (get-text-property (point-at-bol) 'org-todo-head)
12904 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12905 nil (point-at-eol)))
12906 (get-text-property p 'org-todo-head))))
12907 ((not (member kwd org-todo-keywords-1))
12908 (car org-todo-keywords-1))
12909 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12911 (defun org-fast-todo-selection ()
12912 "Fast TODO keyword selection with single keys.
12913 Returns the new TODO keyword, or nil if no state change should occur."
12914 (let* ((fulltable org-todo-key-alist)
12915 (done-keywords org-done-keywords) ;; needed for the faces.
12916 (maxlen (apply 'max (mapcar
12918 (if (stringp (car x)) (string-width (car x)) 0))
12921 (fwidth (+ maxlen 3 1 3))
12922 (ncol (/ (- (window-width) 4) fwidth))
12926 (save-window-excursion
12928 (set-buffer (get-buffer-create " *Org todo*"))
12929 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12931 (setq-local org-done-keywords done-keywords)
12932 (setq tbl fulltable cnt 0)
12933 (while (setq e (pop tbl))
12935 ((equal e '(:startgroup))
12936 (push '() groups) (setq ingroup t)
12941 ((equal e '(:endgroup))
12942 (setq ingroup nil cnt 0)
12944 ((equal e '(:newline))
12949 (while (equal (car tbl) '(:newline))
12951 (setq tbl (cdr tbl)))))
12953 (setq tg (car e) c (cdr e))
12954 (when ingroup (push tg (car groups)))
12955 (setq tg (org-add-props tg nil 'face
12956 (org-get-todo-face tg)))
12957 (when (and (= cnt 0) (not ingroup)) (insert " "))
12958 (insert "[" c "] " tg (make-string
12959 (- fwidth 4 (length tg)) ?\ ))
12960 (when (= (setq cnt (1+ cnt)) ncol)
12962 (when ingroup (insert " "))
12965 (goto-char (point-min))
12966 (unless expert (org-fit-window-to-buffer))
12967 (message "[a-z..]:Set [SPC]:clear")
12968 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12971 (and (= c ?q) (not (rassoc c fulltable))))
12972 (setq quit-flag t))
12974 ((setq e (rassoc c fulltable) tg (car e))
12976 (t (setq quit-flag t)))))))
12978 (defun org-entry-is-todo-p ()
12979 (member (org-get-todo-state) org-not-done-keywords))
12981 (defun org-entry-is-done-p ()
12982 (member (org-get-todo-state) org-done-keywords))
12984 (defun org-get-todo-state ()
12985 "Return the TODO keyword of the current subtree."
12987 (org-back-to-heading t)
12988 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12990 (match-string 2))))
12992 (defun org-at-date-range-p (&optional inactive-ok)
12993 "Non-nil if point is inside a date range.
12995 When optional argument INACTIVE-OK is non-nil, also consider
12996 inactive time ranges.
12998 When this function returns a non-nil value, match data is set
12999 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13004 (let ((pos (point)))
13005 (skip-chars-backward "^[<\r\n")
13006 (skip-chars-backward "<[")
13007 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13008 (>= (match-end 0) pos)
13010 (skip-chars-backward "^<[\r\n")
13011 (skip-chars-backward "<[")
13012 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13013 (>= (match-end 0) pos)
13017 (defun org-get-repeat (&optional timestamp)
13018 "Check if there is a time-stamp with repeater in this entry.
13020 Return the repeater, as a string, or nil. Also return nil when
13021 this function is called before first heading.
13023 When optional argument TIMESTAMP is a string, extract the
13024 repeater from there instead."
13027 (and (string-match org-repeat-re timestamp)
13028 (match-string-no-properties 1 timestamp)))
13029 ((org-before-first-heading-p) nil)
13032 (org-back-to-heading t)
13033 (let ((end (org-entry-end-position)))
13035 (while (re-search-forward org-repeat-re end t)
13036 (when (save-match-data (org-at-timestamp-p 'agenda))
13037 (throw :repeat (match-string-no-properties 1)))))))))))
13039 (defvar org-last-changed-timestamp)
13040 (defvar org-last-inserted-timestamp)
13041 (defvar org-log-post-message)
13042 (defvar org-log-note-purpose)
13043 (defvar org-log-note-how nil)
13044 (defvar org-log-note-extra)
13045 (defun org-auto-repeat-maybe (done-word)
13046 "Check if the current headline contains a repeated time-stamp.
13048 If yes, set TODO state back to what it was and change the base date
13049 of repeating deadline/scheduled time stamps to new date.
13051 This function is run automatically after each state change to a DONE state."
13052 (let* ((repeat (org-get-repeat))
13053 (aa (assoc org-last-state org-todo-kwd-alist))
13054 (interpret (nth 1 aa))
13056 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13057 (msg "Entry repeats: ")
13059 (org-todo-log-states nil)
13060 (end (copy-marker (org-entry-end-position))))
13062 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13063 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13064 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13065 org-todo-repeat-to-state)))
13067 ((and to-state (member to-state org-todo-keywords-1))
13069 ((eq interpret 'type) org-last-state)
13072 (org-back-to-heading t)
13073 (org-add-planning-info nil nil 'closed)
13074 ;; When `org-log-repeat' is non-nil or entry contains
13075 ;; a clock, set LAST_REPEAT property.
13076 (when (or org-log-repeat
13079 (while (re-search-forward org-clock-line-re end t)
13080 (when (org-at-clock-log-p) (throw :clock t))))))
13081 (org-entry-put nil "LAST_REPEAT" (format-time-string
13082 (org-time-stamp-format t t)
13084 (when org-log-repeat
13085 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13086 (memq 'org-add-log-note post-command-hook))
13087 ;; We are already setup for some record.
13088 (when (eq org-log-repeat 'note)
13089 ;; Make sure we take a note, not only a time stamp.
13090 (setq org-log-note-how 'note))
13091 ;; Set up for taking a record.
13092 (org-add-log-setup 'state
13093 (or done-word (car org-done-keywords))
13096 (let ((planning-re (regexp-opt
13097 (list org-scheduled-string org-deadline-string))))
13098 (while (re-search-forward org-ts-regexp end t)
13099 (let* ((ts (match-string 0))
13100 (planning? (org-at-planning-p))
13101 (type (if (not planning?) "Plain:"
13103 (re-search-backward
13104 planning-re (line-beginning-position) t)
13105 (match-string 0)))))
13107 ;; Ignore fake time-stamps (e.g., within comments).
13108 ((not (org-at-timestamp-p 'agenda)))
13109 ;; Time-stamps without a repeater are usually
13110 ;; skipped. However, a SCHEDULED time-stamp without
13111 ;; one is removed, as they are no longer relevant.
13112 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13114 (when (equal type org-scheduled-string)
13115 (org-remove-timestamp-with-keyword type)))
13117 (let ((n (string-to-number (match-string 2 ts)))
13118 (what (match-string 3 ts)))
13119 (when (equal what "w") (setq n (* n 7) what "d"))
13120 (when (and (equal what "h")
13121 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13124 "Cannot repeat in Repeat in %d hour(s) because no hour \
13127 ;; Preparation, see if we need to modify the start
13128 ;; date for the change.
13129 (when (match-end 1)
13130 (let ((time (save-match-data
13131 (org-time-string-to-time ts))))
13133 ((equal (match-string 1 ts) ".")
13134 ;; Shift starting date to today
13135 (org-timestamp-change
13136 (- (org-today) (time-to-days time))
13138 ((equal (match-string 1 ts) "+")
13139 (let ((nshiftmax 10)
13141 (while (or (= nshift 0)
13142 (not (time-less-p (current-time) time)))
13143 (when (= (cl-incf nshift) nshiftmax)
13145 (format "%d repeater intervals were not \
13146 enough to shift date past today. Continue? "
13148 (user-error "Abort")))
13149 (org-timestamp-change n (cdr (assoc what whata)))
13150 (org-in-regexp org-ts-regexp3)
13151 (setq ts (match-string 1))
13154 (org-time-string-to-time ts)))))
13155 (org-timestamp-change (- n) (cdr (assoc what whata)))
13156 ;; Rematch, so that we have everything in place
13157 ;; for the real shift.
13158 (org-in-regexp org-ts-regexp3)
13159 (setq ts (match-string 1))
13160 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13163 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13166 msg type " " org-last-changed-timestamp " "))))))))
13167 (setq org-log-post-message msg)
13168 (message "%s" msg))
13169 (set-marker end nil))))
13171 (defun org-show-todo-tree (arg)
13172 "Make a compact tree which shows all headlines marked with TODO.
13173 The tree will show the lines where the regexp matches, and all higher
13174 headlines above the match.
13175 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13176 With a numeric prefix N, construct a sparse tree for the Nth element
13177 of `org-todo-keywords-1'."
13179 (let ((case-fold-search nil)
13181 (cond ((null arg) org-not-done-regexp)
13184 (completing-read "Keyword (or KWD1|KWD2|...): "
13185 (mapcar #'list org-todo-keywords-1))))
13187 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13189 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13190 (regexp-quote (nth (1- (prefix-numeric-value arg))
13191 org-todo-keywords-1)))
13192 (t (user-error "Invalid prefix argument: %s" arg)))))
13193 (message "%d TODO entries found"
13194 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13196 (defun org--deadline-or-schedule (arg type time)
13197 "Insert DEADLINE or SCHEDULE information in current entry.
13198 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13199 `org-schedule' for information about ARG and TIME arguments."
13200 (let* ((deadline? (eq type 'deadline))
13201 (keyword (if deadline? org-deadline-string org-scheduled-string))
13202 (log (if deadline? org-log-redeadline org-log-reschedule))
13203 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13204 (old-date-time (and old-date (org-time-string-to-time old-date)))
13205 ;; Save repeater cookie from either TIME or current scheduled
13206 ;; time stamp. We are going to insert it back at the end of
13208 (repeater (or (and (org-string-nw-p time)
13209 ;; We use `org-repeat-re' because we need
13210 ;; to tell the difference between a real
13211 ;; repeater and a time delta, e.g. "+2d".
13212 (string-match org-repeat-re time)
13213 (match-string 1 time))
13214 (and (org-string-nw-p old-date)
13215 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13216 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13218 (match-string 1 old-date)))))
13221 (when (and old-date log)
13222 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13224 (org-remove-timestamp-with-keyword keyword)
13225 (message (if deadline? "Item no longer has a deadline."
13226 "Item is no longer scheduled.")))
13229 (org-back-to-heading t)
13230 (let ((regexp (if deadline? org-deadline-time-regexp
13231 org-scheduled-time-regexp)))
13232 (if (not (re-search-forward regexp (line-end-position 2) t))
13233 (user-error (if deadline? "No deadline information to update"
13234 "No scheduled information to update"))
13235 (let* ((rpl0 (match-string 1))
13236 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13237 (msg (if deadline? "Warn starting from" "Delay until")))
13242 (abs (- (time-to-days
13245 nil t nil msg old-date-time)))
13246 (time-to-days old-date-time))))
13249 (org-add-planning-info type time 'closed)
13250 (when (and old-date
13252 (not (equal old-date org-last-inserted-timestamp)))
13253 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13254 org-last-inserted-timestamp
13259 (org-back-to-heading t)
13260 (when (re-search-forward
13261 (concat keyword " " org-last-inserted-timestamp)
13262 (line-end-position 2)
13264 (goto-char (1- (match-end 0)))
13265 (insert " " repeater)
13266 (setq org-last-inserted-timestamp
13267 (concat (substring org-last-inserted-timestamp 0 -1)
13269 (substring org-last-inserted-timestamp -1))))))
13270 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13271 org-last-inserted-timestamp)))))
13273 (defun org-deadline (arg &optional time)
13274 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13275 With one universal prefix argument, remove any deadline from the item.
13276 With two universal prefix arguments, prompt for a warning delay.
13277 With argument TIME, set the deadline at the corresponding date. TIME
13278 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13280 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13282 (lambda () (org--deadline-or-schedule arg 'deadline time))
13284 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13285 'region-start-level
13287 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13288 (org--deadline-or-schedule arg 'deadline time)))
13290 (defun org-schedule (arg &optional time)
13291 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13292 With one universal prefix argument, remove any scheduling date from the item.
13293 With two universal prefix arguments, prompt for a delay cookie.
13294 With argument TIME, scheduled at the corresponding date. TIME can
13295 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13297 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13299 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13301 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13302 'region-start-level
13304 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13305 (org--deadline-or-schedule arg 'scheduled time)))
13307 (defun org-get-scheduled-time (pom &optional inherit)
13308 "Get the scheduled time as a time tuple, of a format suitable
13309 for calling org-schedule with, or if there is no scheduling,
13311 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13313 (apply 'encode-time (org-parse-time-string time)))))
13315 (defun org-get-deadline-time (pom &optional inherit)
13316 "Get the deadline as a time tuple, of a format suitable for
13317 calling org-deadline with, or if there is no scheduling, returns
13319 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13321 (apply 'encode-time (org-parse-time-string time)))))
13323 (defun org-remove-timestamp-with-keyword (keyword)
13324 "Remove all time stamps with KEYWORD in the current entry."
13325 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13328 (org-back-to-heading t)
13330 (outline-next-heading)
13331 (while (re-search-backward re beg t)
13333 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13334 (equal (char-before) ?\ ))
13335 (backward-delete-char 1)
13336 (when (string-match "^[ \t]*$" (buffer-substring
13337 (point-at-bol) (point-at-eol)))
13338 (delete-region (point-at-bol)
13339 (min (point-max) (1+ (point-at-eol))))))))))
13341 (defvar org-time-was-given) ; dynamically scoped parameter
13342 (defvar org-end-time-was-given) ; dynamically scoped parameter
13344 (defun org-at-planning-p ()
13345 "Non-nil when point is on a planning info line."
13346 ;; This is as accurate and faster than `org-element-at-point' since
13347 ;; planning info location is fixed in the section.
13348 (org-with-wide-buffer
13349 (beginning-of-line)
13350 (and (looking-at-p org-planning-line-re)
13353 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13354 (org-back-to-heading t)
13355 (org-with-limited-levels (org-back-to-heading t)))
13356 (line-beginning-position 2))))))
13358 (defun org-add-planning-info (what &optional time &rest remove)
13359 "Insert new timestamp with keyword in the planning line.
13360 WHAT indicates what kind of time stamp to add. It is a symbol
13361 among `closed', `deadline', `scheduled' and nil. TIME indicates
13362 the time to use. If none is given, the user is prompted for
13363 a date. REMOVE indicates what kind of entries to remove. An old
13364 WHAT entry will also be removed."
13365 (let (org-time-was-given org-end-time-was-given default-time default-input)
13367 (when (and (memq what '(scheduled deadline))
13369 (and (stringp time)
13370 (string-match "^[-+]+[0-9]" time))))
13371 ;; Try to get a default date/time from existing timestamp
13373 (org-back-to-heading t)
13374 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13375 (when (re-search-forward (if (eq what 'scheduled)
13376 org-scheduled-time-regexp
13377 org-deadline-time-regexp)
13379 (setq ts (match-string 1)
13380 default-time (apply 'encode-time (org-parse-time-string ts))
13381 default-input (and ts (org-get-compact-tod ts)))))))
13385 ;; This is a string (relative or absolute), set
13387 (apply #'encode-time
13388 (org-read-date-analyze
13389 time default-time (decode-time default-time)))
13390 ;; If necessary, get the time from the user
13391 (or time (org-read-date nil 'to-time nil nil
13392 default-time default-input)))))
13394 (org-with-wide-buffer
13395 (org-back-to-heading t)
13397 (unless (bolp) (insert "\n"))
13398 (cond ((looking-at-p org-planning-line-re)
13399 ;; Move to current indentation.
13400 (skip-chars-forward " \t")
13401 ;; Check if we have to remove something.
13402 (dolist (type (if what (cons what remove) remove))
13404 (when (re-search-forward
13406 (closed org-closed-time-regexp)
13407 (deadline org-deadline-time-regexp)
13408 (scheduled org-scheduled-time-regexp)
13410 (error "Invalid planning type: %s" type)))
13411 (line-end-position) t)
13412 ;; Delete until next keyword or end of line.
13414 (match-beginning 0)
13415 (if (re-search-forward org-keyword-time-not-clock-regexp
13416 (line-end-position)
13418 (match-beginning 0)
13419 (line-end-position))))))
13420 ;; If there is nothing more to add and no more keyword
13421 ;; is left, remove the line completely.
13422 (if (and (looking-at-p "[ \t]*$") (not what))
13423 (delete-region (line-beginning-position)
13424 (line-beginning-position 2))
13425 ;; If we removed last keyword, do not leave trailing
13426 ;; white space at the end of line.
13430 (unless (= (skip-chars-backward " \t" p) 0)
13431 (delete-region (point) (line-end-position)))))))
13432 ((not what) (throw 'exit nil)) ; Nothing to do.
13433 (t (insert-before-markers "\n")
13435 (when org-adapt-indentation
13436 (indent-to-column (1+ (org-outline-level))))))
13438 ;; Insert planning keyword.
13439 (insert (cl-case what
13440 (closed org-closed-string)
13441 (deadline org-deadline-string)
13442 (scheduled org-scheduled-string)
13443 (otherwise (error "Invalid planning type: %s" what)))
13445 ;; Insert associated timestamp.
13446 (let ((ts (org-insert-time-stamp
13448 (or org-time-was-given
13449 (and (eq what 'closed) org-log-done-with-time))
13451 nil nil (list org-end-time-was-given))))
13452 (unless (eolp) (insert " "))
13455 (defvar org-log-note-marker (make-marker)
13456 "Marker pointing at the entry where the note is to be inserted.")
13457 (defvar org-log-note-purpose nil)
13458 (defvar org-log-note-state nil)
13459 (defvar org-log-note-previous-state nil)
13460 (defvar org-log-note-extra nil)
13461 (defvar org-log-note-window-configuration nil)
13462 (defvar org-log-note-return-to (make-marker))
13463 (defvar org-log-note-effective-time nil
13464 "Remembered current time so that dynamically scoped
13465 `org-extend-today-until' affects timestamps in state change log")
13467 (defvar org-log-post-message nil
13468 "Message to be displayed after a log note has been stored.
13469 The auto-repeater uses this.")
13471 (defun org-add-note ()
13472 "Add a note to the current entry.
13473 This is done in the same way as adding a state change note."
13475 (org-add-log-setup 'note))
13477 (defun org-log-beginning (&optional create)
13478 "Return expected start of log notes in current entry.
13479 When optional argument CREATE is non-nil, the function creates
13480 a drawer to store notes, if necessary. Returned position ignores
13482 (org-with-wide-buffer
13483 (let ((drawer (org-log-into-drawer)))
13486 (org-end-of-meta-data)
13487 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13488 (end (if (org-at-heading-p) (point)
13489 (save-excursion (outline-next-heading) (point))))
13490 (case-fold-search t))
13492 ;; Try to find existing drawer.
13493 (while (re-search-forward regexp end t)
13494 (let ((element (org-element-at-point)))
13495 (when (eq (org-element-type element) 'drawer)
13496 (let ((cend (org-element-property :contents-end element)))
13497 (when (and (not org-log-states-order-reversed) cend)
13499 (throw 'exit nil))))
13500 ;; No drawer found. Create one, if permitted.
13502 (unless (bolp) (insert "\n"))
13503 (let ((beg (point)))
13504 (insert ":" drawer ":\n:END:\n")
13505 (org-indent-region beg (point)))
13506 (end-of-line -1)))))
13508 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13509 (skip-chars-forward " \t\n")
13510 (beginning-of-line)
13511 (unless org-log-states-order-reversed
13512 (org-skip-over-state-notes)
13513 (skip-chars-backward " \t\n")
13515 (if (bolp) (point) (line-beginning-position 2))))
13517 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13518 "Set up the post command hook to take a note.
13519 If this is about to TODO state change, the new state is expected in STATE.
13520 HOW is an indicator what kind of note should be created.
13521 EXTRA is additional text that will be inserted into the notes buffer."
13522 (move-marker org-log-note-marker (point))
13523 (setq org-log-note-purpose purpose
13524 org-log-note-state state
13525 org-log-note-previous-state prev-state
13526 org-log-note-how how
13527 org-log-note-extra extra
13528 org-log-note-effective-time (org-current-effective-time))
13529 (add-hook 'post-command-hook 'org-add-log-note 'append))
13531 (defun org-skip-over-state-notes ()
13532 "Skip past the list of State notes in an entry."
13533 (when (ignore-errors (goto-char (org-in-item-p)))
13534 (let* ((struct (org-list-struct))
13535 (prevs (org-list-prevs-alist struct))
13537 (concat "[ \t]*- +"
13538 (replace-regexp-in-string
13540 (org-replace-escapes
13541 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13542 `(("%d" . ,org-ts-regexp-inactive)
13543 ("%D" . ,org-ts-regexp)
13544 ("%s" . "\"\\S-+\"")
13545 ("%S" . "\"\\S-+\"")
13546 ("%t" . ,org-ts-regexp-inactive)
13547 ("%T" . ,org-ts-regexp)
13549 ("%U" . ".*?")))))))
13550 (while (looking-at-p regexp)
13551 (goto-char (or (org-list-get-next-item (point) struct prevs)
13552 (org-list-get-item-end (point) struct)))))))
13554 (defun org-add-log-note (&optional _purpose)
13555 "Pop up a window for taking a note, and add this note later."
13556 (remove-hook 'post-command-hook 'org-add-log-note)
13557 (setq org-log-note-window-configuration (current-window-configuration))
13558 (delete-other-windows)
13559 (move-marker org-log-note-return-to (point))
13560 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13561 (goto-char org-log-note-marker)
13562 (org-switch-to-buffer-other-window "*Org Note*")
13564 (if (memq org-log-note-how '(time state))
13565 (org-store-log-note)
13566 (let ((org-inhibit-startup t)) (org-mode))
13567 (insert (format "# Insert note for %s.
13568 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13570 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13571 ((eq org-log-note-purpose 'done) "closed todo item")
13572 ((eq org-log-note-purpose 'state)
13573 (format "state change from \"%s\" to \"%s\""
13574 (or org-log-note-previous-state "")
13575 (or org-log-note-state "")))
13576 ((eq org-log-note-purpose 'reschedule)
13578 ((eq org-log-note-purpose 'delschedule)
13579 "no longer scheduled")
13580 ((eq org-log-note-purpose 'redeadline)
13581 "changing deadline")
13582 ((eq org-log-note-purpose 'deldeadline)
13583 "removing deadline")
13584 ((eq org-log-note-purpose 'refile)
13586 ((eq org-log-note-purpose 'note)
13588 (t (error "This should not happen")))))
13589 (when org-log-note-extra (insert org-log-note-extra))
13590 (setq-local org-finish-function 'org-store-log-note)
13591 (run-hooks 'org-log-buffer-setup-hook)))
13593 (defvar org-note-abort nil) ; dynamically scoped
13594 (defun org-store-log-note ()
13595 "Finish taking a log note, and insert it to where it belongs."
13596 (let ((txt (prog1 (buffer-string)
13598 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13600 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13601 (setq txt (replace-match "" t t txt)))
13602 (when (string-match "\\s-+\\'" txt)
13603 (setq txt (replace-match "" t t txt)))
13604 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13605 (when (org-string-nw-p note)
13607 (org-replace-escapes
13609 (list (cons "%u" (user-login-name))
13610 (cons "%U" user-full-name)
13611 (cons "%t" (format-time-string
13612 (org-time-stamp-format 'long 'inactive)
13613 org-log-note-effective-time))
13614 (cons "%T" (format-time-string
13615 (org-time-stamp-format 'long nil)
13616 org-log-note-effective-time))
13617 (cons "%d" (format-time-string
13618 (org-time-stamp-format nil 'inactive)
13619 org-log-note-effective-time))
13620 (cons "%D" (format-time-string
13621 (org-time-stamp-format nil nil)
13622 org-log-note-effective-time))
13624 ((not org-log-note-state) "")
13625 ((string-match-p org-ts-regexp
13626 org-log-note-state)
13628 (substring org-log-note-state 1 -1)))
13629 (t (format "\"%s\"" org-log-note-state))))
13632 ((not org-log-note-previous-state) "")
13633 ((string-match-p org-ts-regexp
13634 org-log-note-previous-state)
13637 org-log-note-previous-state 1 -1)))
13638 (t (format "\"%s\""
13639 org-log-note-previous-state)))))))
13640 (when lines (setq note (concat note " \\\\")))
13642 (when (and lines (not org-note-abort))
13643 (with-current-buffer (marker-buffer org-log-note-marker)
13644 (org-with-wide-buffer
13645 ;; Find location for the new note.
13646 (goto-char org-log-note-marker)
13647 (set-marker org-log-note-marker nil)
13648 ;; Note associated to a clock is to be located right after
13649 ;; the clock. Do not move point.
13650 (unless (eq org-log-note-purpose 'clock-out)
13651 (goto-char (org-log-beginning t)))
13652 ;; Make sure point is at the beginning of an empty line.
13653 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13654 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13655 ;; In an existing list, add a new item at the top level.
13656 ;; Otherwise, indent line like a regular one.
13657 (let ((itemp (org-in-item-p)))
13660 (let ((struct (save-excursion
13661 (goto-char itemp) (org-list-struct))))
13662 (org-list-get-ind (org-list-get-top-point struct) struct)))
13663 (org-indent-line)))
13664 (insert (org-list-bullet-string "-") (pop lines))
13665 (let ((ind (org-list-item-body-column (line-beginning-position))))
13666 (dolist (line lines)
13668 (indent-line-to ind)
13670 (message "Note stored")
13671 (org-back-to-heading t)
13672 (org-cycle-hide-drawers 'children))
13673 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13674 ;; from within `org-add-log-note' because `buffer-undo-list'
13675 ;; is then modified outside of `org-with-remote-undo'.
13676 (when (eq this-command 'org-agenda-todo)
13677 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13678 ;; Don't add undo information when called from `org-agenda-todo'.
13679 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13680 (set-window-configuration org-log-note-window-configuration)
13681 (with-current-buffer (marker-buffer org-log-note-return-to)
13682 (goto-char org-log-note-return-to))
13683 (move-marker org-log-note-return-to nil)
13684 (when org-log-post-message (message "%s" org-log-post-message))))
13686 (defun org-remove-empty-drawer-at (pos)
13687 "Remove an empty drawer at position POS.
13688 POS may also be a marker."
13689 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13690 (org-with-wide-buffer
13692 (let ((drawer (org-element-at-point)))
13693 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13694 (not (org-element-property :contents-begin drawer)))
13695 (delete-region (org-element-property :begin drawer)
13696 (progn (goto-char (org-element-property :end drawer))
13697 (skip-chars-backward " \r\t\n")
13701 (defvar org-ts-type nil)
13702 (defun org-sparse-tree (&optional arg type)
13703 "Create a sparse tree, prompt for the details.
13704 This command can create sparse trees. You first need to select the type
13705 of match used to create the tree:
13707 t Show all TODO entries.
13708 T Show entries with a specific TODO keyword.
13709 m Show entries selected by a tags/property match.
13710 p Enter a property name and its value (both with completion on existing
13711 names/values) and show entries with that property.
13712 r Show entries matching a regular expression (`/' can be used as well).
13713 b Show deadlines and scheduled items before a date.
13714 a Show deadlines and scheduled items after a date.
13715 d Show deadlines due within `org-deadline-warning-days'.
13716 D Show deadlines and scheduled items between a date range."
13718 (setq type (or type org-sparse-tree-default-date-type))
13719 (setq org-ts-type type)
13720 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13721 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13722 \[c]ycle through date types: %s"
13724 (all "all timestamps")
13725 (scheduled "only scheduled")
13726 (deadline "only deadline")
13727 (active "only active timestamps")
13728 (inactive "only inactive timestamps")
13729 (closed "with a closed time-stamp")
13730 (otherwise "scheduled/deadline")))
13731 (let ((answer (read-char-exclusive)))
13737 (memq type '(nil all scheduled deadline active inactive closed)))))
13738 (?d (call-interactively 'org-check-deadlines))
13739 (?b (call-interactively 'org-check-before-date))
13740 (?a (call-interactively 'org-check-after-date))
13741 (?D (call-interactively 'org-check-dates-range))
13742 (?t (call-interactively 'org-show-todo-tree))
13743 (?T (org-show-todo-tree '(4)))
13744 (?m (call-interactively 'org-match-sparse-tree))
13746 (let* ((kwd (completing-read
13747 "Property: " (mapcar #'list (org-buffer-property-keys))))
13748 (value (completing-read
13749 "Value: " (mapcar #'list (org-property-values kwd)))))
13750 (unless (string-match "\\`{.*}\\'" value)
13751 (setq value (concat "\"" value "\"")))
13752 (org-match-sparse-tree arg (concat kwd "=" value))))
13753 ((?r ?R ?/) (call-interactively 'org-occur))
13754 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13756 (defvar-local org-occur-highlights nil
13757 "List of overlays used for occur matches.")
13758 (defvar-local org-occur-parameters nil
13759 "Parameters of the active org-occur calls.
13760 This is a list, each call to org-occur pushes as cons cell,
13761 containing the regular expression and the callback, onto the list.
13762 The list can contain several entries if `org-occur' has been called
13763 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13764 will only contain one set of parameters. When the highlights are
13765 removed (for example with `C-c C-c', or with the next edit (depending
13766 on `org-remove-highlights-with-change'), this variable is emptied
13769 (defun org-occur (regexp &optional keep-previous callback)
13770 "Make a compact tree which shows all matches of REGEXP.
13772 The tree will show the lines where the regexp matches, and any other context
13773 defined in `org-show-context-detail', which see.
13775 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13776 done by a previous call to `org-occur' will be kept, to allow stacking of
13777 calls to this command.
13779 Optional argument CALLBACK can be a function of no argument. In this case,
13780 it is called with point at the end of the match, match data being set
13781 accordingly. Current match is shown only if the return value is non-nil.
13782 The function must neither move point nor alter narrowing."
13783 (interactive "sRegexp: \nP")
13784 (when (equal regexp "")
13785 (user-error "Regexp cannot be empty"))
13786 (unless keep-previous
13787 (org-remove-occur-highlights nil nil t))
13788 (push (cons regexp callback) org-occur-parameters)
13791 (goto-char (point-min))
13792 (when (or (not keep-previous) ; do not want to keep
13793 (not org-occur-highlights)) ; no previous matches
13796 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13797 (isearch-no-upper-case-p regexp t)
13798 org-occur-case-fold-search)))
13799 (while (re-search-forward regexp nil t)
13800 (when (or (not callback)
13801 (save-match-data (funcall callback)))
13802 (setq cnt (1+ cnt))
13803 (when org-highlight-sparse-tree-matches
13804 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13805 (org-show-context 'occur-tree)))))
13806 (when org-remove-highlights-with-change
13807 (add-hook 'before-change-functions 'org-remove-occur-highlights
13809 (unless org-sparse-tree-open-archived-trees
13810 (org-hide-archived-subtrees (point-min) (point-max)))
13811 (run-hooks 'org-occur-hook)
13812 (when (called-interactively-p 'interactive)
13813 (message "%d match(es) for regexp %s" cnt regexp))
13816 (defun org-occur-next-match (&optional n _reset)
13817 "Function for `next-error-function' to find sparse tree matches.
13818 N is the number of matches to move, when negative move backwards.
13819 This function always goes back to the starting point when no
13821 (let* ((limit (if (< n 0) (point-min) (point-max)))
13822 (search-func (if (< n 0)
13823 'previous-single-char-property-change
13824 'next-single-char-property-change))
13829 (while (setq p1 (funcall search-func (point) 'org-type))
13830 (when (equal p1 limit)
13832 (user-error "No more matches"))
13833 (when (equal (get-char-property p1 'org-type) 'org-occur)
13837 (throw 'exit (point))))
13840 (user-error "No more matches"))))
13842 (defun org-show-context (&optional key)
13843 "Make sure point and context are visible.
13844 Optional argument KEY, when non-nil, is a symbol. See
13845 `org-show-context-detail' for allowed values and how much is to
13847 (org-show-set-visibility
13848 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13849 ((cdr (assq key org-show-context-detail)))
13850 (t (cdr (assq 'default org-show-context-detail))))))
13852 (defun org-show-set-visibility (detail)
13853 "Set visibility around point according to DETAIL.
13854 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13855 `tree', `canonical' or t. See `org-show-context-detail' for more
13857 ;; Show current heading and possibly its entry, following headline
13858 ;; or all children.
13859 (if (and (org-at-heading-p) (not (eq detail 'local)))
13860 (org-flag-heading nil)
13862 ;; If point is hidden within a drawer or a block, make sure to
13864 (dolist (o (overlays-at (point)))
13865 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13866 (delete-overlay o)))
13867 (unless (org-before-first-heading-p)
13868 (org-with-limited-levels
13870 ((tree canonical t) (org-show-children))
13871 ((nil minimal ancestors))
13873 (outline-next-heading)
13874 (org-flag-heading nil)))))))
13875 ;; Show all siblings.
13876 (when (eq detail 'lineage) (org-show-siblings))
13877 ;; Show ancestors, possibly with their children.
13878 (when (memq detail '(ancestors lineage tree canonical t))
13880 (while (org-up-heading-safe)
13881 (org-flag-heading nil)
13882 (when (memq detail '(canonical t)) (org-show-entry))
13883 (when (memq detail '(tree canonical t)) (org-show-children))))))
13885 (defvar org-reveal-start-hook nil
13886 "Hook run before revealing a location.")
13888 (defun org-reveal (&optional siblings)
13889 "Show current entry, hierarchy above it, and the following headline.
13891 This can be used to show a consistent set of context around
13892 locations exposed with `org-show-context'.
13894 With optional argument SIBLINGS, on each level of the hierarchy all
13895 siblings are shown. This repairs the tree structure to what it would
13896 look like when opened with hierarchical calls to `org-cycle'.
13898 With a \\[universal-argument] \\[universal-argument] prefix, \
13899 go to the parent and show the entire tree."
13901 (run-hooks 'org-reveal-start-hook)
13902 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13903 ((equal siblings '(16))
13905 (when (org-up-heading-safe)
13907 (run-hook-with-args 'org-cycle-hook 'subtree))))
13908 (t (org-show-set-visibility 'lineage))))
13910 (defun org-highlight-new-match (beg end)
13911 "Highlight from BEG to END and mark the highlight is an occur headline."
13912 (let ((ov (make-overlay beg end)))
13913 (overlay-put ov 'face 'secondary-selection)
13914 (overlay-put ov 'org-type 'org-occur)
13915 (push ov org-occur-highlights)))
13917 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13918 "Remove the occur highlights from the buffer.
13919 BEG and END are ignored. If NOREMOVE is nil, remove this function
13920 from the `before-change-functions' in the current buffer."
13922 (unless org-inhibit-highlight-removal
13923 (mapc #'delete-overlay org-occur-highlights)
13924 (setq org-occur-highlights nil)
13925 (setq org-occur-parameters nil)
13927 (remove-hook 'before-change-functions
13928 'org-remove-occur-highlights 'local))))
13932 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13933 "Regular expression matching the priority indicator.")
13935 (defvar org-remove-priority-next-time nil)
13937 (defun org-priority-up ()
13938 "Increase the priority of the current item."
13940 (org-priority 'up))
13942 (defun org-priority-down ()
13943 "Decrease the priority of the current item."
13945 (org-priority 'down))
13947 (defun org-priority (&optional action _show)
13948 "Change the priority of an item.
13949 ACTION can be `set', `up', `down', or a character."
13951 (if (equal action '(4))
13952 (org-show-priority)
13953 (unless org-enable-priority-commands
13954 (user-error "Priority commands are disabled"))
13955 (setq action (or action 'set))
13956 (let (current new news have remove)
13958 (org-back-to-heading t)
13959 (when (looking-at org-priority-regexp)
13960 (setq current (string-to-char (match-string 2))
13963 ((eq action 'remove)
13964 (setq remove t new ?\ ))
13965 ((or (eq action 'set)
13967 (if (not (eq action 'set))
13969 (message "Priority %c-%c, SPC to remove: "
13970 org-highest-priority org-lowest-priority)
13972 (setq new (read-char-exclusive))))
13973 (when (and (= (upcase org-highest-priority) org-highest-priority)
13974 (= (upcase org-lowest-priority) org-lowest-priority))
13975 (setq new (upcase new)))
13976 (cond ((equal new ?\ ) (setq remove t))
13977 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13978 (user-error "Priority must be between `%c' and `%c'"
13979 org-highest-priority org-lowest-priority))))
13982 (1- current) ; normal cycling
13983 ;; last priority was empty
13984 (if (eq last-command this-command)
13985 org-lowest-priority ; wrap around empty to lowest
13987 (if org-priority-start-cycle-with-default
13988 org-default-priority
13989 (1- org-default-priority))))))
13992 (1+ current) ; normal cycling
13993 ;; last priority was empty
13994 (if (eq last-command this-command)
13995 org-highest-priority ; wrap around empty to highest
13997 (if org-priority-start-cycle-with-default
13998 org-default-priority
13999 (1+ org-default-priority))))))
14000 (t (user-error "Invalid action")))
14001 (when (or (< (upcase new) org-highest-priority)
14002 (> (upcase new) org-lowest-priority))
14003 (if (and (memq action '(up down))
14004 (not have) (not (eq last-command this-command)))
14005 ;; `new' is from default priority
14007 "The default can not be set, see `org-default-priority' why")
14008 ;; normal cycling: `new' is beyond highest/lowest priority
14009 ;; and is wrapped around to the empty priority
14011 (setq news (format "%c" new))
14014 (replace-match "" t t nil 1)
14015 (replace-match news t t nil 2))
14017 (user-error "No priority cookie found in line")
14018 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14021 (goto-char (match-end 2))
14022 (insert " [#" news "]"))
14023 (goto-char (match-beginning 3))
14024 (insert "[#" news "] "))))
14025 (org-set-tags nil 'align))
14027 (message "Priority removed")
14028 (message "Priority of current item set to %s" news)))))
14030 (defun org-show-priority ()
14031 "Show the priority of the current item.
14032 This priority is composed of the main priority given with the [#A] cookies,
14033 and by additional input from the age of a schedules or deadline entry."
14035 (let ((pri (if (eq major-mode 'org-agenda-mode)
14036 (org-get-at-bol 'priority)
14039 (beginning-of-line)
14040 (and (looking-at org-heading-regexp)
14041 (org-get-priority (match-string 0))))))))
14042 (message "Priority is %d" (if pri pri -1000))))
14044 (defun org-get-priority (s)
14045 "Find priority cookie and return priority."
14047 (if (functionp org-get-priority-function)
14048 (funcall org-get-priority-function)
14049 (if (not (string-match org-priority-regexp s))
14050 (* 1000 (- org-lowest-priority org-default-priority))
14051 (* 1000 (- org-lowest-priority
14052 (string-to-char (match-string 2 s))))))))
14056 (defvar org-agenda-archives-mode)
14057 (defvar org-map-continue-from nil
14058 "Position from where mapping should continue.
14059 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14061 (defvar org-scanner-tags nil
14062 "The current tag list while the tags scanner is running.")
14064 (defvar org-trust-scanner-tags nil
14065 "Should `org-get-tags-at' use the tags for the scanner.
14066 This is for internal dynamical scoping only.
14067 When this is non-nil, the function `org-get-tags-at' will return the value
14068 of `org-scanner-tags' instead of building the list by itself. This
14069 can lead to large speed-ups when the tags scanner is used in a file with
14070 many entries, and when the list of tags is retrieved, for example to
14071 obtain a list of properties. Building the tags list for each entry in such
14072 a file becomes an N^2 operation - but with this variable set, it scales
14075 (defvar org--matcher-tags-todo-only nil)
14077 (defun org-scan-tags (action matcher todo-only &optional start-level)
14078 "Scan headline tags with inheritance and produce output ACTION.
14080 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14081 or `agenda' to produce an entry list for an agenda view. It can also be
14082 a Lisp form or a function that should be called at each matched headline, in
14083 this case the return value is a list of all return values from these calls.
14085 MATCHER is a function accepting three arguments, returning
14086 a non-nil value whenever a given set of tags qualifies a headline
14087 for inclusion. See `org-make-tags-matcher' for more information.
14088 As a special case, it can also be set to t (respectively nil) in
14089 order to match all (respectively none) headline.
14091 When TODO-ONLY is non-nil, only lines with a TODO keyword are
14092 included in the output.
14094 START-LEVEL can be a string with asterisks, reducing the scope to
14095 headlines matching this string."
14096 (require 'org-agenda)
14097 (let* ((re (concat "^"
14099 ;; Get the correct level to match
14100 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14101 org-outline-regexp)
14103 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14104 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14105 (props (list 'face 'default
14106 'done-face 'org-agenda-done
14107 'undone-face 'default
14108 'mouse-face 'highlight
14109 'org-not-done-regexp org-not-done-regexp
14110 'org-todo-regexp org-todo-regexp
14111 'org-complex-heading-regexp org-complex-heading-regexp
14113 (format "mouse-2 or RET jump to org file %s"
14114 (abbreviate-file-name
14115 (or (buffer-file-name (buffer-base-buffer))
14116 (buffer-name (buffer-base-buffer)))))))
14117 (org-map-continue-from nil)
14118 lspos tags tags-list
14119 (tags-alist (list (cons 0 org-file-tags)))
14120 (llast 0) rtn rtn1 level category i txt
14121 todo marker entry priority
14122 ts-date ts-date-type ts-date-pair)
14123 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14124 (setq action (list 'lambda nil action)))
14126 (goto-char (point-min))
14127 (when (eq action 'sparse-tree)
14129 (org-remove-occur-highlights))
14130 (while (let (case-fold-search)
14131 (re-search-forward re nil t))
14132 (setq org-map-continue-from nil)
14135 ;; TODO: is the 1-2 difference a bug?
14136 (when (match-end 1) (match-string-no-properties 2))
14137 tags (when (match-end 4) (match-string-no-properties 4)))
14138 (goto-char (setq lspos (match-beginning 0)))
14139 (setq level (org-reduced-level (org-outline-level))
14140 category (org-get-category))
14141 (when (eq action 'agenda)
14142 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14143 ts-date (car ts-date-pair)
14144 ts-date-type (cdr ts-date-pair)))
14145 (setq i llast llast level)
14146 ;; remove tag lists from same and sublevels
14147 (while (>= i level)
14148 (when (setq entry (assoc i tags-alist))
14149 (setq tags-alist (delete entry tags-alist)))
14151 ;; add the next tags
14153 (setq tags (org-split-string tags ":")
14155 (cons (cons level tags) tags-alist)))
14156 ;; compile tags for current headline
14158 (if org-use-tag-inheritance
14159 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14161 org-scanner-tags tags-list)
14162 (when org-use-tag-inheritance
14163 (setcdr (car tags-alist)
14164 (mapcar (lambda (x)
14165 (setq x (copy-sequence x))
14166 (org-add-prop-inherited x))
14167 (cdar tags-alist))))
14168 (when (and tags org-use-tag-inheritance
14169 (or (not (eq t org-use-tag-inheritance))
14170 org-tags-exclude-from-inheritance))
14171 ;; Selective inheritance, remove uninherited ones.
14172 (setcdr (car tags-alist)
14173 (org-remove-uninherited-tags (cdar tags-alist))))
14176 ;; eval matcher only when the todo condition is OK
14177 (and (or (not todo-only) (member todo org-todo-keywords-1))
14178 (if (functionp matcher)
14179 (let ((case-fold-search t) (org-trust-scanner-tags t))
14180 (funcall matcher todo tags-list level))
14183 ;; Call the skipper, but return t if it does not
14184 ;; skip, so that the `and' form continues evaluating.
14186 (unless (eq action 'sparse-tree) (org-agenda-skip))
14189 ;; Check if timestamps are deselecting this entry
14190 (or (not todo-only)
14191 (and (member todo org-todo-keywords-1)
14192 (or (not org-agenda-tags-todo-honor-ignore-options)
14193 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14195 ;; select this headline
14197 ((eq action 'sparse-tree)
14198 (and org-highlight-sparse-tree-matches
14199 (org-get-heading) (match-end 0)
14200 (org-highlight-new-match
14201 (match-beginning 1) (match-end 1)))
14202 (org-show-context 'tags-tree))
14203 ((eq action 'agenda)
14204 (setq txt (org-agenda-format-item
14207 (if (eq org-tags-match-list-sublevels 'indented)
14208 (make-string (1- level) ?.) "")
14210 (make-string level ?\s)
14213 priority (org-get-priority txt))
14215 (setq marker (org-agenda-new-marker))
14216 (org-add-props txt props
14217 'org-marker marker 'org-hd-marker marker 'org-category category
14221 'type (concat "tagsmatch" ts-date-type))
14223 ((functionp action)
14224 (setq org-map-continue-from nil)
14226 (setq rtn1 (funcall action))
14228 (t (user-error "Invalid action")))
14230 ;; if we are to skip sublevels, jump to end of subtree
14231 (unless org-tags-match-list-sublevels
14232 (org-end-of-subtree t)
14233 (backward-char 1))))
14234 ;; Get the correct position from where to continue
14235 (if org-map-continue-from
14236 (goto-char org-map-continue-from)
14237 (and (= (point) lspos) (end-of-line 1)))))
14238 (when (and (eq action 'sparse-tree)
14239 (not org-sparse-tree-open-archived-trees))
14240 (org-hide-archived-subtrees (point-min) (point-max)))
14243 (defun org-remove-uninherited-tags (tags)
14244 "Remove all tags that are not inherited from the list TAGS."
14246 ((eq org-use-tag-inheritance t)
14247 (if org-tags-exclude-from-inheritance
14248 (org-delete-all org-tags-exclude-from-inheritance tags)
14250 ((not org-use-tag-inheritance) nil)
14251 ((stringp org-use-tag-inheritance)
14254 (if (and (string-match org-use-tag-inheritance x)
14255 (not (member x org-tags-exclude-from-inheritance)))
14258 ((listp org-use-tag-inheritance)
14261 (if (member x org-use-tag-inheritance) x nil))
14264 (defun org-match-sparse-tree (&optional todo-only match)
14265 "Create a sparse tree according to tags string MATCH.
14267 MATCH is a string with match syntax. It can contain a selection
14268 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14269 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14270 those. See the manual for details.
14272 If optional argument TODO-ONLY is non-nil, only select lines that
14273 are also TODO tasks."
14275 (org-agenda-prepare-buffers (list (current-buffer)))
14276 (let ((org--matcher-tags-todo-only todo-only))
14277 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14278 org--matcher-tags-todo-only)))
14280 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14282 (defvar org-cached-props nil)
14283 (defun org-cached-entry-get (pom property)
14284 (if (or (eq t org-use-property-inheritance)
14285 (and (stringp org-use-property-inheritance)
14286 (let ((case-fold-search t))
14287 (string-match-p org-use-property-inheritance property)))
14288 (and (listp org-use-property-inheritance)
14289 (member-ignore-case property org-use-property-inheritance)))
14290 ;; Caching is not possible, check it directly.
14291 (org-entry-get pom property 'inherit)
14292 ;; Get all properties, so we can do complicated checks easily.
14293 (cdr (assoc-string property
14294 (or org-cached-props
14295 (setq org-cached-props (org-entry-properties pom)))
14298 (defun org-global-tags-completion-table (&optional files)
14299 "Return the list of all tags in all agenda buffer/files.
14300 Optional FILES argument is a list of files which can be used
14301 instead of the agenda files."
14308 (set-buffer (find-file-noselect file))
14309 (mapcar (lambda (x)
14310 (and (stringp (car-safe x))
14311 (list (car-safe x))))
14312 (or org-current-tag-alist (org-get-buffer-tags))))
14313 (if (car-safe files) files
14314 (org-agenda-files))))))))
14316 (defun org-make-tags-matcher (match)
14317 "Create the TAGS/TODO matcher form for the selection string MATCH.
14319 Returns a cons of the selection string MATCH and a function
14320 implementing the matcher.
14322 The matcher is to be called at an Org entry, with point on the
14323 headline, and returns non-nil if the entry matches the selection
14324 string MATCH. It must be called with three arguments: the TODO
14325 keyword at the entry (or nil if none), the list of all tags at
14326 the entry including inherited ones and the reduced level of the
14327 headline. Additionally, the category of the entry, if any, must
14328 be specified as the text property `org-category' on the headline.
14330 This function sets the variable `org--matcher-tags-todo-only' to
14331 a non-nil value if the matcher restricts matching to TODO
14332 entries, otherwise it is not touched.
14334 See also `org-scan-tags'."
14336 ;; Get a new match request, with completion against the global
14337 ;; tags table and the local tags in current buffer.
14338 (let ((org-last-tags-completion-table
14340 (delq nil (append (org-get-buffer-tags)
14341 (org-global-tags-completion-table))))))
14345 'org-tags-completion-function nil nil nil 'org-tags-history))))
14347 (let ((match0 match)
14348 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14350 tagsmatch todomatch tagsmatcher todomatcher)
14352 ;; Expand group tags.
14353 (setq match (org-tags-expand match))
14355 ;; Check if there is a TODO part of this match, which would be the
14356 ;; part after a "/". To make sure that this slash is not part of
14357 ;; a property value to be matched against, we also check that
14358 ;; there is no / after that slash. First, find the last slash.
14360 (while (string-match "/+" match s)
14361 (setq start (match-beginning 0))
14362 (setq s (match-end 0))))
14363 (if (and (string-match "/+" match start)
14364 (not (string-match-p "\"" match start)))
14365 ;; Match contains also a TODO-matching request.
14367 (setq tagsmatch (substring match 0 (match-beginning 0)))
14368 (setq todomatch (substring match (match-end 0)))
14369 (when (string-prefix-p "!" todomatch)
14370 (setq org--matcher-tags-todo-only t)
14371 (setq todomatch (substring todomatch 1)))
14372 (when (string-match "\\`\\s-*\\'" todomatch)
14373 (setq todomatch nil)))
14374 ;; Only matching tags.
14375 (setq tagsmatch match)
14376 (setq todomatch nil))
14378 ;; Make the tags matcher.
14379 (when (org-string-nw-p tagsmatch)
14381 (orterms (org-split-string tagsmatch "|"))
14383 (while (setq term (pop orterms))
14384 (while (and (equal (substring term -1) "\\") orterms)
14385 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14386 (while (string-match re term)
14387 (let* ((rest (substring term (match-end 0)))
14388 (minus (and (match-end 1)
14389 (equal (match-string 1 term) "-")))
14390 (tag (save-match-data
14391 (replace-regexp-in-string
14392 "\\\\-" "-" (match-string 2 term))))
14393 (regexp (eq (string-to-char tag) ?{))
14394 (levelp (match-end 4))
14395 (propp (match-end 5))
14398 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14400 `(,(org-op-to-function (match-string 3 term))
14402 ,(string-to-number (match-string 4 term))))
14404 (let* ((gv (pcase (upcase (match-string 5 term))
14406 '(get-text-property (point) 'org-category))
14408 (p `(org-cached-entry-get nil ,p))))
14409 (pv (match-string 7 term))
14410 (regexp (eq (string-to-char pv) ?{))
14411 (strp (eq (string-to-char pv) ?\"))
14412 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14413 (po (org-op-to-function (match-string 6 term)
14414 (if timep 'time strp))))
14415 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14416 (when timep (setq pv (org-matcher-time pv)))
14417 (cond ((and regexp (eq po 'org<>))
14418 `(not (string-match ,pv (or ,gv ""))))
14419 (regexp `(string-match ,pv (or ,gv "")))
14420 (strp `(,po (or ,gv "") ,pv))
14423 (string-to-number (or ,gv ""))
14424 ,(string-to-number pv))))))
14425 (t `(member ,tag tags-list)))))
14426 (push (if minus `(not ,mm) mm) tagsmatcher)
14428 (push `(and ,@tagsmatcher) orlist)
14429 (setq tagsmatcher nil))
14430 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14432 ;; Make the TODO matcher.
14433 (when (org-string-nw-p todomatch)
14434 (let ((orlist nil))
14435 (dolist (term (org-split-string todomatch "|"))
14436 (while (string-match re term)
14437 (let* ((minus (and (match-end 1)
14438 (equal (match-string 1 term) "-")))
14439 (kwd (match-string 2 term))
14440 (regexp (eq (string-to-char kwd) ?{))
14441 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14442 `(equal todo ,kwd))))
14443 (push (if minus `(not ,mm) mm) todomatcher))
14444 (setq term (substring term (match-end 0))))
14445 (push (if (> (length todomatcher) 1)
14446 (cons 'and todomatcher)
14449 (setq todomatcher nil))
14450 (setq todomatcher (cons 'or orlist))))
14452 ;; Return the string and function of the matcher. If no
14453 ;; tags-specific or todo-specific matcher exists, match
14455 (let ((matcher (if (and tagsmatcher todomatcher)
14456 `(and ,tagsmatcher ,todomatcher)
14457 (or tagsmatcher todomatcher t))))
14458 (when org--matcher-tags-todo-only
14459 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14460 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14462 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14463 "Expand group tags in MATCH.
14465 This replaces every group tag in MATCH with a regexp tag search.
14466 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14467 will be replaced like this:
14469 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14470 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14471 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14473 Replacing by a regexp preserves the structure of the match.
14474 E.g., this expansion
14476 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14478 will match anything tagged with \"Lab\" and \"Home\", or tagged
14479 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14481 A group tag in MATCH can contain regular expressions of its own.
14482 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14483 will be replaced like this:
14485 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14487 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14488 assumed to be a single group tag, and the function will return
14489 the list of tags in this group.
14491 When DOWNCASE is non-nil, expand downcased TAGS."
14493 (let* ((case-fold-search t)
14494 (stable org-mode-syntax-table)
14495 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14496 (taggroups (if downcased
14497 (mapcar (lambda (tg) (mapcar #'downcase tg))
14500 (taggroups-keys (mapcar #'car taggroups))
14501 (return-match (if downcased (downcase match) match))
14503 (work-already-expanded tags-already-expanded)
14504 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14505 ;; @ and _ are allowed as word-components in tags.
14506 (modify-syntax-entry ?@ "w" stable)
14507 (modify-syntax-entry ?_ "w" stable)
14508 ;; Temporarily replace regexp-expressions in the match-expression.
14509 (while (string-match "{.+?}" return-match)
14511 (push (match-string 0 return-match) regexps-in-match)
14512 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14513 (while (and taggroups-keys
14514 (with-syntax-table stable
14516 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14517 (regexp-opt taggroups-keys) "\\>\\)")
14519 (let* ((dir (match-string 1 return-match))
14520 (tag (match-string 2 return-match))
14521 (tag (if downcased (downcase tag) tag)))
14522 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14523 (member tag work-already-expanded))
14524 (setq tags-in-group (assoc tag taggroups))
14525 (push tag work-already-expanded)
14526 ;; Recursively expand each tag in the group, if the tag hasn't
14527 ;; already been expanded. Restore the match-data after all recursive calls.
14529 (let (tags-expanded)
14530 (dolist (x (cdr tags-in-group))
14531 (if (and (member x taggroups-keys)
14532 (not (member x work-already-expanded)))
14533 (setq tags-expanded
14536 (org-tags-expand x t downcased
14537 work-already-expanded)
14539 (setq tags-expanded
14540 (append (list x) tags-expanded)))
14541 (setq work-already-expanded
14543 (append tags-expanded
14544 work-already-expanded))))
14545 (setq tags-in-group
14546 (delete-dups (cons (car tags-in-group)
14548 ;; Filter tag-regexps from tags.
14549 (setq regexp-in-group-escaped
14550 (delq nil (mapcar (lambda (x)
14552 (and (equal "{" (substring x 0 1))
14553 (equal "}" (substring x -1))
14558 (mapcar (lambda (x)
14559 (substring x 1 -1))
14560 regexp-in-group-escaped)
14562 (delq nil (mapcar (lambda (x)
14564 (and (not (equal "{" (substring x 0 1)))
14565 (not (equal "}" (substring x -1)))
14569 ;; If single-as-list, do no more in the while-loop.
14570 (if (not single-as-list)
14572 (when regexp-in-group
14573 (setq regexp-in-group
14575 (mapconcat 'identity regexp-in-group
14577 (setq tags-in-group
14580 (regexp-opt tags-in-group)
14584 (when (stringp tags-in-group)
14585 (org-add-props tags-in-group '(grouptag t)))
14587 (replace-match tags-in-group t t return-match)))
14588 (setq tags-in-group
14589 (append regexp-in-group-escaped tags-in-group))))
14590 (setq taggroups-keys (delete tag taggroups-keys))))
14591 ;; Add the regular expressions back into the match-expression again.
14592 (while regexps-in-match
14593 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14594 (pop regexps-in-match)
14598 (if tags-in-group tags-in-group (list return-match))
14601 (list (if downcased (downcase match) match))
14604 (defun org-op-to-function (op &optional stringp)
14605 "Turn an operator into the appropriate function."
14608 ((equal op "<" ) '(< string< org-time<))
14609 ((equal op ">" ) '(> org-string> org-time>))
14610 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14611 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14612 ((member op '("=" "==")) '(= string= org-time=))
14613 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14614 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14616 (defun org<> (a b) (not (= a b)))
14617 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14618 (defun org-string>= (a b) (not (string< a b)))
14619 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14620 (defun org-string<> (a b) (not (string= a b)))
14621 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14622 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14623 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14624 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14625 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14626 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14628 "Convert S to a floating point time.
14629 If S is already a number, just return it. If it is a string, parse
14630 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14634 (condition-case nil
14635 (float-time (apply #'encode-time (org-parse-time-string s)))
14639 (defun org-time-today ()
14640 "Time in seconds today at 0:00.
14641 Returns the float number of seconds since the beginning of the
14642 epoch to the beginning of today (00:00)."
14643 (float-time (apply 'encode-time
14644 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14646 (defun org-matcher-time (s)
14647 "Interpret a time comparison value."
14650 ((string= s "<now>") (float-time))
14651 ((string= s "<today>") (org-time-today))
14652 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14653 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14654 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14655 (+ (org-time-today)
14656 (* (string-to-number (match-string 1 s))
14657 (cdr (assoc (match-string 2 s)
14658 '(("d" . 86400.0) ("w" . 604800.0)
14659 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14662 (defun org-match-any-p (re list)
14663 "Does re match any element of list?"
14664 (setq list (mapcar (lambda (x) (string-match re x)) list))
14667 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14668 (defvar org-tags-overlay (make-overlay 1 1))
14669 (delete-overlay org-tags-overlay)
14671 (defun org-get-local-tags-at (&optional pos)
14672 "Get a list of tags defined in the current headline."
14673 (org-get-tags-at pos 'local))
14675 (defun org-get-local-tags ()
14676 "Get a list of tags defined in the current headline."
14677 (org-get-tags-at nil 'local))
14679 (defun org-get-tags-at (&optional pos local)
14680 "Get a list of all headline tags applicable at POS.
14681 POS defaults to point. If tags are inherited, the list contains
14682 the targets in the same sequence as the headlines appear, i.e.
14683 the tags of the current headline come last.
14684 When LOCAL is non-nil, only return tags from the current headline,
14685 ignore inherited ones."
14687 (if (and org-trust-scanner-tags
14688 (or (not pos) (equal pos (point)))
14691 (let (tags ltags lastpos parent)
14695 (goto-char (or pos (point)))
14698 (condition-case nil
14700 (org-back-to-heading t)
14701 (while (not (equal lastpos (point)))
14702 (setq lastpos (point))
14703 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14704 (setq ltags (org-split-string
14705 (match-string-no-properties 1) ":"))
14707 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14710 (org-remove-uninherited-tags ltags)
14713 (or org-use-tag-inheritance (throw 'done t))
14714 (when local (throw 'done t))
14715 (or (org-up-heading-safe) (error nil))
14720 (reverse (delete-dups
14722 (org-remove-uninherited-tags
14726 (defun org-add-prop-inherited (s)
14727 (add-text-properties 0 (length s) '(inherited t) s)
14730 (defun org-toggle-tag (tag &optional onoff)
14731 "Toggle the tag TAG for the current line.
14732 If ONOFF is `on' or `off', don't toggle but set to this state."
14734 (org-back-to-heading t)
14736 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14737 (line-end-position) t)
14738 (let ((tags (match-string 1)))
14739 ;; Clear current tags.
14741 ;; Reverse the tags list so any new tag is appended to
14742 ;; the current list of tags.
14743 (nreverse (org-split-string tags ":")))))
14746 (`off (setq current (delete tag current)))
14747 ((or `on (guard (not (member tag current))))
14749 (cl-pushnew tag current :test #'equal))
14750 (_ (setq current (delete tag current))))
14754 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14755 (org-set-tags nil t))
14756 (delete-horizontal-space))
14757 (run-hooks 'org-after-tags-change-hook)
14760 (defun org--align-tags-here (to-col)
14761 "Align tags on the current headline to TO-COL.
14762 Assume point is on a headline."
14763 (let ((pos (point)))
14764 (beginning-of-line)
14765 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14766 (>= pos (match-beginning 2)))
14767 ;; No tags or point within tags: do not align.
14769 (goto-char (match-beginning 1))
14770 (let ((shift (max (- (if (>= to-col 0) to-col
14771 (- (abs to-col) (string-width (match-string 2))))
14774 (replace-match (make-string shift ?\s) nil nil nil 1)
14775 ;; Preserve initial position, if possible. In any case, stop
14777 (when (< pos (point)) (goto-char pos))))))
14779 (defun org-set-tags-command (&optional arg just-align)
14780 "Call the set-tags command for the current entry."
14782 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14783 (org-set-tags arg just-align)
14785 (unless (and (org-region-active-p)
14786 org-loop-over-headlines-in-active-region)
14787 (org-back-to-heading t))
14788 (org-set-tags arg just-align))))
14790 (defun org-set-tags-to (data)
14791 "Set the tags of the current entry to DATA, replacing the current tags.
14792 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14793 If DATA is nil or the empty string, any tags will be removed."
14794 (interactive "sTags: ")
14798 ((equal data "") "")
14800 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14803 (concat ":" (mapconcat 'identity data ":") ":"))))
14806 (org-back-to-heading t)
14807 (when (let ((case-fold-search nil))
14808 (looking-at org-complex-heading-regexp))
14811 (goto-char (match-beginning 5))
14813 (delete-region (point) (point-at-eol))
14814 (org-set-tags nil 'align))
14815 (goto-char (point-at-eol))
14817 (org-set-tags nil 'align)))
14818 (beginning-of-line 1)
14819 (when (looking-at ".*?\\([ \t]+\\)$")
14820 (delete-region (match-beginning 1) (match-end 1))))))
14822 (defun org-align-all-tags ()
14823 "Align the tags in all headings."
14826 (or (ignore-errors (org-back-to-heading t))
14827 (outline-next-heading))
14828 (if (org-at-heading-p)
14830 (message "No headings"))))
14832 (defvar org-indent-indentation-per-level)
14833 (defun org-set-tags (&optional arg just-align)
14834 "Set the tags for the current headline.
14835 With prefix ARG, realign all tags in headings in the current buffer.
14836 When JUST-ALIGN is non-nil, only align tags."
14838 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14839 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14840 'region-start-level
14842 org-loop-over-headlines-in-active-region)
14844 ;; We don't use ARG and JUST-ALIGN here because these args
14845 ;; are not useful when looping over headlines.
14847 org-loop-over-headlines-in-active-region
14849 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14850 (let ((org-setting-tags t))
14853 (goto-char (point-min))
14854 (while (re-search-forward org-outline-regexp-bol nil t)
14855 (org-set-tags nil t)
14857 (message "All tags realigned to column %d" org-tags-column))
14858 (let* ((current (org-get-tags-string))
14860 (if just-align current
14861 ;; Get a new set of tags from the user.
14866 org-last-tags-completion-table
14867 ;; Uniquify tags in alists, yet preserve
14868 ;; structure (i.e., keywords).
14872 (let ((head (car pair)))
14873 (cond ((symbolp head) pair)
14874 ((member head seen) nil)
14875 (t (push head seen)
14878 (or org-current-tag-alist
14879 (org-get-buffer-tags))
14881 org-complete-tags-always-offer-all-agenda-tags
14882 (org-global-tags-completion-table
14883 (org-agenda-files))))))))
14884 (current-tags (org-split-string current ":"))
14886 (nreverse (nthcdr (length current-tags)
14887 (nreverse (org-get-tags-at))))))
14888 (replace-regexp-in-string
14891 (if (or (eq t org-use-fast-tag-selection)
14892 (and org-use-fast-tag-selection
14893 (delq nil (mapcar #'cdr table))))
14894 (org-fast-tag-selection
14895 current-tags inherited-tags table
14896 (and org-fast-tag-selection-include-todo
14897 org-todo-key-alist))
14898 (let ((org-add-colon-after-tag-completion
14899 (< 1 (length table))))
14903 #'org-tags-completion-function
14904 nil nil current 'org-tags-history))))))))))
14906 (when org-tags-sort-function
14910 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14911 org-tags-sort-function)
14914 (if (or (string= ":" tags)
14915 (string= "::" tags))
14917 (if (not (org-string-nw-p tags)) (setq tags "")
14918 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14919 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14921 ;; Insert new tags at the correct column.
14922 (unless (equal current tags)
14924 (beginning-of-line)
14925 (let ((case-fold-search nil))
14926 (looking-at org-complex-heading-regexp))
14927 ;; Remove current tags, if any.
14928 (when (match-end 5) (replace-match "" nil nil nil 5))
14929 ;; Insert new tags, if any. Otherwise, remove trailing
14932 (if (not (equal tags ""))
14933 ;; When text is being inserted on an invisible
14934 ;; region boundary, it can be inadvertently sucked
14935 ;; into invisibility.
14936 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14937 (skip-chars-backward " \t")
14938 (delete-region (point) (line-end-position)))))
14939 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14941 (unless (equal tags "")
14942 (let* ((level (save-excursion
14943 (beginning-of-line)
14944 (skip-chars-forward "\\*")))
14945 (offset (if (bound-and-true-p org-indent-mode)
14946 (* (1- org-indent-indentation-per-level)
14951 (if (> org-tags-column 0) (- offset) offset))))
14952 (org--align-tags-here tags-column))))
14953 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14955 (defun org-change-tag-in-region (beg end tag off)
14956 "Add or remove TAG for each entry in the region.
14957 This works in the agenda, and also in an Org buffer."
14959 (list (region-beginning) (region-end)
14960 (let ((org-last-tags-completion-table
14961 (if (derived-mode-p 'org-mode)
14963 (delq nil (append (org-get-buffer-tags)
14964 (org-global-tags-completion-table))))
14965 (org-global-tags-completion-table))))
14967 "Tag: " 'org-tags-completion-function nil nil nil
14968 'org-tags-history))
14970 (message "[s]et or
[r]emove? ")
14971 (equal (read-char-exclusive) ?r))))
14972 (when (fboundp 'deactivate-mark) (deactivate-mark))
14973 (let ((agendap (equal major-mode 'org-agenda-mode))
14974 l1 l2 m buf pos newhead (cnt 0))
14976 (setq l2 (1- (org-current-line)))
14978 (setq l1 (org-current-line))
14979 (cl-loop for l from l1 to l2 do
14981 (setq m (get-text-property (point) 'org-hd-marker))
14982 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14984 (setq buf (if agendap (marker-buffer m) (current-buffer))
14985 pos (if agendap m (point)))
14986 (with-current-buffer buf
14990 (setq cnt (1+ cnt))
14991 (org-toggle-tag tag (if off 'off 'on))
14992 (setq newhead (org-get-heading)))))
14993 (and agendap (org-agenda-change-all-lines newhead m))))
14994 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14996 (defun org-tags-completion-function (string _predicate &optional flag)
14997 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14998 (confirm (lambda (x) (stringp (car x)))))
14999 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15000 (setq s1 (match-string 1 string)
15001 s2 (match-string 2 string))
15002 (setq s1 "" s2 string))
15006 (setq rtn (try-completion s2 ctable confirm))
15007 (when (stringp rtn)
15009 (concat s1 s2 (substring rtn (length s2))
15010 (if (and org-add-colon-after-tag-completion
15011 (assoc rtn ctable))
15016 (all-completions s2 ctable confirm))
15019 (assoc s2 ctable)))))
15021 (defun org-fast-tag-insert (kwd tags face &optional end)
15022 "Insert KDW, and the TAGS, the latter with face FACE.
15024 (insert (format "%-12s" (concat kwd ":"))
15025 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15028 (defun org-fast-tag-show-exit (flag)
15031 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15032 (replace-match ""))
15035 (org-move-to-column (- (window-width) 19) t)
15036 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15038 (defun org-set-current-tags-overlay (current prefix)
15039 "Add an overlay to CURRENT tag with PREFIX."
15040 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15041 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15042 (org-overlay-display org-tags-overlay (concat prefix s))))
15044 (defvar org-last-tag-selection-key nil)
15045 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15046 "Fast tag selection with single keys.
15047 CURRENT is the current list of tags in the headline, INHERITED is the
15048 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15049 possibly with grouping information. TODO-TABLE is a similar table with
15050 TODO keywords, should these have keys assigned to them.
15051 If the keys are nil, a-z are automatically assigned.
15052 Returns the new tags string, or nil to not change the current settings."
15053 (let* ((fulltable (append table todo-table))
15054 (maxlen (apply 'max (mapcar
15056 (if (stringp (car x)) (string-width (car x)) 0))
15058 (buf (current-buffer))
15059 (expert (eq org-fast-tag-selection-single-key 'expert))
15061 (fwidth (+ maxlen 3 1 3))
15062 (ncol (/ (- (window-width) 4) fwidth))
15065 tg cnt e c char c1 c2 ntable tbl rtn
15066 ov-start ov-end ov-prefix
15067 (exit-after-next org-fast-tag-selection-single-key)
15068 (done-keywords org-done-keywords)
15069 groups ingroup intaggroup)
15071 (beginning-of-line 1)
15072 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15073 (setq ov-start (match-beginning 1)
15074 ov-end (match-end 1)
15076 (setq ov-start (1- (point-at-eol))
15077 ov-end (1+ ov-start))
15078 (skip-chars-forward "^\n\r")
15081 (buffer-substring (1- (point)) (point))
15082 (if (> (current-column) org-tags-column)
15084 (make-string (- org-tags-column (current-column)) ?\ ))))))
15085 (move-overlay org-tags-overlay ov-start ov-end)
15086 (save-window-excursion
15088 (set-buffer (get-buffer-create " *Org tags*"))
15089 (delete-other-windows)
15090 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15091 (org-switch-to-buffer-other-window " *Org tags*"))
15093 (setq-local org-done-keywords done-keywords)
15094 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15095 (org-fast-tag-insert "Current" current c-face "\n\n")
15096 (org-fast-tag-show-exit exit-after-next)
15097 (org-set-current-tags-overlay current ov-prefix)
15098 (setq tbl fulltable char ?a cnt 0)
15099 (while (setq e (pop tbl))
15101 ((eq (car e) :startgroup)
15102 (push '() groups) (setq ingroup t)
15103 (unless (zerop cnt)
15106 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15107 ((eq (car e) :endgroup)
15108 (setq ingroup nil cnt 0)
15109 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15110 ((eq (car e) :startgrouptag)
15111 (setq intaggroup t)
15112 (unless (zerop cnt)
15116 ((eq (car e) :endgrouptag)
15117 (setq intaggroup nil cnt 0)
15119 ((equal e '(:newline))
15120 (unless (zerop cnt)
15124 (while (equal (car tbl) '(:newline))
15126 (setq tbl (cdr tbl)))))
15127 ((equal e '(:grouptags)) (insert " : "))
15129 (setq tg (copy-sequence (car e)) c2 nil)
15132 ;; automatically assign a character.
15133 (setq c1 (string-to-char
15134 (downcase (substring
15135 tg (if (= (string-to-char tg) ?@) 1 0)))))
15136 (if (or (rassoc c1 ntable) (rassoc c1 table))
15137 (while (or (rassoc char ntable) (rassoc char table))
15138 (setq char (1+ char)))
15140 (setq c (or c2 char)))
15141 (when ingroup (push tg (car groups)))
15142 (setq tg (org-add-props tg nil 'face
15144 ((not (assoc tg table))
15145 (org-get-todo-face tg))
15146 ((member tg current) c-face)
15147 ((member tg inherited) i-face))))
15148 (when (equal (caar tbl) :grouptags)
15149 (org-add-props tg nil 'face 'org-tag-group))
15150 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15151 (insert "[" c "] " tg (make-string
15152 (- fwidth 4 (length tg)) ?\ ))
15153 (push (cons tg c) ntable)
15154 (when (= (cl-incf cnt) ncol)
15156 (when (or ingroup intaggroup) (insert " "))
15158 (setq ntable (nreverse ntable))
15160 (goto-char (point-min))
15161 (unless expert (org-fit-window-to-buffer))
15165 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
15166 (if (not groups) "no " "")
15167 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15168 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15169 (setq org-last-tag-selection-key c)
15171 ((= c ?\r) (throw 'exit t))
15173 (setq groups (not groups))
15174 (goto-char (point-min))
15175 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15178 (org-fast-tag-show-exit
15179 (setq exit-after-next (not exit-after-next)))
15181 (delete-other-windows)
15182 (set-window-buffer (split-window-vertically) " *Org tags*")
15183 (org-switch-to-buffer-other-window " *Org tags*")
15184 (org-fit-window-to-buffer)))
15186 (and (= c ?q) (not (rassoc c ntable))))
15187 (delete-overlay org-tags-overlay)
15188 (setq quit-flag t))
15191 (when exit-after-next (setq exit-after-next 'now)))
15193 (condition-case nil
15194 (setq tg (completing-read
15197 (with-current-buffer buf
15199 (org-get-buffer-tags))))))
15200 (quit (setq tg "")))
15201 (when (string-match "\\S-" tg)
15202 (cl-pushnew (list tg) buffer-tags :test #'equal)
15203 (if (member tg current)
15204 (setq current (delete tg current))
15205 (push tg current)))
15206 (when exit-after-next (setq exit-after-next 'now)))
15207 ((setq e (rassoc c todo-table) tg (car e))
15208 (with-current-buffer buf
15209 (save-excursion (org-todo tg)))
15210 (when exit-after-next (setq exit-after-next 'now)))
15211 ((setq e (rassoc c ntable) tg (car e))
15212 (if (member tg current)
15213 (setq current (delete tg current))
15214 (cl-loop for g in groups do
15215 (when (member tg g)
15216 (dolist (x g) (setq current (delete x current)))))
15218 (when exit-after-next (setq exit-after-next 'now))))
15220 ;; Create a sorted list
15224 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15225 (when (eq exit-after-next 'now) (throw 'exit t))
15226 (goto-char (point-min))
15227 (beginning-of-line 2)
15228 (delete-region (point) (point-at-eol))
15229 (org-fast-tag-insert "Current" current c-face)
15230 (org-set-current-tags-overlay current ov-prefix)
15231 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15232 (setq tg (match-string 1))
15233 (add-text-properties
15234 (match-beginning 1) (match-end 1)
15237 ((member tg current) c-face)
15238 ((member tg inherited) i-face)
15239 (t (get-text-property (match-beginning 1) 'face))))))
15240 (goto-char (point-min)))))
15241 (delete-overlay org-tags-overlay)
15243 (mapconcat 'identity current ":")
15246 (defun org-get-tags-string ()
15247 "Get the TAGS string in the current headline."
15248 (unless (org-at-heading-p t)
15249 (user-error "Not on a heading"))
15251 (beginning-of-line 1)
15252 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15253 (match-string-no-properties 1)
15256 (defun org-get-tags ()
15257 "Get the list of tags specified in the current headline."
15258 (org-split-string (org-get-tags-string) ":"))
15260 (defun org-get-buffer-tags ()
15261 "Get a table of all tags used in the buffer, for completion."
15262 (org-with-wide-buffer
15263 (goto-char (point-min))
15264 (let ((tag-re (concat org-outline-regexp-bol
15265 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15267 (while (re-search-forward tag-re nil t)
15268 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15270 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15272 ;;;; The mapping API
15274 (defvar org-agenda-skip-comment-trees)
15275 (defvar org-agenda-skip-function)
15276 (defun org-map-entries (func &optional match scope &rest skip)
15277 "Call FUNC at each headline selected by MATCH in SCOPE.
15279 FUNC is a function or a lisp form. The function will be called without
15280 arguments, with the cursor positioned at the beginning of the headline.
15281 The return values of all calls to the function will be collected and
15282 returned as a list.
15284 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15285 does not need to preserve point. After evaluation, the cursor will be
15286 moved to the end of the line (presumably of the headline of the
15287 processed entry) and search continues from there. Under some
15288 circumstances, this may not produce the wanted results. For example,
15289 if you have removed (e.g. archived) the current (sub)tree it could
15290 mean that the next entry will be skipped entirely. In such cases, you
15291 can specify the position from where search should continue by making
15292 FUNC set the variable `org-map-continue-from' to the desired buffer
15295 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15296 Only headlines that are matched by this query will be considered during
15297 the iteration. When MATCH is nil or t, all headlines will be
15298 visited by the iteration.
15300 SCOPE determines the scope of this command. It can be any of:
15302 nil The current buffer, respecting the restriction if any
15303 tree The subtree started with the entry at point
15304 region The entries within the active region, if any
15306 The entries within the active region, but only those at
15307 the same level than the first one.
15308 file The current buffer, without restriction
15310 The current buffer, and any archives associated with it
15311 agenda All agenda files
15312 agenda-with-archives
15313 All agenda files with any archive files associated with them
15315 If this is a list, all files in the list will be scanned
15317 The remaining args are treated as settings for the skipping facilities of
15318 the scanner. The following items can be given here:
15320 archive skip trees with the archive tag
15321 comment skip trees with the COMMENT keyword
15322 function or Emacs Lisp form:
15323 will be used as value for `org-agenda-skip-function', so
15324 whenever the function returns a position, FUNC will not be
15325 called for that entry and search will continue from the
15328 If your function needs to retrieve the tags including inherited tags
15329 at the *current* entry, you can use the value of the variable
15330 `org-scanner-tags' which will be much faster than getting the value
15331 with `org-get-tags-at'. If your function gets properties with
15332 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15333 to t around the call to `org-entry-properties' to get the same speedup.
15334 Note that if your function moves around to retrieve tags and properties at
15335 a *different* entry, you cannot use these techniques."
15336 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15337 (not (org-region-active-p)))
15338 (let* ((org-agenda-archives-mode nil) ; just to make sure
15339 (org-agenda-skip-archived-trees (memq 'archive skip))
15340 (org-agenda-skip-comment-trees (memq 'comment skip))
15341 (org-agenda-skip-function
15342 (car (org-delete-all '(comment archive) skip)))
15343 (org-tags-match-list-sublevels t)
15344 (start-level (eq scope 'region-start-level))
15346 org-todo-keywords-for-agenda
15347 org-done-keywords-for-agenda
15348 org-todo-keyword-alist-for-agenda
15349 org-tag-alist-for-agenda
15350 org--matcher-tags-todo-only)
15353 ((eq match t) (setq matcher t))
15354 ((eq match nil) (setq matcher t))
15355 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15359 (cond ((eq scope 'tree)
15360 (org-back-to-heading t)
15361 (org-narrow-to-subtree)
15363 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15364 (org-region-active-p))
15365 ;; If needed, set start-level to a string like "2"
15368 (goto-char (region-beginning))
15369 (unless (org-at-heading-p) (outline-next-heading))
15370 (setq start-level (org-current-level))))
15371 (narrow-to-region (region-beginning)
15373 (goto-char (region-end))
15374 (unless (and (bolp) (org-at-heading-p))
15375 (outline-next-heading))
15381 (org-agenda-prepare-buffers
15382 (and buffer-file-name (list buffer-file-name)))
15385 func matcher org--matcher-tags-todo-only start-level)))
15386 ;; Get the right scope
15388 ((and scope (listp scope) (symbolp (car scope)))
15389 (setq scope (eval scope)))
15390 ((eq scope 'agenda)
15391 (setq scope (org-agenda-files t)))
15392 ((eq scope 'agenda-with-archives)
15393 (setq scope (org-agenda-files t))
15394 (setq scope (org-add-archive-files scope)))
15396 (setq scope (and buffer-file-name (list buffer-file-name))))
15397 ((eq scope 'file-with-archives)
15398 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15399 (org-agenda-prepare-buffers scope)
15400 (dolist (file scope)
15401 (with-current-buffer (org-find-base-buffer-visiting file)
15402 (org-with-wide-buffer
15403 (goto-char (point-min))
15408 func matcher org--matcher-tags-todo-only)))))))))
15413 (defconst org-special-properties
15414 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15415 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15416 "The special properties valid in Org mode.
15417 These are properties that are not defined in the property drawer,
15418 but in some other way.")
15420 (defconst org-default-properties
15421 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15422 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15423 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15424 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15425 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15426 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15427 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15428 "Some properties that are used by Org mode for various purposes.
15429 Being in this list makes sure that they are offered for completion.")
15431 (defun org--valid-property-p (property)
15432 "Non nil when string PROPERTY is a valid property name."
15434 (or (equal property "")
15435 (string-match-p "\\s-" property))))
15437 (defun org--update-property-plist (key val props)
15438 "Associate KEY to VAL in alist PROPS.
15439 Modifications are made by side-effect. Return new alist."
15440 (let* ((appending (string= (substring key -1) "+"))
15441 (key (if appending (substring key 0 -1) key))
15442 (old (assoc-string key props t)))
15443 (if (not old) (cons (cons key val) props)
15444 (setcdr old (if appending (concat (cdr old) " " val) val))
15447 (defun org-get-property-block (&optional beg force)
15448 "Return the (beg . end) range of the body of the property drawer.
15449 BEG is the beginning of the current subtree, or of the part
15450 before the first headline. If it is not given, it will be found.
15451 If the drawer does not exist, create it if FORCE is non-nil, or
15453 (org-with-wide-buffer
15454 (when beg (goto-char beg))
15455 (unless (org-before-first-heading-p)
15456 (let ((beg (cond (beg)
15457 ((or (not (featurep 'org-inlinetask))
15458 (org-inlinetask-in-task-p))
15459 (org-back-to-heading t))
15460 (t (org-with-limited-levels (org-back-to-heading t))))))
15462 (when (looking-at-p org-planning-line-re) (forward-line))
15463 (cond ((looking-at org-property-drawer-re)
15465 (cons (point) (progn (goto-char (match-end 0))
15466 (line-beginning-position))))
15469 (org-insert-property-drawer)
15470 (let ((pos (save-excursion (search-forward ":END:")
15471 (line-beginning-position))))
15472 (cons pos pos))))))))
15474 (defun org-at-property-p ()
15475 "Non-nil when point is inside a property drawer.
15476 See `org-property-re' for match data, if applicable."
15478 (beginning-of-line)
15479 (and (looking-at org-property-re)
15480 (let ((property-drawer (save-match-data (org-get-property-block))))
15481 (and property-drawer
15482 (>= (point) (car property-drawer))
15483 (< (point) (cdr property-drawer)))))))
15485 (defun org-property-action ()
15486 "Do an action on properties."
15488 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15489 (let ((c (read-char-exclusive)))
15491 (?s (call-interactively #'org-set-property))
15492 (?d (call-interactively #'org-delete-property))
15493 (?D (call-interactively #'org-delete-property-globally))
15494 (?c (call-interactively #'org-compute-property-at-point))
15495 (otherwise (user-error "No such property action %c" c)))))
15497 (defun org-inc-effort ()
15498 "Increment the value of the effort property in the current entry."
15500 (org-set-effort nil t))
15502 (defvar org-clock-effort) ; Defined in org-clock.el.
15503 (defvar org-clock-current-task) ; Defined in org-clock.el.
15504 (defun org-set-effort (&optional value increment)
15505 "Set the effort property of the current entry.
15506 With numerical prefix arg, use the nth allowed value, 0 stands for the
15507 10th allowed value.
15509 When INCREMENT is non-nil, set the property to the next allowed value."
15511 (when (equal value 0) (setq value 10))
15512 (let* ((completion-ignore-case t)
15513 (prop org-effort-property)
15514 (cur (org-entry-get nil prop))
15515 (allowed (org-property-get-allowed-values nil prop 'table))
15516 (existing (mapcar 'list (org-property-values prop)))
15517 (heading (nth 4 (org-heading-components)))
15520 ((stringp value) value)
15521 ((and allowed (integerp value))
15522 (or (car (nth (1- value) allowed))
15523 (car (org-last allowed))))
15524 ((and allowed increment)
15525 (or (cl-caadr (member (list cur) allowed))
15526 (user-error "Allowed effort values are not set")))
15528 (message "Select 1-9,0, [RET%s]: %s"
15529 (if cur (concat "=" cur) "")
15530 (mapconcat 'car allowed " "))
15531 (setq rpl (read-char-exclusive))
15532 (if (equal rpl ?\r)
15534 (setq rpl (- rpl ?0))
15535 (when (equal rpl 0) (setq rpl 10))
15536 (if (and (> rpl 0) (<= rpl (length allowed)))
15537 (car (nth (1- rpl) allowed))
15538 (org-completing-read "Effort: " allowed nil))))
15540 (org-completing-read
15541 (concat "Effort" (and cur (string-match "\\S-" cur)
15542 (concat " [" cur "]"))
15544 existing nil nil "" nil cur)))))
15545 (unless (equal (org-entry-get nil prop) val)
15546 (org-entry-put nil prop val))
15547 (org-refresh-property
15548 '((effort . identity)
15549 (effort-minutes . org-duration-to-minutes))
15551 (when (equal heading (bound-and-true-p org-clock-current-task))
15552 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15553 (org-clock-update-mode-line))
15554 (message "%s is now %s" prop val)))
15556 (defun org-entry-properties (&optional pom which)
15557 "Get all properties of the current entry.
15559 When POM is a buffer position, get all properties from the entry
15562 This includes the TODO keyword, the tags, time strings for
15563 deadline, scheduled, and clocking, and any additional properties
15564 defined in the entry.
15566 If WHICH is nil or `all', get all properties. If WHICH is
15567 `special' or `standard', only get that subclass. If WHICH is
15568 a string, only get that property.
15570 Return value is an alist. Keys are properties, as upcased
15572 (org-with-point-at pom
15573 (when (and (derived-mode-p 'org-mode)
15574 (ignore-errors (org-back-to-heading t)))
15576 (let* ((beg (point))
15577 (specific (and (stringp which) (upcase which)))
15578 (which (cond ((not specific) which)
15579 ((member specific org-special-properties) 'special)
15582 ;; Get the special properties, like TODO and TAGS.
15583 (when (memq which '(nil all special))
15584 (when (or (not specific) (string= specific "CLOCKSUM"))
15585 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15587 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15589 (when specific (throw 'exit props)))
15590 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15591 (let ((clocksumt (get-text-property (point)
15592 :org-clock-minutes-today)))
15594 (push (cons "CLOCKSUM_T"
15595 (org-duration-from-minutes clocksumt))
15597 (when specific (throw 'exit props)))
15598 (when (or (not specific) (string= specific "ITEM"))
15599 (let ((case-fold-search nil))
15600 (when (looking-at org-complex-heading-regexp)
15602 (let ((title (match-string-no-properties 4)))
15603 (if (org-string-nw-p title)
15604 (org-remove-tabs title)
15607 (when specific (throw 'exit props)))
15608 (when (or (not specific) (string= specific "TODO"))
15609 (let ((case-fold-search nil))
15610 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15611 (push (cons "TODO" (match-string-no-properties 2)) props)))
15612 (when specific (throw 'exit props)))
15613 (when (or (not specific) (string= specific "PRIORITY"))
15614 (push (cons "PRIORITY"
15615 (if (looking-at org-priority-regexp)
15616 (match-string-no-properties 2)
15617 (char-to-string org-default-priority)))
15619 (when specific (throw 'exit props)))
15620 (when (or (not specific) (string= specific "FILE"))
15621 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15623 (when specific (throw 'exit props)))
15624 (when (or (not specific) (string= specific "TAGS"))
15625 (let ((value (org-string-nw-p (org-get-tags-string))))
15626 (when value (push (cons "TAGS" value) props)))
15627 (when specific (throw 'exit props)))
15628 (when (or (not specific) (string= specific "ALLTAGS"))
15629 (let ((value (org-get-tags-at)))
15631 (push (cons "ALLTAGS"
15632 (format ":%s:" (mapconcat #'identity value ":")))
15634 (when specific (throw 'exit props)))
15635 (when (or (not specific) (string= specific "BLOCKED"))
15636 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15637 (when specific (throw 'exit props)))
15638 (when (or (not specific)
15639 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15641 (when (looking-at-p org-planning-line-re)
15643 (let ((bol (line-beginning-position))
15644 ;; Backward compatibility: time keywords used to
15645 ;; be configurable (before 8.3). Make sure we
15646 ;; get the correct keyword.
15647 (key-assoc `(("CLOSED" . ,org-closed-string)
15648 ("DEADLINE" . ,org-deadline-string)
15649 ("SCHEDULED" . ,org-scheduled-string))))
15650 (dolist (pair (if specific (list (assoc specific key-assoc))
15653 (when (search-backward (cdr pair) bol t)
15654 (goto-char (match-end 0))
15655 (skip-chars-forward " \t")
15656 (and (looking-at org-ts-regexp-both)
15657 (push (cons (car pair)
15658 (match-string-no-properties 0))
15660 (when specific (throw 'exit props)))
15661 (when (or (not specific)
15662 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15665 ;; Fix next time-stamp before END. TS is the
15666 ;; list of time-stamps found so far.
15669 ((string= specific "TIMESTAMP")
15671 ((string= specific "TIMESTAMP_IA")
15672 org-ts-regexp-inactive)
15673 ((assoc "TIMESTAMP_IA" ts)
15675 ((assoc "TIMESTAMP" ts)
15676 org-ts-regexp-inactive)
15677 (t org-ts-regexp-both))))
15679 (while (re-search-forward regexp end t)
15681 (let ((object (org-element-context)))
15682 ;; Accept to match timestamps in node
15683 ;; properties, too.
15684 (when (memq (org-element-type object)
15685 '(node-property timestamp))
15687 (org-element-property :type object)))
15689 ((and (memq type '(active active-range))
15690 (not (equal specific "TIMESTAMP_IA")))
15691 (unless (assoc "TIMESTAMP" ts)
15692 (push (cons "TIMESTAMP"
15693 (org-element-property
15694 :raw-value object))
15696 (when specific (throw 'exit ts))))
15697 ((and (memq type '(inactive inactive-range))
15698 (not (string= specific "TIMESTAMP")))
15699 (unless (assoc "TIMESTAMP_IA" ts)
15700 (push (cons "TIMESTAMP_IA"
15701 (org-element-property
15702 :raw-value object))
15704 (when specific (throw 'exit ts))))))
15705 ;; Both timestamp types are found,
15706 ;; move to next part.
15707 (when (= (length ts) 2) (throw 'next ts)))))
15710 ;; First look for timestamps within headline.
15711 (let ((ts (funcall find-ts (line-end-position) nil)))
15712 (if (= (length ts) 2) (setq props (nconc ts props))
15713 ;; Then find timestamps in the section, skipping
15715 (let ((end (save-excursion (outline-next-heading))))
15717 (when (looking-at-p org-planning-line-re) (forward-line))
15718 (setq props (nconc (funcall find-ts end ts) props))))))))
15719 ;; Get the standard properties, like :PROP:.
15720 (when (memq which '(nil all standard))
15721 ;; If we are looking after a specific property, delegate
15722 ;; to `org-entry-get', which is faster. However, make an
15723 ;; exception for "CATEGORY", since it can be also set
15724 ;; through keywords (i.e. #+CATEGORY).
15725 (if (and specific (not (equal specific "CATEGORY")))
15726 (let ((value (org-entry-get beg specific nil t)))
15727 (throw 'exit (and value (list (cons specific value)))))
15728 (let ((range (org-get-property-block beg)))
15730 (let ((end (cdr range)) seen-base)
15731 (goto-char (car range))
15732 ;; Unlike to `org--update-property-plist', we
15733 ;; handle the case where base values is found
15734 ;; after its extension. We also forbid standard
15735 ;; properties to be named as special properties.
15736 (while (re-search-forward org-property-re end t)
15737 (let* ((key (upcase (match-string-no-properties 2)))
15738 (extendp (string-match-p "\\+\\'" key))
15739 (key-base (if extendp (substring key 0 -1) key))
15740 (value (match-string-no-properties 3)))
15742 ((member-ignore-case key-base org-special-properties))
15745 (org--update-property-plist key value props)))
15746 ((member key seen-base))
15747 (t (push key seen-base)
15748 (let ((p (assoc-string key props t)))
15749 (if p (setcdr p (concat value " " (cdr p)))
15750 (push (cons key value) props))))))))))))
15751 (unless (assoc "CATEGORY" props)
15752 (push (cons "CATEGORY" (org-get-category beg)) props)
15753 (when (string= specific "CATEGORY") (throw 'exit props)))
15757 (defun org--property-local-values (property literal-nil)
15758 "Return value for PROPERTY in current entry.
15759 Value is a list whose car is the base value for PROPERTY and cdr
15760 a list of accumulated values. Return nil if neither is found in
15761 the entry. Also return nil when PROPERTY is set to \"nil\",
15762 unless LITERAL-NIL is non-nil."
15763 (let ((range (org-get-property-block)))
15765 (goto-char (car range))
15766 (let* ((case-fold-search t)
15771 (let ((v (and (re-search-forward
15772 (org-re-property property nil t) end t)
15773 (match-string-no-properties 3))))
15774 (list (if literal-nil v (org-not-nil v)))))))
15775 ;; Find additional values.
15776 (let* ((property+ (org-re-property (concat property "+") nil t)))
15777 (while (re-search-forward property+ end t)
15778 (push (match-string-no-properties 3) value)))
15779 ;; Return final values.
15780 (and (not (equal value '(nil))) (nreverse value))))))
15782 (defun org--property-global-value (property literal-nil)
15783 "Return value for PROPERTY in current buffer.
15784 Return value is a string. Return nil if property is not set
15785 globally. Also return nil when PROPERTY is set to \"nil\",
15786 unless LITERAL-NIL is non-nil."
15788 (cdr (or (assoc-string property org-file-properties t)
15789 (assoc-string property org-global-properties t)
15790 (assoc-string property org-global-properties-fixed t)))))
15791 (if literal-nil global (org-not-nil global))))
15793 (defun org-entry-get (pom property &optional inherit literal-nil)
15794 "Get value of PROPERTY for entry or content at point-or-marker POM.
15796 If INHERIT is non-nil and the entry does not have the property,
15797 then also check higher levels of the hierarchy. If INHERIT is
15798 the symbol `selective', use inheritance only if the setting in
15799 `org-use-property-inheritance' selects PROPERTY for inheritance.
15801 If the property is present but empty, the return value is the
15802 empty string. If the property is not present at all, nil is
15803 returned. In any other case, return the value as a string.
15804 Search is case-insensitive.
15806 If LITERAL-NIL is set, return the string value \"nil\" as
15807 a string, do not interpret it as the list atom nil. This is used
15808 for inheritance when a \"nil\" value can supersede a non-nil
15809 value higher up the hierarchy."
15810 (org-with-point-at pom
15812 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15813 ;; We need a special property. Use `org-entry-properties' to
15814 ;; retrieve it, but specify the wanted property.
15815 (cdr (assoc-string property (org-entry-properties nil property))))
15817 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15818 (org-entry-get-with-inheritance property literal-nil))
15820 (let* ((local (org--property-local-values property literal-nil))
15821 (value (and local (mapconcat #'identity (delq nil local) " "))))
15822 (if literal-nil value (org-not-nil value)))))))
15824 (defun org-property-or-variable-value (var &optional inherit)
15825 "Check if there is a property fixing the value of VAR.
15826 If yes, return this value. If not, return the current value of the variable."
15827 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15828 (if (and prop (stringp prop) (string-match "\\S-" prop))
15830 (symbol-value var))))
15832 (defun org-entry-delete (pom property)
15833 "Delete PROPERTY from entry at point-or-marker POM.
15834 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15835 non-nil when a property was removed."
15836 (org-with-point-at pom
15837 (pcase (org-get-property-block)
15838 (`(,begin . ,origin)
15839 (let* ((end (copy-marker origin))
15840 (re (org-re-property
15841 (concat (regexp-quote property) "\\+?") t t)))
15843 (while (re-search-forward re end t)
15844 (delete-region (match-beginning 0) (line-beginning-position 2)))
15845 ;; If drawer is empty, remove it altogether.
15846 (when (= begin end)
15847 (delete-region (line-beginning-position 0)
15848 (line-beginning-position 2)))
15849 ;; Return non-nil if some property was removed.
15850 (prog1 (/= end origin) (set-marker end nil))))
15853 ;; Multi-values properties are properties that contain multiple values
15854 ;; These values are assumed to be single words, separated by whitespace.
15855 (defun org-entry-add-to-multivalued-property (pom property value)
15856 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15857 (let* ((old (org-entry-get pom property))
15858 (values (and old (split-string old))))
15859 (setq value (org-entry-protect-space value))
15860 (unless (member value values)
15861 (setq values (append values (list value)))
15862 (org-entry-put pom property (mapconcat #'identity values " ")))))
15864 (defun org-entry-remove-from-multivalued-property (pom property value)
15865 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15866 (let* ((old (org-entry-get pom property))
15867 (values (and old (split-string old))))
15868 (setq value (org-entry-protect-space value))
15869 (when (member value values)
15870 (setq values (delete value values))
15871 (org-entry-put pom property (mapconcat #'identity values " ")))))
15873 (defun org-entry-member-in-multivalued-property (pom property value)
15874 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15875 (let* ((old (org-entry-get pom property))
15876 (values (and old (split-string old))))
15877 (setq value (org-entry-protect-space value))
15878 (member value values)))
15880 (defun org-entry-get-multivalued-property (pom property)
15881 "Return a list of values in a multivalued property."
15882 (let* ((value (org-entry-get pom property))
15883 (values (and value (split-string value))))
15884 (mapcar #'org-entry-restore-space values)))
15886 (defun org-entry-put-multivalued-property (pom property &rest values)
15887 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15888 VALUES should be a list of strings. Spaces will be protected."
15889 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15890 (let* ((value (org-entry-get pom property))
15891 (values (and value (split-string value))))
15892 (mapcar #'org-entry-restore-space values)))
15894 (defun org-entry-protect-space (s)
15895 "Protect spaces and newline in string S."
15896 (while (string-match " " s)
15897 (setq s (replace-match "%20" t t s)))
15898 (while (string-match "\n" s)
15899 (setq s (replace-match "%0A" t t s)))
15902 (defun org-entry-restore-space (s)
15903 "Restore spaces and newline in string S."
15904 (while (string-match "%20" s)
15905 (setq s (replace-match " " t t s)))
15906 (while (string-match "%0A" s)
15907 (setq s (replace-match "\n" t t s)))
15910 (defvar org-entry-property-inherited-from (make-marker)
15911 "Marker pointing to the entry from where a property was inherited.
15912 Each call to `org-entry-get-with-inheritance' will set this marker to the
15913 location of the entry where the inheritance search matched. If there was
15914 no match, the marker will point nowhere.
15915 Note that also `org-entry-get' calls this function, if the INHERIT flag
15918 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15919 "Get PROPERTY of entry or content at point, search higher levels if needed.
15920 The search will stop at the first ancestor which has the property defined.
15921 If the value found is \"nil\", return nil to show that the property
15922 should be considered as undefined (this is the meaning of nil here).
15923 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15924 (move-marker org-entry-property-inherited-from nil)
15925 (org-with-wide-buffer
15929 (let ((v (org--property-local-values property literal-nil)))
15932 (concat (mapconcat #'identity (delq nil v) " ")
15937 (org-back-to-heading t)
15938 (move-marker org-entry-property-inherited-from (point))
15940 ((org-up-heading-safe))
15942 (let ((global (org--property-global-value property literal-nil)))
15943 (cond ((not global))
15944 (value (setq value (concat global " " value)))
15945 (t (setq value global))))
15946 (throw 'exit nil))))))
15947 (if literal-nil value (org-not-nil value)))))
15949 (defvar org-property-changed-functions nil
15950 "Hook called when the value of a property has changed.
15951 Each hook function should accept two arguments, the name of the property
15952 and the new value.")
15954 (defun org-entry-put (pom property value)
15955 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15957 If the value is nil, it is converted to the empty string. If it
15958 is not a string, an error is raised. Also raise an error on
15959 invalid property names.
15961 PROPERTY can be any regular property (see
15962 `org-special-properties'). It can also be \"TODO\",
15963 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15965 For the last two properties, VALUE may have any of the special
15966 values \"earlier\" and \"later\". The function then increases or
15967 decreases scheduled or deadline date by one day."
15968 (cond ((null value) (setq value ""))
15969 ((not (stringp value)) (error "Properties values should be strings"))
15970 ((not (org--valid-property-p property))
15971 (user-error "Invalid property name: \"%s\"" property)))
15972 (org-with-point-at pom
15973 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15974 (org-back-to-heading t)
15975 (org-with-limited-levels (org-back-to-heading t)))
15976 (let ((beg (point)))
15978 ((equal property "TODO")
15979 (cond ((not (org-string-nw-p value)) (setq value 'none))
15980 ((not (member value org-todo-keywords-1))
15981 (user-error "\"%s\" is not a valid TODO state" value)))
15983 (org-set-tags nil 'align))
15984 ((equal property "PRIORITY")
15985 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15986 (org-set-tags nil 'align))
15987 ((equal property "SCHEDULED")
15989 (if (and (looking-at-p org-planning-line-re)
15991 org-scheduled-time-regexp (line-end-position) t))
15992 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15993 ((string= value "later") (org-timestamp-change 1 'day))
15994 ((string= value "") (org-schedule '(4)))
15995 (t (org-schedule nil value)))
15996 (if (member value '("earlier" "later" ""))
15997 (call-interactively #'org-schedule)
15998 (org-schedule nil value))))
15999 ((equal property "DEADLINE")
16001 (if (and (looking-at-p org-planning-line-re)
16003 org-deadline-time-regexp (line-end-position) t))
16004 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16005 ((string= value "later") (org-timestamp-change 1 'day))
16006 ((string= value "") (org-deadline '(4)))
16007 (t (org-deadline nil value)))
16008 (if (member value '("earlier" "later" ""))
16009 (call-interactively #'org-deadline)
16010 (org-deadline nil value))))
16011 ((member property org-special-properties)
16012 (error "The %s property cannot be set with `org-entry-put'" property))
16014 (let* ((range (org-get-property-block beg 'force))
16016 (case-fold-search t))
16017 (goto-char (car range))
16018 (if (re-search-forward (org-re-property property nil t) end t)
16019 (progn (delete-region (match-beginning 0) (match-end 0))
16020 (goto-char (match-beginning 0)))
16024 (insert ":" property ":")
16025 (when value (insert " " value))
16026 (org-indent-line)))))
16027 (run-hook-with-args 'org-property-changed-functions property value)))
16029 (defun org-buffer-property-keys
16030 (&optional specials defaults columns ignore-malformed)
16031 "Get all property keys in the current buffer.
16033 When SPECIALS is non-nil, also list the special properties that
16034 reflect things like tags and TODO state.
16036 When DEFAULTS is non-nil, also include properties that has
16037 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16038 DESCRIPTION, LOCATION, and LOGGING and others.
16040 When COLUMNS in non-nil, also include property names given in
16041 COLUMN formats in the current buffer.
16043 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16044 automatically performed, such drawers will be silently ignored."
16045 (let ((case-fold-search t)
16047 (and specials org-special-properties)
16048 (and defaults (cons org-effort-property org-default-properties))
16050 (org-with-wide-buffer
16051 (goto-char (point-min))
16052 (while (re-search-forward org-property-start-re nil t)
16053 (let ((range (org-get-property-block)))
16056 (when (and (not ignore-malformed)
16057 (not (org-before-first-heading-p))
16058 (y-or-n-p (format "Malformed drawer at %d, repair?"
16059 (line-beginning-position))))
16060 (org-get-property-block nil t))
16062 (goto-char (car range))
16063 (let ((begin (car range))
16065 ;; Make sure that found property block is not located
16066 ;; before current point, as it would generate an infloop.
16067 ;; It can happen, for example, in the following
16074 ;; *************** Inlinetask
16079 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16080 (while (< (point) end)
16081 (let ((p (progn (looking-at org-property-re)
16082 (match-string-no-properties 2))))
16083 ;; Only add true property name, not extension symbol.
16084 (push (if (not (string-match-p "\\+\\'" p)) p
16085 (substring p 0 -1))
16088 (outline-next-heading)))
16090 (goto-char (point-min))
16091 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16092 (let ((element (org-element-at-point)))
16093 (when (memq (org-element-type element) '(keyword node-property))
16094 (let ((value (org-element-property :value element))
16096 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
16099 (setq start (match-end 0))
16100 (let ((p (match-string-no-properties 1 value)))
16101 (unless (member-ignore-case p org-special-properties)
16102 (push p props))))))))))
16103 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16105 (defun org-property-values (key)
16106 "List all non-nil values of property KEY in current buffer."
16107 (org-with-wide-buffer
16108 (goto-char (point-min))
16109 (let ((case-fold-search t)
16110 (re (org-re-property key))
16112 (while (re-search-forward re nil t)
16113 (push (org-entry-get (point) key) values))
16114 (delete-dups values))))
16116 (defun org-insert-property-drawer ()
16117 "Insert a property drawer into the current entry."
16118 (org-with-wide-buffer
16119 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16120 (org-back-to-heading t)
16121 (org-with-limited-levels (org-back-to-heading t)))
16123 (when (looking-at-p org-planning-line-re) (forward-line))
16124 (unless (looking-at-p org-property-drawer-re)
16125 ;; Make sure we start editing a line from current entry, not from
16126 ;; next one. It prevents extending text properties or overlays
16127 ;; belonging to the latter.
16128 (when (bolp) (backward-char))
16129 (let ((begin (1+ (point)))
16130 (inhibit-read-only t))
16131 (insert "\n:PROPERTIES:\n:END:")
16132 (when (eobp) (insert "\n"))
16133 (org-indent-region begin (point))))))
16135 (defun org-insert-drawer (&optional arg drawer)
16136 "Insert a drawer at point.
16138 When optional argument ARG is non-nil, insert a property drawer.
16140 Optional argument DRAWER, when non-nil, is a string representing
16141 drawer's name. Otherwise, the user is prompted for a name.
16143 If a region is active, insert the drawer around that region
16146 Point is left between drawer's boundaries."
16148 (let* ((drawer (if arg "PROPERTIES"
16149 (or drawer (read-from-minibuffer "Drawer: ")))))
16151 ;; With C-u, fall back on `org-insert-property-drawer'
16152 (arg (org-insert-property-drawer))
16153 ;; Check validity of suggested drawer's name.
16154 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16155 (user-error "Invalid drawer name"))
16156 ;; With an active region, insert a drawer at point.
16157 ((not (org-region-active-p))
16159 (unless (bolp) (insert "\n"))
16160 (insert (format ":%s:\n\n:END:\n" drawer))
16161 (forward-line -2)))
16162 ;; Otherwise, insert the drawer at point
16164 (let ((rbeg (region-beginning))
16165 (rend (copy-marker (region-end))))
16169 (beginning-of-line)
16170 (when (save-excursion
16171 (re-search-forward org-outline-regexp-bol rend t))
16172 (user-error "Drawers cannot contain headlines"))
16173 ;; Position point at the beginning of the first
16174 ;; non-blank line in region. Insert drawer's opening
16175 ;; there, then indent it.
16176 (org-skip-whitespace)
16177 (beginning-of-line)
16178 (insert ":" drawer ":\n")
16180 (indent-for-tab-command)
16181 ;; Move point to the beginning of the first blank line
16182 ;; after the last non-blank line in region. Insert
16183 ;; drawer's closing, then indent it.
16185 (skip-chars-backward " \r\t\n")
16187 (deactivate-mark t)
16188 (indent-for-tab-command)
16189 (unless (eolp) (insert "\n")))
16190 ;; Clear marker, whatever the outcome of insertion is.
16191 (set-marker rend nil)))))))
16193 (defvar org-property-set-functions-alist nil
16194 "Property set function alist.
16195 Each entry should have the following format:
16197 (PROPERTY . READ-FUNCTION)
16199 The read function will be called with the same argument as
16200 `org-completing-read'.")
16202 (defun org-set-property-function (property)
16203 "Get the function that should be used to set PROPERTY.
16204 This is computed according to `org-property-set-functions-alist'."
16205 (or (cdr (assoc property org-property-set-functions-alist))
16206 'org-completing-read))
16208 (defun org-read-property-value (property)
16209 "Read PROPERTY value from user."
16210 (let* ((completion-ignore-case t)
16211 (allowed (org-property-get-allowed-values nil property 'table))
16212 (cur (org-entry-get nil property))
16213 (prompt (concat property " value"
16214 (if (and cur (string-match "\\S-" cur))
16215 (concat " [" cur "]") "") ": "))
16216 (set-function (org-set-property-function property))
16218 (funcall set-function prompt allowed nil
16219 (not (get-text-property 0 'org-unrestricted
16221 (funcall set-function prompt
16222 (mapcar 'list (org-property-values property))
16223 nil nil "" nil cur))))
16226 (defvar org-last-set-property nil)
16227 (defvar org-last-set-property-value nil)
16228 (defun org-read-property-name ()
16229 "Read a property name."
16230 (let ((completion-ignore-case t)
16231 (default-prop (or (and (org-at-property-p)
16232 (match-string-no-properties 2))
16233 org-last-set-property)))
16234 (org-completing-read
16236 (if default-prop (concat " [" default-prop "]") "")
16238 (mapcar #'list (org-buffer-property-keys nil t t))
16239 nil nil nil nil default-prop)))
16241 (defun org-set-property-and-value (use-last)
16242 "Allow to set [PROPERTY]: [value] direction from prompt.
16243 When use-default, don't even ask, just use the last
16244 \"[PROPERTY]: [value]\" string from the history."
16246 (let* ((completion-ignore-case t)
16247 (pv (or (and use-last org-last-set-property-value)
16248 (org-completing-read
16249 "Enter a \"[Property]: [value]\" pair: "
16250 nil nil nil nil nil
16251 org-last-set-property-value)))
16253 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16254 (setq prop (match-string 1 pv)
16255 val (match-string 2 pv))
16256 (org-set-property prop val))))
16258 (defun org-set-property (property value)
16259 "In the current entry, set PROPERTY to VALUE.
16261 When called interactively, this will prompt for a property name, offering
16262 completion on existing and default properties. And then it will prompt
16263 for a value, offering completion either on allowed values (via an inherited
16264 xxx_ALL property) or on existing values in other instances of this property
16265 in the current file.
16267 Throw an error when trying to set a property with an invalid name."
16268 (interactive (list nil nil))
16269 (let ((property (or property (org-read-property-name))))
16270 ;; `org-entry-put' also makes the following check, but this one
16271 ;; avoids polluting `org-last-set-property' and
16272 ;; `org-last-set-property-value' needlessly.
16273 (unless (org--valid-property-p property)
16274 (user-error "Invalid property name: \"%s\"" property))
16275 (let ((value (or value (org-read-property-value property)))
16276 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16277 (setq org-last-set-property property)
16278 (setq org-last-set-property-value (concat property ": " value))
16279 ;; Possibly postprocess the inserted value:
16280 (when fn (setq value (funcall fn value)))
16281 (unless (equal (org-entry-get nil property) value)
16282 (org-entry-put nil property value)))))
16284 (defun org-find-property (property &optional value)
16285 "Find first entry in buffer that sets PROPERTY.
16287 When optional argument VALUE is non-nil, only consider an entry
16288 if it contains PROPERTY set to this value. If PROPERTY should be
16289 explicitly set to nil, use string \"nil\" for VALUE.
16291 Return position where the entry begins, or nil if there is no
16292 such entry. If narrowing is in effect, only search the visible
16293 part of the buffer."
16295 (goto-char (point-min))
16296 (let ((case-fold-search t)
16297 (re (org-re-property property nil (not value) value)))
16299 (while (re-search-forward re nil t)
16300 (when (if value (org-at-property-p)
16301 (org-entry-get (point) property nil t))
16302 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16304 (defun org-delete-property (property)
16305 "In the current entry, delete PROPERTY."
16307 (let* ((completion-ignore-case t)
16308 (cat (org-entry-get (point) "CATEGORY"))
16309 (props0 (org-entry-properties nil 'standard))
16310 (props (if cat props0
16311 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16312 (prop (if (< 1 (length props))
16313 (completing-read "Property: " props nil t)
16317 (message "No property to delete in this entry")
16318 (org-entry-delete nil property)
16319 (message "Property \"%s\" deleted" property)))
16321 (defun org-delete-property-globally (property)
16322 "Remove PROPERTY globally, from all entries.
16323 This function ignores narrowing, if any."
16325 (let* ((completion-ignore-case t)
16326 (prop (completing-read
16327 "Globally remove property: "
16328 (mapcar #'list (org-buffer-property-keys)))))
16330 (org-with-wide-buffer
16331 (goto-char (point-min))
16333 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16334 (while (re-search-forward re nil t)
16335 (when (org-entry-delete (point) property) (cl-incf count)))
16336 (message "Property \"%s\" removed from %d entries" property count))))
16338 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16340 (defun org-compute-property-at-point ()
16341 "Compute the property at point.
16342 This looks for an enclosing column format, extracts the operator and
16343 then applies it to the property in the column format's scope."
16345 (unless (org-at-property-p)
16346 (user-error "Not at a property"))
16347 (let ((prop (match-string-no-properties 2)))
16348 (org-columns-get-format-and-top-level)
16349 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16350 (user-error "No operator defined for property %s" prop))
16351 (org-columns-compute prop)))
16353 (defvar org-property-allowed-value-functions nil
16354 "Hook for functions supplying allowed values for a specific property.
16355 The functions must take a single argument, the name of the property, and
16356 return a flat list of allowed values. If \":ETC\" is one of
16357 the values, this means that these values are intended as defaults for
16358 completion, but that other values should be allowed too.
16359 The functions must return nil if they are not responsible for this
16362 (defun org-property-get-allowed-values (pom property &optional table)
16363 "Get allowed values for the property PROPERTY.
16364 When TABLE is non-nil, return an alist that can directly be used for
16368 ((equal property "TODO")
16369 (setq vals (org-with-point-at pom
16370 (append org-todo-keywords-1 '("")))))
16371 ((equal property "PRIORITY")
16372 (let ((n org-lowest-priority))
16373 (while (>= n org-highest-priority)
16374 (push (char-to-string n) vals)
16376 ((equal property "CATEGORY"))
16377 ((member property org-special-properties))
16378 ((setq vals (run-hook-with-args-until-success
16379 'org-property-allowed-value-functions property)))
16381 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16382 (when (and vals (string-match "\\S-" vals))
16383 (setq vals (car (read-from-string (concat "(" vals ")"))))
16384 (setq vals (mapcar (lambda (x)
16385 (cond ((stringp x) x)
16386 ((numberp x) (number-to-string x))
16387 ((symbolp x) (symbol-name x))
16390 (when (member ":ETC" vals)
16391 (setq vals (remove ":ETC" vals))
16392 (org-add-props (car vals) '(org-unrestricted t)))
16393 (if table (mapcar 'list vals) vals)))
16395 (defun org-property-previous-allowed-value (&optional _previous)
16396 "Switch to the next allowed value for this property."
16398 (org-property-next-allowed-value t))
16400 (defun org-property-next-allowed-value (&optional previous)
16401 "Switch to the next allowed value for this property."
16403 (unless (org-at-property-p)
16404 (user-error "Not at a property"))
16405 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16406 (key (match-string 2))
16407 (value (match-string 3))
16408 (allowed (or (org-property-get-allowed-values (point) key)
16409 (and (member value '("[ ]" "[-]" "[X]"))
16411 (heading (save-match-data (nth 4 (org-heading-components))))
16414 (user-error "Allowed values for this property have not been defined"))
16415 (when previous (setq allowed (reverse allowed)))
16416 (when (member value allowed)
16417 (setq nval (car (cdr (member value allowed)))))
16418 (setq nval (or nval (car allowed)))
16419 (when (equal nval value)
16420 (user-error "Only one allowed value for this property"))
16421 (org-at-property-p)
16422 (replace-match (concat " :" key ": " nval) t t)
16424 (beginning-of-line 1)
16425 (skip-chars-forward " \t")
16426 (when (equal prop org-effort-property)
16427 (org-refresh-property
16428 '((effort . identity)
16429 (effort-minutes . org-duration-to-minutes))
16431 (when (string= org-clock-current-task heading)
16432 (setq org-clock-effort nval)
16433 (org-clock-update-mode-line)))
16434 (run-hook-with-args 'org-property-changed-functions key nval)))
16436 (defun org-find-olp (path &optional this-buffer)
16437 "Return a marker pointing to the entry at outline path OLP.
16438 If anything goes wrong, throw an error.
16439 You can wrap this call to catch the error like this:
16441 (condition-case msg
16442 (org-mobile-locate-entry (match-string 4))
16443 (error (nth 1 msg)))
16445 The return value will then be either a string with the error message,
16446 or a marker if everything is OK.
16448 If THIS-BUFFER is set, the outline path does not contain a file,
16450 (let* ((file (if this-buffer buffer-file-name (pop path)))
16451 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16456 (unless buffer (error "File not found :%s" file))
16457 (with-current-buffer buffer
16458 (unless (derived-mode-p 'org-mode)
16459 (error "Buffer %s needs to be in Org mode" buffer))
16460 (org-with-wide-buffer
16461 (goto-char (point-min))
16462 (dolist (heading path)
16463 (let ((re (format org-complex-heading-regexp-format
16464 (regexp-quote heading)))
16466 (while (re-search-forward re end t)
16467 (setq level (- (match-end 1) (match-beginning 1)))
16468 (when (and (>= level lmin) (<= level lmax))
16469 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16471 (error "Heading not found on level %d: %s" lmax heading))
16473 (error "Heading not unique on level %d: %s" lmax heading))
16475 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16476 (setq end (save-excursion (org-end-of-subtree t t)))))
16477 (when (org-at-heading-p)
16478 (point-marker))))))
16480 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16481 "Find node HEADING in BUFFER.
16482 Return a marker to the heading if it was found, or nil if not.
16483 If POS-ONLY is set, return just the position instead of a marker.
16485 The heading text must match exact, but it may have a TODO keyword,
16486 a priority cookie and tags in the standard locations."
16487 (with-current-buffer (or buffer (current-buffer))
16488 (org-with-wide-buffer
16489 (goto-char (point-min))
16490 (let (case-fold-search)
16491 (when (re-search-forward
16492 (format org-complex-heading-regexp-format
16493 (regexp-quote heading)) nil t)
16495 (match-beginning 0)
16496 (move-marker (make-marker) (match-beginning 0))))))))
16498 (defun org-find-exact-heading-in-directory (heading &optional dir)
16499 "Find Org node headline HEADING in all .org files in directory DIR.
16500 When the target headline is found, return a marker to this location."
16501 (let ((files (directory-files (or dir default-directory)
16502 t "\\`[^.#].*\\.org\\'"))
16505 (dolist (file files)
16506 (message "trying %s" file)
16507 (setq visiting (org-find-base-buffer-visiting file))
16508 (setq buffer (or visiting (find-file-noselect file)))
16509 (setq m (org-find-exact-headline-in-buffer
16511 (when (and (not m) (not visiting)) (kill-buffer buffer))
16512 (and m (throw 'found m))))))
16514 (defun org-find-entry-with-id (ident)
16515 "Locate the entry that contains the ID property with exact value IDENT.
16516 IDENT can be a string, a symbol or a number, this function will search for
16517 the string representation of it.
16518 Return the position where this entry starts, or nil if there is no such entry."
16519 (interactive "sID: ")
16521 ((stringp ident) ident)
16522 ((symbolp ident) (symbol-name ident))
16523 ((numberp ident) (number-to-string ident))
16524 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16525 (org-with-wide-buffer (org-find-property "ID" id))))
16529 (defvar org-last-changed-timestamp nil)
16530 (defvar org-last-inserted-timestamp nil
16531 "The last time stamp inserted with `org-insert-time-stamp'.")
16533 (defun org-time-stamp (arg &optional inactive)
16534 "Prompt for a date/time and insert a time stamp.
16536 If the user specifies a time like HH:MM or if this command is
16537 called with at least one prefix argument, the time stamp contains
16538 the date and the time. Otherwise, only the date is included.
16540 All parts of a date not specified by the user are filled in from
16541 the timestamp at point, if any, or the current date/time
16544 If there is already a timestamp at the cursor, it is replaced.
16546 With two universal prefix arguments, insert an active timestamp
16547 with the current time without prompting the user.
16549 When called from lisp, the timestamp is inactive if INACTIVE is
16553 ((org-at-date-range-p t)
16554 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16555 ((org-at-timestamp-p 'lax) (match-string 0))))
16556 ;; Default time is either the timestamp at point or today.
16557 ;; When entering a range, only the range start is considered.
16558 (default-time (if (not ts) (current-time)
16559 (apply #'encode-time (org-parse-time-string ts))))
16560 (default-input (and ts (org-get-compact-tod ts)))
16562 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16563 (match-string 0 ts)))
16565 org-end-time-was-given
16567 (and (if (equal arg '(16)) (current-time)
16568 ;; Preserve `this-command' and `last-command'.
16569 (let ((this-command this-command)
16570 (last-command last-command))
16572 arg 'totime nil nil default-time default-input
16576 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16577 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16579 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16581 ;; Make sure we're on a timestamp. When in the middle of a date
16582 ;; range, move arbitrarily to range end.
16583 (unless (org-at-timestamp-p 'lax)
16584 (skip-chars-forward "-")
16585 (org-at-timestamp-p 'lax))
16587 (setq org-last-changed-timestamp
16588 (org-insert-time-stamp
16589 time (or org-time-was-given arg)
16590 inactive nil nil (list org-end-time-was-given)))
16593 (insert " " repeater)
16594 (setq org-last-changed-timestamp
16595 (concat (substring org-last-inserted-timestamp 0 -1)
16596 " " repeater ">")))
16597 (message "Timestamp updated"))
16598 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16599 (t (org-insert-time-stamp
16600 time (or org-time-was-given arg) inactive nil nil
16601 (list org-end-time-was-given))))))
16603 ;; FIXME: can we use this for something else, like computing time differences?
16604 (defun org-get-compact-tod (s)
16605 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16606 (let* ((t1 (match-string 1 s))
16607 (h1 (string-to-number (match-string 2 s)))
16608 (m1 (string-to-number (match-string 3 s)))
16609 (t2 (and (match-end 4) (match-string 5 s)))
16610 (h2 (and t2 (string-to-number (match-string 6 s))))
16611 (m2 (and t2 (string-to-number (match-string 7 s))))
16615 (setq dh (- h2 h1) dm (- m2 m1))
16616 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16617 (concat t1 "+" (number-to-string dh)
16618 (and (/= 0 dm) (format ":%02d" dm)))))))
16620 (defun org-time-stamp-inactive (&optional arg)
16621 "Insert an inactive time stamp.
16622 An inactive time stamp is enclosed in square brackets instead of angle
16623 brackets. It is inactive in the sense that it does not trigger agenda entries,
16624 does not link to the calendar and cannot be changed with the S-cursor keys.
16625 So these are more for recording a certain time/date."
16627 (org-time-stamp arg 'inactive))
16629 (defvar org-date-ovl (make-overlay 1 1))
16630 (overlay-put org-date-ovl 'face 'org-date-selected)
16631 (delete-overlay org-date-ovl)
16633 (defvar org-ans1) ; dynamically scoped parameter
16634 (defvar org-ans2) ; dynamically scoped parameter
16636 (defvar org-plain-time-of-day-regexp) ; defined below
16638 (defvar org-overriding-default-time nil) ; dynamically scoped
16639 (defvar org-read-date-overlay nil)
16640 (defvar org-dcst nil) ; dynamically scoped
16641 (defvar org-read-date-history nil)
16642 (defvar org-read-date-final-answer nil)
16643 (defvar org-read-date-analyze-futurep nil)
16644 (defvar org-read-date-analyze-forced-year nil)
16645 (defvar org-read-date-inactive)
16647 (defvar org-read-date-minibuffer-local-map
16648 (let* ((map (make-sparse-keymap)))
16649 (set-keymap-parent map minibuffer-local-map)
16650 (org-defkey map (kbd ".")
16651 (lambda () (interactive)
16652 ;; Are we at the beginning of the prompt?
16653 (if (looking-back "^[^:]+: "
16654 (let ((inhibit-field-text-motion t))
16655 (line-beginning-position)))
16656 (org-eval-in-calendar '(calendar-goto-today))
16658 (org-defkey map (kbd "C-.")
16659 (lambda () (interactive)
16660 (org-eval-in-calendar '(calendar-goto-today))))
16661 (org-defkey map [(meta shift left)]
16662 (lambda () (interactive)
16663 (org-eval-in-calendar '(calendar-backward-month 1))))
16664 (org-defkey map [(meta shift right)]
16665 (lambda () (interactive)
16666 (org-eval-in-calendar '(calendar-forward-month 1))))
16667 (org-defkey map [(meta shift up)]
16668 (lambda () (interactive)
16669 (org-eval-in-calendar '(calendar-backward-year 1))))
16670 (org-defkey map [(meta shift down)]
16671 (lambda () (interactive)
16672 (org-eval-in-calendar '(calendar-forward-year 1))))
16673 (org-defkey map [?\e (shift left)]
16674 (lambda () (interactive)
16675 (org-eval-in-calendar '(calendar-backward-month 1))))
16676 (org-defkey map [?\e (shift right)]
16677 (lambda () (interactive)
16678 (org-eval-in-calendar '(calendar-forward-month 1))))
16679 (org-defkey map [?\e (shift up)]
16680 (lambda () (interactive)
16681 (org-eval-in-calendar '(calendar-backward-year 1))))
16682 (org-defkey map [?\e (shift down)]
16683 (lambda () (interactive)
16684 (org-eval-in-calendar '(calendar-forward-year 1))))
16685 (org-defkey map [(shift up)]
16686 (lambda () (interactive)
16687 (org-eval-in-calendar '(calendar-backward-week 1))))
16688 (org-defkey map [(shift down)]
16689 (lambda () (interactive)
16690 (org-eval-in-calendar '(calendar-forward-week 1))))
16691 (org-defkey map [(shift left)]
16692 (lambda () (interactive)
16693 (org-eval-in-calendar '(calendar-backward-day 1))))
16694 (org-defkey map [(shift right)]
16695 (lambda () (interactive)
16696 (org-eval-in-calendar '(calendar-forward-day 1))))
16697 (org-defkey map "!"
16698 (lambda () (interactive)
16699 (org-eval-in-calendar '(diary-view-entries))
16701 (org-defkey map ">"
16702 (lambda () (interactive)
16703 (org-eval-in-calendar '(calendar-scroll-left 1))))
16704 (org-defkey map "<"
16705 (lambda () (interactive)
16706 (org-eval-in-calendar '(calendar-scroll-right 1))))
16707 (org-defkey map "\C-v"
16708 (lambda () (interactive)
16709 (org-eval-in-calendar
16710 '(calendar-scroll-left-three-months 1))))
16711 (org-defkey map "\M-v"
16712 (lambda () (interactive)
16713 (org-eval-in-calendar
16714 '(calendar-scroll-right-three-months 1))))
16716 "Keymap for minibuffer commands when using `org-read-date'.")
16719 (defvar org-defdecode)
16720 (defvar org-with-time)
16722 (defvar calendar-setup) ; Dynamically scoped.
16723 (defun org-read-date (&optional with-time to-time from-string prompt
16724 default-time default-input inactive)
16725 "Read a date, possibly a time, and make things smooth for the user.
16726 The prompt will suggest to enter an ISO date, but you can also enter anything
16727 which will at least partially be understood by `parse-time-string'.
16728 Unrecognized parts of the date will default to the current day, month, year,
16729 hour and minute. If this command is called to replace a timestamp at point,
16730 or to enter the second timestamp of a range, the default time is taken
16731 from the existing stamp. Furthermore, the command prefers the future,
16732 so if you are giving a date where the year is not given, and the day-month
16733 combination is already past in the current year, it will assume you
16734 mean next year. For details, see the manual. A few examples:
16736 3-2-5 --> 2003-02-05
16737 feb 15 --> currentyear-02-15
16738 2/15 --> currentyear-02-15
16739 sep 12 9 --> 2009-09-12
16740 12:45 --> today 12:45
16741 22 sept 0:34 --> currentyear-09-22 0:34
16742 12 --> currentyear-currentmonth-12
16743 Fri --> nearest Friday after today
16744 -Tue --> last Tuesday
16747 Furthermore you can specify a relative date by giving, as the *first* thing
16748 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16749 change in days weeks, months, years.
16750 With a single plus or minus, the date is relative to today. With a double
16751 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16752 +4d --> four days from today
16753 +4 --> same as above
16754 +2w --> two weeks from today
16755 ++5 --> five days from default date
16757 The function understands only English month and weekday abbreviations.
16759 While prompting, a calendar is popped up - you can also select the
16760 date with the mouse (button 1). The calendar shows a period of three
16761 months. To scroll it to other months, use the keys `>' and `<'.
16762 If you don't like the calendar, turn it off with
16763 (setq org-read-date-popup-calendar nil)
16765 With optional argument TO-TIME, the date will immediately be converted
16766 to an internal time.
16767 With an optional argument WITH-TIME, the prompt will suggest to
16768 also insert a time. Note that when WITH-TIME is not set, you can
16769 still enter a time, and this function will inform the calling routine
16770 about this change. The calling routine may then choose to change the
16771 format used to insert the time stamp into the buffer to include the time.
16772 With optional argument FROM-STRING, read from this string instead from
16773 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16774 the time/date that is used for everything that is not specified by the
16776 (require 'parse-time)
16777 (let* ((org-with-time with-time)
16778 (org-time-stamp-rounding-minutes
16779 (if (equal org-with-time '(16))
16781 org-time-stamp-rounding-minutes))
16782 (org-dcst org-display-custom-times)
16783 (ct (org-current-time))
16784 (org-def (or org-overriding-default-time default-time ct))
16785 (org-defdecode (decode-time org-def))
16786 (cur-frame (selected-frame))
16787 (mouse-autoselect-window nil) ; Don't let the mouse jump
16789 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16790 (calendar-move-hook nil)
16791 (calendar-view-diary-initially-flag nil)
16792 (calendar-view-holidays-initially-flag nil)
16793 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16794 ;; Rationalize `org-def' and `org-defdecode', if required.
16795 (when (< (nth 2 org-defdecode) org-extend-today-until)
16796 (setf (nth 2 org-defdecode) -1)
16797 (setf (nth 1 org-defdecode) 59)
16798 (setq org-def (apply #'encode-time org-defdecode))
16799 (setq org-defdecode (decode-time org-def)))
16800 (let* ((timestr (format-time-string
16801 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16803 (prompt (concat (if prompt (concat prompt " ") "")
16804 (format "Date+time [%s]: " timestr))))
16806 (from-string (setq ans from-string))
16807 (org-read-date-popup-calendar
16809 (save-window-excursion
16811 (when (eq calendar-setup 'calendar-only)
16813 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16814 (select-frame cal-frame))
16815 (org-eval-in-calendar '(setq cursor-type nil) t)
16818 (calendar-forward-day (- (time-to-days org-def)
16819 (calendar-absolute-from-gregorian
16820 (calendar-current-date))))
16821 (org-eval-in-calendar nil t)
16822 (let* ((old-map (current-local-map))
16823 (map (copy-keymap calendar-mode-map))
16824 (minibuffer-local-map
16825 (copy-keymap org-read-date-minibuffer-local-map)))
16826 (org-defkey map (kbd "RET") 'org-calendar-select)
16827 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16828 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16831 (use-local-map map)
16832 (setq org-read-date-inactive inactive)
16833 (add-hook 'post-command-hook 'org-read-date-display)
16835 (read-string prompt
16837 'org-read-date-history
16839 ;; org-ans0: from prompt
16840 ;; org-ans1: from mouse click
16841 ;; org-ans2: from calendar motion
16843 (concat org-ans0 " " (or org-ans1 org-ans2))))
16844 (remove-hook 'post-command-hook 'org-read-date-display)
16845 (use-local-map old-map)
16846 (when org-read-date-overlay
16847 (delete-overlay org-read-date-overlay)
16848 (setq org-read-date-overlay nil)))))
16849 (bury-buffer "*Calendar*")
16851 (delete-frame cal-frame)
16852 (select-frame-set-input-focus cur-frame))))))
16854 (t ; Naked prompt only
16856 (setq ans (read-string prompt default-input
16857 'org-read-date-history timestr))
16858 (when org-read-date-overlay
16859 (delete-overlay org-read-date-overlay)
16860 (setq org-read-date-overlay nil))))))
16862 (setq final (org-read-date-analyze ans org-def org-defdecode))
16864 (when org-read-date-analyze-forced-year
16865 (message "Year was forced into %s"
16866 (if org-read-date-force-compatible-dates
16867 "compatible range (1970-2037)"
16868 "range representable on this machine"))
16871 ;; One round trip to get rid of 34th of August and stuff like that....
16872 (setq final (decode-time (apply 'encode-time final)))
16874 (setq org-read-date-final-answer ans)
16877 (apply 'encode-time final)
16878 (if (and (boundp 'org-time-was-given) org-time-was-given)
16879 (format "%04d-%02d-%02d %02d:%02d"
16880 (nth 5 final) (nth 4 final) (nth 3 final)
16881 (nth 2 final) (nth 1 final))
16882 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16884 (defun org-read-date-display ()
16885 "Display the current date prompt interpretation in the minibuffer."
16886 (when org-read-date-display-live
16887 (when org-read-date-overlay
16888 (delete-overlay org-read-date-overlay))
16889 (when (minibufferp (current-buffer))
16892 (while (not (equal (buffer-substring
16893 (max (point-min) (- (point) 4)) (point))
16896 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16897 " " (or org-ans1 org-ans2)))
16898 (org-end-time-was-given nil)
16899 (f (org-read-date-analyze ans org-def org-defdecode))
16901 org-time-stamp-custom-formats
16902 org-time-stamp-formats))
16903 (fmt (if (or org-with-time
16904 (and (boundp 'org-time-was-given) org-time-was-given))
16907 (txt (format-time-string fmt (apply 'encode-time f)))
16908 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16909 (txt (concat "=> " txt)))
16910 (when (and org-end-time-was-given
16911 (string-match org-plain-time-of-day-regexp txt))
16912 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16913 org-end-time-was-given
16914 (substring txt (match-end 0)))))
16915 (when org-read-date-analyze-futurep
16916 (setq txt (concat txt " (=>F)")))
16917 (setq org-read-date-overlay
16918 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16919 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16921 (defun org-read-date-analyze (ans def defdecode)
16922 "Analyze the combined answer of the date prompt."
16923 ;; FIXME: cleanup and comment
16924 ;; Pass `current-time' result to `decode-time' (instead of calling
16925 ;; without arguments) so that only `current-time' has to be
16926 ;; overridden in tests.
16927 (let ((org-def def)
16928 (org-defdecode defdecode)
16929 (nowdecode (decode-time (current-time)))
16930 delta deltan deltaw deltadef year month day
16931 hour minute second wday pm h2 m2 tl wday1
16932 iso-year iso-weekday iso-week iso-date futurep kill-year)
16933 (setq org-read-date-analyze-futurep nil
16934 org-read-date-analyze-forced-year nil)
16935 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16938 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16939 (setq ans (replace-match "" t t ans)
16941 deltaw (nth 1 delta)
16942 deltadef (nth 2 delta)))
16944 ;; Check if there is an iso week date in there. If yes, store the
16945 ;; info and postpone interpreting it until the rest of the parsing
16947 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16948 (setq iso-year (when (match-end 1)
16949 (org-small-year-to-year
16950 (string-to-number (match-string 1 ans))))
16951 iso-weekday (when (match-end 3)
16952 (string-to-number (match-string 3 ans)))
16953 iso-week (string-to-number (match-string 2 ans)))
16954 (setq ans (replace-match "" t t ans)))
16956 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16957 (when (string-match
16958 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16959 (setq year (if (match-end 2)
16960 (string-to-number (match-string 2 ans))
16961 (progn (setq kill-year t)
16962 (string-to-number (format-time-string "%Y"))))
16963 month (string-to-number (match-string 3 ans))
16964 day (string-to-number (match-string 4 ans)))
16965 (setq year (org-small-year-to-year year))
16966 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16969 ;; Help matching dotted european dates
16970 (when (string-match
16971 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16972 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16974 (string-to-number (format-time-string "%Y")))
16975 day (string-to-number (match-string 1 ans))
16976 month (string-to-number (match-string 2 ans))
16977 ans (replace-match (format "%04d-%02d-%02d" year month day)
16980 ;; Help matching american dates, like 5/30 or 5/30/7
16981 (when (string-match
16982 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16983 (setq year (if (match-end 4)
16984 (string-to-number (match-string 4 ans))
16985 (progn (setq kill-year t)
16986 (string-to-number (format-time-string "%Y"))))
16987 month (string-to-number (match-string 1 ans))
16988 day (string-to-number (match-string 2 ans)))
16989 (setq year (org-small-year-to-year year))
16990 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16992 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16993 ;; If there is a time with am/pm, and *no* time without it, we convert
16994 ;; so that matching will be successful.
16995 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16996 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16997 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16998 (setq hour (string-to-number (match-string 1 ans))
16999 minute (if (match-end 3)
17000 (string-to-number (match-string 3 ans))
17003 (string-to-char (downcase (match-string 4 ans)))))
17004 (if (and (= hour 12) (not pm))
17006 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17007 (setq ans (replace-match (format "%02d:%02d" hour minute)
17010 ;; Check if a time range is given as a duration
17011 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17012 (setq hour (string-to-number (match-string 1 ans))
17013 h2 (+ hour (string-to-number (match-string 3 ans)))
17014 minute (string-to-number (match-string 2 ans))
17015 m2 (+ minute (if (match-end 5) (string-to-number
17016 (match-string 5 ans))0)))
17017 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17018 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17021 ;; Check if there is a time range
17022 (when (boundp 'org-end-time-was-given)
17023 (setq org-time-was-given nil)
17024 (when (and (string-match org-plain-time-of-day-regexp ans)
17026 (setq org-end-time-was-given (match-string 8 ans))
17027 (setq ans (concat (substring ans 0 (match-beginning 7))
17028 (substring ans (match-end 7))))))
17030 (setq tl (parse-time-string ans)
17031 day (or (nth 3 tl) (nth 3 org-defdecode))
17034 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17035 ;; Day was specified. Make sure DAY+MONTH
17036 ;; combination happens in the future.
17039 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17040 (nth 4 nowdecode)))
17041 (t (nth 4 org-defdecode)))
17043 (cond ((and (not kill-year) (nth 5 tl)))
17044 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17045 ;; Month was guessed in the future and is at least
17046 ;; equal to NOWDECODE's. Fix year accordingly.
17048 (if (or (> month (nth 4 nowdecode))
17049 (>= day (nth 3 nowdecode)))
17051 (1+ (nth 5 nowdecode))))
17052 ;; Month was specified. Make sure MONTH+YEAR
17053 ;; combination happens in the future.
17056 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17057 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17058 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17059 (t (nth 5 nowdecode))))
17060 (t (nth 5 org-defdecode)))
17061 hour (or (nth 2 tl) (nth 2 org-defdecode))
17062 minute (or (nth 1 tl) (nth 1 org-defdecode))
17063 second (or (nth 0 tl) 0)
17066 (when (and (eq org-read-date-prefer-future 'time)
17067 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17068 (equal day (nth 3 nowdecode))
17069 (equal month (nth 4 nowdecode))
17070 (equal year (nth 5 nowdecode))
17072 (or (< (nth 2 tl) (nth 2 nowdecode))
17073 (and (= (nth 2 tl) (nth 2 nowdecode))
17075 (< (nth 1 tl) (nth 1 nowdecode)))))
17079 ;; Special date definitions below
17082 ;; There was an iso week
17085 (setq year (or iso-year year)
17086 day (or iso-weekday wday 1)
17087 wday nil ; to make sure that the trigger below does not match
17088 iso-date (calendar-gregorian-from-absolute
17089 (calendar-iso-to-absolute
17090 (list iso-week day year))))
17091 ; FIXME: Should we also push ISO weeks into the future?
17092 ; (when (and org-read-date-prefer-future
17094 ; (< (calendar-absolute-from-gregorian iso-date)
17095 ; (time-to-days (current-time))))
17096 ; (setq year (1+ year)
17097 ; iso-date (calendar-gregorian-from-absolute
17098 ; (calendar-iso-to-absolute
17099 ; (list iso-week day year)))))
17100 (setq month (car iso-date)
17101 year (nth 2 iso-date)
17102 day (nth 1 iso-date)))
17106 ;; Pass `current-time' result to `decode-time' (instead of
17107 ;; calling without arguments) so that only `current-time' has
17108 ;; to be overridden in tests.
17109 (let ((now (decode-time (current-time))))
17110 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17111 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17112 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17113 ((equal deltaw "m") (setq month (+ month deltan)))
17114 ((equal deltaw "y") (setq year (+ year deltan)))))
17115 ((and wday (not (nth 3 tl)))
17116 ;; Weekday was given, but no day, so pick that day in the week
17117 ;; on or after the derived date.
17118 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17119 (unless (equal wday wday1)
17120 (setq day (+ day (% (- wday wday1 -7) 7))))))
17121 (when (and (boundp 'org-time-was-given)
17123 (setq org-time-was-given t))
17124 (when (< year 100) (setq year (+ 2000 year)))
17125 ;; Check of the date is representable
17126 (if org-read-date-force-compatible-dates
17128 (when (< year 1970)
17129 (setq year 1970 org-read-date-analyze-forced-year t))
17130 (when (> year 2037)
17131 (setq year 2037 org-read-date-analyze-forced-year t)))
17132 (condition-case nil
17133 (ignore (encode-time second minute hour day month year))
17135 (setq year (nth 5 org-defdecode))
17136 (setq org-read-date-analyze-forced-year t))))
17137 (setq org-read-date-analyze-futurep futurep)
17138 (list second minute hour day month year)))
17140 (defvar parse-time-weekdays)
17141 (defun org-read-date-get-relative (s today default)
17142 "Check string S for special relative date string.
17143 TODAY and DEFAULT are internal times, for today and for a default.
17144 Return shift list (N what def-flag)
17145 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17146 N is the number of WHATs to shift.
17147 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17148 the DEFAULT date rather than TODAY."
17149 (require 'parse-time)
17153 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17155 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17156 "\\([ \t]\\|$\\)") s)
17157 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17158 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17159 (string-to-char (substring (match-string 1 s) -1))
17161 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17162 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17163 (what (if (match-end 3) (match-string 3 s) "d"))
17164 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17165 (date (if rel default today))
17166 (wday (nth 6 (decode-time date)))
17170 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17171 (when (= delta 0) (setq delta 7))
17173 (setq delta (- delta 7))
17174 (when (= delta 0) (setq delta -7)))
17175 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17176 (list delta "d" rel))
17177 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17179 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17180 "Turn a user-specified date into the internal representation.
17181 The internal representation needed by the calendar is (month day year).
17182 This is a wrapper to handle the brain-dead convention in calendar that
17183 user function argument order change dependent on argument order."
17184 (pcase calendar-date-style
17185 (`american (list arg1 arg2 arg3))
17186 (`european (list arg2 arg1 arg3))
17187 (`iso (list arg2 arg3 arg1))))
17189 (defun org-eval-in-calendar (form &optional keepdate)
17190 "Eval FORM in the calendar window and return to current window.
17191 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17192 (let ((sf (selected-frame))
17193 (sw (selected-window)))
17194 (select-window (get-buffer-window "*Calendar*" t))
17196 (when (and (not keepdate) (calendar-cursor-to-date))
17197 (let* ((date (calendar-cursor-to-date))
17198 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17199 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17200 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17202 (select-frame-set-input-focus sf)))
17204 (defun org-calendar-select ()
17205 "Return to `org-read-date' with the date currently selected.
17206 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17208 (when (calendar-cursor-to-date)
17209 (let* ((date (calendar-cursor-to-date))
17210 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17211 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17212 (when (active-minibuffer-window) (exit-minibuffer))))
17214 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17215 "Insert a date stamp for the date given by the internal TIME.
17216 See `format-time-string' for the format of TIME.
17217 WITH-HM means use the stamp format that includes the time of the day.
17218 INACTIVE means use square brackets instead of angular ones, so that the
17219 stamp will not contribute to the agenda.
17220 PRE and POST are optional strings to be inserted before and after the
17222 The command returns the inserted time stamp."
17223 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17225 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17226 (insert-before-markers (or pre ""))
17227 (when (listp extra)
17228 (setq extra (car extra))
17229 (if (and (stringp extra)
17230 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17231 (setq extra (format "-%02d:%02d"
17232 (string-to-number (match-string 1 extra))
17233 (string-to-number (match-string 2 extra))))
17236 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17237 (insert-before-markers (setq stamp (format-time-string fmt time)))
17238 (insert-before-markers (or post ""))
17239 (setq org-last-inserted-timestamp stamp)))
17241 (defun org-toggle-time-stamp-overlays ()
17242 "Toggle the use of custom time stamp formats."
17244 (setq org-display-custom-times (not org-display-custom-times))
17245 (unless org-display-custom-times
17246 (let ((p (point-min)) (bmp (buffer-modified-p)))
17247 (while (setq p (next-single-property-change p 'display))
17248 (when (and (get-text-property p 'display)
17249 (eq (get-text-property p 'face) 'org-date))
17250 (remove-text-properties
17251 p (setq p (next-single-property-change p 'display))
17253 (set-buffer-modified-p bmp)))
17254 (org-restart-font-lock)
17255 (setq org-table-may-need-update t)
17256 (if org-display-custom-times
17257 (message "Time stamps are overlaid with custom format")
17258 (message "Time stamp overlays removed")))
17260 (defun org-display-custom-time (beg end)
17261 "Overlay modified time stamp format over timestamp between BEG and END."
17262 (let* ((ts (buffer-substring beg end))
17263 t1 with-hm tf time str (off 0))
17265 (setq t1 (org-parse-time-string ts t))
17266 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17267 (setq off (- (match-end 0) (match-beginning 0)))))
17268 (setq end (- end off))
17269 (setq with-hm (and (nth 1 t1) (nth 2 t1))
17270 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17271 time (org-fix-decoded-time t1)
17273 (format-time-string
17274 (substring tf 1 -1) (apply 'encode-time time))
17275 nil 'mouse-face 'highlight))
17276 (put-text-property beg end 'display str)))
17278 (defun org-fix-decoded-time (time)
17279 "Set 0 instead of nil for the first 6 elements of time.
17280 Don't touch the rest."
17282 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17284 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17285 "Difference between TIMESTAMP-STRING and now in days.
17286 If SECONDS is non-nil, return the difference in seconds."
17287 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17288 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17289 (funcall fdiff (current-time)))))
17291 (defun org-deadline-close-p (timestamp-string &optional ndays)
17292 "Is the time in TIMESTAMP-STRING close to the current date?"
17293 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17294 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17295 (not (org-entry-is-done-p))))
17297 (defun org-get-wdays (ts &optional delay zero-delay)
17298 "Get the deadline lead time appropriate for timestring TS.
17299 When DELAY is non-nil, get the delay time for scheduled items
17300 instead of the deadline lead time. When ZERO-DELAY is non-nil
17301 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17302 don't try to find the delay cookie in the scheduled timestamp."
17303 (let ((tv (if delay org-scheduled-delay-days
17304 org-deadline-warning-days)))
17306 ((or (and delay (< tv 0))
17307 (and delay zero-delay (<= tv 0))
17308 (and (not delay) (<= tv 0)))
17309 ;; Enforce this value no matter what
17311 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17312 ;; lead time is specified.
17313 (floor (* (string-to-number (match-string 1 ts))
17314 (cdr (assoc (match-string 2 ts)
17315 '(("d" . 1) ("w" . 7)
17316 ("m" . 30.4) ("y" . 365.25)
17317 ("h" . 0.041667)))))))
17318 ;; go for the default.
17321 (defun org-calendar-select-mouse (ev)
17322 "Return to `org-read-date' with the date currently selected.
17323 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17325 (mouse-set-point ev)
17326 (when (calendar-cursor-to-date)
17327 (let* ((date (calendar-cursor-to-date))
17328 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17329 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17330 (when (active-minibuffer-window) (exit-minibuffer))))
17332 (defun org-check-deadlines (ndays)
17333 "Check if there are any deadlines due or past due.
17334 A deadline is considered due if it happens within `org-deadline-warning-days'
17335 days from today's date. If the deadline appears in an entry marked DONE,
17336 it is not shown. A numeric prefix argument NDAYS can be used to test that
17337 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17340 (let* ((org-warn-days
17342 ((equal ndays '(4)) 100000)
17343 (ndays (prefix-numeric-value ndays))
17344 (t (abs org-deadline-warning-days))))
17345 (case-fold-search nil)
17346 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17348 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17349 (message "%d deadlines past-due or due within %d days"
17350 (org-occur regexp nil callback)
17353 (defsubst org-re-timestamp (type)
17354 "Return a regexp for timestamp TYPE.
17355 Allowed values for TYPE are:
17357 all: all timestamps
17358 active: only active timestamps (<...>)
17359 inactive: only inactive timestamps ([...])
17360 scheduled: only scheduled timestamps
17361 deadline: only deadline timestamps
17362 closed: only closed time-stamps
17364 When TYPE is nil, fall back on returning a regexp that matches
17365 both scheduled and deadline timestamps."
17367 (all org-ts-regexp-both)
17368 (active org-ts-regexp)
17369 (inactive org-ts-regexp-inactive)
17370 (scheduled org-scheduled-time-regexp)
17371 (deadline org-deadline-time-regexp)
17372 (closed org-closed-time-regexp)
17375 (regexp-opt (list org-deadline-string org-scheduled-string))
17376 " *<\\([^>]+\\)>"))))
17378 (defun org-check-before-date (d)
17379 "Check if there are deadlines or scheduled entries before date D."
17380 (interactive (list (org-read-date)))
17381 (let* ((case-fold-search nil)
17382 (regexp (org-re-timestamp org-ts-type))
17383 (ts-type org-ts-type)
17386 (let ((match (match-string 1)))
17387 (and (if (memq ts-type '(active inactive all))
17388 (eq (org-element-type (save-excursion
17390 (org-element-context)))
17392 (org-at-planning-p))
17394 (org-time-string-to-time match)
17395 (org-time-string-to-time d)))))))
17396 (message "%d entries before %s"
17397 (org-occur regexp nil callback)
17400 (defun org-check-after-date (d)
17401 "Check if there are deadlines or scheduled entries after date D."
17402 (interactive (list (org-read-date)))
17403 (let* ((case-fold-search nil)
17404 (regexp (org-re-timestamp org-ts-type))
17405 (ts-type org-ts-type)
17408 (let ((match (match-string 1)))
17409 (and (if (memq ts-type '(active inactive all))
17410 (eq (org-element-type (save-excursion
17412 (org-element-context)))
17414 (org-at-planning-p))
17416 (org-time-string-to-time match)
17417 (org-time-string-to-time d))))))))
17418 (message "%d entries after %s"
17419 (org-occur regexp nil callback)
17422 (defun org-check-dates-range (start-date end-date)
17423 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17424 (interactive (list (org-read-date nil nil nil "Range starts")
17425 (org-read-date nil nil nil "Range end")))
17426 (let ((case-fold-search nil)
17427 (regexp (org-re-timestamp org-ts-type))
17429 (let ((type org-ts-type))
17431 (let ((match (match-string 1)))
17433 (if (memq type '(active inactive all))
17434 (eq (org-element-type (save-excursion
17436 (org-element-context)))
17438 (org-at-planning-p))
17440 (org-time-string-to-time match)
17441 (org-time-string-to-time start-date)))
17443 (org-time-string-to-time match)
17444 (org-time-string-to-time end-date))))))))
17445 (message "%d entries between %s and %s"
17446 (org-occur regexp nil callback) start-date end-date)))
17448 (defun org-evaluate-time-range (&optional to-buffer)
17449 "Evaluate a time range by computing the difference between start and end.
17450 Normally the result is just printed in the echo area, but with prefix arg
17451 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17452 If the time range is actually in a table, the result is inserted into the
17454 For time difference computation, a year is assumed to be exactly 365
17455 days in order to avoid rounding problems."
17458 (org-clock-update-time-maybe)
17460 (unless (org-at-date-range-p t)
17461 (goto-char (point-at-bol))
17462 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17463 (unless (org-at-date-range-p t)
17464 (user-error "Not at a time-stamp range, and none found in current line")))
17465 (let* ((ts1 (match-string 1))
17466 (ts2 (match-string 2))
17467 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17468 (match-end (match-end 0))
17469 (time1 (org-time-string-to-time ts1))
17470 (time2 (org-time-string-to-time ts2))
17471 (t1 (float-time time1))
17472 (t2 (float-time time2))
17473 (diff (abs (- t2 t1)))
17474 (negative (< (- t2 t1) 0))
17475 ;; (ys (floor (* 365 24 60 60)))
17478 (fy "%dy %dd %02d:%02d")
17480 (fd "%dd %02d:%02d")
17485 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17487 d (floor (/ diff ds)) diff (mod diff ds)
17488 h (floor (/ diff hs)) diff (mod diff hs)
17489 m (floor (/ diff 60)))
17490 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17492 d (floor (+ (/ diff ds) 0.5))
17494 (if (not to-buffer)
17495 (message "%s" (org-make-tdiff-string y d h m))
17496 (if (org-at-table-p)
17498 (goto-char match-end)
17500 (and (looking-at " *|") (goto-char (match-end 0))))
17501 (goto-char match-end))
17503 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17504 (replace-match ""))
17505 (when negative (insert " -"))
17506 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17507 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17508 (insert " " (format fh h m))))
17509 (when align (org-table-align))
17510 (message "Time difference inserted")))))
17512 (defun org-make-tdiff-string (y d h m)
17516 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17519 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17522 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17525 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17527 (apply 'format fmt (nreverse l))))
17529 (defun org-time-string-to-time (s)
17530 "Convert timestamp string S into internal time."
17531 (apply #'encode-time (org-parse-time-string s)))
17533 (defun org-time-string-to-seconds (s)
17534 "Convert a timestamp string S into a number of seconds."
17535 (float-time (org-time-string-to-time s)))
17537 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17539 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17540 "Convert time stamp S to an absolute day number.
17542 If DAYNR in non-nil, and there is a specifier for a cyclic time
17543 stamp, get the closest date to DAYNR. If PREFER is
17544 `past' (respectively `future') return a date past (respectively
17545 after) or equal to DAYNR.
17547 POS is the location of time stamp S, as a buffer position in
17550 Diary sexp timestamps are matched against DAYNR, when non-nil.
17551 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17554 ((string-match "\\`%%\\((.*)\\)" s)
17555 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17556 ;; only able to match individual dates. If it fails, raise an
17559 (org-diary-sexp-entry
17560 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17562 (signal 'org-diary-sexp-no-match (list s))))
17563 (daynr (org-closest-date s daynr prefer))
17565 (condition-case errdata
17566 (apply #'encode-time (org-parse-time-string s))
17567 (error (error "Bad timestamp `%s'%s\nError was: %s"
17569 (if (not (and buffer pos)) ""
17570 (format-message " at %d in buffer `%s'" pos buffer))
17571 (cdr errdata))))))))
17573 (defun org-days-to-iso-week (days)
17574 "Return the iso week number."
17576 (car (calendar-iso-from-absolute days)))
17578 (defun org-small-year-to-year (year)
17579 "Convert 2-digit years into 4-digit years.
17580 YEAR is expanded into one of the 30 next years, if possible, or
17581 into a past one. Any year larger than 99 is returned unchanged."
17582 (if (>= year 100) year
17583 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17584 (century (/ current 100))
17585 (offset (- year (% current 100))))
17586 (cond ((> offset 30) (+ (* (1- century) 100) year))
17587 ((> offset -70) (+ (* century 100) year))
17588 (t (+ (* (1+ century) 100) year))))))
17590 (defun org-time-from-absolute (d)
17591 "Return the time corresponding to date D.
17592 D may be an absolute day number, or a calendar-type list (month day year)."
17593 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17594 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17596 (defvar org-agenda-current-date)
17597 (defun org-calendar-holiday ()
17598 "List of holidays, for Diary display in Org mode."
17599 (require 'holidays)
17600 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17601 (and hl (mapconcat #'identity hl "; "))))
17603 (defun org-diary-sexp-entry (sexp entry d)
17604 "Process a SEXP diary ENTRY for date D."
17605 (require 'diary-lib)
17606 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17608 (let* ((sexp `(let ((entry ,entry)
17610 ,(car (read-from-string sexp))))
17611 (result (if calendar-debug-sexp (eval sexp)
17612 (condition-case nil
17616 (message "Bad sexp at line %d in %s: %s"
17618 (buffer-file-name) sexp)
17620 (cond ((stringp result) (split-string result "; "))
17621 ((and (consp result)
17622 (not (consp (cdr result)))
17623 (stringp (cdr result))) (cdr result))
17624 ((and (consp result)
17625 (stringp (car result))) result)
17628 (defun org-diary-to-ical-string (frombuf)
17629 "Get iCalendar entries from diary entries in buffer FROMBUF.
17630 This uses the icalendar.el library."
17631 (let* ((tmpdir temporary-file-directory)
17632 (tmpfile (make-temp-name
17633 (expand-file-name "orgics" tmpdir)))
17635 (with-current-buffer frombuf
17636 (icalendar-export-region (point-min) (point-max) tmpfile)
17637 (setq buf (find-buffer-visiting tmpfile))
17639 (goto-char (point-min))
17640 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17641 (setq b (match-beginning 0)))
17642 (goto-char (point-max))
17643 (when (re-search-backward "^END:VEVENT" nil t)
17644 (setq e (match-end 0)))
17645 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17647 (delete-file tmpfile)
17650 (defun org-closest-date (start current prefer)
17651 "Return closest date to CURRENT starting from START.
17653 CURRENT and START are both time stamps.
17655 When PREFER is `past', return a date that is either CURRENT or
17656 past. When PREFER is `future', return a date that is either
17659 Only time stamps with a repeater are modified. Any other time
17660 stamp stay unchanged. In any case, return value is an absolute
17662 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17663 ;; No repeater. Do not shift time stamp.
17664 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17665 (let ((value (string-to-number (match-string 1 start)))
17666 (type (match-string 2 start)))
17668 ;; Repeater with a 0-value is considered as void.
17669 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17670 (let* ((base (org-date-to-gregorian start))
17671 (target (org-date-to-gregorian current))
17672 (sday (calendar-absolute-from-gregorian base))
17673 (cday (calendar-absolute-from-gregorian target))
17675 ;; If START is already past CURRENT, just return START.
17676 (if (<= cday sday) sday
17677 ;; Compute closest date before (N1) and closest date past
17681 (let ((missing-hours
17682 (mod (+ (- (* 24 (- cday sday))
17683 (nth 2 (org-parse-time-string start)))
17684 org-extend-today-until)
17686 (setf n1 (if (= missing-hours 0) cday
17687 (- cday (1+ (/ missing-hours 24)))))
17688 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17690 (let ((value (if (equal type "w") (* 7 value) value)))
17691 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17692 (setf n2 (+ n1 value))))
17696 ;; Add N months to gregorian date D, i.e.,
17697 ;; a list (MONTH DAY YEAR). Return a valid
17699 (let ((m (+ (nth 0 d) n)))
17702 (+ (/ m 12) (nth 2 d))))))
17703 (months ; Complete months to TARGET.
17704 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17705 (- (nth 0 target) (nth 0 base))
17706 ;; If START's day is greater than
17707 ;; TARGET's, remove incomplete month.
17708 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17711 (before (funcall add-months base months)))
17712 (setf n1 (calendar-absolute-from-gregorian before))
17714 (calendar-absolute-from-gregorian
17715 (funcall add-months before value)))))
17717 (let* ((d (nth 1 base))
17720 (years ; Complete years to TARGET.
17721 (* (/ (- (nth 2 target)
17723 ;; If START's month and day are
17724 ;; greater than TARGET's, remove
17725 ;; incomplete year.
17726 (if (or (> (nth 0 target) m)
17727 (and (= (nth 0 target) m)
17728 (> (nth 1 target) d)))
17733 (before (list m d (+ y years))))
17734 (setf n1 (calendar-absolute-from-gregorian before))
17735 (setf n2 (calendar-absolute-from-gregorian
17736 (list m d (+ (nth 2 before) value)))))))
17737 ;; Handle PREFER parameter, if any.
17739 ((eq prefer 'past) (if (= cday n2) n2 n1))
17740 ((eq prefer 'future) (if (= cday n1) n1 n2))
17741 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17743 (defun org-date-to-gregorian (d)
17744 "Turn any specification of date D into a Gregorian date for the calendar."
17745 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17746 ((and (listp d) (= (length d) 3)) d)
17748 (let ((d (org-parse-time-string d)))
17749 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17750 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17752 (defun org-parse-time-string (s &optional nodefault)
17753 "Parse the standard Org time string.
17755 This should be a lot faster than the normal `parse-time-string'.
17757 If time is not given, defaults to 0:00. However, with optional
17758 NODEFAULT, hour and minute fields will be nil if not given."
17759 (cond ((string-match org-ts-regexp0 s)
17761 (when (or (match-beginning 8) (not nodefault))
17762 (string-to-number (or (match-string 8 s) "0")))
17763 (when (or (match-beginning 7) (not nodefault))
17764 (string-to-number (or (match-string 7 s) "0")))
17765 (string-to-number (match-string 4 s))
17766 (string-to-number (match-string 3 s))
17767 (string-to-number (match-string 2 s))
17769 ((string-match "^<[^>]+>$" s)
17770 ;; FIXME: `decode-time' needs to be called with ZONE as its
17771 ;; second argument. However, this requires at least Emacs
17772 ;; 25.1. We can do it when we switch to this version as our
17773 ;; minimal requirement.
17774 (decode-time (seconds-to-time (org-matcher-time s))))
17775 (t (error "Not a standard Org time string: %s" s))))
17777 (defun org-timestamp-up (&optional arg)
17778 "Increase the date item at the cursor by one.
17779 If the cursor is on the year, change the year. If it is on the month,
17780 the day or the time, change that.
17781 With prefix ARG, change by that many units."
17783 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17785 (defun org-timestamp-down (&optional arg)
17786 "Decrease the date item at the cursor by one.
17787 If the cursor is on the year, change the year. If it is on the month,
17788 the day or the time, change that.
17789 With prefix ARG, change by that many units."
17791 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17793 (defun org-timestamp-up-day (&optional arg)
17794 "Increase the date in the time stamp by one day.
17795 With prefix ARG, change that many days."
17797 (if (and (not (org-at-timestamp-p 'lax))
17798 (org-at-heading-p))
17800 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17802 (defun org-timestamp-down-day (&optional arg)
17803 "Decrease the date in the time stamp by one day.
17804 With prefix ARG, change that many days."
17806 (if (and (not (org-at-timestamp-p 'lax))
17807 (org-at-heading-p))
17809 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17811 (defun org-at-timestamp-p (&optional extended)
17812 "Non-nil if point is inside a timestamp.
17814 By default, the function only consider syntactically valid active
17815 timestamps. However, the caller may have a broader definition
17816 for timestamps. As a consequence, optional argument EXTENDED can
17817 be set to the following values
17821 Include also syntactically valid inactive timestamps.
17825 Include timestamps allowed in Agenda, i.e., those in
17826 properties drawers, planning lines and clock lines.
17830 Ignore context. The function matches any part of the
17831 document looking like a timestamp. This includes comments,
17834 For backward-compatibility with Org 9.0, every other non-nil
17835 value is equivalent to `inactive'.
17837 When at a timestamp, return the position of the point as a symbol
17838 among `bracket', `after', `year', `month', `hour', `minute',
17839 `day' or a number of character from the last know part of the
17842 When matching, the match groups are the following:
17845 group 3: day number
17847 group 5: hours, if any
17848 group 6: minutes, if any"
17849 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17852 (let ((boundaries (org-in-regexp regexp)))
17854 (cond ((null boundaries) nil)
17855 ((eq extended 'lax) t)
17857 (or (and (eq extended 'agenda)
17858 (or (org-at-planning-p)
17859 (org-at-property-p)
17860 (and (bound-and-true-p
17861 org-agenda-include-inactive-timestamps)
17862 (org-at-clock-log-p))))
17865 (when (= pos (cdr boundaries)) (forward-char -1))
17866 (org-element-type (org-element-context)))))))))))
17869 ((= pos (match-beginning 0)) 'bracket)
17870 ;; Distinguish location right before the closing bracket from
17872 ((= pos (1- (match-end 0))) 'bracket)
17873 ((= pos (match-end 0)) 'after)
17874 ((org-pos-in-match-range pos 2) 'year)
17875 ((org-pos-in-match-range pos 3) 'month)
17876 ((org-pos-in-match-range pos 7) 'hour)
17877 ((org-pos-in-match-range pos 8) 'minute)
17878 ((or (org-pos-in-match-range pos 4)
17879 (org-pos-in-match-range pos 5)) 'day)
17880 ((and (> pos (or (match-end 8) (match-end 5)))
17881 (< pos (match-end 0)))
17882 (- pos (or (match-end 8) (match-end 5))))
17885 (defun org-toggle-timestamp-type ()
17886 "Toggle the type (<active> or [inactive]) of a time stamp."
17888 (when (org-at-timestamp-p 'lax)
17889 (let ((beg (match-beginning 0)) (end (match-end 0))
17890 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17893 (while (re-search-forward "[][<>]" end t)
17894 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17896 (message "Timestamp is now %sactive"
17897 (if (equal (char-after beg) ?<) "" "in")))))
17899 (defun org-at-clock-log-p ()
17900 "Non-nil if point is on a clock log line."
17901 (and (org-match-line org-clock-line-re)
17902 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17904 (defvar org-clock-history) ; defined in org-clock.el
17905 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17906 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17907 "Change the date in the time stamp at point.
17908 The date will be changed by N times WHAT. WHAT can be `day', `month',
17909 `year', `minute', `second'. If WHAT is not given, the cursor position
17910 in the timestamp determines what will be changed.
17911 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17912 (let ((origin (point))
17913 (timestamp? (org-at-timestamp-p 'lax))
17916 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17918 ts time time0 fixnext clrgx)
17919 (unless timestamp? (user-error "Not at a timestamp"))
17920 (if (and (not what) (eq timestamp? 'bracket))
17921 (org-toggle-timestamp-type)
17922 ;; Point isn't on brackets. Remember the part of the time-stamp
17923 ;; the point was in. Indeed, size of time-stamps may change,
17924 ;; but point must be kept in the same category nonetheless.
17925 (setq origin-cat timestamp?)
17926 (when (and (not what) (not (eq timestamp? 'day))
17927 org-display-custom-times
17928 (get-text-property (point) 'display)
17929 (not (get-text-property (1- (point)) 'display)))
17930 (setq timestamp? 'day))
17931 (setq timestamp? (or what timestamp?)
17932 inactive (= (char-after (match-beginning 0)) ?\[)
17933 ts (match-string 0))
17935 (when (string-match
17936 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17938 (setq extra (match-string 1 ts))
17939 (when suppress-tmp-delay
17940 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17941 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17943 (setq time0 (org-parse-time-string ts))
17945 (eq timestamp? 'minute)
17946 (not current-prefix-arg))
17947 ;; This looks like s-up and s-down. Change by one rounding step.
17948 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17949 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17950 (setcar (cdr time0) (+ (nth 1 time0)
17951 (if (> n 0) (- rem) (- dm rem))))))
17953 (apply #'encode-time
17955 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17956 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17957 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17958 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17959 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17961 (when (and (memq timestamp? '(hour minute))
17963 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17964 (setq extra (org-modify-ts-extra
17966 (if (eq timestamp? 'hour) 2 5)
17968 (when (integerp timestamp?)
17969 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17970 (when (eq what 'calendar)
17971 (let ((cal-date (org-get-date-from-calendar)))
17972 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17973 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17974 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17975 (setcar time0 (or (car time0) 0))
17976 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17977 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17978 (setq time (apply 'encode-time time0))))
17979 ;; Insert the new time-stamp, and ensure point stays in the same
17980 ;; category as before (i.e. not after the last position in that
17982 (let ((pos (point)))
17983 ;; Stay before inserted string. `save-excursion' is of no use.
17984 (setq org-last-changed-timestamp
17985 (org-insert-time-stamp time with-hm inactive nil nil extra))
17988 (looking-at org-ts-regexp3)
17991 ;; `day' category ends before `hour' if any, or at the end
17992 ;; of the day name.
17993 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17994 (`hour (min (match-end 7) origin))
17995 (`minute (min (1- (match-end 8)) origin))
17996 ((pred integerp) (min (1- (match-end 0)) origin))
17997 ;; Point was right after the time-stamp. However, the
17998 ;; time-stamp length might have changed, so refer to
17999 ;; (match-end 0) instead.
18000 (`after (match-end 0))
18001 ;; `year' and `month' have both fixed size: point couldn't
18002 ;; have moved into another part.
18004 ;; Update clock if on a CLOCK line.
18005 (org-clock-update-time-maybe)
18006 ;; Maybe adjust the closest clock in `org-clock-history'
18007 (when org-clock-adjust-closest
18008 (if (not (and (org-at-clock-log-p)
18009 (< 1 (length (delq nil (mapcar 'marker-position
18010 org-clock-history))))))
18011 (message "No clock to adjust")
18012 (cond ((save-excursion ; fix previous clock?
18013 (re-search-backward org-ts-regexp0 nil t)
18014 (looking-back (concat org-clock-string " \\[")
18015 (line-beginning-position)))
18016 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18017 ((save-excursion ; fix next clock?
18018 (re-search-backward org-ts-regexp0 nil t)
18019 (looking-at (concat org-ts-regexp0 "\\] =>")))
18020 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18021 (save-window-excursion
18022 ;; Find closest clock to point, adjust the previous/next one in history
18023 (let* ((p (save-excursion (org-back-to-heading t)))
18024 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18026 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18027 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18029 (message "No clock to adjust")
18031 (org-goto-marker-or-bmk clfixpos)
18033 (when (re-search-forward clrgx nil t)
18034 (goto-char (match-beginning 1))
18035 (let (org-clock-adjust-closest)
18036 (org-timestamp-change n timestamp? updown))
18037 (message "Clock adjusted in %s for heading: %s"
18038 (file-name-nondirectory (buffer-file-name))
18039 (org-get-heading t t)))))))))
18040 ;; Try to recenter the calendar window, if any.
18041 (when (and org-calendar-follow-timestamp-change
18042 (get-buffer-window "*Calendar*" t)
18043 (memq timestamp? '(day month year)))
18044 (org-recenter-calendar (time-to-days time))))))
18046 (defun org-modify-ts-extra (s pos n dm)
18047 "Change the different parts of the lead-time and repeat fields in timestamp."
18048 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18050 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18052 ((or (org-pos-in-match-range pos 2)
18053 (org-pos-in-match-range pos 3))
18054 (setq m (string-to-number (match-string 3 s))
18055 h (string-to-number (match-string 2 s)))
18056 (if (org-pos-in-match-range pos 2)
18058 (setq n (* dm (with-no-warnings (signum n))))
18059 (unless (= 0 (setq rem (% m dm)))
18060 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18062 (when (< m 0) (setq m (+ m 60) h (1- h)))
18063 (when (> m 59) (setq m (- m 60) h (1+ h)))
18064 (setq h (mod h 24))
18065 (setq ng 1 new (format "-%02d:%02d" h m)))
18066 ((org-pos-in-match-range pos 6)
18067 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18068 ((org-pos-in-match-range pos 5)
18069 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18071 ((org-pos-in-match-range pos 9)
18072 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18073 ((org-pos-in-match-range pos 8)
18074 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18078 (substring s 0 (match-beginning ng))
18080 (substring s (match-end ng))))))
18083 (defun org-recenter-calendar (d)
18084 "If the calendar is visible, recenter it to date D."
18085 (let ((cwin (get-buffer-window "*Calendar*" t)))
18087 (let ((calendar-move-hook nil))
18088 (with-selected-window cwin
18089 (calendar-goto-date
18090 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18092 (defun org-goto-calendar (&optional arg)
18093 "Go to the Emacs calendar at the current date.
18094 If there is a time stamp in the current line, go to that date.
18095 A prefix ARG can be used to force the current date."
18097 (let ((calendar-move-hook nil)
18098 (calendar-view-holidays-initially-flag nil)
18099 (calendar-view-diary-initially-flag nil)
18101 (when (or (org-at-timestamp-p 'lax)
18102 (org-match-line (concat ".*" org-ts-regexp)))
18103 (let ((d1 (time-to-days (current-time)))
18104 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
18105 (setq diff (- d2 d1))))
18107 (calendar-goto-today)
18108 (when (and diff (not arg)) (calendar-forward-day diff))))
18110 (defun org-get-date-from-calendar ()
18111 "Return a list (month day year) of date at point in calendar."
18112 (with-current-buffer "*Calendar*"
18114 (calendar-cursor-to-date))))
18116 (defun org-date-from-calendar ()
18117 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18118 If there is already a time stamp at the cursor position, update it."
18120 (if (org-at-timestamp-p 'lax)
18121 (org-timestamp-change 0 'calendar)
18122 (let ((cal-date (org-get-date-from-calendar)))
18123 (org-insert-time-stamp
18124 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18126 (defcustom org-effort-durations
18130 ("w" . ,(* 60 8 5))
18131 ("m" . ,(* 60 8 5 4))
18132 ("y" . ,(* 60 8 5 40)))
18133 "Conversion factor to minutes for an effort modifier.
18135 Each entry has the form (MODIFIER . MINUTES).
18137 In an effort string, a number followed by MODIFIER is multiplied
18138 by the specified number of MINUTES to obtain an effort in
18141 For example, if the value of this variable is ((\"hours\" . 60)), then an
18142 effort string \"2hours\" is equivalent to 120 minutes."
18145 :package-version '(Org . "8.3")
18146 :type '(alist :key-type (string :tag "Modifier")
18147 :value-type (number :tag "Minutes")))
18149 (defcustom org-image-actual-width t
18150 "Should we use the actual width of images when inlining them?
18152 When set to t, always use the image width.
18154 When set to a number, use imagemagick (when available) to set
18155 the image's width to this value.
18157 When set to a number in a list, try to get the width from any
18158 #+ATTR.* keyword if it matches a width specification like
18160 #+ATTR_HTML: :width 300px
18162 and fall back on that number if none is found.
18164 When set to nil, try to get the width from an #+ATTR.* keyword
18165 and fall back on the original width if none is found.
18167 This requires Emacs >= 24.1, build with imagemagick support."
18168 :group 'org-appearance
18170 :package-version '(Org . "8.0")
18172 (const :tag "Use the image width" t)
18173 (integer :tag "Use a number of pixels")
18174 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18175 (const :tag "Use #+ATTR* or don't resize" nil)))
18177 (defcustom org-agenda-inhibit-startup nil
18178 "Inhibit startup when preparing agenda buffers.
18179 When this variable is t, the initialization of the Org agenda
18180 buffers is inhibited: e.g. the visibility state is not set, the
18181 tables are not re-aligned, etc."
18184 :group 'org-agenda)
18186 (defcustom org-agenda-ignore-properties nil
18187 "Avoid updating text properties when building the agenda.
18188 Properties are used to prepare buffers for effort estimates,
18189 appointments, statistics and subtree-local categories.
18190 If you don't use these in the agenda, you can add them to this
18191 list and agenda building will be a bit faster.
18192 The value is a list, with zero or more of the symbols `effort', `appt',
18193 `stats' or `category'."
18194 :type '(set :greedy t
18200 :package-version '(Org . "8.3")
18201 :group 'org-agenda)
18205 (defun org-save-all-org-buffers ()
18206 "Save all Org buffers without user confirmation."
18208 (message "Saving all Org buffers...")
18209 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18210 (when (featurep 'org-id) (org-id-locations-save))
18211 (message "Saving all Org buffers... done"))
18213 (defun org-revert-all-org-buffers ()
18214 "Revert all Org buffers.
18215 Prompt for confirmation when there are unsaved changes.
18216 Be sure you know what you are doing before letting this function
18217 overwrite your changes.
18219 This function is useful in a setup where one tracks org files
18220 with a version control system, to revert on one machine after pulling
18221 changes from another. I believe the procedure must be like this:
18223 1. M-x org-save-all-org-buffers
18224 2. Pull changes from the other machine, resolve conflicts
18225 3. M-x org-revert-all-org-buffers"
18227 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18228 (user-error "Abort"))
18230 (save-window-excursion
18231 (dolist (b (buffer-list))
18232 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18233 (with-current-buffer b buffer-file-name))
18234 (pop-to-buffer-same-window b)
18235 (revert-buffer t 'no-confirm)))
18236 (when (and (featurep 'org-id) org-id-track-globally)
18237 (org-id-locations-load)))))
18242 (defun org-switchb (&optional arg)
18243 "Switch between Org buffers.
18245 With `\\[universal-argument]' prefix, restrict available buffers to files.
18247 With `\\[universal-argument] \\[universal-argument]' \
18248 prefix, restrict available buffers to agenda files."
18250 (let ((blist (org-buffer-list
18251 (cond ((equal arg '(4)) 'files)
18252 ((equal arg '(16)) 'agenda)))))
18253 (pop-to-buffer-same-window
18254 (completing-read "Org buffer: "
18255 (mapcar #'list (mapcar #'buffer-name blist))
18258 (defun org-buffer-list (&optional predicate exclude-tmp)
18259 "Return a list of Org buffers.
18260 PREDICATE can be `export', `files' or `agenda'.
18262 export restrict the list to Export buffers.
18263 files restrict the list to buffers visiting Org files.
18264 agenda restrict the list to buffers visiting agenda files.
18266 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18268 (agenda-files (and (eq predicate 'agenda)
18269 (mapcar 'file-truename (org-agenda-files t))))
18272 ((eq predicate 'files)
18273 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18274 ((eq predicate 'export)
18275 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18276 ((eq predicate 'agenda)
18278 (with-current-buffer b
18279 (and (derived-mode-p 'org-mode)
18280 (setq bfn (buffer-file-name b))
18281 (member (file-truename bfn) agenda-files)))))
18282 (t (lambda (b) (with-current-buffer b
18283 (or (derived-mode-p 'org-mode)
18284 (string-match "\\*Org .*Export"
18285 (buffer-name b)))))))))
18289 (if (and (funcall filter b)
18290 (or (not exclude-tmp)
18291 (not (string-match "tmp" (buffer-name b)))))
18296 (defun org-agenda-files (&optional unrestricted archives)
18297 "Get the list of agenda files.
18298 Optional UNRESTRICTED means return the full list even if a restriction
18299 is currently in place.
18300 When ARCHIVES is t, include all archive files that are really being
18301 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18302 `org-agenda-archives-mode' is t."
18305 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18306 ((stringp org-agenda-files) (org-read-agenda-file-list))
18307 ((listp org-agenda-files) org-agenda-files)
18308 (t (error "Invalid value of `org-agenda-files'")))))
18309 (setq files (apply 'append
18310 (mapcar (lambda (f)
18311 (if (file-directory-p f)
18313 f t org-agenda-file-regexp)
18316 (when org-agenda-skip-unavailable-files
18317 (setq files (delq nil
18320 (and (file-readable-p file) file)))
18322 (when (or (eq archives t)
18323 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18324 (setq files (org-add-archive-files files)))
18327 (defun org-agenda-file-p (&optional file)
18328 "Return non-nil, if FILE is an agenda file.
18329 If FILE is omitted, use the file associated with the current
18331 (let ((fname (or file (buffer-file-name))))
18333 (member (file-truename fname)
18334 (mapcar #'file-truename (org-agenda-files t))))))
18336 (defun org-edit-agenda-file-list ()
18337 "Edit the list of agenda files.
18338 Depending on setup, this either uses customize to edit the variable
18339 `org-agenda-files', or it visits the file that is holding the list. In the
18340 latter case, the buffer is set up in a way that saving it automatically kills
18341 the buffer and restores the previous window configuration."
18343 (if (stringp org-agenda-files)
18344 (let ((cw (current-window-configuration)))
18345 (find-file org-agenda-files)
18346 (setq-local org-window-configuration cw)
18347 (add-hook 'after-save-hook
18349 (set-window-configuration
18350 (prog1 org-window-configuration
18351 (kill-buffer (current-buffer))))
18352 (org-install-agenda-files-menu)
18353 (message "New agenda file list installed"))
18355 (message "%s" (substitute-command-keys
18356 "Edit list and finish with \\[save-buffer]")))
18357 (customize-variable 'org-agenda-files)))
18359 (defun org-store-new-agenda-file-list (list)
18360 "Set new value for the agenda file list and save it correctly."
18361 (if (stringp org-agenda-files)
18362 (let ((fe (org-read-agenda-file-list t)) b u)
18363 (while (setq b (find-buffer-visiting org-agenda-files))
18365 (with-temp-file org-agenda-files
18368 (lambda (f) ;; Keep un-expanded entries.
18369 (if (setq u (assoc f fe))
18374 (let ((org-mode-hook nil) (org-inhibit-startup t)
18375 (org-insert-mode-line-in-empty-file nil))
18376 (setq org-agenda-files list)
18377 (customize-save-variable 'org-agenda-files org-agenda-files))))
18379 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18380 "Read the list of agenda files from a file.
18381 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18382 filenames, used by `org-store-new-agenda-file-list' to write back
18383 un-expanded file names."
18384 (when (file-directory-p org-agenda-files)
18385 (error "`org-agenda-files' cannot be a single directory"))
18386 (when (stringp org-agenda-files)
18388 (insert-file-contents org-agenda-files)
18391 (let ((e (expand-file-name (substitute-in-file-name f)
18393 (if pair-with-expansion
18396 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18399 (defun org-cycle-agenda-files ()
18400 "Cycle through the files in `org-agenda-files'.
18401 If the current buffer visits an agenda file, find the next one in the list.
18402 If the current buffer does not, find the first agenda file."
18404 (let* ((fs (or (org-agenda-files t)
18405 (user-error "No agenda files")))
18406 (files (copy-sequence fs))
18407 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18410 (while (and (setq file (pop files))
18411 (not (equal (file-truename file) tcf)))))
18412 (find-file (car (or files fs)))
18413 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18415 (defun org-agenda-file-to-front (&optional to-end)
18416 "Move/add the current file to the top of the agenda file list.
18417 If the file is not present in the list, it is added to the front. If it is
18418 present, it is moved there. With optional argument TO-END, add/move to the
18421 (let ((org-agenda-skip-unavailable-files nil)
18422 (file-alist (mapcar (lambda (x)
18423 (cons (file-truename x) x))
18424 (org-agenda-files t)))
18425 (ctf (file-truename
18426 (or buffer-file-name
18427 (user-error "Please save the current buffer to a file"))))
18429 (setq x (assoc ctf file-alist) had x)
18431 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18433 (setq file-alist (append (delq x file-alist) (list x)))
18434 (setq file-alist (cons x (delq x file-alist))))
18435 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18436 (org-install-agenda-files-menu)
18437 (message "File %s to %s of agenda file list"
18438 (if had "moved" "added") (if to-end "end" "front"))))
18440 (defun org-remove-file (&optional file)
18441 "Remove current file from the list of files in variable `org-agenda-files'.
18442 These are the files which are being checked for agenda entries.
18443 Optional argument FILE means use this file instead of the current."
18445 (let* ((org-agenda-skip-unavailable-files nil)
18446 (file (or file buffer-file-name
18447 (user-error "Current buffer does not visit a file")))
18448 (true-file (file-truename file))
18449 (afile (abbreviate-file-name file))
18450 (files (delq nil (mapcar
18452 (unless (equal true-file
18455 (org-agenda-files t)))))
18456 (if (not (= (length files) (length (org-agenda-files t))))
18458 (org-store-new-agenda-file-list files)
18459 (org-install-agenda-files-menu)
18460 (message "Removed from Org Agenda list: %s" afile))
18461 (message "File was not in list: %s (not removed)" afile))))
18463 (defun org-file-menu-entry (file)
18464 (vector file (list 'find-file file) t))
18466 (defun org-check-agenda-file (file)
18467 "Make sure FILE exists. If not, ask user what to do."
18468 (unless (file-exists-p file)
18469 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18470 (abbreviate-file-name file))
18471 (let ((r (downcase (read-char-exclusive))))
18474 (org-remove-file file)
18475 (throw 'nextfile t))
18476 (t (user-error "Abort"))))))
18478 (defun org-get-agenda-file-buffer (file)
18479 "Get an agenda buffer visiting FILE.
18480 If the buffer needs to be created, add it to the list of buffers
18481 which might be released later."
18482 (let ((buf (org-find-base-buffer-visiting file)))
18484 buf ; just return it
18485 ;; Make a new buffer and remember it
18486 (setq buf (find-file-noselect file))
18487 (when buf (push buf org-agenda-new-buffers))
18490 (defun org-release-buffers (blist)
18491 "Release all buffers in list, asking the user for confirmation when needed.
18492 When a buffer is unmodified, it is just killed. When modified, it is saved
18493 \(if the user agrees) and then killed."
18495 (dolist (buf blist)
18496 (setq file (buffer-file-name buf))
18497 (when (and (buffer-modified-p buf)
18499 (y-or-n-p (format "Save file %s? " file)))
18500 (with-current-buffer buf (save-buffer)))
18501 (kill-buffer buf))))
18503 (defun org-agenda-prepare-buffers (files)
18504 "Create buffers for all agenda files, protect archived trees and comments."
18506 (let ((pa '(:org-archived t))
18507 (pc '(:org-comment t))
18508 (pall '(:org-archived t :org-comment t))
18509 (inhibit-read-only t)
18510 (org-inhibit-startup org-agenda-inhibit-startup)
18511 (rea (concat ":" org-archive-tag ":"))
18513 (setq org-tag-alist-for-agenda nil
18514 org-tag-groups-alist-for-agenda nil)
18517 (dolist (file files)
18521 (org-check-agenda-file file)
18522 (set-buffer (org-get-agenda-file-buffer file)))
18524 (org-set-regexps-and-options 'tags-only)
18526 (or (memq 'category org-agenda-ignore-properties)
18527 (org-refresh-category-properties))
18528 (or (memq 'stats org-agenda-ignore-properties)
18529 (org-refresh-stats-properties))
18530 (or (memq 'effort org-agenda-ignore-properties)
18531 (org-refresh-effort-properties))
18532 (or (memq 'appt org-agenda-ignore-properties)
18533 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18534 (setq org-todo-keywords-for-agenda
18535 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18536 (setq org-done-keywords-for-agenda
18537 (append org-done-keywords-for-agenda org-done-keywords))
18538 (setq org-todo-keyword-alist-for-agenda
18539 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18540 (setq org-tag-alist-for-agenda
18542 (append org-tag-alist-for-agenda
18543 org-current-tag-alist)))
18544 ;; Merge current file's tag groups into global
18545 ;; `org-tag-groups-alist-for-agenda'.
18546 (when org-group-tags
18547 (dolist (alist org-tag-groups-alist)
18548 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18550 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18551 (push alist org-tag-groups-alist-for-agenda)))))
18552 (org-with-silent-modifications
18554 (remove-text-properties (point-min) (point-max) pall)
18555 (when org-agenda-skip-archived-trees
18556 (goto-char (point-min))
18557 (while (re-search-forward rea nil t)
18558 (when (org-at-heading-p t)
18559 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18560 (goto-char (point-min))
18561 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18562 (while (re-search-forward re nil t)
18563 (when (save-match-data (org-in-commented-heading-p t))
18564 (add-text-properties
18565 (match-beginning 0) (org-end-of-subtree t) pc)))))
18566 (goto-char pos)))))
18567 (setq org-todo-keywords-for-agenda
18568 (org-uniquify org-todo-keywords-for-agenda))
18569 (setq org-todo-keyword-alist-for-agenda
18570 (org-uniquify org-todo-keyword-alist-for-agenda))))
18573 ;;;; CDLaTeX minor mode
18575 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18576 "Keymap for the minor `org-cdlatex-mode'.")
18578 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18579 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18580 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18581 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18582 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18584 (defvar org-cdlatex-texmathp-advice-is-done nil
18585 "Flag remembering if we have applied the advice to texmathp already.")
18587 (define-minor-mode org-cdlatex-mode
18588 "Toggle the minor `org-cdlatex-mode'.
18589 This mode supports entering LaTeX environment and math in LaTeX fragments
18591 \\{org-cdlatex-mode-map}"
18593 (when org-cdlatex-mode
18595 (run-hooks 'cdlatex-mode-hook)
18596 (cdlatex-compute-tables))
18597 (unless org-cdlatex-texmathp-advice-is-done
18598 (setq org-cdlatex-texmathp-advice-is-done t)
18599 (defadvice texmathp (around org-math-always-on activate)
18600 "Always return t in Org buffers.
18601 This is because we want to insert math symbols without dollars even outside
18602 the LaTeX math segments. If Org mode thinks that point is actually inside
18603 an embedded LaTeX fragment, let `texmathp' do its job.
18604 `\\[org-cdlatex-mode-map]'"
18608 ((not (derived-mode-p 'org-mode)) ad-do-it)
18609 ((eq this-command 'cdlatex-math-symbol)
18610 (setq ad-return-value t
18611 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18613 (let ((p (org-inside-LaTeX-fragment-p)))
18614 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18615 (setq ad-return-value t
18616 texmathp-why '("Org mode embedded math" . 0))
18617 (when p ad-do-it)))))))))
18619 (defun turn-on-org-cdlatex ()
18620 "Unconditionally turn on `org-cdlatex-mode'."
18621 (org-cdlatex-mode 1))
18623 (defun org-try-cdlatex-tab ()
18624 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18625 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18626 - inside a LaTeX fragment, or
18627 - after the first word in a line, where an abbreviation expansion could
18628 insert a LaTeX environment."
18629 (when org-cdlatex-mode
18631 ;; Before any word on the line: No expansion possible.
18632 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18633 ;; Just after first word on the line: Expand it. Make sure it
18634 ;; cannot happen on headlines, though.
18636 (skip-chars-backward "a-zA-Z0-9*")
18637 (skip-chars-backward " \t")
18638 (and (bolp) (not (org-at-heading-p))))
18640 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18642 (defun org-cdlatex-underscore-caret (&optional _arg)
18643 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18644 Revert to the normal definition outside of these fragments."
18646 (if (org-inside-LaTeX-fragment-p)
18647 (call-interactively 'cdlatex-sub-superscript)
18648 (let (org-cdlatex-mode)
18649 (call-interactively (key-binding (vector last-input-event))))))
18651 (defun org-cdlatex-math-modify (&optional _arg)
18652 "Execute `cdlatex-math-modify' in LaTeX fragments.
18653 Revert to the normal definition outside of these fragments."
18655 (if (org-inside-LaTeX-fragment-p)
18656 (call-interactively 'cdlatex-math-modify)
18657 (let (org-cdlatex-mode)
18658 (call-interactively (key-binding (vector last-input-event))))))
18660 (defun org-cdlatex-environment-indent (&optional environment item)
18661 "Execute `cdlatex-environment' and indent the inserted environment.
18663 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18665 The inserted environment is indented to current indentation
18666 unless point is at the beginning of the line, in which the
18667 environment remains unintended."
18669 ;; cdlatex-environment always return nil. Therefore, capture output
18670 ;; first and determine if an environment was selected.
18671 (let* ((beg (point-marker))
18672 (end (copy-marker (point) t))
18674 (ignore-errors (cdlatex-environment environment item))
18676 ;; Figure out how many lines to move forward after the
18677 ;; environment has been inserted.
18678 (lines (when inserted
18680 (- (cl-loop while (< beg (point))
18682 do (forward-line -1)
18685 (if (progn (goto-char beg)
18686 (and (progn (skip-chars-forward " \t") (eolp))
18687 (progn (skip-chars-backward " \t") (bolp))))
18689 (env (org-trim (delete-and-extract-region beg end))))
18691 ;; Get indentation of next line unless at column 0.
18692 (let ((ind (if (bolp) 0
18694 (org-return-indent)
18695 (prog1 (org-get-indentation)
18696 (when (progn (skip-chars-forward " \t") (eolp))
18697 (delete-region beg (point)))))))
18698 (bol (progn (skip-chars-backward " \t") (bolp))))
18699 ;; Insert a newline before environment unless at column zero
18700 ;; to "escape" the current line. Insert a newline if
18701 ;; something is one the same line as \end{ENVIRONMENT}.
18703 (concat (unless bol "\n") env
18704 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18705 (unless (zerop ind)
18708 (while (< (point) end)
18709 (unless (eolp) (indent-line-to ind))
18712 (forward-line lines)
18713 (indent-line-to ind)))
18714 (set-marker beg nil)
18715 (set-marker end nil)))
18718 ;;;; LaTeX fragments
18720 (defun org-inside-LaTeX-fragment-p ()
18721 "Test if point is inside a LaTeX fragment.
18722 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18723 sequence appearing also before point.
18724 Even though the matchers for math are configurable, this function assumes
18725 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18726 delimiters are skipped when they have been removed by customization.
18727 The return value is nil, or a cons cell with the delimiter and the
18728 position of this delimiter.
18730 This function does a reasonably good job, but can locally be fooled by
18731 for example currency specifications. For example it will assume being in
18732 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18733 fragments that are properly closed, but during editing, we have to live
18734 with the uncertainty caused by missing closing delimiters. This function
18735 looks only before point, not after."
18737 (let ((pos (point))
18738 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18739 (lim (save-excursion (org-backward-paragraph) (point)))
18740 dd-on str (start 0) m re)
18743 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18744 re (nth 1 (assoc "$" org-latex-regexps)))
18745 (while (string-match re str start)
18747 ((= (match-end 0) (length str))
18748 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18749 ((= (match-end 0) (- (length str) 5))
18751 (t (setq start (match-end 0))))))
18752 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18754 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18755 (and (match-beginning 2) (throw 'exit nil))
18757 (while (re-search-backward "\\$\\$" lim t)
18758 (setq dd-on (not dd-on)))
18760 (when dd-on (cons "$$" m))))))
18762 (defun org-inside-latex-macro-p ()
18763 "Is point inside a LaTeX macro or its arguments?"
18766 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18768 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18769 "Build an overlay between BEG and END using IMAGE file.
18770 Argument IMAGETYPE is the extension of the displayed image,
18771 as a string. It defaults to \"png\"."
18772 (let ((ov (make-overlay beg end))
18773 (imagetype (or (intern imagetype) 'png)))
18774 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18775 (overlay-put ov 'evaporate t)
18777 'modification-hooks
18778 (list (lambda (o _flag _beg _end &optional _l)
18779 (delete-overlay o))))
18782 (list 'image :type imagetype :file image :ascent 'center))))
18784 (defun org--list-latex-overlays (&optional beg end)
18785 "List all Org LaTeX overlays in current buffer.
18786 Limit to overlays between BEG and END when those are provided."
18788 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18789 (overlays-in (or beg (point-min)) (or end (point-max)))))
18791 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18792 "Remove all overlays with LaTeX fragment images in current buffer.
18793 When optional arguments BEG and END are non-nil, remove all
18794 overlays between them instead. Return a non-nil value when some
18795 overlays were removed, nil otherwise."
18796 (let ((overlays (org--list-latex-overlays beg end)))
18797 (mapc #'delete-overlay overlays)
18800 (defun org-toggle-latex-fragment (&optional arg)
18801 "Preview the LaTeX fragment at point, or all locally or globally.
18803 If the cursor is on a LaTeX fragment, create the image and overlay
18804 it over the source code, if there is none. Remove it otherwise.
18805 If there is no fragment at point, display all fragments in the
18808 With prefix ARG, preview or clear image for all fragments in the
18809 current subtree or in the whole buffer when used before the first
18810 headline. With a prefix ARG `\\[universal-argument] \
18811 \\[universal-argument]' preview or clear images
18812 for all fragments in the buffer."
18814 (when (display-graphic-p)
18819 ((or (equal arg '(16))
18820 (and (equal arg '(4))
18821 (org-with-limited-levels (org-before-first-heading-p))))
18822 (if (org-remove-latex-fragment-image-overlays)
18823 (progn (message "LaTeX fragments images removed from buffer")
18825 (setq msg "Creating images for buffer...")))
18827 (org-with-limited-levels (org-back-to-heading t))
18829 (setq end (progn (org-end-of-subtree t) (point)))
18830 (if (org-remove-latex-fragment-image-overlays beg end)
18832 (message "LaTeX fragment images removed from subtree")
18834 (setq msg "Creating images for subtree...")))
18835 ((let ((datum (org-element-context)))
18836 (when (memq (org-element-type datum)
18837 '(latex-environment latex-fragment))
18838 (setq beg (org-element-property :begin datum))
18839 (setq end (org-element-property :end datum))
18840 (if (org-remove-latex-fragment-image-overlays beg end)
18841 (progn (message "LaTeX fragment image removed")
18843 (setq msg "Creating image...")))))
18845 (org-with-limited-levels
18846 (setq beg (if (org-at-heading-p) (line-beginning-position)
18847 (outline-previous-heading)
18849 (setq end (progn (outline-next-heading) (point)))
18850 (if (org-remove-latex-fragment-image-overlays beg end)
18852 (message "LaTeX fragment images removed from section")
18854 (setq msg "Creating images for section...")))))
18855 (let ((file (buffer-file-name (buffer-base-buffer))))
18857 (concat org-preview-latex-image-directory "org-ltximg")
18859 ;; Emacs cannot overlay images from remote hosts. Create
18860 ;; it in `temporary-file-directory' instead.
18861 (if (or (not file) (file-remote-p file))
18862 temporary-file-directory
18864 'overlays msg 'forbuffer org-preview-latex-default-process))
18865 (message (concat msg "done")))))))
18867 (defun org-format-latex
18868 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18869 "Replace LaTeX fragments with links to an image.
18871 The function takes care of creating the replacement image.
18873 Only consider fragments between BEG and END when those are
18876 When optional argument OVERLAYS is non-nil, display the image on
18877 top of the fragment instead of replacing it.
18879 PROCESSING-TYPE is the conversion method to use, as a symbol.
18881 Some of the options can be changed using the variable
18882 `org-format-latex-options', which see."
18883 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18884 (unless (eq processing-type 'verbatim)
18885 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18888 (goto-char (or beg (point-min)))
18889 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18890 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18891 (overlay-recenter (or end (point-max))))
18892 (while (re-search-forward math-regexp end t)
18893 (unless (and overlays
18894 (eq (get-char-property (point) 'org-overlay-type)
18895 'org-latex-overlay))
18896 (let* ((context (org-element-context))
18897 (type (org-element-type context)))
18898 (when (memq type '(latex-environment latex-fragment))
18899 (let ((block-type (eq type 'latex-environment))
18900 (value (org-element-property :value context))
18901 (beg (org-element-property :begin context))
18902 (end (save-excursion
18903 (goto-char (org-element-property :end context))
18904 (skip-chars-backward " \r\t\n")
18907 ((eq processing-type 'mathjax)
18908 ;; Prepare for MathJax processing.
18909 (if (not (string-match "\\`\\$\\$?" value))
18911 (delete-region beg end)
18912 (if (string= (match-string 0 value) "$$")
18913 (insert "\\[" (substring value 2 -2) "\\]")
18914 (insert "\\(" (substring value 1 -1) "\\)"))))
18915 ((assq processing-type org-preview-latex-process-alist)
18916 ;; Process to an image.
18919 (let* ((processing-info
18920 (cdr (assq processing-type org-preview-latex-process-alist)))
18921 (face (face-at-point))
18922 ;; Get the colors from the face at point.
18924 (let ((color (plist-get org-format-latex-options
18926 (if (and forbuffer (eq color 'auto))
18927 (face-attribute face :foreground nil 'default)
18930 (let ((color (plist-get org-format-latex-options
18932 (if (and forbuffer (eq color 'auto))
18933 (face-attribute face :background nil 'default)
18935 (hash (sha1 (prin1-to-string
18936 (list org-format-latex-header
18937 org-latex-default-packages-alist
18938 org-latex-packages-alist
18939 org-format-latex-options
18940 forbuffer value fg bg))))
18941 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18942 (absprefix (expand-file-name prefix dir))
18943 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18944 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18945 (sep (and block-type "\n\n"))
18946 (link (concat sep "[[file:" linkfile "]]" sep))
18948 (org-combine-plists
18949 org-format-latex-options
18950 `(:foreground ,fg :background ,bg))))
18951 (when msg (message msg cnt))
18952 (unless checkdir-flag ; Ensure the directory exists.
18953 (setq checkdir-flag t)
18954 (let ((todir (file-name-directory absprefix)))
18955 (unless (file-directory-p todir)
18956 (make-directory todir t))))
18957 (unless (file-exists-p movefile)
18958 (org-create-formula-image
18959 value movefile options forbuffer processing-type))
18962 (dolist (o (overlays-in beg end))
18963 (when (eq (overlay-get o 'org-overlay-type)
18964 'org-latex-overlay)
18965 (delete-overlay o)))
18966 (org--format-latex-make-overlay beg end movefile imagetype)
18968 (delete-region beg end)
18970 (org-add-props link
18971 (list 'org-latex-src
18972 (replace-regexp-in-string "\"" "" value)
18973 'org-latex-src-embed-type
18974 (if block-type 'paragraph 'character)))))))
18975 ((eq processing-type 'mathml)
18976 ;; Process to MathML.
18977 (unless (org-format-latex-mathml-available-p)
18978 (user-error "LaTeX to MathML converter not configured"))
18980 (when msg (message msg cnt))
18982 (delete-region beg end)
18983 (insert (org-format-latex-as-mathml
18984 value block-type prefix dir)))
18986 (error "Unknown conversion process %s for LaTeX fragments"
18987 processing-type)))))))))))
18989 (defun org-create-math-formula (latex-frag &optional mathml-file)
18990 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18991 Use `org-latex-to-mathml-convert-command'. If the conversion is
18992 sucessful, return the portion between \"<math...> </math>\"
18993 elements otherwise return nil. When MATHML-FILE is specified,
18994 write the results in to that file. When invoked as an
18995 interactive command, prompt for LATEX-FRAG, with initial value
18996 set to the current active region and echo the results for user
18998 (interactive (list (let ((frag (when (org-region-active-p)
18999 (buffer-substring-no-properties
19000 (region-beginning) (region-end)))))
19001 (read-string "LaTeX Fragment: " frag nil frag))))
19002 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19003 (let* ((tmp-in-file
19004 (let ((file (file-relative-name
19005 (make-temp-name (expand-file-name "ltxmathml-in")))))
19006 (write-region latex-frag nil file)
19008 (tmp-out-file (file-relative-name
19009 (make-temp-name (expand-file-name "ltxmathml-out"))))
19011 org-latex-to-mathml-convert-command
19012 `((?j . ,(and org-latex-to-mathml-jar-file
19013 (shell-quote-argument
19015 org-latex-to-mathml-jar-file))))
19016 (?I . ,(shell-quote-argument tmp-in-file))
19018 (?o . ,(shell-quote-argument tmp-out-file)))))
19019 mathml shell-command-output)
19020 (when (called-interactively-p 'any)
19021 (unless (org-format-latex-mathml-available-p)
19022 (user-error "LaTeX to MathML converter not configured")))
19023 (message "Running %s" cmd)
19024 (setq shell-command-output (shell-command-to-string cmd))
19026 (when (file-readable-p tmp-out-file)
19027 (with-current-buffer (find-file-noselect tmp-out-file t)
19028 (goto-char (point-min))
19029 (when (re-search-forward
19030 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19032 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19034 (prog1 (match-string 0) (kill-buffer))))))
19038 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19040 (write-region mathml nil mathml-file))
19041 (when (called-interactively-p 'any)
19043 ((message "LaTeX to MathML conversion failed")
19044 (message shell-command-output)))
19045 (delete-file tmp-in-file)
19046 (when (file-exists-p tmp-out-file)
19047 (delete-file tmp-out-file))
19050 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19051 prefix &optional dir)
19052 "Use `org-create-math-formula' but check local cache first."
19053 (let* ((absprefix (expand-file-name prefix dir))
19054 (print-length nil) (print-level nil)
19055 (formula-id (concat
19060 org-latex-to-mathml-convert-command)))))
19061 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19062 (formula-cache-dir (file-name-directory formula-cache)))
19064 (unless (file-directory-p formula-cache-dir)
19065 (make-directory formula-cache-dir t))
19067 (unless (file-exists-p formula-cache)
19068 (org-create-math-formula latex-frag formula-cache))
19070 (if (file-exists-p formula-cache)
19071 ;; Successful conversion. Return the link to MathML file.
19073 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19074 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19075 'org-latex-src-embed-type (if latex-frag-type
19076 'paragraph 'character)))
19077 ;; Failed conversion. Return the LaTeX fragment verbatim
19080 (defun org--get-display-dpi ()
19081 "Get the DPI of the display.
19082 The function assumes that the display has the same pixel width in
19083 the horizontal and vertical directions."
19084 (if (display-graphic-p)
19085 (round (/ (display-pixel-height)
19086 (/ (display-mm-height) 25.4)))
19087 (error "Attempt to calculate the dpi of a non-graphic display")))
19089 (defun org-create-formula-image
19090 (string tofile options buffer &optional processing-type)
19091 "Create an image from LaTeX source using external processes.
19093 The LaTeX STRING is saved to a temporary LaTeX file, then
19094 converted to an image file by process PROCESSING-TYPE defined in
19095 `org-preview-latex-process-alist'. A nil value defaults to
19096 `org-preview-latex-default-process'.
19098 The generated image file is eventually moved to TOFILE.
19100 The OPTIONS argument controls the size, foreground color and
19101 background color of the generated image.
19103 When BUFFER non-nil, this function is used for LaTeX previewing.
19104 Otherwise, it is used to deal with LaTeX snippets showed in
19106 (let* ((processing-type (or processing-type
19107 org-preview-latex-default-process))
19109 (cdr (assq processing-type org-preview-latex-process-alist)))
19110 (programs (plist-get processing-info :programs))
19111 (error-message (or (plist-get processing-info :message) ""))
19112 (use-xcolor (plist-get processing-info :use-xcolor))
19113 (image-input-type (plist-get processing-info :image-input-type))
19114 (image-output-type (plist-get processing-info :image-output-type))
19115 (post-clean (or (plist-get processing-info :post-clean)
19116 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19117 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19119 (or (plist-get processing-info :latex-header)
19120 (org-latex-make-preamble
19121 (org-export-get-environment (org-export-get-backend 'latex))
19122 org-format-latex-header
19124 (latex-compiler (plist-get processing-info :latex-compiler))
19125 (image-converter (plist-get processing-info :image-converter))
19126 (tmpdir temporary-file-directory)
19127 (texfilebase (make-temp-name
19128 (expand-file-name "orgtex" tmpdir)))
19129 (texfile (concat texfilebase ".tex"))
19130 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19132 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19133 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19134 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19135 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19137 (bg (or (plist-get options (if buffer :background :html-background))
19139 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19140 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19141 (dolist (program programs)
19142 (org-check-external-command program error-message))
19144 (progn (if (eq fg 'default)
19145 (setq fg (org-latex-color :foreground))
19146 (setq fg (org-latex-color-format fg)))
19147 (if (eq bg 'default)
19148 (setq bg (org-latex-color :background))
19149 (setq bg (org-latex-color-format
19150 (if (string= bg "Transparent") "white" bg))))
19151 (with-temp-file texfile
19152 (insert latex-header)
19153 (insert "\n\\begin{document}\n"
19154 "\\definecolor{fg}{rgb}{" fg "}\n"
19155 "\\definecolor{bg}{rgb}{" bg "}\n"
19156 "\n\\pagecolor{bg}\n"
19160 "\n\\end{document}\n")))
19161 (if (eq fg 'default)
19162 (setq fg (org-dvipng-color :foreground))
19163 (unless (string= fg "Transparent")
19164 (setq fg (org-dvipng-color-format fg))))
19165 (if (eq bg 'default)
19166 (setq bg (org-dvipng-color :background))
19167 (unless (string= bg "Transparent")
19168 (setq bg (org-dvipng-color-format bg))))
19169 (with-temp-file texfile
19170 (insert latex-header)
19171 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19173 (let* ((err-msg (format "Please adjust `%s' part of \
19174 `org-preview-latex-process-alist'."
19178 texfile latex-compiler image-input-type err-msg log-buf))
19181 image-input-file image-converter image-output-type err-msg log-buf
19182 `((?F . ,(shell-quote-argument fg))
19183 (?B . ,(shell-quote-argument bg))
19184 (?D . ,(shell-quote-argument (format "%s" dpi)))
19185 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19186 (copy-file image-output-file tofile 'replace)
19187 (dolist (e post-clean)
19188 (when (file-exists-p (concat texfilebase e))
19189 (delete-file (concat texfilebase e))))
19190 image-output-file)))
19192 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19193 "Fill a LaTeX header template TPL.
19194 In the template, the following place holders will be recognized:
19196 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19197 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19198 [PACKAGES] \\usepackage statements for PKG
19199 [NO-PACKAGES] do not include PKG
19200 [EXTRA] the string EXTRA
19201 [NO-EXTRA] do not include EXTRA
19203 For backward compatibility, if both the positive and the negative place
19204 holder is missing, the positive one (without the \"NO-\") will be
19205 assumed to be present at the end of the template.
19206 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19208 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19209 (let (rpl (end ""))
19210 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19211 (setq rpl (if (or (match-end 1) (not def-pkg))
19212 "" (org-latex-packages-to-string def-pkg snippets-p t))
19213 tpl (replace-match rpl t t tpl))
19214 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19216 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19217 (setq rpl (if (or (match-end 1) (not pkg))
19218 "" (org-latex-packages-to-string pkg snippets-p t))
19219 tpl (replace-match rpl t t tpl))
19220 (when pkg (setq end
19222 (org-latex-packages-to-string pkg snippets-p)))))
19224 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19225 (setq rpl (if (or (match-end 1) (not extra))
19226 "" (concat extra "\n"))
19227 tpl (replace-match rpl t t tpl))
19228 (when (and extra (string-match "\\S-" extra))
19229 (setq end (concat end "\n" extra))))
19231 (if (string-match "\\S-" end)
19232 (concat tpl "\n" end)
19235 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19236 "Turn an alist of packages into a string with the \\usepackage macros."
19237 (setq pkg (mapconcat (lambda(p)
19240 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19241 (format "%% Package %s omitted" (cadr p)))
19242 ((equal "" (car p))
19243 (format "\\usepackage{%s}" (cadr p)))
19245 (format "\\usepackage[%s]{%s}"
19246 (car p) (cadr p)))))
19249 (if newline (concat pkg "\n") pkg))
19251 (defun org-dvipng-color (attr)
19252 "Return a RGB color specification for dvipng."
19253 (org-dvipng-color-format (face-attribute 'default attr nil)))
19255 (defun org-dvipng-color-format (color-name)
19256 "Convert COLOR-NAME to a RGB color value for dvipng."
19257 (apply #'format "rgb %s %s %s"
19258 (mapcar 'org-normalize-color
19259 (color-values color-name))))
19261 (defun org-latex-color (attr)
19262 "Return a RGB color for the LaTeX color package."
19263 (org-latex-color-format (face-attribute 'default attr nil)))
19265 (defun org-latex-color-format (color-name)
19266 "Convert COLOR-NAME to a RGB color value."
19267 (apply #'format "%s,%s,%s"
19268 (mapcar 'org-normalize-color
19269 (color-values color-name))))
19271 (defun org-normalize-color (value)
19272 "Return string to be used as color value for an RGB component."
19273 (format "%g" (/ value 65535.0)))
19279 (defvar-local org-inline-image-overlays nil)
19281 (defun org-toggle-inline-images (&optional include-linked)
19282 "Toggle the display of inline images.
19283 INCLUDE-LINKED is passed to `org-display-inline-images'."
19285 (if org-inline-image-overlays
19287 (org-remove-inline-images)
19288 (when (called-interactively-p 'interactive)
19289 (message "Inline image display turned off")))
19290 (org-display-inline-images include-linked)
19291 (when (called-interactively-p 'interactive)
19292 (message (if org-inline-image-overlays
19293 (format "%d images displayed inline"
19294 (length org-inline-image-overlays))
19295 "No images to display inline")))))
19297 (defun org-redisplay-inline-images ()
19298 "Refresh the display of inline images."
19300 (if (not org-inline-image-overlays)
19301 (org-toggle-inline-images)
19302 (org-toggle-inline-images)
19303 (org-toggle-inline-images)))
19305 (defun org-display-inline-images (&optional include-linked refresh beg end)
19306 "Display inline images.
19308 An inline image is a link which follows either of these
19311 1. Its path is a file with an extension matching return value
19312 from `image-file-name-regexp' and it has no contents.
19314 2. Its description consists in a single link of the previous
19317 When optional argument INCLUDE-LINKED is non-nil, also links with
19318 a text description part will be inlined. This can be nice for
19319 a quick look at those images, but it does not reflect what
19320 exported files will look like.
19322 When optional argument REFRESH is non-nil, refresh existing
19323 images between BEG and END. This will create new image displays
19324 only if necessary. BEG and END default to the buffer
19327 (when (display-graphic-p)
19329 (org-remove-inline-images)
19330 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19331 (org-with-wide-buffer
19332 (goto-char (or beg (point-min)))
19333 (let* ((case-fold-search t)
19334 (file-extension-re (image-file-name-regexp))
19335 (link-abbrevs (mapcar #'car
19336 (append org-link-abbrev-alist-local
19337 org-link-abbrev-alist)))
19338 ;; Check absolute, relative file names and explicit
19339 ;; "file:" links. Also check link abbreviations since
19340 ;; some might expand to "file" links.
19341 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19342 (if (not link-abbrevs) ""
19343 (format "\\|\\(?:%s:\\)"
19344 (regexp-opt link-abbrevs))))))
19345 (while (re-search-forward file-types-re end t)
19346 (let ((link (save-match-data (org-element-context))))
19347 ;; Check if we're at an inline image, i.e., an image file
19348 ;; link without a description (unless INCLUDE-LINKED is
19350 (when (and (equal "file" (org-element-property :type link))
19352 (null (org-element-contents link)))
19353 (string-match-p file-extension-re
19354 (org-element-property :path link)))
19355 (let ((file (expand-file-name
19357 (org-element-property :path link)))))
19358 (when (file-exists-p file)
19360 ;; Apply `org-image-actual-width' specifications.
19362 ((not (image-type-available-p 'imagemagick)) nil)
19363 ((eq org-image-actual-width t) nil)
19364 ((listp org-image-actual-width)
19366 ;; First try to find a width among
19367 ;; attributes associated to the paragraph
19368 ;; containing link.
19371 (while (and (setq e (org-element-property
19373 (not (eq (org-element-type e)
19378 (goto-char (org-element-property :begin paragraph))
19381 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19382 (org-element-property
19383 :post-affiliated paragraph)
19385 (string-to-number (match-string 1))))))
19386 ;; Otherwise, fall-back to provided number.
19387 (car org-image-actual-width)))
19388 ((numberp org-image-actual-width)
19389 org-image-actual-width)))
19390 (old (get-char-property-and-overlay
19391 (org-element-property :begin link)
19392 'org-image-overlay)))
19393 (if (and (car-safe old) refresh)
19394 (image-refresh (overlay-get (cdr old) 'display))
19395 (let ((image (create-image file
19396 (and width 'imagemagick)
19400 (let ((ov (make-overlay
19401 (org-element-property :begin link)
19404 (org-element-property :end link))
19405 (skip-chars-backward " \t")
19407 (overlay-put ov 'display image)
19408 (overlay-put ov 'face 'default)
19409 (overlay-put ov 'org-image-overlay t)
19411 ov 'modification-hooks
19412 (list 'org-display-inline-remove-overlay))
19413 (push ov org-inline-image-overlays)))))))))))))))
19415 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19416 "Remove inline-display overlay if a corresponding region is modified."
19417 (let ((inhibit-modification-hooks t))
19418 (when (and ov after)
19419 (delete ov org-inline-image-overlays)
19420 (delete-overlay ov))))
19422 (defun org-remove-inline-images ()
19423 "Remove inline display of images."
19425 (mapc #'delete-overlay org-inline-image-overlays)
19426 (setq org-inline-image-overlays nil))
19430 (defun org-remap (map &rest commands)
19431 "In MAP, remap the functions given in COMMANDS.
19432 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19435 (setq old (pop commands) new (pop commands))
19436 (org-defkey map (vector 'remap old) new))))
19438 ;; Outline functions from `outline-mode-prefix-map'
19439 ;; that can be remapped in Org:
19440 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19441 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19442 (define-key org-mode-map [remap outline-forward-same-level]
19443 'org-forward-heading-same-level)
19444 (define-key org-mode-map [remap outline-backward-same-level]
19445 'org-backward-heading-same-level)
19446 (define-key org-mode-map [remap outline-show-branches]
19447 'org-kill-note-or-show-branches)
19448 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19449 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19450 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19451 (define-key org-mode-map [remap outline-next-visible-heading]
19452 'org-next-visible-heading)
19453 (define-key org-mode-map [remap outline-previous-visible-heading]
19454 'org-previous-visible-heading)
19455 (define-key org-mode-map [remap show-children] 'org-show-children)
19457 ;; Outline functions from `outline-mode-prefix-map' that can not
19458 ;; be remapped in Org:
19460 ;; - the column "key binding" shows whether the Outline function is still
19461 ;; available in Org mode on the same key that it has been bound to in
19463 ;; - "overridden": key used for a different functionality in Org mode
19464 ;; - else: key still bound to the same Outline function in Org mode
19466 ;; | Outline function | key binding | Org replacement |
19467 ;; |------------------------------------+-------------+--------------------------|
19468 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19469 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19470 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19471 ;; | `show-entry' | overridden | no replacement |
19472 ;; | `show-branches' | `C-c C-k' | still same function |
19473 ;; | `show-subtree' | overridden | visibility cycling |
19474 ;; | `show-all' | overridden | no replacement |
19475 ;; | `hide-subtree' | overridden | visibility cycling |
19476 ;; | `hide-body' | overridden | no replacement |
19477 ;; | `hide-entry' | overridden | visibility cycling |
19478 ;; | `hide-leaves' | overridden | no replacement |
19479 ;; | `hide-sublevels' | overridden | no replacement |
19480 ;; | `hide-other' | overridden | no replacement |
19482 ;; Make `C-c C-x' a prefix key
19483 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19485 ;; TAB key with modifiers
19486 (org-defkey org-mode-map "\C-i" 'org-cycle)
19487 (org-defkey org-mode-map [(tab)] 'org-cycle)
19488 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19489 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19491 ;; The following line is necessary under Suse GNU/Linux
19492 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19493 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19494 (define-key org-mode-map [backtab] 'org-shifttab)
19496 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19497 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19498 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
19500 ;; Cursor keys with modifiers
19501 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19502 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19503 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19504 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19506 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19507 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19508 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19509 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19510 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19511 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19513 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19514 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19515 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19516 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19518 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19519 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19520 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19521 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19524 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19525 (dolist (pair org-babel-key-bindings)
19526 (define-key org-babel-map (car pair) (cdr pair)))
19528 ;;; Extra keys for tty access.
19529 ;; We only set them when really needed because otherwise the
19530 ;; menus don't show the simple keys
19532 (when (or org-use-extra-keys (not window-system))
19533 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19534 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19535 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19536 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19537 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19538 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19539 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19540 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19541 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19542 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19543 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19544 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19545 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19546 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19547 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19548 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19549 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19550 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19551 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19552 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19553 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19554 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19555 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19556 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19557 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19558 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19559 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19560 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19562 ;; All the other keys
19563 (org-remap org-mode-map
19564 'self-insert-command 'org-self-insert-command
19565 'delete-char 'org-delete-char
19566 'delete-backward-char 'org-delete-backward-char)
19567 (org-defkey org-mode-map "|" 'org-force-self-insert)
19569 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19570 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19571 (if (boundp 'narrow-map)
19572 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19573 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19574 (if (boundp 'narrow-map)
19575 (org-defkey narrow-map "b" 'org-narrow-to-block)
19576 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19577 (if (boundp 'narrow-map)
19578 (org-defkey narrow-map "e" 'org-narrow-to-element)
19579 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19580 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19581 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19582 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19583 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19584 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19585 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19586 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19587 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19588 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19589 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19590 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19591 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19592 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19593 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19594 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19595 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19596 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19597 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19598 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19599 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19600 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19601 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19602 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19603 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19604 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19605 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19606 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19607 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19608 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19609 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19610 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19611 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19612 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19613 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19614 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19615 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19616 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19617 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19618 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19619 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19620 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19621 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19622 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19623 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19624 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19625 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19626 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19627 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19628 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19629 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19630 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19631 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19632 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19633 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19634 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19635 (org-defkey org-mode-map "\C-c^" 'org-sort)
19636 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19637 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19638 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19639 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19640 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19641 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19642 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19643 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19644 (org-defkey org-mode-map "\C-m" 'org-return)
19645 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19646 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19647 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19648 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19649 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19650 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19651 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19652 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19653 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19654 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19655 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19656 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19657 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19658 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19659 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19660 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19661 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19662 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19663 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19664 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19665 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19666 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19667 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19668 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19669 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19671 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19672 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19673 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19675 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19676 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19677 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19678 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19679 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19680 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19681 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19682 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19683 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19684 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19685 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19686 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19687 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19688 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19689 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19690 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19691 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19692 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19693 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19694 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19695 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19696 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19698 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19699 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19700 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19701 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19702 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19704 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19706 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19708 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19709 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19711 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19714 (defconst org-speed-commands-default
19716 ("Outline Navigation")
19717 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19718 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19719 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19720 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19721 ("F" . org-next-block)
19722 ("B" . org-previous-block)
19723 ("u" . (org-speed-move-safe 'outline-up-heading))
19725 ("g" . (org-refile t))
19726 ("Outline Visibility")
19728 ("C" . org-shifttab)
19729 (" " . org-display-outline-path)
19730 ("s" . org-narrow-to-subtree)
19731 ("=" . org-columns)
19732 ("Outline Structure Editing")
19734 ("D" . org-metadown)
19735 ("r" . org-metaright)
19736 ("l" . org-metaleft)
19737 ("R" . org-shiftmetaright)
19738 ("L" . org-shiftmetaleft)
19739 ("i" . (progn (forward-char 1) (call-interactively
19740 'org-insert-heading-respect-content)))
19743 ("a" . org-archive-subtree-default-with-confirmation)
19744 ("@" . org-mark-subtree)
19745 ("#" . org-toggle-comment)
19747 ("I" . org-clock-in)
19748 ("O" . org-clock-out)
19749 ("Meta Data Editing")
19751 ("," . (org-priority))
19752 ("0" . (org-priority ?\ ))
19753 ("1" . (org-priority ?A))
19754 ("2" . (org-priority ?B))
19755 ("3" . (org-priority ?C))
19756 (":" . org-set-tags-command)
19757 ("e" . org-set-effort)
19758 ("E" . org-inc-effort)
19759 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19760 (org-entry-put (point) "APPT_WARNTIME" m)))
19761 ("Agenda Views etc")
19763 ("/" . org-sparse-tree)
19765 ("o" . org-open-at-point)
19766 ("?" . org-speed-command-help)
19767 ("<" . (org-agenda-set-restriction-lock 'subtree))
19768 (">" . (org-agenda-remove-restriction-lock))
19770 "The default speed commands.")
19772 (defun org-print-speed-command (e)
19773 (if (> (length (car e)) 1)
19778 (princ (make-string (length (car e)) ?-))
19782 (if (symbolp (cdr e))
19783 (princ (symbol-name (cdr e)))
19787 (defun org-speed-command-help ()
19788 "Show the available speed commands."
19790 (if (not org-use-speed-commands)
19791 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19792 (with-output-to-temp-buffer "*Help*"
19793 (princ "User-defined Speed commands\n===========================\n")
19794 (mapc #'org-print-speed-command org-speed-commands-user)
19796 (princ "Built-in Speed commands\n=======================\n")
19797 (mapc #'org-print-speed-command org-speed-commands-default))
19798 (with-current-buffer "*Help*"
19799 (setq truncate-lines t))))
19801 (defun org-speed-move-safe (cmd)
19802 "Execute CMD, but make sure that the cursor always ends up in a headline.
19803 If not, return to the original position and throw an error."
19805 (let ((pos (point)))
19806 (call-interactively cmd)
19807 (unless (and (bolp) (org-at-heading-p))
19809 (error "Boundary reached while executing %s" cmd))))
19811 (defvar org-self-insert-command-undo-counter 0)
19813 (defvar org-table-auto-blank-field) ; defined in org-table.el
19814 (defvar org-speed-command nil)
19816 (defun org-speed-command-activate (keys)
19817 "Hook for activating single-letter speed commands.
19818 `org-speed-commands-default' specifies a minimal command set.
19819 Use `org-speed-commands-user' for further customization."
19820 (when (or (and (bolp) (looking-at org-outline-regexp))
19821 (and (functionp org-use-speed-commands)
19822 (funcall org-use-speed-commands)))
19823 (cdr (assoc keys (append org-speed-commands-user
19824 org-speed-commands-default)))))
19826 (defun org-babel-speed-command-activate (keys)
19827 "Hook for activating single-letter code block commands."
19828 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19829 (cdr (assoc keys org-babel-key-bindings))))
19831 (defcustom org-speed-command-hook
19832 '(org-speed-command-activate org-babel-speed-command-activate)
19833 "Hook for activating speed commands at strategic locations.
19834 Hook functions are called in sequence until a valid handler is
19837 Each hook takes a single argument, a user-pressed command key
19838 which is also a `self-insert-command' from the global map.
19840 Within the hook, examine the cursor position and the command key
19841 and return nil or a valid handler as appropriate. Handler could
19842 be one of an interactive command, a function, or a form.
19844 Set `org-use-speed-commands' to non-nil value to enable this
19845 hook. The default setting is `org-speed-command-activate'."
19846 :group 'org-structure
19850 (defun org-self-insert-command (N)
19851 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19852 If the cursor is in a table looking at whitespace, the whitespace is
19853 overwritten, and the table is not marked as requiring realignment."
19855 (org-check-before-invisible-edit 'insert)
19857 ((and org-use-speed-commands
19858 (let ((kv (this-command-keys-vector)))
19859 (setq org-speed-command
19860 (run-hook-with-args-until-success
19861 'org-speed-command-hook
19862 (make-string 1 (aref kv (1- (length kv))))))))
19864 ((commandp org-speed-command)
19865 (setq this-command org-speed-command)
19866 (call-interactively org-speed-command))
19867 ((functionp org-speed-command)
19868 (funcall org-speed-command))
19869 ((and org-speed-command (listp org-speed-command))
19870 (eval org-speed-command))
19871 (t (let (org-use-speed-commands)
19872 (call-interactively 'org-self-insert-command)))))
19876 (not (org-region-active-p))
19878 ;; Check if we blank the field, and if that triggers align.
19879 (and (featurep 'org-table) org-table-auto-blank-field
19881 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19882 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19883 ;; Got extra space, this field does not determine
19885 (let (org-table-may-need-update) (org-table-blank-field))
19886 ;; No extra space, this field may determine column
19888 (org-table-blank-field)))
19890 (looking-at "[^|\n]* \\( \\)|"))
19891 ;; There is room for insertion without re-aligning the table.
19892 (delete-region (match-beginning 1) (match-end 1))
19893 (self-insert-command N))
19895 (setq org-table-may-need-update t)
19896 (self-insert-command N)
19897 (org-fix-tags-on-the-fly)
19898 (when org-self-insert-cluster-for-undo
19899 (if (not (eq last-command 'org-self-insert-command))
19900 (setq org-self-insert-command-undo-counter 1)
19901 (if (>= org-self-insert-command-undo-counter 20)
19902 (setq org-self-insert-command-undo-counter 1)
19903 (and (> org-self-insert-command-undo-counter 0)
19904 buffer-undo-list (listp buffer-undo-list)
19905 (not (cadr buffer-undo-list)) ; remove nil entry
19906 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19907 (setq org-self-insert-command-undo-counter
19908 (1+ org-self-insert-command-undo-counter))))))))
19910 (defun org-check-before-invisible-edit (kind)
19911 "Check is editing if kind KIND would be dangerous with invisible text around.
19912 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19913 ;; First, try to get out of here as quickly as possible, to reduce overhead
19914 (when (and org-catch-invisible-edits
19915 (or (not (boundp 'visible-mode)) (not visible-mode))
19916 (or (get-char-property (point) 'invisible)
19917 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19918 ;; OK, we need to take a closer look. Do not consider
19919 ;; invisibility obtained through text properties (e.g., link
19920 ;; fontification), as it cannot be toggled.
19921 (let* ((invisible-at-point
19922 (pcase (get-char-property-and-overlay (point) 'invisible)
19923 (`(,_ . ,(and (pred overlayp) o)) o)))
19924 ;; Assume that point cannot land in the middle of an
19925 ;; overlay, or between two overlays.
19926 (invisible-before-point
19927 (and (not invisible-at-point)
19929 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19930 (`(,_ . ,(and (pred overlayp) o)) o))))
19931 (border-and-ok-direction
19933 ;; Check if we are acting predictably before invisible
19935 (and invisible-at-point
19936 (memq kind '(insert delete-backward)))
19937 ;; Check if we are acting predictably after invisible text
19938 ;; This works not well, and I have turned it off. It seems
19939 ;; better to always show and stop after invisible text.
19940 ;; (and (not invisible-at-point) invisible-before-point
19941 ;; (memq kind '(insert delete)))
19943 (when (or invisible-at-point invisible-before-point)
19944 (when (eq org-catch-invisible-edits 'error)
19945 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19946 (if (and org-custom-properties-overlays
19947 (y-or-n-p "Display invisible properties in this buffer? "))
19948 (org-toggle-custom-properties-visibility)
19949 ;; Make the area visible
19951 (when invisible-before-point
19953 (previous-single-char-property-change (point) 'invisible)))
19954 ;; Remove whatever overlay is currently making yet-to-be
19955 ;; edited text invisible. Also remove nested invisibility
19956 ;; related overlays.
19957 (delete-overlay (or invisible-at-point invisible-before-point))
19958 (let ((origin (if invisible-at-point (point) (1- (point)))))
19959 (while (pcase (get-char-property-and-overlay origin 'invisible)
19960 (`(,_ . ,(and (pred overlayp) o))
19964 ((eq org-catch-invisible-edits 'show)
19965 ;; That's it, we do the edit after showing
19967 "Unfolding invisible region around point before editing")
19969 ((and (eq org-catch-invisible-edits 'smart)
19970 border-and-ok-direction)
19971 (message "Unfolding invisible region around point before editing"))
19973 ;; Don't do the edit, make the user repeat it in full visibility
19974 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19976 (defun org-fix-tags-on-the-fly ()
19977 "Align tags in headline at point.
19978 Unlike to `org-set-tags', it ignores region and sorting."
19979 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19980 (org-at-heading-p))
19981 (let ((org-ignore-region t)
19982 (org-tags-sort-function nil))
19983 (org-set-tags nil t))))
19985 (defun org-delete-backward-char (N)
19986 "Like `delete-backward-char', insert whitespace at field end in tables.
19987 When deleting backwards, in tables this function will insert whitespace in
19988 front of the next \"|\" separator, to keep the table aligned. The table will
19989 still be marked for re-alignment if the field did fill the entire column,
19990 because, in this case the deletion might narrow the column."
19993 (org-check-before-invisible-edit 'delete-backward)
19994 (if (and (org-at-table-p)
19996 (not (org-region-active-p))
19997 (string-match "|" (buffer-substring (point-at-bol) (point)))
19998 (looking-at ".*?|"))
19999 (let ((pos (point))
20000 (noalign (looking-at "[^|\n\r]* |"))
20001 (c org-table-may-need-update))
20002 (backward-delete-char N)
20003 (unless overwrite-mode
20004 (skip-chars-forward "^|")
20006 (goto-char (1- pos)))
20007 ;; noalign: if there were two spaces at the end, this field
20008 ;; does not determine the width of the column.
20009 (when noalign (setq org-table-may-need-update c)))
20010 (backward-delete-char N)
20011 (org-fix-tags-on-the-fly))))
20013 (defun org-delete-char (N)
20014 "Like `delete-char', but insert whitespace at field end in tables.
20015 When deleting characters, in tables this function will insert whitespace in
20016 front of the next \"|\" separator, to keep the table aligned. The table will
20017 still be marked for re-alignment if the field did fill the entire column,
20018 because, in this case the deletion might narrow the column."
20021 (org-check-before-invisible-edit 'delete)
20022 (if (and (org-at-table-p)
20024 (not (= (char-after) ?|))
20026 (if (looking-at ".*?|")
20027 (let ((pos (point))
20028 (noalign (looking-at "[^|\n\r]* |"))
20029 (c org-table-may-need-update))
20031 (concat (substring (match-string 0) 1 -1) " |") nil t)
20033 ;; noalign: if there were two spaces at the end, this field
20034 ;; does not determine the width of the column.
20035 (when noalign (setq org-table-may-need-update c)))
20038 (org-fix-tags-on-the-fly))))
20040 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20041 (put 'org-self-insert-command 'delete-selection
20043 (not (run-hook-with-args-until-success
20044 'self-insert-uses-region-functions))))
20045 (put 'orgtbl-self-insert-command 'delete-selection
20047 (not (run-hook-with-args-until-success
20048 'self-insert-uses-region-functions))))
20049 (put 'org-delete-char 'delete-selection 'supersede)
20050 (put 'org-delete-backward-char 'delete-selection 'supersede)
20051 (put 'org-yank 'delete-selection 'yank)
20053 ;; Make `flyspell-mode' delay after some commands
20054 (put 'org-self-insert-command 'flyspell-delayed t)
20055 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20056 (put 'org-delete-char 'flyspell-delayed t)
20057 (put 'org-delete-backward-char 'flyspell-delayed t)
20059 ;; Make pabbrev-mode expand after Org mode commands
20060 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20061 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20063 (defun org-transpose-words ()
20064 "Transpose words for Org.
20065 This uses the `org-mode-transpose-word-syntax-table' syntax
20066 table, which interprets characters in `org-emphasis-alist' as
20067 word constituents."
20069 (with-syntax-table org-mode-transpose-word-syntax-table
20070 (call-interactively 'transpose-words)))
20071 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20073 (defvar org-ctrl-c-ctrl-c-hook nil
20074 "Hook for functions attaching themselves to `C-c C-c'.
20076 This can be used to add additional functionality to the C-c C-c
20077 key which executes context-dependent commands. This hook is run
20078 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20079 run after the last test.
20081 Each function will be called with no arguments. The function
20082 must check if the context is appropriate for it to act. If yes,
20083 it should do its thing and then return a non-nil value. If the
20084 context is wrong, just do nothing and return nil.")
20086 (defvar org-ctrl-c-ctrl-c-final-hook nil
20087 "Hook for functions attaching themselves to `C-c C-c'.
20089 This can be used to add additional functionality to the C-c C-c
20090 key which executes context-dependent commands. This hook is run
20091 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20092 before the first test.
20094 Each function will be called with no arguments. The function
20095 must check if the context is appropriate for it to act. If yes,
20096 it should do its thing and then return a non-nil value. If the
20097 context is wrong, just do nothing and return nil.")
20099 (defvar org-tab-first-hook nil
20100 "Hook for functions to attach themselves to TAB.
20101 See `org-ctrl-c-ctrl-c-hook' for more information.
20102 This hook runs as the first action when TAB is pressed, even before
20103 `org-cycle' messes around with the `outline-regexp' to cater for
20104 inline tasks and plain list item folding.
20105 If any function in this hook returns t, any other actions that
20106 would have been caused by TAB (such as table field motion or visibility
20107 cycling) will not occur.")
20109 (defvar org-tab-after-check-for-table-hook nil
20110 "Hook for functions to attach themselves to TAB.
20111 See `org-ctrl-c-ctrl-c-hook' for more information.
20112 This hook runs after it has been established that the cursor is not in a
20113 table, but before checking if the cursor is in a headline or if global cycling
20115 If any function in this hook returns t, not other actions like visibility
20116 cycling will be done.")
20118 (defvar org-tab-after-check-for-cycling-hook nil
20119 "Hook for functions to attach themselves to TAB.
20120 See `org-ctrl-c-ctrl-c-hook' for more information.
20121 This hook runs after it has been established that not table field motion and
20122 not visibility should be done because of current context. This is probably
20123 the place where a package like yasnippets can hook in.")
20125 (defvar org-tab-before-tab-emulation-hook nil
20126 "Hook for functions to attach themselves to TAB.
20127 See `org-ctrl-c-ctrl-c-hook' for more information.
20128 This hook runs after every other options for TAB have been exhausted, but
20129 before indentation and \t insertion takes place.")
20131 (defvar org-metaleft-hook nil
20132 "Hook for functions attaching themselves to `M-left'.
20133 See `org-ctrl-c-ctrl-c-hook' for more information.")
20134 (defvar org-metaright-hook nil
20135 "Hook for functions attaching themselves to `M-right'.
20136 See `org-ctrl-c-ctrl-c-hook' for more information.")
20137 (defvar org-metaup-hook nil
20138 "Hook for functions attaching themselves to `M-up'.
20139 See `org-ctrl-c-ctrl-c-hook' for more information.")
20140 (defvar org-metadown-hook nil
20141 "Hook for functions attaching themselves to `M-down'.
20142 See `org-ctrl-c-ctrl-c-hook' for more information.")
20143 (defvar org-shiftmetaleft-hook nil
20144 "Hook for functions attaching themselves to `M-S-left'.
20145 See `org-ctrl-c-ctrl-c-hook' for more information.")
20146 (defvar org-shiftmetaright-hook nil
20147 "Hook for functions attaching themselves to `M-S-right'.
20148 See `org-ctrl-c-ctrl-c-hook' for more information.")
20149 (defvar org-shiftmetaup-hook nil
20150 "Hook for functions attaching themselves to `M-S-up'.
20151 See `org-ctrl-c-ctrl-c-hook' for more information.")
20152 (defvar org-shiftmetadown-hook nil
20153 "Hook for functions attaching themselves to `M-S-down'.
20154 See `org-ctrl-c-ctrl-c-hook' for more information.")
20155 (defvar org-metareturn-hook nil
20156 "Hook for functions attaching themselves to `M-RET'.
20157 See `org-ctrl-c-ctrl-c-hook' for more information.")
20158 (defvar org-shiftup-hook nil
20159 "Hook for functions attaching themselves to `S-up'.
20160 See `org-ctrl-c-ctrl-c-hook' for more information.")
20161 (defvar org-shiftup-final-hook nil
20162 "Hook for functions attaching themselves to `S-up'.
20163 This one runs after all other options except shift-select have been excluded.
20164 See `org-ctrl-c-ctrl-c-hook' for more information.")
20165 (defvar org-shiftdown-hook nil
20166 "Hook for functions attaching themselves to `S-down'.
20167 See `org-ctrl-c-ctrl-c-hook' for more information.")
20168 (defvar org-shiftdown-final-hook nil
20169 "Hook for functions attaching themselves to `S-down'.
20170 This one runs after all other options except shift-select have been excluded.
20171 See `org-ctrl-c-ctrl-c-hook' for more information.")
20172 (defvar org-shiftleft-hook nil
20173 "Hook for functions attaching themselves to `S-left'.
20174 See `org-ctrl-c-ctrl-c-hook' for more information.")
20175 (defvar org-shiftleft-final-hook nil
20176 "Hook for functions attaching themselves to `S-left'.
20177 This one runs after all other options except shift-select have been excluded.
20178 See `org-ctrl-c-ctrl-c-hook' for more information.")
20179 (defvar org-shiftright-hook nil
20180 "Hook for functions attaching themselves to `S-right'.
20181 See `org-ctrl-c-ctrl-c-hook' for more information.")
20182 (defvar org-shiftright-final-hook nil
20183 "Hook for functions attaching themselves to `S-right'.
20184 This one runs after all other options except shift-select have been excluded.
20185 See `org-ctrl-c-ctrl-c-hook' for more information.")
20187 (defun org-modifier-cursor-error ()
20188 "Throw an error, a modified cursor command was applied in wrong context."
20189 (user-error "This command is active in special context like tables, headlines or items"))
20191 (defun org-shiftselect-error ()
20192 "Throw an error because Shift-Cursor command was applied in wrong context."
20193 (if (and (boundp 'shift-select-mode) shift-select-mode)
20194 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20195 (user-error "This command works only in special context like headlines or timestamps")))
20197 (defun org-call-for-shift-select (cmd)
20198 (let ((this-command-keys-shift-translated t))
20199 (call-interactively cmd)))
20201 (defun org-shifttab (&optional arg)
20202 "Global visibility cycling or move to previous table field.
20203 Call `org-table-previous-field' within a table.
20204 When ARG is nil, cycle globally through visibility states.
20205 When ARG is a numeric prefix, show contents of this level."
20208 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20210 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20211 (message "Content view to level: %d" arg)
20212 (org-content (prefix-numeric-value arg2))
20213 (org-cycle-show-empty-lines t)
20214 (setq org-cycle-global-status 'overview)))
20215 (t (call-interactively 'org-global-cycle))))
20217 (defun org-shiftmetaleft ()
20218 "Promote subtree or delete table column.
20219 Calls `org-promote-subtree', `org-outdent-item-tree', or
20220 `org-table-delete-column', depending on context. See the
20221 individual commands for more information."
20224 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20225 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20226 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20227 ((if (not (org-region-active-p)) (org-at-item-p)
20228 (save-excursion (goto-char (region-beginning))
20230 (call-interactively 'org-outdent-item-tree))
20231 (t (org-modifier-cursor-error))))
20233 (defun org-shiftmetaright ()
20234 "Demote subtree or insert table column.
20235 Calls `org-demote-subtree', `org-indent-item-tree', or
20236 `org-table-insert-column', depending on context. See the
20237 individual commands for more information."
20240 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20241 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20242 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20243 ((if (not (org-region-active-p)) (org-at-item-p)
20244 (save-excursion (goto-char (region-beginning))
20246 (call-interactively 'org-indent-item-tree))
20247 (t (org-modifier-cursor-error))))
20249 (defun org-shiftmetaup (&optional _arg)
20250 "Drag the line at point up.
20251 In a table, kill the current row.
20252 On a clock timestamp, update the value of the timestamp like `S-<up>'
20253 but also adjust the previous clocked item in the clock history.
20254 Everywhere else, drag the line at point up."
20257 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20258 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20259 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20260 (call-interactively 'org-timestamp-up)))
20261 (t (call-interactively 'org-drag-line-backward))))
20263 (defun org-shiftmetadown (&optional _arg)
20264 "Drag the line at point down.
20265 In a table, insert an empty row at the current line.
20266 On a clock timestamp, update the value of the timestamp like `S-<down>'
20267 but also adjust the previous clocked item in the clock history.
20268 Everywhere else, drag the line at point down."
20271 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20272 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20273 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20274 (call-interactively 'org-timestamp-down)))
20275 (t (call-interactively 'org-drag-line-forward))))
20277 (defsubst org-hidden-tree-error ()
20279 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20281 (defun org-metaleft (&optional _arg)
20282 "Promote heading, list item at point or move table column left.
20284 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20285 depending on context. With no specific context, calls the Emacs
20286 default `backward-word'. See the individual commands for more
20289 This function runs the hook `org-metaleft-hook' as a first step,
20290 and returns at first non-nil value."
20293 ((run-hook-with-args-until-success 'org-metaleft-hook))
20294 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20295 ((org-with-limited-levels
20296 (or (org-at-heading-p)
20297 (and (org-region-active-p)
20299 (goto-char (region-beginning))
20300 (org-at-heading-p)))))
20301 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20302 (call-interactively 'org-do-promote))
20303 ;; At an inline task.
20304 ((org-at-heading-p)
20305 (call-interactively 'org-inlinetask-promote))
20306 ((or (org-at-item-p)
20307 (and (org-region-active-p)
20309 (goto-char (region-beginning))
20311 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20312 (call-interactively 'org-outdent-item))
20313 (t (call-interactively 'backward-word))))
20315 (defun org-metaright (&optional _arg)
20316 "Demote heading, list item at point or move table column right.
20318 In front of a drawer or a block keyword, indent it correctly.
20320 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20321 `org-indent-drawer' or `org-indent-block' depending on context.
20322 With no specific context, calls the Emacs default `forward-word'.
20323 See the individual commands for more information.
20325 This function runs the hook `org-metaright-hook' as a first step,
20326 and returns at first non-nil value."
20329 ((run-hook-with-args-until-success 'org-metaright-hook))
20330 ((org-at-table-p) (call-interactively 'org-table-move-column))
20331 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20332 ((org-at-block-p) (call-interactively 'org-indent-block))
20333 ((org-with-limited-levels
20334 (or (org-at-heading-p)
20335 (and (org-region-active-p)
20337 (goto-char (region-beginning))
20338 (org-at-heading-p)))))
20339 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20340 (call-interactively 'org-do-demote))
20341 ;; At an inline task.
20342 ((org-at-heading-p)
20343 (call-interactively 'org-inlinetask-demote))
20344 ((or (org-at-item-p)
20345 (and (org-region-active-p)
20347 (goto-char (region-beginning))
20349 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20350 (call-interactively 'org-indent-item))
20351 (t (call-interactively 'forward-word))))
20353 (defun org-check-for-hidden (what)
20354 "Check if there are hidden headlines/items in the current visual line.
20355 WHAT can be either `headlines' or `items'. If the current line is
20356 an outline or item heading and it has a folded subtree below it,
20357 this function returns t, nil otherwise."
20359 ((eq what 'headlines) org-outline-regexp-bol)
20360 ((eq what 'items) (org-item-beginning-re))
20361 (t (error "This should not happen"))))
20365 (unless (org-region-active-p)
20366 (setq beg (point-at-bol))
20367 (beginning-of-line 2)
20368 (while (and (not (eobp)) ;; this is like `next-line'
20369 (get-char-property (1- (point)) 'invisible))
20370 (beginning-of-line 2))
20373 (goto-char (point-at-eol))
20374 (setq end (max end (point)))
20375 (while (re-search-forward re end t)
20376 (when (get-char-property (match-beginning 0) 'invisible)
20380 (defun org-metaup (&optional _arg)
20381 "Move subtree up or move table row up.
20382 Calls `org-move-subtree-up' or `org-table-move-row' or
20383 `org-move-item-up', depending on context. See the individual commands
20384 for more information."
20387 ((run-hook-with-args-until-success 'org-metaup-hook))
20388 ((org-region-active-p)
20389 (let* ((a (min (region-beginning) (region-end)))
20390 (b (1- (max (region-beginning) (region-end))))
20391 (c (save-excursion (goto-char a)
20392 (move-beginning-of-line 0)))
20393 (d (save-excursion (goto-char a)
20394 (move-end-of-line 0) (point))))
20395 (transpose-regions a b c d)
20397 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20398 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20399 ((org-at-item-p) (call-interactively 'org-move-item-up))
20400 (t (org-drag-element-backward))))
20402 (defun org-metadown (&optional _arg)
20403 "Move subtree down or move table row down.
20404 Calls `org-move-subtree-down' or `org-table-move-row' or
20405 `org-move-item-down', depending on context. See the individual
20406 commands for more information."
20409 ((run-hook-with-args-until-success 'org-metadown-hook))
20410 ((org-region-active-p)
20411 (let* ((a (min (region-beginning) (region-end)))
20412 (b (max (region-beginning) (region-end)))
20413 (c (save-excursion (goto-char b)
20414 (move-beginning-of-line 1)))
20415 (d (save-excursion (goto-char b)
20416 (move-end-of-line 1) (1+ (point)))))
20417 (transpose-regions a b c d)
20419 ((org-at-table-p) (call-interactively 'org-table-move-row))
20420 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20421 ((org-at-item-p) (call-interactively 'org-move-item-down))
20422 (t (org-drag-element-forward))))
20424 (defun org-shiftup (&optional arg)
20425 "Increase item in timestamp or increase priority of current headline.
20426 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20427 depending on context. See the individual commands for more information."
20430 ((run-hook-with-args-until-success 'org-shiftup-hook))
20431 ((and org-support-shift-select (org-region-active-p))
20432 (org-call-for-shift-select 'previous-line))
20433 ((org-at-timestamp-p 'lax)
20434 (call-interactively (if org-edit-timestamp-down-means-later
20435 'org-timestamp-down 'org-timestamp-up)))
20436 ((and (not (eq org-support-shift-select 'always))
20437 org-enable-priority-commands
20438 (org-at-heading-p))
20439 (call-interactively 'org-priority-up))
20440 ((and (not org-support-shift-select) (org-at-item-p))
20441 (call-interactively 'org-previous-item))
20442 ((org-clocktable-try-shift 'up arg))
20443 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20444 (org-support-shift-select
20445 (org-call-for-shift-select 'previous-line))
20446 (t (org-shiftselect-error))))
20448 (defun org-shiftdown (&optional arg)
20449 "Decrease item in timestamp or decrease priority of current headline.
20450 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20451 depending on context. See the individual commands for more information."
20454 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20455 ((and org-support-shift-select (org-region-active-p))
20456 (org-call-for-shift-select 'next-line))
20457 ((org-at-timestamp-p 'lax)
20458 (call-interactively (if org-edit-timestamp-down-means-later
20459 'org-timestamp-up 'org-timestamp-down)))
20460 ((and (not (eq org-support-shift-select 'always))
20461 org-enable-priority-commands
20462 (org-at-heading-p))
20463 (call-interactively 'org-priority-down))
20464 ((and (not org-support-shift-select) (org-at-item-p))
20465 (call-interactively 'org-next-item))
20466 ((org-clocktable-try-shift 'down arg))
20467 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20468 (org-support-shift-select
20469 (org-call-for-shift-select 'next-line))
20470 (t (org-shiftselect-error))))
20472 (defun org-shiftright (&optional arg)
20473 "Cycle the thing at point or in the current line, depending on context.
20474 Depending on context, this does one of the following:
20476 - switch a timestamp at point one day into the future
20477 - on a headline, switch to the next TODO keyword.
20478 - on an item, switch entire list to the next bullet type
20479 - on a property line, switch to the next allowed value
20480 - on a clocktable definition line, move time block into the future"
20483 ((run-hook-with-args-until-success 'org-shiftright-hook))
20484 ((and org-support-shift-select (org-region-active-p))
20485 (org-call-for-shift-select 'forward-char))
20486 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20487 ((and (not (eq org-support-shift-select 'always))
20488 (org-at-heading-p))
20489 (let ((org-inhibit-logging
20490 (not org-treat-S-cursor-todo-selection-as-state-change))
20491 (org-inhibit-blocking
20492 (not org-treat-S-cursor-todo-selection-as-state-change)))
20493 (org-call-with-arg 'org-todo 'right)))
20494 ((or (and org-support-shift-select
20495 (not (eq org-support-shift-select 'always))
20496 (org-at-item-bullet-p))
20497 (and (not org-support-shift-select) (org-at-item-p)))
20498 (org-call-with-arg 'org-cycle-list-bullet nil))
20499 ((and (not (eq org-support-shift-select 'always))
20500 (org-at-property-p))
20501 (call-interactively 'org-property-next-allowed-value))
20502 ((org-clocktable-try-shift 'right arg))
20503 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20504 (org-support-shift-select
20505 (org-call-for-shift-select 'forward-char))
20506 (t (org-shiftselect-error))))
20508 (defun org-shiftleft (&optional arg)
20509 "Cycle the thing at point or in the current line, depending on context.
20510 Depending on context, this does one of the following:
20512 - switch a timestamp at point one day into the past
20513 - on a headline, switch to the previous TODO keyword.
20514 - on an item, switch entire list to the previous bullet type
20515 - on a property line, switch to the previous allowed value
20516 - on a clocktable definition line, move time block into the past"
20519 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20520 ((and org-support-shift-select (org-region-active-p))
20521 (org-call-for-shift-select 'backward-char))
20522 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20523 ((and (not (eq org-support-shift-select 'always))
20524 (org-at-heading-p))
20525 (let ((org-inhibit-logging
20526 (not org-treat-S-cursor-todo-selection-as-state-change))
20527 (org-inhibit-blocking
20528 (not org-treat-S-cursor-todo-selection-as-state-change)))
20529 (org-call-with-arg 'org-todo 'left)))
20530 ((or (and org-support-shift-select
20531 (not (eq org-support-shift-select 'always))
20532 (org-at-item-bullet-p))
20533 (and (not org-support-shift-select) (org-at-item-p)))
20534 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20535 ((and (not (eq org-support-shift-select 'always))
20536 (org-at-property-p))
20537 (call-interactively 'org-property-previous-allowed-value))
20538 ((org-clocktable-try-shift 'left arg))
20539 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20540 (org-support-shift-select
20541 (org-call-for-shift-select 'backward-char))
20542 (t (org-shiftselect-error))))
20544 (defun org-shiftcontrolright ()
20545 "Switch to next TODO set."
20548 ((and org-support-shift-select (org-region-active-p))
20549 (org-call-for-shift-select 'forward-word))
20550 ((and (not (eq org-support-shift-select 'always))
20551 (org-at-heading-p))
20552 (org-call-with-arg 'org-todo 'nextset))
20553 (org-support-shift-select
20554 (org-call-for-shift-select 'forward-word))
20555 (t (org-shiftselect-error))))
20557 (defun org-shiftcontrolleft ()
20558 "Switch to previous TODO set."
20561 ((and org-support-shift-select (org-region-active-p))
20562 (org-call-for-shift-select 'backward-word))
20563 ((and (not (eq org-support-shift-select 'always))
20564 (org-at-heading-p))
20565 (org-call-with-arg 'org-todo 'previousset))
20566 (org-support-shift-select
20567 (org-call-for-shift-select 'backward-word))
20568 (t (org-shiftselect-error))))
20570 (defun org-shiftcontrolup (&optional n)
20571 "Change timestamps synchronously up in CLOCK log lines.
20572 Optional argument N tells to change by that many units."
20574 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20575 (let (org-support-shift-select)
20576 (org-clock-timestamps-up n))
20577 (user-error "Not at a clock log")))
20579 (defun org-shiftcontroldown (&optional n)
20580 "Change timestamps synchronously down in CLOCK log lines.
20581 Optional argument N tells to change by that many units."
20583 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20584 (let (org-support-shift-select)
20585 (org-clock-timestamps-down n))
20586 (user-error "Not at a clock log")))
20588 (defun org-increase-number-at-point (&optional inc)
20589 "Increment the number at point.
20590 With an optional prefix numeric argument INC, increment using
20591 this numeric value."
20593 (if (not (number-at-point))
20594 (user-error "Not on a number")
20595 (unless inc (setq inc 1))
20596 (let ((pos (point))
20597 (beg (skip-chars-backward "-+^/*0-9eE."))
20598 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20599 (setq nap (buffer-substring-no-properties
20600 (+ pos beg) (+ pos beg end)))
20601 (delete-region (+ pos beg) (+ pos beg end))
20602 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20603 (when (org-at-table-p)
20605 (org-table-end-of-field 1))))
20607 (defun org-decrease-number-at-point (&optional inc)
20608 "Decrement the number at point.
20609 With an optional prefix numeric argument INC, decrement using
20610 this numeric value."
20612 (org-increase-number-at-point (- (or inc 1))))
20614 (defun org-ctrl-c-ret ()
20615 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20618 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20619 (t (call-interactively 'org-insert-heading))))
20621 (defun org-find-visible ()
20623 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20624 (get-char-property s 'invisible)))
20626 (defun org-find-invisible ()
20628 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20629 (not (get-char-property s 'invisible))))
20632 (defun org-copy-visible (beg end)
20633 "Copy the visible parts of the region."
20636 (while (/= beg end)
20637 (when (get-char-property beg 'invisible)
20638 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20639 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20640 (setq result (concat result (buffer-substring beg next)))
20642 (kill-new result)))
20644 (defun org-copy-special ()
20645 "Copy region in table or copy current subtree.
20646 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20647 context. See the individual commands for more information."
20649 (call-interactively
20650 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20652 (defun org-cut-special ()
20653 "Cut region in table or cut current subtree.
20654 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20655 context. See the individual commands for more information."
20657 (call-interactively
20658 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20660 (defun org-paste-special (arg)
20661 "Paste rectangular region into table, or past subtree relative to level.
20662 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20663 See the individual commands for more information."
20665 (if (org-at-table-p)
20666 (org-table-paste-rectangle)
20667 (org-paste-subtree arg)))
20669 (defun org-edit-special (&optional arg)
20670 "Call a special editor for the element at point.
20671 When at a table, call the formula editor with `org-table-edit-formulas'.
20672 When in a source code block, call `org-edit-src-code'.
20673 When in a fixed-width region, call `org-edit-fixed-width-region'.
20674 When in an export block, call `org-edit-export-block'.
20675 When in a LaTeX environment, call `org-edit-latex-environment'.
20676 When at an #+INCLUDE keyword, visit the included file.
20677 When at a footnote reference, call `org-edit-footnote-reference'
20678 On a link, call `ffap' to visit the link at point.
20679 Otherwise, return a user error."
20681 (let ((element (org-element-at-point)))
20682 (barf-if-buffer-read-only)
20683 (pcase (org-element-type element)
20685 (if (not arg) (org-edit-src-code)
20686 (let* ((info (org-babel-get-src-block-info))
20687 (lang (nth 0 info))
20688 (params (nth 2 info))
20689 (session (cdr (assq :session params))))
20690 (if (not session) (org-edit-src-code)
20691 ;; At a src-block with a session and function called with
20692 ;; an ARG: switch to the buffer related to the inferior
20695 (funcall (intern (concat "org-babel-prep-session:" lang))
20696 session params))))))
20698 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20699 (org-open-link-from-string
20702 (let ((value (org-element-property :value element)))
20703 (cond ((org-file-url-p value)
20704 (user-error "The file is specified as a URL, cannot be edited"))
20705 ((not (org-string-nw-p value))
20706 (user-error "No file to edit"))
20707 ((string-match "\\`\"\\(.*?\\)\"" value)
20708 (match-string 1 value))
20709 ((string-match "\\`[^ \t\"]\\S-*" value)
20710 (match-string 0 value))
20711 (t (user-error "No valid file specified")))))))
20712 (user-error "No special environment to edit here")))
20714 (if (eq (org-element-property :type element) 'table.el)
20715 (org-edit-table.el)
20716 (call-interactively 'org-table-edit-formulas)))
20717 ;; Only Org tables contain `table-row' type elements.
20718 (`table-row (call-interactively 'org-table-edit-formulas))
20719 (`example-block (org-edit-src-code))
20720 (`export-block (org-edit-export-block))
20721 (`fixed-width (org-edit-fixed-width-region))
20722 (`latex-environment (org-edit-latex-environment))
20724 ;; No notable element at point. Though, we may be at a link or
20725 ;; a footnote reference, which are objects. Thus, scan deeper.
20726 (let ((context (org-element-context element)))
20727 (pcase (org-element-type context)
20728 (`footnote-reference (org-edit-footnote-reference))
20729 (`inline-src-block (org-edit-inline-src-code))
20730 (`link (call-interactively #'ffap))
20731 (_ (user-error "No special environment to edit here"))))))))
20733 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20734 (defun org-ctrl-c-ctrl-c (&optional arg)
20735 "Set tags in headline, or update according to changed information at point.
20737 This command does many different things, depending on context:
20739 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20740 this is what we do.
20742 - If the cursor is on a statistics cookie, update it.
20744 - If the cursor is in a headline, prompt for tags and insert them
20745 into the current line, aligned to `org-tags-column'. When called
20746 with prefix arg, realign all tags in the current buffer.
20748 - If the cursor is in one of the special #+KEYWORD lines, this
20749 triggers scanning the buffer for these lines and updating the
20752 - If the cursor is inside a table, realign the table. This command
20753 works even if the automatic table editor has been turned off.
20755 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20758 - If the cursor is at a footnote reference or definition, jump to
20759 the corresponding definition or references, respectively.
20761 - If the cursor is a the beginning of a dynamic block, update it.
20763 - If the current buffer is a capture buffer, close note and file it.
20765 - If the cursor is on a <<<target>>>, update radio targets and
20766 corresponding links in this buffer.
20768 - If the cursor is on a numbered item in a plain list, renumber the
20771 - If the cursor is on a checkbox, toggle it.
20773 - If the cursor is on a code block, evaluate it. The variable
20774 `org-confirm-babel-evaluate' can be used to control prompting
20775 before code block evaluation, by default every code block
20776 evaluation requires confirmation. Code block evaluation can be
20777 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20780 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20781 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20782 (org-remove-occur-highlights)
20783 (message "Temporary highlights/overlays removed from current buffer"))
20784 ((and (local-variable-p 'org-finish-function)
20785 (fboundp org-finish-function))
20786 (funcall org-finish-function))
20787 ((org-babel-hash-at-point))
20788 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20791 (org-element-lineage
20792 (org-element-context)
20793 ;; Limit to supported contexts.
20794 '(babel-call clock dynamic-block footnote-definition
20795 footnote-reference inline-babel-call inline-src-block
20796 inlinetask item keyword node-property paragraph
20797 plain-list planning property-drawer radio-target
20798 src-block statistics-cookie table table-cell table-row
20801 (type (org-element-type context)))
20802 ;; For convenience: at the first line of a paragraph on the same
20803 ;; line as an item, apply function on that item instead.
20804 (when (eq type 'paragraph)
20805 (let ((parent (org-element-property :parent context)))
20806 (when (and (eq (org-element-type parent) 'item)
20807 (= (line-beginning-position)
20808 (org-element-property :begin parent)))
20809 (setq context parent)
20810 (setq type 'item))))
20811 ;; Act according to type of element or object at point.
20813 ;; Do nothing on a blank line, except if it is contained in
20814 ;; a src block. Hence, we first check if point is in such
20815 ;; a block and then if it is at a blank line.
20817 ((or `inline-src-block `src-block)
20818 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20819 (org-babel-eval-wipe-error-buffer)
20820 (org-babel-execute-src-block
20821 current-prefix-arg (org-babel-get-src-block-info nil context))))
20822 ((guard (org-match-line "[ \t]*$"))
20823 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20825 (substitute-command-keys
20826 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20827 ((or `babel-call `inline-babel-call)
20828 (let ((info (org-babel-lob-get-info context)))
20829 (when info (org-babel-execute-src-block nil info))))
20830 (`clock (org-clock-update-time-maybe))
20833 (goto-char (org-element-property :post-affiliated context))
20834 (org-update-dblock)))
20835 (`footnote-definition
20836 (goto-char (org-element-property :post-affiliated context))
20837 (call-interactively 'org-footnote-action))
20838 (`footnote-reference (call-interactively #'org-footnote-action))
20839 ((or `headline `inlinetask)
20840 (save-excursion (goto-char (org-element-property :begin context))
20841 (call-interactively #'org-set-tags)))
20843 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20844 ;; unconditionally, whereas `C-u' will toggle its presence.
20845 ;; Without a universal argument, if the item has a checkbox,
20846 ;; toggle it. Otherwise repair the list.
20847 (let* ((box (org-element-property :checkbox context))
20848 (struct (org-element-property :structure context))
20849 (old-struct (copy-tree struct))
20850 (parents (org-list-parents-alist struct))
20851 (prevs (org-list-prevs-alist struct))
20852 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20853 (org-list-set-checkbox
20854 (org-element-property :begin context) struct
20855 (cond ((equal arg '(16)) "[-]")
20856 ((and (not box) (equal arg '(4))) "[ ]")
20857 ((or (not box) (equal arg '(4))) nil)
20858 ((eq box 'on) "[ ]")
20860 ;; Mimic `org-list-write-struct' but with grabbing a return
20861 ;; value from `org-list-struct-fix-box'.
20862 (org-list-struct-fix-ind struct parents 2)
20863 (org-list-struct-fix-item-end struct)
20864 (org-list-struct-fix-bul struct prevs)
20865 (org-list-struct-fix-ind struct parents)
20867 (org-list-struct-fix-box struct parents prevs orderedp)))
20868 (if (and box (equal struct old-struct))
20869 (if (equal arg '(16))
20870 (message "Checkboxes already reset")
20871 (user-error "Cannot toggle this checkbox: %s"
20873 "all subitems checked"
20874 "unchecked subitems")))
20875 (org-list-struct-apply-struct struct old-struct)
20876 (org-update-checkbox-count-maybe))
20878 (message "Checkboxes were removed due to empty box at line %d"
20879 (org-current-line block-item))))))
20881 (let ((org-inhibit-startup-visibility-stuff t)
20882 (org-startup-align-all-tables nil))
20883 (when (boundp 'org-table-coordinate-overlays)
20884 (mapc #'delete-overlay org-table-coordinate-overlays)
20885 (setq org-table-coordinate-overlays nil))
20886 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20887 (message "Local setup has been refreshed"))
20889 ;; At a plain list, with a double C-u argument, set
20890 ;; checkboxes of each item to "[-]", whereas a single one
20891 ;; will toggle their presence according to the state of the
20892 ;; first item in the list. Without an argument, repair the
20894 (let* ((begin (org-element-property :contents-begin context))
20895 (beginm (move-marker (make-marker) begin))
20896 (struct (org-element-property :structure context))
20897 (old-struct (copy-tree struct))
20898 (first-box (save-excursion
20900 (looking-at org-list-full-item-re)
20901 (match-string-no-properties 3)))
20902 (new-box (cond ((equal arg '(16)) "[-]")
20903 ((equal arg '(4)) (unless first-box "[ ]"))
20904 ((equal first-box "[X]") "[ ]")
20909 (org-list-get-all-items
20910 begin struct (org-list-prevs-alist struct)))
20911 (org-list-set-checkbox pos struct new-box)))
20912 ((and first-box (eq (point) begin))
20913 ;; For convenience, when point is at bol on the first
20914 ;; item of the list and no argument is provided, simply
20915 ;; toggle checkbox of that item, if any.
20916 (org-list-set-checkbox begin struct new-box)))
20917 (org-list-write-struct
20918 struct (org-list-parents-alist struct) old-struct)
20919 (org-update-checkbox-count-maybe)
20920 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20921 ((or `property-drawer `node-property)
20922 (call-interactively #'org-property-action))
20924 (call-interactively #'org-update-radio-target-regexp))
20925 (`statistics-cookie
20926 (call-interactively #'org-update-statistics-cookies))
20927 ((or `table `table-cell `table-row)
20928 ;; At a table, recalculate every field and align it. Also
20929 ;; send the table if necessary. If the table has
20930 ;; a `table.el' type, just give up. At a table row or cell,
20931 ;; maybe recalculate line but always align table.
20932 (if (eq (org-element-property :type context) 'table.el)
20933 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20934 Use `\\[org-edit-special]' to edit table.el tables"))
20935 (if (or (eq type 'table)
20936 ;; Check if point is at a TBLFM line.
20937 (and (eq type 'table-row)
20938 (= (point) (org-element-property :end context))))
20940 (if (org-at-TBLFM-p)
20941 (progn (require 'org-table)
20942 (org-table-calc-current-TBLFM))
20943 (goto-char (org-element-property :contents-begin context))
20944 (org-call-with-arg 'org-table-recalculate (or arg t))
20945 (orgtbl-send-table 'maybe)))
20946 (org-table-maybe-eval-formula)
20947 (cond (arg (call-interactively #'org-table-recalculate))
20948 ((org-table-maybe-recalculate-line))
20949 (t (org-table-align))))))
20950 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20951 (org-timestamp-change 0 'day))
20952 ((and `nil (guard (org-at-heading-p)))
20953 ;; When point is on an unsupported object type, we can miss
20954 ;; the fact that it also is at a heading. Handle it here.
20955 (call-interactively #'org-set-tags))
20957 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20960 (substitute-command-keys
20961 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20963 (defun org-mode-restart ()
20965 (let ((indent-status (bound-and-true-p org-indent-mode)))
20966 (funcall major-mode)
20967 (hack-local-variables)
20968 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20969 (org-indent-mode -1))
20970 (org-reset-file-cache))
20971 (message "%s restarted" major-mode))
20973 (defun org-kill-note-or-show-branches ()
20974 "Abort storing current note, or call `outline-show-branches'."
20976 (if (not org-finish-function)
20978 (outline-hide-subtree)
20979 (call-interactively 'outline-show-branches))
20980 (let ((org-note-abort t))
20981 (funcall org-finish-function))))
20983 (defun org-delete-indentation (&optional arg)
20984 "Join current line to previous and fix whitespace at join.
20986 If previous line is a headline add to headline title. Otherwise
20987 the function calls `delete-indentation'.
20989 With a non-nil optional argument, join it to the following one."
20991 (if (save-excursion
20992 (beginning-of-line (if arg 1 0))
20993 (let ((case-fold-search nil))
20994 (looking-at org-complex-heading-regexp)))
20996 (let ((tags-column (when (match-beginning 5)
20997 (save-excursion (goto-char (match-beginning 5))
20998 (current-column))))
20999 (string (concat " " (progn (when arg (forward-line 1))
21000 (org-trim (delete-and-extract-region
21001 (line-beginning-position)
21002 (line-end-position)))))))
21003 (unless (bobp) (delete-region (point) (1- (point))))
21004 (goto-char (or (match-end 4)
21005 (match-beginning 5)
21007 (skip-chars-backward " \t")
21008 (save-excursion (insert string))
21009 ;; Adjust alignment of tags.
21011 ((not tags-column)) ;no tags
21012 (org-auto-align-tags (org-set-tags nil t))
21013 (t (org--align-tags-here tags-column)))) ;preserve tags column
21014 (delete-indentation arg)))
21016 (defun org-open-line (n)
21017 "Insert a new row in tables, call `open-line' elsewhere.
21018 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21019 As a special case, when a document starts with a table, allow to
21020 call `open-line' on the very first character."
21022 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21023 (org-table-insert-row)
21026 (defun org-return (&optional indent)
21027 "Goto next table row or insert a newline.
21029 Calls `org-table-next-row' or `newline', depending on context.
21031 When optional INDENT argument is non-nil, call
21032 `newline-and-indent' instead of `newline'.
21034 When `org-return-follows-link' is non-nil and point is on
21035 a timestamp or a link, call `org-open-at-point'. However, it
21036 will not happen if point is in a table or on a \"dead\"
21037 object (e.g., within a comment). In these case, you need to use
21038 `org-open-at-point' directly."
21040 (let ((context (if org-return-follows-link (org-element-context)
21041 (org-element-at-point))))
21043 ;; In a table, call `org-table-next-row'. However, before first
21044 ;; column or after last one, split the table.
21045 ((or (and (eq (org-element-type context) 'table)
21046 (>= (point) (org-element-property :contents-begin context))
21047 (< (point) (org-element-property :contents-end context)))
21048 (org-element-lineage context '(table-row table-cell) t))
21049 (if (or (looking-at-p "[ \t]*$")
21050 (save-excursion (skip-chars-backward " \t") (bolp)))
21052 (org-table-justify-field-maybe)
21053 (call-interactively #'org-table-next-row)))
21054 ;; On a link or a timestamp, call `org-open-at-point' if
21055 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21056 ;; locations, e.g., in a comment, as `org-open-at-point'.
21057 ((and org-return-follows-link
21058 (or (org-in-regexp org-ts-regexp-both nil t)
21059 (org-in-regexp org-tsr-regexp-both nil t)
21060 (org-in-regexp org-any-link-re nil t)))
21061 (call-interactively #'org-open-at-point))
21062 ;; Insert newline in heading, but preserve tags.
21064 (save-excursion (beginning-of-line)
21065 (let ((case-fold-search nil))
21066 (looking-at org-complex-heading-regexp))))
21067 ;; At headline. Split line. However, if point is on keyword,
21068 ;; priority cookie or tags, do not break any of them: add
21069 ;; a newline after the headline instead.
21070 (let ((tags-column (and (match-beginning 5)
21071 (save-excursion (goto-char (match-beginning 5))
21072 (current-column))))
21074 (when (and (match-end 4) (org-point-in-group (point) 4))
21075 (delete-and-extract-region (point) (match-end 4)))))
21076 ;; Adjust tag alignment.
21078 ((not (and tags-column string)))
21079 (org-auto-align-tags (org-set-tags nil t))
21080 (t (org--align-tags-here tags-column))) ;preserve tags column
21083 (if indent (newline-and-indent) (newline))
21084 (when string (save-excursion (insert (org-trim string))))))
21085 ;; In a list, make sure indenting keeps trailing text within.
21088 (org-element-lineage context '(item)))
21089 (let ((trailing-data
21090 (delete-and-extract-region (point) (line-end-position))))
21091 (newline-and-indent)
21092 (save-excursion (insert trailing-data))))
21093 (t (if indent (newline-and-indent) (newline))))))
21095 (defun org-return-indent ()
21096 "Goto next table row or insert a newline and indent.
21097 Calls `org-table-next-row' or `newline-and-indent', depending on
21098 context. See the individual commands for more information."
21102 (defun org-ctrl-c-star ()
21103 "Compute table, or change heading status of lines.
21104 Calls `org-table-recalculate' or `org-toggle-heading',
21105 depending on context."
21109 (call-interactively 'org-table-recalculate))
21111 ;; Convert all lines in region to list items
21112 (call-interactively 'org-toggle-heading))))
21114 (defun org-ctrl-c-minus ()
21115 "Insert separator line in table or modify bullet status of line.
21116 Also turns a plain line or a region of lines into list items.
21117 Calls `org-table-insert-hline', `org-toggle-item', or
21118 `org-cycle-list-bullet', depending on context."
21122 (call-interactively 'org-table-insert-hline))
21123 ((org-region-active-p)
21124 (call-interactively 'org-toggle-item))
21126 (call-interactively 'org-cycle-list-bullet))
21128 (call-interactively 'org-toggle-item))))
21130 (defun org-toggle-heading (&optional nstars)
21131 "Convert headings to normal text, or items or text to headings.
21132 If there is no active region, only convert the current line.
21134 With a `\\[universal-argument]' prefix, convert the whole list at
21135 point into heading.
21139 - If the first non blank line is a headline, remove the stars
21140 from all headlines in the region.
21142 - If it is a normal line, turn each and every normal line (i.e.,
21143 not an heading or an item) in the region into headings. If you
21144 want to convert only the first line of this region, use one
21145 universal prefix argument.
21147 - If it is a plain list item, turn all plain list items into headings.
21149 When converting a line into a heading, the number of stars is chosen
21150 such that the lines become children of the current entry. However,
21151 when a numeric prefix argument is given, its value determines the
21152 number of stars to add."
21156 ;; Return beginning of first non-blank line, starting from
21161 (while (org-at-comment-p) (forward-line))
21162 (skip-chars-forward " \r\t\n")
21165 ;; Determine boundaries of changes. If a universal prefix has
21166 ;; been given, put the list in a region. If region ends at a bol,
21167 ;; do not consider the last line to be in the region.
21169 (when (and current-prefix-arg (org-at-item-p))
21170 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21171 (org-mark-element))
21173 (if (org-region-active-p)
21174 (setq beg (funcall skip-blanks (region-beginning))
21175 end (copy-marker (save-excursion
21176 (goto-char (region-end))
21177 (if (bolp) (point) (point-at-eol)))))
21178 (setq beg (funcall skip-blanks (point-at-bol))
21179 end (copy-marker (point-at-eol))))
21180 ;; Ensure inline tasks don't count as headings.
21181 (org-with-limited-levels
21185 ;; Case 1. Started at an heading: de-star headings.
21186 ((org-at-heading-p)
21187 (while (< (point) end)
21188 (when (org-at-heading-p t)
21189 (looking-at org-outline-regexp) (replace-match "")
21192 ;; Case 2. Started at an item: change items into headlines.
21193 ;; One star will be added by `org-list-to-subtree'.
21195 (while (< (point) end)
21196 (when (org-at-item-p)
21197 ;; Pay attention to cases when region ends before list.
21198 (let* ((struct (org-list-struct))
21200 (min (org-list-get-bottom-point struct) (1+ end))))
21202 (narrow-to-region (point) list-end)
21203 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21206 ;; Case 3. Started at normal text: make every line an heading,
21207 ;; skipping headlines and items.
21210 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21212 (cond (nstars "") ; stars from prefix only
21213 ((equal stars "") "*") ; before first heading
21214 (org-odd-levels-only "**") ; inside heading, odd
21215 (t "*"))) ; inside heading, oddeven
21216 (rpl (concat stars add-stars " "))
21217 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21218 (while (< (point) (if (equal nstars '(4)) lend end))
21219 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21220 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21221 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21222 (forward-line)))))))
21223 (unless toggled (message "Cannot toggle heading from here"))))
21225 (defun org-meta-return (&optional arg)
21226 "Insert a new heading or wrap a region in a table.
21227 Calls `org-insert-heading', `org-insert-item' or
21228 `org-table-wrap-region', depending on context. When called with
21229 an argument, unconditionally call `org-insert-heading'."
21231 (org-check-before-invisible-edit 'insert)
21232 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21233 (call-interactively (cond (arg #'org-insert-heading)
21234 ((org-at-table-p) #'org-table-wrap-region)
21235 ((org-in-item-p) #'org-insert-item)
21236 (t #'org-insert-heading)))))
21240 (defsubst org-in-subtree-not-table-p ()
21241 "Are we in a subtree and not in a table?"
21242 (and (not (org-before-first-heading-p))
21243 (not (org-at-table-p))))
21245 ;; Define the Org mode menus
21246 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21248 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21249 ["Next Field" org-cycle (org-at-table-p)]
21250 ["Previous Field" org-shifttab (org-at-table-p)]
21251 ["Next Row" org-return (org-at-table-p)]
21253 ["Blank Field" org-table-blank-field (org-at-table-p)]
21254 ["Edit Field" org-table-edit-field (org-at-table-p)]
21255 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21258 ["Move Column Left" org-metaleft (org-at-table-p)]
21259 ["Move Column Right" org-metaright (org-at-table-p)]
21260 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21261 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21263 ["Move Row Up" org-metaup (org-at-table-p)]
21264 ["Move Row Down" org-metadown (org-at-table-p)]
21265 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21266 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21267 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21269 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21271 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21272 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21273 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21274 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21277 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21278 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21279 ["Edit Formulas" org-edit-special (org-at-table-p)]
21281 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21282 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21283 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21285 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21287 ["Sum Column/Rectangle" org-table-sum
21288 (or (org-at-table-p) (org-region-active-p))]
21289 ["Which Column?" org-table-current-column (org-at-table-p)])
21291 org-table-toggle-formula-debugger
21292 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21293 ["Show Col/Row Numbers"
21294 org-table-toggle-coordinate-overlays
21296 :selected (bound-and-true-p org-table-overlay-coordinates)]
21298 ["Create" org-table-create (not (org-at-table-p))]
21299 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21300 ["Import from File" org-table-import (not (org-at-table-p))]
21301 ["Export to File" org-table-export (org-at-table-p)]
21303 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21306 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21307 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21309 (easy-menu-define org-org-menu org-mode-map "Org menu"
21312 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21313 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21314 ["Sparse Tree..." org-sparse-tree t]
21315 ["Reveal Context" org-reveal t]
21316 ["Show All" outline-show-all t]
21318 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21320 ["New Heading" org-insert-heading t]
21321 ("Navigate Headings"
21322 ["Up" outline-up-heading t]
21323 ["Next" outline-next-visible-heading t]
21324 ["Previous" outline-previous-visible-heading t]
21325 ["Next Same Level" outline-forward-same-level t]
21326 ["Previous Same Level" outline-backward-same-level t]
21328 ["Jump" org-goto t])
21330 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21332 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21333 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21335 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21336 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21337 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21339 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21341 ["Copy visible text" org-copy-visible t]
21343 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21344 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21345 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21346 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21348 ["Sort Region/Children" org-sort t]
21350 ["Convert to odd levels" org-convert-to-odd-levels t]
21351 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21353 ["Emphasis..." org-emphasize t]
21354 ["Edit Source Example" org-edit-special t]
21356 ["Footnote new/jump" org-footnote-action t]
21357 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21359 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21361 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21362 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21363 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21367 ["Store Link (Global)" org-store-link t]
21368 ["Find existing link to here" org-occur-link-in-agenda-files t]
21369 ["Insert Link" org-insert-link t]
21370 ["Follow Link" org-open-at-point t]
21372 ["Next link" org-next-link t]
21373 ["Previous link" org-previous-link t]
21375 ["Descriptive Links"
21376 org-toggle-link-display
21378 :selected org-descriptive-links
21381 org-toggle-link-display
21383 :selected (not org-descriptive-links)])
21386 ["TODO/DONE/-" org-todo t]
21388 ["Next keyword" org-shiftright (org-at-heading-p)]
21389 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21390 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21391 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21392 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21393 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21394 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21396 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21397 :selected org-enforce-todo-dependencies :style toggle :active t]
21398 "Settings for tree at point"
21399 ["Do Children sequentially" org-toggle-ordered-property :style radio
21400 :selected (org-entry-get nil "ORDERED")
21401 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21402 ["Do Children parallel" org-toggle-ordered-property :style radio
21403 :selected (not (org-entry-get nil "ORDERED"))
21404 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21406 ["Set Priority" org-priority t]
21407 ["Priority Up" org-shiftup t]
21408 ["Priority Down" org-shiftdown t]
21410 ["Get news from all feeds" org-feed-update-all t]
21411 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21412 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21413 ("TAGS and Properties"
21414 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21415 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21417 ["Set property" org-set-property (not (org-before-first-heading-p))]
21418 ["Column view of properties" org-columns t]
21419 ["Insert Column View DBlock" org-columns-insert-dblock t])
21420 ("Dates and Scheduling"
21421 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21422 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21424 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21425 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21426 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21427 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21428 ["Compute Time Range" org-evaluate-time-range t]
21429 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21430 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21432 ["Custom time format" org-toggle-time-stamp-overlays
21433 :style radio :selected org-display-custom-times]
21435 ["Goto Calendar" org-goto-calendar t]
21436 ["Date from Calendar" org-date-from-calendar t]
21438 ["Start/Restart Timer" org-timer-start t]
21439 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21440 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21441 ["Insert Timer String" org-timer t]
21442 ["Insert Timer Item" org-timer-item t])
21444 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21445 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21446 ["Clock out" org-clock-out t]
21447 ["Clock cancel" org-clock-cancel t]
21449 ["Mark as default task" org-clock-mark-default-task t]
21450 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21451 ["Goto running clock" org-clock-goto t]
21453 ["Display times" org-clock-display t]
21454 ["Create clock table" org-clock-report t]
21456 ["Record DONE time"
21457 (progn (setq org-log-done (not org-log-done))
21458 (message "Switching to %s will %s record a timestamp"
21459 (car org-done-keywords)
21460 (if org-log-done "automatically" "not")))
21461 :style toggle :selected org-log-done])
21463 ["Agenda Command..." org-agenda t]
21464 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21465 ("File List for Agenda")
21466 ("Special views current file"
21467 ["TODO Tree" org-show-todo-tree t]
21468 ["Check Deadlines" org-check-deadlines t]
21469 ["Tags/Property tree" org-match-sparse-tree t])
21471 ["Export/Publish..." org-export-dispatch t]
21473 ["Org CDLaTeX mode" org-cdlatex-mode :active (featurep 'cdlatex)
21474 :style toggle :selected org-cdlatex-mode]
21475 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21476 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21477 ["Modify math symbol" org-cdlatex-math-modify
21478 (org-inside-LaTeX-fragment-p)]
21479 ["Insert citation" org-reftex-citation t])
21482 ["Push Files and Views" org-mobile-push t]
21483 ["Get Captured and Flagged" org-mobile-pull t]
21484 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21486 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21489 ["Show Version" org-version t]
21490 ["Info Documentation" org-info t])
21492 ["Browse Org Group" org-customize t]
21494 ["Expand This Menu" org-create-customize-menu
21495 (fboundp 'customize-menu-create)])
21496 ["Send bug report" org-submit-bug-report t]
21499 ["Refresh setup current buffer" org-mode-restart t]
21500 ["Reload Org (after update)" org-reload t]
21501 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21504 (defun org-info (&optional node)
21505 "Read documentation for Org in the info system.
21506 With optional NODE, go directly to that node."
21508 (info (format "(org)%s" (or node ""))))
21511 (defun org-submit-bug-report ()
21512 "Submit a bug report on Org via mail.
21514 Don't hesitate to report any problems or inaccurate documentation.
21516 If you don't have setup sending mail from (X)Emacs, please copy the
21517 output buffer into your mail program, as it gives us important
21518 information about your Org version and configuration."
21520 (require 'reporter)
21521 (defvar reporter-prompt-for-summary-p)
21522 (org-load-modules-maybe)
21523 (org-require-autoloaded-modules)
21524 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21525 (reporter-submit-bug-report
21526 "emacs-orgmode@gnu.org"
21527 (org-version nil 'full)
21529 (save-window-excursion
21530 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21531 (delete-other-windows)
21533 (insert "You are about to submit a bug report to the Org mailing list.
21535 We would like to add your full Org and Outline configuration to the
21536 bug report. This greatly simplifies the work of the maintainer and
21537 other experts on the mailing list.
21539 HOWEVER, some variables you have customized may contain private
21540 information. The names of customers, colleagues, or friends, might
21541 appear in the form of file names, tags, todo states, or search strings.
21542 If you answer yes to the prompt, you might want to check and remove
21543 such private information before sending the email.")
21544 (add-text-properties (point-min) (point-max) '(face org-warning))
21545 (when (yes-or-no-p "Include your Org configuration ")
21549 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21550 (or (and (symbol-value v)
21551 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21553 (get v 'custom-type) (get v 'standard-value)
21554 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21556 (kill-buffer (get-buffer "*Warn about privacy*"))
21559 "Remember to cover the basics, that is, what you expected to happen and
21560 what in fact did happen. You don't know how to make a good report? See
21562 http://orgmode.org/manual/Feedback.html#Feedback
21564 Your bug report will be posted to the Org mailing list.
21565 ------------------------------------------------------------------------")
21567 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21568 (replace-match "\\1Bug: \\3 [\\2]")))))
21571 (defun org-install-agenda-files-menu ()
21572 (let ((bl (buffer-list)))
21575 (set-buffer (pop bl))
21576 (when (derived-mode-p 'org-mode) (setq bl nil)))
21577 (when (derived-mode-p 'org-mode)
21579 '("Org") "File List for Agenda"
21582 ["Edit File List" (org-edit-agenda-file-list) t]
21583 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21584 ["Remove Current File from List" org-remove-file t]
21585 ["Cycle through agenda files" org-cycle-agenda-files t]
21586 ["Occur in all agenda files" org-occur-in-agenda-files t]
21588 (mapcar 'org-file-menu-entry
21589 ;; Prevent initialization from failing.
21590 (ignore-errors (org-agenda-files t)))))))))
21594 (defun org-require-autoloaded-modules ()
21597 '(org-agenda org-archive org-attach org-clock org-colview org-id
21598 org-table org-timer)))
21601 (defun org-reload (&optional uncompiled)
21602 "Reload all org lisp files.
21603 With prefix arg UNCOMPILED, load the uncompiled versions."
21605 (require 'loadhist)
21606 (let* ((org-dir (org-find-library-dir "org"))
21607 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21608 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21609 (remove-re (format "\\`%s\\'"
21610 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21611 (feats (delete-dups
21612 (mapcar 'file-name-sans-extension
21613 (mapcar 'file-name-nondirectory
21615 (mapcar 'feature-file
21622 (if (and (string-match feature-re f)
21623 (not (string-match remove-re f)))
21627 (list "org-version" "org")))
21628 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21629 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21630 load-uncore load-misses)
21633 (mapcar (lambda (f)
21634 (or (org-load-noerror-mustsuffix (concat org-dir f))
21635 (and (string= org-dir contrib-dir)
21636 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21637 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21638 (add-to-list 'load-uncore f 'append)
21643 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21644 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21646 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21647 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21648 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21651 (defun org-customize ()
21652 "Call the customize function with org as argument."
21654 (org-load-modules-maybe)
21655 (org-require-autoloaded-modules)
21656 (customize-browse 'org))
21658 (defun org-create-customize-menu ()
21659 "Create a full customization menu for Org mode, insert it into the menu."
21661 (org-load-modules-maybe)
21662 (org-require-autoloaded-modules)
21663 (if (fboundp 'customize-menu-create)
21666 '("Org") "Customize"
21667 `(["Browse Org group" org-customize t]
21669 ,(customize-menu-create 'org)
21670 ["Set" Custom-set t]
21671 ["Save" Custom-save t]
21672 ["Reset to Current" Custom-reset-current t]
21673 ["Reset to Saved" Custom-reset-saved t]
21674 ["Reset to Standard Settings" Custom-reset-standard t]))
21675 (message "\"Org\"-menu now contains full customization menu"))
21676 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21678 ;;;; Miscellaneous stuff
21680 ;;; Generally useful functions
21682 (defun org-get-at-eol (property n)
21683 "Get text property PROPERTY at the end of line less N characters."
21684 (get-text-property (- (point-at-eol) n) property))
21686 (defun org-find-text-property-in-string (prop s)
21687 "Return the first non-nil value of property PROP in string S."
21688 (or (get-text-property 0 prop s)
21689 (get-text-property (or (next-single-property-change 0 prop s) 0)
21692 (defun org-display-warning (message)
21693 "Display the given MESSAGE as a warning."
21694 (display-warning 'org message :warning))
21696 (defun org-eval (form)
21697 "Eval FORM and return result."
21698 (condition-case error
21700 (error (format "%%![Error: %s]" error))))
21702 (defun org-in-clocktable-p ()
21703 "Check if the cursor is in a clocktable."
21704 (let ((pos (point)) start)
21707 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21708 (setq start (match-beginning 0))
21709 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21710 (>= (match-end 0) pos)
21713 (defun org-in-verbatim-emphasis ()
21715 (and (org-in-regexp org-verbatim-re 2)
21716 (>= (point) (match-beginning 3))
21717 (<= (point) (match-end 4)))))
21719 (defun org-overlay-display (ovl text &optional face evap)
21720 "Make overlay OVL display TEXT with face FACE."
21721 (overlay-put ovl 'display text)
21722 (if face (overlay-put ovl 'face face))
21723 (if evap (overlay-put ovl 'evaporate t)))
21725 (defun org-overlay-before-string (ovl text &optional face evap)
21726 "Make overlay OVL display TEXT with face FACE."
21727 (if face (org-add-props text nil 'face face))
21728 (overlay-put ovl 'before-string text)
21729 (if evap (overlay-put ovl 'evaporate t)))
21731 (defun org-find-overlays (prop &optional pos delete)
21732 "Find all overlays specifying PROP at POS or point.
21733 If DELETE is non-nil, delete all those overlays."
21735 (dolist (ov (overlays-at (or pos (point))) found)
21736 (cond ((not (overlay-get ov prop)))
21737 (delete (delete-overlay ov))
21738 (t (push ov found))))))
21740 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21741 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21742 (if (and marker (marker-buffer marker)
21743 (buffer-live-p (marker-buffer marker)))
21745 (pop-to-buffer-same-window (marker-buffer marker))
21746 (when (or (> marker (point-max)) (< marker (point-min)))
21749 (org-show-context 'org-goto))
21751 (bookmark-jump bookmark)
21752 (error "Cannot find location"))))
21754 (defun org-quote-csv-field (s)
21755 "Quote field for inclusion in CSV material."
21756 (if (string-match "[\",]" s)
21757 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21760 (defun org-force-self-insert (N)
21761 "Needed to enforce self-insert under remapping."
21763 (self-insert-command N))
21765 (defun org-shorten-string (s maxlength)
21766 "Shorten string S so that it is no longer than MAXLENGTH characters.
21767 If the string is shorter or has length MAXLENGTH, just return the
21768 original string. If it is longer, the functions finds a space in the
21769 string, breaks this string off at that locations and adds three dots
21770 as ellipsis. Including the ellipsis, the string will not be longer
21771 than MAXLENGTH. If finding a good breaking point in the string does
21772 not work, the string is just chopped off in the middle of a word
21774 (if (<= (length s) maxlength)
21776 (let* ((n (max (- maxlength 4) 1))
21777 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21778 (if (string-match re s)
21779 (concat (match-string 1 s) "...")
21780 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21782 (defun org-get-indentation (&optional line)
21783 "Get the indentation of the current line, interpreting tabs.
21784 When LINE is given, assume it represents a line and compute its indentation."
21786 (when (string-match "^ *" (org-remove-tabs line))
21789 (beginning-of-line 1)
21790 (skip-chars-forward " \t")
21791 (current-column))))
21793 (defun org-get-string-indentation (s)
21794 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21795 (let ((n -1) (i 0) (w tab-width) c)
21797 (while (< (setq n (1+ n)) (length s))
21798 (setq c (aref s n))
21799 (cond ((= c ?\ ) (setq i (1+ i)))
21800 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21801 (t (throw 'exit t)))))
21804 (defun org-remove-tabs (s &optional width)
21805 "Replace tabulators in S with spaces.
21806 Assumes that s is a single line, starting in column 0."
21807 (setq width (or width tab-width))
21808 (while (string-match "\t" s)
21809 (setq s (replace-match
21811 (- (* width (/ (+ (match-beginning 0) width) width))
21812 (match-beginning 0)) ?\ )
21816 (defun org-fix-indentation (line ind)
21817 "Fix indentation in LINE.
21818 IND is a cons cell with target and minimum indentation.
21819 If the current indentation in LINE is smaller than the minimum,
21820 leave it alone. If it is larger than ind, set it to the target."
21821 (let* ((l (org-remove-tabs line))
21822 (i (org-get-indentation l))
21823 (i1 (car ind)) (i2 (cdr ind)))
21824 (when (>= i i2) (setq l (substring line i2)))
21826 (concat (make-string i1 ?\ ) l)
21829 (defun org-remove-indentation (code &optional n)
21830 "Remove maximum common indentation in string CODE and return it.
21831 N may optionally be the number of columns to remove. Return CODE
21832 as-is if removal failed."
21835 (if (org-do-remove-indentation n) (buffer-string) code)))
21837 (defun org-do-remove-indentation (&optional n)
21838 "Remove the maximum common indentation from the buffer.
21839 When optional argument N is a positive integer, remove exactly
21840 that much characters from indentation, if possible. Return nil
21843 (goto-char (point-min))
21844 ;; Find maximum common indentation, if not specified.
21846 (let ((min-ind (point-max)))
21848 (while (re-search-forward "^[ \t]*\\S-" nil t)
21849 (let ((ind (1- (current-column))))
21850 (if (zerop ind) (throw :exit nil)
21851 (setq min-ind (min min-ind ind))))))
21853 (if (zerop n) (throw :exit nil)
21854 ;; Remove exactly N indentation, but give up if not possible.
21855 (while (not (eobp))
21856 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21857 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21858 ((< ind n) (throw :exit nil))
21859 (t (indent-line-to (- ind n))))
21864 (defun org-fill-template (template alist)
21865 "Find each %key of ALIST in TEMPLATE and replace it."
21866 (let ((case-fold-search nil))
21867 (dolist (entry (sort (copy-sequence alist)
21868 (lambda (a b) (< (length (car a)) (length (car b))))))
21870 (replace-regexp-in-string
21871 (concat "%" (regexp-quote (car entry)))
21872 (or (cdr entry) "") template t t)))
21875 (defun org-base-buffer (buffer)
21876 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21879 (or (buffer-base-buffer buffer)
21882 (defun org-wrap (string &optional width lines)
21883 "Wrap string to either a number of lines, or a width in characters.
21884 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21885 that costs. If there is a word longer than WIDTH, the text is actually
21886 wrapped to the length of that word.
21887 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21888 many lines, whatever width that takes.
21889 The return value is a list of lines, without newlines at the end."
21890 (let* ((words (split-string string))
21891 (maxword (apply 'max (mapcar 'org-string-width words)))
21894 (org-do-wrap words (max maxword width)))
21897 (setq ll (org-do-wrap words maxword))
21898 (if (<= (length ll) lines)
21901 (while (> (length ll) lines)
21903 (setq ll (org-do-wrap words w)))
21905 (t (error "Cannot wrap this")))))
21907 (defun org-do-wrap (words width)
21908 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21911 (setq line (pop words))
21912 (while (and words (< (+ (length line) (length (car words))) width))
21913 (setq line (concat line " " (pop words))))
21914 (setq lines (push line lines)))
21917 (defun org-quote-vert (s)
21918 "Replace \"|\" with \"\\vert\"."
21919 (while (string-match "|" s)
21920 (setq s (replace-match "\\vert" t t s)))
21923 (defun org-uuidgen-p (s)
21924 "Is S an ID created by UUIDGEN?"
21925 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21927 (defun org-in-src-block-p (&optional inside)
21928 "Whether point is in a code source block.
21929 When INSIDE is non-nil, don't consider we are within a src block
21930 when point is at #+BEGIN_SRC or #+END_SRC."
21931 (let ((case-fold-search t))
21932 (or (and (eq (get-char-property (point) 'src-block) t))
21936 (beginning-of-line)
21937 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21939 (defun org-context ()
21940 "Return a list of contexts of the current cursor position.
21941 If several contexts apply, all are returned.
21942 Each context entry is a list with a symbol naming the context, and
21943 two positions indicating start and end of the context. Possible
21946 :headline anywhere in a headline
21947 :headline-stars on the leading stars in a headline
21948 :todo-keyword on a TODO keyword (including DONE) in a headline
21949 :tags on the TAGS in a headline
21950 :priority on the priority cookie in a headline
21951 :item on the first line of a plain list item
21952 :item-bullet on the bullet/number of a plain list item
21953 :checkbox on the checkbox in a plain list item
21954 :table in an Org table
21955 :table-special on a special filed in a table
21956 :table-table in a table.el table
21957 :clocktable in a clocktable
21958 :src-block in a source block
21959 :link on a hyperlink
21960 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21961 :target on a <<target>>
21962 :radio-target on a <<<radio-target>>>
21963 :latex-fragment on a LaTeX fragment
21964 :latex-preview on a LaTeX fragment with overlaid preview image
21966 This function expects the position to be visible because it uses font-lock
21967 faces as a help to recognize the following contexts: :table-special, :link,
21969 (let* ((f (get-text-property (point) 'face))
21970 (faces (if (listp f) f (list f)))
21971 (case-fold-search t)
21972 (p (point)) clist o)
21973 ;; First the large context
21975 ((org-at-heading-p t)
21976 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21978 (beginning-of-line 1)
21979 (looking-at org-todo-line-tags-regexp))
21980 (push (org-point-in-group p 1 :headline-stars) clist)
21981 (push (org-point-in-group p 2 :todo-keyword) clist)
21982 (push (org-point-in-group p 4 :tags) clist))
21984 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21985 (when (looking-at "\\[#[A-Z0-9]\\]")
21986 (push (org-point-in-group p 0 :priority) clist)))
21989 (push (org-point-in-group p 2 :item-bullet) clist)
21990 (push (list :item (point-at-bol)
21991 (save-excursion (org-end-of-item) (point)))
21993 (and (org-at-item-checkbox-p)
21994 (push (org-point-in-group p 0 :checkbox) clist)))
21997 (push (list :table (org-table-begin) (org-table-end)) clist)
21998 (when (memq 'org-formula faces)
21999 (push (list :table-special
22000 (previous-single-property-change p 'face)
22001 (next-single-property-change p 'face)) clist)))
22002 ((org-at-table-p 'any)
22003 (push (list :table-table) clist)))
22006 (let ((case-fold-search t))
22007 ;; New the "medium" contexts: clocktables, source blocks
22008 (cond ((org-in-clocktable-p)
22009 (push (list :clocktable
22010 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22011 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22012 (match-beginning 1))
22013 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22014 (match-end 0))) clist))
22015 ((org-in-src-block-p)
22016 (push (list :src-block
22017 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22018 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22019 (match-beginning 1))
22020 (and (search-forward "#+END_SRC" nil t)
22021 (match-beginning 0))) clist))))
22024 ;; Now the small context
22026 ((org-at-timestamp-p)
22027 (push (org-point-in-group p 0 :timestamp) clist))
22028 ((memq 'org-link faces)
22030 (previous-single-property-change p 'face)
22031 (next-single-property-change p 'face)) clist))
22032 ((memq 'org-special-keyword faces)
22033 (push (list :keyword
22034 (previous-single-property-change p 'face)
22035 (next-single-property-change p 'face)) clist))
22037 (push (org-point-in-group p 0 :target) clist)
22038 (goto-char (1- (match-beginning 0)))
22039 (when (looking-at org-radio-target-regexp)
22040 (push (org-point-in-group p 0 :radio-target) clist))
22044 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22046 (overlays-at (point))))
22047 (push (list :latex-fragment
22048 (overlay-start o) (overlay-end o)) clist)
22049 (push (list :latex-preview
22050 (overlay-start o) (overlay-end o)) clist))
22051 ((org-inside-LaTeX-fragment-p)
22052 ;; FIXME: positions wrong.
22053 (push (list :latex-fragment (point) (point)) clist)))
22055 (setq clist (nreverse (delq nil clist)))
22058 (defun org-in-regexp (regexp &optional nlines visually)
22059 "Check if point is inside a match of REGEXP.
22061 Normally only the current line is checked, but you can include
22062 NLINES extra lines around point into the search. If VISUALLY is
22063 set, require that the cursor is not after the match but really
22064 on, so that the block visually is on the match.
22066 Return nil or a cons cell (BEG . END) where BEG and END are,
22067 respectively, the positions at the beginning and the end of the
22070 (let ((pos (point))
22071 (eol (line-end-position (if nlines (1+ nlines) 1))))
22073 (beginning-of-line (- 1 (or nlines 0)))
22074 (while (and (re-search-forward regexp eol t)
22075 (<= (match-beginning 0) pos))
22076 (let ((end (match-end 0)))
22077 (when (or (> end pos) (and (= end pos) (not visually)))
22078 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22080 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22081 "Non-nil when point is between matches of START-RE and END-RE.
22083 Also return a non-nil value when point is on one of the matches.
22085 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22086 buffer positions. Default values are the positions of headlines
22087 surrounding the point.
22089 The functions returns a cons cell whose car (resp. cdr) is the
22090 position before START-RE (resp. after END-RE)."
22092 (let ((pos (point))
22093 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22094 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22097 ;; Point is on a block when on START-RE or if START-RE can be
22098 ;; found before it...
22099 (and (or (org-in-regexp start-re)
22100 (re-search-backward start-re limit-up t))
22101 (setq beg (match-beginning 0))
22102 ;; ... and END-RE after it...
22103 (goto-char (match-end 0))
22104 (re-search-forward end-re limit-down t)
22105 (> (setq end (match-end 0)) pos)
22106 ;; ... without another START-RE in-between.
22107 (goto-char (match-beginning 0))
22108 (not (re-search-backward start-re (1+ beg) t))
22110 (cons beg end))))))
22112 (defun org-in-block-p (names)
22113 "Non-nil when point belongs to a block whose name belongs to NAMES.
22115 NAMES is a list of strings containing names of blocks.
22117 Return first block name matched, or nil. Beware that in case of
22118 nested blocks, the returned name may not belong to the closest
22122 (let ((case-fold-search t)
22123 (lim-up (save-excursion (outline-previous-heading)))
22124 (lim-down (save-excursion (outline-next-heading))))
22125 (dolist (name names)
22126 (let ((n (regexp-quote name)))
22127 (when (org-between-regexps-p
22128 (concat "^[ \t]*#\\+begin_" n)
22129 (concat "^[ \t]*#\\+end_" n)
22131 (throw 'exit n)))))
22134 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22135 "Call `multi-occur' with buffers for all agenda files."
22136 (interactive "sOrg-files matching: ")
22137 (let* ((files (org-agenda-files))
22138 (tnames (mapcar #'file-truename files))
22139 (extra org-agenda-text-search-extra-files))
22140 (when (eq (car extra) 'agenda-archives)
22141 (setq extra (cdr extra))
22142 (setq files (org-add-archive-files files)))
22144 (unless (member (file-truename f) tnames)
22145 (unless (member f files) (setq files (append files (list f))))
22146 (setq tnames (append tnames (list (file-truename f))))))
22148 (mapcar (lambda (x)
22149 (with-current-buffer
22150 ;; FIXME: Why not just (find-file-noselect x)?
22151 ;; Is it to avoid the "revert buffer" prompt?
22152 (or (get-file-buffer x) (find-file-noselect x))
22158 (add-hook 'occur-mode-find-occurrence-hook
22159 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22161 (defun org-occur-link-in-agenda-files ()
22162 "Create a link and search for it in the agendas.
22163 The link is not stored in `org-stored-links', it is just created
22164 for the search purpose."
22166 (let ((link (condition-case nil
22167 (org-store-link nil)
22168 (error "Unable to create a link to here"))))
22169 (org-occur-in-agenda-files (regexp-quote link))))
22171 (defun org-reverse-string (string)
22172 "Return the reverse of STRING."
22173 (apply 'string (reverse (string-to-list string))))
22175 ;; defsubst org-uniquify must be defined before first use
22177 (defun org-uniquify-alist (alist)
22178 "Merge elements of ALIST with the same key.
22180 For example, in this alist:
22182 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22183 => \\='((a 1 3) (b 2))
22185 merge (a 1) and (a 3) into (a 1 3).
22187 The function returns the new ALIST."
22189 (dolist (e alist rtn)
22191 (if (not (assoc (car e) rtn))
22193 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22194 (setq rtn (assq-delete-all (car e) rtn))
22197 (defun org-delete-all (elts list)
22198 "Remove all elements in ELTS from LIST.
22199 Comparison is done with `equal'. It is a destructive operation
22200 that may remove elements by altering the list structure."
22202 (setq list (delete (pop elts) list)))
22205 (defun org-back-over-empty-lines ()
22206 "Move backwards over whitespace, to the beginning of the first empty line.
22207 Returns the number of empty lines passed."
22208 (let ((pos (point)))
22209 (if (cdr (assq 'heading org-blank-before-new-entry))
22210 (skip-chars-backward " \t\n\r")
22212 (forward-line -1)))
22213 (beginning-of-line 2)
22214 (goto-char (min (point) pos))
22215 (count-lines (point) pos)))
22217 (defun org-skip-whitespace ()
22218 (skip-chars-forward " \t\n\r"))
22220 (defun org-point-in-group (point group &optional context)
22221 "Check if POINT is in match-group GROUP.
22222 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22223 match. If the match group does not exist or point is not inside it,
22225 (and (match-beginning group)
22226 (>= point (match-beginning group))
22227 (<= point (match-end group))
22229 (list context (match-beginning group) (match-end group))
22232 (defun org-switch-to-buffer-other-window (&rest args)
22233 "Switch to buffer in a second window on the current frame.
22234 In particular, do not allow pop-up frames.
22235 Returns the newly created buffer."
22237 (apply 'switch-to-buffer-other-window args)))
22239 (defun org-combine-plists (&rest plists)
22240 "Create a single property list from all plists in PLISTS.
22241 The process starts by copying the first list, and then setting properties
22242 from the other lists. Settings in the last list are the most significant
22243 ones and overrule settings in the other lists."
22244 (let ((rtn (copy-sequence (pop plists)))
22247 (setq ls (pop plists))
22249 (setq p (pop ls) v (pop ls))
22250 (setq rtn (plist-put rtn p v))))
22253 (defun org-replace-escapes (string table)
22254 "Replace %-escapes in STRING with values in TABLE.
22255 TABLE is an association list with keys like \"%a\" and string values.
22256 The sequences in STRING may contain normal field width and padding information,
22257 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22258 so values can contain further %-escapes if they are define later in TABLE."
22259 (let ((tbl (copy-alist table))
22260 (case-fold-search nil)
22264 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22265 (when (and (cdr e) (string-match re (cdr e)))
22266 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22268 (add-text-properties 0 3 (list 'sref sref) safe)
22269 (setcdr e (replace-match safe t t (cdr e)))))
22270 (while (string-match re string)
22271 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22273 (setq string (replace-match rpl t t string))))
22274 (while (setq pchg (next-property-change pchg string))
22275 (let ((sref (get-text-property pchg 'sref string)))
22276 (when (and sref (string-match "SREF" string pchg))
22277 (setq string (replace-match sref t t string)))))
22280 (defun org-find-base-buffer-visiting (file)
22281 "Like `find-buffer-visiting' but always return the base buffer and
22282 not an indirect buffer."
22283 (let ((buf (or (get-file-buffer file)
22284 (find-buffer-visiting file))))
22286 (or (buffer-base-buffer buf) buf)
22289 ;;; TODO: Only called once, from ox-odt which should probably use
22290 ;;; org-export-inline-image-p or something.
22291 (defun org-file-image-p (file)
22292 "Return non-nil if FILE is an image."
22294 (string-match (image-file-name-regexp) file)))
22296 (defun org-get-cursor-date (&optional with-time)
22297 "Return the date at cursor in as a time.
22298 This works in the calendar and in the agenda, anywhere else it just
22299 returns the current time.
22300 If WITH-TIME is non-nil, returns the time of the event at point (in
22301 the agenda) or the current time of the day."
22302 (let (date day defd tp hod mod)
22304 (setq tp (get-text-property (point) 'time))
22305 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22306 (setq hod (string-to-number (match-string 1 tp))
22307 mod (string-to-number (match-string 2 tp))))
22308 (or tp (let ((now (decode-time)))
22309 (setq hod (nth 2 now)
22310 mod (nth 1 now)))))
22312 ((eq major-mode 'calendar-mode)
22313 (setq date (calendar-cursor-to-date)
22314 defd (encode-time 0 (or mod 0) (or hod 0)
22315 (nth 1 date) (nth 0 date) (nth 2 date))))
22316 ((eq major-mode 'org-agenda-mode)
22317 (setq day (get-text-property (point) 'day))
22319 (setq date (calendar-gregorian-from-absolute day)
22320 defd (encode-time 0 (or mod 0) (or hod 0)
22321 (nth 1 date) (nth 0 date) (nth 2 date))))))
22322 (or defd (current-time))))
22324 (defun org-mark-subtree (&optional up)
22325 "Mark the current subtree.
22326 This puts point at the start of the current subtree, and mark at
22327 the end. If a numeric prefix UP is given, move up into the
22328 hierarchy of headlines by UP levels before marking the subtree."
22330 (org-with-limited-levels
22331 (cond ((org-at-heading-p) (beginning-of-line))
22332 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22333 (t (outline-previous-visible-heading 1))))
22334 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22335 (if (called-interactively-p 'any)
22336 (call-interactively 'org-mark-element)
22337 (org-mark-element)))
22339 (defun org-file-newer-than-p (file time)
22340 "Non-nil if FILE is newer than TIME.
22341 FILE is a filename, as a string, TIME is a list of integers, as
22342 returned by, e.g., `current-time'."
22343 (and (file-exists-p file)
22344 ;; Only compare times up to whole seconds as some file-systems
22345 ;; (e.g. HFS+) do not retain any finer granularity. As
22346 ;; a consequence, make sure we return non-nil when the two
22347 ;; times are equal.
22348 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22349 (cl-subseq time 0 2)))))
22351 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22352 "Compile a SOURCE file using PROCESS.
22354 PROCESS is either a function or a list of shell commands, as
22355 strings. EXT is a file extension, without the leading dot, as
22356 a string. It is used to check if the process actually succeeded.
22358 PROCESS must create a file with the same base name and directory
22359 as SOURCE, but ending with EXT. The function then returns its
22360 filename. Otherwise, it raises an error. The error message can
22361 then be refined by providing string ERR-MSG, which is appended to
22362 the standard message.
22364 If PROCESS is a function, it is called with a single argument:
22367 If it is a list of commands, each of them is called using
22368 `shell-command'. By default, in each command, %b, %f, %F, %o and
22369 %O are replaced with, respectively, SOURCE base name, name, full
22370 name, directory and absolute output file name. It is possible,
22371 however, to use more place-holders by specifying them in optional
22372 argument SPEC, as an alist following the pattern
22374 (CHARACTER . REPLACEMENT-STRING).
22376 When PROCESS is a list of commands, optional argument LOG-BUF can
22377 be set to a buffer or a buffer name. `shell-command' then uses
22379 (let* ((base-name (file-name-base source))
22380 (full-name (file-truename source))
22381 (out-dir (or (file-name-directory source) "./"))
22382 (output (expand-file-name (concat base-name "." ext) out-dir))
22383 (time (current-time))
22384 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22385 (save-window-excursion
22387 ((pred functionp) (funcall process (shell-quote-argument source)))
22389 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22391 `((?b . ,(shell-quote-argument base-name))
22392 (?f . ,(shell-quote-argument source))
22393 (?F . ,(shell-quote-argument full-name))
22394 (?o . ,(shell-quote-argument out-dir))
22395 (?O . ,(shell-quote-argument output))))))
22396 (dolist (command process)
22397 (shell-command (format-spec command spec) log-buf))
22398 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22399 (_ (error "No valid command to process %S%s" source err-msg))))
22400 ;; Check for process failure. Output file is expected to be
22401 ;; located in the same directory as SOURCE.
22402 (unless (org-file-newer-than-p output time)
22403 (error (format "File %S wasn't produced%s" output err-msg)))
22408 (defvar org-element-greater-elements)
22409 (defun org--get-expected-indentation (element contentsp)
22410 "Expected indentation column for current line, according to ELEMENT.
22411 ELEMENT is an element containing point. CONTENTSP is non-nil
22412 when indentation is to be computed according to contents of
22414 (let ((type (org-element-type element))
22415 (start (org-element-property :begin element))
22416 (post-affiliated (org-element-property :post-affiliated element)))
22417 (org-with-wide-buffer
22421 ((diary-sexp footnote-definition) 0)
22422 ((headline inlinetask nil)
22423 (if (not org-adapt-indentation) 0
22424 (let ((level (org-current-level)))
22425 (if level (1+ level) 0))))
22426 ((item plain-list) (org-list-item-body-column post-affiliated))
22429 (org-get-indentation))))
22430 ((memq type '(headline inlinetask nil))
22431 (if (org-match-line "[ \t]*$")
22432 (org--get-expected-indentation element t)
22434 ((memq type '(diary-sexp footnote-definition)) 0)
22435 ;; First paragraph of a footnote definition or an item.
22436 ;; Indent like parent.
22437 ((< (line-beginning-position) start)
22438 (org--get-expected-indentation
22439 (org-element-property :parent element) t))
22440 ;; At first line: indent according to previous sibling, if any,
22441 ;; ignoring footnote definitions and inline tasks, or parent's
22443 ((= (line-beginning-position) start)
22446 (if (= (point-min) start) (throw 'exit 0)
22447 (goto-char (1- start))
22448 (let* ((previous (org-element-at-point))
22450 (while (and parent (<= (org-element-property :end parent) start))
22451 (setq previous parent
22452 parent (org-element-property :parent parent)))
22454 ((not previous) (throw 'exit 0))
22455 ((> (org-element-property :end previous) start)
22456 (throw 'exit (org--get-expected-indentation previous t)))
22457 ((memq (org-element-type previous)
22458 '(footnote-definition inlinetask))
22459 (setq start (org-element-property :begin previous)))
22460 (t (goto-char (org-element-property :begin previous))
22462 (if (bolp) (org-get-indentation)
22463 ;; At first paragraph in an item or
22464 ;; a footnote definition.
22465 (org--get-expected-indentation
22466 (org-element-property :parent previous) t))))))))))
22467 ;; Otherwise, move to the first non-blank line above.
22469 (beginning-of-line)
22470 (let ((pos (point)))
22471 (skip-chars-backward " \r\t\n")
22473 ;; Two blank lines end a footnote definition or a plain
22474 ;; list. When we indent an empty line after them, the
22475 ;; containing list or footnote definition is over, so it
22476 ;; qualifies as a previous sibling. Therefore, we indent
22477 ;; like its first line.
22478 ((and (memq type '(footnote-definition plain-list))
22479 (> (count-lines (point) pos) 2))
22481 (org-get-indentation))
22482 ;; Line above is the first one of a paragraph at the
22483 ;; beginning of an item or a footnote definition. Indent
22485 ((< (line-beginning-position) start)
22486 (org--get-expected-indentation
22487 (org-element-property :parent element) t))
22488 ;; Line above is the beginning of an element, i.e., point
22489 ;; was originally on the blank lines between element's start
22491 ((= (line-beginning-position) post-affiliated)
22492 (org--get-expected-indentation element t))
22493 ;; POS is after contents in a greater element. Indent like
22494 ;; the beginning of the element.
22495 ((and (memq type org-element-greater-elements)
22496 (let ((cend (org-element-property :contents-end element)))
22497 (and cend (<= cend pos))))
22498 ;; As a special case, if point is at the end of a footnote
22499 ;; definition or an item, indent like the very last element
22500 ;; within. If that last element is an item, indent like
22502 (if (memq type '(footnote-definition item plain-list))
22503 (let ((last (org-element-at-point)))
22505 (org--get-expected-indentation
22506 last (eq (org-element-type last) 'item)))
22508 (org-get-indentation)))
22509 ;; In any other case, indent like the current line.
22510 (t (org-get-indentation)))))))))
22512 (defun org--align-node-property ()
22513 "Align node property at point.
22514 Alignment is done according to `org-property-format', which see."
22515 (when (save-excursion
22516 (beginning-of-line)
22517 (looking-at org-property-re))
22519 (concat (match-string 4)
22521 (format org-property-format (match-string 1) (match-string 3))))
22524 (defun org-indent-line ()
22525 "Indent line depending on context.
22527 Indentation is done according to the following rules:
22529 - Footnote definitions, diary sexps, headlines and inline tasks
22530 have to start at column 0.
22532 - On the very first line of an element, consider, in order, the
22533 next rules until one matches:
22535 1. If there's a sibling element before, ignoring footnote
22536 definitions and inline tasks, indent like its first line.
22538 2. If element has a parent, indent like its contents. More
22539 precisely, if parent is an item, indent after the
22540 description part, if any, or the bullet (see
22541 `org-list-description-max-indent'). Else, indent like
22542 parent's first line.
22544 3. Otherwise, indent relatively to current level, if
22545 `org-adapt-indentation' is non-nil, or to left margin.
22547 - On a blank line at the end of an element, indent according to
22548 the type of the element. More precisely
22550 1. If element is a plain list, an item, or a footnote
22551 definition, indent like the very last element within.
22553 2. If element is a paragraph, indent like its last non blank
22556 3. Otherwise, indent like its very first line.
22558 - In the code part of a source block, use language major mode
22559 to indent current line if `org-src-tab-acts-natively' is
22560 non-nil. If it is nil, do nothing.
22562 - Otherwise, indent like the first non-blank line above.
22564 The function doesn't indent an item as it could break the whole
22565 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22566 `\\[org-shiftmetaright]'.
22568 Also align node properties according to `org-property-format'."
22572 (let ((indent-line-function
22573 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22574 (indent-according-to-mode)))
22575 ((org-at-heading-p) 'noindent)
22577 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22578 (type (org-element-type element)))
22579 (cond ((and (memq type '(plain-list item))
22580 (= (line-beginning-position)
22581 (org-element-property :post-affiliated element)))
22583 ((and (eq type 'latex-environment)
22584 (>= (point) (org-element-property :post-affiliated element))
22585 (< (point) (org-with-wide-buffer
22586 (goto-char (org-element-property :end element))
22587 (skip-chars-backward " \r\t\n")
22588 (line-beginning-position 2))))
22590 ((and (eq type 'src-block)
22591 org-src-tab-acts-natively
22592 (> (line-beginning-position)
22593 (org-element-property :post-affiliated element))
22594 (< (line-beginning-position)
22595 (org-with-wide-buffer
22596 (goto-char (org-element-property :end element))
22597 (skip-chars-backward " \r\t\n")
22598 (line-beginning-position))))
22599 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22601 (let ((column (org--get-expected-indentation element nil)))
22602 ;; Preserve current column.
22603 (if (<= (current-column) (current-indentation))
22604 (indent-line-to column)
22605 (save-excursion (indent-line-to column))))
22606 ;; Align node property. Also preserve current column.
22607 (when (eq type 'node-property)
22608 (let ((column (current-column)))
22609 (org--align-node-property)
22610 (org-move-to-column column)))))))))
22612 (defun org-indent-region (start end)
22613 "Indent each non-blank line in the region.
22614 Called from a program, START and END specify the region to
22615 indent. The function will not indent contents of example blocks,
22616 verse blocks and export blocks as leading white spaces are
22617 assumed to be significant there."
22621 (skip-chars-forward " \r\t\n")
22622 (unless (eobp) (beginning-of-line))
22625 ;; Set IND as indentation for all lines between point and
22626 ;; POS. Blank lines are ignored. Leave point after POS
22628 (let ((limit (copy-marker pos)))
22629 (while (< (point) limit)
22630 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22632 (set-marker limit nil))))
22633 (end (copy-marker end)))
22634 (while (< (point) end)
22635 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22636 (let* ((element (org-element-at-point))
22637 (type (org-element-type element))
22638 (element-end (copy-marker (org-element-property :end element)))
22639 (ind (org--get-expected-indentation element nil)))
22641 ;; Element indented as a single block. Example blocks
22642 ;; preserving indentation are a special case since the
22643 ;; "contents" must not be indented whereas the block
22645 ((or (memq type '(export-block latex-environment))
22646 (and (eq type 'example-block)
22648 (or org-src-preserve-indentation
22649 (org-element-property :preserve-indent element)))))
22650 (let ((offset (- ind (org-get-indentation))))
22651 (unless (zerop offset)
22652 (indent-rigidly (org-element-property :begin element)
22653 (org-element-property :end element)
22655 (goto-char element-end))
22656 ;; Elements indented line wise. Be sure to exclude
22657 ;; example blocks (preserving indentation) and source
22658 ;; blocks from this category as they are treated
22659 ;; specially later.
22660 ((or (memq type '(paragraph table table-row))
22661 (not (or (org-element-property :contents-begin element)
22662 (memq type '(example-block src-block)))))
22663 (when (eq type 'node-property)
22664 (org--align-node-property)
22665 (beginning-of-line))
22666 (funcall indent-to ind (min element-end end)))
22667 ;; Elements consisting of three parts: before the
22668 ;; contents, the contents, and after the contents. The
22669 ;; contents are treated specially, according to the
22670 ;; element type, or not indented at all. Other parts are
22671 ;; indented as a single block.
22673 (let* ((post (copy-marker
22674 (org-element-property :post-affiliated element)))
22678 ((not (org-element-property :contents-begin element))
22679 ;; Fake contents for source blocks.
22680 (org-with-wide-buffer
22682 (line-beginning-position 2)))
22683 ((memq type '(footnote-definition item plain-list))
22684 ;; Contents in these elements could start on
22685 ;; the same line as the beginning of the
22686 ;; element. Make sure we start indenting
22687 ;; from the second line.
22688 (org-with-wide-buffer
22691 (skip-chars-forward " \r\t\n")
22692 (if (eobp) (point) (line-beginning-position))))
22693 (t (org-element-property :contents-begin element)))))
22695 (or (org-element-property :contents-end element)
22696 ;; Fake contents for source blocks.
22697 (org-with-wide-buffer
22698 (goto-char element-end)
22699 (skip-chars-backward " \r\t\n")
22700 (line-beginning-position)))
22702 ;; Do not change items indentation individually as it
22703 ;; might break the list as a whole. On the other
22704 ;; hand, when at a plain list, indent it as a whole.
22705 (cond ((eq type 'plain-list)
22706 (let ((offset (- ind (org-get-indentation))))
22707 (unless (zerop offset)
22708 (indent-rigidly (org-element-property :begin element)
22709 (org-element-property :end element)
22712 ((eq type 'item) (goto-char cbeg))
22713 (t (funcall indent-to ind (min cbeg end))))
22714 (when (< (point) end)
22716 ((example-block verse-block))
22718 ;; In a source block, indent source code
22719 ;; according to language major mode, but only if
22720 ;; `org-src-tab-acts-natively' is non-nil.
22721 (when (and (< (point) end) org-src-tab-acts-natively)
22723 (org-babel-do-in-edit-buffer
22724 (indent-region (point-min) (point-max))))))
22725 (t (org-indent-region (point) (min cend end))))
22726 (goto-char (min cend end))
22727 (when (< (point) end)
22728 (funcall indent-to ind (min element-end end))))
22729 (set-marker post nil)
22730 (set-marker cbeg nil)
22731 (set-marker cend nil))))
22732 (set-marker element-end nil))))
22733 (set-marker end nil))))
22735 (defun org-indent-drawer ()
22736 "Indent the drawer at point."
22738 (unless (save-excursion
22739 (beginning-of-line)
22740 (looking-at-p org-drawer-regexp))
22741 (user-error "Not at a drawer"))
22742 (let ((element (org-element-at-point)))
22743 (unless (memq (org-element-type element) '(drawer property-drawer))
22744 (user-error "Not at a drawer"))
22745 (org-with-wide-buffer
22746 (org-indent-region (org-element-property :begin element)
22747 (org-element-property :end element))))
22748 (message "Drawer at point indented"))
22750 (defun org-indent-block ()
22751 "Indent the block at point."
22753 (unless (save-excursion
22754 (beginning-of-line)
22755 (let ((case-fold-search t))
22756 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22757 (user-error "Not at a block"))
22758 (let ((element (org-element-at-point)))
22759 (unless (memq (org-element-type element)
22760 '(comment-block center-block dynamic-block example-block
22761 export-block quote-block special-block
22762 src-block verse-block))
22763 (user-error "Not at a block"))
22764 (org-with-wide-buffer
22765 (org-indent-region (org-element-property :begin element)
22766 (org-element-property :end element))))
22767 (message "Block at point indented"))
22772 ;; We use our own fill-paragraph and auto-fill functions.
22774 ;; `org-fill-paragraph' relies on adaptive filling and context
22775 ;; checking. Appropriate `fill-prefix' is computed with
22776 ;; `org-adaptive-fill-function'.
22778 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22779 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22780 ;; `org-adaptive-fill-function' value. Internally,
22781 ;; `org-comment-line-break-function' breaks the line.
22783 ;; `org-setup-filling' installs filling and auto-filling related
22784 ;; variables during `org-mode' initialization.
22786 (defun org-setup-filling ()
22787 (require 'org-element)
22788 ;; Prevent auto-fill from inserting unwanted new items.
22789 (when (boundp 'fill-nobreak-predicate)
22791 fill-nobreak-predicate
22793 (append fill-nobreak-predicate
22794 '(org-fill-line-break-nobreak-p
22795 org-fill-n-macro-as-item-nobreak-p
22796 org-fill-paragraph-with-timestamp-nobreak-p)))))
22797 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22798 (setq-local paragraph-start paragraph-ending)
22799 (setq-local paragraph-separate paragraph-ending))
22800 (setq-local fill-paragraph-function 'org-fill-paragraph)
22801 (setq-local auto-fill-inhibit-regexp nil)
22802 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22803 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22804 (setq-local comment-line-break-function 'org-comment-line-break-function))
22806 (defun org-fill-line-break-nobreak-p ()
22807 "Non-nil when a new line at point would create an Org line break."
22809 (skip-chars-backward "[ \t]")
22810 (skip-chars-backward "\\\\")
22811 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22813 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22814 "Non-nil when a new line at point would split a timestamp."
22815 (and (org-at-timestamp-p 'lax)
22816 (not (looking-at org-ts-regexp-both))))
22818 (defun org-fill-n-macro-as-item-nobreak-p ()
22819 "Non-nil when a new line at point would create a new list."
22820 ;; During export, a "n" macro followed by a dot or a closing
22821 ;; parenthesis can end up being parsed as a new list item.
22822 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22824 (declare-function message-in-body-p "message" ())
22825 (defvar orgtbl-line-start-regexp) ; From org-table.el
22826 (defun org-adaptive-fill-function ()
22827 "Compute a fill prefix for the current line.
22828 Return fill prefix, as a string, or nil if current line isn't
22829 meant to be filled. For convenience, if `adaptive-fill-regexp'
22830 matches in paragraphs or comments, use it."
22832 (when (derived-mode-p 'message-mode)
22834 (beginning-of-line)
22835 (cond ((not (message-in-body-p)) (throw 'exit nil))
22836 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22837 ((looking-at message-cite-prefix-regexp)
22838 (throw 'exit (match-string-no-properties 0)))
22839 ((looking-at org-outline-regexp)
22840 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22841 (org-with-wide-buffer
22842 (unless (org-at-heading-p)
22843 (let* ((p (line-beginning-position))
22844 (element (save-excursion
22845 (beginning-of-line)
22846 (org-element-at-point)))
22847 (type (org-element-type element))
22848 (post-affiliated (org-element-property :post-affiliated element)))
22849 (unless (< p post-affiliated)
22853 (beginning-of-line)
22854 (looking-at "[ \t]*")
22855 (concat (match-string 0) "# ")))
22856 (footnote-definition "")
22858 (make-string (org-list-item-body-column post-affiliated) ?\s))
22860 ;; Fill prefix is usually the same as the current line,
22861 ;; unless the paragraph is at the beginning of an item.
22862 (let ((parent (org-element-property :parent element)))
22864 (beginning-of-line)
22865 (cond ((eq (org-element-type parent) 'item)
22866 (make-string (org-list-item-body-column
22867 (org-element-property :begin parent))
22869 ((and adaptive-fill-regexp
22871 ;; `adaptive-fill-function' to let
22872 ;; `fill-context-prefix' handle
22873 ;; `adaptive-fill-regexp' variable.
22874 (let (adaptive-fill-function)
22875 (fill-context-prefix
22877 (org-element-property :end element)))))
22878 ((looking-at "[ \t]+") (match-string 0))
22881 ;; Only fill contents if P is within block boundaries.
22882 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22885 (cend (save-excursion
22886 (goto-char (org-element-property :end element))
22887 (skip-chars-backward " \r\t\n")
22888 (line-beginning-position))))
22889 (when (and (>= p cbeg) (< p cend))
22890 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22894 (declare-function message-goto-body "message" ())
22895 (defvar message-cite-prefix-regexp) ; From message.el
22897 (defun org-fill-element (&optional justify)
22898 "Fill element at point, when applicable.
22900 This function only applies to comment blocks, comments, example
22901 blocks and paragraphs. Also, as a special case, re-align table
22902 when point is at one.
22904 If JUSTIFY is non-nil (interactively, with prefix argument),
22905 justify as well. If `sentence-end-double-space' is non-nil, then
22906 period followed by one space does not end a sentence, so don't
22907 break a line there. The variable `fill-column' controls the
22910 For convenience, when point is at a plain list, an item or
22911 a footnote definition, try to fill the first paragraph within."
22912 (with-syntax-table org-mode-transpose-word-syntax-table
22913 ;; Move to end of line in order to get the first paragraph within
22914 ;; a plain list or a footnote definition.
22915 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22916 ;; First check if point is in a blank line at the beginning of
22917 ;; the buffer. In that case, ignore filling.
22918 (cl-case (org-element-type element)
22919 ;; Use major mode filling function is src blocks.
22920 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22921 ;; Align Org tables, leave table.el tables as-is.
22922 (table-row (org-table-align) t)
22924 (when (eq (org-element-property :type element) 'org)
22926 (goto-char (org-element-property :post-affiliated element))
22927 (org-table-align)))
22930 ;; Paragraphs may contain `line-break' type objects.
22931 (let ((beg (max (point-min)
22932 (org-element-property :contents-begin element)))
22933 (end (min (point-max)
22934 (org-element-property :contents-end element))))
22935 ;; Do nothing if point is at an affiliated keyword.
22936 (if (< (line-end-position) beg) t
22937 (when (derived-mode-p 'message-mode)
22938 ;; In `message-mode', do not fill following citation
22939 ;; in current paragraph nor text before message body.
22940 (let ((body-start (save-excursion (message-goto-body))))
22941 (when body-start (setq beg (max body-start beg))))
22942 (when (save-excursion
22944 (concat "^" message-cite-prefix-regexp) end t))
22945 (setq end (match-beginning 0))))
22946 ;; Fill paragraph, taking line breaks into account.
22949 (let ((cuts (list beg)))
22950 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22951 (when (eq 'line-break
22953 (save-excursion (backward-char)
22954 (org-element-context))))
22955 (push (point) cuts)))
22956 (dolist (c (delq end cuts))
22957 (fill-region-as-paragraph c end justify)
22960 ;; Contents of `comment-block' type elements should be
22961 ;; filled as plain text, but only if point is within block
22964 (let* ((case-fold-search t)
22965 (beg (save-excursion
22966 (goto-char (org-element-property :begin element))
22967 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22970 (end (save-excursion
22971 (goto-char (org-element-property :end element))
22972 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22973 (line-beginning-position))))
22974 (if (or (< (point) beg) (> (point) end)) t
22975 (fill-region-as-paragraph
22976 (save-excursion (end-of-line)
22977 (re-search-backward "^[ \t]*$" beg 'move)
22978 (line-beginning-position))
22979 (save-excursion (beginning-of-line)
22980 (re-search-forward "^[ \t]*$" end 'move)
22981 (line-beginning-position))
22985 (let ((begin (org-element-property :post-affiliated element))
22986 (end (org-element-property :end element)))
22987 (when (and (>= (point) begin) (<= (point) end))
22988 (let ((begin (save-excursion
22990 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22991 (progn (forward-line) (point))
22993 (end (save-excursion
22995 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22996 (1- (line-beginning-position))
22997 (skip-chars-backward " \r\t\n")
22998 (line-end-position)))))
22999 ;; Do not fill comments when at a blank line.
23000 (when (> end begin)
23003 (beginning-of-line)
23004 (looking-at "[ \t]*#")
23005 (let ((comment-prefix (match-string 0)))
23006 (goto-char (match-end 0))
23007 (if (looking-at adaptive-fill-regexp)
23008 (concat comment-prefix (match-string 0))
23009 (concat comment-prefix " "))))))
23011 (fill-region-as-paragraph begin end justify))))))
23013 ;; Ignore every other element.
23016 (defun org-fill-paragraph (&optional justify region)
23017 "Fill element at point, when applicable.
23019 This function only applies to comment blocks, comments, example
23020 blocks and paragraphs. Also, as a special case, re-align table
23021 when point is at one.
23023 For convenience, when point is at a plain list, an item or
23024 a footnote definition, try to fill the first paragraph within.
23026 If JUSTIFY is non-nil (interactively, with prefix argument),
23027 justify as well. If `sentence-end-double-space' is non-nil, then
23028 period followed by one space does not end a sentence, so don't
23029 break a line there. The variable `fill-column' controls the
23032 The REGION argument is non-nil if called interactively; in that
23033 case, if Transient Mark mode is enabled and the mark is active,
23034 fill each of the elements in the active region, instead of just
23035 filling the current element."
23036 (interactive (progn
23037 (barf-if-buffer-read-only)
23038 (list (if current-prefix-arg 'full) t)))
23040 ((and (derived-mode-p 'message-mode)
23041 (or (not (message-in-body-p))
23042 (save-excursion (move-beginning-of-line 1)
23043 (looking-at message-cite-prefix-regexp))))
23044 ;; First ensure filling is correct in message-mode.
23045 (let ((fill-paragraph-function
23046 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23047 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23048 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23049 (paragraph-separate
23050 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23051 (fill-paragraph nil)))
23052 ((and region transient-mark-mode mark-active
23053 (not (eq (region-beginning) (region-end))))
23054 (let ((origin (point-marker))
23055 (start (region-beginning)))
23058 (goto-char (region-end))
23059 (while (> (point) start)
23060 (org-backward-paragraph)
23061 (org-fill-element justify)))
23063 (set-marker origin nil))))
23064 (t (org-fill-element justify))))
23065 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23067 (defun org-auto-fill-function ()
23068 "Auto-fill function."
23069 ;; Check if auto-filling is meaningful.
23070 (let ((fc (current-fill-column)))
23071 (when (and fc (> (current-column) fc))
23072 (let* ((fill-prefix (org-adaptive-fill-function))
23073 ;; Enforce empty fill prefix, if required. Otherwise, it
23074 ;; will be computed again.
23075 (adaptive-fill-mode (not (equal fill-prefix ""))))
23076 (when fill-prefix (do-auto-fill))))))
23078 (defun org-comment-line-break-function (&optional soft)
23079 "Break line at point and indent, continuing comment if within one.
23080 The inserted newline is marked hard if variable
23081 `use-hard-newlines' is true, unless optional argument SOFT is
23083 (if soft (insert-and-inherit ?\n) (newline 1))
23084 (save-excursion (forward-char -1) (delete-horizontal-space))
23085 (delete-horizontal-space)
23086 (indent-to-left-margin)
23087 (insert-before-markers-and-inherit fill-prefix))
23090 ;;; Fixed Width Areas
23092 (defun org-toggle-fixed-width ()
23093 "Toggle fixed-width markup.
23095 Add or remove fixed-width markup on current line, whenever it
23096 makes sense. Return an error otherwise.
23098 If a region is active and if it contains only fixed-width areas
23099 or blank lines, remove all fixed-width markup in it. If the
23100 region contains anything else, convert all non-fixed-width lines
23101 to fixed-width ones.
23103 Blank lines at the end of the region are ignored unless the
23104 region only contains such lines."
23106 (if (not (org-region-active-p))
23109 ;; Remove fixed width marker only in a fixed-with element.
23111 ;; Add fixed width maker in paragraphs, in blank lines after
23112 ;; elements or at the beginning of a headline or an inlinetask,
23113 ;; and before any one-line elements (e.g., a clock).
23115 (beginning-of-line)
23116 (let* ((element (org-element-at-point))
23117 (type (org-element-type element)))
23119 ((and (eq type 'fixed-width)
23120 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23122 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23123 ((and (memq type '(babel-call clock comment diary-sexp headline
23124 horizontal-rule keyword paragraph
23126 (<= (org-element-property :post-affiliated element) (point)))
23127 (skip-chars-forward " \t")
23129 ((and (looking-at-p "[ \t]*$")
23130 (or (eq type 'inlinetask)
23132 (skip-chars-forward " \r\t\n")
23133 (<= (org-element-property :end element) (point)))))
23134 (delete-region (point) (line-end-position))
23137 (t (user-error "Cannot insert a fixed-width line here")))))
23139 (let* ((begin (save-excursion
23140 (goto-char (region-beginning))
23141 (line-beginning-position)))
23144 (goto-char (region-end))
23145 (unless (eolp) (beginning-of-line))
23146 (if (save-excursion (re-search-backward "\\S-" begin t))
23147 (progn (skip-chars-backward " \r\t\n") (point))
23153 (skip-chars-forward " \r\t\n")
23154 (when (eobp) (throw 'not-all-p nil))
23155 (while (< (point) end)
23156 (let ((element (org-element-at-point)))
23157 (if (eq (org-element-type element) 'fixed-width)
23158 (goto-char (org-element-property :end element))
23159 (throw 'not-all-p nil))))
23161 (if all-fixed-width-p
23164 (while (< (point) end)
23165 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23168 (if (= (line-end-position) (match-end 0)) 0 1)))
23170 (let ((min-ind (point-max)))
23171 ;; Find minimum indentation across all lines.
23174 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23177 (while (< (point) end)
23178 (unless (looking-at-p "[ \t]*$")
23179 (let ((ind (org-get-indentation)))
23180 (setq min-ind (min min-ind ind))
23181 (when (zerop ind) (throw 'zerop t))))
23183 ;; Loop over all lines and add fixed-width markup everywhere
23184 ;; but in fixed-width lines.
23187 (while (< (point) end)
23189 ((org-at-heading-p)
23192 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23195 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23196 (let* ((element (org-element-at-point))
23197 (element-end (org-element-property :end element)))
23198 (if (eq (org-element-type element) 'fixed-width)
23199 (progn (goto-char element-end)
23200 (skip-chars-backward " \r\t\n")
23202 (let ((limit (min end element-end)))
23203 (while (< (point) limit)
23204 (org-move-to-column min-ind t)
23206 (forward-line))))))
23208 (org-move-to-column min-ind t)
23210 (forward-line)))))))
23211 (set-marker end nil))))
23216 ;; Org comments syntax is quite complex. It requires the entire line
23217 ;; to be just a comment. Also, even with the right syntax at the
23218 ;; beginning of line, some elements (e.g., verse-block or
23219 ;; example-block) don't accept comments. Usual Emacs comment commands
23220 ;; cannot cope with those requirements. Therefore, Org replaces them.
23222 ;; Org still relies on `comment-dwim', but cannot trust
23223 ;; `comment-only-p'. So, `comment-region-function' and
23224 ;; `uncomment-region-function' both point
23225 ;; to`org-comment-or-uncomment-region'. Eventually,
23226 ;; `org-insert-comment' takes care of insertion of comments at the
23227 ;; beginning of line.
23229 ;; `org-setup-comments-handling' install comments related variables
23230 ;; during `org-mode' initialization.
23232 (defun org-setup-comments-handling ()
23234 (setq-local comment-use-syntax nil)
23235 (setq-local comment-start "# ")
23236 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23237 (setq-local comment-insert-comment-function 'org-insert-comment)
23238 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23239 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23241 (defun org-insert-comment ()
23242 "Insert an empty comment above current line.
23243 If the line is empty, insert comment at its beginning. When
23244 point is within a source block, comment according to the related
23246 (if (let ((element (org-element-at-point)))
23247 (and (eq (org-element-type element) 'src-block)
23249 (goto-char (org-element-property :post-affiliated element))
23250 (line-end-position))
23253 (goto-char (org-element-property :end element))
23254 (skip-chars-backward " \r\t\n")
23255 (line-beginning-position))
23257 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23258 (beginning-of-line)
23259 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23264 (defvar comment-empty-lines) ; From newcomment.el.
23265 (defun org-comment-or-uncomment-region (beg end &rest _)
23266 "Comment or uncomment each non-blank line in the region.
23267 Uncomment each non-blank line between BEG and END if it only
23268 contains commented lines. Otherwise, comment them. If region is
23269 strictly within a source block, use appropriate comment syntax."
23270 (if (let ((element (org-element-at-point)))
23271 (and (eq (org-element-type element) 'src-block)
23273 (goto-char (org-element-property :post-affiliated element))
23274 (line-end-position))
23276 (>= (save-excursion
23277 (goto-char (org-element-property :end element))
23278 (skip-chars-backward " \r\t\n")
23279 (line-beginning-position))
23281 ;; Translate region boundaries for the Org buffer to the source
23283 (let ((offset (- end beg)))
23286 (org-babel-do-in-edit-buffer
23287 (comment-or-uncomment-region (point) (+ offset (point))))))
23290 (narrow-to-region (save-excursion (goto-char beg)
23291 (skip-chars-forward " \r\t\n" end)
23292 (line-beginning-position))
23293 (save-excursion (goto-char end)
23294 (skip-chars-backward " \r\t\n" beg)
23295 (line-end-position)))
23297 ;; UNCOMMENTP is non-nil when every non blank line between
23298 ;; BEG and END is a comment.
23300 (goto-char (point-min))
23301 (while (and (not (eobp))
23302 (let ((element (org-element-at-point)))
23303 (and (eq (org-element-type element) 'comment)
23304 (goto-char (min (point-max)
23305 (org-element-property
23306 :end element)))))))
23309 ;; Only blank lines and comments in region: uncomment it.
23311 (goto-char (point-min))
23312 (while (not (eobp))
23313 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23314 (replace-match "" nil nil nil 1))
23316 ;; Comment each line in region.
23317 (let ((min-indent (point-max)))
23318 ;; First find the minimum indentation across all lines.
23320 (goto-char (point-min))
23321 (while (and (not (eobp)) (not (zerop min-indent)))
23322 (unless (looking-at "[ \t]*$")
23323 (setq min-indent (min min-indent (current-indentation))))
23325 ;; Then loop over all lines.
23327 (goto-char (point-min))
23328 (while (not (eobp))
23329 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23330 ;; Don't get fooled by invisible text (e.g. link path)
23331 ;; when moving to column MIN-INDENT.
23332 (let ((buffer-invisibility-spec nil))
23333 (org-move-to-column min-indent t))
23334 (insert comment-start))
23335 (forward-line)))))))))
23337 (defun org-comment-dwim (_arg)
23338 "Call `comment-dwim' within a source edit buffer if needed."
23340 (if (org-in-src-block-p)
23341 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23342 (call-interactively 'comment-dwim)))
23347 ;; This section contains tools to operate on timestamp objects, as
23348 ;; returned by, e.g. `org-element-context'.
23350 (defun org-timestamp--to-internal-time (timestamp &optional end)
23351 "Encode TIMESTAMP object into Emacs internal time.
23352 Use end of date range or time range when END is non-nil."
23353 (apply #'encode-time
23356 (lambda (prop) (or (org-element-property prop timestamp) 0))
23357 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23358 '(:minute-start :hour-start :day-start :month-start
23361 (defun org-timestamp-has-time-p (timestamp)
23362 "Non-nil when TIMESTAMP has a time specified."
23363 (org-element-property :hour-start timestamp))
23365 (defun org-timestamp-format (timestamp format &optional end utc)
23366 "Format a TIMESTAMP object into a string.
23368 FORMAT is a format specifier to be passed to
23369 `format-time-string'.
23371 When optional argument END is non-nil, use end of date-range or
23372 time-range, if possible.
23374 When optional argument UTC is non-nil, time will be expressed as
23376 (format-time-string
23377 format (org-timestamp--to-internal-time timestamp end)
23380 (defun org-timestamp-split-range (timestamp &optional end)
23381 "Extract a TIMESTAMP object from a date or time range.
23383 END, when non-nil, means extract the end of the range.
23384 Otherwise, extract its start.
23386 Return a new timestamp object."
23387 (let ((type (org-element-property :type timestamp)))
23388 (if (memq type '(active inactive diary)) timestamp
23389 (let ((split-ts (org-element-copy timestamp)))
23391 (org-element-put-property
23392 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23393 ;; Copy start properties over end properties if END is
23394 ;; non-nil. Otherwise, copy end properties over `start' ones.
23395 (let ((p-alist '((:minute-start . :minute-end)
23396 (:hour-start . :hour-end)
23397 (:day-start . :day-end)
23398 (:month-start . :month-end)
23399 (:year-start . :year-end))))
23400 (dolist (p-cell p-alist)
23401 (org-element-put-property
23403 (funcall (if end #'car #'cdr) p-cell)
23404 (org-element-property
23405 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23406 ;; Eventually refresh `:raw-value'.
23407 (org-element-put-property split-ts :raw-value nil)
23408 (org-element-put-property
23409 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23411 (defun org-timestamp-translate (timestamp &optional boundary)
23412 "Translate TIMESTAMP object to custom format.
23414 Format string is defined in `org-time-stamp-custom-formats',
23417 When optional argument BOUNDARY is non-nil, it is either the
23418 symbol `start' or `end'. In this case, only translate the
23419 starting or ending part of TIMESTAMP if it is a date or time
23420 range. Otherwise, translate both parts.
23422 Return timestamp as-is if `org-display-custom-times' is nil or if
23423 it has a `diary' type."
23424 (let ((type (org-element-property :type timestamp)))
23425 (if (or (not org-display-custom-times) (eq type 'diary))
23426 (org-element-interpret-data timestamp)
23427 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23428 org-time-stamp-custom-formats)))
23429 (if (and (not boundary) (memq type '(active-range inactive-range)))
23430 (concat (org-timestamp-format timestamp fmt)
23432 (org-timestamp-format timestamp fmt t))
23433 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23439 (defvar reftex-docstruct-symbol)
23442 (defun org-reftex-citation ()
23443 "Use reftex-citation to insert a citation into the buffer.
23444 This looks for a line like
23446 #+BIBLIOGRAPHY: foo plain option:-d
23448 and derives from it that foo.bib is the bibliography file relevant
23449 for this document. It then installs the necessary environment for RefTeX
23450 to work in this buffer and calls `reftex-citation' to insert a citation
23453 Export of such citations to both LaTeX and HTML is handled by the contributed
23454 package ox-bibtex by Taru Karttunen."
23456 (let ((reftex-docstruct-symbol 'org--rds)
23458 (org-with-wide-buffer
23459 (let ((case-fold-search t)
23460 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23461 (if (not (save-excursion
23462 (or (re-search-forward re nil t)
23463 (re-search-backward re nil t))))
23464 (user-error "No bibliography defined in file")
23465 (setq bib (concat (match-string 1) ".bib")
23466 org--rds (list (list 'bib bib))))))
23467 (call-interactively 'reftex-citation)))
23469 ;;;; Functions extending outline functionality
23471 (defun org-beginning-of-line (&optional n)
23472 "Go to the beginning of the current visible line.
23474 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23475 tags on the first attempt, and only move to after the tags when
23476 the cursor is already beyond the end of the headline.
23478 With argument N not nil or 1, move forward N - 1 lines first."
23480 (let ((origin (point))
23481 (special (pcase org-special-ctrl-a/e
23482 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23484 ;; First move to a visible line.
23485 (if (bound-and-true-p visual-line-mode)
23486 (beginning-of-visual-line n)
23487 (move-beginning-of-line n)
23488 ;; `move-beginning-of-line' may leave point after invisible
23489 ;; characters if line starts with such of these (e.g., with
23490 ;; a link at column 0). Really move to the beginning of the
23491 ;; current visible line.
23492 (beginning-of-line))
23494 ;; No special behavior. Point is already at the beginning of
23495 ;; a line, logical or visual.
23497 ;; `beginning-of-visual-line' left point before logical beginning
23498 ;; of line: point is at the beginning of a visual line. Bail
23500 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23501 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23502 ;; At a headline, special position is before the title, but
23503 ;; after any TODO keyword or priority cookie.
23504 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23505 (line-end-position)))
23507 (if (eq special 'reversed)
23508 (when (and (= origin bol) (eq last-command this-command))
23509 (goto-char refpos))
23510 (when (or (> origin refpos) (= origin bol))
23511 (goto-char refpos)))))
23512 ((and (looking-at org-list-full-item-re)
23513 (memq (org-element-type (save-match-data (org-element-at-point)))
23514 '(item plain-list)))
23515 ;; Set special position at first white space character after
23516 ;; bullet, and check-box, if any.
23517 (let ((after-bullet
23518 (let ((box (match-end 3)))
23519 (cond ((not box) (match-end 1))
23520 ((eq (char-after box) ?\s) (1+ box))
23522 (if (eq special 'reversed)
23523 (when (and (= (point) origin) (eq last-command this-command))
23524 (goto-char after-bullet))
23525 (when (or (> origin after-bullet) (= (point) origin))
23526 (goto-char after-bullet)))))
23527 ;; No special context. Point is already at beginning of line.
23530 (defun org-end-of-line (&optional n)
23531 "Go to the end of the line, but before ellipsis, if any.
23533 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23534 tags on the first attempt, and only move to after the tags when
23535 the cursor is already beyond the end of the headline.
23537 With argument N not nil or 1, move forward N - 1 lines first."
23539 (let ((origin (point))
23540 (special (pcase org-special-ctrl-a/e
23541 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23543 ;; First move to a visible line.
23544 (if (bound-and-true-p visual-line-mode)
23545 (beginning-of-visual-line n)
23546 (move-beginning-of-line n))
23548 ;; At a headline, with tags.
23551 (beginning-of-line)
23552 (let ((case-fold-search nil))
23553 (looking-at org-complex-heading-regexp)))
23555 (let ((tags (save-excursion
23556 (goto-char (match-beginning 5))
23557 (skip-chars-backward " \t")
23559 (visual-end (and (bound-and-true-p visual-line-mode)
23561 (end-of-visual-line)
23563 ;; If `end-of-visual-line' brings us before end of line or
23564 ;; even tags, i.e., the headline spans over multiple visual
23565 ;; lines, move there.
23566 (cond ((and visual-end
23567 (< visual-end tags)
23568 (<= origin visual-end))
23569 (goto-char visual-end))
23570 ((eq special 'reversed)
23571 (if (and (= origin (line-end-position))
23572 (eq this-command last-command))
23576 (if (or (< origin tags) (= origin (line-end-position)))
23579 ((bound-and-true-p visual-line-mode)
23580 (let ((bol (line-beginning-position)))
23581 (end-of-visual-line)
23582 ;; If `end-of-visual-line' gets us past the ellipsis at the
23583 ;; end of a line, backtrack and use `end-of-line' instead.
23584 (when (/= bol (line-beginning-position))
23587 (t (end-of-line)))))
23589 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23590 (define-key org-mode-map "\C-e" 'org-end-of-line)
23592 (defun org-backward-sentence (&optional _arg)
23593 "Go to beginning of sentence, or beginning of table field.
23594 This will call `backward-sentence' or `org-table-beginning-of-field',
23595 depending on context."
23597 (let* ((element (org-element-at-point))
23598 (contents-begin (org-element-property :contents-begin element))
23599 (table (org-element-lineage element '(table) t)))
23601 (> (point) contents-begin)
23602 (<= (point) (org-element-property :contents-end table)))
23603 (call-interactively #'org-table-beginning-of-field)
23605 (when (and contents-begin
23606 (< (point-min) contents-begin)
23607 (> (point) contents-begin))
23608 (narrow-to-region contents-begin
23609 (org-element-property :contents-end element)))
23610 (call-interactively #'backward-sentence)))))
23612 (defun org-forward-sentence (&optional _arg)
23613 "Go to end of sentence, or end of table field.
23614 This will call `forward-sentence' or `org-table-end-of-field',
23615 depending on context."
23617 (if (and (org-at-heading-p)
23618 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23620 (narrow-to-region (line-beginning-position) (line-end-position))
23621 (call-interactively #'forward-sentence))
23622 (let* ((element (org-element-at-point))
23623 (contents-end (org-element-property :contents-end element))
23624 (table (org-element-lineage element '(table) t)))
23626 (>= (point) (org-element-property :contents-begin table))
23627 (< (point) contents-end))
23628 (call-interactively #'org-table-end-of-field)
23630 (when (and contents-end
23631 (> (point-max) contents-end)
23632 ;; Skip blank lines between elements.
23633 (< (org-element-property :end element)
23634 (save-excursion (goto-char contents-end)
23635 (skip-chars-forward " \r\t\n"))))
23636 (narrow-to-region (org-element-property :contents-begin element)
23638 ;; End of heading is considered as the end of a sentence.
23639 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
23640 (call-interactively #'forward-sentence)))))))
23642 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23643 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23645 (defun org-kill-line (&optional _arg)
23646 "Kill line, to tags or end of line."
23649 ((or (not org-special-ctrl-k)
23651 (not (org-at-heading-p)))
23652 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23653 org-ctrl-k-protect-subtree
23654 (or (eq org-ctrl-k-protect-subtree 'error)
23655 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23656 (user-error "C-k aborted as it would kill a hidden subtree"))
23657 (call-interactively
23658 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23659 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23660 (kill-region (point) (match-beginning 1))
23661 (org-set-tags nil t))
23662 (t (kill-region (point) (point-at-eol)))))
23664 (define-key org-mode-map "\C-k" 'org-kill-line)
23666 (defun org-yank (&optional arg)
23667 "Yank. If the kill is a subtree, treat it specially.
23668 This command will look at the current kill and check if is a single
23669 subtree, or a series of subtrees[1]. If it passes the test, and if the
23670 cursor is at the beginning of a line or after the stars of a currently
23671 empty headline, then the yank is handled specially. How exactly depends
23672 on the value of the following variables.
23674 `org-yank-folded-subtrees'
23675 By default, this variable is non-nil, which results in
23676 subtree(s) being folded after insertion, except if doing so
23677 would swallow text after the yanked text.
23679 `org-yank-adjusted-subtrees'
23680 When non-nil (the default value is nil), the subtree will be
23681 promoted or demoted in order to fit into the local outline tree
23682 structure, which means that the level will be adjusted so that it
23683 becomes the smaller one of the two *visible* surrounding headings.
23685 Any prefix to this command will cause `yank' to be called directly with
23686 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23688 plainly yank the text as it is.
23690 \[1] The test checks if the first non-white line is a heading
23691 and if there are no other headings with fewer stars."
23693 (org-yank-generic 'yank arg))
23695 (defun org-yank-generic (command arg)
23696 "Perform some yank-like command.
23698 This function implements the behavior described in the `org-yank'
23699 documentation. However, it has been generalized to work for any
23700 interactive command with similar behavior."
23702 ;; pretend to be command COMMAND
23703 (setq this-command command)
23706 (call-interactively command)
23708 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23709 (and (org-kill-is-subtree-p)
23711 (and (looking-at "[ \t]*$")
23714 (buffer-substring (point-at-bol) (point)))))))
23717 ((and subtreep org-yank-folded-subtrees)
23718 (let ((beg (point))
23720 (if (and subtreep org-yank-adjusted-subtrees)
23721 (org-paste-subtree nil nil 'for-yank)
23722 (call-interactively command))
23726 (when (and (bolp) subtreep
23727 (not (setq swallowp
23728 (org-yank-folding-would-swallow-text beg end))))
23729 (org-with-limited-levels
23730 (or (looking-at org-outline-regexp)
23731 (re-search-forward org-outline-regexp-bol end t))
23732 (while (and (< (point) end) (looking-at org-outline-regexp))
23733 (outline-hide-subtree)
23734 (org-cycle-show-empty-lines 'folded)
23735 (condition-case nil
23736 (outline-forward-same-level 1)
23737 (error (goto-char end))))))
23740 "Inserted text not folded because that would swallow text"))
23743 (skip-chars-forward " \t\n\r")
23744 (beginning-of-line 1)
23745 (push-mark beg 'nomsg)))
23746 ((and subtreep org-yank-adjusted-subtrees)
23747 (let ((beg (point-at-bol)))
23748 (org-paste-subtree nil nil 'for-yank)
23749 (push-mark beg 'nomsg)))
23751 (call-interactively command))))))
23753 (defun org-yank-folding-would-swallow-text (beg end)
23754 "Would hide-subtree at BEG swallow any text after END?"
23756 (org-with-limited-levels
23759 (when (or (looking-at org-outline-regexp)
23760 (re-search-forward org-outline-regexp-bol end t))
23761 (setq level (org-outline-level)))
23763 (skip-chars-forward " \t\r\n\v\f")
23765 (and (bolp) (looking-at-p org-outline-regexp)
23766 (<= (org-outline-level) level))))))))
23768 (define-key org-mode-map "\C-y" 'org-yank)
23770 (defun org-truely-invisible-p ()
23771 "Check if point is at a character currently not visible.
23772 This version does not only check the character property, but also
23774 (unless (bound-and-true-p visible-mode)
23775 (org-invisible-p)))
23777 (defun org-invisible-p2 ()
23778 "Check if point is at a character currently not visible.
23780 If the point is at EOL (and not at the beginning of a buffer too),
23781 move it back by one char before doing this check."
23783 (when (and (eolp) (not (bobp)))
23785 (org-invisible-p)))
23787 (defun org-back-to-heading (&optional invisible-ok)
23788 "Call `outline-back-to-heading', but provide a better error message."
23789 (condition-case nil
23790 (outline-back-to-heading invisible-ok)
23791 (error (error "Before first headline at position %d in buffer %s"
23792 (point) (current-buffer)))))
23794 (defun org-before-first-heading-p ()
23795 "Before first heading?"
23798 (null (re-search-backward org-outline-regexp-bol nil t))))
23800 (defun org-at-heading-p (&optional ignored)
23801 (outline-on-heading-p t))
23803 (defun org-in-commented-heading-p (&optional no-inheritance)
23804 "Non-nil if point is under a commented heading.
23805 This function also checks ancestors of the current headline,
23806 unless optional argument NO-INHERITANCE is non-nil."
23808 ((org-before-first-heading-p) nil)
23809 ((let ((headline (nth 4 (org-heading-components))))
23811 (let ((case-fold-search nil))
23812 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23814 (no-inheritance nil)
23816 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23818 (defun org-at-comment-p nil
23819 "Is cursor in a commented line?"
23822 (beginning-of-line)
23823 (looking-at "^[ \t]*# "))))
23825 (defun org-at-drawer-p nil
23826 "Is cursor at a drawer keyword?"
23828 (move-beginning-of-line 1)
23829 (looking-at org-drawer-regexp)))
23831 (defun org-at-block-p nil
23832 "Is cursor at a block keyword?"
23834 (move-beginning-of-line 1)
23835 (looking-at org-block-regexp)))
23837 (defun org-point-at-end-of-empty-headline ()
23838 "If point is at the end of an empty headline, return t, else nil.
23839 If the heading only contains a TODO keyword, it is still still considered
23841 (let ((case-fold-search nil))
23842 (and (looking-at "[ \t]*$")
23843 org-todo-line-regexp
23845 (beginning-of-line)
23846 (looking-at org-todo-line-regexp)
23847 (string= (match-string 3) "")))))
23849 (defun org-at-heading-or-item-p ()
23850 (or (org-at-heading-p) (org-at-item-p)))
23852 (defun org-at-target-p ()
23853 (or (org-in-regexp org-radio-target-regexp)
23854 (org-in-regexp org-target-regexp)))
23855 ;; Compatibility alias with Org versions < 7.8.03
23856 (defalias 'org-on-target-p 'org-at-target-p)
23858 (defun org-up-heading-all (arg)
23859 "Move to the heading line of which the present line is a subheading.
23860 This function considers both visible and invisible heading lines.
23861 With argument, move up ARG levels."
23862 (outline-up-heading arg t))
23864 (defun org-up-heading-safe ()
23865 "Move to the heading line of which the present line is a subheading.
23866 This version will not throw an error. It will return the level of the
23867 headline found, or nil if no higher level is found.
23869 Also, this function will be a lot faster than `outline-up-heading',
23870 because it relies on stars being the outline starters. This can really
23871 make a significant difference in outlines with very many siblings."
23872 (when (ignore-errors (org-back-to-heading t))
23873 (let ((level-up (1- (funcall outline-level))))
23874 (and (> level-up 0)
23875 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23876 (funcall outline-level)))))
23878 (defun org-first-sibling-p ()
23879 "Is this heading the first child of its parents?"
23881 (let ((re org-outline-regexp-bol)
23883 (unless (org-at-heading-p t)
23884 (user-error "Not at a heading"))
23885 (setq level (funcall outline-level))
23887 (if (not (re-search-backward re nil t))
23889 (setq l (funcall outline-level))
23892 (defun org-goto-sibling (&optional previous)
23893 "Goto the next sibling, even if it is invisible.
23894 When PREVIOUS is set, go to the previous sibling instead. Returns t
23895 when a sibling was found. When none is found, return nil and don't
23897 (let ((fun (if previous 're-search-backward 're-search-forward))
23899 (re org-outline-regexp-bol)
23901 (when (ignore-errors (org-back-to-heading t))
23902 (setq level (funcall outline-level))
23904 (or previous (forward-char 1))
23905 (while (funcall fun re nil t)
23906 (setq l (funcall outline-level))
23907 (when (< l level) (goto-char pos) (throw 'exit nil))
23908 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23912 (defun org-show-siblings ()
23913 "Show all siblings of the current headline."
23915 (while (org-goto-sibling) (org-flag-heading nil)))
23917 (while (org-goto-sibling 'previous)
23918 (org-flag-heading nil))))
23920 (defun org-goto-first-child ()
23921 "Goto the first child, even if it is invisible.
23922 Return t when a child was found. Otherwise don't move point and
23924 (let (level (pos (point)) (re org-outline-regexp-bol))
23925 (when (ignore-errors (org-back-to-heading t))
23926 (setq level (outline-level))
23928 (if (and (re-search-forward re nil t) (> (outline-level) level))
23929 (progn (goto-char (match-beginning 0)) t)
23930 (goto-char pos) nil))))
23932 (defun org-show-hidden-entry ()
23933 "Show an entry where even the heading is hidden."
23937 (defun org-flag-heading (flag &optional entry)
23938 "Flag the current heading. FLAG non-nil means make invisible.
23939 When ENTRY is non-nil, show the entire entry."
23941 (org-back-to-heading t)
23942 ;; Check if we should show the entire entry
23947 (and (outline-next-heading)
23948 (org-flag-heading nil))))
23949 (outline-flag-region (max (point-min) (1- (point)))
23950 (save-excursion (outline-end-of-heading) (point))
23953 (defun org-get-next-sibling ()
23954 "Move to next heading of the same level, and return point.
23955 If there is no such heading, return nil.
23956 This is like outline-next-sibling, but invisible headings are ok."
23957 (let ((level (funcall outline-level)))
23958 (outline-next-heading)
23959 (while (and (not (eobp)) (> (funcall outline-level) level))
23960 (outline-next-heading))
23961 (unless (or (eobp) (< (funcall outline-level) level))
23964 (defun org-get-last-sibling ()
23965 "Move to previous heading of the same level, and return point.
23966 If there is no such heading, return nil."
23967 (let ((opoint (point))
23968 (level (funcall outline-level)))
23969 (outline-previous-heading)
23970 (when (and (/= (point) opoint) (outline-on-heading-p t))
23971 (while (and (> (funcall outline-level) level)
23973 (outline-previous-heading))
23974 (unless (< (funcall outline-level) level)
23977 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23978 "Goto to the end of a subtree."
23979 ;; This contains an exact copy of the original function, but it uses
23980 ;; `org-back-to-heading', to make it work also in invisible
23981 ;; trees. And is uses an invisible-ok argument.
23982 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23983 ;; Furthermore, when used inside Org, finding the end of a large subtree
23984 ;; with many children and grandchildren etc, this can be much faster
23985 ;; than the outline version.
23986 (org-back-to-heading invisible-ok)
23988 (level (funcall outline-level)))
23989 (if (and (derived-mode-p 'org-mode) (< level 1000))
23990 ;; A true heading (not a plain list item), in Org
23991 ;; This means we can easily find the end by looking
23992 ;; only for the right number of stars. Using a regexp to do
23993 ;; this is so much faster than using a Lisp loop.
23994 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23996 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23997 ;; something else, do it the slow way
23998 (while (and (not (eobp))
23999 (or first (> (funcall outline-level) level)))
24001 (outline-next-heading)))
24003 (when (memq (preceding-char) '(?\n ?\^M))
24004 ;; Go to end of line before heading
24006 (when (memq (preceding-char) '(?\n ?\^M))
24007 ;; leave blank line before heading
24008 (forward-char -1)))))
24011 (defun org-end-of-meta-data (&optional full)
24012 "Skip planning line and properties drawer in current entry.
24013 When optional argument FULL is non-nil, also skip empty lines,
24014 clocking lines and regular drawers at the beginning of the
24016 (org-back-to-heading t)
24018 (when (looking-at-p org-planning-line-re) (forward-line))
24019 (when (looking-at org-property-drawer-re)
24020 (goto-char (match-end 0))
24022 (when (and full (not (org-at-heading-p)))
24024 (let ((end (save-excursion (outline-next-heading) (point)))
24025 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24026 (while (not (eobp))
24027 (cond ((looking-at-p org-drawer-regexp)
24028 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24031 ((looking-at-p re) (forward-line))
24032 (t (throw 'exit t))))))))
24034 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24035 "Move forward to the ARG'th subheading at same level as this one.
24036 Stop at the first and last subheadings of a superior heading.
24037 Normally this only looks at visible headings, but when INVISIBLE-OK is
24038 non-nil it will also look at invisible ones."
24040 (let ((backward? (and arg (< arg 0))))
24041 (if (org-before-first-heading-p)
24042 (if backward? (goto-char (point-min)) (outline-next-heading))
24043 (org-back-to-heading invisible-ok)
24044 (unless backward? (end-of-line)) ;do not match current headline
24045 (let ((level (- (match-end 0) (match-beginning 0) 1))
24046 (f (if backward? #'re-search-backward #'re-search-forward))
24047 (count (if arg (abs arg) 1))
24049 (while (and (> count 0)
24050 (funcall f org-outline-regexp-bol nil 'move))
24051 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24052 (cond ((< l level) (setq count 0))
24055 (not (org-invisible-p
24056 (line-beginning-position)))))
24058 (when (= l level) (setq result (point)))))))
24059 (goto-char result))
24060 (beginning-of-line))))
24062 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24063 "Move backward to the ARG'th subheading at same level as this one.
24064 Stop at the first and last subheadings of a superior heading."
24066 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24068 (defun org-next-visible-heading (arg)
24069 "Move to the next visible heading.
24071 This function wraps `outline-next-visible-heading' with
24072 `org-with-limited-levels' in order to skip over inline tasks and
24073 respect customization of `org-odd-levels-only'."
24075 (org-with-limited-levels
24076 (outline-next-visible-heading arg)))
24078 (defun org-previous-visible-heading (arg)
24079 "Move to the previous visible heading.
24081 This function wraps `outline-previous-visible-heading' with
24082 `org-with-limited-levels' in order to skip over inline tasks and
24083 respect customization of `org-odd-levels-only'."
24085 (org-with-limited-levels
24086 (outline-previous-visible-heading arg)))
24088 (defun org-next-block (arg &optional backward block-regexp)
24089 "Jump to the next block.
24091 With a prefix argument ARG, jump forward ARG many blocks.
24093 When BACKWARD is non-nil, jump to the previous block.
24095 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24096 Match data is set according to this regexp when the function
24099 Return point at beginning of the opening line of found block.
24100 Throw an error if no block is found."
24102 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24103 (case-fold-search t)
24104 (search-fn (if backward #'re-search-backward #'re-search-forward))
24108 (if backward (beginning-of-line) (end-of-line))
24109 (while (and (> count 0) (funcall search-fn re nil t))
24110 (let ((element (save-excursion
24111 (goto-char (match-beginning 0))
24112 (save-match-data (org-element-at-point)))))
24113 (when (and (memq (org-element-type element)
24114 '(center-block comment-block dynamic-block
24115 example-block export-block quote-block
24116 special-block src-block verse-block))
24117 (<= (match-beginning 0)
24118 (org-element-property :post-affiliated element)))
24119 (setq last-element element)
24122 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24123 (save-match-data (org-show-context)))
24125 (user-error "No %s code blocks" (if backward "previous" "further")))))
24127 (defun org-previous-block (arg &optional block-regexp)
24128 "Jump to the previous block.
24129 With a prefix argument ARG, jump backward ARG many source blocks.
24130 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24132 (org-next-block arg t block-regexp))
24134 (defun org-forward-paragraph ()
24135 "Move forward to beginning of next paragraph or equivalent.
24137 The function moves point to the beginning of the next visible
24138 structural element, which can be a paragraph, a table, a list
24139 item, etc. It also provides some special moves for convenience:
24141 - On an affiliated keyword, jump to the beginning of the
24143 - On an item or a footnote definition, move to the second
24144 element inside, if any.
24145 - On a table or a property drawer, jump after it.
24146 - On a verse or source block, stop after blank lines."
24149 (let* ((deactivate-mark nil)
24150 (element (org-element-at-point))
24151 (type (org-element-type element))
24152 (post-affiliated (org-element-property :post-affiliated element))
24153 (contents-begin (org-element-property :contents-begin element))
24154 (contents-end (org-element-property :contents-end element))
24155 (end (let ((end (org-element-property :end element)) (parent element))
24156 (while (and (setq parent (org-element-property :parent parent))
24157 (= (org-element-property :contents-end parent) end))
24158 (setq end (org-element-property :end parent)))
24160 (cond ((not element)
24161 (skip-chars-forward " \r\t\n")
24162 (or (eobp) (beginning-of-line)))
24163 ;; On affiliated keywords, move to element's beginning.
24164 ((< (point) post-affiliated)
24165 (goto-char post-affiliated))
24166 ;; At a table row, move to the end of the table. Similarly,
24167 ;; at a node property, move to the end of the property
24169 ((memq type '(node-property table-row))
24170 (goto-char (org-element-property
24171 :end (org-element-property :parent element))))
24172 ((memq type '(property-drawer table)) (goto-char end))
24173 ;; Consider blank lines as separators in verse and source
24174 ;; blocks to ease editing.
24175 ((memq type '(src-block verse-block))
24176 (when (eq type 'src-block)
24178 (save-excursion (goto-char end)
24179 (skip-chars-backward " \r\t\n")
24180 (line-beginning-position))))
24181 (beginning-of-line)
24182 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24183 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24185 (skip-chars-forward " \r\t\n")
24186 (if (= (point) contents-end) (goto-char end)
24187 (beginning-of-line))))
24188 ;; With no contents, just skip element.
24189 ((not contents-begin) (goto-char end))
24190 ;; If contents are invisible, skip the element altogether.
24191 ((org-invisible-p (line-end-position))
24194 (org-with-limited-levels (outline-next-visible-heading 1)))
24195 ;; At a plain list, make sure we move to the next item
24196 ;; instead of skipping the whole list.
24197 (plain-list (forward-char)
24198 (org-forward-paragraph))
24199 (otherwise (goto-char end))))
24200 ((>= (point) contents-end) (goto-char end))
24201 ((>= (point) contents-begin)
24202 ;; This can only happen on paragraphs and plain lists.
24204 (paragraph (goto-char end))
24205 ;; At a plain list, try to move to second element in
24206 ;; first item, if possible.
24207 (plain-list (end-of-line)
24208 (org-forward-paragraph))))
24209 ;; When contents start on the middle of a line (e.g. in
24210 ;; items and footnote definitions), try to reach first
24211 ;; element starting after current line.
24212 ((> (line-end-position) contents-begin)
24214 (org-forward-paragraph))
24215 (t (goto-char contents-begin))))))
24217 (defun org-backward-paragraph ()
24218 "Move backward to start of previous paragraph or equivalent.
24220 The function moves point to the beginning of the current
24221 structural element, which can be a paragraph, a table, a list
24222 item, etc., or to the beginning of the previous visible one if
24223 point is already there. It also provides some special moves for
24226 - On an affiliated keyword, jump to the first one.
24227 - On a table or a property drawer, move to its beginning.
24228 - On comment, example, export, src and verse blocks, stop
24229 before blank lines."
24232 (let* ((deactivate-mark nil)
24233 (element (org-element-at-point))
24234 (type (org-element-type element))
24235 (contents-end (org-element-property :contents-end element))
24236 (post-affiliated (org-element-property :post-affiliated element))
24237 (begin (org-element-property :begin element))
24238 (special? ;blocks handled specially
24239 (memq type '(comment-block example-block export-block src-block
24243 ;; These types have no proper contents. Fake line
24244 ;; below the block opening line as contents beginning.
24245 (save-excursion (goto-char begin) (line-beginning-position 2))
24246 (org-element-property :contents-begin element))))
24248 ((not element) (goto-char (point-min)))
24251 (org-backward-paragraph))
24252 ((<= (point) post-affiliated) (goto-char begin))
24253 ;; Special behavior: on a table or a property drawer, move to
24255 ((memq type '(node-property table-row))
24256 (goto-char (org-element-property
24257 :post-affiliated (org-element-property :parent element))))
24259 (if (<= (point) contents-begin) (goto-char post-affiliated)
24260 ;; Inside a verse block, see blank lines as paragraph
24262 (let ((origin (point)))
24263 (skip-chars-backward " \r\t\n" contents-begin)
24264 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24265 (skip-chars-forward " \r\t\n" origin)
24266 (if (= (point) origin) (goto-char contents-begin)
24267 (beginning-of-line))))))
24268 ((eq type 'paragraph) (goto-char contents-begin)
24269 ;; When at first paragraph in an item or a footnote definition,
24270 ;; move directly to beginning of line.
24271 (let ((parent-contents
24272 (org-element-property
24273 :contents-begin (org-element-property :parent element))))
24274 (when (and parent-contents (= parent-contents contents-begin))
24275 (beginning-of-line))))
24276 ;; At the end of a greater element, move to the beginning of
24277 ;; the last element within.
24278 ((and contents-end (>= (point) contents-end))
24279 (goto-char (1- contents-end))
24280 (org-backward-paragraph))
24281 (t (goto-char (or post-affiliated begin))))
24282 ;; Ensure we never leave point invisible.
24283 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24285 (defun org-forward-element ()
24286 "Move forward by one element.
24287 Move to the next element at the same level, when possible."
24289 (cond ((eobp) (user-error "Cannot move further down"))
24290 ((org-with-limited-levels (org-at-heading-p))
24291 (let ((origin (point)))
24292 (goto-char (org-end-of-subtree nil t))
24293 (unless (org-with-limited-levels (org-at-heading-p))
24295 (user-error "Cannot move further down"))))
24297 (let* ((elem (org-element-at-point))
24298 (end (org-element-property :end elem))
24299 (parent (org-element-property :parent elem)))
24300 (cond ((and parent (= (org-element-property :contents-end parent) end))
24301 (goto-char (org-element-property :end parent)))
24302 ((integer-or-marker-p end) (goto-char end))
24303 (t (message "No element at point")))))))
24305 (defun org-backward-element ()
24306 "Move backward by one element.
24307 Move to the previous element at the same level, when possible."
24309 (cond ((bobp) (user-error "Cannot move further up"))
24310 ((org-with-limited-levels (org-at-heading-p))
24311 ;; At a headline, move to the previous one, if any, or stay
24313 (let ((origin (point)))
24314 (org-with-limited-levels (org-backward-heading-same-level 1))
24315 ;; When current headline has no sibling above, move to its
24317 (when (= (point) origin)
24318 (or (org-with-limited-levels (org-up-heading-safe))
24319 (progn (goto-char origin)
24320 (user-error "Cannot move further up"))))))
24322 (let* ((elem (org-element-at-point))
24323 (beg (org-element-property :begin elem)))
24325 ;; Move to beginning of current element if point isn't
24327 ((null beg) (message "No element at point"))
24328 ((/= (point) beg) (goto-char beg))
24330 (skip-chars-backward " \r\t\n")
24332 (let ((prev (org-element-at-point)))
24333 (goto-char (org-element-property :begin prev))
24334 (while (and (setq prev (org-element-property :parent prev))
24335 (<= (org-element-property :end prev) beg))
24336 (goto-char (org-element-property :begin prev)))))))))))
24338 (defun org-up-element ()
24339 "Move to upper element."
24341 (if (org-with-limited-levels (org-at-heading-p))
24342 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24343 (let* ((elem (org-element-at-point))
24344 (parent (org-element-property :parent elem)))
24345 (if parent (goto-char (org-element-property :begin parent))
24346 (if (org-with-limited-levels (org-before-first-heading-p))
24347 (user-error "No surrounding element")
24348 (org-with-limited-levels (org-back-to-heading)))))))
24350 (defun org-down-element ()
24351 "Move to inner element."
24353 (let ((element (org-element-at-point)))
24355 ((memq (org-element-type element) '(plain-list table))
24356 (goto-char (org-element-property :contents-begin element))
24358 ((memq (org-element-type element) org-element-greater-elements)
24359 ;; If contents are hidden, first disclose them.
24360 (when (org-invisible-p (line-end-position)) (org-cycle))
24361 (goto-char (or (org-element-property :contents-begin element)
24362 (user-error "No content for this element"))))
24363 (t (user-error "No inner element")))))
24365 (defun org-drag-element-backward ()
24366 "Move backward element at point."
24368 (let ((elem (or (org-element-at-point)
24369 (user-error "No element at point"))))
24370 (if (eq (org-element-type elem) 'headline)
24371 ;; Preserve point when moving a whole tree, even if point was
24372 ;; on blank lines below the headline.
24373 (let ((offset (skip-chars-backward " \t\n")))
24374 (unwind-protect (org-move-subtree-up)
24375 (forward-char (- offset))))
24378 (goto-char (org-element-property :begin elem))
24379 (skip-chars-backward " \r\t\n")
24381 (let* ((beg (org-element-property :begin elem))
24382 (prev (org-element-at-point))
24384 (while (and (setq up (org-element-property :parent up))
24385 (<= (org-element-property :end up) beg))
24388 ;; Error out if no previous element or previous element is
24389 ;; a parent of the current one.
24390 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24391 (user-error "Cannot drag element backward")
24392 (let ((pos (point)))
24393 (org-element-swap-A-B prev-elem elem)
24394 (goto-char (+ (org-element-property :begin prev-elem)
24395 (- pos (org-element-property :begin elem))))))))))
24397 (defun org-drag-element-forward ()
24398 "Move forward element at point."
24400 (let* ((pos (point))
24401 (elem (or (org-element-at-point)
24402 (user-error "No element at point"))))
24403 (when (= (point-max) (org-element-property :end elem))
24404 (user-error "Cannot drag element forward"))
24405 (goto-char (org-element-property :end elem))
24406 (let ((next-elem (org-element-at-point)))
24407 (when (or (org-element-nested-p elem next-elem)
24408 (and (eq (org-element-type next-elem) 'headline)
24409 (not (eq (org-element-type elem) 'headline))))
24411 (user-error "Cannot drag element forward"))
24412 ;; Compute new position of point: it's shifted by NEXT-ELEM
24413 ;; body's length (without final blanks) and by the length of
24414 ;; blanks between ELEM and NEXT-ELEM.
24415 (let ((size-next (- (save-excursion
24416 (goto-char (org-element-property :end next-elem))
24417 (skip-chars-backward " \r\t\n")
24419 ;; Small correction if buffer doesn't end
24420 ;; with a newline character.
24421 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24422 (org-element-property :begin next-elem)))
24423 (size-blank (- (org-element-property :end elem)
24425 (goto-char (org-element-property :end elem))
24426 (skip-chars-backward " \r\t\n")
24429 (org-element-swap-A-B elem next-elem)
24430 (goto-char (+ pos size-next size-blank))))))
24432 (defun org-drag-line-forward (arg)
24433 "Drag the line at point ARG lines forward."
24435 (dotimes (_ (abs arg))
24436 (let ((c (current-column)))
24439 (beginning-of-line 2)
24440 (transpose-lines 1)
24441 (beginning-of-line 0))
24442 (transpose-lines 1)
24443 (beginning-of-line -1))
24444 (org-move-to-column c))))
24446 (defun org-drag-line-backward (arg)
24447 "Drag the line at point ARG lines backward."
24449 (org-drag-line-forward (- arg)))
24451 (defun org-mark-element ()
24452 "Put point at beginning of this element, mark at end.
24454 Interactively, if this command is repeated or (in Transient Mark
24455 mode) if the mark is active, it marks the next element after the
24456 ones already marked."
24458 (let (deactivate-mark)
24459 (if (and (called-interactively-p 'any)
24460 (or (and (eq last-command this-command) (mark t))
24461 (and transient-mark-mode mark-active)))
24465 (goto-char (org-element-property :end (org-element-at-point)))))
24466 (let ((element (org-element-at-point)))
24468 (push-mark (org-element-property :end element) t t)
24469 (goto-char (org-element-property :begin element))))))
24471 (defun org-narrow-to-element ()
24472 "Narrow buffer to current element."
24474 (let ((elem (org-element-at-point)))
24476 ((eq (car elem) 'headline)
24478 (org-element-property :begin elem)
24479 (org-element-property :end elem)))
24480 ((memq (car elem) org-element-greater-elements)
24482 (org-element-property :contents-begin elem)
24483 (org-element-property :contents-end elem)))
24486 (org-element-property :begin elem)
24487 (org-element-property :end elem))))))
24489 (defun org-transpose-element ()
24490 "Transpose current and previous elements, keeping blank lines between.
24491 Point is moved after both elements."
24493 (org-skip-whitespace)
24494 (let ((end (org-element-property :end (org-element-at-point))))
24495 (org-drag-element-backward)
24498 (defun org-unindent-buffer ()
24499 "Un-indent the visible part of the buffer.
24500 Relative indentation (between items, inside blocks, etc.) isn't
24503 (unless (eq major-mode 'org-mode)
24504 (user-error "Cannot un-indent a buffer not in Org mode"))
24505 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24508 (dolist (element (reverse contents))
24509 (if (memq (org-element-type element) '(headline section))
24510 (funcall unindent-tree (org-element-contents element))
24514 (org-element-property :begin element)
24515 (org-element-property :end element))
24516 (org-do-remove-indentation))))))))
24517 (funcall unindent-tree (org-element-contents parse-tree))))
24519 (defun org-show-children (&optional level)
24520 "Show all direct subheadings of this heading.
24521 Prefix arg LEVEL is how many levels below the current level
24522 should be shown. Default is enough to cause the following
24523 heading to appear."
24525 ;; If `orgstruct-mode' is active, use the slower version.
24526 (if orgstruct-mode (call-interactively #'outline-show-children)
24528 (org-back-to-heading t)
24529 (let* ((current-level (funcall outline-level))
24530 (max-level (org-get-valid-level
24532 (if level (prefix-numeric-value level) 1)))
24533 (end (save-excursion (org-end-of-subtree t t)))
24534 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24535 (past-first-child nil)
24536 ;; Make sure to skip inlinetasks.
24537 (re (format regexp-fmt
24540 ((not (featurep 'org-inlinetask)) "")
24541 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24543 (t (1- org-inlinetask-min-level))))))
24544 ;; Display parent heading.
24545 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24547 ;; Display children. First child may be deeper than expected
24548 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24549 ;; MAX-LEVEL accordingly.
24550 (while (re-search-forward re end t)
24551 (unless past-first-child
24552 (setq re (format regexp-fmt
24554 (max (funcall outline-level) max-level)))
24555 (setq past-first-child t))
24556 (outline-flag-region
24557 (line-end-position 0) (line-end-position) nil))))))
24559 (defun org-show-subtree ()
24560 "Show everything after this heading at deeper levels."
24562 (outline-flag-region
24565 (org-end-of-subtree t t))
24568 (defun org-show-entry ()
24569 "Show the body directly following this heading.
24570 Show the heading too, if it is currently invisible."
24574 (org-back-to-heading t)
24575 (outline-flag-region
24576 (max (point-min) (1- (point)))
24578 (if (re-search-forward
24579 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24580 (match-beginning 1)
24583 (org-cycle-hide-drawers 'children))))
24585 (defun org-make-options-regexp (kwds &optional extra)
24586 "Make a regular expression for keyword lines.
24587 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24588 when non-nil, is a regexp matching keywords names."
24589 (concat "^[ \t]*#\\+\\("
24591 (and extra (concat (and kwds "\\|") extra))
24592 "\\):[ \t]*\\(.*\\)"))
24594 ;;;; Integration with and fixes for other packages
24598 (defvar-local org-imenu-markers nil
24599 "All markers currently used by Imenu.")
24601 (defun org-imenu-new-marker (&optional pos)
24602 "Return a new marker for use by Imenu, and remember the marker."
24603 (let ((m (make-marker)))
24604 (move-marker m (or pos (point)))
24605 (push m org-imenu-markers)
24608 (defun org-imenu-get-tree ()
24609 "Produce the index for Imenu."
24610 (dolist (x org-imenu-markers) (move-marker x nil))
24611 (setq org-imenu-markers nil)
24612 (let* ((case-fold-search nil)
24613 (n org-imenu-depth)
24614 (re (concat "^" (org-get-limited-outline-regexp)))
24615 (subs (make-vector (1+ n) nil))
24617 m level head0 head)
24618 (org-with-wide-buffer
24619 (goto-char (point-max))
24620 (while (re-search-backward re nil t)
24621 (setq level (org-reduced-level (funcall outline-level)))
24622 (when (and (<= level n)
24623 (looking-at org-complex-heading-regexp)
24624 (setq head0 (match-string-no-properties 4)))
24625 (setq head (org-link-display-format head0)
24626 m (org-imenu-new-marker))
24627 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24628 (if (>= level last-level)
24629 (push (cons head m) (aref subs level))
24630 (push (cons head (aref subs (1+ level))) (aref subs level))
24631 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24632 (setq last-level level))))
24635 (eval-after-load "imenu"
24637 (add-hook 'imenu-after-jump-hook
24639 (when (derived-mode-p 'org-mode)
24640 (org-show-context 'org-goto))))))
24642 (defun org-link-display-format (s)
24643 "Replace links in string S with their description.
24644 If there is no description, use the link target."
24646 (replace-regexp-in-string
24647 org-bracket-link-analytic-regexp
24649 (if (match-end 5) (match-string 5 m)
24650 (concat (match-string 1 m) (match-string 3 m))))
24653 (defun org-toggle-link-display ()
24654 "Toggle the literal or descriptive display of links."
24656 (if org-descriptive-links
24657 (progn (org-remove-from-invisibility-spec '(org-link))
24658 (org-restart-font-lock)
24659 (setq org-descriptive-links nil))
24660 (progn (add-to-invisibility-spec '(org-link))
24661 (org-restart-font-lock)
24662 (setq org-descriptive-links t))))
24664 ;; Speedbar support
24666 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24667 "Overlay marking the agenda restriction line in speedbar.")
24668 (overlay-put org-speedbar-restriction-lock-overlay
24669 'face 'org-agenda-restriction-lock)
24670 (overlay-put org-speedbar-restriction-lock-overlay
24671 'help-echo "Agendas are currently limited to this item.")
24672 (delete-overlay org-speedbar-restriction-lock-overlay)
24674 (defun org-speedbar-set-agenda-restriction ()
24675 "Restrict future agenda commands to the location at point in speedbar.
24676 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24678 (require 'org-agenda)
24679 (let (p m tp np dir txt)
24681 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24683 (setq m (get-text-property p 'org-imenu-marker))
24684 (with-current-buffer (marker-buffer m)
24686 (org-agenda-set-restriction-lock 'subtree)))
24687 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24688 'speedbar-function 'speedbar-find-file))
24689 (setq tp (previous-single-property-change
24690 (1+ p) 'speedbar-function)
24691 np (next-single-property-change
24692 tp 'speedbar-function)
24693 dir (speedbar-line-directory)
24694 txt (buffer-substring-no-properties (or tp (point-min))
24695 (or np (point-max))))
24696 (with-current-buffer (find-file-noselect
24697 (let ((default-directory dir))
24698 (expand-file-name txt)))
24699 (unless (derived-mode-p 'org-mode)
24700 (user-error "Cannot restrict to non-Org mode file"))
24701 (org-agenda-set-restriction-lock 'file)))
24702 (t (user-error "Don't know how to restrict Org mode agenda")))
24703 (move-overlay org-speedbar-restriction-lock-overlay
24704 (point-at-bol) (point-at-eol))
24705 (setq current-prefix-arg nil)
24706 (org-agenda-maybe-redo)))
24708 (defvar speedbar-file-key-map)
24709 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24710 (eval-after-load "speedbar"
24712 (speedbar-add-supported-extension ".org")
24713 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24714 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24715 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24716 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24717 (add-hook 'speedbar-visiting-tag-hook
24718 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24720 ;;; Fixes and Hacks for problems with other packages
24722 (defun org--flyspell-object-check-p (element)
24723 "Non-nil when Flyspell can check object at point.
24724 ELEMENT is the element at point."
24725 (let ((object (save-excursion
24726 (when (looking-at-p "\\>") (backward-char))
24727 (org-element-context element))))
24728 (cl-case (org-element-type object)
24729 ;; Prevent checks in links due to keybinding conflict with
24731 ((code entity export-snippet inline-babel-call
24732 inline-src-block line-break latex-fragment link macro
24733 statistics-cookie target timestamp verbatim)
24735 (footnote-reference
24736 ;; Only in inline footnotes, within the definition.
24737 (and (eq (org-element-property :type object) 'inline)
24739 (goto-char (org-element-property :begin object))
24740 (search-forward ":" nil t 2))
24744 (defun org-mode-flyspell-verify ()
24745 "Function used for `flyspell-generic-check-word-predicate'."
24746 (if (org-at-heading-p)
24747 ;; At a headline or an inlinetask, check title only. This is
24748 ;; faster than relying on `org-element-at-point'.
24749 (and (save-excursion (beginning-of-line)
24750 (and (let ((case-fold-search t))
24751 (not (looking-at-p "\\*+ END[ \t]*$")))
24752 (let ((case-fold-search nil))
24753 (looking-at org-complex-heading-regexp))))
24754 (match-beginning 4)
24755 (>= (point) (match-beginning 4))
24756 (or (not (match-beginning 5))
24757 (< (point) (match-beginning 5))))
24758 (let* ((element (org-element-at-point))
24759 (post-affiliated (org-element-property :post-affiliated element)))
24761 ;; Ignore checks in all affiliated keywords but captions.
24762 ((< (point) post-affiliated)
24763 (and (save-excursion
24764 (beginning-of-line)
24765 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24766 (> (point) (match-end 0))
24767 (org--flyspell-object-check-p element)))
24768 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24769 ((let ((log (org-log-into-drawer)))
24771 (let ((drawer (org-element-lineage element '(drawer))))
24773 (eq (compare-strings
24775 (org-element-property :drawer-name drawer) nil nil t)
24779 (cl-case (org-element-type element)
24780 ((comment quote-section) t)
24782 ;; Allow checks between block markers, not on them.
24783 (and (> (line-beginning-position) post-affiliated)
24786 (skip-chars-forward " \r\t\n")
24787 (< (point) (org-element-property :end element)))))
24788 ;; Arbitrary list of keywords where checks are meaningful.
24789 ;; Make sure point is on the value part of the element.
24791 (and (member (org-element-property :key element)
24792 '("DESCRIPTION" "TITLE"))
24794 (search-backward ":" (line-beginning-position) t))))
24795 ;; Check is globally allowed in paragraphs verse blocks and
24796 ;; table rows (after affiliated keywords) but some objects
24797 ;; must not be affected.
24798 ((paragraph table-row verse-block)
24799 (let ((cbeg (org-element-property :contents-begin element))
24800 (cend (org-element-property :contents-end element)))
24801 (and cbeg (>= (point) cbeg) (< (point) cend)
24802 (org--flyspell-object-check-p element))))))))))
24803 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24805 (defun org-remove-flyspell-overlays-in (beg end)
24806 "Remove flyspell overlays in region."
24807 (and (bound-and-true-p flyspell-mode)
24808 (fboundp 'flyspell-delete-region-overlays)
24809 (flyspell-delete-region-overlays beg end)))
24811 (defvar flyspell-delayed-commands)
24812 (eval-after-load "flyspell"
24813 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24815 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24816 (eval-after-load "bookmark"
24817 '(if (boundp 'bookmark-after-jump-hook)
24818 ;; We can use the hook
24819 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24820 ;; Hook not available, use advice
24821 (defadvice bookmark-jump (after org-make-visible activate)
24822 "Make the position visible."
24823 (org-bookmark-jump-unhide))))
24825 ;; Make sure saveplace shows the location if it was hidden
24826 (eval-after-load "saveplace"
24827 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24828 "Make the position visible."
24829 (org-bookmark-jump-unhide)))
24831 ;; Make sure ecb shows the location if it was hidden
24832 (eval-after-load "ecb"
24833 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24834 "Make hierarchy visible when jumping into location from ECB tree buffer."
24835 (when (derived-mode-p 'org-mode)
24836 (org-show-context))))
24838 (defun org-bookmark-jump-unhide ()
24839 "Unhide the current position, to show the bookmark location."
24840 (and (derived-mode-p 'org-mode)
24841 (or (org-invisible-p)
24842 (save-excursion (goto-char (max (point-min) (1- (point))))
24843 (org-invisible-p)))
24844 (org-show-context 'bookmark-jump)))
24846 (defun org-mark-jump-unhide ()
24847 "Make the point visible with `org-show-context' after jumping to the mark."
24848 (when (and (derived-mode-p 'org-mode)
24850 (org-show-context 'mark-goto)))
24852 (eval-after-load "simple"
24853 '(defadvice pop-to-mark-command (after org-make-visible activate)
24854 "Make the point visible with `org-show-context'."
24855 (org-mark-jump-unhide)))
24857 (eval-after-load "simple"
24858 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24859 "Make the point visible with `org-show-context'."
24860 (org-mark-jump-unhide)))
24862 (eval-after-load "simple"
24863 '(defadvice pop-global-mark (after org-make-visible activate)
24864 "Make the point visible with `org-show-context'."
24865 (org-mark-jump-unhide)))
24867 ;; Make session.el ignore our circular variable
24868 (defvar session-globals-exclude)
24869 (eval-after-load "session"
24870 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24876 (run-hooks 'org-load-hook)
24878 ;;; org.el ends here