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")
4172 (const :tag
"For all compilers" nil
)
4173 (repeat :tag
"Allowed compiler" string
)))
4174 (string :tag
"A line of LaTeX"))))
4176 (defcustom org-latex-packages-alist nil
4177 "Alist of packages to be inserted in every LaTeX header.
4179 These will be inserted after `org-latex-default-packages-alist'.
4180 Each element is either a cell or a string.
4182 A cell is of the format:
4184 (\"options\" \"package\" SNIPPET-FLAG)
4186 SNIPPET-FLAG, when non-nil, indicates that this package is also
4187 needed when turning LaTeX snippets into images for inclusion into
4190 A string will be inserted as-is in the header of the document.
4192 Make sure that you only list packages here which:
4194 - you want in every file;
4195 - do not conflict with the setup in `org-format-latex-header';
4196 - do not conflict with the default packages in
4197 `org-latex-default-packages-alist'."
4199 :group
'org-export-latex
4200 :set
'org-set-packages-alist
4201 :get
'org-get-packages-alist
4204 (list :tag
"options/package pair"
4205 (string :tag
"options")
4206 (string :tag
"package")
4207 (boolean :tag
"Snippet"))
4208 (string :tag
"A line of LaTeX"))))
4210 (defgroup org-appearance nil
4211 "Settings for Org mode appearance."
4212 :tag
"Org Appearance"
4215 (defcustom org-level-color-stars-only nil
4216 "Non-nil means fontify only the stars in each headline.
4217 When nil, the entire headline is fontified.
4218 Changing it requires restart of `font-lock-mode' to become effective
4219 also in regions already fontified."
4220 :group
'org-appearance
4223 (defcustom org-hide-leading-stars nil
4224 "Non-nil means hide the first N-1 stars in a headline.
4225 This works by using the face `org-hide' for these stars. This
4226 face is white for a light background, and black for a dark
4227 background. You may have to customize the face `org-hide' to
4229 Changing it requires restart of `font-lock-mode' to become effective
4230 also in regions already fontified.
4231 You may also set this on a per-file basis by adding one of the following
4232 lines to the buffer:
4234 #+STARTUP: hidestars
4235 #+STARTUP: showstars"
4236 :group
'org-appearance
4239 (defcustom org-hidden-keywords nil
4240 "List of symbols corresponding to keywords to be hidden the org buffer.
4241 For example, a value \\='(title) for this list will make the document's title
4242 appear in the buffer without the initial #+TITLE: keyword."
4243 :group
'org-appearance
4245 :type
'(set (const :tag
"#+AUTHOR" author
)
4246 (const :tag
"#+DATE" date
)
4247 (const :tag
"#+EMAIL" email
)
4248 (const :tag
"#+TITLE" title
)))
4250 (defcustom org-custom-properties nil
4251 "List of properties (as strings) with a special meaning.
4252 The default use of these custom properties is to let the user
4253 hide them with `org-toggle-custom-properties-visibility'."
4254 :group
'org-properties
4255 :group
'org-appearance
4257 :type
'(repeat (string :tag
"Property Name")))
4259 (defcustom org-fontify-done-headline nil
4260 "Non-nil means change the face of a headline if it is marked DONE.
4261 Normally, only the TODO/DONE keyword indicates the state of a headline.
4262 When this is non-nil, the headline after the keyword is set to the
4263 `org-headline-done' as an additional indication."
4264 :group
'org-appearance
4267 (defcustom org-fontify-emphasized-text t
4268 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4269 Changing this variable requires a restart of Emacs to take effect."
4270 :group
'org-appearance
4273 (defcustom org-fontify-whole-heading-line nil
4274 "Non-nil means fontify the whole line for headings.
4275 This is useful when setting a background color for the
4277 :group
'org-appearance
4280 (defcustom org-highlight-latex-and-related nil
4281 "Non-nil means highlight LaTeX related syntax in the buffer.
4282 When non nil, the value should be a list containing any of the
4284 `latex' Highlight LaTeX snippets and environments.
4285 `script' Highlight subscript and superscript.
4286 `entities' Highlight entities."
4287 :group
'org-appearance
4289 :package-version
'(Org .
"8.0")
4291 (const :tag
"No highlighting" nil
)
4292 (set :greedy t
:tag
"Highlight"
4293 (const :tag
"LaTeX snippets and environments" latex
)
4294 (const :tag
"Subscript and superscript" script
)
4295 (const :tag
"Entities" entities
))))
4297 (defcustom org-hide-emphasis-markers nil
4298 "Non-nil mean font-lock should hide the emphasis marker characters."
4299 :group
'org-appearance
4302 (defcustom org-hide-macro-markers nil
4303 "Non-nil mean font-lock should hide the brackets marking macro calls."
4304 :group
'org-appearance
4307 (defcustom org-pretty-entities nil
4308 "Non-nil means show entities as UTF8 characters.
4309 When nil, the \\name form remains in the buffer."
4310 :group
'org-appearance
4314 (defcustom org-pretty-entities-include-sub-superscripts t
4315 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4316 :group
'org-appearance
4320 (defvar org-emph-re nil
4321 "Regular expression for matching emphasis.
4322 After a match, the match groups contain these elements:
4323 0 The match of the full regular expression, including the characters
4324 before and after the proper match
4325 1 The character before the proper match, or empty at beginning of line
4326 2 The proper match, including the leading and trailing markers
4327 3 The leading marker like * or /, indicating the type of highlighting
4328 4 The text between the emphasis markers, not including the markers
4329 5 The character after the match, empty at the end of a line")
4331 (defvar org-verbatim-re nil
4332 "Regular expression for matching verbatim text.")
4334 (defvar org-emphasis-regexp-components
) ; defined just below
4335 (defvar org-emphasis-alist
) ; defined just below
4336 (defun org-set-emph-re (var val
)
4337 "Set variable and compute the emphasis regular expression."
4339 (when (and (boundp 'org-emphasis-alist
)
4340 (boundp 'org-emphasis-regexp-components
)
4341 org-emphasis-alist org-emphasis-regexp-components
)
4343 ((`(,pre
,post
,border
,body
,nl
) org-emphasis-regexp-components
)
4344 (body (if (<= nl
0) body
4345 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl
)))
4347 (format (concat "\\([%s]\\|^\\)" ;before markers
4348 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4349 "\\([%s]\\|$\\)") ;after markers
4350 pre border border body border post
)))
4351 (setq org-emph-re
(format template
"*/_+"))
4352 (setq org-verbatim-re
(format template
"=~")))))
4354 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4355 ;; set this option proved cumbersome. See this message/thread:
4356 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4357 (defvar org-emphasis-regexp-components
4358 '("- \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4359 "Components used to build the regular expression for emphasis.
4360 This is a list with five entries. Terminology: In an emphasis string
4361 like \" *strong word* \", we call the initial space PREMATCH, the final
4362 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4363 and \"trong wor\" is the body. The different components in this variable
4364 specify what is allowed/forbidden in each part:
4366 pre Chars allowed as prematch. Beginning of line will be allowed too.
4367 post Chars allowed as postmatch. End of line will be allowed too.
4368 border The chars *forbidden* as border characters.
4369 body-regexp A regexp like \".\" to match a body character. Don't use
4370 non-shy groups here, and don't allow newline here.
4371 newline The maximum number of newlines allowed in an emphasis exp.
4373 You need to reload Org or to restart Emacs after customizing this.")
4375 (defcustom org-emphasis-alist
4379 ("=" org-verbatim verbatim
)
4380 ("~" org-code verbatim
)
4381 ("+" (:strike-through t
)))
4382 "Alist of characters and faces to emphasize text.
4383 Text starting and ending with a special character will be emphasized,
4384 for example *bold*, _underlined_ and /italic/. This variable sets the
4385 marker characters and the face to be used by font-lock for highlighting
4388 You need to reload Org or to restart Emacs after customizing this."
4389 :group
'org-appearance
4390 :set
'org-set-emph-re
4392 :package-version
'(Org .
"8.0")
4395 (string :tag
"Marker character")
4397 (face :tag
"Font-lock-face")
4398 (plist :tag
"Face property list"))
4399 (option (const verbatim
)))))
4401 (defvar org-protecting-blocks
'("src" "example" "export")
4402 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4403 This is needed for font-lock setup.")
4405 ;;; Functions and variables from their packages
4406 ;; Declared here to avoid compiler warnings
4407 (defvar mark-active
)
4410 (declare-function calc-eval
"calc" (str &optional separator
&rest args
))
4411 (declare-function calendar-forward-day
"cal-move" (arg))
4412 (declare-function calendar-goto-date
"cal-move" (date))
4413 (declare-function calendar-goto-today
"cal-move" ())
4414 (declare-function calendar-iso-from-absolute
"cal-iso" (date))
4415 (declare-function calendar-iso-to-absolute
"cal-iso" (date))
4416 (declare-function cdlatex-compute-tables
"ext:cdlatex" ())
4417 (declare-function cdlatex-tab
"ext:cdlatex" ())
4418 (declare-function dired-get-filename
4420 (&optional localp no-error-if-not-filep
))
4421 (declare-function iswitchb-read-buffer
4424 default require-match _predicate start matches-set
))
4425 (declare-function org-agenda-change-all-lines
4427 (newhead hdmarker
&optional fixface just-this
))
4428 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4431 (declare-function org-agenda-copy-local-variable
"org-agenda" (var))
4432 (declare-function org-agenda-format-item
4434 (extra txt
&optional level category tags dotime
4436 (declare-function org-agenda-maybe-redo
"org-agenda" ())
4437 (declare-function org-agenda-new-marker
"org-agenda" (&optional pos
))
4438 (declare-function org-agenda-save-markers-for-cut-and-paste
4441 (declare-function org-agenda-set-restriction-lock
"org-agenda" (&optional type
))
4442 (declare-function org-agenda-skip
"org-agenda" ())
4443 (declare-function org-attach-reveal
"org-attach" (&optional if-exists
))
4444 (declare-function org-gnus-follow-link
"org-gnus" (&optional group article
))
4445 (declare-function org-indent-mode
"org-indent" (&optional arg
))
4446 (declare-function org-inlinetask-goto-beginning
"org-inlinetask" ())
4447 (declare-function org-inlinetask-goto-end
"org-inlinetask" ())
4448 (declare-function org-inlinetask-in-task-p
"org-inlinetask" ())
4449 (declare-function org-inlinetask-remove-END-maybe
"org-inlinetask" ())
4450 (declare-function orgtbl-send-table
"org-table" (&optional maybe
))
4451 (declare-function parse-time-string
"parse-time" (string))
4452 (declare-function speedbar-line-directory
"speedbar" (&optional depth
))
4454 (defvar align-mode-rules-list
)
4455 (defvar calc-embedded-close-formula
)
4456 (defvar calc-embedded-open-formula
)
4457 (defvar calc-embedded-open-mode
)
4458 (defvar font-lock-unfontify-region-function
)
4459 (defvar iswitchb-temp-buflist
)
4460 (defvar org-agenda-tags-todo-honor-ignore-options
)
4461 (defvar remember-data-file
)
4462 (defvar texmathp-why
)
4465 (defun turn-on-orgtbl ()
4466 "Unconditionally turn on `orgtbl-mode'."
4467 (require 'org-table
)
4470 (defun org-at-table-p (&optional table-type
)
4471 "Non-nil if the cursor is inside an Org table.
4472 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4473 (and (org-match-line (if table-type
"[ \t]*[|+]" "[ \t]*|"))
4474 (or (not (derived-mode-p 'org-mode
))
4475 (let ((e (org-element-lineage (org-element-at-point) '(table) t
)))
4476 (and e
(or table-type
4477 (eq 'org
(org-element-property :type e
))))))))
4479 (defun org-at-table.el-p
()
4480 "Non-nil when point is at a table.el table."
4481 (and (org-match-line "[ \t]*[|+]")
4482 (let ((element (org-element-at-point)))
4483 (and (eq (org-element-type element
) 'table
)
4484 (eq (org-element-property :type element
) 'table.el
)))))
4486 (defun org-at-table-hline-p ()
4487 "Non-nil when point is inside a hline in a table.
4488 Assume point is already in a table."
4489 (org-match-line org-table-hline-regexp
))
4491 (defun org-table-map-tables (function &optional quietly
)
4492 "Apply FUNCTION to the start of all tables in the buffer."
4493 (org-with-wide-buffer
4494 (goto-char (point-min))
4495 (while (re-search-forward org-table-any-line-regexp nil t
)
4497 (message "Mapping tables: %d%%"
4498 (floor (* 100.0 (point)) (buffer-size))))
4499 (beginning-of-line 1)
4500 (when (and (looking-at org-table-line-regexp
)
4501 ;; Exclude tables in src/example/verbatim/clocktable blocks
4502 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4503 (save-excursion (funcall function
))
4504 (or (looking-at org-table-line-regexp
)
4506 (re-search-forward org-table-any-border-regexp nil
1)))
4507 (unless quietly
(message "Mapping tables: done")))
4509 (declare-function org-clock-save-markers-for-cut-and-paste
"org-clock" (beg end
))
4510 (declare-function org-clock-update-mode-line
"org-clock" ())
4511 (declare-function org-resolve-clocks
"org-clock"
4512 (&optional also-non-dangling-p prompt last-valid
))
4514 (defun org-at-TBLFM-p (&optional pos
)
4515 "Non-nil when point (or POS) is in #+TBLFM line."
4517 (goto-char (or pos
(point)))
4519 (and (let ((case-fold-search t
)) (looking-at org-TBLFM-regexp
))
4520 (eq (org-element-type (org-element-at-point)) 'table
))))
4522 (defvar org-clock-start-time
)
4523 (defvar org-clock-marker
(make-marker)
4524 "Marker recording the last clock-in.")
4525 (defvar org-clock-hd-marker
(make-marker)
4526 "Marker recording the last clock-in, but the headline position.")
4527 (defvar org-clock-heading
""
4528 "The heading of the current clock entry.")
4529 (defun org-clock-is-active ()
4530 "Return the buffer where the clock is currently running.
4531 Return nil if no clock is running."
4532 (marker-buffer org-clock-marker
))
4534 (defun org-check-running-clock ()
4535 "Check if the current buffer contains the running clock.
4536 If yes, offer to stop it and to save the buffer with the changes."
4537 (when (and (equal (marker-buffer org-clock-marker
) (current-buffer))
4538 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4541 (when (y-or-n-p "Save changed buffer?")
4544 (defun org-clocktable-try-shift (dir n
)
4545 "Check if this line starts a clock table, if yes, shift the time block."
4546 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4547 (org-clocktable-shift dir n
)))
4550 (defun org-clock-persistence-insinuate ()
4551 "Set up hooks for clock persistence."
4552 (require 'org-clock
)
4553 (add-hook 'org-mode-hook
'org-clock-load
)
4554 (add-hook 'kill-emacs-hook
'org-clock-save
))
4556 (defgroup org-archive nil
4557 "Options concerning archiving in Org mode."
4559 :group
'org-structure
)
4561 (defcustom org-archive-location
"%s_archive::"
4562 "The location where subtrees should be archived.
4564 The value of this variable is a string, consisting of two parts,
4565 separated by a double-colon. The first part is a filename and
4566 the second part is a headline.
4568 When the filename is omitted, archiving happens in the same file.
4569 %s in the filename will be replaced by the current file
4570 name (without the directory part). Archiving to a different file
4571 is useful to keep archived entries from contributing to the
4574 The archived entries will be filed as subtrees of the specified
4575 headline. When the headline is omitted, the subtrees are simply
4576 filed away at the end of the file, as top-level entries. Also in
4577 the heading you can use %s to represent the file name, this can be
4578 useful when using the same archive for a number of different files.
4580 Here are a few examples:
4582 If the current file is Projects.org, archive in file
4583 Projects.org_archive, as top-level trees. This is the default.
4585 \"::* Archived Tasks\"
4586 Archive in the current file, under the top-level headline
4587 \"* Archived Tasks\".
4589 \"~/org/archive.org::\"
4590 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4592 \"~/org/archive.org::* From %s\"
4593 Archive in file ~/org/archive.org (absolute path), under headlines
4594 \"From FILENAME\" where file name is the current file name.
4596 \"~/org/datetree.org::datetree/* Finished Tasks\"
4597 The \"datetree/\" string is special, signifying to archive
4598 items to the datetree. Items are placed in either the CLOSED
4599 date of the item, or the current date if there is no CLOSED date.
4600 The heading will be a subentry to the current date. There doesn't
4601 need to be a heading, but there always needs to be a slash after
4602 datetree. For example, to store archived items directly in the
4603 datetree, use \"~/org/datetree.org::datetree/\".
4605 \"basement::** Finished Tasks\"
4606 Archive in file ./basement (relative path), as level 3 trees
4607 below the level 2 heading \"** Finished Tasks\".
4609 You may set this option on a per-file basis by adding to the buffer a
4612 #+ARCHIVE: basement::** Finished Tasks
4614 You may also define it locally for a subtree by setting an ARCHIVE property
4615 in the entry. If such a property is found in an entry, or anywhere up
4616 the hierarchy, it will be used."
4620 (defcustom org-agenda-skip-archived-trees t
4621 "Non-nil means the agenda will skip any items located in archived trees.
4622 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4623 variable is no longer recommended, you should leave it at the value t.
4624 Instead, use the key `v' to cycle the archives-mode in the agenda."
4626 :group
'org-agenda-skip
4629 (defcustom org-columns-skip-archived-trees t
4630 "Non-nil means ignore archived trees when creating column view."
4632 :group
'org-properties
4635 (defcustom org-cycle-open-archived-trees nil
4636 "Non-nil means `org-cycle' will open archived trees.
4637 An archived tree is a tree marked with the tag ARCHIVE.
4638 When nil, archived trees will stay folded. You can still open them with
4639 normal outline commands like `show-all', but not with the cycling commands."
4644 (defcustom org-sparse-tree-open-archived-trees nil
4645 "Non-nil means sparse tree construction shows matches in archived trees.
4646 When nil, matches in these trees are highlighted, but the trees are kept in
4649 :group
'org-sparse-trees
4652 (defcustom org-sparse-tree-default-date-type nil
4653 "The default date type when building a sparse tree.
4654 When this is nil, a date is a scheduled or a deadline timestamp.
4655 Otherwise, these types are allowed:
4658 active: only active timestamps (<...>)
4659 inactive: only inactive timestamps ([...])
4660 scheduled: only scheduled timestamps
4661 deadline: only deadline timestamps"
4662 :type
'(choice (const :tag
"Scheduled or deadline" nil
)
4663 (const :tag
"All timestamps" all
)
4664 (const :tag
"Only active timestamps" active
)
4665 (const :tag
"Only inactive timestamps" inactive
)
4666 (const :tag
"Only scheduled timestamps" scheduled
)
4667 (const :tag
"Only deadline timestamps" deadline
)
4668 (const :tag
"Only closed timestamps" closed
))
4670 :package-version
'(Org .
"8.3")
4671 :group
'org-sparse-trees
)
4673 (defun org-cycle-hide-archived-subtrees (state)
4674 "Re-hide all archived subtrees after a visibility state change.
4675 STATE should be one of the symbols listed in the docstring of
4677 (when (and (not org-cycle-open-archived-trees
)
4678 (not (memq state
'(overview folded
))))
4680 (let* ((globalp (memq state
'(contents all
)))
4681 (beg (if globalp
(point-min) (point)))
4682 (end (if globalp
(point-max) (org-end-of-subtree t
))))
4683 (org-hide-archived-subtrees beg end
)
4685 (when (looking-at-p (concat ".*:" org-archive-tag
":"))
4686 (message "%s" (substitute-command-keys
4687 "Subtree is archived and stays closed. Use \
4688 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4690 (defun org-force-cycle-archived ()
4691 "Cycle subtree even if it is archived."
4693 (setq this-command
'org-cycle
)
4694 (let ((org-cycle-open-archived-trees t
))
4695 (call-interactively 'org-cycle
)))
4697 (defun org-hide-archived-subtrees (beg end
)
4698 "Re-hide all archived subtrees after a visibility state change."
4699 (org-with-wide-buffer
4700 (let ((case-fold-search nil
)
4701 (re (concat org-outline-regexp-bol
".*:" org-archive-tag
":")))
4703 ;; Include headline point is currently on.
4705 (while (and (< (point) end
) (re-search-forward re end t
))
4706 (when (member org-archive-tag
(org-get-tags))
4707 (org-flag-subtree t
)
4708 (org-end-of-subtree t
))))))
4710 (declare-function outline-end-of-heading
"outline" ())
4711 (declare-function outline-flag-region
"outline" (from to flag
))
4712 (defun org-flag-subtree (flag)
4714 (org-back-to-heading t
)
4715 (outline-end-of-heading)
4716 (outline-flag-region (point)
4717 (progn (org-end-of-subtree t
) (point))
4720 (defalias 'org-advertized-archive-subtree
'org-archive-subtree
)
4722 ;; Declare Column View Code
4724 (declare-function org-columns-get-format-and-top-level
"org-colview" ())
4725 (declare-function org-columns-compute
"org-colview" (property))
4729 (declare-function org-id-store-link
"org-id")
4730 (declare-function org-id-locations-load
"org-id")
4731 (declare-function org-id-locations-save
"org-id")
4732 (defvar org-id-track-globally
)
4734 ;;; Variables for pre-computed regular expressions, all buffer local
4736 (defvar-local org-todo-regexp nil
4737 "Matches any of the TODO state keywords.
4738 Since TODO keywords are case-sensitive, `case-fold-search' is
4739 expected to be bound to nil when matching against this regexp.")
4741 (defvar-local org-not-done-regexp nil
4742 "Matches any of the TODO state keywords except the last one.
4743 Since TODO keywords are case-sensitive, `case-fold-search' is
4744 expected to be bound to nil when matching against this regexp.")
4746 (defvar-local org-not-done-heading-regexp nil
4747 "Matches a TODO headline that is not done.
4748 Since TODO keywords are case-sensitive, `case-fold-search' is
4749 expected to be bound to nil when matching against this regexp.")
4751 (defvar-local org-todo-line-regexp nil
4752 "Matches a headline and puts TODO state into group 2 if present.
4753 Since TODO keywords are case-sensitive, `case-fold-search' is
4754 expected to be bound to nil when matching against this regexp.")
4756 (defvar-local org-complex-heading-regexp nil
4757 "Matches a headline and puts everything into groups:
4760 group 2: The TODO keyword, maybe
4761 group 3: Priority cookie
4762 group 4: True headline
4765 Since TODO keywords are case-sensitive, `case-fold-search' is
4766 expected to be bound to nil when matching against this regexp.")
4768 (defvar-local org-complex-heading-regexp-format nil
4769 "Printf format to make regexp to match an exact headline.
4770 This regexp will match the headline of any node which has the
4771 exact headline text that is put into the format, but may have any
4772 TODO state, priority and tags.")
4774 (defvar-local org-todo-line-tags-regexp nil
4775 "Matches a headline and puts TODO state into group 2 if present.
4776 Also put tags into group 4 if tags are present.")
4778 (defconst org-plain-time-of-day-regexp
4781 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4784 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4786 "Regular expression to match a plain time or time range.
4787 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4788 groups carry important information:
4790 1 the first time, range or not
4791 8 the second time, if it is a range.")
4793 (defconst org-plain-time-extension-regexp
4796 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4797 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4798 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4799 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4800 groups carry important information:
4803 9 minutes of duration")
4805 (defconst org-stamp-time-of-day-regexp
4807 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4808 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4810 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4811 "Regular expression to match a timestamp time or time range.
4812 After a match, the following groups carry important information:
4814 1 date plus weekday, for back referencing to make sure both times are on the same day
4815 2 the first time, range or not
4816 4 the second time, if it is a range.")
4818 (defconst org-startup-options
4819 '(("fold" org-startup-folded t
)
4820 ("overview" org-startup-folded t
)
4821 ("nofold" org-startup-folded nil
)
4822 ("showall" org-startup-folded nil
)
4823 ("showeverything" org-startup-folded showeverything
)
4824 ("content" org-startup-folded content
)
4825 ("indent" org-startup-indented t
)
4826 ("noindent" org-startup-indented nil
)
4827 ("hidestars" org-hide-leading-stars t
)
4828 ("showstars" org-hide-leading-stars nil
)
4829 ("odd" org-odd-levels-only t
)
4830 ("oddeven" org-odd-levels-only nil
)
4831 ("align" org-startup-align-all-tables t
)
4832 ("noalign" org-startup-align-all-tables nil
)
4833 ("inlineimages" org-startup-with-inline-images t
)
4834 ("noinlineimages" org-startup-with-inline-images nil
)
4835 ("latexpreview" org-startup-with-latex-preview t
)
4836 ("nolatexpreview" org-startup-with-latex-preview nil
)
4837 ("customtime" org-display-custom-times t
)
4838 ("logdone" org-log-done time
)
4839 ("lognotedone" org-log-done note
)
4840 ("nologdone" org-log-done nil
)
4841 ("lognoteclock-out" org-log-note-clock-out t
)
4842 ("nolognoteclock-out" org-log-note-clock-out nil
)
4843 ("logrepeat" org-log-repeat state
)
4844 ("lognoterepeat" org-log-repeat note
)
4845 ("logdrawer" org-log-into-drawer t
)
4846 ("nologdrawer" org-log-into-drawer nil
)
4847 ("logstatesreversed" org-log-states-order-reversed t
)
4848 ("nologstatesreversed" org-log-states-order-reversed nil
)
4849 ("nologrepeat" org-log-repeat nil
)
4850 ("logreschedule" org-log-reschedule time
)
4851 ("lognotereschedule" org-log-reschedule note
)
4852 ("nologreschedule" org-log-reschedule nil
)
4853 ("logredeadline" org-log-redeadline time
)
4854 ("lognoteredeadline" org-log-redeadline note
)
4855 ("nologredeadline" org-log-redeadline nil
)
4856 ("logrefile" org-log-refile time
)
4857 ("lognoterefile" org-log-refile note
)
4858 ("nologrefile" org-log-refile nil
)
4859 ("fninline" org-footnote-define-inline t
)
4860 ("nofninline" org-footnote-define-inline nil
)
4861 ("fnlocal" org-footnote-section nil
)
4862 ("fnauto" org-footnote-auto-label t
)
4863 ("fnprompt" org-footnote-auto-label nil
)
4864 ("fnconfirm" org-footnote-auto-label confirm
)
4865 ("fnplain" org-footnote-auto-label plain
)
4866 ("fnadjust" org-footnote-auto-adjust t
)
4867 ("nofnadjust" org-footnote-auto-adjust nil
)
4868 ("constcgs" constants-unit-system cgs
)
4869 ("constSI" constants-unit-system SI
)
4870 ("noptag" org-tag-persistent-alist nil
)
4871 ("hideblocks" org-hide-block-startup t
)
4872 ("nohideblocks" org-hide-block-startup nil
)
4873 ("beamer" org-startup-with-beamer-mode t
)
4874 ("entitiespretty" org-pretty-entities t
)
4875 ("entitiesplain" org-pretty-entities nil
))
4876 "Variable associated with STARTUP options for org-mode.
4877 Each element is a list of three items: the startup options (as written
4878 in the #+STARTUP line), the corresponding variable, and the value to set
4879 this variable to if the option is found. An optional forth element PUSH
4880 means to push this value onto the list in the variable.")
4882 (defcustom org-group-tags t
4883 "When non-nil (the default), use group tags.
4884 This can be turned on/off through `org-toggle-tags-groups'."
4889 (defvar org-inhibit-startup nil
) ; Dynamically-scoped param.
4891 (defun org-toggle-tags-groups ()
4892 "Toggle support for group tags.
4893 Support for group tags is controlled by the option
4894 `org-group-tags', which is non-nil by default."
4896 (setq org-group-tags
(not org-group-tags
))
4897 (cond ((and (derived-mode-p 'org-agenda-mode
)
4900 ((derived-mode-p 'org-mode
)
4901 (let ((org-inhibit-startup t
)) (org-mode))))
4902 (message "Groups tags support has been turned %s"
4903 (if org-group-tags
"on" "off")))
4905 (defun org-set-regexps-and-options (&optional tags-only
)
4906 "Precompute regular expressions used in the current buffer.
4907 When optional argument TAGS-ONLY is non-nil, only compute tags
4908 related expressions."
4909 (when (derived-mode-p 'org-mode
)
4910 (let ((alist (org--setup-collect-keywords
4911 (org-make-options-regexp
4912 (append '("FILETAGS" "TAGS" "SETUPFILE")
4913 (and (not tags-only
)
4914 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4915 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4916 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4917 ;; Startup options. Get this early since it does change
4918 ;; behavior for other options (e.g., tags).
4919 (let ((startup (cdr (assq 'startup alist
))))
4920 (dolist (option startup
)
4921 (let ((entry (assoc-string option org-startup-options t
)))
4923 (let ((var (nth 1 entry
))
4924 (val (nth 2 entry
)))
4925 (if (not (nth 3 entry
)) (set (make-local-variable var
) val
)
4926 (unless (listp (symbol-value var
))
4927 (set (make-local-variable var
) nil
))
4928 (add-to-list var val
)))))))
4929 (setq-local org-file-tags
4930 (mapcar #'org-add-prop-inherited
4931 (cdr (assq 'filetags alist
))))
4932 (setq org-current-tag-alist
4933 (append org-tag-persistent-alist
4934 (let ((tags (cdr (assq 'tags alist
))))
4935 (if tags
(org-tag-string-to-alist tags
)
4937 (setq org-tag-groups-alist
4938 (org-tag-alist-to-groups org-current-tag-alist
))
4941 (setq-local org-file-properties
(cdr (assq 'property alist
)))
4942 ;; Archive location.
4943 (let ((archive (cdr (assq 'archive alist
))))
4944 (when archive
(setq-local org-archive-location archive
)))
4946 (let ((cat (org-string-nw-p (cdr (assq 'category alist
)))))
4948 (setq-local org-category
(intern cat
))
4949 (setq-local org-file-properties
4950 (org--update-property-plist
4951 "CATEGORY" cat org-file-properties
))))
4953 (let ((column (cdr (assq 'columns alist
))))
4954 (when column
(setq-local org-columns-default-format column
)))
4956 (setq org-table-formula-constants-local
(cdr (assq 'constants alist
)))
4957 ;; Link abbreviations.
4958 (let ((links (cdr (assq 'link alist
))))
4959 (when links
(setq org-link-abbrev-alist-local
(nreverse links
))))
4961 (let ((priorities (cdr (assq 'priorities alist
))))
4963 (setq-local org-highest-priority
(nth 0 priorities
))
4964 (setq-local org-lowest-priority
(nth 1 priorities
))
4965 (setq-local org-default-priority
(nth 2 priorities
))))
4967 (let ((scripts (assq 'scripts alist
)))
4969 (setq-local org-use-sub-superscripts
(cdr scripts
))))
4971 (setq-local org-todo-kwd-alist nil
)
4972 (setq-local org-todo-key-alist nil
)
4973 (setq-local org-todo-key-trigger nil
)
4974 (setq-local org-todo-keywords-1 nil
)
4975 (setq-local org-done-keywords nil
)
4976 (setq-local org-todo-heads nil
)
4977 (setq-local org-todo-sets nil
)
4978 (setq-local org-todo-log-states nil
)
4979 (let ((todo-sequences
4980 (or (nreverse (cdr (assq 'todo alist
)))
4981 (let ((d (default-value 'org-todo-keywords
)))
4982 (if (not (stringp (car d
))) d
4983 ;; XXX: Backward compatibility code.
4984 (list (cons org-todo-interpretation d
)))))))
4985 (dolist (sequence todo-sequences
)
4986 (let* ((sequence (or (run-hook-with-args-until-success
4987 'org-todo-setup-filter-hook sequence
)
4989 (sequence-type (car sequence
))
4990 (keywords (cdr sequence
))
4991 (sep (member "|" keywords
))
4993 (dolist (k (remove "|" keywords
))
4994 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4996 (error "Invalid TODO keyword %s" k
))
4997 (let ((name (match-string 1 k
))
4998 (key (match-string 2 k
))
4999 (log (org-extract-log-state-settings k
)))
5001 (push (cons name
(and key
(string-to-char key
))) alist
)
5002 (when log
(push log org-todo-log-states
))))
5003 (let* ((names (nreverse names
))
5004 (done (if sep
(org-remove-keyword-keys (cdr sep
))
5007 (tail (list sequence-type head
(car done
) (org-last done
))))
5008 (add-to-list 'org-todo-heads head
'append
)
5009 (push names org-todo-sets
)
5010 (setq org-done-keywords
(append org-done-keywords done nil
))
5011 (setq org-todo-keywords-1
(append org-todo-keywords-1 names nil
))
5012 (setq org-todo-key-alist
5013 (append org-todo-key-alist
5015 (append '((:startgroup
))
5018 (dolist (k names
) (push (cons k tail
) org-todo-kwd-alist
))))))
5019 (setq org-todo-sets
(nreverse org-todo-sets
)
5020 org-todo-kwd-alist
(nreverse org-todo-kwd-alist
)
5021 org-todo-key-trigger
(delq nil
(mapcar #'cdr org-todo-key-alist
))
5022 org-todo-key-alist
(org-assign-fast-keys org-todo-key-alist
))
5023 ;; Compute the regular expressions and other local variables.
5024 ;; Using `org-outline-regexp-bol' would complicate them much,
5025 ;; because of the fixed white space at the end of that string.
5026 (unless org-done-keywords
5027 (setq org-done-keywords
5028 (and org-todo-keywords-1
(last org-todo-keywords-1
))))
5029 (setq org-not-done-keywords
5030 (org-delete-all org-done-keywords
5031 (copy-sequence org-todo-keywords-1
))
5032 org-todo-regexp
(regexp-opt org-todo-keywords-1 t
)
5033 org-not-done-regexp
(regexp-opt org-not-done-keywords t
)
5034 org-not-done-heading-regexp
5035 (format org-heading-keyword-regexp-format org-not-done-regexp
)
5036 org-todo-line-regexp
5037 (format org-heading-keyword-maybe-regexp-format org-todo-regexp
)
5038 org-complex-heading-regexp
5039 (concat "^\\(\\*+\\)"
5040 "\\(?: +" org-todo-regexp
"\\)?"
5041 "\\(?: +\\(\\[#.\\]\\)\\)?"
5042 "\\(?: +\\(.*?\\)\\)??"
5043 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5045 org-complex-heading-regexp-format
5046 (concat "^\\(\\*+\\)"
5047 "\\(?: +" org-todo-regexp
"\\)?"
5048 "\\(?: +\\(\\[#.\\]\\)\\)?"
5050 ;; Stats cookies can be stuck to body.
5051 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5053 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5055 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5057 org-todo-line-tags-regexp
5058 (concat "^\\(\\*+\\)"
5059 "\\(?: +" org-todo-regexp
"\\)?"
5060 "\\(?: +\\(.*?\\)\\)??"
5061 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5063 (org-compute-latex-and-related-regexp)))))
5065 (defun org--setup-collect-keywords (regexp &optional files alist
)
5066 "Return setup keywords values as an alist.
5068 REGEXP matches a subset of setup keywords. FILES is a list of
5069 file names already visited. It is used to avoid circular setup
5070 files. ALIST, when non-nil, is the alist computed so far.
5072 Return value contains the following keys: `archive', `category',
5073 `columns', `constants', `filetags', `link', `priorities',
5074 `property', `scripts', `startup', `tags' and `todo'."
5075 (org-with-wide-buffer
5076 (goto-char (point-min))
5077 (let ((case-fold-search t
))
5078 (while (re-search-forward regexp nil t
)
5079 (let ((element (org-element-at-point)))
5080 (when (eq (org-element-type element
) 'keyword
)
5081 (let ((key (org-element-property :key element
))
5082 (value (org-element-property :value element
)))
5084 ((equal key
"ARCHIVE")
5085 (when (org-string-nw-p value
)
5086 (push (cons 'archive value
) alist
)))
5087 ((equal key
"CATEGORY") (push (cons 'category value
) alist
))
5088 ((equal key
"COLUMNS") (push (cons 'columns value
) alist
))
5089 ((equal key
"CONSTANTS")
5090 (let* ((constants (assq 'constants alist
))
5091 (store (cdr constants
)))
5092 (dolist (pair (split-string value
))
5093 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5095 (let* ((name (match-string 1 pair
))
5096 (value (match-string 2 pair
))
5097 (old (assoc name store
)))
5098 (if old
(setcdr old value
)
5099 (push (cons name value
) store
)))))
5100 (if constants
(setcdr constants store
)
5101 (push (cons 'constants store
) alist
))))
5102 ((equal key
"FILETAGS")
5103 (when (org-string-nw-p value
)
5104 (let ((old (assq 'filetags alist
))
5106 (mapcar (lambda (x) (org-split-string x
":"))
5107 (split-string value
)))))
5108 (if old
(setcdr old
(append new
(cdr old
)))
5109 (push (cons 'filetags new
) alist
)))))
5111 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value
)
5112 (let ((links (assq 'link alist
))
5113 (pair (cons (match-string-no-properties 1 value
)
5114 (match-string-no-properties 2 value
))))
5115 (if links
(push pair
(cdr links
))
5116 (push (list 'link pair
) alist
)))))
5117 ((equal key
"OPTIONS")
5118 (when (and (org-string-nw-p value
)
5119 (string-match "\\^:\\(t\\|nil\\|{}\\)" value
))
5120 (push (cons 'scripts
(read (match-string 1 value
))) alist
)))
5121 ((equal key
"PRIORITIES")
5122 (push (cons 'priorities
5123 (let ((prio (split-string value
)))
5124 (if (< (length prio
) 3) '(?A ?C ?B
)
5125 (mapcar #'string-to-char prio
))))
5127 ((equal key
"PROPERTY")
5128 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value
)
5129 (let* ((property (assq 'property alist
))
5130 (value (org--update-property-plist
5131 (match-string-no-properties 1 value
)
5132 (match-string-no-properties 2 value
)
5134 (if property
(setcdr property value
)
5135 (push (cons 'property value
) alist
)))))
5136 ((equal key
"STARTUP")
5137 (let ((startup (assq 'startup alist
)))
5140 (append (cdr startup
) (split-string value
)))
5141 (push (cons 'startup
(split-string value
)) alist
))))
5143 (let ((tag-cell (assq 'tags alist
)))
5145 (setcdr tag-cell
(concat (cdr tag-cell
) "\n" value
))
5146 (push (cons 'tags value
) alist
))))
5147 ((member key
'("TODO" "SEQ_TODO" "TYP_TODO"))
5148 (let ((todo (assq 'todo alist
))
5149 (value (cons (if (equal key
"TYP_TODO") 'type
'sequence
)
5150 (split-string value
))))
5151 (if todo
(push value
(cdr todo
))
5152 (push (list 'todo value
) alist
))))
5153 ((equal key
"SETUPFILE")
5154 (unless buffer-read-only
; Do not check in Gnus messages.
5155 (let ((f (and (org-string-nw-p value
)
5157 (org-unbracket-string "\"" "\"" value
)))))
5158 (when (and f
(file-readable-p f
) (not (member f files
)))
5160 (setq default-directory
(file-name-directory f
))
5161 (insert-file-contents f
)
5163 ;; Fake Org mode to benefit from cache
5164 ;; without recurring needlessly.
5165 (let ((major-mode 'org-mode
))
5166 (org--setup-collect-keywords
5167 regexp
(cons f files
) alist
)))))))))))))))
5170 (defun org-tag-string-to-alist (s)
5171 "Return tag alist associated to string S.
5172 S is a value for TAGS keyword or produced with
5173 `org-tag-alist-to-string'. Return value is an alist suitable for
5174 `org-tag-alist' or `org-tag-persistent-alist'."
5175 (let ((lines (mapcar #'split-string
(split-string s
"\n" t
)))
5176 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5177 "\\|{.+?}\\)" ; regular expression
5178 "\\(?:(\\(.\\))\\)?\\'"))
5180 (dolist (tokens lines
(cdr (nreverse alist
)))
5181 (push '(:newline
) alist
)
5183 (let ((token (pop tokens
)))
5186 (push '(:startgroup
) alist
)
5187 (when (equal (nth 1 tokens
) ":") (setq group-flag t
)))
5189 (push '(:endgroup
) alist
)
5190 (setq group-flag nil
))
5192 (push '(:startgrouptag
) alist
)
5193 (when (equal (nth 1 tokens
) ":") (setq group-flag t
)))
5195 (push '(:endgrouptag
) alist
)
5196 (setq group-flag nil
))
5198 (push '(:grouptags
) alist
))
5199 ((guard (string-match tag-re token
))
5200 (let ((tag (match-string 1 token
))
5201 (key (and (match-beginning 2)
5202 (string-to-char (match-string 2 token
)))))
5203 ;; Push all tags in groups, no matter if they already
5204 ;; appear somewhere else in the list.
5205 (when (or group-flag
(not (assoc tag alist
)))
5206 (push (cons tag key
) alist
))))))))))
5208 (defun org-tag-alist-to-string (alist &optional skip-key
)
5209 "Return tag string associated to ALIST.
5211 ALIST is an alist, as defined in `org-tag-alist' or
5212 `org-tag-persistent-alist', or produced with
5213 `org-tag-string-to-alist'.
5215 Return value is a string suitable as a value for \"TAGS\"
5218 When optional argument SKIP-KEY is non-nil, skip selection keys
5220 (mapconcat (lambda (token)
5222 (`(:startgroup
) "{")
5224 (`(:startgrouptag
) "[")
5225 (`(:endgrouptag
) "]")
5229 (guard (not skip-key
))
5230 `(,(and tag
(pred stringp
)) .
,(and key
(pred characterp
))))
5231 (format "%s(%c)" tag key
))
5232 (`(,(and tag
(pred stringp
)) .
,_
) tag
)
5233 (_ (user-error "Invalid tag token: %S" token
))))
5237 (defun org-tag-alist-to-groups (alist)
5238 "Return group alist from tag ALIST.
5239 ALIST is an alist, as defined in `org-tag-alist' or
5240 `org-tag-persistent-alist', or produced with
5241 `org-tag-string-to-alist'. Return value is an alist following
5242 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5243 a string, summarizing TAGS, as a list of strings."
5244 (let (groups group-status current-group
)
5245 (dolist (token alist
(nreverse groups
))
5247 (`(,(or :startgroup
:startgrouptag
)) (setq group-status t
))
5248 (`(,(or :endgroup
:endgrouptag
))
5249 (when (eq group-status
'append
)
5250 (push (nreverse current-group
) groups
))
5251 (setq group-status nil
))
5252 (`(:grouptags
) (setq group-status
'append
))
5253 ((and `(,tag .
,_
) (guard group-status
))
5254 (if (eq group-status
'append
) (push tag current-group
)
5255 (setq current-group
(list tag
))))
5258 (defvar org--file-cache
(make-hash-table :test
#'equal
)
5259 "Hash table to store contents of files referenced via a URL.
5260 This is the cache of file URLs read using `org-file-contents'.")
5262 (defun org-reset-file-cache ()
5263 "Reset the cache of files downloaded by `org-file-contents'."
5264 (clrhash org--file-cache
))
5266 (defun org-file-url-p (file)
5267 "Non-nil if FILE is a URL."
5269 (string-match-p ffap-url-regexp file
))
5271 (defun org-file-contents (file &optional noerror nocache
)
5272 "Return the contents of FILE, as a string.
5274 FILE can be a file name or URL.
5276 If FILE is a URL, download the contents. If the URL contents are
5277 already cached in the `org--file-cache' hash table, the download step
5280 If NOERROR is non-nil, ignore the error when unable to read the FILE
5283 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5284 is available. This option applies only if FILE is a URL."
5285 (let* ((is-url (org-file-url-p file
))
5288 (gethash file org--file-cache
))))
5292 (with-current-buffer (url-retrieve-synchronously file
)
5293 (goto-char (point-min))
5294 ;; Move point to after the url-retrieve header.
5295 (search-forward "\n\n" nil
:move
)
5296 ;; Search for the success code only in the url-retrieve header.
5298 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil
:noerror
))
5299 ;; Update the cache `org--file-cache' and return contents.
5301 (buffer-substring-no-properties (point) (point-max))
5303 (funcall (if noerror
#'message
#'user-error
)
5304 "Unable to fetch file from %S"
5310 (insert-file-contents file
)
5313 (funcall (if noerror
#'message
#'user-error
)
5314 "Unable to read file %S"
5317 (defun org-extract-log-state-settings (x)
5318 "Extract the log state setting from a TODO keyword string.
5319 This will extract info from a string like \"WAIT(w@/!)\"."
5320 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x
)
5321 (let ((kw (match-string 1 x
))
5322 (log1 (and (match-end 3) (match-string 3 x
)))
5323 (log2 (and (match-end 4) (match-string 4 x
))))
5326 (and log1
(if (equal log1
"!") 'time
'note
))
5327 (and log2
(if (equal log2
"!") 'time
'note
)))))))
5329 (defun org-remove-keyword-keys (list)
5330 "Remove a pair of parenthesis at the end of each string in LIST."
5332 (if (string-match "(.*)$" x
)
5333 (substring x
0 (match-beginning 0))
5337 (defun org-assign-fast-keys (alist)
5338 "Assign fast keys to a keyword-key alist.
5339 Respect keys that are already there."
5340 (let (new e
(alt ?
0))
5341 (while (setq e
(pop alist
))
5342 (if (or (memq (car e
) '(:newline
:grouptags
:endgroup
:startgroup
))
5343 (cdr e
)) ;; Key already assigned.
5345 (let ((clist (string-to-list (downcase (car e
))))
5346 (used (append new alist
)))
5347 (when (= (car clist
) ?
@)
5349 (while (and clist
(rassoc (car clist
) used
))
5352 (while (rassoc alt used
)
5354 (push (cons (car e
) (or (car clist
) alt
)) new
))))
5357 ;;; Some variables used in various places
5359 (defvar org-window-configuration nil
5360 "Used in various places to store a window configuration.")
5361 (defvar org-selected-window nil
5362 "Used in various places to store a window configuration.")
5363 (defvar org-finish-function nil
5364 "Function to be called when `C-c C-c' is used.
5365 This is for getting out of special buffers like capture.")
5366 (defvar org-last-state
)
5368 ;; Defined somewhere in this file, but used before definition.
5369 (defvar org-entities
) ;; defined in org-entities.el
5370 (defvar org-struct-menu
)
5371 (defvar org-org-menu
)
5372 (defvar org-tbl-menu
)
5374 ;;;; Define the Org mode
5376 ;; We use a before-change function to check if a table might need
5378 (defvar org-table-may-need-update t
5379 "Indicates that a table might need an update.
5380 This variable is set by `org-before-change-function'.
5381 `org-table-align' sets it back to nil.")
5382 (defun org-before-change-function (_beg _end
)
5383 "Every change indicates that a table might need an update."
5384 (setq org-table-may-need-update t
))
5385 (defvar org-mode-map
)
5386 (defvar org-inhibit-startup-visibility-stuff nil
) ; Dynamically-scoped param.
5387 (defvar org-agenda-keep-modes nil
) ; Dynamically-scoped param.
5388 (defvar org-inhibit-logging nil
) ; Dynamically-scoped param.
5389 (defvar org-inhibit-blocking nil
) ; Dynamically-scoped param.
5390 (defvar org-table-buffer-is-an nil
)
5392 (defvar bidi-paragraph-direction
)
5393 (defvar buffer-face-mode-face
)
5397 ;; Other stuff we need.
5398 (require 'time-date
)
5399 (unless (fboundp 'time-subtract
) (defalias 'time-subtract
'subtract-time
))
5401 (autoload 'easy-menu-add
"easymenu")
5404 ;; (require 'org-macs) moved higher up in the file before it is first used
5405 (require 'org-entities
)
5406 ;; (require 'org-compat) moved higher up in the file before it is first used
5407 (require 'org-faces
)
5409 (require 'org-pcomplete
)
5411 (require 'org-footnote
)
5412 (require 'org-macro
)
5418 (define-derived-mode org-mode outline-mode
"Org"
5419 "Outline-based notes management and organizer, alias
5420 \"Carsten's outline-mode for keeping track of everything.\"
5422 Org mode develops organizational tasks around a NOTES file which
5423 contains information about projects as plain text. Org mode is
5424 implemented on top of Outline mode, which is ideal to keep the content
5425 of large files well structured. It supports ToDo items, deadlines and
5426 time stamps, which magically appear in the diary listing of the Emacs
5427 calendar. Tables are easily created with a built-in table editor.
5428 Plain text URL-like links connect to websites, emails (VM), Usenet
5429 messages (Gnus), BBDB entries, and any files related to the project.
5430 For printing and sharing of notes, an Org file (or a part of it)
5431 can be exported as a structured ASCII or HTML file.
5433 The following commands are available:
5437 ;; Get rid of Outline menus, they are not needed
5438 ;; Need to do this here because define-derived-mode sets up
5439 ;; the keymap so late. Still, it is a waste to call this each time
5440 ;; we switch another buffer into Org mode.
5441 (define-key org-mode-map
[menu-bar headings
] 'undefined
)
5442 (define-key org-mode-map
[menu-bar hide
] 'undefined
)
5443 (define-key org-mode-map
[menu-bar show
] 'undefined
)
5445 (org-load-modules-maybe)
5446 (org-install-agenda-files-menu)
5447 (when org-descriptive-links
(add-to-invisibility-spec '(org-link)))
5448 (add-to-invisibility-spec '(org-cwidth))
5449 (add-to-invisibility-spec '(org-hide-block . t
))
5450 (setq-local outline-regexp org-outline-regexp
)
5451 (setq-local outline-level
'org-outline-level
)
5452 (setq bidi-paragraph-direction
'left-to-right
)
5453 (when (and (stringp org-ellipsis
) (not (equal "" org-ellipsis
)))
5454 (unless org-display-table
5455 (setq org-display-table
(make-display-table)))
5456 (set-display-table-slot
5458 (vconcat (mapcar (lambda (c) (make-glyph-code c
'org-ellipsis
))
5460 (setq buffer-display-table org-display-table
))
5461 (org-set-regexps-and-options)
5462 (org-set-font-lock-defaults)
5463 (when (and org-tag-faces
(not org-tags-special-faces-re
))
5464 ;; tag faces set outside customize.... force initialization.
5465 (org-set-tag-faces 'org-tag-faces org-tag-faces
))
5467 (setq-local calc-embedded-open-mode
"# ")
5468 ;; Modify a few syntax entries
5469 (modify-syntax-entry ?
@ "w")
5470 (modify-syntax-entry ?
\" "\"")
5471 (modify-syntax-entry ?
\\ "_")
5472 (modify-syntax-entry ?~
"_")
5473 (setq-local font-lock-unfontify-region-function
'org-unfontify-region
)
5474 ;; Activate before-change-function
5475 (setq-local org-table-may-need-update t
)
5476 (add-hook 'before-change-functions
'org-before-change-function nil
'local
)
5477 ;; Check for running clock before killing a buffer
5478 (add-hook 'kill-buffer-hook
'org-check-running-clock nil
'local
)
5479 ;; Initialize macros templates.
5480 (org-macro-initialize-templates)
5481 ;; Initialize radio targets.
5482 (org-update-radio-target-regexp)
5484 (setq-local indent-line-function
'org-indent-line
)
5485 (setq-local indent-region-function
'org-indent-region
)
5486 ;; Filling and auto-filling.
5489 (org-setup-comments-handling)
5490 ;; Initialize cache.
5491 (org-element-cache-reset)
5492 ;; Beginning/end of defun
5493 (setq-local beginning-of-defun-function
'org-backward-element
)
5494 (setq-local end-of-defun-function
5496 (if (not (org-at-heading-p))
5497 (org-forward-element)
5498 (org-forward-element)
5499 (forward-char -
1))))
5500 ;; Next error for sparse trees
5501 (setq-local next-error-function
'org-occur-next-match
)
5502 ;; Make sure dependence stuff works reliably, even for users who set it
5504 (if org-enforce-todo-dependencies
5505 (add-hook 'org-blocker-hook
5506 'org-block-todo-from-children-or-siblings-or-parent
)
5507 (remove-hook 'org-blocker-hook
5508 'org-block-todo-from-children-or-siblings-or-parent
))
5509 (if org-enforce-todo-checkbox-dependencies
5510 (add-hook 'org-blocker-hook
5511 'org-block-todo-from-checkboxes
)
5512 (remove-hook 'org-blocker-hook
5513 'org-block-todo-from-checkboxes
))
5515 ;; Align options lines
5517 align-mode-rules-list
5518 '((org-in-buffer-settings
5519 (regexp .
"^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5520 (modes .
'(org-mode)))))
5523 (setq-local imenu-create-index-function
'org-imenu-get-tree
)
5525 ;; Make isearch reveal context
5526 (setq-local outline-isearch-open-invisible-function
5527 (lambda (&rest _
) (org-show-context 'isearch
)))
5529 ;; Setup the pcomplete hooks
5530 (setq-local pcomplete-command-completion-function
'org-pcomplete-initial
)
5531 (setq-local pcomplete-command-name-function
'org-command-at-point
)
5532 (setq-local pcomplete-default-completion-function
'ignore
)
5533 (setq-local pcomplete-parse-arguments-function
'org-parse-arguments
)
5534 (setq-local pcomplete-termination-string
"")
5535 (setq-local buffer-face-mode-face
'org-default
)
5537 ;; If empty file that did not turn on Org mode automatically, make
5539 (when (and org-insert-mode-line-in-empty-file
5540 (called-interactively-p 'any
)
5541 (= (point-min) (point-max)))
5542 (insert "# -*- mode: org -*-\n\n"))
5543 (unless org-inhibit-startup
5545 (when org-startup-with-beamer-mode
(org-beamer-mode))
5546 (when org-startup-align-all-tables
5547 (org-table-map-tables #'org-table-align t
))
5548 (when org-startup-with-inline-images
(org-display-inline-images))
5549 (when org-startup-with-latex-preview
(org-toggle-latex-fragment '(16)))
5550 (unless org-inhibit-startup-visibility-stuff
(org-set-startup-visibility))
5551 (when org-startup-truncated
(setq truncate-lines t
))
5552 (when org-startup-indented
(require 'org-indent
) (org-indent-mode 1))
5553 (org-refresh-effort-properties)))
5554 ;; Try to set `org-hide' face correctly.
5555 (let ((foreground (org-find-invisible-foreground)))
5557 (set-face-foreground 'org-hide foreground
))))
5559 ;; Update `customize-package-emacs-version-alist'
5560 (add-to-list 'customize-package-emacs-version-alist
5561 '(Org ("8.0" .
"24.4")
5569 (defvar org-mode-transpose-word-syntax-table
5570 (let ((st (make-syntax-table text-mode-syntax-table
)))
5571 (dolist (c org-emphasis-alist st
)
5572 (modify-syntax-entry (string-to-char (car c
)) "w p" st
))))
5574 (when (fboundp 'abbrev-table-put
)
5575 (abbrev-table-put org-mode-abbrev-table
5576 :parents
(list text-mode-abbrev-table
)))
5578 (defun org-find-invisible-foreground ()
5579 (let ((candidates (remove
5582 (list (face-background 'default
)
5583 (face-background 'org-default
))
5586 (when (boundp alist
)
5587 (cdr (assq 'background-color
(symbol-value alist
)))))
5588 '(default-frame-alist initial-frame-alist window-system-default-frame-alist
))
5589 (list (face-foreground 'org-hide
))))))
5590 (car (remove nil candidates
))))
5592 (defun org-current-time (&optional rounding-minutes past
)
5593 "Current time, possibly rounded to ROUNDING-MINUTES.
5594 When ROUNDING-MINUTES is not an integer, fall back on the car of
5595 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5596 the rounding returns a past time."
5597 (let ((r (or (and (integerp rounding-minutes
) rounding-minutes
)
5598 (car org-time-stamp-rounding-minutes
)))
5599 (time (decode-time)) res
)
5604 (append (list 0 (* r
(floor (+ .5 (/ (float (nth 1 time
)) r
)))))
5606 (if (and past
(< (float-time (time-subtract (current-time) res
)) 0))
5607 (seconds-to-time (- (float-time res
) (* r
60)))
5611 "Return today date, considering `org-extend-today-until'."
5613 (time-subtract (current-time)
5614 (list 0 (* 3600 org-extend-today-until
) 0))))
5616 ;;;; Font-Lock stuff, including the activators
5618 (defvar org-mouse-map
(make-sparse-keymap))
5619 (org-defkey org-mouse-map
[mouse-2
] 'org-open-at-mouse
)
5620 (org-defkey org-mouse-map
[mouse-3
] 'org-find-file-at-mouse
)
5621 (when org-mouse-1-follows-link
5622 (org-defkey org-mouse-map
[follow-link
] 'mouse-face
))
5623 (when org-tab-follows-link
5624 (org-defkey org-mouse-map
[(tab)] 'org-open-at-point
)
5625 (org-defkey org-mouse-map
"\C-i" 'org-open-at-point
))
5627 (require 'font-lock
)
5629 (defconst org-non-link-chars
"]\t\n\r<>")
5630 (defvar org-link-types-re nil
5631 "Matches a link that has a url-like prefix like \"http:\"")
5632 (defvar org-link-re-with-space nil
5633 "Matches a link with spaces, optional angular brackets around it.")
5634 (defvar org-link-re-with-space2 nil
5635 "Matches a link with spaces, optional angular brackets around it.")
5636 (defvar org-link-re-with-space3 nil
5637 "Matches a link with spaces, only for internal part in bracket links.")
5638 (defvar org-angle-link-re nil
5639 "Matches link with angular brackets, spaces are allowed.")
5640 (defvar org-plain-link-re nil
5641 "Matches plain link, without spaces.")
5642 (defvar org-bracket-link-regexp nil
5643 "Matches a link in double brackets.")
5644 (defvar org-bracket-link-analytic-regexp nil
5645 "Regular expression used to analyze links.
5646 Here is what the match groups contain after a match:
5652 (defvar org-bracket-link-analytic-regexp
++ nil
5653 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5654 (defvar org-any-link-re nil
5655 "Regular expression matching any link.")
5657 (defconst org-match-sexp-depth
3
5658 "Number of stacked braces for sub/superscript matching.")
5660 (defun org-create-multibrace-regexp (left right n
)
5661 "Create a regular expression which will match a balanced sexp.
5662 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5663 as single character strings.
5664 The regexp returned will match the entire expression including the
5665 delimiters. It will also define a single group which contains the
5666 match except for the outermost delimiters. The maximum depth of
5667 stacked delimiters is N. Escaping delimiters is not possible."
5668 (let* ((nothing (concat "[^" left right
"]*?"))
5671 (next (concat "\\(?:" nothing left nothing right
"\\)+" nothing
)))
5674 re
(concat re or next
)
5675 next
(concat "\\(?:" nothing left next right
"\\)+" nothing
)))
5676 (concat left
"\\(" re
"\\)" right
)))
5678 (defconst org-match-substring-regexp
5680 "\\(\\S-\\)\\([_^]\\)\\("
5681 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)"
5683 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth
) "\\)"
5685 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5686 "The regular expression matching a sub- or superscript.")
5688 (defconst org-match-substring-with-braces-regexp
5690 "\\(\\S-\\)\\([_^]\\)"
5691 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)")
5692 "The regular expression matching a sub- or superscript, forcing braces.")
5694 (defun org-make-link-regexps ()
5695 "Update the link regular expressions.
5696 This should be called after the variable `org-link-parameters' has changed."
5697 (let ((types-re (regexp-opt (org-link-types) t
)))
5698 (setq org-link-types-re
5699 (concat "\\`" types-re
":")
5700 org-link-re-with-space
5701 (concat "<?" types-re
":"
5702 "\\([^" org-non-link-chars
" ]"
5703 "[^" org-non-link-chars
"]*"
5704 "[^" org-non-link-chars
" ]\\)>?")
5705 org-link-re-with-space2
5706 (concat "<?" types-re
":"
5707 "\\([^" org-non-link-chars
" ]"
5709 "[^" org-non-link-chars
" ]\\)>?")
5710 org-link-re-with-space3
5711 (concat "<?" types-re
":"
5712 "\\([^" org-non-link-chars
" ]"
5715 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5720 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5721 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5722 org-bracket-link-regexp
5723 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5724 org-bracket-link-analytic-regexp
5727 "\\(" types-re
":\\)?"
5730 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5732 org-bracket-link-analytic-regexp
++
5735 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t
) ":\\)?"
5738 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5741 (concat "\\(" org-bracket-link-regexp
"\\)\\|\\("
5742 org-angle-link-re
"\\)\\|\\("
5743 org-plain-link-re
"\\)"))))
5745 (org-make-link-regexps)
5747 (defvar org-emph-face nil
)
5749 (defun org-do-emphasis-faces (limit)
5750 "Run through the buffer and emphasize strings."
5751 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5752 (car org-emphasis-regexp-components
))))
5754 (while (re-search-forward quick-re limit t
)
5755 (let* ((marker (match-string 2))
5756 (verbatim?
(member marker
'("~" "="))))
5757 (when (save-excursion
5758 (goto-char (match-beginning 0))
5760 ;; Do not match table hlines.
5761 (not (and (equal marker
"+")
5763 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5764 ;; Do not match headline stars. Do not consider
5765 ;; stars of a headline as closing marker for bold
5767 (not (and (equal marker
"*")
5770 (skip-chars-backward "*")
5771 (looking-at-p org-outline-regexp-bol
))))
5772 ;; Match full emphasis markup regexp.
5773 (looking-at (if verbatim? org-verbatim-re org-emph-re
))
5774 ;; Do not span over paragraph boundaries.
5775 (not (string-match-p org-element-paragraph-separate
5777 ;; Do not span over cells in table rows.
5778 (not (and (save-match-data (org-match-line "[ \t]*|"))
5779 (string-match-p "|" (match-string 4))))))
5780 (pcase-let ((`(,_
,face
,_
) (assoc marker org-emphasis-alist
)))
5781 (font-lock-prepend-text-property
5782 (match-beginning 2) (match-end 2) 'face face
)
5784 (org-remove-flyspell-overlays-in
5785 (match-beginning 0) (match-end 0)))
5786 (add-text-properties (match-beginning 2) (match-end 2)
5787 '(font-lock-multiline t org-emphasis t
))
5788 (when org-hide-emphasis-markers
5789 (add-text-properties (match-end 4) (match-beginning 5)
5790 '(invisible org-link
))
5791 (add-text-properties (match-beginning 3) (match-end 3)
5792 '(invisible org-link
)))
5793 (throw :exit t
))))))))
5795 (defun org-emphasize (&optional char
)
5796 "Insert or change an emphasis, i.e. a font like bold or italic.
5797 If there is an active region, change that region to a new emphasis.
5798 If there is no region, just insert the marker characters and position
5799 the cursor between them.
5800 CHAR should be the marker character. If it is a space, it means to
5801 remove the emphasis of the selected region.
5802 If CHAR is not given (for example in an interactive call) it will be
5805 (let ((erc org-emphasis-regexp-components
)
5806 (string "") beg end move s
)
5807 (if (org-region-active-p)
5808 (setq beg
(region-beginning)
5810 string
(buffer-substring beg end
))
5814 (message "Emphasis marker or tag: [%s]"
5815 (mapconcat #'car org-emphasis-alist
""))
5816 (setq char
(read-char-exclusive)))
5817 (if (equal char ?\s
)
5820 (unless (assoc (char-to-string char
) org-emphasis-alist
)
5821 (user-error "No such emphasis marker: \"%c\"" char
))
5822 (setq s
(char-to-string char
)))
5823 (while (and (> (length string
) 1)
5824 (equal (substring string
0 1) (substring string -
1))
5825 (assoc (substring string
0 1) org-emphasis-alist
))
5826 (setq string
(substring string
1 -
1)))
5827 (setq string
(concat s string s
))
5828 (when beg
(delete-region beg end
))
5830 (string-match (concat "[" (nth 0 erc
) "\n]")
5831 (char-to-string (char-before (point)))))
5834 (string-match (concat "[" (nth 1 erc
) "\n]")
5835 (char-to-string (char-after (point)))))
5836 (insert " ") (backward-char 1))
5838 (and move
(backward-char 1))))
5840 (defconst org-nonsticky-props
5841 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link
))
5843 (defsubst org-rear-nonsticky-at
(pos)
5844 (add-text-properties (1- pos
) pos
(list 'rear-nonsticky org-nonsticky-props
)))
5846 (defun org-activate-links (limit)
5847 "Add link properties to links.
5848 This includes angle, plain, and bracket links."
5850 (while (re-search-forward org-any-link-re limit t
)
5851 (let* ((start (match-beginning 0))
5853 (style (cond ((eq ?
< (char-after start
)) 'angle
)
5854 ((eq ?\
[ (char-after (1+ start
))) 'bracket
)
5856 (when (and (memq style org-highlight-links
)
5857 ;; Do not confuse plain links with tags.
5858 (not (and (eq style
'plain
)
5859 (let ((face (get-text-property
5860 (max (1- start
) (point-min)) 'face
)))
5861 (if (consp face
) (memq 'org-tag face
)
5862 (eq 'org-tag face
))))))
5863 (let* ((link-object (save-excursion
5865 (save-match-data (org-element-link-parser))))
5866 (link (org-element-property :raw-link link-object
))
5867 (type (org-element-property :type link-object
))
5868 (path (org-element-property :path link-object
))
5869 (properties ;for link's visible part
5871 'face
(pcase (org-link-get-parameter type
:face
)
5872 ((and (pred functionp
) face
) (funcall face path
))
5873 ((and (pred facep
) face
) face
)
5874 ((and (pred consp
) face
) face
) ;anonymous
5876 'mouse-face
(or (org-link-get-parameter type
:mouse-face
)
5878 'keymap
(or (org-link-get-parameter type
:keymap
)
5880 'help-echo
(pcase (org-link-get-parameter type
:help-echo
)
5881 ((and (pred stringp
) echo
) echo
)
5882 ((and (pred functionp
) echo
) echo
)
5883 (_ (concat "LINK: " link
)))
5884 'htmlize-link
(pcase (org-link-get-parameter type
5886 ((and (pred functionp
) f
) (funcall f
))
5888 'font-lock-multiline t
)))
5889 (org-remove-flyspell-overlays-in start end
)
5890 (org-rear-nonsticky-at end
)
5891 (if (not (eq 'bracket style
))
5892 (add-text-properties start end properties
)
5893 ;; Handle invisible parts in bracket links.
5894 (remove-text-properties start end
'(invisible nil
))
5897 ,(or (org-link-get-parameter type
:display
)
5900 (visible-start (or (match-beginning 4) (match-beginning 2)))
5901 (visible-end (or (match-end 4) (match-end 2))))
5902 (add-text-properties start visible-start hidden
)
5903 (add-text-properties visible-start visible-end properties
)
5904 (add-text-properties visible-end end hidden
)
5905 (org-rear-nonsticky-at visible-start
)
5906 (org-rear-nonsticky-at visible-end
)))
5907 (let ((f (org-link-get-parameter type
:activate-func
)))
5909 (funcall f start end path
(eq style
'bracket
))))
5910 (throw :exit t
))))) ;signal success
5913 (defun org-activate-code (limit)
5914 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t
)
5915 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5916 (remove-text-properties (match-beginning 0) (match-end 0)
5917 '(display t invisible t intangible t
))
5920 (defcustom org-src-fontify-natively t
5921 "When non-nil, fontify code in code blocks.
5922 See also the `org-block' face."
5925 :package-version
'(Org .
"8.3")
5926 :group
'org-appearance
5929 (defcustom org-allow-promoting-top-level-subtree nil
5930 "When non-nil, allow promoting a top level subtree.
5931 The leading star of the top level headline will be replaced
5935 :group
'org-appearance
)
5937 (defun org-fontify-meta-lines-and-blocks (limit)
5939 (org-fontify-meta-lines-and-blocks-1 limit
)
5940 (error (message "org-mode fontification error in %S at %d"
5942 (line-number-at-pos)))))
5944 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5945 "Fontify #+ lines and blocks."
5946 (let ((case-fold-search t
))
5947 (when (re-search-forward
5948 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5950 (let ((beg (match-beginning 0))
5951 (block-start (match-end 0))
5953 (lang (match-string 7))
5954 (beg1 (line-beginning-position 2))
5955 (dc1 (downcase (match-string 2)))
5956 (dc3 (downcase (match-string 3)))
5957 end end1 quoting block-type
)
5959 ((and (match-end 4) (equal dc3
"+begin"))
5961 (setq block-type
(downcase (match-string 5))
5962 quoting
(member block-type org-protecting-blocks
))
5963 (when (re-search-forward
5964 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5965 nil t
) ;; on purpose, we look further than LIMIT
5966 (setq end
(min (point-max) (match-end 0))
5967 end1
(min (point-max) (1- (match-beginning 0))))
5968 (setq block-end
(match-beginning 0))
5970 (org-remove-flyspell-overlays-in beg1 end1
)
5971 (remove-text-properties beg end
5972 '(display t invisible t intangible t
)))
5973 (add-text-properties
5974 beg end
'(font-lock-fontified t font-lock-multiline t
))
5975 (add-text-properties beg beg1
'(face org-meta-line
))
5976 (org-remove-flyspell-overlays-in beg beg1
)
5977 (add-text-properties ; For end_src
5978 end1
(min (point-max) (1+ end
)) '(face org-meta-line
))
5979 (org-remove-flyspell-overlays-in end1 end
)
5981 ((and lang
(not (string= lang
"")) org-src-fontify-natively
)
5982 (org-src-font-lock-fontify-block lang block-start block-end
)
5983 (add-text-properties beg1 block-end
'(src-block t
)))
5985 (add-text-properties beg1
(min (point-max) (1+ end1
))
5989 (intern (format "org-block-%s" lang
))))
5990 (append (and (facep face-name
) (list face-name
))
5991 '(org-block))))))) ; end of source block
5992 ((not org-fontify-quote-and-verse-blocks
))
5993 ((string= block-type
"quote")
5994 (add-face-text-property
5995 beg1
(min (point-max) (1+ end1
)) 'org-quote t
))
5996 ((string= block-type
"verse")
5997 (add-face-text-property
5998 beg1
(min (point-max) (1+ end1
)) 'org-verse t
)))
5999 (add-text-properties beg beg1
'(face org-block-begin-line
))
6000 (add-text-properties (min (point-max) (1+ end
)) (min (point-max) (1+ end1
))
6001 '(face org-block-end-line
))
6003 ((member dc1
'("+title:" "+author:" "+email:" "+date:"))
6004 (org-remove-flyspell-overlays-in
6006 (if (equal "+title:" dc1
) (match-end 2) (match-end 0)))
6007 (add-text-properties
6009 (if (member (intern (substring dc1
1 -
1)) org-hidden-keywords
)
6010 '(font-lock-fontified t invisible t
)
6011 '(font-lock-fontified t face org-document-info-keyword
)))
6012 (add-text-properties
6013 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6014 (if (string-equal dc1
"+title:")
6015 '(font-lock-fontified t face org-document-title
)
6016 '(font-lock-fontified t face org-document-info
))))
6017 ((string-prefix-p "+caption" dc1
)
6018 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6019 (remove-text-properties (match-beginning 0) (match-end 0)
6020 '(display t invisible t intangible t
))
6021 ;; Handle short captions.
6024 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6025 (add-text-properties (line-beginning-position) (match-end 1)
6026 '(font-lock-fontified t face org-meta-line
))
6027 (add-text-properties (match-end 0) (line-end-position)
6028 '(font-lock-fontified t face org-block
))
6030 ((member dc3
'(" " ""))
6031 (org-remove-flyspell-overlays-in beg
(match-end 0))
6032 (add-text-properties
6034 '(font-lock-fontified t face font-lock-comment-face
)))
6035 (t ;; just any other in-buffer setting, but not indented
6036 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6037 (remove-text-properties (match-beginning 0) (match-end 0)
6038 '(display t invisible t intangible t
))
6039 (add-text-properties beg
(match-end 0)
6040 '(font-lock-fontified t face org-meta-line
))
6043 (defun org-fontify-drawers (limit)
6045 (when (re-search-forward org-drawer-regexp limit t
)
6046 (add-text-properties
6047 (match-beginning 0) (match-end 0)
6048 '(font-lock-fontified t face org-special-keyword
))
6049 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6052 (defun org-fontify-macros (limit)
6054 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t
)
6055 (add-text-properties
6056 (match-beginning 0) (match-end 0)
6057 '(font-lock-fontified t face org-macro
))
6058 (when org-hide-macro-markers
6059 (add-text-properties (match-end 2) (match-beginning 2)
6061 (add-text-properties (match-beginning 1) (match-end 1)
6063 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6066 (defun org-activate-footnote-links (limit)
6067 "Add text properties for footnotes."
6068 (let ((fn (org-footnote-next-reference-or-definition limit
)))
6070 (let* ((beg (nth 1 fn
))
6073 (referencep (/= (line-beginning-position) beg
)))
6074 (when (and referencep
(nth 3 fn
))
6077 (search-forward (or label
"fn:"))
6078 (org-remove-flyspell-overlays-in beg
(match-end 0))))
6079 (add-text-properties beg end
6080 (list 'mouse-face
'highlight
6081 'keymap org-mouse-map
6083 (if referencep
"Footnote reference"
6084 "Footnote definition")
6085 'font-lock-fontified t
6086 'font-lock-multiline t
6087 'face
'org-footnote
))))))
6089 (defun org-activate-dates (limit)
6090 "Add text properties for dates."
6091 (when (and (re-search-forward org-tsr-regexp-both limit t
)
6092 (not (equal (char-before (match-beginning 0)) 91)))
6093 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6094 (add-text-properties (match-beginning 0) (match-end 0)
6095 (list 'mouse-face
'highlight
6096 'keymap org-mouse-map
))
6097 (org-rear-nonsticky-at (match-end 0))
6098 (when org-display-custom-times
6099 ;; If it's a date range, activate custom time for second date.
6101 (org-display-custom-time (match-beginning 3) (match-end 3)))
6102 (org-display-custom-time (match-beginning 1) (match-end 1)))
6105 (defvar-local org-target-link-regexp nil
6106 "Regular expression matching radio targets in plain text.")
6108 (defconst org-target-regexp
(let ((border "[^<>\n\r \t]"))
6109 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6110 border border border
))
6111 "Regular expression matching a link target.")
6113 (defconst org-radio-target-regexp
(format "<%s>" org-target-regexp
)
6114 "Regular expression matching a radio target.")
6116 (defconst org-any-target-regexp
6117 (format "%s\\|%s" org-radio-target-regexp org-target-regexp
)
6118 "Regular expression matching any target.")
6120 (defun org-activate-target-links (limit)
6121 "Add text properties for target matches."
6122 (when org-target-link-regexp
6123 (let ((case-fold-search t
))
6124 (when (re-search-forward org-target-link-regexp limit t
)
6125 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6126 (add-text-properties (match-beginning 1) (match-end 1)
6127 (list 'mouse-face
'highlight
6128 'keymap org-mouse-map
6129 'help-echo
"Radio target link"
6130 'org-linked-text t
))
6131 (org-rear-nonsticky-at (match-end 1))
6134 (defun org-update-radio-target-regexp ()
6135 "Find all radio targets in this file and update the regular expression.
6136 Also refresh fontification if needed."
6138 (let ((old-regexp org-target-link-regexp
)
6139 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6140 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6142 (org-with-wide-buffer
6143 (goto-char (point-min))
6145 (while (re-search-forward org-radio-target-regexp nil t
)
6146 ;; Make sure point is really within the object.
6148 (let ((obj (org-element-context)))
6149 (when (eq (org-element-type obj
) 'radio-target
)
6150 (cl-pushnew (org-element-property :value obj
) rtn
6153 (setq org-target-link-regexp
6158 (replace-regexp-in-string
6159 " +" "\\s-+" (regexp-quote x
) t t
))
6163 (unless (equal old-regexp org-target-link-regexp
)
6165 (let ((regexp (cond ((not old-regexp
) org-target-link-regexp
)
6166 ((not org-target-link-regexp
) old-regexp
)
6171 (substring re
(length before-re
)
6172 (- (length after-re
))))
6173 (list old-regexp org-target-link-regexp
)
6176 (org-with-wide-buffer
6177 (goto-char (point-min))
6178 (while (re-search-forward regexp nil t
)
6179 (org-element-cache-refresh (match-beginning 1)))))
6180 ;; Re fontify buffer.
6181 (when (memq 'radio org-highlight-links
)
6182 (org-restart-font-lock)))))
6184 (defun org-hide-wide-columns (limit)
6186 (setq s
(text-property-any (point) (or limit
(point-max))
6189 (setq e
(next-single-property-change s
'org-cwidth
))
6190 (add-text-properties s e
'(invisible org-cwidth
))
6194 (defvar org-latex-and-related-regexp nil
6195 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6197 (defun org-compute-latex-and-related-regexp ()
6198 "Compute regular expression for LaTeX, entities and sub/superscript.
6199 Result depends on variable `org-highlight-latex-and-related'."
6201 org-latex-and-related-regexp
6203 (cond ((not (memq 'script org-highlight-latex-and-related
)) nil
)
6204 ((eq org-use-sub-superscripts
'{})
6205 (list org-match-substring-with-braces-regexp
))
6206 (org-use-sub-superscripts (list org-match-substring-regexp
))))
6208 (when (memq 'latex org-highlight-latex-and-related
)
6209 (let ((matchers (plist-get org-format-latex-options
:matchers
)))
6212 (and (member (car x
) matchers
) (nth 1 x
)))
6213 org-latex-regexps
)))))
6215 (when (memq 'entities org-highlight-latex-and-related
)
6216 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6217 (mapconcat 'identity
(append re-latex re-entities re-sub
) "\\|"))))
6219 (defun org-do-latex-and-related (limit)
6220 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6221 LIMIT bounds the search for syntax to highlight. Stop at first
6222 highlighted object, if any. Return t if some highlighting was
6223 done, nil otherwise."
6224 (when (org-string-nw-p org-latex-and-related-regexp
)
6226 (while (re-search-forward org-latex-and-related-regexp limit t
)
6230 (memq f
'(org-code org-verbatim underline org-special-keyword
)))
6232 (goto-char (1+ (match-beginning 0)))
6233 (face-at-point nil t
)))
6234 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6238 (font-lock-prepend-text-property
6239 (+ offset
(match-beginning 0)) (match-end 0)
6240 'face
'org-latex-and-related
)
6241 (add-text-properties (+ offset
(match-beginning 0)) (match-end 0)
6242 '(font-lock-multiline t
)))
6246 (defun org-restart-font-lock ()
6247 "Restart `font-lock-mode', to force refontification."
6248 (when (and (boundp 'font-lock-mode
) font-lock-mode
)
6250 (font-lock-mode 1)))
6252 (defun org-activate-tags (limit)
6253 (when (re-search-forward
6254 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t
)
6255 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6256 (add-text-properties (match-beginning 1) (match-end 1)
6257 (list 'mouse-face
'highlight
6258 'keymap org-mouse-map
))
6259 (org-rear-nonsticky-at (match-end 1))
6262 (defun org-outline-level ()
6263 "Compute the outline level of the heading at point.
6265 If this is called at a normal headline, the level is the number
6266 of stars. Use `org-reduced-level' to remove the effect of
6267 `org-odd-levels'. Unlike to `org-current-level', this function
6268 takes into consideration inlinetasks."
6269 (org-with-wide-buffer
6271 (if (re-search-backward org-outline-regexp-bol nil t
)
6272 (1- (- (match-end 0) (match-beginning 0)))
6275 (defvar org-font-lock-keywords nil
)
6277 (defsubst org-re-property
(property &optional literal allow-null value
)
6278 "Return a regexp matching a PROPERTY line.
6280 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6281 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6282 non-nil, match properties even without a value.
6284 Match group 3 is set to the value when it exists. If there is no
6285 value and ALLOW-NULL is non-nil, it is set to the empty string.
6287 With optional argument VALUE, match only property lines with
6288 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6289 unless LITERAL is non-nil."
6292 (format "\\(?1::\\(?2:%s\\):\\)"
6293 (if literal property
(regexp-quote property
)))
6295 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6296 (if literal value
(regexp-quote value
))))
6298 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6300 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6302 (defconst org-property-re
6303 (org-re-property "\\S-+" 'literal t
)
6304 "Regular expression matching a property line.
6305 There are four matching groups:
6306 1: :PROPKEY: including the leading and trailing colon,
6307 2: PROPKEY without the leading and trailing colon,
6308 3: PROPVAL without leading or trailing spaces,
6309 4: the indentation of the current line,
6310 5: trailing whitespace.")
6312 (defvar org-font-lock-hook nil
6313 "Functions to be called for special font lock stuff.")
6315 (defvar org-font-lock-extra-keywords nil
) ;Dynamically scoped.
6317 (defvar org-font-lock-set-keywords-hook nil
6318 "Functions that can manipulate `org-font-lock-extra-keywords'.
6319 This is called after `org-font-lock-extra-keywords' is defined, but before
6320 it is installed to be used by font lock. This can be useful if something
6321 needs to be inserted at a specific position in the font-lock sequence.")
6323 (defun org-font-lock-hook (limit)
6324 "Run `org-font-lock-hook' within LIMIT."
6325 (run-hook-with-args 'org-font-lock-hook limit
))
6327 (defun org-set-font-lock-defaults ()
6328 "Set font lock defaults for the current buffer."
6329 (let* ((em org-fontify-emphasized-text
)
6330 (lk org-highlight-links
)
6331 (org-font-lock-extra-keywords
6334 '(org-font-lock-hook)
6336 `(,(if org-fontify-whole-heading-line
6337 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6338 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6339 (1 (org-get-level-face 1))
6340 (2 (org-get-level-face 2))
6341 (3 (org-get-level-face 3)))
6343 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6346 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t
))
6347 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t
))
6348 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t
))
6349 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t
))
6351 '(org-fontify-drawers)
6353 (list org-property-re
6354 '(1 'org-special-keyword t
)
6355 '(3 'org-property-value t
))
6356 ;; Link related fontification.
6357 '(org-activate-links)
6358 (when (memq 'tag lk
) '(org-activate-tags (1 'org-tag prepend
)))
6359 (when (memq 'radio lk
) '(org-activate-target-links (1 'org-link t
)))
6360 (when (memq 'date lk
) '(org-activate-dates (0 'org-date t
)))
6361 (when (memq 'footnote lk
) '(org-activate-footnote-links))
6363 (list org-any-target-regexp
'(0 'org-target t
))
6365 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t
))
6367 '(org-fontify-macros)
6368 '(org-hide-wide-columns (0 nil append
))
6370 (list (format org-heading-keyword-regexp-format
6372 '(2 (org-get-todo-face 2) t
))
6374 (if org-fontify-done-headline
6375 (list (format org-heading-keyword-regexp-format
6378 (mapconcat 'regexp-quote org-done-keywords
"\\|")
6380 '(2 'org-headline-done t
))
6383 '(org-font-lock-add-priority-faces)
6385 '(org-font-lock-add-tag-faces)
6387 (when (and org-group-tags org-tag-groups-alist
)
6388 (list (concat org-outline-regexp-bol
".+\\(:"
6389 (regexp-opt (mapcar 'car org-tag-groups-alist
))
6391 '(1 'org-tag-group prepend
)))
6393 (list (concat "\\<" org-deadline-string
) '(0 'org-special-keyword t
))
6394 (list (concat "\\<" org-scheduled-string
) '(0 'org-special-keyword t
))
6395 (list (concat "\\<" org-closed-string
) '(0 'org-special-keyword t
))
6396 (list (concat "\\<" org-clock-string
) '(0 'org-special-keyword t
))
6398 (when em
'(org-do-emphasis-faces))
6400 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6401 1 'org-checkbox prepend
)
6402 (when (cdr (assq 'checkbox org-list-automatic-rules
))
6403 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6404 (0 (org-get-checkbox-statistics-face) t
)))
6405 ;; Description list items
6406 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6407 1 'org-list-dt prepend
)
6408 ;; ARCHIVEd headings
6410 org-outline-regexp-bol
6411 "\\(.*:" org-archive-tag
":.*\\)")
6412 '(1 'org-archived prepend
))
6414 '(org-do-latex-and-related)
6415 '(org-fontify-entities)
6416 '(org-raise-scripts)
6418 '(org-activate-code (1 'org-code t
))
6421 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6424 '(9 'org-special-keyword t
))
6425 ;; Blocks and meta lines
6426 '(org-fontify-meta-lines-and-blocks))))
6427 (setq org-font-lock-extra-keywords
(delq nil org-font-lock-extra-keywords
))
6428 (run-hooks 'org-font-lock-set-keywords-hook
)
6429 ;; Now set the full font-lock-keywords
6430 (setq-local org-font-lock-keywords org-font-lock-extra-keywords
)
6431 (setq-local font-lock-defaults
6432 '(org-font-lock-keywords t nil nil backward-paragraph
))
6433 (kill-local-variable 'font-lock-keywords
)
6436 (defun org-toggle-pretty-entities ()
6437 "Toggle the composition display of entities as UTF8 characters."
6439 (setq-local org-pretty-entities
(not org-pretty-entities
))
6440 (org-restart-font-lock)
6441 (if org-pretty-entities
6442 (message "Entities are now displayed as UTF8 characters")
6445 (decompose-region (point-min) (point-max))
6446 (message "Entities are now displayed as plain text"))))
6448 (defvar-local org-custom-properties-overlays nil
6449 "List of overlays used for custom properties.")
6451 (defun org-toggle-custom-properties-visibility ()
6452 "Display or hide properties in `org-custom-properties'."
6454 (if org-custom-properties-overlays
6455 (progn (mapc #'delete-overlay org-custom-properties-overlays
)
6456 (setq org-custom-properties-overlays nil
))
6457 (when org-custom-properties
6458 (org-with-wide-buffer
6459 (goto-char (point-min))
6460 (let ((regexp (org-re-property (regexp-opt org-custom-properties
) t t
)))
6461 (while (re-search-forward regexp nil t
)
6462 (let ((end (cdr (save-match-data (org-get-property-block)))))
6463 (when (and end
(< (point) end
))
6464 ;; Hide first custom property in current drawer.
6465 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6466 (overlay-put o
'invisible t
)
6467 (overlay-put o
'org-custom-property t
)
6468 (push o org-custom-properties-overlays
))
6469 ;; Hide additional custom properties in the same drawer.
6470 (while (re-search-forward regexp end t
)
6471 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6472 (overlay-put o
'invisible t
)
6473 (overlay-put o
'org-custom-property t
)
6474 (push o org-custom-properties-overlays
)))))
6475 ;; Each entry is limited to a single property drawer.
6476 (outline-next-heading)))))))
6478 (defun org-fontify-entities (limit)
6479 "Find an entity to fontify."
6481 (when org-pretty-entities
6483 ;; "\_ "-family is left out on purpose. Only the first one,
6484 ;; i.e., "\_ ", could be fontified anyway, and it would be
6485 ;; confusing when adding a second white space character.
6486 (while (re-search-forward
6487 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6489 (when (and (not (org-at-comment-p))
6490 (setq ee
(org-entity-get (match-string 1)))
6491 (= (length (nth 6 ee
)) 1))
6492 (let* ((end (if (equal (match-string 2) "{}")
6495 (add-text-properties
6496 (match-beginning 0) end
6497 (list 'font-lock-fontified t
))
6498 (compose-region (match-beginning 0) end
6504 (defun org-fontify-like-in-org-mode (s &optional odd-levels
)
6505 "Fontify string S like in Org mode."
6508 (let ((org-odd-levels-only odd-levels
))
6510 (org-font-lock-ensure)
6516 (defun org-get-level-face (n)
6517 "Get the right face for match N in font-lock matching of headlines."
6518 (setq org-l
(- (match-end 2) (match-beginning 1) 1))
6519 (when org-odd-levels-only
(setq org-l
(1+ (/ org-l
2))))
6520 (if org-cycle-level-faces
6521 (setq org-f
(nth (%
(1- org-l
) org-n-level-faces
) org-level-faces
))
6522 (setq org-f
(nth (1- (min org-l org-n-level-faces
)) org-level-faces
)))
6524 ((eq n
1) (if org-hide-leading-stars
'org-hide org-f
))
6526 (t (unless org-level-color-stars-only org-f
))))
6528 (defun org-face-from-face-or-color (context inherit face-or-color
)
6529 "Create a face list that inherits INHERIT, but sets the foreground color.
6530 When FACE-OR-COLOR is not a string, just return it."
6531 (if (stringp face-or-color
)
6532 (list :inherit inherit
6533 (cdr (assoc context org-faces-easy-properties
))
6537 (defun org-get-todo-face (kwd)
6538 "Get the right face for a TODO keyword KWD.
6539 If KWD is a number, get the corresponding match group."
6540 (when (numberp kwd
) (setq kwd
(match-string kwd
)))
6541 (or (org-face-from-face-or-color
6542 'todo
'org-todo
(cdr (assoc kwd org-todo-keyword-faces
)))
6543 (and (member kwd org-done-keywords
) 'org-done
)
6546 (defun org-get-priority-face (priority)
6547 "Get the right face for PRIORITY.
6548 PRIORITY is a character."
6549 (or (org-face-from-face-or-color
6550 'priority
'org-priority
(cdr (assq priority org-priority-faces
)))
6553 (defun org-get-tag-face (tag)
6554 "Get the right face for TAG.
6555 If TAG is a number, get the corresponding match group."
6556 (let ((tag (if (wholenump tag
) (match-string tag
) tag
)))
6557 (or (org-face-from-face-or-color
6558 'tag
'org-tag
(cdr (assoc tag org-tag-faces
)))
6561 (defun org-font-lock-add-priority-faces (limit)
6562 "Add the special priority faces."
6563 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t
)
6564 (add-text-properties
6565 (match-beginning 1) (match-end 1)
6566 (list 'face
(org-get-priority-face (string-to-char (match-string 2)))
6567 'font-lock-fontified t
))))
6569 (defun org-font-lock-add-tag-faces (limit)
6570 "Add the special tag faces."
6571 (when (and org-tag-faces org-tags-special-faces-re
)
6572 (while (re-search-forward org-tags-special-faces-re limit t
)
6573 (add-text-properties (match-beginning 1) (match-end 1)
6574 (list 'face
(org-get-tag-face 1)
6575 'font-lock-fontified t
))
6576 (backward-char 1))))
6578 (defun org-unfontify-region (beg end
&optional _maybe_loudly
)
6579 "Remove fontification and activation overlays from links."
6580 (font-lock-default-unfontify-region beg end
)
6581 (let* ((buffer-undo-list t
)
6582 (inhibit-read-only t
) (inhibit-point-motion-hooks t
)
6583 (inhibit-modification-hooks t
)
6584 deactivate-mark buffer-file-name buffer-file-truename
)
6585 (decompose-region beg end
)
6586 (remove-text-properties beg end
6587 '(mouse-face t keymap t org-linked-text t
6588 invisible t intangible t
6590 (org-remove-font-lock-display-properties beg end
)))
6592 (defconst org-script-display
'(((raise -
0.3) (height 0.7))
6593 ((raise 0.3) (height 0.7))
6596 "Display properties for showing superscripts and subscripts.")
6598 (defun org-remove-font-lock-display-properties (beg end
)
6599 "Remove specific display properties that have been added by font lock.
6600 The will remove the raise properties that are used to show superscripts
6604 (setq next
(next-single-property-change beg
'display nil end
)
6605 prop
(get-text-property beg
'display
))
6606 (when (member prop org-script-display
)
6607 (put-text-property beg next
'display nil
))
6610 (defun org-raise-scripts (limit)
6611 "Add raise properties to sub/superscripts."
6612 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6614 (if (eq org-use-sub-superscripts t
)
6615 org-match-substring-regexp
6616 org-match-substring-with-braces-regexp
)
6618 (let* ((pos (point)) table-p comment-p
6619 (mpos (match-beginning 3))
6620 (emph-p (get-text-property mpos
'org-emphasis
))
6621 (link-p (get-text-property mpos
'mouse-face
))
6622 (keyw-p (eq 'org-special-keyword
(get-text-property mpos
'face
))))
6623 (goto-char (point-at-bol))
6624 (setq table-p
(looking-at-p org-table-dataline-regexp
)
6625 comment-p
(looking-at-p "^[ \t]*#[ +]"))
6628 (when (member (char-after) '(?_ ?^
)) (goto-char (1- pos
)))
6629 (unless (or comment-p emph-p link-p keyw-p
)
6630 (put-text-property (match-beginning 3) (match-end 0)
6632 (if (equal (char-after (match-beginning 2)) ?^
)
6633 (nth (if table-p
3 1) org-script-display
)
6634 (nth (if table-p
2 0) org-script-display
)))
6635 (add-text-properties (match-beginning 2) (match-end 2)
6636 (list 'invisible t
))
6637 (when (and (eq (char-after (match-beginning 3)) ?
{)
6638 (eq (char-before (match-end 3)) ?
}))
6639 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6640 (list 'invisible t
))
6641 (add-text-properties (1- (match-end 3)) (match-end 3)
6642 (list 'invisible t
))))
6645 ;;;; Visibility cycling, including org-goto and indirect buffer
6649 (defvar-local org-cycle-global-status nil
)
6650 (put 'org-cycle-global-status
'org-state t
)
6651 (defvar-local org-cycle-subtree-status nil
)
6652 (put 'org-cycle-subtree-status
'org-state t
)
6654 (defvar org-inlinetask-min-level
)
6656 (defun org-unlogged-message (&rest args
)
6657 "Display a message, but avoid logging it in the *Messages* buffer."
6658 (let ((message-log-max nil
))
6659 (apply 'message args
)))
6662 (defun org-cycle (&optional arg
)
6663 "TAB-action and visibility cycling for Org mode.
6665 This is the command invoked in Org mode by the `TAB' key. Its main
6666 purpose is outline visibility cycling, but it also invokes other actions
6667 in special contexts.
6669 When this function is called with a `\\[universal-argument]' prefix, rotate \
6671 buffer through 3 states (global cycling)
6672 1. OVERVIEW: Show only top-level headlines.
6673 2. CONTENTS: Show all headlines of all levels, but no body text.
6674 3. SHOW ALL: Show everything.
6676 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6677 switch to the startup visibility,
6678 determined by the variable `org-startup-folded', and by any VISIBILITY
6679 properties in the buffer.
6681 With a `\\[universal-argument] \\[universal-argument] \
6682 \\[universal-argument]' prefix argument, show the entire buffer, including
6685 When inside a table, re-align the table and move to the next field.
6687 When point is at the beginning of a headline, rotate the subtree started
6688 by this line through 3 different states (local cycling)
6689 1. FOLDED: Only the main headline is shown.
6690 2. CHILDREN: The main headline and the direct children are shown.
6691 From this state, you can move to one of the children
6692 and zoom in further.
6693 3. SUBTREE: Show the entire subtree, including body text.
6694 If there is no subtree, switch directly from CHILDREN to FOLDED.
6696 When point is at the beginning of an empty headline and the variable
6697 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6698 of the headline by demoting and promoting it to likely levels. This
6699 speeds up creation document structure by pressing `TAB' once or several
6700 times right after creating a new headline.
6702 When there is a numeric prefix, go up to a heading with level ARG, do
6703 a `show-subtree' and return to the previous cursor position. If ARG
6704 is negative, go up that many levels.
6706 When point is not at the beginning of a headline, execute the global
6707 binding for `TAB', which is re-indenting the line. See the option
6708 `org-cycle-emulate-tab' for details.
6710 As a special case, if point is at the beginning of the buffer and there is
6711 no headline in line 1, this function will act as if called with prefix arg
6712 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6713 prefix arg, but only
6714 if the variable `org-cycle-global-at-bob' is t."
6716 (org-load-modules-maybe)
6717 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook
)
6718 (and org-cycle-level-after-item
/entry-creation
6719 (or (org-cycle-level)
6720 (org-cycle-item-indentation))))
6722 (or org-cycle-max-level
6723 (and (boundp 'org-inlinetask-min-level
)
6724 org-inlinetask-min-level
6725 (1- org-inlinetask-min-level
))))
6726 (nstars (and limit-level
6727 (if org-odd-levels-only
6728 (and limit-level
(1- (* limit-level
2)))
6731 (if (not (derived-mode-p 'org-mode
))
6733 (concat "\\*" (if nstars
(format "\\{1,%d\\} " nstars
) "+ "))))
6734 (bob-special (and org-cycle-global-at-bob
(not arg
) (bobp)
6735 (not (looking-at org-outline-regexp
))))
6738 (delq 'org-optimize-window-after-visibility-change
6739 (copy-sequence org-cycle-hook
))
6746 (setq last-command
'dummy
)
6747 (org-set-startup-visibility)
6748 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6752 (org-unlogged-message "Entire buffer visible, including drawers"))
6754 ((equal arg
'(4)) (org-cycle-internal-global))
6756 ;; Try hiding block at point.
6757 ((org-hide-block-toggle-maybe))
6759 ;; Try cdlatex TAB completion
6760 ((org-try-cdlatex-tab))
6762 ;; Table: enter it or move to the next field.
6763 ((org-at-table-p 'any
)
6764 (if (org-at-table.el-p
)
6765 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6766 Use `\\[org-edit-special]' to edit table.el tables"))
6767 (if arg
(org-table-edit-field t
)
6768 (org-table-justify-field-maybe)
6769 (call-interactively 'org-table-next-field
))))
6771 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook
))
6773 ;; Global cycling: delegate to `org-cycle-internal-global'.
6774 (bob-special (org-cycle-internal-global))
6776 ;; Drawers: delegate to `org-flag-drawer'.
6778 (beginning-of-line 1)
6779 (looking-at org-drawer-regexp
))
6780 (org-flag-drawer ; toggle block visibility
6781 (not (get-char-property (match-end 0) 'invisible
))))
6783 ;; Show-subtree, ARG levels up from here.
6786 (org-back-to-heading)
6787 (outline-up-heading (if (< arg
0) (- arg
)
6788 (- (funcall outline-level
) arg
)))
6789 (org-show-subtree)))
6791 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6792 ((and (featurep 'org-inlinetask
)
6793 (org-inlinetask-at-task-p)
6794 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6795 (org-inlinetask-toggle-visibility))
6797 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6798 ((and (or (and org-cycle-include-plain-lists
(org-at-item-p))
6799 (save-excursion (move-beginning-of-line 1)
6800 (looking-at org-outline-regexp
)))
6801 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6802 (org-cycle-internal-local))
6804 ;; From there: TAB emulation and template completion.
6805 (buffer-read-only (org-back-to-heading))
6807 ((run-hook-with-args-until-success
6808 'org-tab-after-check-for-cycling-hook
))
6810 ((org-try-structure-completion))
6812 ((run-hook-with-args-until-success
6813 'org-tab-before-tab-emulation-hook
))
6815 ((and (eq org-cycle-emulate-tab
'exc-hl-bol
)
6817 (not (looking-at org-outline-regexp
))))
6818 (call-interactively (global-key-binding "\t")))
6820 ((if (and (memq org-cycle-emulate-tab
'(white whitestart
))
6821 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6822 (or (and (eq org-cycle-emulate-tab
'white
)
6823 (= (match-end 0) (point-at-eol)))
6824 (and (eq org-cycle-emulate-tab
'whitestart
)
6825 (>= (match-end 0) pos
))))
6827 (eq org-cycle-emulate-tab t
))
6828 (call-interactively (global-key-binding "\t")))
6831 (org-back-to-heading)
6834 (defun org-cycle-internal-global ()
6835 "Do the global cycling action."
6836 ;; Hack to avoid display of messages for .org attachments in Gnus
6837 (let ((ga (string-match "\\*fontification" (buffer-name))))
6839 ((and (eq last-command this-command
)
6840 (eq org-cycle-global-status
'overview
))
6841 ;; We just created the overview - now do table of contents
6842 ;; This can be slow in very large buffers, so indicate action
6843 (run-hook-with-args 'org-pre-cycle-hook
'contents
)
6844 (unless ga
(org-unlogged-message "CONTENTS..."))
6846 (unless ga
(org-unlogged-message "CONTENTS...done"))
6847 (setq org-cycle-global-status
'contents
)
6848 (run-hook-with-args 'org-cycle-hook
'contents
))
6850 ((and (eq last-command this-command
)
6851 (eq org-cycle-global-status
'contents
))
6852 ;; We just showed the table of contents - now show everything
6853 (run-hook-with-args 'org-pre-cycle-hook
'all
)
6855 (unless ga
(org-unlogged-message "SHOW ALL"))
6856 (setq org-cycle-global-status
'all
)
6857 (run-hook-with-args 'org-cycle-hook
'all
))
6860 ;; Default action: go to overview
6861 (run-hook-with-args 'org-pre-cycle-hook
'overview
)
6863 (unless ga
(org-unlogged-message "OVERVIEW"))
6864 (setq org-cycle-global-status
'overview
)
6865 (run-hook-with-args 'org-cycle-hook
'overview
)))))
6867 (defvar org-called-with-limited-levels nil
6868 "Non-nil when `org-with-limited-levels' is currently active.")
6870 (defun org-invisible-p (&optional pos
)
6871 "Non-nil if the character after POS is invisible.
6872 If POS is nil, use `point' instead."
6873 (get-char-property (or pos
(point)) 'invisible
))
6875 (defun org-cycle-internal-local ()
6876 "Do the local cycling action."
6877 (let ((goal-column 0) eoh eol eos has-children children-skipped struct
)
6878 ;; First, determine end of headline (EOH), end of subtree or item
6879 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6884 (setq struct
(org-list-struct))
6885 (setq eoh
(point-at-eol))
6886 (setq eos
(org-list-get-item-end-before-blank (point) struct
))
6887 (setq has-children
(org-list-has-child-p (point) struct
)))
6888 (org-back-to-heading)
6889 (setq eoh
(save-excursion (outline-end-of-heading) (point)))
6890 (setq eos
(save-excursion (org-end-of-subtree t t
)
6891 (when (bolp) (backward-char)) (point)))
6894 (let ((level (funcall outline-level
)))
6895 (outline-next-heading)
6896 (and (org-at-heading-p t
)
6897 (> (funcall outline-level
) level
))))
6899 (org-list-search-forward (org-item-beginning-re) eos t
)))))
6900 ;; Determine end invisible part of buffer (EOL)
6901 (beginning-of-line 2)
6902 (while (and (not (eobp)) ;This is like `next-line'.
6903 (get-char-property (1- (point)) 'invisible
))
6904 (goto-char (next-single-char-property-change (point) 'invisible
))
6905 (and (eolp) (beginning-of-line 2)))
6907 ;; Find out what to do next and set `this-command'
6910 ;; Nothing is hidden behind this heading
6911 (unless (org-before-first-heading-p)
6912 (run-hook-with-args 'org-pre-cycle-hook
'empty
))
6913 (org-unlogged-message "EMPTY ENTRY")
6914 (setq org-cycle-subtree-status nil
)
6917 (outline-next-heading)
6918 (when (org-invisible-p) (org-flag-heading nil
))))
6919 ((and (or (>= eol eos
)
6920 (not (string-match "\\S-" (buffer-substring eol eos
))))
6922 (not (setq children-skipped
6923 org-cycle-skip-children-state-if-no-children
))))
6924 ;; Entire subtree is hidden in one line: children view
6925 (unless (org-before-first-heading-p)
6926 (run-hook-with-args 'org-pre-cycle-hook
'children
))
6928 (org-list-set-item-visibility (point-at-bol) struct
'children
)
6930 (org-with-limited-levels (org-show-children))
6931 (org-show-set-visibility 'canonical
)
6932 ;; FIXME: This slows down the func way too much.
6933 ;; How keep drawers hidden in subtree anyway?
6934 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6935 ;; (org-cycle-hide-drawers 'subtree))
6937 ;; Fold every list in subtree to top-level items.
6938 (when (eq org-cycle-include-plain-lists
'integrate
)
6940 (org-back-to-heading)
6941 (while (org-list-search-forward (org-item-beginning-re) eos t
)
6942 (beginning-of-line 1)
6943 (let* ((struct (org-list-struct))
6944 (prevs (org-list-prevs-alist struct
))
6945 (end (org-list-get-bottom-point struct
)))
6946 (dolist (e (org-list-get-all-items (point) struct prevs
))
6947 (org-list-set-item-visibility e struct
'folded
))
6948 (goto-char (if (< end eos
) end eos
)))))))
6949 (org-unlogged-message "CHILDREN")
6952 (outline-next-heading)
6953 (when (org-invisible-p) (org-flag-heading nil
)))
6954 (setq org-cycle-subtree-status
'children
)
6955 (unless (org-before-first-heading-p)
6956 (run-hook-with-args 'org-cycle-hook
'children
)))
6957 ((or children-skipped
6958 (and (eq last-command this-command
)
6959 (eq org-cycle-subtree-status
'children
)))
6960 ;; We just showed the children, or no children are there,
6961 ;; now show everything.
6962 (unless (org-before-first-heading-p)
6963 (run-hook-with-args 'org-pre-cycle-hook
'subtree
))
6964 (outline-flag-region eoh eos nil
)
6965 (org-unlogged-message
6966 (if children-skipped
"SUBTREE (NO CHILDREN)" "SUBTREE"))
6967 (setq org-cycle-subtree-status
'subtree
)
6968 (unless (org-before-first-heading-p)
6969 (run-hook-with-args 'org-cycle-hook
'subtree
)))
6971 ;; Default action: hide the subtree.
6972 (run-hook-with-args 'org-pre-cycle-hook
'folded
)
6973 (outline-flag-region eoh eos t
)
6974 (org-unlogged-message "FOLDED")
6975 (setq org-cycle-subtree-status
'folded
)
6976 (unless (org-before-first-heading-p)
6977 (run-hook-with-args 'org-cycle-hook
'folded
))))))
6980 (defun org-global-cycle (&optional arg
)
6981 "Cycle the global visibility. For details see `org-cycle'.
6982 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6983 With a numeric prefix, show all headlines up to that level."
6985 (let ((org-cycle-include-plain-lists
6986 (if (derived-mode-p 'org-mode
) org-cycle-include-plain-lists nil
)))
6990 (outline-hide-sublevels arg
)
6991 (setq org-cycle-global-status
'contents
))
6993 (org-set-startup-visibility)
6994 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6996 (org-cycle '(4))))))
6998 (defun org-set-startup-visibility ()
6999 "Set the visibility required by startup options and properties."
7001 ((eq org-startup-folded t
)
7003 ((eq org-startup-folded
'content
)
7005 ((or (eq org-startup-folded
'showeverything
)
7006 (eq org-startup-folded nil
))
7007 (outline-show-all)))
7008 (unless (eq org-startup-folded
'showeverything
)
7009 (when org-hide-block-startup
(org-hide-block-all))
7010 (org-set-visibility-according-to-property 'no-cleanup
)
7011 (org-cycle-hide-archived-subtrees 'all
)
7012 (org-cycle-hide-drawers 'all
)
7013 (org-cycle-show-empty-lines t
)))
7015 (defun org-set-visibility-according-to-property (&optional no-cleanup
)
7016 "Switch subtree visibilities according to :VISIBILITY: property."
7018 (org-with-wide-buffer
7019 (goto-char (point-min))
7020 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t
)
7021 (if (not (org-at-property-p)) (outline-next-heading)
7022 (let ((state (match-string 3)))
7024 (org-back-to-heading t
)
7025 (outline-hide-subtree)
7028 ((equal state
"folded")
7029 (outline-hide-subtree))
7030 ((equal state
"children")
7031 (org-show-hidden-entry)
7032 (org-show-children))
7033 ((equal state
"content")
7036 (org-narrow-to-subtree)
7038 ((member state
'("all" "showall"))
7039 (outline-show-subtree)))))))
7041 (org-cycle-hide-archived-subtrees 'all
)
7042 (org-cycle-hide-drawers 'all
)
7043 (org-cycle-show-empty-lines 'all
))))
7045 ;; This function uses outline-regexp instead of the more fundamental
7046 ;; org-outline-regexp so that org-cycle-global works outside of Org
7047 ;; buffers, where outline-regexp is needed.
7048 (defun org-overview ()
7049 "Switch to overview mode, showing only top-level headlines.
7050 This shows all headlines with a level equal or greater than the level
7051 of the first headline in the buffer. This is important, because if the
7052 first headline is not level one, then (hide-sublevels 1) gives confusing
7058 (goto-char (point-min))
7059 (when (re-search-forward (concat "^" outline-regexp
) nil t
)
7060 (goto-char (match-beginning 0))
7061 (funcall outline-level
)))))
7062 (and level
(outline-hide-sublevels level
)))))
7064 (defun org-content (&optional arg
)
7065 "Show all headlines in the buffer, like a table of contents.
7066 With numerical argument N, show content up to level N."
7070 ;; Visit all headings and show their offspring
7071 (and (integerp arg
) (org-overview))
7072 (goto-char (point-max))
7074 (while (and (progn (condition-case nil
7075 (outline-previous-visible-heading 1)
7076 (error (goto-char (point-min))))
7078 (looking-at org-outline-regexp
))
7080 (org-show-children (1- arg
))
7081 (outline-show-branches))
7082 (when (bobp) (throw 'exit nil
))))))
7084 (defun org-optimize-window-after-visibility-change (state)
7085 "Adjust the window after a change in outline visibility.
7086 This function is the default value of the hook `org-cycle-hook'."
7087 (when (get-buffer-window (current-buffer))
7089 ((eq state
'content
) nil
)
7090 ((eq state
'all
) nil
)
7091 ((eq state
'folded
) nil
)
7092 ((eq state
'children
) (or (org-subtree-end-visible-p) (recenter 1)))
7093 ((eq state
'subtree
) (or (org-subtree-end-visible-p) (recenter 1))))))
7095 (defun org-remove-empty-overlays-at (pos)
7096 "Remove outline overlays that do not contain non-white stuff."
7097 (dolist (o (overlays-at pos
))
7098 (and (eq 'outline
(overlay-get o
'invisible
))
7099 (not (string-match "\\S-" (buffer-substring (overlay-start o
)
7101 (delete-overlay o
))))
7103 (defun org-clean-visibility-after-subtree-move ()
7104 "Fix visibility issues after moving a subtree."
7105 ;; First, find a reasonable region to look at:
7106 ;; Start two siblings above, end three below
7107 (let* ((beg (save-excursion
7108 (and (org-get-last-sibling)
7109 (org-get-last-sibling))
7111 (end (save-excursion
7112 (and (org-get-next-sibling)
7113 (org-get-next-sibling)
7114 (org-get-next-sibling))
7115 (if (org-at-heading-p)
7118 (level (looking-at "\\*+"))
7119 (re (when level
(concat "^" (regexp-quote (match-string 0)) " "))))
7122 (narrow-to-region beg end
)
7124 ;; Properly fold already folded siblings
7125 (goto-char (point-min))
7126 (while (re-search-forward re nil t
)
7127 (when (and (not (org-invisible-p))
7129 (goto-char (point-at-eol)) (org-invisible-p)))
7130 (outline-hide-entry))))
7131 (org-cycle-show-empty-lines 'overview
)
7132 (org-cycle-hide-drawers 'overview
)))))
7134 (defun org-cycle-show-empty-lines (state)
7135 "Show empty lines above all visible headlines.
7136 The region to be covered depends on STATE when called through
7137 `org-cycle-hook'. Lisp program can use t for STATE to get the
7138 entire buffer covered. Note that an empty line is only shown if there
7139 are at least `org-cycle-separator-lines' empty lines before the headline."
7140 (when (/= org-cycle-separator-lines
0)
7142 (let* ((n (abs org-cycle-separator-lines
))
7144 ((= n
1) "\\(\n[ \t]*\n\\*+\\) ")
7145 ((= n
2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7146 (t (let ((ns (number-to-string (- n
2))))
7147 (concat "^\\(?:[ \t]*\n\\)\\{" ns
"," ns
"\\}"
7148 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7151 ((memq state
'(overview contents t
))
7152 (setq beg
(point-min) end
(point-max)))
7153 ((memq state
'(children folded
))
7155 end
(progn (org-end-of-subtree t t
)
7156 (line-beginning-position 2)))))
7159 (while (re-search-forward re end t
)
7160 (unless (get-char-property (match-end 1) 'invisible
)
7161 (let ((e (match-end 1))
7162 (b (if (>= org-cycle-separator-lines
0)
7165 (goto-char (match-beginning 0))
7166 (skip-chars-backward " \t\n")
7167 (line-end-position)))))
7168 (outline-flag-region b e nil
))))))))
7169 ;; Never hide empty lines at the end of the file.
7171 (goto-char (point-max))
7172 (outline-previous-heading)
7173 (outline-end-of-heading)
7174 (when (and (looking-at "[ \t\n]+")
7175 (= (match-end 0) (point-max)))
7176 (outline-flag-region (point) (match-end 0) nil
))))
7178 (defun org-show-empty-lines-in-parent ()
7179 "Move to the parent and re-show empty lines before visible headlines."
7181 (let ((context (if (org-up-heading-safe) 'children
'overview
)))
7182 (org-cycle-show-empty-lines context
))))
7184 (defun org-files-list ()
7185 "Return `org-agenda-files' list, plus all open Org files.
7186 This is useful for operations that need to scan all of a user's
7187 open and agenda-wise Org files."
7188 (let ((files (mapcar #'expand-file-name
(org-agenda-files))))
7189 (dolist (buf (buffer-list))
7190 (with-current-buffer buf
7191 (when (and (derived-mode-p 'org-mode
) (buffer-file-name))
7192 (cl-pushnew (expand-file-name (buffer-file-name)) files
7196 (defsubst org-entry-beginning-position
()
7197 "Return the beginning position of the current entry."
7198 (save-excursion (org-back-to-heading t
) (point)))
7200 (defsubst org-entry-end-position
()
7201 "Return the end position of the current entry."
7202 (save-excursion (outline-next-heading) (point)))
7204 (defun org-cycle-hide-drawers (state &optional exceptions
)
7205 "Re-hide all drawers after a visibility state change.
7206 STATE should be one of the symbols listed in the docstring of
7207 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7208 a list of strings specifying which drawers should not be hidden."
7209 (when (and (derived-mode-p 'org-mode
)
7210 (not (memq state
'(overview folded contents
))))
7212 (let* ((globalp (eq state
'all
))
7213 (beg (if globalp
(point-min) (point)))
7214 (end (if globalp
(point-max)
7215 (if (eq state
'children
)
7216 (save-excursion (outline-next-heading) (point))
7217 (org-end-of-subtree t
)))))
7219 (while (re-search-forward org-drawer-regexp
(max end
(point)) t
)
7220 (unless (member-ignore-case (match-string 1) exceptions
)
7221 (let ((drawer (org-element-at-point)))
7222 (when (memq (org-element-type drawer
) '(drawer property-drawer
))
7223 (org-flag-drawer t drawer
)
7224 ;; Make sure to skip drawer entirely or we might flag
7225 ;; it another time when matching its ending line with
7226 ;; `org-drawer-regexp'.
7227 (goto-char (org-element-property :end drawer
))))))))))
7229 (defun org-flag-drawer (flag &optional element
)
7230 "When FLAG is non-nil, hide the drawer we are at.
7231 Otherwise make it visible. When optional argument ELEMENT is
7232 a parsed drawer, as returned by `org-element-at-point', hide or
7233 show that drawer instead."
7234 (let ((drawer (or element
7235 (and (save-excursion
7237 (looking-at-p org-drawer-regexp
))
7238 (org-element-at-point)))))
7239 (when (memq (org-element-type drawer
) '(drawer property-drawer
))
7240 (let ((post (org-element-property :post-affiliated drawer
)))
7242 (outline-flag-region
7243 (progn (goto-char post
) (line-end-position))
7244 (progn (goto-char (org-element-property :end drawer
))
7245 (skip-chars-backward " \r\t\n")
7246 (line-end-position))
7248 ;; When the drawer is hidden away, make sure point lies in
7249 ;; a visible part of the buffer.
7250 (when (and flag
(> (line-beginning-position) post
))
7251 (goto-char post
))))))
7253 (defun org-subtree-end-visible-p ()
7254 "Is the end of the current subtree visible?"
7255 (pos-visible-in-window-p
7256 (save-excursion (org-end-of-subtree t
) (point))))
7258 (defun org-first-headline-recenter ()
7259 "Move cursor to the first headline and recenter the headline."
7260 (let ((window (get-buffer-window)))
7262 (goto-char (point-min))
7263 (when (re-search-forward (concat "^\\(" org-outline-regexp
"\\)") nil t
)
7264 (set-window-start window
(line-beginning-position))))))
7266 ;;; Saving and restoring visibility
7268 (defun org-outline-overlay-data (&optional use-markers
)
7269 "Return a list of the locations of all outline overlays.
7270 These are overlays with the `invisible' property value `outline'.
7271 The return value is a list of cons cells, with start and stop
7272 positions for each overlay.
7273 If USE-MARKERS is set, return the positions as markers."
7275 (org-with-wide-buffer
7278 (when (eq (overlay-get o
'invisible
) 'outline
)
7279 (setq beg
(overlay-start o
)
7280 end
(overlay-end o
))
7281 (and beg end
(> end beg
)
7283 (cons (copy-marker beg
)
7284 (copy-marker end t
))
7286 (overlays-in (point-min) (point-max)))))))
7288 (defun org-set-outline-overlay-data (data)
7289 "Create visibility overlays for all positions in DATA.
7290 DATA should have been made by `org-outline-overlay-data'."
7291 (org-with-wide-buffer
7293 (dolist (c data
) (outline-flag-region (car c
) (cdr c
) t
))))
7295 ;;; Folding of blocks
7297 (defvar-local org-hide-block-overlays nil
7298 "Overlays hiding blocks.")
7300 (defun org-block-map (function &optional start end
)
7301 "Call FUNCTION at the head of all source blocks in the current buffer.
7302 Optional arguments START and END can be used to limit the range."
7303 (let ((start (or start
(point-min)))
7304 (end (or end
(point-max))))
7307 (while (and (< (point) end
) (re-search-forward org-block-regexp end t
))
7310 (goto-char (match-beginning 0))
7311 (funcall function
)))))))
7313 (defun org-hide-block-toggle-all ()
7314 "Toggle the visibility of all blocks in the current buffer."
7315 (org-block-map 'org-hide-block-toggle
))
7317 (defun org-hide-block-all ()
7318 "Fold all blocks in the current buffer."
7320 (org-show-block-all)
7321 (org-block-map 'org-hide-block-toggle-maybe
))
7323 (defun org-show-block-all ()
7324 "Unfold all blocks in the current buffer."
7326 (mapc #'delete-overlay org-hide-block-overlays
)
7327 (setq org-hide-block-overlays nil
))
7329 (defun org-hide-block-toggle-maybe ()
7330 "Toggle visibility of block at point.
7331 Unlike to `org-hide-block-toggle', this function does not throw
7332 an error. Return a non-nil value when toggling is successful."
7334 (ignore-errors (org-hide-block-toggle)))
7336 (defun org-hide-block-toggle (&optional force
)
7337 "Toggle the visibility of the current block.
7338 When optional argument FORCE is `off', make block visible. If it
7339 is non-nil, hide it unconditionally. Throw an error when not at
7340 a block. Return a non-nil value when toggling is successful."
7342 (let ((element (org-element-at-point)))
7343 (unless (memq (org-element-type element
)
7344 '(center-block comment-block dynamic-block example-block
7345 export-block quote-block special-block
7346 src-block verse-block
))
7347 (user-error "Not at a block"))
7348 (let* ((start (save-excursion
7349 (goto-char (org-element-property :post-affiliated element
))
7350 (line-end-position)))
7351 (end (save-excursion
7352 (goto-char (org-element-property :end element
))
7353 (skip-chars-backward " \r\t\n")
7354 (line-end-position)))
7355 (overlays (overlays-at start
)))
7357 ;; Do nothing when not before or at the block opening line or
7358 ;; at the block closing line.
7359 ((let ((eol (line-end-position))) (and (> eol start
) (/= eol end
))) nil
)
7360 ((and (not (eq force
'off
))
7361 (not (memq t
(mapcar
7363 (eq (overlay-get o
'invisible
) 'org-hide-block
))
7365 (let ((ov (make-overlay start end
)))
7366 (overlay-put ov
'invisible
'org-hide-block
)
7367 ;; Make the block accessible to `isearch'.
7369 ov
'isearch-open-invisible
7371 (when (memq ov org-hide-block-overlays
)
7372 (setq org-hide-block-overlays
(delq ov org-hide-block-overlays
)))
7373 (when (eq (overlay-get ov
'invisible
) 'org-hide-block
)
7374 (delete-overlay ov
))))
7375 (push ov org-hide-block-overlays
)
7376 ;; When the block is hidden away, make sure point is left in
7377 ;; a visible part of the buffer.
7378 (when (> (line-beginning-position) start
)
7380 (beginning-of-line))
7381 ;; Signal successful toggling.
7383 ((or (not force
) (eq force
'off
))
7384 (dolist (ov overlays t
)
7385 (when (memq ov org-hide-block-overlays
)
7386 (setq org-hide-block-overlays
(delq ov org-hide-block-overlays
)))
7387 (when (eq (overlay-get ov
'invisible
) 'org-hide-block
)
7388 (delete-overlay ov
))))))))
7390 ;; Remove overlays when changing major mode
7391 (add-hook 'org-mode-hook
7392 (lambda () (add-hook 'change-major-mode-hook
7393 'org-show-block-all
'append
'local
)))
7397 (defvar org-goto-window-configuration nil
)
7398 (defvar org-goto-marker nil
)
7399 (defvar org-goto-map
)
7400 (defun org-goto-map ()
7401 "Set the keymap `org-goto'."
7403 (let ((map (make-sparse-keymap)))
7404 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7405 mouse-drag-region universal-argument org-occur
)))
7407 (substitute-key-definition cmd cmd map global-map
)))
7408 (suppress-keymap map
)
7409 (org-defkey map
"\C-m" 'org-goto-ret
)
7410 (org-defkey map
[(return)] 'org-goto-ret
)
7411 (org-defkey map
[(left)] 'org-goto-left
)
7412 (org-defkey map
[(right)] 'org-goto-right
)
7413 (org-defkey map
[(control ?g
)] 'org-goto-quit
)
7414 (org-defkey map
"\C-i" 'org-cycle
)
7415 (org-defkey map
[(tab)] 'org-cycle
)
7416 (org-defkey map
[(down)] 'outline-next-visible-heading
)
7417 (org-defkey map
[(up)] 'outline-previous-visible-heading
)
7418 (if org-goto-auto-isearch
7419 (if (fboundp 'define-key-after
)
7420 (define-key-after map
[t] 'org-goto-local-auto-isearch)
7422 (org-defkey map "q" 'org-goto-quit)
7423 (org-defkey map "n" 'outline-next-visible-heading)
7424 (org-defkey map "p" 'outline-previous-visible-heading)
7425 (org-defkey map "f" 'outline-forward-same-level)
7426 (org-defkey map "b" 'outline-backward-same-level)
7427 (org-defkey map "u" 'outline-up-heading))
7428 (org-defkey map "/" 'org-occur)
7429 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7430 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7431 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7432 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7433 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7436 (defconst org-goto-help
7437 "Browse buffer copy, to find location or copy text.%s
7438 RET=jump to location C-g=quit and return to previous location
7439 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7441 (defvar org-goto-start-pos) ; dynamically scoped parameter
7443 (defun org-goto (&optional alternative-interface)
7444 "Look up a different location in the current file, keeping current visibility.
7446 When you want look-up or go to a different location in a
7447 document, the fastest way is often to fold the entire buffer and
7448 then dive into the tree. This method has the disadvantage, that
7449 the previous location will be folded, which may not be what you
7452 This command works around this by showing a copy of the current
7453 buffer in an indirect buffer, in overview mode. You can dive
7454 into the tree in that copy, use org-occur and incremental search
7455 to find a location. When pressing RET or `Q', the command
7456 returns to the original buffer in which the visibility is still
7457 unchanged. After RET it will also jump to the location selected
7458 in the indirect buffer and expose the headline hierarchy above.
7460 With a prefix argument, use the alternative interface: e.g., if
7461 `org-goto-interface' is `outline' use `outline-path-completion'."
7464 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7465 (org-refile-use-outline-path t)
7466 (org-refile-target-verify-function nil)
7468 (if (not alternative-interface)
7470 (if (eq org-goto-interface 'outline)
7471 'outline-path-completion
7473 (org-goto-start-pos (point))
7475 (if (eq interface 'outline)
7476 (car (org-get-location (current-buffer) org-goto-help))
7477 (let ((pa (org-refile-get-location "Goto")))
7478 (org-refile-check-position pa)
7482 (org-mark-ring-push org-goto-start-pos)
7483 (goto-char selected-point)
7484 (when (or (org-invisible-p) (org-invisible-p2))
7485 (org-show-context 'org-goto)))
7488 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7489 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7490 (defvar org-goto-local-auto-isearch-map) ; defined below
7492 (defun org-get-location (_buf help)
7493 "Let the user select a location in current buffer.
7494 This function uses a recursive edit. It returns the selected position
7497 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7498 (isearch-hide-immediately nil)
7499 (isearch-search-fun-function
7500 (lambda () 'org-goto-local-search-headings))
7501 (org-goto-selected-point org-goto-exit-command))
7503 (save-window-excursion
7504 (delete-other-windows)
7505 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7506 (pop-to-buffer-same-window
7508 (make-indirect-buffer (current-buffer) "*org-goto*")
7509 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7510 (with-output-to-temp-buffer "*Org Help*"
7511 (princ (format help (if org-goto-auto-isearch
7512 " Just type for auto-isearch."
7513 " n/p/f/b/u to navigate, q to quit."))))
7514 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7515 (setq buffer-read-only nil)
7516 (let ((org-startup-truncated t)
7517 (org-startup-folded nil)
7518 (org-startup-align-all-tables nil))
7521 (setq buffer-read-only t)
7522 (if (and (boundp 'org-goto-start-pos)
7523 (integer-or-marker-p org-goto-start-pos))
7524 (progn (goto-char org-goto-start-pos)
7525 (when (org-invisible-p)
7526 (org-show-set-visibility 'lineage)))
7527 (goto-char (point-min)))
7528 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7529 (message "Select location and press RET")
7530 (use-local-map org-goto-map)
7532 (kill-buffer "*org-goto*")
7533 (cons org-goto-selected-point org-goto-exit-command))))
7535 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7536 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7537 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7538 (if (fboundp 'isearch-other-control-char)
7540 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7541 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7542 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7543 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7544 (define-key org-goto-local-auto-isearch-map [return] nil))
7546 (defun org-goto-local-search-headings (string bound noerror)
7547 "Search and make sure that any matches are in headlines."
7549 (while (if isearch-forward
7550 (search-forward string bound noerror)
7551 (search-backward string bound noerror))
7552 (when (save-match-data
7553 (and (save-excursion
7555 (looking-at org-complex-heading-regexp))
7556 (or (not (match-beginning 5))
7557 (< (point) (match-beginning 5)))))
7558 (throw 'return (point))))))
7560 (defun org-goto-local-auto-isearch ()
7563 (goto-char (point-min))
7564 (let ((keys (this-command-keys)))
7565 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7567 (isearch-process-search-char (string-to-char keys)))))
7569 (defun org-goto-ret (&optional _arg)
7570 "Finish `org-goto' by going to the new location."
7572 (setq org-goto-selected-point (point))
7573 (setq org-goto-exit-command 'return)
7576 (defun org-goto-left ()
7577 "Finish `org-goto' by going to the new location."
7579 (if (org-at-heading-p)
7581 (beginning-of-line 1)
7582 (setq org-goto-selected-point (point)
7583 org-goto-exit-command 'left)
7585 (user-error "Not on a heading")))
7587 (defun org-goto-right ()
7588 "Finish `org-goto' by going to the new location."
7590 (if (org-at-heading-p)
7592 (setq org-goto-selected-point (point)
7593 org-goto-exit-command 'right)
7595 (user-error "Not on a heading")))
7597 (defun org-goto-quit ()
7598 "Finish `org-goto' without cursor motion."
7600 (setq org-goto-selected-point nil)
7601 (setq org-goto-exit-command 'quit)
7604 ;;; Indirect buffer display of subtrees
7606 (defvar org-indirect-dedicated-frame nil
7607 "This is the frame being used for indirect tree display.")
7608 (defvar org-last-indirect-buffer nil)
7610 (defun org-tree-to-indirect-buffer (&optional arg)
7611 "Create indirect buffer and narrow it to current subtree.
7613 With a numerical prefix ARG, go up to this level and then take that tree.
7614 If ARG is negative, go up that many levels.
7616 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7617 indirect buffer previously made with this command, to avoid proliferation of
7618 indirect buffers. However, when you call the command with a \
7619 `\\[universal-argument]' prefix, or
7620 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7621 so that you can work with several indirect buffers at the same time. If
7622 `org-indirect-buffer-display' is `dedicated-frame', the \
7623 `\\[universal-argument]' prefix also
7624 requests that a new frame be made for the new buffer, so that the dedicated
7625 frame is not changed."
7627 (let ((cbuf (current-buffer))
7628 (cwin (selected-window))
7630 beg end level heading ibuf)
7632 (org-back-to-heading t)
7634 (setq level (org-outline-level))
7635 (when (< arg 0) (setq arg (+ level arg)))
7636 (while (> (setq level (org-outline-level)) arg)
7637 (org-up-heading-safe)))
7639 heading (org-get-heading 'no-tags))
7640 (org-end-of-subtree t t)
7641 (when (org-at-heading-p) (backward-char 1))
7643 (when (and (buffer-live-p org-last-indirect-buffer)
7644 (not (eq org-indirect-buffer-display 'new-frame))
7646 (kill-buffer org-last-indirect-buffer))
7647 (setq ibuf (org-get-indirect-buffer cbuf heading)
7648 org-last-indirect-buffer ibuf)
7650 ((or (eq org-indirect-buffer-display 'new-frame)
7651 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7652 (select-frame (make-frame))
7653 (delete-other-windows)
7654 (pop-to-buffer-same-window ibuf)
7655 (org-set-frame-title heading))
7656 ((eq org-indirect-buffer-display 'dedicated-frame)
7658 (select-frame (or (and org-indirect-dedicated-frame
7659 (frame-live-p org-indirect-dedicated-frame)
7660 org-indirect-dedicated-frame)
7661 (setq org-indirect-dedicated-frame (make-frame)))))
7662 (delete-other-windows)
7663 (pop-to-buffer-same-window ibuf)
7664 (org-set-frame-title (concat "Indirect: " heading)))
7665 ((eq org-indirect-buffer-display 'current-window)
7666 (pop-to-buffer-same-window ibuf))
7667 ((eq org-indirect-buffer-display 'other-window)
7668 (pop-to-buffer ibuf))
7669 (t (error "Invalid value")))
7670 (narrow-to-region beg end)
7673 (run-hook-with-args 'org-cycle-hook 'all)
7674 (and (window-live-p cwin) (select-window cwin))))
7676 (defun org-get-indirect-buffer (&optional buffer heading)
7677 (setq buffer (or buffer (current-buffer)))
7678 (let ((n 1) (base (buffer-name buffer)) bname)
7679 (while (buffer-live-p
7683 (if heading (concat heading "-" (number-to-string n))
7684 (number-to-string n))))))
7687 (make-indirect-buffer buffer bname 'clone)
7688 (error (make-indirect-buffer buffer bname)))))
7690 (defun org-set-frame-title (title)
7691 "Set the title of the current frame to the string TITLE."
7692 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7694 ;;;; Structure editing
7696 ;;; Inserting headlines
7698 (defun org--line-empty-p (n)
7699 "Is the Nth next line empty?
7701 Counts the current line as N = 1 and the previous line as N = 0;
7702 see `beginning-of-line'."
7705 (or (beginning-of-line n) t)
7707 (looking-at "[ \t]*$")))))
7709 (defun org-previous-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 0))
7714 (defun org-next-line-empty-p ()
7715 "Is the previous line a blank line?
7716 When NEXT is non-nil, check the next line instead."
7717 (org--line-empty-p 2))
7719 (defun org--blank-before-heading-p (&optional parent)
7720 "Non-nil when an empty line should precede a new heading here.
7721 When optional argument PARENT is non-nil, consider parent
7722 headline instead of current one."
7723 (pcase (assq 'heading org-blank-before-new-entry)
7726 (org-with-limited-levels
7727 (unless (and (org-before-first-heading-p)
7728 (not (outline-next-heading)))
7729 (org-back-to-heading t)
7730 (when parent (org-up-heading-safe))
7732 (org-previous-line-empty-p))
7733 ((outline-next-heading)
7734 (org-previous-line-empty-p))
7735 ;; Ignore trailing spaces on last buffer line.
7736 ((progn (skip-chars-backward " \t") (bolp))
7737 (org-previous-line-empty-p))
7739 (`(heading . ,value) value)
7742 (defun org-insert-heading (&optional arg invisible-ok top)
7743 "Insert a new heading or an item with the same depth at point.
7745 If point is at the beginning of a heading, insert a new heading
7746 or a new headline above the current one. When at the beginning
7747 of a regular line of text, turn it into a heading.
7749 If point is in the middle of a line, split it and create a new
7750 headline with the text in the current line after point (see
7751 `org-M-RET-may-split-line' on how to modify this behavior). As
7752 a special case, on a headline, splitting can only happen on the
7753 title itself. E.g., this excludes breaking stars or tags.
7755 With a `\\[universal-argument]' prefix, set \
7756 `org-insert-heading-respect-content' to
7757 a non-nil value for the duration of the command. This forces the
7758 insertion of a heading after the current subtree, independently
7759 on the location of point.
7761 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7762 insert the heading at the end of the tree
7763 above the current heading. For example, if point is within a
7764 2nd-level heading, then it will insert a 2nd-level heading at
7765 the end of the 1st-level parent subtree.
7767 When INVISIBLE-OK is set, stop at invisible headlines when going
7768 back. This is important for non-interactive uses of the
7771 When optional argument TOP is non-nil, insert a level 1 heading,
7774 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7775 (level (org-current-level))
7776 (stars (make-string (if (and level (not top)) level 1) ?*)))
7778 ((or org-insert-heading-respect-content
7779 (member arg '((4) (16)))
7780 (and (not invisible-ok)
7781 (invisible-p (max (1- (point)) (point-min)))))
7782 ;; Position point at the location of insertion.
7783 (if (not level) ;before first headline
7784 (org-with-limited-levels (outline-next-heading))
7785 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7787 (org-with-limited-levels (org-back-to-heading invisible-ok))
7788 (cond ((equal arg '(16))
7789 (org-up-heading-safe)
7790 (org-end-of-subtree t t))
7792 (org-end-of-subtree t t))))
7793 (unless (bolp) (insert "\n")) ;ensure final newline
7794 (unless (and blank? (org-previous-line-empty-p))
7795 (org-N-empty-lines-before-current (if blank? 1 0)))
7796 (insert stars " \n")
7801 (when blank? (save-excursion (insert "\n")))
7802 (save-excursion (insert stars " \n"))
7803 (unless (and blank? (org-previous-line-empty-p))
7804 (org-N-empty-lines-before-current (if blank? 1 0)))
7806 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7807 (org-match-line org-complex-heading-regexp)
7808 (org-pos-in-match-range (point) 4))
7809 ;; Grab the text that should moved to the new headline.
7811 (let ((split (delete-and-extract-region (point) (match-end 4))))
7812 (if (looking-at "[ \t]*$") (replace-match "")
7813 (org-set-tags nil t))
7815 (when blank? (insert "\n"))
7816 (insert "\n" stars " ")
7817 (when (org-string-nw-p split) (insert split))
7818 (when (eobp) (save-excursion (insert "\n")))))
7821 (when blank? (insert "\n"))
7822 (insert "\n" stars " ")
7823 (when (eobp) (save-excursion (insert "\n"))))))
7824 ;; On regular text, turn line into a headline or split, if
7828 (unless (and blank? (org-previous-line-empty-p))
7829 (org-N-empty-lines-before-current (if blank? 1 0))))
7831 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7833 (insert "\n" stars " ")
7834 (unless (and blank? (org-previous-line-empty-p))
7835 (org-N-empty-lines-before-current (if blank? 1 0))))))
7836 (run-hooks 'org-insert-heading-hook))
7838 (defun org-N-empty-lines-before-current (n)
7839 "Make the number of empty lines before current exactly N.
7840 So this will delete or add empty lines."
7841 (let ((column (current-column)))
7844 (let ((start (save-excursion
7845 (skip-chars-backward " \r\t\n")
7846 (line-end-position))))
7847 (delete-region start (line-end-position 0))))
7848 (insert (make-string n ?\n))
7849 (move-to-column column)))
7851 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7852 "Return the heading of the current entry, without the stars.
7853 When NO-TAGS is non-nil, don't include tags.
7854 When NO-TODO is non-nil, don't include TODO keywords.
7855 When NO-PRIORITY is non-nil, don't include priority cookie.
7856 When NO-COMMENT is non-nil, don't include COMMENT string."
7858 (org-back-to-heading t)
7859 (let ((case-fold-search nil))
7860 (looking-at org-complex-heading-regexp)
7861 (let ((todo (and (not no-todo) (match-string 2)))
7862 (priority (and (not no-priority) (match-string 3)))
7863 (headline (pcase (match-string 4)
7865 ((and (guard no-comment) h)
7866 (replace-regexp-in-string
7868 (format "\\`%s[ \t]+" org-comment-string))
7871 (tags (and (not no-tags) (match-string 5))))
7872 (mapconcat #'identity
7873 (delq nil (list todo priority headline tags))
7876 (defvar orgstruct-mode) ; defined below
7878 (defun org-heading-components ()
7879 "Return the components of the current heading.
7880 This is a list with the following elements:
7881 - the level as an integer
7882 - the reduced level, different if `org-odd-levels-only' is set.
7883 - the TODO keyword, or nil
7884 - the priority character, like ?A, or nil if no priority is given
7885 - the headline text itself, or the tags string if no headline text
7886 - the tags string, or nil."
7888 (org-back-to-heading t)
7889 (when (let (case-fold-search)
7893 org-complex-heading-regexp)))
7895 (list (length (match-string 1))
7896 (org-reduced-level (length (match-string 1)))
7901 (list (length (match-string 1))
7902 (org-reduced-level (length (match-string 1)))
7903 (match-string-no-properties 2)
7904 (and (match-end 3) (aref (match-string 3) 2))
7905 (match-string-no-properties 4)
7906 (match-string-no-properties 5))))))
7908 (defun org-get-entry ()
7909 "Get the entry text, after heading, entire subtree."
7911 (org-back-to-heading t)
7912 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7914 (defun org-edit-headline (&optional heading)
7915 "Edit the current headline.
7916 Set it to HEADING when provided."
7918 (org-with-wide-buffer
7919 (org-back-to-heading t)
7920 (let ((case-fold-search nil))
7921 (when (looking-at org-complex-heading-regexp)
7922 (let* ((old (match-string-no-properties 4))
7923 (new (save-match-data
7924 (org-trim (or heading (read-string "Edit: " old))))))
7925 (unless (equal old new)
7926 (if old (replace-match new t t nil 4)
7927 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7929 (org-set-tags nil t)
7930 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7932 (defun org-insert-heading-after-current ()
7933 "Insert a new heading with same level as current, after current subtree."
7935 (org-back-to-heading)
7936 (org-insert-heading)
7937 (org-move-subtree-down)
7940 (defun org-insert-heading-respect-content (&optional invisible-ok)
7941 "Insert heading with `org-insert-heading-respect-content' set to t."
7943 (org-insert-heading '(4) invisible-ok))
7945 (defun org-insert-todo-heading-respect-content (&optional force-state)
7946 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7948 (org-insert-todo-heading force-state '(4)))
7950 (defun org-insert-todo-heading (arg &optional force-heading)
7951 "Insert a new heading with the same level and TODO state as current heading.
7953 If the heading has no TODO state, or if the state is DONE, use
7954 the first state (TODO by default). Also with one prefix arg,
7955 force first state. With two prefix args, force inserting at the
7956 end of the parent subtree.
7958 When called at a plain list item, insert a new item with an
7959 unchecked check box."
7961 (when (or force-heading (not (org-insert-item 'checkbox)))
7962 (org-insert-heading (or (and (equal arg '(16)) '(16))
7965 (org-forward-heading-same-level -1)
7966 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7968 (if (or (equal arg '(4))
7969 (not (match-beginning 2))
7970 (member (match-string 2) org-done-keywords))
7971 (car org-todo-keywords-1)
7975 (run-hook-with-args-until-success
7976 'org-todo-get-default-hook new-mark-x nil)
7978 (beginning-of-line 1)
7979 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7980 (if org-treat-insert-todo-heading-as-state-change
7982 (insert new-mark " "))))
7983 (when org-provide-todo-statistics
7984 (org-update-parent-todo-statistics))))
7986 (defun org-insert-subheading (arg)
7987 "Insert a new subheading and demote it.
7988 Works for outline headings and for plain lists alike."
7990 (org-insert-heading arg)
7992 ((org-at-heading-p) (org-do-demote))
7993 ((org-at-item-p) (org-indent-item))))
7995 (defun org-insert-todo-subheading (arg)
7996 "Insert a new subheading with TODO keyword or checkbox and demote it.
7997 Works for outline headings and for plain lists alike."
7999 (org-insert-todo-heading arg)
8001 ((org-at-heading-p) (org-do-demote))
8002 ((org-at-item-p) (org-indent-item))))
8004 ;;; Promotion and Demotion
8006 (defvar org-after-demote-entry-hook nil
8007 "Hook run after an entry has been demoted.
8008 The cursor will be at the beginning of the entry.
8009 When a subtree is being demoted, the hook will be called for each node.")
8011 (defvar org-after-promote-entry-hook nil
8012 "Hook run after an entry has been promoted.
8013 The cursor will be at the beginning of the entry.
8014 When a subtree is being promoted, the hook will be called for each node.")
8016 (defun org-promote-subtree ()
8017 "Promote the entire subtree.
8018 See also `org-promote'."
8021 (org-with-limited-levels (org-map-tree 'org-promote)))
8022 (org-fix-position-after-promote))
8024 (defun org-demote-subtree ()
8025 "Demote the entire subtree.
8026 See `org-demote' and `org-promote'."
8029 (org-with-limited-levels (org-map-tree 'org-demote)))
8030 (org-fix-position-after-promote))
8032 (defun org-do-promote ()
8033 "Promote the current heading higher up the tree.
8034 If the region is active in `transient-mark-mode', promote all
8035 headings in the region."
8038 (if (org-region-active-p)
8039 (org-map-region 'org-promote (region-beginning) (region-end))
8041 (org-fix-position-after-promote))
8043 (defun org-do-demote ()
8044 "Demote the current heading lower down the tree.
8045 If the region is active in `transient-mark-mode', demote all
8046 headings in the region."
8049 (if (org-region-active-p)
8050 (org-map-region 'org-demote (region-beginning) (region-end))
8052 (org-fix-position-after-promote))
8054 (defun org-fix-position-after-promote ()
8055 "Fix cursor position and indentation after demoting/promoting."
8056 (let ((pos (point)))
8057 (when (save-excursion
8059 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8060 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8061 (cond ((eobp) (insert " "))
8062 ((eolp) (insert " "))
8063 ((equal (char-after) ?\s) (forward-char 1))))))
8065 (defun org-current-level ()
8066 "Return the level of the current entry, or nil if before the first headline.
8067 The level is the number of stars at the beginning of the
8068 headline. Use `org-reduced-level' to remove the effect of
8069 `org-odd-levels'. Unlike to `org-outline-level', this function
8070 ignores inlinetasks."
8071 (let ((level (org-with-limited-levels (org-outline-level))))
8072 (and (> level 0) level)))
8074 (defun org-get-previous-line-level ()
8075 "Return the outline depth of the last headline before the current line.
8076 Returns 0 for the first headline in the buffer, and nil if before the
8078 (and (org-current-level)
8079 (or (and (/= (line-beginning-position) (point-min))
8080 (save-excursion (beginning-of-line 0) (org-current-level)))
8083 (defun org-reduced-level (l)
8084 "Compute the effective level of a heading.
8085 This takes into account the setting of `org-odd-levels-only'."
8088 (org-odd-levels-only (1+ (floor (/ l 2))))
8091 (defun org-level-increment ()
8092 "Return the number of stars that will be added or removed at a
8093 time to headlines when structure editing, based on the value of
8094 `org-odd-levels-only'."
8095 (if org-odd-levels-only 2 1))
8097 (defun org-get-valid-level (level &optional change)
8098 "Rectify a level change under the influence of `org-odd-levels-only'.
8099 LEVEL is a current level, CHANGE is by how much the level should
8100 be modified. Even if CHANGE is nil, LEVEL may be returned
8101 modified because even level numbers will become the next higher
8102 odd number. Returns values greater than 0."
8103 (if org-odd-levels-only
8104 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8105 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8106 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8107 (max 1 (+ level (or change 0)))))
8109 (defun org-promote ()
8110 "Promote the current heading higher up the tree."
8111 (org-with-wide-buffer
8112 (org-back-to-heading t)
8113 (let* ((after-change-functions (remq 'flyspell-after-change-function
8114 after-change-functions))
8115 (level (save-match-data (funcall outline-level)))
8116 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8117 (diff (abs (- level (length up-head) -1))))
8119 ((and (= level 1) org-allow-promoting-top-level-subtree)
8120 (replace-match "# " nil t))
8122 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8123 (t (replace-match up-head nil t)))
8125 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8126 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8127 (run-hooks 'org-after-promote-entry-hook))))
8129 (defun org-demote ()
8130 "Demote the current heading lower down the tree."
8131 (org-with-wide-buffer
8132 (org-back-to-heading t)
8133 (let* ((after-change-functions (remq 'flyspell-after-change-function
8134 after-change-functions))
8135 (level (save-match-data (funcall outline-level)))
8136 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8137 (diff (abs (- level (length down-head) -1))))
8138 (replace-match down-head nil t)
8139 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8140 (when org-adapt-indentation (org-fixup-indentation diff))
8141 (run-hooks 'org-after-demote-entry-hook))))
8143 (defun org-cycle-level ()
8144 "Cycle the level of an empty headline through possible states.
8145 This goes first to child, then to parent, level, then up the hierarchy.
8146 After top level, it switches back to sibling level."
8148 (let ((org-adapt-indentation nil))
8149 (when (org-point-at-end-of-empty-headline)
8150 (setq this-command 'org-cycle-level) ; Only needed for caching
8151 (let ((cur-level (org-current-level))
8152 (prev-level (org-get-previous-line-level)))
8154 ;; If first headline in file, promote to top-level.
8156 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8157 do (org-do-promote)))
8158 ;; If same level as prev, demote one.
8159 ((= prev-level cur-level)
8161 ;; If parent is top-level, promote to top level if not already.
8163 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8164 do (org-do-promote)))
8165 ;; If top-level, return to prev-level.
8167 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8168 do (org-do-demote)))
8169 ;; If less than prev-level, promote one.
8170 ((< cur-level prev-level)
8172 ;; If deeper than prev-level, promote until higher than
8174 ((> cur-level prev-level)
8175 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8176 do (org-do-promote))))
8179 (defun org-map-tree (fun)
8180 "Call FUN for every heading underneath the current one."
8181 (org-back-to-heading t)
8182 (let ((level (funcall outline-level)))
8186 (outline-next-heading)
8187 (> (funcall outline-level) level))
8191 (defun org-map-region (fun beg end)
8192 "Call FUN for every heading between BEG and END."
8193 (let ((org-ignore-region t))
8195 (setq end (copy-marker end))
8197 (when (and (re-search-forward org-outline-regexp-bol nil t)
8201 (outline-next-heading)
8206 (defun org-fixup-indentation (diff)
8207 "Change the indentation in the current entry by DIFF.
8209 DIFF is an integer. Indentation is done according to the
8212 - Planning information and property drawers are always indented
8213 according to the new level of the headline;
8215 - Footnote definitions and their contents are ignored;
8217 - Inlinetasks' boundaries are not shifted;
8219 - Empty lines are ignored;
8221 - Other lines' indentation are shifted by DIFF columns, unless
8222 it would introduce a structural change in the document, in
8223 which case no shifting is done at all.
8225 Assume point is at a heading or an inlinetask beginning."
8226 (org-with-wide-buffer
8227 (narrow-to-region (line-beginning-position)
8229 (if (org-with-limited-levels (org-at-heading-p))
8230 (org-with-limited-levels (outline-next-heading))
8231 (org-inlinetask-goto-end))
8234 ;; Indent properly planning info and property drawer.
8235 (when (looking-at-p org-planning-line-re)
8238 (when (looking-at org-property-drawer-re)
8239 (goto-char (match-end 0))
8241 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8243 (when (zerop diff) (throw 'no-shift nil))
8244 ;; If DIFF is negative, first check if a shift is possible at all
8245 ;; (e.g., it doesn't break structure). This can only happen if
8246 ;; some contents are not properly indented.
8247 (let ((case-fold-search t))
8249 (let ((diff (- diff))
8250 (forbidden-re (concat org-outline-regexp
8252 (substring org-footnote-definition-re 1))))
8256 ((looking-at-p "[ \t]*$") (forward-line))
8257 ((and (looking-at-p org-footnote-definition-re)
8258 (let ((e (org-element-at-point)))
8259 (and (eq (org-element-type e) 'footnote-definition)
8260 (goto-char (org-element-property :end e))))))
8261 ((looking-at-p org-outline-regexp) (forward-line))
8262 ;; Give up if shifting would move before column 0 or
8263 ;; if it would introduce a headline or a footnote
8266 (skip-chars-forward " \t")
8267 (let ((ind (current-column)))
8268 (when (or (< ind diff)
8269 (and (= ind diff) (looking-at-p forbidden-re)))
8270 (throw 'no-shift nil)))
8271 ;; Ignore contents of example blocks and source
8272 ;; blocks if their indentation is meant to be
8273 ;; preserved. Jump to block's closing line.
8275 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8276 (let ((e (org-element-at-point)))
8277 (and (memq (org-element-type e)
8278 '(example-block src-block))
8279 (or org-src-preserve-indentation
8280 (org-element-property :preserve-indent e))
8281 (goto-char (org-element-property :end e))
8282 (progn (skip-chars-backward " \r\t\n")
8285 (forward-line))))))))
8286 ;; Shift lines but footnote definitions, inlinetasks boundaries
8287 ;; by DIFF. Also skip contents of source or example blocks
8288 ;; when indentation is meant to be preserved.
8291 ((and (looking-at-p org-footnote-definition-re)
8292 (let ((e (org-element-at-point)))
8293 (and (eq (org-element-type e) 'footnote-definition)
8294 (goto-char (org-element-property :end e))))))
8295 ((looking-at-p org-outline-regexp) (forward-line))
8296 ((looking-at-p "[ \t]*$") (forward-line))
8298 (indent-line-to (+ (org-get-indentation) diff))
8300 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8301 (let ((e (org-element-at-point)))
8302 (and (memq (org-element-type e)
8303 '(example-block src-block))
8304 (or org-src-preserve-indentation
8305 (org-element-property :preserve-indent e))
8306 (goto-char (org-element-property :end e))
8307 (progn (skip-chars-backward " \r\t\n")
8310 (forward-line)))))))))
8312 (defun org-convert-to-odd-levels ()
8313 "Convert an Org file with all levels allowed to one with odd levels.
8314 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8317 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8318 (let ((outline-level 'org-outline-level)
8319 (org-odd-levels-only nil) n)
8321 (goto-char (point-min))
8322 (while (re-search-forward "^\\*\\*+ " nil t)
8323 (setq n (- (length (match-string 0)) 2))
8324 (while (>= (setq n (1- n)) 0)
8326 (end-of-line 1))))))
8328 (defun org-convert-to-oddeven-levels ()
8329 "Convert an Org file with only odd levels to one with odd/even levels.
8330 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8331 file contains a section with an even level, conversion would
8332 destroy the structure of the file. An error is signaled in this
8335 (goto-char (point-min))
8336 ;; First check if there are no even levels
8337 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8338 (org-show-set-visibility 'canonical)
8339 (error "Not all levels are odd in this file. Conversion not possible"))
8340 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8341 (let ((outline-regexp org-outline-regexp)
8342 (outline-level 'org-outline-level)
8343 (org-odd-levels-only nil) n)
8345 (goto-char (point-min))
8346 (while (re-search-forward "^\\*\\*+ " nil t)
8347 (setq n (/ (1- (length (match-string 0))) 2))
8348 (while (>= (setq n (1- n)) 0)
8350 (end-of-line 1))))))
8352 (defun org-tr-level (n)
8353 "Make N odd if required."
8354 (if org-odd-levels-only (1+ (/ n 2)) n))
8356 ;;; Vertical tree motion, cutting and pasting of subtrees
8358 (defun org-move-subtree-up (&optional arg)
8359 "Move the current subtree up past ARG headlines of the same level."
8361 (org-move-subtree-down (- (prefix-numeric-value arg))))
8363 (defun org-move-subtree-down (&optional arg)
8364 "Move the current subtree down past ARG headlines of the same level."
8366 (setq arg (prefix-numeric-value arg))
8367 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8368 'org-get-last-sibling))
8369 (ins-point (make-marker))
8371 (col (current-column))
8372 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8374 (org-back-to-heading)
8377 (setq ne-beg (org-back-over-empty-lines))
8380 (save-excursion (outline-end-of-heading)
8381 (setq folded (org-invisible-p)))
8382 (progn (org-end-of-subtree nil t)
8383 (unless (eobp) (backward-char))))
8384 (outline-next-heading)
8385 (setq ne-end (org-back-over-empty-lines))
8388 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8389 ;; include less whitespace
8392 (forward-line (- ne-beg ne-end))
8393 (setq beg (point))))
8394 ;; Find insertion point, with error handling
8396 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8397 (progn (goto-char beg0)
8398 (user-error "Cannot move past superior level or buffer limit")))
8399 (setq cnt (1- cnt)))
8401 ;; Moving forward - still need to move over subtree
8402 (org-end-of-subtree t t)
8404 (org-back-over-empty-lines)
8405 (or (bolp) (newline))))
8406 (setq ne-ins (org-back-over-empty-lines))
8407 (move-marker ins-point (point))
8408 (setq txt (buffer-substring beg end))
8409 (org-save-markers-in-region beg end)
8410 (delete-region beg end)
8411 (org-remove-empty-overlays-at beg)
8412 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8413 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8414 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8415 (let ((bbb (point)))
8416 (insert-before-markers txt)
8417 (org-reinstall-markers-in-region bbb)
8418 (move-marker ins-point bbb))
8419 (or (bolp) (insert "\n"))
8420 (setq ins-end (point))
8421 (goto-char ins-point)
8422 (org-skip-whitespace)
8423 (when (and (< arg 0)
8424 (org-first-sibling-p)
8426 ;; Move whitespace back to beginning
8429 (let ((kill-whole-line t))
8430 (kill-line (- ne-ins ne-beg)) (point)))
8431 (insert (make-string (- ne-ins ne-beg) ?\n)))
8432 (move-marker ins-point nil)
8434 (outline-hide-subtree)
8437 (org-cycle-hide-drawers 'children))
8438 (org-clean-visibility-after-subtree-move)
8439 ;; move back to the initial column we were at
8440 (move-to-column col)))
8442 (defvar org-subtree-clip ""
8443 "Clipboard for cut and paste of subtrees.
8444 This is actually only a copy of the kill, because we use the normal kill
8445 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8447 (defvar org-subtree-clip-folded nil
8448 "Was the last copied subtree folded?
8449 This is used to fold the tree back after pasting.")
8451 (defun org-cut-subtree (&optional n)
8452 "Cut the current subtree into the clipboard.
8453 With prefix arg N, cut this many sequential subtrees.
8454 This is a short-hand for marking the subtree and then cutting it."
8456 (org-copy-subtree n 'cut))
8458 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8459 "Copy the current subtree it in the clipboard.
8460 With prefix arg N, copy this many sequential subtrees.
8461 This is a short-hand for marking the subtree and then copying it.
8462 If CUT is non-nil, actually cut the subtree.
8463 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8464 of some markers in the region, even if CUT is non-nil. This is
8465 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8467 (let (beg end folded (beg0 (point)))
8468 (if (called-interactively-p 'any)
8469 (org-back-to-heading nil) ; take what looks like a subtree
8470 (org-back-to-heading t)) ; take what is really there
8472 (skip-chars-forward " \t\r\n")
8475 (outline-next-heading)
8476 (save-excursion (outline-end-of-heading)
8477 (setq folded (org-invisible-p)))
8478 (ignore-errors (org-forward-heading-same-level (1- n) t))
8479 (org-end-of-subtree t t)))
8480 ;; Include the end of an inlinetask
8481 (when (and (featurep 'org-inlinetask)
8482 (looking-at-p (concat (org-inlinetask-outline-regexp)
8488 (setq org-subtree-clip-folded folded)
8489 (when (or cut force-store-markers)
8490 (org-save-markers-in-region beg end))
8491 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8492 (setq org-subtree-clip (current-kill 0))
8493 (message "%s: Subtree(s) with %d characters"
8494 (if cut "Cut" "Copied")
8495 (length org-subtree-clip)))))
8497 (defun org-paste-subtree (&optional level tree for-yank remove)
8498 "Paste the clipboard as a subtree, with modification of headline level.
8499 The entire subtree is promoted or demoted in order to match a new headline
8502 If the cursor is at the beginning of a headline, the same level as
8503 that headline is used to paste the tree.
8505 If not, the new level is derived from the *visible* headings
8506 before and after the insertion point, and taken to be the inferior headline
8507 level of the two. So if the previous visible heading is level 3 and the
8508 next is level 4 (or vice versa), level 4 will be used for insertion.
8509 This makes sure that the subtree remains an independent subtree and does
8510 not swallow low level entries.
8512 You can also force a different level, either by using a numeric prefix
8513 argument, or by inserting the heading marker by hand. For example, if the
8514 cursor is after \"*****\", then the tree will be shifted to level 5.
8516 If optional TREE is given, use this text instead of the kill ring.
8518 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8519 move back over whitespace before inserting, and move point to the end of
8520 the inserted text when done.
8522 When REMOVE is non-nil, remove the subtree from the clipboard."
8524 (setq tree (or tree (and kill-ring (current-kill 0))))
8525 (unless (org-kill-is-subtree-p tree)
8527 (substitute-command-keys
8528 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8529 (org-with-limited-levels
8530 (let* ((visp (not (org-invisible-p)))
8532 (^re_ "\\(\\*+\\)[ \t]*")
8533 (old-level (if (string-match org-outline-regexp-bol txt)
8534 (- (match-end 0) (match-beginning 0) 1)
8536 (force-level (cond (level (prefix-numeric-value level))
8537 ((and (looking-at "[ \t]*$")
8539 "^\\*+$" (buffer-substring
8540 (point-at-bol) (point))))
8541 (- (match-end 0) (match-beginning 0)))
8543 (looking-at org-outline-regexp))
8544 (- (match-end 0) (point) 1))))
8545 (previous-level (save-excursion
8548 (outline-previous-visible-heading 1)
8549 (if (looking-at ^re_)
8550 (- (match-end 0) (match-beginning 0) 1)
8553 (next-level (save-excursion
8556 (or (looking-at org-outline-regexp)
8557 (outline-next-visible-heading 1))
8558 (if (looking-at ^re_)
8559 (- (match-end 0) (match-beginning 0) 1)
8562 (new-level (or force-level (max previous-level next-level)))
8563 (shift (if (or (= old-level -1)
8565 (= old-level new-level))
8567 (- new-level old-level)))
8568 (delta (if (> shift 0) -1 1))
8569 (func (if (> shift 0) 'org-demote 'org-promote))
8570 (org-odd-levels-only nil)
8572 ;; Remove the forced level indicator
8574 (delete-region (point-at-bol) (point)))
8576 (beginning-of-line (if (bolp) 1 2))
8578 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8579 (insert-before-markers txt)
8580 (unless (string-suffix-p "\n" txt) (insert "\n"))
8581 (setq newend (point))
8582 (org-reinstall-markers-in-region beg)
8585 (skip-chars-forward " \t\n\r")
8587 (when (and (org-invisible-p) visp)
8588 (save-excursion (outline-show-heading)))
8589 ;; Shift if necessary
8592 (narrow-to-region beg end)
8593 (while (not (= shift 0))
8594 (org-map-region func (point-min) (point-max))
8595 (setq shift (+ delta shift)))
8596 (goto-char (point-min))
8597 (setq newend (point-max))))
8598 (when (or (called-interactively-p 'interactive) for-yank)
8599 (message "Clipboard pasted as level %d subtree" new-level))
8600 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8602 (eq org-subtree-clip (current-kill 0))
8603 org-subtree-clip-folded)
8604 ;; The tree was folded before it was killed/copied
8605 (outline-hide-subtree))
8606 (and for-yank (goto-char newend))
8607 (and remove (setq kill-ring (cdr kill-ring))))))
8609 (defun org-kill-is-subtree-p (&optional txt)
8610 "Check if the current kill is an outline subtree, or a set of trees.
8611 Returns nil if kill does not start with a headline, or if the first
8612 headline level is not the largest headline level in the tree.
8613 So this will actually accept several entries of equal levels as well,
8614 which is OK for `org-paste-subtree'.
8615 If optional TXT is given, check this string instead of the current kill."
8616 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8617 (re (org-get-limited-outline-regexp))
8618 (^re (concat "^" re))
8619 (start-level (and kill
8621 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8623 (- (match-end 2) (match-beginning 2) 1)))
8624 (start (1+ (or (match-beginning 2) -1))))
8625 (if (not start-level)
8627 nil) ;; does not even start with a heading
8629 (while (setq start (string-match ^re kill (1+ start)))
8630 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8634 (defvar org-markers-to-move nil
8635 "Markers that should be moved with a cut-and-paste operation.
8636 Those markers are stored together with their positions relative to
8637 the start of the region.")
8639 (defun org-save-markers-in-region (beg end)
8640 "Check markers in region.
8641 If these markers are between BEG and END, record their position relative
8642 to BEG, so that after moving the block of text, we can put the markers back
8644 This function gets called just before an entry or tree gets cut from the
8645 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8646 called immediately, to move the markers with the entries."
8647 (setq org-markers-to-move nil)
8648 (when (featurep 'org-clock)
8649 (org-clock-save-markers-for-cut-and-paste beg end))
8650 (when (featurep 'org-agenda)
8651 (org-agenda-save-markers-for-cut-and-paste beg end)))
8653 (defun org-check-and-save-marker (marker beg end)
8654 "Check if MARKER is between BEG and END.
8655 If yes, remember the marker and the distance to BEG."
8656 (when (and (marker-buffer marker)
8657 (equal (marker-buffer marker) (current-buffer))
8658 (>= marker beg) (< marker end))
8659 (push (cons marker (- marker beg)) org-markers-to-move)))
8661 (defun org-reinstall-markers-in-region (beg)
8662 "Move all remembered markers to their position relative to BEG."
8663 (dolist (x org-markers-to-move)
8664 (move-marker (car x) (+ beg (cdr x))))
8665 (setq org-markers-to-move nil))
8667 (defun org-narrow-to-subtree ()
8668 "Narrow buffer to the current subtree."
8672 (org-with-limited-levels
8674 (progn (org-back-to-heading t) (point))
8675 (progn (org-end-of-subtree t t)
8676 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8679 (defun org-narrow-to-block ()
8680 "Narrow buffer to the current block."
8682 (let* ((case-fold-search t)
8683 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8684 "^[ \t]*#\\+end_.*")))
8686 (narrow-to-region (car blockp) (cdr blockp))
8687 (user-error "Not in a block"))))
8689 (defun org-clone-subtree-with-time-shift (n &optional shift)
8690 "Clone the task (subtree) at point N times.
8691 The clones will be inserted as siblings.
8693 In interactive use, the user will be prompted for the number of
8694 clones to be produced. If the entry has a timestamp, the user
8695 will also be prompted for a time shift, which may be a repeater
8696 as used in time stamps, for example `+3d'. To disable this,
8697 you can call the function with a universal prefix argument.
8699 When a valid repeater is given and the entry contains any time
8700 stamps, the clones will become a sequence in time, with time
8701 stamps in the subtree shifted for each clone produced. If SHIFT
8702 is nil or the empty string, time stamps will be left alone. The
8703 ID property of the original subtree is removed.
8705 In each clone, all the CLOCK entries will be removed. This
8706 prevents Org from considering that the clocked times overlap.
8708 If the original subtree did contain time stamps with a repeater,
8709 the following will happen:
8710 - the repeater will be removed in each clone
8711 - an additional clone will be produced, with the current, unshifted
8712 date(s) in the entry.
8713 - the original entry will be placed *after* all the clones, with
8715 - the start days in the repeater in the original entry will be shifted
8716 to past the last clone.
8717 In this way you can spell out a number of instances of a repeating task,
8718 and still retain the repeater to cover future instances of the task.
8720 As described above, N+1 clones are produced when the original
8721 subtree has a repeater. Setting N to 0, then, can be used to
8722 remove the repeater from a subtree and create a shifted clone
8723 with the original repeater."
8724 (interactive "nNumber of clones to produce: ")
8725 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8726 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8727 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8728 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8731 (if (and (not (equal current-prefix-arg '(4)))
8734 (re-search-forward org-ts-regexp-both end-of-tree t)))
8735 (read-from-minibuffer
8736 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8737 ""))) ;No time shift
8739 (and (org-string-nw-p shift)
8740 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8742 (user-error "Invalid shift specification %s" shift)))))
8743 (goto-char end-of-tree)
8744 (unless (bolp) (insert "\n"))
8745 (let* ((end (point))
8746 (template (buffer-substring beg end))
8747 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8748 (shift-what (pcase (and doshift (match-string 2 shift))
8751 ("w" (setq shift-n (* 7 shift-n)) 'day)
8754 (_ (error "Unsupported time unit"))))
8758 (idprop (org-entry-get nil "ID")))
8760 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8762 (delete-region beg end)
8765 (setq nmax (1+ nmax))
8766 (setq n-no-remove nmax))
8768 (cl-loop for n from nmin to nmax do
8774 (goto-char (point-min))
8776 (and idprop (if org-clone-delete-id
8777 (org-entry-delete nil "ID")
8778 (org-id-get-create t)))
8780 (while (re-search-forward org-clock-line-re nil t)
8781 (delete-region (line-beginning-position)
8782 (line-beginning-position 2)))
8783 (goto-char (point-min))
8784 (while (re-search-forward org-drawer-regexp nil t)
8785 (org-remove-empty-drawer-at (point))))
8786 (goto-char (point-min))
8788 (while (re-search-forward org-ts-regexp-both nil t)
8789 (org-timestamp-change (* n shift-n) shift-what))
8790 (unless (= n n-no-remove)
8791 (goto-char (point-min))
8792 (while (re-search-forward org-ts-regexp nil t)
8794 (goto-char (match-beginning 0))
8795 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8796 (delete-region (match-beginning 1) (match-end 1)))))))
8802 (defun org-sort (&optional with-case)
8803 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8804 Optional argument WITH-CASE means sort case-sensitively."
8807 (cond ((org-at-table-p) #'org-table-sort-lines)
8808 ((org-at-item-p) #'org-sort-list)
8809 (t #'org-sort-entries))
8812 (defun org-sort-remove-invisible (s)
8813 "Remove invisible part of links and emphasis markers from string S."
8814 (remove-text-properties 0 (length s) org-rm-props s)
8815 (replace-regexp-in-string
8816 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8817 (replace-regexp-in-string
8818 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8819 (org-link-display-format s)
8822 (defvar org-priority-regexp) ; defined later in the file
8824 (defvar org-after-sorting-entries-or-items-hook nil
8825 "Hook that is run after a bunch of entries or items have been sorted.
8826 When children are sorted, the cursor is in the parent line when this
8827 hook gets called. When a region or a plain list is sorted, the cursor
8828 will be in the first entry of the sorted region/list.")
8830 (defun org-sort-entries
8831 (&optional with-case sorting-type getkey-func compare-func property
8833 "Sort entries on a certain level of an outline tree.
8834 If there is an active region, the entries in the region are sorted.
8835 Else, if the cursor is before the first entry, sort the top-level items.
8836 Else, the children of the entry at point are sorted.
8838 Sorting can be alphabetically, numerically, by date/time as given by
8839 a time stamp, by a property, by priority order, or by a custom function.
8841 The command prompts for the sorting type unless it has been given to the
8842 function through the SORTING-TYPE argument, which needs to be a character,
8843 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8844 the precise meaning of each character:
8846 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8847 c By creation time, which is assumed to be the first inactive time stamp
8848 at the beginning of a line.
8849 d By deadline date/time.
8851 n Numerically, by converting the beginning of the entry/item to a number.
8852 o By order of TODO keywords.
8853 p By priority according to the cookie.
8854 r By the value of a property.
8855 s By scheduled date/time.
8856 t By date/time, either the first active time stamp in the entry, or, if
8857 none exist, by the first inactive one.
8859 Capital letters will reverse the sort order.
8861 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8862 called with point at the beginning of the record. It must return a
8863 value that is compatible with COMPARE-FUNC, the function used to
8866 Comparing entries ignores case by default. However, with an optional argument
8867 WITH-CASE, the sorting considers case as well.
8869 Sorting is done against the visible part of the headlines, it ignores hidden
8872 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8874 A non-nil value for INTERACTIVE? is used to signal that this
8875 function is being called interactively."
8876 (interactive (list current-prefix-arg nil nil nil nil t))
8877 (let ((case-func (if with-case 'identity 'downcase))
8878 start beg end stars re re2
8880 ;; Find beginning and end of region to sort
8882 ((org-region-active-p)
8883 ;; we will sort the region
8884 (setq end (region-end)
8886 (goto-char (region-beginning))
8887 (unless (org-at-heading-p) (outline-next-heading))
8888 (setq start (point)))
8889 ((or (org-at-heading-p)
8890 (ignore-errors (progn (org-back-to-heading) t)))
8891 ;; we will sort the children of the current headline
8892 (org-back-to-heading)
8894 end (progn (org-end-of-subtree t t)
8895 (or (bolp) (insert "\n"))
8896 (when (>= (org-back-over-empty-lines) 1)
8901 (outline-show-subtree)
8902 (outline-next-heading))
8904 ;; we will sort the top-level entries in this file
8905 (goto-char (point-min))
8906 (or (org-at-heading-p) (outline-next-heading))
8907 (setq start (point))
8908 (goto-char (point-max))
8909 (beginning-of-line 1)
8910 (when (looking-at ".*?\\S-")
8911 ;; File ends in a non-white line
8914 (setq end (point-max))
8915 (setq what "top-level")
8917 (outline-show-all)))
8920 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8922 (looking-at "\\(\\*+\\)")
8923 (setq stars (match-string 1)
8924 re (concat "^" (regexp-quote stars) " +")
8925 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8926 txt (buffer-substring beg end))
8927 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8928 (when (and (not (equal stars "*")) (string-match re2 txt))
8929 (user-error "Region to sort contains a level above the first entry"))
8931 (unless sorting-type
8933 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8934 [t]ime
[s]cheduled [d]eadline [c]reated cloc[k]ing
8935 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8937 (setq sorting-type (read-char-exclusive)))
8940 (and (= (downcase sorting-type) ?f)
8942 (or (and interactive?
8944 "Function for extracting keys: "))
8945 (error "Missing key extractor")))))
8947 (and (= (downcase sorting-type) ?r)
8950 (completing-read "Property: "
8951 (mapcar #'list (org-buffer-property-keys t))
8954 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8955 (message "Sorting entries...")
8958 (narrow-to-region start end)
8959 (let ((restore-clock?
8960 ;; The clock marker is lost when using `sort-subr'; mark
8961 ;; the clock with temporary `:org-clock-marker-backup'
8963 (when (and (eq (org-clock-is-active) (current-buffer))
8964 (<= start (marker-position org-clock-marker))
8965 (>= end (marker-position org-clock-marker)))
8966 (org-with-silent-modifications
8967 (put-text-property (1- org-clock-marker) org-clock-marker
8968 :org-clock-marker-backup t))
8970 (dcst (downcase sorting-type))
8971 (case-fold-search nil)
8972 (now (current-time)))
8974 (/= dcst sorting-type)
8975 ;; This function moves to the beginning character of the "record" to
8978 (if (re-search-forward re nil t)
8979 (goto-char (match-beginning 0))
8980 (goto-char (point-max))))
8981 ;; This function moves to the last character of the "record" being
8986 (outline-forward-same-level 1)
8988 (goto-char (point-max))))))
8989 ;; This function returns the value that gets sorted against.
8993 (if (looking-at org-complex-heading-regexp)
8994 (string-to-number (org-sort-remove-invisible (match-string 4)))
8997 (if (looking-at org-complex-heading-regexp)
8998 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9001 (or (get-text-property (point) :org-clock-minutes) 0))
9003 (let ((end (save-excursion (outline-next-heading) (point))))
9004 (if (or (re-search-forward org-ts-regexp end t)
9005 (re-search-forward org-ts-regexp-both end t))
9006 (org-time-string-to-seconds (match-string 0))
9009 (let ((end (save-excursion (outline-next-heading) (point))))
9010 (if (re-search-forward
9011 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9013 (org-time-string-to-seconds (match-string 0))
9016 (let ((end (save-excursion (outline-next-heading) (point))))
9017 (if (re-search-forward org-scheduled-time-regexp end t)
9018 (org-time-string-to-seconds (match-string 1))
9021 (let ((end (save-excursion (outline-next-heading) (point))))
9022 (if (re-search-forward org-deadline-time-regexp end t)
9023 (org-time-string-to-seconds (match-string 1))
9026 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9027 (string-to-char (match-string 2))
9028 org-default-priority))
9030 (or (org-entry-get nil property) ""))
9032 (when (looking-at org-complex-heading-regexp)
9033 (let* ((m (match-string 2))
9034 (s (if (member m org-done-keywords) '- '+)))
9035 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9039 (setq tmp (funcall getkey-func))
9040 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9042 (error "Invalid key function `%s'" getkey-func)))
9043 (t (error "Invalid sorting type `%c'" sorting-type))))
9046 ((= dcst ?a) 'string<)
9051 (concat "Function for comparing keys "
9052 "(empty for default `sort-subr' predicate): ")
9054 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
9055 (when restore-clock?
9056 (move-marker org-clock-marker
9057 (1+ (next-single-property-change
9058 start :org-clock-marker-backup)))
9059 (remove-text-properties (1- org-clock-marker) org-clock-marker
9060 '(:org-clock-marker-backup t)))))
9061 (run-hooks 'org-after-sorting-entries-or-items-hook)
9062 (message "Sorting entries...done")))
9064 ;;; The orgstruct minor mode
9066 ;; Define a minor mode which can be used in other modes in order to
9067 ;; integrate the Org mode structure editing commands.
9069 ;; This is really a hack, because the Org mode structure commands use
9070 ;; keys which normally belong to the major mode. Here is how it
9071 ;; works: The minor mode defines all the keys necessary to operate the
9072 ;; structure commands, but wraps the commands into a function which
9073 ;; tests if the cursor is currently at a headline or a plain list
9074 ;; item. If that is the case, the structure command is used,
9075 ;; temporarily setting many Org mode variables like regular
9076 ;; expressions for filling etc. However, when any of those keys is
9077 ;; used at a different location, function uses `key-binding' to look
9078 ;; up if the key has an associated command in another currently active
9079 ;; keymap (minor modes, major mode, global), and executes that
9080 ;; command. There might be problems if any of the keys is otherwise
9081 ;; used as a prefix key.
9083 (defcustom orgstruct-heading-prefix-regexp ""
9084 "Regexp that matches the custom prefix of Org headlines in
9085 orgstruct(++)-mode."
9088 :package-version '(Org . "8.3")
9090 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9092 (defcustom orgstruct-setup-hook nil
9093 "Hook run after orgstruct-mode-map is filled."
9096 :package-version '(Org . "8.0")
9099 (defvar orgstruct-initialized nil)
9101 (defvar org-local-vars nil
9102 "List of local variables, for use by `orgstruct-mode'.")
9105 (define-minor-mode orgstruct-mode
9106 "Toggle the minor mode `orgstruct-mode'.
9107 This mode is for using Org mode structure commands in other
9108 modes. The following keys behave as if Org mode were active, if
9109 the cursor is on a headline, or on a plain list item (both as
9110 defined by Org mode)."
9111 nil " OrgStruct" (make-sparse-keymap)
9112 (funcall (if orgstruct-mode
9113 'add-to-invisibility-spec
9114 'remove-from-invisibility-spec)
9116 (when orgstruct-mode
9117 (org-load-modules-maybe)
9118 (unless orgstruct-initialized
9120 (setq orgstruct-initialized t))))
9123 (defun turn-on-orgstruct ()
9124 "Unconditionally turn on `orgstruct-mode'."
9127 (defvar-local orgstruct-is-++ nil
9128 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9129 (defvar-local org-fb-vars nil)
9130 (defun orgstruct++-mode (&optional arg)
9131 "Toggle `orgstruct-mode', the enhanced version of it.
9132 In addition to setting orgstruct-mode, this also exports all
9133 indentation and autofilling variables from Org mode into the
9134 buffer. It will also recognize item context in multiline items."
9136 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9138 (progn (orgstruct-mode -1)
9139 (dolist (v org-fb-vars)
9140 (set (make-local-variable (car v))
9141 (if (eq (car-safe (cadr v)) 'quote)
9145 (setq org-fb-vars nil)
9146 (unless org-local-vars
9147 (setq org-local-vars (org-get-local-variables)))
9149 (dolist (x org-local-vars)
9151 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9152 \\|fill-prefix\\|indent-\\)"
9153 (symbol-name (car x)))
9154 (setq var (car x) val (nth 1 x))
9155 (push (list var `(quote ,(eval var))) org-fb-vars)
9156 (set (make-local-variable var)
9157 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9158 (setq-local orgstruct-is-++ t))))
9161 (defun turn-on-orgstruct++ ()
9162 "Unconditionally turn on `orgstruct++-mode'."
9163 (orgstruct++-mode 1))
9165 (defun orgstruct-error ()
9166 "Error when there is no default binding for a structure key."
9168 (funcall (if (fboundp 'user-error)
9171 "This key has no function outside structure elements"))
9173 (defun orgstruct-setup ()
9174 "Setup orgstruct keymap."
9175 (dolist (cell '((org-demote . t)
9179 (org-shiftmetaleft . t)
9180 (org-shiftmetaright . t)
9181 org-backward-element
9182 org-backward-heading-same-level
9187 org-force-cycle-archived
9188 org-forward-heading-same-level
9190 org-insert-heading-respect-content
9191 org-kill-note-or-show-branches
9196 org-narrow-to-subtree
9212 outline-next-visible-heading
9213 outline-previous-visible-heading
9215 outline-up-heading))
9216 (let ((f (or (car-safe cell) cell))
9217 (disable-when-heading-prefix (cdr-safe cell)))
9219 (let ((new-bindings))
9220 (dolist (binding (nconc (where-is-internal f org-mode-map)
9221 (where-is-internal f outline-mode-map)))
9222 (push binding new-bindings)
9223 ;; TODO use local-function-key-map
9224 (dolist (rep '(("<tab>" . "TAB")
9225 ("<return>" . "RET")
9226 ("<escape>" . "ESC")
9227 ("<delete>" . "DEL")))
9228 (setq binding (read-kbd-macro
9229 (let ((case-fold-search))
9230 (replace-regexp-in-string
9231 (regexp-quote (cdr rep))
9233 (key-description binding)))))
9234 (cl-pushnew binding new-bindings :test 'equal)))
9235 (dolist (binding new-bindings)
9236 (let ((key (lookup-key orgstruct-mode-map binding)))
9237 (when (or (not key) (numberp key))
9239 (org-defkey orgstruct-mode-map
9241 (orgstruct-make-binding
9242 f binding disable-when-heading-prefix))))))))))
9243 (run-hooks 'orgstruct-setup-hook))
9245 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9246 "Create a function for binding in the structure minor mode.
9247 FUN is the command to call inside a table. KEY is the key that
9248 should be checked in for a command to execute outside of tables.
9249 Non-nil `disable-when-heading-prefix' means to disable the command
9250 if `orgstruct-heading-prefix-regexp' is not empty."
9251 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9254 (while (fboundp (intern nname))
9255 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9256 (setq name (intern nname)))
9258 (let ((bindings '((org-heading-regexp
9260 orgstruct-heading-prefix-regexp
9261 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9263 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9264 (org-outline-regexp-bol
9265 (concat "^" org-outline-regexp))
9266 (outline-regexp org-outline-regexp)
9267 (outline-heading-end-regexp "\n")
9268 (outline-level 'org-outline-level)
9269 (outline-heading-alist))))
9271 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9272 "Outside of structure, run the binding of `"
9273 (key-description key) "'."
9274 (when disable-when-heading-prefix
9276 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9277 "back to the default binding due to limitations of Org's implementation of\n"
9278 "`" (symbol-name fun) "'.")))
9281 ,(and disable-when-heading-prefix
9282 '(not (string= orgstruct-heading-prefix-regexp ""))))
9287 (org-context-p 'headline 'item
9289 '(org-insert-heading
9290 org-insert-heading-respect-content
9292 '(when orgstruct-is-++
9295 (let* ((orgstruct-mode)
9302 ("<\\([^>]*\\)tab>" . "\\1TAB")
9303 ("<\\([^>]*\\)return>" . "\\1RET")
9304 ("<\\([^>]*\\)escape>" . "\\1ESC")
9305 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9308 (setq key (read-kbd-macro
9309 (let ((case-fold-search))
9310 (replace-regexp-in-string
9313 (key-description key))))))
9314 (when (key-binding key)
9315 (throw 'exit (key-binding key))))))))
9316 (if (keymapp binding)
9317 (org-set-transient-map binding)
9318 (let ((func (or binding
9320 'orgstruct-error))))
9322 (call-interactively func)))))
9323 (org-run-like-in-org-mode
9327 (call-interactively ',fun)))))))))
9330 (defun org-contextualize-keys (alist contexts)
9331 "Return valid elements in ALIST depending on CONTEXTS.
9333 `org-agenda-custom-commands' or `org-capture-templates' are the
9334 values used for ALIST, and `org-agenda-custom-commands-contexts'
9335 or `org-capture-templates-contexts' are the associated contexts
9338 ;; normalize contexts
9340 (lambda(c) (cond ((listp (cadr c))
9341 (list (car c) (car c) (nth 1 c)))
9342 ((string= "" (cadr c))
9343 (list (car c) (car c) (nth 2 c)))
9347 ;; loop over all commands or templates
9351 ((not (assoc (car c) contexts))
9353 ((and (assoc (car c) contexts)
9354 (setq vrules (org-contextualize-validate-key
9357 (unless (equal (car vr) (cadr vr))
9360 (if (not repl) (push c r)
9361 (push (cadr repl) s)
9364 (cdr (or (assoc (cadr repl) alist)
9365 (error "Undefined key `%s' as contextual replacement for `%s'"
9366 (cadr repl) (car c)))))
9368 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9373 (let ((tpl (car x)))
9382 (defun org-contextualize-validate-key (key contexts)
9383 "Check CONTEXTS for agenda or capture KEY."
9385 (dolist (r contexts)
9386 (dolist (rr (car (last r)))
9388 (and (equal key (car r))
9389 (if (functionp rr) (funcall rr)
9390 (or (and (eq (car rr) 'in-file)
9392 (string-match (cdr rr) (buffer-file-name)))
9393 (and (eq (car rr) 'in-mode)
9394 (string-match (cdr rr) (symbol-name major-mode)))
9395 (and (eq (car rr) 'in-buffer)
9396 (string-match (cdr rr) (buffer-name)))
9397 (when (and (eq (car rr) 'not-in-file)
9399 (not (string-match (cdr rr) (buffer-file-name))))
9400 (when (eq (car rr) 'not-in-mode)
9401 (not (string-match (cdr rr) (symbol-name major-mode))))
9402 (when (eq (car rr) 'not-in-buffer)
9403 (not (string-match (cdr rr) (buffer-name)))))))
9405 (delete-dups (delq nil res))))
9407 (defun org-context-p (&rest contexts)
9408 "Check if local context is any of CONTEXTS.
9409 Possible values in the list of contexts are `table', `headline', and `item'."
9410 (let ((pos (point)))
9411 (goto-char (point-at-bol))
9412 (prog1 (or (and (memq 'table contexts)
9413 (looking-at "[ \t]*|"))
9414 (and (memq 'headline contexts)
9415 (looking-at org-outline-regexp))
9416 (and (memq 'item contexts)
9417 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9418 (and (memq 'item-body contexts)
9423 (defun org-run-like-in-org-mode (cmd)
9424 "Run a command, pretending that the current buffer is in Org mode.
9425 This will temporarily bind local variables that are typically bound in
9426 Org mode to the values they have in Org mode, and then interactively
9428 (org-load-modules-maybe)
9429 (unless org-local-vars
9430 (setq org-local-vars (org-get-local-variables)))
9432 (dolist (var org-local-vars)
9433 (when (or (not (boundp (car var)))
9434 (eq (symbol-value (car var))
9435 (default-value (car var))))
9436 (push (list (car var) `(quote ,(cadr var))) binds)))
9438 (call-interactively (quote ,cmd))))))
9440 (defun org-get-category (&optional pos force-refresh)
9441 "Get the category applying to position POS."
9443 (when force-refresh (org-refresh-category-properties))
9444 (let ((pos (or pos (point))))
9445 (or (get-text-property pos 'org-category)
9446 (progn (org-refresh-category-properties)
9447 (get-text-property pos 'org-category))))))
9449 ;;; Refresh properties
9451 (defun org-refresh-properties (dprop tprop)
9452 "Refresh buffer text properties.
9453 DPROP is the drawer property and TPROP is either the
9454 corresponding text property to set, or an alist with each element
9455 being a text property (as a symbol) and a function to apply to
9456 the value of the drawer property."
9457 (let* ((case-fold-search t)
9458 (inhibit-read-only t)
9459 (inherit? (org-property-inherit-p dprop))
9460 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9461 (global (and inherit? (org--property-global-value dprop nil))))
9462 (org-with-silent-modifications
9463 (org-with-point-at 1
9464 ;; Set global values (e.g., values defined through
9465 ;; "#+PROPERTY:" keywords) to the whole buffer.
9466 (when global (put-text-property (point-min) (point-max) tprop global))
9467 ;; Set local values.
9468 (while (re-search-forward property-re nil t)
9469 (when (org-at-property-p)
9470 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9471 (outline-next-heading))))))
9473 (defun org-refresh-property (tprop p &optional inherit)
9474 "Refresh the buffer text property TPROP from the drawer property P.
9475 The refresh happens only for the current headline, or the whole
9476 sub-tree if optional argument INHERIT is non-nil."
9477 (unless (org-before-first-heading-p)
9479 (org-back-to-heading t)
9480 (let ((start (point))
9481 (end (save-excursion
9482 (if inherit (org-end-of-subtree t t)
9483 (or (outline-next-heading) (point-max))))))
9485 ;; TPROP is a text property symbol.
9486 (put-text-property start end tprop p)
9487 ;; TPROP is an alist with (property . function) elements.
9488 (pcase-dolist (`(,prop . ,f) tprop)
9489 (put-text-property start end prop (funcall f p))))))))
9491 (defun org-refresh-category-properties ()
9492 "Refresh category text properties in the buffer."
9493 (let ((case-fold-search t)
9494 (inhibit-read-only t)
9496 (cond ((null org-category)
9497 (if buffer-file-name
9498 (file-name-sans-extension
9499 (file-name-nondirectory buffer-file-name))
9501 ((symbolp org-category) (symbol-name org-category))
9503 (org-with-silent-modifications
9504 (org-with-wide-buffer
9505 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9506 ;; This is the default category for the buffer. If none is
9507 ;; found, fall-back to `org-category' or buffer file name.
9509 (point-min) (point-max)
9511 (catch 'buffer-category
9512 (goto-char (point-max))
9513 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9514 (let ((element (org-element-at-point)))
9515 (when (eq (org-element-type element) 'keyword)
9516 (throw 'buffer-category
9517 (org-element-property :value element)))))
9519 ;; Set sub-tree specific categories.
9520 (goto-char (point-min))
9521 (let ((regexp (org-re-property "CATEGORY")))
9522 (while (re-search-forward regexp nil t)
9523 (let ((value (match-string-no-properties 3)))
9524 (when (org-at-property-p)
9526 (save-excursion (org-back-to-heading t) (point))
9527 (save-excursion (org-end-of-subtree t t) (point))
9531 (defun org-refresh-stats-properties ()
9532 "Refresh stats text properties in the buffer."
9533 (org-with-silent-modifications
9534 (org-with-point-at 1
9535 (let ((regexp (concat org-outline-regexp-bol
9536 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9537 (while (re-search-forward regexp nil t)
9538 (let* ((numerator (string-to-number (match-string 1)))
9539 (denominator (and (match-end 2)
9540 (string-to-number (match-string 2))))
9541 (stats (cond ((not denominator) numerator) ;percent
9542 ((= denominator 0) 0)
9543 (t (/ (* numerator 100) denominator)))))
9544 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9545 'org-stats stats)))))))
9547 (defun org-refresh-effort-properties ()
9548 "Refresh effort properties"
9549 (org-refresh-properties
9551 '((effort . identity)
9552 (effort-minutes . org-duration-to-minutes))))
9556 ;;; Link abbreviations
9558 (defun org-link-expand-abbrev (link)
9559 "Apply replacements as defined in `org-link-abbrev-alist'."
9560 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9561 (let* ((key (match-string 1 link))
9562 (as (or (assoc key org-link-abbrev-alist-local)
9563 (assoc key org-link-abbrev-alist)))
9564 (tag (and (match-end 2) (match-string 3 link)))
9570 ((symbolp rpl) (funcall rpl tag))
9571 ((string-match "%(\\([^)]+\\))" rpl)
9574 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9575 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9576 ((string-match "%h" rpl)
9577 (replace-match (url-hexify-string (or tag "")) t t rpl))
9578 (t (concat rpl tag)))))
9581 ;;; Storing and inserting links
9583 (defvar org-insert-link-history nil
9584 "Minibuffer history for links inserted with `org-insert-link'.")
9586 (defvar org-stored-links nil
9587 "Contains the links stored with `org-store-link'.")
9589 (defvar org-store-link-plist nil
9590 "Plist with info about the most recently link created with `org-store-link'.")
9592 (defun org-store-link-functions ()
9593 "Return a list of functions that are called to create and store a link.
9594 The functions defined in the :store property of
9595 `org-link-parameters'.
9597 Each function will be called in turn until one returns a non-nil
9598 value. Each function should check if it is responsible for
9599 creating this link (for example by looking at the major mode).
9600 If not, it must exit and return nil. If yes, it should return
9601 a non-nil value after calling `org-store-link-props' with a list
9602 of properties and values. Special properties are:
9604 :type The link prefix, like \"http\". This must be given.
9605 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9606 This is obligatory as well.
9607 :description Optional default description for the second pair
9608 of brackets in an Org mode link. The user can still change
9609 this when inserting this link into an Org mode buffer.
9611 In addition to these, any additional properties can be specified
9612 and then used in capture templates."
9613 (cl-loop for link in org-link-parameters
9615 do (setq store-func (org-link-get-parameter (car link) :store))
9617 collect store-func))
9619 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9620 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9623 (defun org-store-link (arg)
9624 "Store an org-link to the current location.
9626 This link is added to `org-stored-links' and can later be inserted
9627 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9629 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9631 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9632 `org-gnus-prefer-web-links' for links to Usenet articles.
9634 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9635 skipping storing functions that are not
9638 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9639 prefix ARG forces storing a link for each line in the
9642 (org-load-modules-maybe)
9643 (if (and (equal arg '(64)) (org-region-active-p))
9645 (let ((end (region-end)))
9646 (goto-char (region-beginning))
9648 (while (< (point-at-eol) end)
9649 (move-end-of-line 1) (activate-mark)
9650 (let (current-prefix-arg)
9651 (call-interactively 'org-store-link))
9652 (move-beginning-of-line 2)
9653 (set-mark (point)))))
9654 (setq org-store-link-plist nil)
9655 (let (link cpltxt desc description search txt custom-id agenda-link)
9657 ;; Store a link using an external link type, if any function is
9658 ;; available. If more than one can generate a link from current
9659 ;; location, ask which one to use.
9660 ((and (not (equal arg '(16)))
9661 (let ((results-alist nil))
9662 (dolist (f (org-store-link-functions))
9664 ;; XXX: return value is not link's plist, so we
9665 ;; store the new value before it is modified. It
9666 ;; would be cleaner to ask store link functions to
9667 ;; return the plist instead.
9668 (push (cons f (copy-sequence org-store-link-plist))
9670 (pcase results-alist
9672 (`((,_ . ,_)) t) ;single choice: nothing to do
9673 (`((,name . ,_) . ,_)
9674 ;; Reinstate link plist associated to the chosen
9676 (apply #'org-store-link-props
9679 "Which function for creating the link? "
9680 (mapcar #'car results-alist) nil t name)
9683 (setq link (plist-get org-store-link-plist :link))
9684 (setq desc (or (plist-get org-store-link-plist :description)
9687 ;; Store a link from a source code buffer.
9688 ((org-src-edit-buffer-p)
9689 (let ((coderef-format (org-src-coderef-format)))
9690 (cond ((save-excursion
9692 (looking-at (org-src-coderef-regexp coderef-format)))
9693 (setq link (format "(%s)" (match-string-no-properties 3))))
9694 ((called-interactively-p 'any)
9695 (let ((label (read-string "Code line label: ")))
9697 (setq link (format coderef-format label))
9698 (let ((gc (- 79 (length link))))
9699 (if (< (current-column) gc)
9700 (org-move-to-column gc t)
9703 (setq link (concat "(" label ")"))
9705 (t (setq link nil)))))
9707 ;; We are in the agenda, link to referenced location
9708 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9709 (let ((m (or (get-text-property (point) 'org-hd-marker)
9710 (get-text-property (point) 'org-marker))))
9712 (org-with-point-at m
9714 (if (called-interactively-p 'any)
9715 (call-interactively 'org-store-link)
9716 (org-store-link nil)))))))
9718 ((eq major-mode 'calendar-mode)
9719 (let ((cd (calendar-cursor-to-date)))
9722 (car org-time-stamp-formats)
9724 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9726 (org-store-link-props :type "calendar" :date cd)))
9728 ((eq major-mode 'help-mode)
9729 (setq link (concat "help:" (save-excursion
9730 (goto-char (point-min))
9731 (looking-at "^[^ ]+")
9733 (org-store-link-props :type "help"))
9735 ((eq major-mode 'w3-mode)
9736 (setq cpltxt (if (and (buffer-name)
9737 (not (string-match "Untitled" (buffer-name))))
9740 link (url-view-url t))
9741 (org-store-link-props :type "w3" :url (url-view-url t)))
9743 ((eq major-mode 'image-mode)
9744 (setq cpltxt (concat "file:"
9745 (abbreviate-file-name buffer-file-name))
9747 (org-store-link-props :type "image" :file buffer-file-name))
9749 ;; In dired, store a link to the file of the current line
9750 ((derived-mode-p 'dired-mode)
9751 (let ((file (dired-get-filename nil t)))
9753 (abbreviate-file-name
9754 (expand-file-name (dired-get-filename nil t)))
9755 ;; otherwise, no file so use current directory.
9757 (setq cpltxt (concat "file:" file)
9760 ((setq search (run-hook-with-args-until-success
9761 'org-create-file-search-functions))
9762 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9764 (setq cpltxt (or description link)))
9766 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9767 (org-with-limited-levels
9768 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9770 ;; Store a link using the target at point
9771 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9774 (abbreviate-file-name
9775 (buffer-file-name (buffer-base-buffer)))
9776 "::" (match-string 1))
9778 ((and (featurep 'org-id)
9779 (or (eq org-id-link-to-org-use-id t)
9780 (and (called-interactively-p 'any)
9781 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9782 (and (eq org-id-link-to-org-use-id
9783 'create-if-interactive-and-no-custom-id)
9785 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9786 ;; Store a link using the ID at point
9787 (setq link (condition-case nil
9788 (prog1 (org-id-store-link)
9789 (setq desc (or (plist-get org-store-link-plist
9793 ;; Probably before first headline, link only to file
9795 (abbreviate-file-name
9796 (buffer-file-name (buffer-base-buffer))))))))
9798 ;; Just link to current headline
9799 (setq cpltxt (concat "file:"
9800 (abbreviate-file-name
9801 (buffer-file-name (buffer-base-buffer)))))
9802 ;; Add a context search string
9803 (when (org-xor org-context-in-file-links
9805 (let* ((element (org-element-at-point))
9806 (name (org-element-property :name element)))
9808 ((org-at-heading-p) nil)
9810 ((org-region-active-p)
9811 (buffer-substring (region-beginning) (region-end)))))
9812 (when (or (null txt) (string-match "\\S-" txt))
9816 (org-make-org-heading-search-string txt)
9819 (nth 4 (ignore-errors (org-heading-components)))
9821 (when (string-match "::\\'" cpltxt)
9822 (setq cpltxt (substring cpltxt 0 -2)))
9823 (setq link cpltxt)))))
9825 ((buffer-file-name (buffer-base-buffer))
9826 ;; Just link to this file here.
9827 (setq cpltxt (concat "file:"
9828 (abbreviate-file-name
9829 (buffer-file-name (buffer-base-buffer)))))
9830 ;; Add a context string.
9831 (when (org-xor org-context-in-file-links
9833 (setq txt (if (org-region-active-p)
9834 (buffer-substring (region-beginning) (region-end))
9835 (buffer-substring (point-at-bol) (point-at-eol))))
9836 ;; Only use search option if there is some text.
9837 (when (string-match "\\S-" txt)
9839 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9843 ((called-interactively-p 'interactive)
9844 (user-error "No method for storing a link from this buffer"))
9846 (t (setq link nil)))
9848 ;; We're done setting link and desc, clean up
9849 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9850 (setq link (or link cpltxt)
9851 desc (or desc cpltxt))
9853 ((equal desc "NONE") (setq desc nil))
9855 (replace-regexp-in-string
9856 org-bracket-link-analytic-regexp
9857 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9860 (if (not (and (or (called-interactively-p 'any)
9861 executing-kbd-macro)
9863 (or agenda-link (and link (org-make-link-string link desc)))
9864 (push (list link desc) org-stored-links)
9865 (message "Stored: %s" (or desc link))
9867 (setq link (concat "file:" (abbreviate-file-name
9868 (buffer-file-name)) "::#" custom-id))
9869 (push (list link desc) org-stored-links))
9870 (car org-stored-links)))))
9872 (defun org-store-link-props (&rest plist)
9873 "Store link properties.
9874 The properties are pre-processed by extracting names, addresses
9876 (let ((x (plist-get plist :from)))
9878 (let ((adr (mail-extract-address-components x)))
9879 (setq plist (plist-put plist :fromname (car adr)))
9880 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9881 (let ((x (plist-get plist :to)))
9883 (let ((adr (mail-extract-address-components x)))
9884 (setq plist (plist-put plist :toname (car adr)))
9885 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9886 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9888 (setq plist (plist-put plist :date-timestamp
9890 (org-time-stamp-format t) x)))
9891 (setq plist (plist-put plist :date-timestamp-inactive
9893 (org-time-stamp-format t t) x)))))
9894 (let ((from (plist-get plist :from))
9895 (to (plist-get plist :to)))
9896 (when (and from to org-from-is-user-regexp)
9898 (plist-put plist :fromto
9899 (if (string-match org-from-is-user-regexp from)
9901 (concat "from %f"))))))
9902 (setq org-store-link-plist plist))
9904 (defun org-add-link-props (&rest plist)
9905 "Add these properties to the link property list."
9908 (setq key (pop plist) value (pop plist))
9909 (setq org-store-link-plist
9910 (plist-put org-store-link-plist key value)))))
9912 (defun org-email-link-description (&optional fmt)
9913 "Return the description part of an email link.
9914 This takes information from `org-store-link-plist' and formats it
9915 according to FMT (default from `org-email-link-description-format')."
9916 (setq fmt (or fmt org-email-link-description-format))
9917 (let* ((p org-store-link-plist)
9918 (to (plist-get p :toaddress))
9919 (from (plist-get p :fromaddress))
9922 (cons "%c" (plist-get p :fromto))
9923 (cons "%F" (plist-get p :from))
9924 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9925 (cons "%T" (plist-get p :to))
9926 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9927 (cons "%s" (plist-get p :subject))
9928 (cons "%d" (plist-get p :date))
9929 (cons "%m" (plist-get p :message-id)))))
9930 (when (string-match "%c" fmt)
9931 ;; Check if the user wrote this message
9932 (if (and org-from-is-user-regexp from to
9933 (save-match-data (string-match org-from-is-user-regexp from)))
9934 (setq fmt (replace-match "to %t" t t fmt))
9935 (setq fmt (replace-match "from %f" t t fmt))))
9936 (org-replace-escapes fmt table)))
9938 (defun org-make-org-heading-search-string (&optional string)
9939 "Make search string for the current headline or STRING."
9941 (and (derived-mode-p 'org-mode)
9943 (org-back-to-heading t)
9944 (org-element-property :raw-value (org-element-at-point))))))
9945 (lines org-context-in-file-links))
9946 (unless string (setq s (concat "*" s))) ;Add * for headlines
9947 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9948 (when (and string (integerp lines) (> lines 0))
9949 (let ((slines (org-split-string s "\n")))
9950 (when (< lines (length slines))
9953 (reverse (nthcdr (- (length slines) lines)
9954 (reverse slines))) "\n")))))
9955 (mapconcat #'identity (split-string s) " ")))
9957 (defconst org-link-escape-chars
9960 "List of characters that should be escaped in a link when stored to Org.
9961 This is the list that is used for internal purposes.")
9963 (defun org-make-link-string (link &optional description)
9964 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9965 (unless (org-string-nw-p link) (error "Empty link"))
9966 (let ((uri (cond ((string-match org-link-types-re link)
9967 (concat (match-string 1 link)
9968 (org-link-escape (substring link (match-end 1)))))
9969 ((or (file-name-absolute-p link)
9970 (string-match-p "\\`\\.\\.?/" link))
9971 (org-link-escape link))
9972 ;; For readability, do not encode space characters
9974 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9976 (and (org-string-nw-p description)
9977 ;; Remove brackets from description, as they are fatal.
9978 (replace-regexp-in-string
9979 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9980 (org-trim description)))))
9983 (if description (format "[%s]" description) ""))))
9985 (defun org-link-escape (text &optional table merge)
9986 "Return percent escaped representation of TEXT.
9987 TEXT is a string with the text to escape.
9988 Optional argument TABLE is a list with characters that should be
9989 escaped. When nil, `org-link-escape-chars' is used.
9990 If optional argument MERGE is set, merge TABLE into
9991 `org-link-escape-chars'."
9992 (let ((characters-to-encode
9993 (cond ((null table) org-link-escape-chars)
9994 (merge (append org-link-escape-chars table))
9998 (if (or (memq c characters-to-encode)
9999 (and org-url-hexify-p (or (< c 32) (> c 126))))
10000 (mapconcat (lambda (e) (format "%%%.2X" e))
10001 (or (encode-coding-char c 'utf-8)
10002 (error "Unable to percent escape character: %c" c))
10004 (char-to-string c)))
10007 (defun org-link-unescape (str)
10008 "Unhex hexified Unicode parts in string STR.
10009 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10010 reciprocal of `org-link-escape', which see."
10011 (if (org-string-nw-p str)
10012 (replace-regexp-in-string
10013 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10016 (defun org-link-unescape-compound (hex)
10017 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10018 Note: this function also decodes single byte encodings like
10019 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10021 (let* ((bytes (cdr (split-string hex "%")))
10026 (let* ((val (string-to-number (pop bytes) 16))
10030 ((>= val 252) (cons 6 252))
10031 ((>= val 248) (cons 5 248))
10032 ((>= val 240) (cons 4 240))
10033 ((>= val 224) (cons 3 224))
10034 ((>= val 192) (cons 2 192))
10037 (when (>= val 192) (setq eat (car shift-xor)))
10038 (setq val (logxor val (cdr shift-xor)))
10039 (setq sum (+ (lsh sum (car shift-xor)) val))
10040 (when (> eat 0) (setq eat (- eat 1)))
10042 ((= 0 eat) ;multi byte
10043 (setq ret (concat ret (char-to-string sum)))
10045 ((not bytes) ; single byte(s)
10046 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10049 (defun org-link-unescape-single-byte-sequence (hex)
10050 "Unhexify hex-encoded single byte character sequences."
10051 (mapconcat (lambda (byte)
10052 (char-to-string (string-to-number byte 16)))
10053 (cdr (split-string hex "%")) ""))
10055 (defun org-xor (a b)
10059 (defun org-fixup-message-id-for-http (s)
10060 "Replace special characters in a message id, so it can be used in an http query."
10061 (when (string-match "%" s)
10062 (setq s (mapconcat (lambda (c)
10065 (char-to-string c)))
10067 (while (string-match "<" s)
10068 (setq s (replace-match "%3C" t t s)))
10069 (while (string-match ">" s)
10070 (setq s (replace-match "%3E" t t s)))
10071 (while (string-match "@" s)
10072 (setq s (replace-match "%40" t t s)))
10075 (defun org-link-prettify (link)
10076 "Return a human-readable representation of LINK.
10077 The car of LINK must be a raw link.
10078 The cdr of LINK must be either a link description or nil."
10079 (let ((desc (or (cadr link) "<no description>")))
10080 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10081 "<" (car link) ">")))
10084 (defun org-insert-link-global ()
10085 "Insert a link like Org mode does.
10086 This command can be called in any mode to insert a link in Org syntax."
10088 (org-load-modules-maybe)
10089 (org-run-like-in-org-mode 'org-insert-link))
10091 (defun org-insert-all-links (arg &optional pre post)
10092 "Insert all links in `org-stored-links'.
10093 When a universal prefix, do not delete the links from `org-stored-links'.
10094 When `ARG' is a number, insert the last N link(s).
10095 `PRE' and `POST' are optional arguments to define a string to
10096 prepend or to append."
10098 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10099 (links (copy-sequence org-stored-links))
10101 (po (or post "\n"))
10103 (if (null org-stored-links)
10104 (message "No link to insert")
10105 (while (and (or (listp arg) (>= arg cnt))
10106 (setq l (if (listp arg)
10108 (pop org-stored-links))))
10109 (setq cnt (1+ cnt))
10111 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10114 (defun org-insert-last-stored-link (arg)
10115 "Insert the last link stored in `org-stored-links'."
10117 (org-insert-all-links arg "" "\n"))
10119 (defun org-link-fontify-links-to-this-file ()
10120 "Fontify links to the current file in `org-stored-links'."
10121 (let ((f (buffer-file-name)) a b)
10122 (setq a (mapcar (lambda(l)
10123 (let ((ll (car l)))
10124 (when (and (string-match "^file:\\(.+\\)::" ll)
10125 (equal f (expand-file-name (match-string 1 ll))))
10128 (when (featurep 'org-id)
10129 (setq b (mapcar (lambda(l)
10130 (let ((ll (car l)))
10131 (when (and (string-match "^id:\\(.+\\)$" ll)
10132 (equal f (expand-file-name
10133 (or (org-id-find-id-file
10134 (match-string 1 ll)) ""))))
10136 org-stored-links)))
10138 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10139 (delq nil (append a b)))))
10141 (defvar org--links-history nil)
10142 (defun org-insert-link (&optional complete-file link-location default-description)
10143 "Insert a link. At the prompt, enter the link.
10145 Completion can be used to insert any of the link protocol prefixes in use.
10147 The history can be used to select a link previously stored with
10148 `org-store-link'. When the empty string is entered (i.e. if you just
10149 press `RET' at the prompt), the link defaults to the most recently
10150 stored link. As `SPC' triggers completion in the minibuffer, you need to
10151 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10153 You will also be prompted for a description, and if one is given, it will
10154 be displayed in the buffer instead of the link.
10156 If there is already a link at point, this command will allow you to edit
10157 link and description parts.
10159 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10161 selected using completion. The path to the file will be relative to the
10162 current directory if the file is in the current directory or a subdirectory.
10163 Otherwise, the link will be the absolute path as completed in the minibuffer
10164 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10165 option `org-link-file-path-type'.
10167 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10168 absolute path even if the file is in
10169 the current directory or below.
10171 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10172 prefix negates `org-keep-stored-link-after-insertion'.
10174 If the LINK-LOCATION parameter is non-nil, this value will be used as
10175 the link location instead of reading one interactively.
10177 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10178 be used as the default description. Otherwise, if
10179 `org-make-link-description-function' is non-nil, this function
10180 will be called with the link target, and the result will be the
10181 default link description."
10183 (let* ((wcf (current-window-configuration))
10184 (origbuf (current-buffer))
10185 (region (when (org-region-active-p)
10186 (buffer-substring (region-beginning) (region-end))))
10187 (remove (and region (list (region-beginning) (region-end))))
10189 (link link-location)
10190 (abbrevs org-link-abbrev-alist-local)
10191 entry all-prefixes auto-desc)
10193 (link-location) ; specified by arg, just use it.
10194 ((org-in-regexp org-bracket-link-regexp 1)
10195 ;; We do have a link at point, and we are going to edit it.
10196 (setq remove (list (match-beginning 0) (match-end 0)))
10197 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10198 (setq link (read-string "Link: "
10200 (match-string-no-properties 1)))))
10201 ((or (org-in-regexp org-angle-link-re)
10202 (org-in-regexp org-plain-link-re))
10203 ;; Convert to bracket link
10204 (setq remove (list (match-beginning 0) (match-end 0))
10205 link (read-string "Link: "
10206 (org-unbracket-string "<" ">" (match-string 0)))))
10207 ((member complete-file '((4) (16)))
10208 ;; Completing read for file names.
10209 (setq link (org-file-complete-link complete-file)))
10211 ;; Read link, with completion for stored links.
10212 (org-link-fontify-links-to-this-file)
10213 (org-switch-to-buffer-other-window "*Org Links*")
10214 (with-current-buffer "*Org Links*"
10216 (insert "Insert a link.
10217 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10218 (when org-stored-links
10219 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10220 (insert (mapconcat 'org-link-prettify
10221 (reverse org-stored-links) "\n")))
10222 (goto-char (point-min)))
10223 (let ((cw (selected-window)))
10224 (select-window (get-buffer-window "*Org Links*" 'visible))
10225 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10226 (unless (pos-visible-in-window-p (point-max))
10227 (org-fit-window-to-buffer))
10228 (and (window-live-p cw) (select-window cw)))
10229 (setq all-prefixes (append (mapcar 'car abbrevs)
10230 (mapcar 'car org-link-abbrev-alist)
10233 ;; Fake a link history, containing the stored links.
10234 (let ((org--links-history
10235 (append (mapcar #'car org-stored-links)
10236 org-insert-link-history)))
10238 (org-completing-read
10241 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10242 (mapcar #'car org-stored-links))
10244 'org--links-history
10245 (caar org-stored-links)))
10246 (unless (org-string-nw-p link) (user-error "No link selected"))
10247 (dolist (l org-stored-links)
10248 (when (equal link (cadr l))
10249 (setq link (car l))
10250 (setq auto-desc t)))
10251 (when (or (member link all-prefixes)
10252 (and (equal ":" (substring link -1))
10253 (member (substring link 0 -1) all-prefixes)
10254 (setq link (substring link 0 -1))))
10255 (setq link (with-current-buffer origbuf
10256 (org-link-try-special-completion link)))))
10257 (set-window-configuration wcf)
10258 (kill-buffer "*Org Links*"))
10259 (setq entry (assoc link org-stored-links))
10260 (or entry (push link org-insert-link-history))
10261 (setq desc (or desc (nth 1 entry)))))
10263 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10264 (not org-keep-stored-link-after-insertion))
10265 (setq org-stored-links (delq (assoc link org-stored-links)
10266 org-stored-links)))
10268 (when (and (string-match org-plain-link-re link)
10269 (not (string-match org-ts-regexp link)))
10270 ;; URL-like link, normalize the use of angular brackets.
10271 (setq link (org-unbracket-string "<" ">" link)))
10273 ;; Check if we are linking to the current file with a search
10274 ;; option If yes, simplify the link by using only the search
10276 (when (and buffer-file-name
10277 (let ((case-fold-search nil))
10278 (string-match "\\`file:\\(.+?\\)::" link)))
10279 (let ((path (match-string-no-properties 1 link))
10280 (search (substring-no-properties link (match-end 0))))
10282 (when (equal (file-truename buffer-file-name) (file-truename path))
10283 ;; We are linking to this same file, with a search option
10284 (setq link search)))))
10286 ;; Check if we can/should use a relative path. If yes, simplify
10288 (let ((case-fold-search nil))
10289 (when (string-match "\\`\\(file\\|docview\\):" link)
10290 (let* ((type (match-string-no-properties 0 link))
10291 (path-start (match-end 0))
10292 (search (and (string-match "::\\(.*\\)\\'" link)
10293 (match-string 1 link)))
10296 (substring-no-properties
10297 link path-start (match-beginning 0))
10298 (substring-no-properties link (match-end 0))))
10301 ((or (eq org-link-file-path-type 'absolute)
10302 (equal complete-file '(16)))
10303 (setq path (abbreviate-file-name (expand-file-name path))))
10304 ((eq org-link-file-path-type 'noabbrev)
10305 (setq path (expand-file-name path)))
10306 ((eq org-link-file-path-type 'relative)
10307 (setq path (file-relative-name path)))
10310 (if (string-match (concat "^" (regexp-quote
10312 (file-name-as-directory
10313 default-directory))))
10314 (expand-file-name path))
10315 ;; We are linking a file with relative path name.
10316 (setq path (substring (expand-file-name path)
10318 (setq path (abbreviate-file-name (expand-file-name path)))))))
10319 (setq link (concat type path (and search (concat "::" search))))
10320 (when (equal desc origpath)
10321 (setq desc path)))))
10324 (let ((initial-input
10326 (default-description)
10327 ((not org-make-link-description-function) desc)
10328 (t (condition-case nil
10329 (funcall org-make-link-description-function link desc)
10331 (message "Can't get link description from `%s'"
10332 (symbol-name org-make-link-description-function))
10335 (setq desc (read-string "Description: " initial-input))))
10337 (unless (string-match "\\S-" desc) (setq desc nil))
10338 (when remove (apply 'delete-region remove))
10339 (insert (org-make-link-string link desc))
10340 ;; Redisplay so as the new link has proper invisible characters.
10343 (defun org-link-try-special-completion (type)
10344 "If there is completion support for link type TYPE, offer it."
10345 (let ((fun (org-link-get-parameter type :complete)))
10346 (if (functionp fun)
10348 (read-string "Link (no completion support): " (concat type ":")))))
10350 (defun org-file-complete-link (&optional arg)
10351 "Create a file link using completion."
10352 (let ((file (read-file-name "File: "))
10353 (pwd (file-name-as-directory (expand-file-name ".")))
10354 (pwd1 (file-name-as-directory (abbreviate-file-name
10355 (expand-file-name ".")))))
10356 (cond ((equal arg '(16))
10358 (abbreviate-file-name (expand-file-name file))))
10360 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10361 (concat "file:" (match-string 1 file)))
10363 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10364 (expand-file-name file))
10366 (match-string 1 (expand-file-name file))))
10367 (t (concat "file:" file)))))
10369 (defun org-completing-read (&rest args)
10370 "Completing-read with SPACE being a normal character."
10371 (let ((enable-recursive-minibuffers t)
10372 (minibuffer-local-completion-map
10373 (copy-keymap minibuffer-local-completion-map)))
10374 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10375 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10376 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10377 'org-time-stamp-inactive)
10378 (apply #'completing-read args)))
10380 ;;; Opening/following a link
10382 (defvar org-link-search-failed nil)
10384 (defvar org-open-link-functions nil
10385 "Hook for functions finding a plain text link.
10386 These functions must take a single argument, the link content.
10387 They will be called for links that look like [[link text][description]]
10388 when LINK TEXT does not have a protocol like \"http:\" and does not look
10389 like a filename (e.g. \"./blue.png\").
10391 These functions will be called *before* Org attempts to resolve the
10392 link by doing text searches in the current buffer - so if you want a
10393 link \"[[target]]\" to still find \"<<target>>\", your function should
10394 handle this as a special case.
10396 When the function does handle the link, it must return a non-nil value.
10397 If it decides that it is not responsible for this link, it must return
10398 nil to indicate that that Org can continue with other options like
10399 exact and fuzzy text search.")
10401 (defun org-next-link (&optional search-backward)
10402 "Move forward to the next link.
10403 If the link is in hidden text, expose it."
10405 (when (and org-link-search-failed (eq this-command last-command))
10406 (goto-char (point-min))
10407 (message "Link search wrapped back to beginning of buffer"))
10408 (setq org-link-search-failed nil)
10409 (let* ((pos (point))
10411 (a (assq :link ct))
10412 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10413 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10414 ((looking-at org-any-link-re)
10415 ;; Don't stay stuck at link without an org-link face
10416 (forward-char (if search-backward -1 1))))
10417 (if (funcall srch-fun org-any-link-re nil t)
10419 (goto-char (match-beginning 0))
10420 (when (org-invisible-p) (org-show-context)))
10422 (setq org-link-search-failed t)
10423 (message "No further link found"))))
10425 (defun org-previous-link ()
10426 "Move backward to the previous link.
10427 If the link is in hidden text, expose it."
10429 (funcall 'org-next-link t))
10431 (defun org-translate-link (s)
10432 "Translate a link string if a translation function has been defined."
10434 (insert (org-trim s))
10435 (org-trim (org-element-interpret-data (org-element-context)))))
10437 (defun org-translate-link-from-planner (type path)
10438 "Translate a link from Emacs Planner syntax so that Org can follow it.
10439 This is still an experimental function, your mileage may vary."
10441 ((member type '("http" "https" "news" "ftp"))
10442 ;; standard Internet links are the same.
10444 ((and (equal type "irc") (string-match "^//" path))
10445 ;; Planner has two / at the beginning of an irc link, we have 1.
10446 ;; We should have zero, actually....
10447 (setq path (substring path 1)))
10448 ((and (equal type "lisp") (string-match "^/" path))
10449 ;; Planner has a slash, we do not.
10450 (setq type "elisp" path (substring path 1)))
10451 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10452 ;; A typical message link. Planner has the id after the final slash,
10453 ;; we separate it with a hash mark
10454 (setq path (concat (match-string 1 path) "#"
10455 (org-unbracket-string "<" ">" (match-string 2 path))))))
10458 (defun org-find-file-at-mouse (ev)
10459 "Open file link or URL at mouse."
10461 (mouse-set-point ev)
10462 (org-open-at-point 'in-emacs))
10464 (defun org-open-at-mouse (ev)
10465 "Open file link or URL at mouse.
10466 See the docstring of `org-open-file' for details."
10468 (mouse-set-point ev)
10469 (when (eq major-mode 'org-agenda-mode)
10470 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10471 (org-open-at-point))
10473 (defvar org-window-config-before-follow-link nil
10474 "The window configuration before following a link.
10475 This is saved in case the need arises to restore it.")
10478 (defun org-open-at-point-global ()
10479 "Follow a link or time-stamp like Org mode does.
10480 This command can be called in any mode to follow an external link
10481 or a time-stamp that has Org mode syntax. Its behavior is
10482 undefined when called on internal links (e.g., fuzzy links).
10483 Raise an error when there is nothing to follow. "
10485 (cond ((org-in-regexp org-any-link-re)
10486 (org-open-link-from-string (match-string-no-properties 0)))
10487 ((or (org-in-regexp org-ts-regexp-both nil t)
10488 (org-in-regexp org-tsr-regexp-both nil t))
10489 (org-follow-timestamp-link))
10490 (t (user-error "No link found"))))
10493 (defun org-open-link-from-string (s &optional arg reference-buffer)
10494 "Open a link in the string S, as if it was in Org mode."
10495 (interactive "sLink: \nP")
10496 (let ((reference-buffer (or reference-buffer (current-buffer))))
10498 (let ((org-inhibit-startup (not reference-buffer)))
10501 (goto-char (point-min))
10502 (when reference-buffer
10503 (setq org-link-abbrev-alist-local
10504 (with-current-buffer reference-buffer
10505 org-link-abbrev-alist-local)))
10506 (org-open-at-point arg reference-buffer)))))
10508 (defvar org-open-at-point-functions nil
10509 "Hook that is run when following a link at point.
10511 Functions in this hook must return t if they identify and follow
10512 a link at point. If they don't find anything interesting at point,
10513 they must return nil.")
10515 (defvar org-link-search-inhibit-query nil)
10516 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10517 (defun org--open-doi-link (path)
10518 "Open a \"doi\" type link.
10519 PATH is a the path to search for, as a string."
10520 (browse-url (url-encode-url (concat org-doi-server-url path))))
10522 (defun org--open-elisp-link (path)
10523 "Open a \"elisp\" type link.
10524 PATH is the sexp to evaluate, as a string."
10526 (if (or (and (org-string-nw-p
10527 org-confirm-elisp-link-not-regexp)
10528 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10529 (not org-confirm-elisp-link-function)
10530 (funcall org-confirm-elisp-link-function
10531 (format "Execute \"%s\" as elisp? "
10532 (org-add-props cmd nil 'face 'org-warning))))
10533 (message "%s => %s" cmd
10534 (if (eq (string-to-char cmd) ?\()
10536 (call-interactively (read cmd))))
10537 (user-error "Abort"))))
10539 (defun org--open-help-link (path)
10540 "Open a \"help\" type link.
10541 PATH is a symbol name, as a string."
10542 (pcase (intern path)
10543 ((and (pred fboundp) variable) (describe-function variable))
10544 ((and (pred boundp) function) (describe-variable function))
10545 (name (user-error "Unknown function or variable: %s" name))))
10547 (defun org--open-shell-link (path)
10548 "Open a \"shell\" type link.
10549 PATH is the command to execute, as a string."
10550 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10552 (if (or (and (org-string-nw-p
10553 org-confirm-shell-link-not-regexp)
10555 org-confirm-shell-link-not-regexp cmd))
10556 (not org-confirm-shell-link-function)
10557 (funcall org-confirm-shell-link-function
10558 (format "Execute \"%s\" in shell? "
10559 (org-add-props cmd nil
10560 'face 'org-warning))))
10562 (message "Executing %s" cmd)
10563 (shell-command cmd buf)
10564 (when (featurep 'midnight)
10565 (setq clean-buffer-list-kill-buffer-names
10566 (cons (buffer-name buf)
10567 clean-buffer-list-kill-buffer-names))))
10568 (user-error "Abort"))))
10570 (defun org-open-at-point (&optional arg reference-buffer)
10571 "Open link, timestamp, footnote or tags at point.
10573 When point is on a link, follow it. Normally, files will be
10574 opened by an appropriate application. If the optional prefix
10575 argument ARG is non-nil, Emacs will visit the file. With
10576 a double prefix argument, try to open outside of Emacs, in the
10577 application the system uses for this file type.
10579 When point is on a timestamp, open the agenda at the day
10582 When point is a footnote definition, move to the first reference
10583 found. If it is on a reference, move to the associated
10586 When point is on a headline, display a list of every link in the
10587 entry, so it is possible to pick one, or all, of them. If point
10588 is on a tag, call `org-tags-view' instead.
10590 When optional argument REFERENCE-BUFFER is non-nil, it should
10591 specify a buffer from where the link search should happen. This
10592 is used internally by `org-open-link-from-string'.
10594 On top of syntactically correct links, this function will also
10595 try to open links and time-stamps in comments, example
10596 blocks... i.e., whenever point is on something looking like
10597 a timestamp or a link."
10599 ;; On a code block, open block's results.
10600 (unless (call-interactively 'org-babel-open-src-block-result)
10601 (org-load-modules-maybe)
10602 (setq org-window-config-before-follow-link (current-window-configuration))
10603 (org-remove-occur-highlights nil nil t)
10604 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10606 ;; Only consider supported types, even if they are not
10607 ;; the closest one.
10608 (org-element-lineage
10609 (org-element-context)
10610 '(clock footnote-definition footnote-reference headline
10611 inlinetask link timestamp)
10613 (type (org-element-type context))
10614 (value (org-element-property :value context)))
10616 ;; On a headline or an inlinetask, but not on a timestamp,
10617 ;; a link, a footnote reference.
10618 ((memq type '(headline inlinetask))
10619 (org-match-line org-complex-heading-regexp)
10620 (if (and (match-beginning 5)
10621 (>= (point) (match-beginning 5))
10622 (< (point) (match-end 5)))
10624 (org-tags-view arg (substring (match-string 5) 0 -1))
10626 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10628 (require 'org-attach)
10629 (org-attach-reveal 'if-exists))
10630 (`(,links . ,links-end)
10631 (dolist (link (if (stringp links) (list links) links))
10632 (search-forward link nil links-end)
10633 (goto-char (match-beginning 0))
10634 (org-open-at-point))))))
10635 ;; On a footnote reference or at definition's label.
10636 ((or (eq type 'footnote-reference)
10637 (and (eq type 'footnote-definition)
10639 ;; Do not validate action when point is on the
10640 ;; spaces right after the footnote label, in
10641 ;; order to be on par with behaviour on links.
10642 (skip-chars-forward " \t")
10644 (org-element-property :contents-begin context)))
10645 (if begin (< (point) begin)
10646 (= (org-element-property :post-affiliated context)
10647 (line-beginning-position)))))))
10648 (org-footnote-action))
10649 ;; No valid context. Ignore catch-all types like `headline'.
10650 ;; If point is on something looking like a link or
10651 ;; a time-stamp, try opening it. It may be useful in
10652 ;; comments, example blocks...
10653 ((memq type '(footnote-definition headline inlinetask nil))
10654 (call-interactively #'org-open-at-point-global))
10655 ;; On a clock line, make sure point is on the timestamp
10656 ;; before opening it.
10657 ((and (eq type 'clock)
10659 (>= (point) (org-element-property :begin value))
10660 (<= (point) (org-element-property :end value)))
10661 (org-follow-timestamp-link))
10662 ;; Do nothing on white spaces after an object.
10665 (goto-char (org-element-property :end context))
10666 (skip-chars-backward " \t")
10668 (user-error "No link found"))
10669 ((eq type 'timestamp) (org-follow-timestamp-link))
10671 (let ((type (org-element-property :type context))
10672 (path (org-link-unescape (org-element-property :path context))))
10673 ;; Switch back to REFERENCE-BUFFER needed when called in
10674 ;; a temporary buffer through `org-open-link-from-string'.
10675 (with-current-buffer (or reference-buffer (current-buffer))
10677 ((equal type "file")
10678 (if (string-match "[*?{]" (file-name-nondirectory path))
10680 ;; Look into `org-link-parameters' in order to find
10681 ;; a DEDICATED-FUNCTION to open file. The function
10682 ;; will be applied on raw link instead of parsed
10683 ;; link due to the limitation in `org-add-link-type'
10684 ;; ("open" function called with a single argument).
10685 ;; If no such function is found, fallback to
10686 ;; `org-open-file'.
10687 (let* ((option (org-element-property :search-option context))
10688 (app (org-element-property :application context))
10689 (dedicated-function
10690 (org-link-get-parameter
10691 (if app (concat type "+" app) type)
10693 (if dedicated-function
10694 (funcall dedicated-function
10696 (and option (concat "::" option))))
10697 (apply #'org-open-file
10700 ((equal app "emacs") 'emacs)
10701 ((equal app "sys") 'system))
10702 (cond ((not option) nil)
10703 ((string-match-p "\\`[0-9]+\\'" option)
10704 (list (string-to-number option)))
10706 (org-link-unescape option)))))))))
10707 ((functionp (org-link-get-parameter type :follow))
10708 (funcall (org-link-get-parameter type :follow) path))
10709 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10710 (unless (run-hook-with-args-until-success
10711 'org-open-link-functions path)
10712 (if (not arg) (org-mark-ring-push)
10713 (switch-to-buffer-other-window
10714 (org-get-buffer-for-internal-link (current-buffer))))
10716 (org-with-wide-buffer
10717 (if (equal type "radio")
10718 (org-search-radio-target
10719 (org-element-property :path context))
10721 (if (member type '("custom-id" "coderef"))
10722 (org-element-property :raw-link context)
10724 ;; Prevent fuzzy links from matching
10726 (and (equal type "fuzzy")
10727 (+ 2 (org-element-property :begin context)))))
10729 (unless (and (<= (point-min) destination)
10730 (>= (point-max) destination))
10732 (goto-char destination))))
10733 (t (browse-url-at-point))))))
10734 (t (user-error "No link found")))))
10735 (run-hook-with-args 'org-follow-link-hook)))
10737 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10738 "Offer links in the current entry and return the selected link.
10739 If there is only one link, return it.
10740 If NTH is an integer, return the NTH link found.
10741 If ZERO is a string, check also this string for a link, and if
10742 there is one, return it."
10743 (with-current-buffer buffer
10744 (org-with-wide-buffer
10747 have-zero end links link c)
10748 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10749 (push (match-string 0 zero) links)
10750 (setq cnt (1- cnt) have-zero t))
10752 (org-back-to-heading t)
10753 (setq end (save-excursion (outline-next-heading) (point)))
10754 (while (re-search-forward org-any-link-re end t)
10755 (push (match-string 0) links))
10756 (setq links (org-uniquify (reverse links))))
10759 (message "No links"))
10760 ((equal (length links) 1)
10761 (setq link (car links)))
10762 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10763 (setq link (nth (if have-zero nth (1- nth)) links)))
10764 (t ; we have to select a link
10766 (save-window-excursion
10767 (delete-other-windows)
10768 (with-output-to-temp-buffer "*Select Link*"
10771 ((not (string-match org-bracket-link-regexp l))
10772 (princ (format "[%c] %s\n" (cl-incf cnt)
10773 (org-unbracket-string "<" ">" l))))
10775 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10776 (match-string 3 l) (match-string 1 l))))
10777 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10778 (match-string 1 l)))))))
10779 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10780 (message "Select link to open, RET to open all:")
10781 (setq c (read-char-exclusive))
10782 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10783 (when (equal c ?q) (user-error "Abort"))
10784 (if (equal c ?\C-m)
10786 (setq nth (- c ?0))
10787 (when have-zero (setq nth (1+ nth)))
10788 (unless (and (integerp nth) (>= (length links) nth))
10789 (user-error "Invalid link selection"))
10790 (setq link (nth (1- nth) links)))))
10791 (cons link end)))))
10793 ;; TODO: These functions are deprecated since `org-open-at-point'
10794 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10795 (defun org-open-file-with-system (path)
10796 "Open file at PATH using the system way of opening it."
10797 (org-open-file path 'system))
10798 (defun org-open-file-with-emacs (path)
10799 "Open file at PATH in Emacs."
10800 (org-open-file path 'emacs))
10805 (defvar org-create-file-search-functions nil
10806 "List of functions to construct the right search string for a file link.
10807 These functions are called in turn with point at the location to
10808 which the link should point.
10810 A function in the hook should first test if it would like to
10811 handle this file type, for example by checking the `major-mode'
10812 or the file extension. If it decides not to handle this file, it
10813 should just return nil to give other functions a chance. If it
10814 does handle the file, it must return the search string to be used
10815 when following the link. The search string will be part of the
10816 file link, given after a double colon, and `org-open-at-point'
10817 will automatically search for it. If special measures must be
10818 taken to make the search successful, another function should be
10819 added to the companion hook `org-execute-file-search-functions',
10822 A function in this hook may also use `setq' to set the variable
10823 `description' to provide a suggestion for the descriptive text to
10824 be used for this link when it gets inserted into an Org buffer
10825 with \\[org-insert-link].")
10827 (defvar org-execute-file-search-functions nil
10828 "List of functions to execute a file search triggered by a link.
10830 Functions added to this hook must accept a single argument, the
10831 search string that was part of the file link, the part after the
10832 double colon. The function must first check if it would like to
10833 handle this search, for example by checking the `major-mode' or
10834 the file extension. If it decides not to handle this search, it
10835 should just return nil to give other functions a chance. If it
10836 does handle the search, it must return a non-nil value to keep
10837 other functions from trying.
10839 Each function can access the current prefix argument through the
10840 variable `current-prefix-arg'. Note that a single prefix is used
10841 to force opening a link in Emacs, so it may be good to only use a
10842 numeric or double prefix to guide the search function.
10844 In case this is needed, a function in this hook can also restore
10845 the window configuration before `org-open-at-point' was called using:
10847 (set-window-configuration org-window-config-before-follow-link)")
10849 (defun org-search-radio-target (target)
10850 "Search a radio target matching TARGET in current buffer.
10851 White spaces are not significant."
10852 (let ((re (format "<<<%s>>>"
10853 (mapconcat #'regexp-quote
10854 (split-string target)
10855 "[ \t]+\\(?:\n[ \t]*\\)?")))
10857 (goto-char (point-min))
10858 (catch :radio-match
10859 (while (re-search-forward re nil t)
10861 (let ((object (org-element-context)))
10862 (when (eq (org-element-type object) 'radio-target)
10863 (goto-char (org-element-property :begin object))
10864 (org-show-context 'link-search)
10865 (throw :radio-match nil))))
10867 (user-error "No match for radio target: %s" target))))
10869 (defun org-link-search (s &optional avoid-pos stealth)
10870 "Search for a search string S.
10872 If S starts with \"#\", it triggers a custom ID search.
10874 If S is enclosed within parenthesis, it initiates a coderef
10877 If S is surrounded by forward slashes, it is interpreted as
10878 a regular expression. In Org mode files, this will create an
10879 `org-occur' sparse tree. In ordinary files, `occur' will be used
10880 to list matches. If the current buffer is in `dired-mode', grep
10881 will be used to search in all files.
10883 When AVOID-POS is given, ignore matches near that position.
10885 When optional argument STEALTH is non-nil, do not modify
10886 visibility around point, thus ignoring `org-show-context-detail'
10889 Search is case-insensitive and ignores white spaces. Return type
10890 of matched result, which is either `dedicated' or `fuzzy'."
10891 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10892 (let* ((case-fold-search t)
10894 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10895 (starred (eq (string-to-char normalized) ?*))
10896 (words (split-string (if starred (substring s 1) s)))
10897 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10898 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10901 ;; Check if there are any special search functions.
10902 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10903 ((eq (string-to-char s) ?#)
10904 ;; Look for a custom ID S if S starts with "#".
10905 (let* ((id (substring normalized 1))
10906 (match (org-find-property "CUSTOM_ID" id)))
10907 (if match (progn (goto-char match) (setf type 'dedicated))
10908 (error "No match for custom ID: %s" id))))
10909 ((string-match "\\`(\\(.*\\))\\'" normalized)
10910 ;; Look for coderef targets if S is enclosed within parenthesis.
10911 (let ((coderef (match-string-no-properties 1 normalized))
10912 (re (substring s-single-re 1 -1)))
10913 (goto-char (point-min))
10914 (catch :coderef-match
10915 (while (re-search-forward re nil t)
10916 (let ((element (org-element-at-point)))
10917 (when (and (memq (org-element-type element)
10918 '(example-block src-block))
10919 ;; Build proper regexp according to current
10920 ;; block's label format.
10923 (or (org-element-property :label-fmt element)
10924 org-coderef-label-format))))
10926 (beginning-of-line)
10927 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10928 (format label-fmt coderef))))))
10929 (setq type 'dedicated)
10930 (goto-char (match-beginning 1))
10931 (throw :coderef-match nil))))
10933 (error "No match for coderef: %s" coderef))))
10934 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10935 ;; Look for a regular expression.
10936 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10937 (match-string 1 s)))
10938 ;; From here, we handle fuzzy links.
10940 ;; Look for targets, only if not in a headline search.
10941 ((and (not starred)
10942 (let ((target (format "<<%s>>" s-multi-re)))
10943 (catch :target-match
10944 (goto-char (point-min))
10945 (while (re-search-forward target nil t)
10947 (let ((context (org-element-context)))
10948 (when (eq (org-element-type context) 'target)
10949 (setq type 'dedicated)
10950 (goto-char (org-element-property :begin context))
10951 (throw :target-match t))))
10953 ;; Look for elements named after S, only if not in a headline
10955 ((and (not starred)
10956 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10958 (goto-char (point-min))
10959 (while (re-search-forward name nil t)
10960 (let ((element (org-element-at-point)))
10963 (org-element-property :name element)))
10964 (setq type 'dedicated)
10965 (beginning-of-line)
10966 (throw :name-match t))))
10968 ;; Regular text search. Prefer headlines in Org mode buffers.
10969 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10970 ;; statistics cookies and tags.
10971 ((and (derived-mode-p 'org-mode)
10973 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10974 org-outline-regexp-bol
10976 (mapconcat #'regexp-quote words ".+")))
10977 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10978 (comment-re (eval-when-compile
10979 (format "\\`%s[ \t]+" org-comment-string))))
10980 (goto-char (point-min))
10982 (while (re-search-forward title-re nil t)
10985 (replace-regexp-in-string
10987 (replace-regexp-in-string
10988 comment-re "" (org-get-heading t t t)))))
10991 (beginning-of-line)
10992 (setq type 'dedicated))
10993 ;; Offer to create non-existent headline depending on
10994 ;; `org-link-search-must-match-exact-headline'.
10995 ((and (derived-mode-p 'org-mode)
10996 (not org-link-search-inhibit-query)
10997 (eq org-link-search-must-match-exact-headline 'query-to-create)
10998 (yes-or-no-p "No match - create this as a new heading? "))
10999 (goto-char (point-max))
11000 (unless (bolp) (newline))
11001 (org-insert-heading nil t t)
11003 (beginning-of-line 0))
11004 ;; Only headlines are looked after. No need to process
11005 ;; further: throw an error.
11006 ((and (derived-mode-p 'org-mode)
11007 (or starred org-link-search-must-match-exact-headline))
11009 (error "No match for fuzzy expression: %s" normalized))
11010 ;; Regular text search.
11011 ((catch :fuzzy-match
11012 (goto-char (point-min))
11013 (while (re-search-forward s-multi-re nil t)
11014 ;; Skip match if it contains AVOID-POS or it is included in
11015 ;; a link with a description but outside the description.
11016 (unless (or (and avoid-pos
11017 (<= (match-beginning 0) avoid-pos)
11018 (> (match-end 0) avoid-pos))
11019 (and (save-match-data
11020 (org-in-regexp org-bracket-link-regexp))
11021 (match-beginning 3)
11022 (or (> (match-beginning 3) (point))
11023 (<= (match-end 3) (point)))
11024 (org-element-lineage
11025 (save-match-data (org-element-context))
11027 (goto-char (match-beginning 0))
11029 (throw :fuzzy-match t)))
11031 ;; All failed. Throw an error.
11032 (t (goto-char origin)
11033 (error "No match for fuzzy expression: %s" normalized)))
11034 ;; Disclose surroundings of match, if appropriate.
11035 (when (and (derived-mode-p 'org-mode) (not stealth))
11036 (org-show-context 'link-search))
11039 (defun org-get-buffer-for-internal-link (buffer)
11040 "Return a buffer to be used for displaying the link target of internal links."
11042 ((not org-display-internal-link-with-indirect-buffer)
11044 ((string-suffix-p "(Clone)" (buffer-name buffer))
11045 (message "Buffer is already a clone, not making another one")
11046 ;; we also do not modify visibility in this case
11048 (t ; make a new indirect buffer for displaying the link
11049 (let* ((bn (buffer-name buffer))
11050 (ibn (concat bn "(Clone)"))
11051 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11052 (with-current-buffer ib (org-overview))
11055 (defun org-do-occur (regexp &optional cleanup)
11056 "Call the Emacs command `occur'.
11057 If CLEANUP is non-nil, remove the printout of the regular expression
11058 in the *Occur* buffer. This is useful if the regex is long and not useful
11062 (let ((cwin (selected-window)) win beg end)
11063 (when (setq win (get-buffer-window "*Occur*"))
11064 (select-window win))
11065 (goto-char (point-min))
11066 (when (re-search-forward "match[a-z]+" nil t)
11067 (setq beg (match-end 0))
11068 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11069 (setq end (1- (match-beginning 0)))))
11070 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11071 (goto-char (point-min))
11072 (select-window cwin))))
11074 ;;; The mark ring for links jumps
11076 (defvar org-mark-ring nil
11077 "Mark ring for positions before jumps in Org mode.")
11078 (defvar org-mark-ring-last-goto nil
11079 "Last position in the mark ring used to go back.")
11080 ;; Fill and close the ring
11081 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11082 (dotimes (_ org-mark-ring-length)
11083 (push (make-marker) org-mark-ring))
11084 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11087 (defun org-mark-ring-push (&optional pos buffer)
11088 "Put the current position or POS into the mark ring and rotate it."
11090 (setq pos (or pos (point)))
11091 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11092 (move-marker (car org-mark-ring)
11094 (or buffer (current-buffer)))
11096 (substitute-command-keys
11097 "Position saved to mark ring, go back with \
11098 `\\[org-mark-ring-goto]'.")))
11100 (defun org-mark-ring-goto (&optional n)
11101 "Jump to the previous position in the mark ring.
11102 With prefix arg N, jump back that many stored positions. When
11103 called several times in succession, walk through the entire ring.
11104 Org mode commands jumping to a different position in the current file,
11105 or to another Org file, automatically push the old position onto the ring."
11108 (if (eq last-command this-command)
11109 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11110 (setq p org-mark-ring))
11111 (setq org-mark-ring-last-goto p)
11113 (pop-to-buffer-same-window (marker-buffer m))
11115 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11117 (defun org-add-angle-brackets (s)
11118 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11119 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11122 ;;; Following specific links
11124 (defvar org-agenda-buffer-tmp-name)
11125 (defvar org-agenda-start-on-weekday)
11126 (defun org-follow-timestamp-link ()
11127 "Open an agenda view for the time-stamp date/range at point."
11129 ((org-at-date-range-p t)
11130 (let ((org-agenda-start-on-weekday)
11131 (t1 (match-string 1))
11132 (t2 (match-string 2)) tt1 tt2)
11133 (setq tt1 (time-to-days (org-time-string-to-time t1))
11134 tt2 (time-to-days (org-time-string-to-time t2)))
11135 (let ((org-agenda-buffer-tmp-name
11136 (format "*Org Agenda(a:%s)"
11137 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11138 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11139 ((org-at-timestamp-p 'lax)
11140 (let ((org-agenda-buffer-tmp-name
11141 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11142 (org-agenda-list nil (time-to-days (org-time-string-to-time
11143 (substring (match-string 1) 0 10)))
11145 (t (error "This should not happen"))))
11148 ;;; Following file links
11149 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11150 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11151 (declare-function mailcap-mime-info
11152 "mailcap" (string &optional request no-decode))
11153 (defvar org-wait nil)
11154 (defun org-open-file (path &optional in-emacs line search)
11155 "Open the file at PATH.
11156 First, this expands any special file name abbreviations. Then the
11157 configuration variable `org-file-apps' is checked if it contains an
11158 entry for this file type, and if yes, the corresponding command is launched.
11160 If no application is found, Emacs simply visits the file.
11162 With optional prefix argument IN-EMACS, Emacs will visit the file.
11163 With a double \\[universal-argument] \\[universal-argument] \
11164 prefix arg, Org tries to avoid opening in Emacs
11165 and to use an external application to visit the file.
11167 Optional LINE specifies a line to go to, optional SEARCH a string
11168 to search for. If LINE or SEARCH is given, the file will be
11169 opened in Emacs, unless an entry from org-file-apps that makes
11170 use of groups in a regexp matches.
11172 If you want to change the way frames are used when following a
11173 link, please customize `org-link-frame-setup'.
11175 If the file does not exist, an error is thrown."
11176 (let* ((file (if (equal path "")
11178 (substitute-in-file-name (expand-file-name path))))
11179 (file-apps (append org-file-apps (org-default-apps)))
11180 (apps (cl-remove-if
11181 'org-file-apps-entry-match-against-dlink-p file-apps))
11182 (apps-dlink (cl-remove-if-not
11183 'org-file-apps-entry-match-against-dlink-p file-apps))
11184 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11185 (dirp (unless remp (file-directory-p file)))
11186 (file (if (and dirp org-open-directory-means-index-dot-org)
11187 (concat (file-name-as-directory file) "index.org")
11189 (a-m-a-p (assq 'auto-mode apps))
11190 (dfile (downcase file))
11191 ;; Reconstruct the original link from the PATH, LINE and
11193 (link (cond (line (concat file "::" (number-to-string line)))
11194 (search (concat file "::" search))
11196 (dlink (downcase link))
11198 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11199 (match-string 1 dfile)))
11200 (save-position-maybe
11201 (let ((old-buffer (current-buffer))
11203 (old-mode major-mode))
11205 (and (derived-mode-p 'org-mode)
11206 (eq old-mode 'org-mode)
11207 (or (not (eq old-buffer (current-buffer)))
11208 (not (eq old-pos (point))))
11209 (org-mark-ring-push old-pos old-buffer)))))
11210 cmd link-match-data)
11212 ((member in-emacs '((16) system))
11213 (setq cmd (cdr (assq 'system apps))))
11214 (in-emacs (setq cmd 'emacs))
11216 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11217 (and dirp (cdr (assq 'directory apps)))
11218 ;; First, try matching against apps-dlink if we
11219 ;; get a match here, store the match data for
11221 (let ((match (assoc-default dlink apps-dlink
11224 (progn (setq link-match-data (match-data))
11226 (progn (setq in-emacs (or in-emacs line search))
11227 nil))) ; if we have no match in apps-dlink,
11228 ; always open the file in emacs if line or search
11229 ; is given (for backwards compatibility)
11230 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11232 (cdr (assoc ext apps))
11233 (cdr (assq t apps))))))
11234 (when (eq cmd 'system)
11235 (setq cmd (cdr (assq 'system apps))))
11236 (when (eq cmd 'default)
11237 (setq cmd (cdr (assoc t apps))))
11238 (when (eq cmd 'mailcap)
11240 (mailcap-parse-mailcaps)
11241 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11242 (command (mailcap-mime-info mime-type)))
11243 (if (stringp command)
11245 (setq cmd 'emacs))))
11246 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11247 (not (file-exists-p file))
11248 (not org-open-non-existing-files))
11249 (user-error "No such file: %s" file))
11251 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11252 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11253 (while (string-match "['\"]%s['\"]" cmd)
11254 (setq cmd (replace-match "%s" t t cmd)))
11255 (setq cmd (replace-regexp-in-string
11257 (shell-quote-argument (convert-standard-filename file))
11261 ;; Replace "%1", "%2" etc. in command with group matches from regex
11263 (let ((match-index 1)
11264 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11265 (set-match-data link-match-data)
11266 (while (<= match-index number-of-groups)
11267 (let ((regex (concat "%" (number-to-string match-index)))
11268 (replace-with (match-string match-index dlink)))
11269 (while (string-match regex cmd)
11270 (setq cmd (replace-match replace-with t t cmd))))
11271 (setq match-index (+ match-index 1)))))
11273 (save-window-excursion
11274 (message "Running %s...done" cmd)
11275 (start-process-shell-command cmd nil cmd)
11276 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11279 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11281 (cond (line (org-goto-line line)
11282 (when (derived-mode-p 'org-mode) (org-reveal)))
11283 (search (condition-case err
11284 (org-link-search search)
11285 ;; Save position before error-ing out so user
11286 ;; can easily move back to the original buffer.
11287 (error (funcall save-position-maybe)
11288 (error (nth 1 err)))))))
11291 (set-match-data link-match-data)
11292 (condition-case nil
11293 (funcall cmd file link)
11294 ;; FIXME: Remove this check when most default installations
11295 ;; of Emacs have at least Org 9.0.
11296 ((debug wrong-number-of-arguments wrong-type-argument
11298 (user-error "Please see Org News for version 9.0 about \
11299 `org-file-apps'--Lisp error: %S" cmd)))))
11301 ;; FIXME: Remove this check when most default installations of
11302 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11303 ;; fall back to `org-link-frame-setup' for an old usage of
11304 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11305 (user-error "Please see Org News for version 9.0 about \
11306 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11307 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11308 (funcall save-position-maybe)))
11310 (defun org-file-apps-entry-match-against-dlink-p (entry)
11311 "This function returns non-nil if `entry' uses a regular
11312 expression which should be matched against the whole link by
11315 It assumes that is the case when the entry uses a regular
11316 expression which has at least one grouping construct and the
11317 action is either a lisp form or a command string containing
11318 `%1', i.e. using at least one subexpression match as a
11320 (let ((selector (car entry))
11321 (action (cdr entry)))
11322 (if (stringp selector)
11323 (and (> (regexp-opt-depth selector) 0)
11324 (or (and (stringp action)
11325 (string-match "%[0-9]" action))
11329 (defun org-default-apps ()
11330 "Return the default applications for this operating system."
11332 ((eq system-type 'darwin)
11333 org-file-apps-defaults-macosx)
11334 ((eq system-type 'windows-nt)
11335 org-file-apps-defaults-windowsnt)
11336 (t org-file-apps-defaults-gnu)))
11338 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11339 "Convert extensions to regular expressions in the cars of LIST.
11340 Also, weed out any non-string entries, because the return value is used
11341 only for regexp matching.
11342 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11343 point to the symbol `emacs', indicating that the file should
11344 be opened in Emacs."
11347 (mapcar (lambda (x)
11348 (unless (not (stringp (car x)))
11349 (if (string-match "\\W" (car x))
11351 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11353 (when add-auto-mode
11354 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11356 (defvar ange-ftp-name-format)
11357 (defun org-file-remote-p (file)
11358 "Test whether FILE specifies a location on a remote system.
11359 Return non-nil if the location is indeed remote.
11361 For example, the filename \"/user@host:/foo\" specifies a location
11362 on the system \"/user@host:\"."
11363 (cond ((fboundp 'file-remote-p)
11364 (file-remote-p file))
11365 ((fboundp 'tramp-handle-file-remote-p)
11366 (tramp-handle-file-remote-p file))
11367 ((and (boundp 'ange-ftp-name-format)
11368 (string-match (car ange-ftp-name-format) file))
11374 (defun org-get-org-file ()
11375 "Read a filename, with default directory `org-directory'."
11376 (let ((default (or org-default-notes-file remember-data-file)))
11377 (read-file-name (format "File name [%s]: " default)
11378 (file-name-as-directory org-directory)
11381 (defun org-notes-order-reversed-p ()
11382 "Check if the current file should receive notes in reversed order."
11384 ((not org-reverse-note-order) nil)
11385 ((eq t org-reverse-note-order) t)
11386 ((not (listp org-reverse-note-order)) nil)
11388 (dolist (entry org-reverse-note-order)
11389 (when (string-match (car entry) buffer-file-name)
11390 (throw 'exit (cdr entry))))))))
11392 (defvar org-refile-target-table nil
11393 "The list of refile targets, created by `org-refile'.")
11395 (defvar org-agenda-new-buffers nil
11396 "Buffers created to visit agenda files.")
11398 (defvar org-refile-cache nil
11399 "Cache for refile targets.")
11401 (defvar org-refile-markers nil
11402 "All the markers used for caching refile locations.")
11404 (defun org-refile-marker (pos)
11405 "Get a new refile marker, but only if caching is in use."
11406 (if (not org-refile-use-cache)
11408 (let ((m (make-marker)))
11409 (move-marker m pos)
11410 (push m org-refile-markers)
11413 (defun org-refile-cache-clear ()
11414 "Clear the refile cache and disable all the markers."
11415 (dolist (m org-refile-markers) (move-marker m nil))
11416 (setq org-refile-markers nil)
11417 (setq org-refile-cache nil)
11418 (message "Refile cache has been cleared"))
11420 (defun org-refile-cache-check-set (set)
11421 "Check if all the markers in the cache still have live buffers."
11424 (while (and set (setq marker (nth 3 (pop set))))
11425 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11426 (when (and marker (null (marker-buffer marker)))
11427 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11429 (throw 'exit nil)))
11432 (defun org-refile-cache-put (set &rest identifiers)
11433 "Push the refile targets SET into the cache, under IDENTIFIERS."
11434 (let* ((key (sha1 (prin1-to-string identifiers)))
11435 (entry (assoc key org-refile-cache)))
11438 (push (cons key set) org-refile-cache))))
11440 (defun org-refile-cache-get (&rest identifiers)
11441 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11443 ((not org-refile-cache) nil)
11444 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11446 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11447 org-refile-cache))))
11448 (and set (org-refile-cache-check-set set) set)))))
11450 (defvar org-outline-path-cache nil
11451 "Alist between buffer positions and outline paths.
11452 It value is an alist (POSITION . PATH) where POSITION is the
11453 buffer position at the beginning of an entry and PATH is a list
11454 of strings describing the outline path for that entry, in reverse
11457 (defun org-refile-get-targets (&optional default-buffer)
11458 "Produce a table with refile targets."
11459 (let ((case-fold-search nil)
11460 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11461 (entries (or org-refile-targets '((nil . (:level . 1)))))
11462 targets tgs files desc descre)
11463 (message "Getting targets...")
11464 (with-current-buffer (or default-buffer (current-buffer))
11465 (dolist (entry entries)
11466 (setq files (car entry) desc (cdr entry))
11468 ((null files) (setq files (list (current-buffer))))
11469 ((eq files 'org-agenda-files)
11470 (setq files (org-agenda-files 'unrestricted)))
11471 ((and (symbolp files) (fboundp files))
11472 (setq files (funcall files)))
11473 ((and (symbolp files) (boundp files))
11474 (setq files (symbol-value files))))
11475 (when (stringp files) (setq files (list files)))
11477 ((eq (car desc) :tag)
11478 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11479 ((eq (car desc) :todo)
11480 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11481 ((eq (car desc) :regexp)
11482 (setq descre (cdr desc)))
11483 ((eq (car desc) :level)
11484 (setq descre (concat "^\\*\\{" (number-to-string
11485 (if org-odd-levels-only
11486 (1- (* 2 (cdr desc)))
11489 ((eq (car desc) :maxlevel)
11490 (setq descre (concat "^\\*\\{1," (number-to-string
11491 (if org-odd-levels-only
11492 (1- (* 2 (cdr desc)))
11495 (t (error "Bad refiling target description %s" desc)))
11497 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11499 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11502 (setq f (buffer-file-name (buffer-base-buffer f))))
11503 (setq f (and f (expand-file-name f)))
11504 (when (eq org-refile-use-outline-path 'file)
11505 (push (list (file-name-nondirectory f) f nil nil) tgs))
11506 (when (eq org-refile-use-outline-path 'buffer-name)
11507 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11508 (when (eq org-refile-use-outline-path 'full-file-path)
11509 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11510 (org-with-wide-buffer
11511 (goto-char (point-min))
11512 (setq org-outline-path-cache nil)
11513 (while (re-search-forward descre nil t)
11514 (beginning-of-line)
11515 (let ((case-fold-search nil))
11516 (looking-at org-complex-heading-regexp))
11517 (let ((begin (point))
11518 (heading (match-string-no-properties 4)))
11520 org-refile-target-verify-function
11522 (funcall org-refile-target-verify-function)))
11524 (let ((re (format org-complex-heading-regexp-format
11525 (regexp-quote heading)))
11527 (if (not org-refile-use-outline-path) heading
11531 (pcase org-refile-use-outline-path
11532 (`file (list (file-name-nondirectory
11534 (buffer-base-buffer)))))
11536 (list (buffer-file-name
11537 (buffer-base-buffer))))
11540 (buffer-base-buffer))))
11542 (mapcar (lambda (s) (replace-regexp-in-string
11543 "/" "\\/" s nil t))
11544 (org-get-outline-path t t)))
11546 (push (list target f re (org-refile-marker (point)))
11548 (when (= (point) begin)
11549 ;; Verification function has not moved point.
11550 (end-of-line)))))))
11551 (when org-refile-use-cache
11552 (org-refile-cache-put tgs (buffer-file-name) descre))
11553 (setq targets (append tgs targets))))))
11554 (message "Getting targets...done")
11555 (delete-dups (nreverse targets))))
11557 (defun org--get-outline-path-1 (&optional use-cache)
11558 "Return outline path to current headline.
11560 Outline path is a list of strings, in reverse order. When
11561 optional argument USE-CACHE is non-nil, make use of a cache. See
11562 `org-get-outline-path' for details.
11564 Assume buffer is widened and point is on a headline."
11565 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11567 (heading (let ((case-fold-search nil))
11568 (looking-at org-complex-heading-regexp)
11569 (if (not (match-end 4)) ""
11570 ;; Remove statistics cookies.
11572 (org-link-display-format
11573 (replace-regexp-in-string
11574 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11575 (match-string-no-properties 4))))))))
11576 (if (org-up-heading-safe)
11577 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11579 (push (cons p path) org-outline-path-cache))
11581 ;; This is a new root node. Since we assume we are moving
11582 ;; forward, we can drop previous cache so as to limit number
11583 ;; of associations there.
11584 (let ((path (list heading)))
11585 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11588 (defun org-get-outline-path (&optional with-self use-cache)
11589 "Return the outline path to the current entry.
11591 An outline path is a list of ancestors for current headline, as
11592 a list of strings. Statistics cookies are removed and links are
11593 replaced with their description, if any, or their path otherwise.
11595 When optional argument WITH-SELF is non-nil, the path also
11596 includes the current headline.
11598 When optional argument USE-CACHE is non-nil, cache outline paths
11599 between calls to this function so as to avoid backtracking. This
11600 argument is useful when planning to find more than one outline
11601 path in the same document. In that case, there are two
11602 conditions to satisfy:
11603 - `org-outline-path-cache' is set to nil before starting the
11605 - outline paths are computed by increasing buffer positions."
11606 (org-with-wide-buffer
11607 (and (or (and with-self (org-back-to-heading t))
11608 (org-up-heading-safe))
11609 (reverse (org--get-outline-path-1 use-cache)))))
11611 (defun org-format-outline-path (path &optional width prefix separator)
11612 "Format the outline path PATH for display.
11613 WIDTH is the maximum number of characters that is available.
11614 PREFIX is a prefix to be included in the returned string,
11615 such as the file name.
11616 SEPARATOR is inserted between the different parts of the path,
11617 the default is \"/\"."
11618 (setq width (or width 79))
11619 (setq path (delq nil path))
11620 (unless (> width 0)
11621 (user-error "Argument `width' must be positive"))
11622 (setq separator (or separator "/"))
11623 (let* ((org-odd-levels-only nil)
11625 prefix (and prefix path separator)
11627 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11628 (cl-loop for head in path
11630 collect (org-add-props
11632 (nth (% n org-n-level-faces) org-level-faces)))
11634 (when (> (length fpath) width)
11636 ;; It's unlikely that `width' will be this small, but don't
11637 ;; waste characters by adding ".." if it is.
11638 (setq fpath (substring fpath 0 width))
11639 (setf (substring fpath (- width 2)) "..")))
11642 (defun org-display-outline-path (&optional file current separator just-return-string)
11643 "Display the current outline path in the echo area.
11645 If FILE is non-nil, prepend the output with the file name.
11646 If CURRENT is non-nil, append the current heading to the output.
11647 SEPARATOR is passed through to `org-format-outline-path'. It separates
11648 the different parts of the path and defaults to \"/\".
11649 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11651 (let* (case-fold-search
11652 (bfn (buffer-file-name (buffer-base-buffer)))
11653 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11655 (when current (setq path (append path
11657 (org-back-to-heading t)
11658 (when (looking-at org-complex-heading-regexp)
11659 (list (match-string 4)))))))
11661 (org-format-outline-path
11664 (and file bfn (concat (file-name-nondirectory bfn) separator))
11666 (if just-return-string
11667 (org-no-properties res)
11668 (org-unlogged-message "%s" res))))
11670 (defvar org-refile-history nil
11671 "History for refiling operations.")
11673 (defvar org-after-refile-insert-hook nil
11674 "Hook run after `org-refile' has inserted its stuff at the new location.
11675 Note that this is still *before* the stuff will be removed from
11676 the *old* location.")
11678 (defvar org-capture-last-stored-marker)
11679 (defvar org-refile-keep nil
11680 "Non-nil means `org-refile' will copy instead of refile.")
11683 "Like `org-refile', but copy."
11685 (let ((org-refile-keep t))
11686 (funcall 'org-refile nil nil nil "Copy")))
11688 (defun org-refile (&optional arg default-buffer rfloc msg)
11689 "Move the entry or entries at point to another heading.
11691 The list of target headings is compiled using the information in
11692 `org-refile-targets', which see.
11694 At the target location, the entry is filed as a subitem of the
11695 target heading. Depending on `org-reverse-note-order', the new
11696 subitem will either be the first or the last subitem.
11698 If there is an active region, all entries in that region will be
11699 refiled. However, the region must fulfill the requirement that
11700 the first heading sets the top-level of the moved text.
11702 With a `\\[universal-argument]' ARG, the command will only visit the target \
11704 and not actually move anything.
11706 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11707 location where the last
11708 refiling operation has put the subtree.
11710 With a numeric prefix argument of `2', refile to the running clock.
11712 With a numeric prefix argument of `3', emulate `org-refile-keep'
11713 being set to t and copy to the target location, don't move it.
11714 Beware that keeping refiled entries may result in duplicated ID
11717 RFLOC can be a refile location obtained in a different way.
11719 MSG is a string to replace \"Refile\" in the default prompt with
11720 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11722 See also `org-refile-use-outline-path'.
11724 If you are using target caching (see `org-refile-use-cache'), you
11725 have to clear the target cache in order to find new targets.
11726 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11727 prefix argument (`C-u C-u C-u C-c C-w')."
11729 (if (member arg '(0 (64)))
11730 (org-refile-cache-clear)
11731 (let* ((actionmsg (cond (msg msg)
11732 ((equal arg 3) "Refile (and keep)")
11734 (regionp (org-region-active-p))
11735 (region-start (and regionp (region-beginning)))
11736 (region-end (and regionp (region-end)))
11737 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11738 pos it nbuf file level reversed)
11739 (setq last-command nil)
11741 (goto-char region-start)
11742 (or (bolp) (goto-char (point-at-bol)))
11743 (setq region-start (point))
11744 (unless (or (org-kill-is-subtree-p
11745 (buffer-substring region-start region-end))
11746 (prog1 org-refile-active-region-within-subtree
11747 (let ((s (point-at-eol)))
11748 (org-toggle-heading)
11749 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11750 (user-error "The region is not a (sequence of) subtree(s)")))
11751 (if (equal arg '(16))
11752 (org-refile-goto-last-stored)
11755 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11757 (setq it (list (or org-clock-heading "running clock")
11759 (marker-buffer org-clock-hd-marker))
11761 (marker-position org-clock-hd-marker)))
11765 (let (heading-text)
11767 (unless (and arg (listp arg))
11768 (org-back-to-heading t)
11770 (replace-regexp-in-string
11771 org-bracket-link-regexp
11773 (or (nth 4 (org-heading-components))
11775 (org-refile-get-location
11776 (cond ((and arg (listp arg)) "Goto")
11777 (regionp (concat actionmsg " region to"))
11778 (t (concat actionmsg " subtree \""
11779 heading-text "\" to")))
11781 (and (not (equal '(4) arg))
11782 org-refile-allow-creating-parent-nodes)))))))
11783 (setq file (nth 1 it)
11785 (when (and (not arg)
11787 (equal (buffer-file-name) file)
11789 (and (>= pos region-start)
11790 (<= pos region-end))
11791 (and (>= pos (point))
11792 (< pos (save-excursion
11793 (org-end-of-subtree t t))))))
11794 (error "Cannot refile to position inside the tree or region"))
11795 (setq nbuf (or (find-buffer-visiting file)
11796 (find-file-noselect file)))
11797 (if (and arg (not (equal arg 3)))
11799 (pop-to-buffer-same-window nbuf)
11800 (goto-char (cond (pos)
11801 ((org-notes-order-reversed-p) (point-min))
11803 (org-show-context 'org-goto))
11806 (org-kill-new (buffer-substring region-start region-end))
11807 (org-save-markers-in-region region-start region-end))
11808 (org-copy-subtree 1 nil t))
11809 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11810 (find-file-noselect file)))
11811 (setq reversed (org-notes-order-reversed-p))
11812 (org-with-wide-buffer
11816 (setq level (org-get-valid-level (funcall outline-level) 1))
11819 (or (outline-next-heading) (point-max))
11820 (or (save-excursion (org-get-next-sibling))
11821 (org-end-of-subtree t t)
11825 (goto-char (point-max))
11826 (goto-char (point-min))
11827 (or (outline-next-heading) (goto-char (point-max)))))
11828 (unless (bolp) (newline))
11829 (org-paste-subtree level nil nil t)
11830 (when org-log-refile
11831 (org-add-log-setup 'refile nil nil org-log-refile)
11832 (unless (eq org-log-refile 'note)
11833 (save-excursion (org-add-log-note))))
11834 (and org-auto-align-tags
11835 (let ((org-loop-over-headlines-in-active-region nil))
11836 (org-set-tags nil t)))
11837 (let ((bookmark-name (plist-get org-bookmark-names-plist
11839 (when bookmark-name
11840 (with-demoted-errors
11841 (bookmark-set bookmark-name))))
11842 ;; If we are refiling for capture, make sure that the
11843 ;; last-capture pointers point here
11844 (when (bound-and-true-p org-capture-is-refiling)
11845 (let ((bookmark-name (plist-get org-bookmark-names-plist
11846 :last-capture-marker)))
11847 (when bookmark-name
11848 (with-demoted-errors
11849 (bookmark-set bookmark-name))))
11850 (move-marker org-capture-last-stored-marker (point)))
11851 (when (fboundp 'deactivate-mark) (deactivate-mark))
11852 (run-hooks 'org-after-refile-insert-hook)))
11853 (unless org-refile-keep
11855 (delete-region (point) (+ (point) (- region-end region-start)))
11857 (and (org-back-to-heading t) (point))
11858 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11859 (when (featurep 'org-inlinetask)
11860 (org-inlinetask-remove-END-maybe))
11861 (setq org-markers-to-move nil)
11862 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11864 (defun org-refile-goto-last-stored ()
11865 "Go to the location where the last refile was stored."
11867 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11868 (message "This is the location of the last refile"))
11870 (defun org-refile--get-location (refloc tbl)
11871 "When user refile to REFLOC, find the associated target in TBL.
11872 Also check `org-refile-target-table'."
11876 (lambda (r) (or (assoc r tbl)
11877 (assoc r org-refile-target-table)))
11878 (list (replace-regexp-in-string "/$" "" refloc)
11879 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11881 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11882 "Prompt the user for a refile location, using PROMPT.
11883 PROMPT should not be suffixed with a colon and a space, because
11884 this function appends the default value from
11885 `org-refile-history' automatically, if that is not empty."
11886 (let ((org-refile-targets org-refile-targets)
11887 (org-refile-use-outline-path org-refile-use-outline-path))
11888 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11889 (unless org-refile-target-table
11890 (user-error "No refile targets"))
11891 (let* ((cbuf (current-buffer))
11892 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11893 (cfunc (if (and org-refile-use-outline-path
11894 org-outline-path-complete-in-steps)
11895 #'org-olpath-completing-read
11896 #'completing-read))
11897 (extra (if org-refile-use-outline-path "/" ""))
11898 (cbnex (concat (buffer-name) extra))
11899 (filename (and cfn (expand-file-name cfn)))
11902 (if (and (not (member org-refile-use-outline-path
11903 '(file full-file-path)))
11904 (not (equal filename (nth 1 x))))
11905 (cons (concat (car x) extra " ("
11906 (file-name-nondirectory (nth 1 x)) ")")
11908 (cons (concat (car x) extra) (cdr x))))
11909 org-refile-target-table))
11910 (completion-ignore-case t)
11912 (prompt (concat prompt
11913 (or (and (car org-refile-history)
11914 (concat " (default " (car org-refile-history) ")"))
11915 (and (assoc cbnex tbl) (setq cdef cbnex)
11916 (concat " (default " cbnex ")"))) ": "))
11917 pa answ parent-target child parent old-hist)
11918 (setq old-hist org-refile-history)
11919 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11920 nil 'org-refile-history (or cdef (car org-refile-history))))
11921 (if (setq pa (org-refile--get-location answ tbl))
11923 (org-refile-check-position pa)
11924 (when (or (not org-refile-history)
11925 (not (eq old-hist org-refile-history))
11926 (not (equal (car pa) (car org-refile-history))))
11927 (setq org-refile-history
11928 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11930 (cdr org-refile-history))))
11931 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11932 (pop org-refile-history)))
11934 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11936 (setq parent (match-string 1 answ)
11937 child (match-string 2 answ))
11938 (setq parent-target (org-refile--get-location parent tbl))
11939 (when (and parent-target
11940 (or (eq new-nodes t)
11941 (and (eq new-nodes 'confirm)
11942 (y-or-n-p (format "Create new node \"%s\"? "
11944 (org-refile-new-child parent-target child)))
11945 (user-error "Invalid target location")))))
11947 (declare-function org-string-nw-p "org-macs" (s))
11948 (defun org-refile-check-position (refile-pointer)
11949 "Check if the refile pointer matches the headline to which it points."
11950 (let* ((file (nth 1 refile-pointer))
11951 (re (nth 2 refile-pointer))
11952 (pos (nth 3 refile-pointer))
11954 (if (and (not (markerp pos)) (not file))
11955 (user-error "Please indicate a target file in the refile path")
11956 (when (org-string-nw-p re)
11957 (setq buffer (if (markerp pos)
11958 (marker-buffer pos)
11959 (or (find-buffer-visiting file)
11960 (find-file-noselect file))))
11961 (with-current-buffer buffer
11962 (org-with-wide-buffer
11964 (beginning-of-line 1)
11965 (unless (looking-at-p re)
11966 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11968 (defun org-refile-new-child (parent-target child)
11969 "Use refile target PARENT-TARGET to add new CHILD below it."
11970 (unless parent-target
11971 (error "Cannot find parent for new node"))
11972 (let ((file (nth 1 parent-target))
11973 (pos (nth 3 parent-target))
11975 (with-current-buffer (or (find-buffer-visiting file)
11976 (find-file-noselect file))
11977 (org-with-wide-buffer
11980 (goto-char (point-max))
11981 (unless (bolp) (newline)))
11982 (when (looking-at org-outline-regexp)
11983 (setq level (funcall outline-level))
11984 (org-end-of-subtree t t))
11985 (org-back-over-empty-lines)
11986 (insert "\n" (make-string
11987 (if pos (org-get-valid-level level 1) 1) ?*)
11989 (beginning-of-line 0)
11990 (list (concat (car parent-target) "/" child) file "" (point))))))
11992 (defun org-olpath-completing-read (prompt collection &rest args)
11993 "Read an outline path like a file name."
11994 (let ((thetable collection))
11995 (apply #'completing-read
11997 (lambda (string predicate &optional flag)
11999 ((eq flag nil) (try-completion string thetable))
12001 (let ((l (length string)))
12002 (mapcar (lambda (x)
12003 (let ((r (substring x l))
12004 (f (if (string-match " ([^)]*)$" x)
12007 (if (string-match "/" r)
12008 (concat string (substring r 0 (match-end 0)) f)
12010 (all-completions string thetable predicate))))
12012 ((eq flag 'lambda) (assoc string thetable))))
12015 ;;;; Dynamic blocks
12017 (defun org-find-dblock (name)
12018 "Find the first dynamic block with name NAME in the buffer.
12019 If not found, stay at current position and return nil."
12020 (let ((case-fold-search t) pos)
12022 (goto-char (point-min))
12023 (setq pos (and (re-search-forward
12024 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12025 (match-beginning 0))))
12026 (when pos (goto-char pos))
12029 (defun org-create-dblock (plist)
12030 "Create a dynamic block section, with parameters taken from PLIST.
12031 PLIST must contain a :name entry which is used as the name of the block."
12032 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12035 (let ((col (current-column))
12036 (name (plist-get plist :name)))
12037 (insert "#+BEGIN: " name)
12039 (if (eq (car plist) :name)
12040 (setq plist (cddr plist))
12041 (insert " " (prin1-to-string (pop plist)))))
12042 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12043 (beginning-of-line -2)))
12045 (defun org-prepare-dblock ()
12046 "Prepare dynamic block for refresh.
12047 This empties the block, puts the cursor at the insert position and returns
12048 the property list including an extra property :name with the block name."
12049 (unless (looking-at org-dblock-start-re)
12050 (user-error "Not at a dynamic block"))
12051 (let* ((begdel (1+ (match-end 0)))
12052 (name (org-no-properties (match-string 1)))
12053 (params (append (list :name name)
12054 (read (concat "(" (match-string 3) ")")))))
12056 (beginning-of-line 1)
12057 (skip-chars-forward " \t")
12058 (setq params (plist-put params :indentation-column (current-column))))
12059 (unless (re-search-forward org-dblock-end-re nil t)
12060 (error "Dynamic block not terminated"))
12063 (list :content (buffer-substring
12064 begdel (match-beginning 0)))))
12065 (delete-region begdel (match-beginning 0))
12070 (defun org-map-dblocks (&optional command)
12071 "Apply COMMAND to all dynamic blocks in the current buffer.
12072 If COMMAND is not given, use `org-update-dblock'."
12073 (let ((cmd (or command 'org-update-dblock)))
12075 (goto-char (point-min))
12076 (while (re-search-forward org-dblock-start-re nil t)
12077 (goto-char (match-beginning 0))
12079 (condition-case nil
12081 (error (message "Error during update of dynamic block"))))
12082 (unless (re-search-forward org-dblock-end-re nil t)
12083 (error "Dynamic block not terminated"))))))
12085 (defun org-dblock-update (&optional arg)
12086 "User command for updating dynamic blocks.
12087 Update the dynamic block at point. With prefix ARG, update all dynamic
12088 blocks in the buffer."
12091 (org-update-all-dblocks)
12092 (or (looking-at org-dblock-start-re)
12093 (org-beginning-of-dblock))
12094 (org-update-dblock)))
12096 (defun org-update-dblock ()
12097 "Update the dynamic block at point.
12098 This means to empty the block, parse for parameters and then call
12099 the correct writing function."
12102 (let* ((win (selected-window))
12104 (line (org-current-line))
12105 (params (org-prepare-dblock))
12106 (name (plist-get params :name))
12107 (indent (plist-get params :indentation-column))
12108 (cmd (intern (concat "org-dblock-write:" name))))
12109 (message "Updating dynamic block `%s' at line %d..." name line)
12110 (funcall cmd params)
12111 (message "Updating dynamic block `%s' at line %d...done" name line)
12113 (when (and indent (> indent 0))
12114 (setq indent (make-string indent ?\ ))
12116 (select-window win)
12117 (org-beginning-of-dblock)
12119 (while (not (looking-at org-dblock-end-re))
12121 (beginning-of-line 2))
12122 (when (looking-at org-dblock-end-re)
12123 (and (looking-at "[ \t]+")
12124 (replace-match ""))
12125 (insert indent)))))))
12127 (defun org-beginning-of-dblock ()
12128 "Find the beginning of the dynamic block at point.
12129 Error if there is no such block at point."
12130 (let ((pos (point))
12133 (if (and (re-search-backward org-dblock-start-re nil t)
12134 (setq beg (match-beginning 0))
12135 (re-search-forward org-dblock-end-re nil t)
12136 (> (match-end 0) pos))
12139 (error "Not in a dynamic block"))))
12141 (defun org-update-all-dblocks ()
12142 "Update all dynamic blocks in the buffer.
12143 This function can be used in a hook."
12145 (when (derived-mode-p 'org-mode)
12146 (org-map-dblocks 'org-update-dblock)))
12151 (declare-function org-export-backend-options "ox" (cl-x) t)
12152 (defun org-get-export-keywords ()
12153 "Return a list of all currently understood export keywords.
12154 Export keywords include options, block names, attributes and
12155 keywords relative to each registered export back-end."
12158 (bound-and-true-p org-export-registered-backends)
12159 (delq nil keywords))
12160 ;; Back-end name (for keywords, like #+LATEX:)
12161 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12162 (dolist (option-entry (org-export-backend-options backend))
12163 ;; Back-end options.
12164 (push (nth 1 option-entry) keywords)))))
12166 (defconst org-options-keywords
12167 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12168 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12169 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12170 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12171 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12173 (defcustom org-structure-template-alist
12174 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12175 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12176 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12177 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12178 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12179 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12180 ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
12181 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12183 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12185 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12188 ("I" "#+INCLUDE: %file ?"))
12189 "Structure completion elements.
12190 This is a list of abbreviation keys and values. The value gets inserted
12191 if you type `<' followed by the key and then press the completion key,
12192 usually `TAB'. %file will be replaced by a file name after prompting
12193 for the file using completion. The cursor will be placed at the position
12194 of the `?' in the template.
12195 There are two templates for each key, the first uses the original Org syntax,
12196 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12197 the default when the /org-mtags.el/ module has been loaded. See also the
12198 variable `org-mtags-prefer-muse-templates'."
12199 :group 'org-edit-structure
12202 (string :tag "Key")
12203 (string :tag "Template")))
12205 :package-version '(Org . "8.3"))
12207 (defun org-try-structure-completion ()
12208 "Try to complete a structure template before point.
12209 This looks for strings like \"<e\" on an otherwise empty line and
12211 (let ((l (buffer-substring (point-at-bol) (point)))
12213 (when (and (looking-at "[ \t]*$")
12214 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12215 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12216 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12217 (match-beginning 1)) a)
12220 (defun org-complete-expand-structure-template (start cell)
12221 "Expand a structure template."
12222 (let ((rpl (nth 1 cell))
12224 (delete-region start (point))
12225 (when (string-match "\\`[ \t]*#\\+" rpl)
12228 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12229 (setq ind (buffer-substring (point-at-bol) (point))))
12231 (setq start (point))
12232 (when (string-match "%file" rpl)
12233 (setq rpl (replace-match
12237 (abbreviate-file-name (read-file-name "Include file: ")))
12240 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12241 (concat "\n" ind)))
12243 (when (re-search-backward "\\?" start t) (delete-char 1))))
12245 ;;;; TODO, DEADLINE, Comments
12247 (defun org-toggle-comment ()
12248 "Change the COMMENT state of an entry."
12251 (org-back-to-heading)
12252 (let ((case-fold-search nil))
12253 (looking-at org-complex-heading-regexp))
12254 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12255 (skip-chars-forward " \t")
12256 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12257 (if (org-in-commented-heading-p t)
12258 (delete-region (point)
12259 (progn (search-forward " " (line-end-position) 'move)
12260 (skip-chars-forward " \t")
12262 (insert org-comment-string)
12263 (unless (eolp) (insert " ")))))
12265 (defvar org-last-todo-state-is-todo nil
12266 "This is non-nil when the last TODO state change led to a TODO state.
12267 If the last change removed the TODO tag or switched to DONE, then
12270 (defvar org-setting-tags nil) ; dynamically skipped
12272 (defvar org-todo-setup-filter-hook nil
12273 "Hook for functions that pre-filter todo specs.
12274 Each function takes a todo spec and returns either nil or the spec
12275 transformed into canonical form." )
12277 (defvar org-todo-get-default-hook nil
12278 "Hook for functions that get a default item for todo.
12279 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12280 nil or a string to be used for the todo mark." )
12282 (defvar org-agenda-headline-snapshot-before-repeat)
12284 (defun org-current-effective-time ()
12285 "Return current time adjusted for `org-extend-today-until' variable."
12286 (let* ((ct (org-current-time))
12287 (dct (decode-time ct))
12290 (org-use-last-clock-out-time-as-effective-time
12291 (or (org-clock-get-last-clock-out-time) ct))
12292 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12293 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12297 (defun org-todo-yesterday (&optional arg)
12298 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12300 (if (eq major-mode 'org-agenda-mode)
12301 (apply 'org-agenda-todo-yesterday arg)
12302 (let* ((org-use-effective-time t)
12303 (hour (nth 2 (decode-time (org-current-time))))
12304 (org-extend-today-until (1+ hour)))
12307 (defvar org-block-entry-blocking ""
12308 "First entry preventing the TODO state change.")
12310 (defun org-cancel-repeater ()
12311 "Cancel a repeater by setting its numeric value to zero."
12314 (org-back-to-heading t)
12315 (let ((bound1 (point))
12316 (bound0 (save-excursion (outline-next-heading) (point))))
12317 (when (and (re-search-forward
12318 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12319 org-deadline-time-regexp "\\)\\|\\("
12320 org-ts-regexp "\\)")
12322 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12324 (replace-match "0" t nil nil 1)))))
12327 (defvar org-blocked-by-checkboxes)
12328 (defun org-todo (&optional arg)
12329 "Change the TODO state of an item.
12331 The state of an item is given by a keyword at the start of the heading,
12333 *** TODO Write paper
12336 The different keywords are specified in the variable `org-todo-keywords'.
12337 By default the available states are \"TODO\" and \"DONE\". So, for this
12338 example: when the item starts with TODO, it is changed to DONE.
12339 When it starts with DONE, the DONE is removed. And when neither TODO nor
12340 DONE are present, add TODO at the beginning of the heading.
12342 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12344 With numeric prefix ARG, switch to that state.
12345 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12347 keywords (nextset).
12348 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12349 prefix, circumvent any state blocking.
12350 With a numeric prefix arg of 0, inhibit note taking for the change.
12351 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12353 When called through ELisp, arg is also interpreted in the following way:
12354 `none' -> empty state
12355 \"\" -> switch to empty state
12356 `done' -> switch to DONE
12357 `nextset' -> switch to the next set of keywords
12358 `previousset' -> switch to the previous set of keywords
12359 \"WAITING\" -> switch to the specified keyword, but only if it
12360 really is a member of `org-todo-keywords'."
12362 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12363 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12364 'region-start-level 'region))
12365 org-loop-over-headlines-in-active-region)
12368 org-loop-over-headlines-in-active-region
12369 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12370 (when (equal arg '(16)) (setq arg 'nextset))
12371 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12372 (let ((org-blocker-hook org-blocker-hook)
12375 (when (equal arg '(64))
12376 (setq arg nil org-blocker-hook nil))
12377 (when (and org-blocker-hook
12378 (or org-inhibit-blocking
12379 (org-entry-get nil "NOBLOCKING")))
12380 (setq org-blocker-hook nil))
12383 (org-back-to-heading t)
12384 (when (org-in-commented-heading-p t)
12385 (org-toggle-comment)
12387 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12388 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12389 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12390 (let* ((match-data (match-data))
12391 (startpos (copy-marker (line-beginning-position)))
12392 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12393 (org-log-done org-log-done)
12394 (org-log-repeat org-log-repeat)
12395 (org-todo-log-states org-todo-log-states)
12396 (org-inhibit-logging
12398 (progn (setq arg nil) 'note) org-inhibit-logging))
12399 (this (match-string 1))
12400 (hl-pos (match-beginning 0))
12401 (head (org-get-todo-sequence-head this))
12402 (ass (assoc head org-todo-kwd-alist))
12403 (interpret (nth 1 ass))
12404 (done-word (nth 3 ass))
12405 (final-done-word (nth 4 ass))
12406 (org-last-state (or this ""))
12407 (completion-ignore-case t)
12408 (member (member this org-todo-keywords-1))
12409 (tail (cdr member))
12411 ((and org-todo-key-trigger
12412 (or (and (equal arg '(4))
12413 (eq org-use-fast-todo-selection 'prefix))
12414 (and (not arg) org-use-fast-todo-selection
12415 (not (eq org-use-fast-todo-selection
12417 ;; Use fast selection.
12418 (org-fast-todo-selection))
12419 ((and (equal arg '(4))
12420 (or (not org-use-fast-todo-selection)
12421 (not org-todo-key-trigger)))
12422 ;; Read a state with completion.
12424 "State: " (mapcar #'list org-todo-keywords-1)
12428 (if tail (car tail) nil)
12429 (car org-todo-keywords-1)))
12431 (unless (equal member org-todo-keywords-1)
12433 (nth (- (length org-todo-keywords-1)
12435 org-todo-keywords-1)
12436 (org-last org-todo-keywords-1))))
12437 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12438 (setq arg nil))) ;hack to fall back to cycling
12440 ;; User or caller requests a specific state.
12442 ((equal arg "") nil)
12443 ((eq arg 'none) nil)
12444 ((eq arg 'done) (or done-word (car org-done-keywords)))
12446 (or (car (cdr (member head org-todo-heads)))
12447 (car org-todo-heads)))
12448 ((eq arg 'previousset)
12449 (let ((org-todo-heads (reverse org-todo-heads)))
12450 (or (car (cdr (member head org-todo-heads)))
12451 (car org-todo-heads))))
12452 ((car (member arg org-todo-keywords-1)))
12454 (user-error "State `%s' not valid in this file" arg))
12455 ((nth (1- (prefix-numeric-value arg))
12456 org-todo-keywords-1))))
12457 ((null member) (or head (car org-todo-keywords-1)))
12458 ((equal this final-done-word) nil) ;-> make empty
12459 ((null tail) nil) ;-> first entry
12460 ((memq interpret '(type priority))
12461 (if (eq this-command last-command)
12463 (if (> (length tail) 0)
12464 (or done-word (car org-done-keywords))
12469 (run-hook-with-args-until-success
12470 'org-todo-get-default-hook org-state org-last-state)
12472 (next (if org-state (concat " " org-state " ") " "))
12473 (change-plist (list :type 'todo-state-change :from this :to org-state
12474 :position startpos))
12476 (when org-blocker-hook
12477 (let (org-blocked-by-checkboxes block-reason)
12478 (setq org-last-todo-state-is-todo
12479 (not (member this org-done-keywords)))
12480 (unless (save-excursion
12482 (org-with-wide-buffer
12483 (run-hook-with-args-until-failure
12484 'org-blocker-hook change-plist))))
12485 (setq block-reason (if org-blocked-by-checkboxes
12486 "contained checkboxes"
12487 (format "\"%s\"" org-block-entry-blocking)))
12488 (if (called-interactively-p 'interactive)
12489 (user-error "TODO state change from %s to %s blocked (by %s)"
12490 this org-state block-reason)
12492 (message "TODO state change from %s to %s blocked (by %s)"
12493 this org-state block-reason)
12494 (throw 'exit nil)))))
12495 (store-match-data match-data)
12496 (replace-match next t t)
12497 (cond ((equal this org-state)
12498 (message "TODO state was already %s" (org-trim next)))
12499 ((not (pos-visible-in-window-p hl-pos))
12500 (message "TODO state changed to %s" (org-trim next))))
12502 (setq head (org-get-todo-sequence-head org-state)
12503 ass (assoc head org-todo-kwd-alist)
12504 interpret (nth 1 ass)
12505 done-word (nth 3 ass)
12506 final-done-word (nth 4 ass)))
12507 (when (memq arg '(nextset previousset))
12508 (message "Keyword-Set %d/%d: %s"
12509 (- (length org-todo-sets) -1
12510 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12511 (length org-todo-sets)
12512 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12513 (setq org-last-todo-state-is-todo
12514 (not (member org-state org-done-keywords)))
12515 (setq now-done-p (and (member org-state org-done-keywords)
12516 (not (member this org-done-keywords))))
12517 (and logging (org-local-logging logging))
12518 (when (and (or org-todo-log-states org-log-done)
12519 (not (eq org-inhibit-logging t))
12520 (not (memq arg '(nextset previousset))))
12521 ;; We need to look at recording a time and note.
12522 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12523 (nth 2 (assoc this org-todo-log-states))))
12524 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12525 (setq dolog 'time))
12526 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12528 (member org-state org-not-done-keywords)
12529 (not (member this org-not-done-keywords))))
12530 ;; This is now a todo state and was not one before
12531 ;; If there was a CLOSED time stamp, get rid of it.
12532 (org-add-planning-info nil nil 'closed))
12533 (when (and now-done-p org-log-done)
12534 ;; It is now done, and it was not done before.
12535 (org-add-planning-info 'closed (org-current-effective-time))
12536 (when (and (not dolog) (eq 'note org-log-done))
12537 (org-add-log-setup 'done org-state this 'note)))
12538 (when (and org-state dolog)
12539 ;; This is a non-nil state, and we need to log it.
12540 (org-add-log-setup 'state org-state this dolog)))
12541 ;; Fixup tag positioning.
12542 (org-todo-trigger-tag-changes org-state)
12543 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12544 (when org-provide-todo-statistics
12545 (org-update-parent-todo-statistics))
12546 (run-hooks 'org-after-todo-state-change-hook)
12547 (when (and arg (not (member org-state org-done-keywords)))
12548 (setq head (org-get-todo-sequence-head org-state)))
12549 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12550 ;; Do we need to trigger a repeat?
12552 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12553 ;; This is for the agenda, take a snapshot of the headline.
12555 (setq org-agenda-headline-snapshot-before-repeat
12556 (org-get-heading))))
12557 (org-auto-repeat-maybe org-state))
12558 ;; Fixup cursor location if close to the keyword.
12559 (when (and (outline-on-heading-p)
12561 (save-excursion (beginning-of-line 1)
12562 (looking-at org-todo-line-regexp))
12563 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12564 (goto-char (or (match-end 2) (match-end 1)))
12565 (and (looking-at " ") (just-one-space)))
12566 (when org-trigger-hook
12568 (run-hook-with-args 'org-trigger-hook change-plist)))
12569 (when commentp (org-toggle-comment))))))))
12571 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12572 "Block turning an entry into a TODO, using the hierarchy.
12573 This checks whether the current task should be blocked from state
12574 changes. Such blocking occurs when:
12576 1. The task has children which are not all in a completed state.
12578 2. A task has a parent with the property :ORDERED:, and there
12579 are siblings prior to the current task with incomplete
12582 3. The parent of the task is blocked because it has siblings that should
12583 be done first, or is child of a block grandparent TODO entry."
12585 (if (not org-enforce-todo-dependencies)
12586 t ; if locally turned off don't block
12588 ;; If this is not a todo state change, or if this entry is already DONE,
12590 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12591 (member (plist-get change-plist :from)
12592 (cons 'done org-done-keywords))
12593 (member (plist-get change-plist :to)
12594 (cons 'todo org-not-done-keywords))
12595 (not (plist-get change-plist :to)))
12596 (throw 'dont-block t))
12597 ;; If this task has children, and any are undone, it's blocked
12599 (org-back-to-heading t)
12600 (let ((this-level (funcall outline-level)))
12601 (outline-next-heading)
12602 (let ((child-level (funcall outline-level)))
12603 (while (and (not (eobp))
12604 (> child-level this-level))
12605 ;; this todo has children, check whether they are all
12607 (when (and (not (org-entry-is-done-p))
12608 (org-entry-is-todo-p))
12609 (setq org-block-entry-blocking (org-get-heading))
12610 (throw 'dont-block nil))
12611 (outline-next-heading)
12612 (setq child-level (funcall outline-level))))))
12613 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12614 ;; any previous siblings are undone, it's blocked
12616 (org-back-to-heading t)
12617 (let* ((pos (point))
12618 (parent-pos (and (org-up-heading-safe) (point)))
12619 (case-fold-search nil))
12620 (unless parent-pos (throw 'dont-block t)) ; no parent
12621 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12623 (re-search-forward org-not-done-heading-regexp pos t))
12624 (setq org-block-entry-blocking (match-string 0))
12625 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12626 ;; Search further up the hierarchy, to see if an ancestor is blocked
12628 (goto-char parent-pos)
12629 (unless (looking-at org-not-done-heading-regexp)
12630 (throw 'dont-block t)) ; do not block, parent is not a TODO
12632 (setq parent-pos (and (org-up-heading-safe) (point)))
12633 (unless parent-pos (throw 'dont-block t)) ; no parent
12634 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12636 (re-search-forward org-not-done-heading-regexp pos t)
12637 (setq org-block-entry-blocking (org-get-heading)))
12638 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12640 (defcustom org-track-ordered-property-with-tag nil
12641 "Should the ORDERED property also be shown as a tag?
12642 The ORDERED property decides if an entry should require subtasks to be
12643 completed in sequence. Since a property is not very visible, setting
12644 this option means that toggling the ORDERED property with the command
12645 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12646 not relevant for the behavior, but it makes things more visible.
12648 Note that toggling the tag with tags commands will not change the property
12649 and therefore not influence behavior!
12651 This can be t, meaning the tag ORDERED should be used, It can also be a
12652 string to select a different tag for this task."
12655 (const :tag "No tracking" nil)
12656 (const :tag "Track with ORDERED tag" t)
12657 (string :tag "Use other tag")))
12659 (defun org-toggle-ordered-property ()
12660 "Toggle the ORDERED property of the current entry.
12661 For better visibility, you can track the value of this property with a tag.
12662 See variable `org-track-ordered-property-with-tag'."
12664 (let* ((t1 org-track-ordered-property-with-tag)
12665 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12667 (org-back-to-heading)
12668 (if (org-entry-get nil "ORDERED")
12670 (org-delete-property "ORDERED")
12671 (and tag (org-toggle-tag tag 'off))
12672 (message "Subtasks can be completed in arbitrary order"))
12673 (org-entry-put nil "ORDERED" "t")
12674 (and tag (org-toggle-tag tag 'on))
12675 (message "Subtasks must be completed in sequence")))))
12677 (defun org-block-todo-from-checkboxes (change-plist)
12678 "Block turning an entry into a TODO, using checkboxes.
12679 This checks whether the current task should be blocked from state
12680 changes because there are unchecked boxes in this entry."
12681 (if (not org-enforce-todo-checkbox-dependencies)
12682 t ; if locally turned off don't block
12684 ;; If this is not a todo state change, or if this entry is already DONE,
12686 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12687 (member (plist-get change-plist :from)
12688 (cons 'done org-done-keywords))
12689 (member (plist-get change-plist :to)
12690 (cons 'todo org-not-done-keywords))
12691 (not (plist-get change-plist :to)))
12692 (throw 'dont-block t))
12693 ;; If this task has checkboxes that are not checked, it's blocked
12695 (org-back-to-heading t)
12696 (let ((beg (point)) end)
12697 (outline-next-heading)
12700 (when (org-list-search-forward
12701 (concat (org-item-beginning-re)
12702 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12705 (when (boundp 'org-blocked-by-checkboxes)
12706 (setq org-blocked-by-checkboxes t))
12707 (throw 'dont-block nil))))
12708 t))) ; do not block
12710 (defun org-entry-blocked-p ()
12711 "Non-nil if entry at point is blocked."
12712 (and (not (org-entry-get nil "NOBLOCKING"))
12713 (member (org-entry-get nil "TODO") org-not-done-keywords)
12714 (not (run-hook-with-args-until-failure
12716 (list :type 'todo-state-change
12721 (defun org-update-statistics-cookies (all)
12722 "Update the statistics cookie, either from TODO or from checkboxes.
12723 This should be called with the cursor in a line with a statistics
12724 cookie. When called with a \\[universal-argument] prefix, update
12725 all statistics cookies in the buffer."
12729 (org-update-checkbox-count 'all)
12730 (org-map-entries 'org-update-parent-todo-statistics))
12731 (if (not (org-at-heading-p))
12732 (org-update-checkbox-count)
12733 (let ((pos (point-marker))
12735 (ignore-errors (org-back-to-heading t))
12736 (if (not (org-at-heading-p))
12737 (org-update-checkbox-count)
12738 (setq l1 (org-outline-level))
12739 (setq end (save-excursion
12740 (outline-next-heading)
12741 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12743 (if (and (save-excursion
12745 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12746 (not (save-excursion (re-search-forward
12747 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12748 (org-update-checkbox-count)
12749 (if (and l2 (> l2 l1))
12752 (org-update-parent-todo-statistics))
12754 (beginning-of-line 1)
12755 (while (re-search-forward
12756 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12758 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12760 (move-marker pos nil)))))
12762 (defvar org-entry-property-inherited-from) ;; defined below
12763 (defun org-update-parent-todo-statistics ()
12764 "Update any statistics cookie in the parent of the current headline.
12765 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12766 the entire subtree and this will travel up the hierarchy and update
12767 statistics everywhere."
12768 (let* ((prop (save-excursion (org-up-heading-safe)
12769 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12770 (recursive (or (not org-hierarchical-todo-statistics)
12771 (and prop (string-match "\\<recursive\\>" prop))))
12772 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12775 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12776 level ltoggle l1 new ndel
12777 (cnt-all 0) (cnt-done 0) is-percent kwd
12778 checkbox-beg cookie-present)
12781 (beginning-of-line 1)
12782 (setq ltoggle (funcall outline-level))
12783 ;; Three situations are to consider:
12785 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12786 ;; to the top-level ancestor on the headline;
12788 ;; 2. If parent has "recursive" property, repeat up to the
12789 ;; headline setting that property, taking inheritance into
12792 ;; 3. Else, move up to direct parent and proceed only once.
12793 (while (and (setq level (org-up-heading-safe))
12794 (or recursive first)
12796 (setq first nil cookie-present nil)
12800 (downcase (or (org-entry-get nil "COOKIE_DATA")
12803 (while (re-search-forward box-re (point-at-eol) t)
12804 (setq cnt-all 0 cnt-done 0 cookie-present t)
12805 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12807 (unless (outline-next-heading) (throw 'exit nil))
12808 (while (and (looking-at org-complex-heading-regexp)
12809 (> (setq l1 (length (match-string 1))) level))
12810 (setq kwd (and (or recursive (= l1 ltoggle))
12812 (if (or (eq org-provide-todo-statistics 'all-headlines)
12813 (and (eq org-provide-todo-statistics t)
12814 (or (member kwd org-done-keywords)))
12815 (and (listp org-provide-todo-statistics)
12816 (stringp (car org-provide-todo-statistics))
12817 (or (member kwd org-provide-todo-statistics)
12818 (member kwd org-done-keywords)))
12819 (and (listp org-provide-todo-statistics)
12820 (listp (car org-provide-todo-statistics))
12821 (or (member kwd (car org-provide-todo-statistics))
12822 (and (member kwd org-done-keywords)
12823 (member kwd (cadr org-provide-todo-statistics))))))
12824 (setq cnt-all (1+ cnt-all))
12825 (and (eq org-provide-todo-statistics t)
12827 (setq cnt-all (1+ cnt-all))))
12828 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12829 (member kwd org-done-keywords))
12830 (and (listp org-provide-todo-statistics)
12831 (listp (car org-provide-todo-statistics))
12832 (member kwd org-done-keywords)
12833 (member kwd (cadr org-provide-todo-statistics)))
12834 (and (listp org-provide-todo-statistics)
12835 (stringp (car org-provide-todo-statistics))
12836 (member kwd org-done-keywords)))
12837 (setq cnt-done (1+ cnt-done)))
12838 (outline-next-heading)))
12841 (format "[%d%%]" (floor (* 100.0 cnt-done)
12843 (format "[%d/%d]" cnt-done cnt-all))
12844 ndel (- (match-end 0) checkbox-beg))
12845 (goto-char checkbox-beg)
12847 (delete-region (point) (+ (point) ndel))
12848 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12849 (when cookie-present
12850 (run-hook-with-args 'org-after-todo-statistics-hook
12851 cnt-done (- cnt-all cnt-done))))))
12852 (run-hooks 'org-todo-statistics-hook)))
12854 (defvar org-after-todo-statistics-hook nil
12855 "Hook that is called after a TODO statistics cookie has been updated.
12856 Each function is called with two arguments: the number of not-done entries
12857 and the number of done entries.
12859 For example, the following function, when added to this hook, will switch
12860 an entry to DONE when all children are done, and back to TODO when new
12861 entries are set to a TODO status. Note that this hook is only called
12862 when there is a statistics cookie in the headline!
12864 (defun org-summary-todo (n-done n-not-done)
12865 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12866 (let (org-log-done org-log-states) ; turn off logging
12867 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12870 (defvar org-todo-statistics-hook nil
12871 "Hook that is run whenever Org thinks TODO statistics should be updated.
12872 This hook runs even if there is no statistics cookie present, in which case
12873 `org-after-todo-statistics-hook' would not run.")
12875 (defun org-todo-trigger-tag-changes (state)
12876 "Apply the changes defined in `org-todo-state-tags-triggers'."
12877 (let ((l org-todo-state-tags-triggers)
12879 (when (or (not state) (equal state ""))
12880 (setq changes (append changes (cdr (assoc "" l)))))
12881 (when (and (stringp state) (> (length state) 0))
12882 (setq changes (append changes (cdr (assoc state l)))))
12883 (when (member state org-not-done-keywords)
12884 (setq changes (append changes (cdr (assq 'todo l)))))
12885 (when (member state org-done-keywords)
12886 (setq changes (append changes (cdr (assq 'done l)))))
12887 (dolist (c changes)
12888 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12890 (defun org-local-logging (value)
12891 "Get logging settings from a property VALUE."
12892 ;; Directly set the variables, they are already local.
12893 (setq org-log-done nil
12895 org-todo-log-states nil)
12896 (dolist (w (split-string value))
12899 ((setq a (assoc w org-startup-options))
12900 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12901 (set (nth 1 a) (nth 2 a))))
12902 ((setq a (org-extract-log-state-settings w))
12903 (and (member (car a) org-todo-keywords-1)
12904 (push a org-todo-log-states)))))))
12906 (defun org-get-todo-sequence-head (kwd)
12907 "Return the head of the TODO sequence to which KWD belongs.
12908 If KWD is not set, check if there is a text property remembering the
12913 (or (get-text-property (point-at-bol) 'org-todo-head)
12915 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12916 nil (point-at-eol)))
12917 (get-text-property p 'org-todo-head))))
12918 ((not (member kwd org-todo-keywords-1))
12919 (car org-todo-keywords-1))
12920 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12922 (defun org-fast-todo-selection ()
12923 "Fast TODO keyword selection with single keys.
12924 Returns the new TODO keyword, or nil if no state change should occur."
12925 (let* ((fulltable org-todo-key-alist)
12926 (done-keywords org-done-keywords) ;; needed for the faces.
12927 (maxlen (apply 'max (mapcar
12929 (if (stringp (car x)) (string-width (car x)) 0))
12932 (fwidth (+ maxlen 3 1 3))
12933 (ncol (/ (- (window-width) 4) fwidth))
12937 (save-window-excursion
12939 (set-buffer (get-buffer-create " *Org todo*"))
12940 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12942 (setq-local org-done-keywords done-keywords)
12943 (setq tbl fulltable cnt 0)
12944 (while (setq e (pop tbl))
12946 ((equal e '(:startgroup))
12947 (push '() groups) (setq ingroup t)
12952 ((equal e '(:endgroup))
12953 (setq ingroup nil cnt 0)
12955 ((equal e '(:newline))
12960 (while (equal (car tbl) '(:newline))
12962 (setq tbl (cdr tbl)))))
12964 (setq tg (car e) c (cdr e))
12965 (when ingroup (push tg (car groups)))
12966 (setq tg (org-add-props tg nil 'face
12967 (org-get-todo-face tg)))
12968 (when (and (= cnt 0) (not ingroup)) (insert " "))
12969 (insert "[" c "] " tg (make-string
12970 (- fwidth 4 (length tg)) ?\ ))
12971 (when (= (setq cnt (1+ cnt)) ncol)
12973 (when ingroup (insert " "))
12976 (goto-char (point-min))
12977 (unless expert (org-fit-window-to-buffer))
12978 (message "[a-z..]:Set [SPC]:clear")
12979 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12982 (and (= c ?q) (not (rassoc c fulltable))))
12983 (setq quit-flag t))
12985 ((setq e (rassoc c fulltable) tg (car e))
12987 (t (setq quit-flag t)))))))
12989 (defun org-entry-is-todo-p ()
12990 (member (org-get-todo-state) org-not-done-keywords))
12992 (defun org-entry-is-done-p ()
12993 (member (org-get-todo-state) org-done-keywords))
12995 (defun org-get-todo-state ()
12996 "Return the TODO keyword of the current subtree."
12998 (org-back-to-heading t)
12999 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13001 (match-string 2))))
13003 (defun org-at-date-range-p (&optional inactive-ok)
13004 "Non-nil if point is inside a date range.
13006 When optional argument INACTIVE-OK is non-nil, also consider
13007 inactive time ranges.
13009 When this function returns a non-nil value, match data is set
13010 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13015 (let ((pos (point)))
13016 (skip-chars-backward "^[<\r\n")
13017 (skip-chars-backward "<[")
13018 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13019 (>= (match-end 0) pos)
13021 (skip-chars-backward "^<[\r\n")
13022 (skip-chars-backward "<[")
13023 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13024 (>= (match-end 0) pos)
13028 (defun org-get-repeat (&optional timestamp)
13029 "Check if there is a time-stamp with repeater in this entry.
13031 Return the repeater, as a string, or nil. Also return nil when
13032 this function is called before first heading.
13034 When optional argument TIMESTAMP is a string, extract the
13035 repeater from there instead."
13038 (and (string-match org-repeat-re timestamp)
13039 (match-string-no-properties 1 timestamp)))
13040 ((org-before-first-heading-p) nil)
13043 (org-back-to-heading t)
13044 (let ((end (org-entry-end-position)))
13046 (while (re-search-forward org-repeat-re end t)
13047 (when (save-match-data (org-at-timestamp-p 'agenda))
13048 (throw :repeat (match-string-no-properties 1)))))))))))
13050 (defvar org-last-changed-timestamp)
13051 (defvar org-last-inserted-timestamp)
13052 (defvar org-log-post-message)
13053 (defvar org-log-note-purpose)
13054 (defvar org-log-note-how nil)
13055 (defvar org-log-note-extra)
13056 (defun org-auto-repeat-maybe (done-word)
13057 "Check if the current headline contains a repeated time-stamp.
13059 If yes, set TODO state back to what it was and change the base date
13060 of repeating deadline/scheduled time stamps to new date.
13062 This function is run automatically after each state change to a DONE state."
13063 (let* ((repeat (org-get-repeat))
13064 (aa (assoc org-last-state org-todo-kwd-alist))
13065 (interpret (nth 1 aa))
13067 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13068 (msg "Entry repeats: ")
13070 (org-todo-log-states nil)
13071 (end (copy-marker (org-entry-end-position))))
13073 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13074 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13075 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13076 org-todo-repeat-to-state)))
13078 ((and to-state (member to-state org-todo-keywords-1))
13080 ((eq interpret 'type) org-last-state)
13083 (org-back-to-heading t)
13084 (org-add-planning-info nil nil 'closed)
13085 ;; When `org-log-repeat' is non-nil or entry contains
13086 ;; a clock, set LAST_REPEAT property.
13087 (when (or org-log-repeat
13090 (while (re-search-forward org-clock-line-re end t)
13091 (when (org-at-clock-log-p) (throw :clock t))))))
13092 (org-entry-put nil "LAST_REPEAT" (format-time-string
13093 (org-time-stamp-format t t)
13095 (when org-log-repeat
13096 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13097 (memq 'org-add-log-note post-command-hook))
13098 ;; We are already setup for some record.
13099 (when (eq org-log-repeat 'note)
13100 ;; Make sure we take a note, not only a time stamp.
13101 (setq org-log-note-how 'note))
13102 ;; Set up for taking a record.
13103 (org-add-log-setup 'state
13104 (or done-word (car org-done-keywords))
13107 (let ((planning-re (regexp-opt
13108 (list org-scheduled-string org-deadline-string))))
13109 (while (re-search-forward org-ts-regexp end t)
13110 (let* ((ts (match-string 0))
13111 (planning? (org-at-planning-p))
13112 (type (if (not planning?) "Plain:"
13114 (re-search-backward
13115 planning-re (line-beginning-position) t)
13116 (match-string 0)))))
13118 ;; Ignore fake time-stamps (e.g., within comments).
13119 ((not (org-at-timestamp-p 'agenda)))
13120 ;; Time-stamps without a repeater are usually
13121 ;; skipped. However, a SCHEDULED time-stamp without
13122 ;; one is removed, as they are no longer relevant.
13123 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13125 (when (equal type org-scheduled-string)
13126 (org-remove-timestamp-with-keyword type)))
13128 (let ((n (string-to-number (match-string 2 ts)))
13129 (what (match-string 3 ts)))
13130 (when (equal what "w") (setq n (* n 7) what "d"))
13131 (when (and (equal what "h")
13132 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13135 "Cannot repeat in Repeat in %d hour(s) because no hour \
13138 ;; Preparation, see if we need to modify the start
13139 ;; date for the change.
13140 (when (match-end 1)
13141 (let ((time (save-match-data
13142 (org-time-string-to-time ts))))
13144 ((equal (match-string 1 ts) ".")
13145 ;; Shift starting date to today
13146 (org-timestamp-change
13147 (- (org-today) (time-to-days time))
13149 ((equal (match-string 1 ts) "+")
13150 (let ((nshiftmax 10)
13152 (while (or (= nshift 0)
13153 (not (time-less-p (current-time) time)))
13154 (when (= (cl-incf nshift) nshiftmax)
13156 (format "%d repeater intervals were not \
13157 enough to shift date past today. Continue? "
13159 (user-error "Abort")))
13160 (org-timestamp-change n (cdr (assoc what whata)))
13161 (org-in-regexp org-ts-regexp3)
13162 (setq ts (match-string 1))
13165 (org-time-string-to-time ts)))))
13166 (org-timestamp-change (- n) (cdr (assoc what whata)))
13167 ;; Rematch, so that we have everything in place
13168 ;; for the real shift.
13169 (org-in-regexp org-ts-regexp3)
13170 (setq ts (match-string 1))
13171 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13174 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13177 msg type " " org-last-changed-timestamp " "))))))))
13178 (setq org-log-post-message msg)
13179 (message "%s" msg))
13180 (set-marker end nil))))
13182 (defun org-show-todo-tree (arg)
13183 "Make a compact tree which shows all headlines marked with TODO.
13184 The tree will show the lines where the regexp matches, and all higher
13185 headlines above the match.
13186 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13187 With a numeric prefix N, construct a sparse tree for the Nth element
13188 of `org-todo-keywords-1'."
13190 (let ((case-fold-search nil)
13192 (cond ((null arg) org-not-done-regexp)
13195 (completing-read "Keyword (or KWD1|KWD2|...): "
13196 (mapcar #'list org-todo-keywords-1))))
13198 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13200 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13201 (regexp-quote (nth (1- (prefix-numeric-value arg))
13202 org-todo-keywords-1)))
13203 (t (user-error "Invalid prefix argument: %s" arg)))))
13204 (message "%d TODO entries found"
13205 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13207 (defun org--deadline-or-schedule (arg type time)
13208 "Insert DEADLINE or SCHEDULE information in current entry.
13209 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13210 `org-schedule' for information about ARG and TIME arguments."
13211 (let* ((deadline? (eq type 'deadline))
13212 (keyword (if deadline? org-deadline-string org-scheduled-string))
13213 (log (if deadline? org-log-redeadline org-log-reschedule))
13214 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13215 (old-date-time (and old-date (org-time-string-to-time old-date)))
13216 ;; Save repeater cookie from either TIME or current scheduled
13217 ;; time stamp. We are going to insert it back at the end of
13219 (repeater (or (and (org-string-nw-p time)
13220 ;; We use `org-repeat-re' because we need
13221 ;; to tell the difference between a real
13222 ;; repeater and a time delta, e.g. "+2d".
13223 (string-match org-repeat-re time)
13224 (match-string 1 time))
13225 (and (org-string-nw-p old-date)
13226 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13227 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13229 (match-string 1 old-date)))))
13232 (when (and old-date log)
13233 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13235 (org-remove-timestamp-with-keyword keyword)
13236 (message (if deadline? "Item no longer has a deadline."
13237 "Item is no longer scheduled.")))
13240 (org-back-to-heading t)
13241 (let ((regexp (if deadline? org-deadline-time-regexp
13242 org-scheduled-time-regexp)))
13243 (if (not (re-search-forward regexp (line-end-position 2) t))
13244 (user-error (if deadline? "No deadline information to update"
13245 "No scheduled information to update"))
13246 (let* ((rpl0 (match-string 1))
13247 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13248 (msg (if deadline? "Warn starting from" "Delay until")))
13253 (abs (- (time-to-days
13256 nil t nil msg old-date-time)))
13257 (time-to-days old-date-time))))
13260 (org-add-planning-info type time 'closed)
13261 (when (and old-date
13263 (not (equal old-date org-last-inserted-timestamp)))
13264 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13265 org-last-inserted-timestamp
13270 (org-back-to-heading t)
13271 (when (re-search-forward
13272 (concat keyword " " org-last-inserted-timestamp)
13273 (line-end-position 2)
13275 (goto-char (1- (match-end 0)))
13276 (insert " " repeater)
13277 (setq org-last-inserted-timestamp
13278 (concat (substring org-last-inserted-timestamp 0 -1)
13280 (substring org-last-inserted-timestamp -1))))))
13281 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13282 org-last-inserted-timestamp)))))
13284 (defun org-deadline (arg &optional time)
13285 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13286 With one universal prefix argument, remove any deadline from the item.
13287 With two universal prefix arguments, prompt for a warning delay.
13288 With argument TIME, set the deadline at the corresponding date. TIME
13289 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13291 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13293 (lambda () (org--deadline-or-schedule arg 'deadline time))
13295 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13296 'region-start-level
13298 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13299 (org--deadline-or-schedule arg 'deadline time)))
13301 (defun org-schedule (arg &optional time)
13302 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13303 With one universal prefix argument, remove any scheduling date from the item.
13304 With two universal prefix arguments, prompt for a delay cookie.
13305 With argument TIME, scheduled at the corresponding date. TIME can
13306 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13308 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13310 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13312 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13313 'region-start-level
13315 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13316 (org--deadline-or-schedule arg 'scheduled time)))
13318 (defun org-get-scheduled-time (pom &optional inherit)
13319 "Get the scheduled time as a time tuple, of a format suitable
13320 for calling org-schedule with, or if there is no scheduling,
13322 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13324 (apply 'encode-time (org-parse-time-string time)))))
13326 (defun org-get-deadline-time (pom &optional inherit)
13327 "Get the deadline as a time tuple, of a format suitable for
13328 calling org-deadline with, or if there is no scheduling, returns
13330 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13332 (apply 'encode-time (org-parse-time-string time)))))
13334 (defun org-remove-timestamp-with-keyword (keyword)
13335 "Remove all time stamps with KEYWORD in the current entry."
13336 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13339 (org-back-to-heading t)
13341 (outline-next-heading)
13342 (while (re-search-backward re beg t)
13344 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13345 (equal (char-before) ?\ ))
13346 (backward-delete-char 1)
13347 (when (string-match "^[ \t]*$" (buffer-substring
13348 (point-at-bol) (point-at-eol)))
13349 (delete-region (point-at-bol)
13350 (min (point-max) (1+ (point-at-eol))))))))))
13352 (defvar org-time-was-given) ; dynamically scoped parameter
13353 (defvar org-end-time-was-given) ; dynamically scoped parameter
13355 (defun org-at-planning-p ()
13356 "Non-nil when point is on a planning info line."
13357 ;; This is as accurate and faster than `org-element-at-point' since
13358 ;; planning info location is fixed in the section.
13359 (org-with-wide-buffer
13360 (beginning-of-line)
13361 (and (looking-at-p org-planning-line-re)
13364 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13365 (org-back-to-heading t)
13366 (org-with-limited-levels (org-back-to-heading t)))
13367 (line-beginning-position 2))))))
13369 (defun org-add-planning-info (what &optional time &rest remove)
13370 "Insert new timestamp with keyword in the planning line.
13371 WHAT indicates what kind of time stamp to add. It is a symbol
13372 among `closed', `deadline', `scheduled' and nil. TIME indicates
13373 the time to use. If none is given, the user is prompted for
13374 a date. REMOVE indicates what kind of entries to remove. An old
13375 WHAT entry will also be removed."
13376 (let (org-time-was-given org-end-time-was-given default-time default-input)
13378 (when (and (memq what '(scheduled deadline))
13380 (and (stringp time)
13381 (string-match "^[-+]+[0-9]" time))))
13382 ;; Try to get a default date/time from existing timestamp
13384 (org-back-to-heading t)
13385 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13386 (when (re-search-forward (if (eq what 'scheduled)
13387 org-scheduled-time-regexp
13388 org-deadline-time-regexp)
13390 (setq ts (match-string 1)
13391 default-time (apply 'encode-time (org-parse-time-string ts))
13392 default-input (and ts (org-get-compact-tod ts)))))))
13396 ;; This is a string (relative or absolute), set
13398 (apply #'encode-time
13399 (org-read-date-analyze
13400 time default-time (decode-time default-time)))
13401 ;; If necessary, get the time from the user
13402 (or time (org-read-date nil 'to-time nil nil
13403 default-time default-input)))))
13405 (org-with-wide-buffer
13406 (org-back-to-heading t)
13408 (unless (bolp) (insert "\n"))
13409 (cond ((looking-at-p org-planning-line-re)
13410 ;; Move to current indentation.
13411 (skip-chars-forward " \t")
13412 ;; Check if we have to remove something.
13413 (dolist (type (if what (cons what remove) remove))
13415 (when (re-search-forward
13417 (closed org-closed-time-regexp)
13418 (deadline org-deadline-time-regexp)
13419 (scheduled org-scheduled-time-regexp)
13421 (error "Invalid planning type: %s" type)))
13422 (line-end-position) t)
13423 ;; Delete until next keyword or end of line.
13425 (match-beginning 0)
13426 (if (re-search-forward org-keyword-time-not-clock-regexp
13427 (line-end-position)
13429 (match-beginning 0)
13430 (line-end-position))))))
13431 ;; If there is nothing more to add and no more keyword
13432 ;; is left, remove the line completely.
13433 (if (and (looking-at-p "[ \t]*$") (not what))
13434 (delete-region (line-beginning-position)
13435 (line-beginning-position 2))
13436 ;; If we removed last keyword, do not leave trailing
13437 ;; white space at the end of line.
13441 (unless (= (skip-chars-backward " \t" p) 0)
13442 (delete-region (point) (line-end-position)))))))
13443 ((not what) (throw 'exit nil)) ; Nothing to do.
13444 (t (insert-before-markers "\n")
13446 (when org-adapt-indentation
13447 (indent-to-column (1+ (org-outline-level))))))
13449 ;; Insert planning keyword.
13450 (insert (cl-case what
13451 (closed org-closed-string)
13452 (deadline org-deadline-string)
13453 (scheduled org-scheduled-string)
13454 (otherwise (error "Invalid planning type: %s" what)))
13456 ;; Insert associated timestamp.
13457 (let ((ts (org-insert-time-stamp
13459 (or org-time-was-given
13460 (and (eq what 'closed) org-log-done-with-time))
13462 nil nil (list org-end-time-was-given))))
13463 (unless (eolp) (insert " "))
13466 (defvar org-log-note-marker (make-marker)
13467 "Marker pointing at the entry where the note is to be inserted.")
13468 (defvar org-log-note-purpose nil)
13469 (defvar org-log-note-state nil)
13470 (defvar org-log-note-previous-state nil)
13471 (defvar org-log-note-extra nil)
13472 (defvar org-log-note-window-configuration nil)
13473 (defvar org-log-note-return-to (make-marker))
13474 (defvar org-log-note-effective-time nil
13475 "Remembered current time so that dynamically scoped
13476 `org-extend-today-until' affects timestamps in state change log")
13478 (defvar org-log-post-message nil
13479 "Message to be displayed after a log note has been stored.
13480 The auto-repeater uses this.")
13482 (defun org-add-note ()
13483 "Add a note to the current entry.
13484 This is done in the same way as adding a state change note."
13486 (org-add-log-setup 'note))
13488 (defun org-log-beginning (&optional create)
13489 "Return expected start of log notes in current entry.
13490 When optional argument CREATE is non-nil, the function creates
13491 a drawer to store notes, if necessary. Returned position ignores
13493 (org-with-wide-buffer
13494 (let ((drawer (org-log-into-drawer)))
13497 (org-end-of-meta-data)
13498 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13499 (end (if (org-at-heading-p) (point)
13500 (save-excursion (outline-next-heading) (point))))
13501 (case-fold-search t))
13503 ;; Try to find existing drawer.
13504 (while (re-search-forward regexp end t)
13505 (let ((element (org-element-at-point)))
13506 (when (eq (org-element-type element) 'drawer)
13507 (let ((cend (org-element-property :contents-end element)))
13508 (when (and (not org-log-states-order-reversed) cend)
13510 (throw 'exit nil))))
13511 ;; No drawer found. Create one, if permitted.
13513 (unless (bolp) (insert "\n"))
13514 (let ((beg (point)))
13515 (insert ":" drawer ":\n:END:\n")
13516 (org-indent-region beg (point)))
13517 (end-of-line -1)))))
13519 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13520 (skip-chars-forward " \t\n")
13521 (beginning-of-line)
13522 (unless org-log-states-order-reversed
13523 (org-skip-over-state-notes)
13524 (skip-chars-backward " \t\n")
13526 (if (bolp) (point) (line-beginning-position 2))))
13528 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13529 "Set up the post command hook to take a note.
13530 If this is about to TODO state change, the new state is expected in STATE.
13531 HOW is an indicator what kind of note should be created.
13532 EXTRA is additional text that will be inserted into the notes buffer."
13533 (move-marker org-log-note-marker (point))
13534 (setq org-log-note-purpose purpose
13535 org-log-note-state state
13536 org-log-note-previous-state prev-state
13537 org-log-note-how how
13538 org-log-note-extra extra
13539 org-log-note-effective-time (org-current-effective-time))
13540 (add-hook 'post-command-hook 'org-add-log-note 'append))
13542 (defun org-skip-over-state-notes ()
13543 "Skip past the list of State notes in an entry."
13544 (when (ignore-errors (goto-char (org-in-item-p)))
13545 (let* ((struct (org-list-struct))
13546 (prevs (org-list-prevs-alist struct))
13548 (concat "[ \t]*- +"
13549 (replace-regexp-in-string
13551 (org-replace-escapes
13552 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13553 `(("%d" . ,org-ts-regexp-inactive)
13554 ("%D" . ,org-ts-regexp)
13555 ("%s" . "\"\\S-+\"")
13556 ("%S" . "\"\\S-+\"")
13557 ("%t" . ,org-ts-regexp-inactive)
13558 ("%T" . ,org-ts-regexp)
13560 ("%U" . ".*?")))))))
13561 (while (looking-at-p regexp)
13562 (goto-char (or (org-list-get-next-item (point) struct prevs)
13563 (org-list-get-item-end (point) struct)))))))
13565 (defun org-add-log-note (&optional _purpose)
13566 "Pop up a window for taking a note, and add this note later."
13567 (remove-hook 'post-command-hook 'org-add-log-note)
13568 (setq org-log-note-window-configuration (current-window-configuration))
13569 (delete-other-windows)
13570 (move-marker org-log-note-return-to (point))
13571 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13572 (goto-char org-log-note-marker)
13573 (org-switch-to-buffer-other-window "*Org Note*")
13575 (if (memq org-log-note-how '(time state))
13576 (org-store-log-note)
13577 (let ((org-inhibit-startup t)) (org-mode))
13578 (insert (format "# Insert note for %s.
13579 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13581 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13582 ((eq org-log-note-purpose 'done) "closed todo item")
13583 ((eq org-log-note-purpose 'state)
13584 (format "state change from \"%s\" to \"%s\""
13585 (or org-log-note-previous-state "")
13586 (or org-log-note-state "")))
13587 ((eq org-log-note-purpose 'reschedule)
13589 ((eq org-log-note-purpose 'delschedule)
13590 "no longer scheduled")
13591 ((eq org-log-note-purpose 'redeadline)
13592 "changing deadline")
13593 ((eq org-log-note-purpose 'deldeadline)
13594 "removing deadline")
13595 ((eq org-log-note-purpose 'refile)
13597 ((eq org-log-note-purpose 'note)
13599 (t (error "This should not happen")))))
13600 (when org-log-note-extra (insert org-log-note-extra))
13601 (setq-local org-finish-function 'org-store-log-note)
13602 (run-hooks 'org-log-buffer-setup-hook)))
13604 (defvar org-note-abort nil) ; dynamically scoped
13605 (defun org-store-log-note ()
13606 "Finish taking a log note, and insert it to where it belongs."
13607 (let ((txt (prog1 (buffer-string)
13609 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13611 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13612 (setq txt (replace-match "" t t txt)))
13613 (when (string-match "\\s-+\\'" txt)
13614 (setq txt (replace-match "" t t txt)))
13615 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13616 (when (org-string-nw-p note)
13618 (org-replace-escapes
13620 (list (cons "%u" (user-login-name))
13621 (cons "%U" user-full-name)
13622 (cons "%t" (format-time-string
13623 (org-time-stamp-format 'long 'inactive)
13624 org-log-note-effective-time))
13625 (cons "%T" (format-time-string
13626 (org-time-stamp-format 'long nil)
13627 org-log-note-effective-time))
13628 (cons "%d" (format-time-string
13629 (org-time-stamp-format nil 'inactive)
13630 org-log-note-effective-time))
13631 (cons "%D" (format-time-string
13632 (org-time-stamp-format nil nil)
13633 org-log-note-effective-time))
13635 ((not org-log-note-state) "")
13636 ((string-match-p org-ts-regexp
13637 org-log-note-state)
13639 (substring org-log-note-state 1 -1)))
13640 (t (format "\"%s\"" org-log-note-state))))
13643 ((not org-log-note-previous-state) "")
13644 ((string-match-p org-ts-regexp
13645 org-log-note-previous-state)
13648 org-log-note-previous-state 1 -1)))
13649 (t (format "\"%s\""
13650 org-log-note-previous-state)))))))
13651 (when lines (setq note (concat note " \\\\")))
13653 (when (and lines (not org-note-abort))
13654 (with-current-buffer (marker-buffer org-log-note-marker)
13655 (org-with-wide-buffer
13656 ;; Find location for the new note.
13657 (goto-char org-log-note-marker)
13658 (set-marker org-log-note-marker nil)
13659 ;; Note associated to a clock is to be located right after
13660 ;; the clock. Do not move point.
13661 (unless (eq org-log-note-purpose 'clock-out)
13662 (goto-char (org-log-beginning t)))
13663 ;; Make sure point is at the beginning of an empty line.
13664 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13665 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13666 ;; In an existing list, add a new item at the top level.
13667 ;; Otherwise, indent line like a regular one.
13668 (let ((itemp (org-in-item-p)))
13671 (let ((struct (save-excursion
13672 (goto-char itemp) (org-list-struct))))
13673 (org-list-get-ind (org-list-get-top-point struct) struct)))
13674 (org-indent-line)))
13675 (insert (org-list-bullet-string "-") (pop lines))
13676 (let ((ind (org-list-item-body-column (line-beginning-position))))
13677 (dolist (line lines)
13679 (indent-line-to ind)
13681 (message "Note stored")
13682 (org-back-to-heading t)
13683 (org-cycle-hide-drawers 'children))
13684 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13685 ;; from within `org-add-log-note' because `buffer-undo-list'
13686 ;; is then modified outside of `org-with-remote-undo'.
13687 (when (eq this-command 'org-agenda-todo)
13688 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13689 ;; Don't add undo information when called from `org-agenda-todo'.
13690 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13691 (set-window-configuration org-log-note-window-configuration)
13692 (with-current-buffer (marker-buffer org-log-note-return-to)
13693 (goto-char org-log-note-return-to))
13694 (move-marker org-log-note-return-to nil)
13695 (when org-log-post-message (message "%s" org-log-post-message))))
13697 (defun org-remove-empty-drawer-at (pos)
13698 "Remove an empty drawer at position POS.
13699 POS may also be a marker."
13700 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13701 (org-with-wide-buffer
13703 (let ((drawer (org-element-at-point)))
13704 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13705 (not (org-element-property :contents-begin drawer)))
13706 (delete-region (org-element-property :begin drawer)
13707 (progn (goto-char (org-element-property :end drawer))
13708 (skip-chars-backward " \r\t\n")
13712 (defvar org-ts-type nil)
13713 (defun org-sparse-tree (&optional arg type)
13714 "Create a sparse tree, prompt for the details.
13715 This command can create sparse trees. You first need to select the type
13716 of match used to create the tree:
13718 t Show all TODO entries.
13719 T Show entries with a specific TODO keyword.
13720 m Show entries selected by a tags/property match.
13721 p Enter a property name and its value (both with completion on existing
13722 names/values) and show entries with that property.
13723 r Show entries matching a regular expression (`/' can be used as well).
13724 b Show deadlines and scheduled items before a date.
13725 a Show deadlines and scheduled items after a date.
13726 d Show deadlines due within `org-deadline-warning-days'.
13727 D Show deadlines and scheduled items between a date range."
13729 (setq type (or type org-sparse-tree-default-date-type))
13730 (setq org-ts-type type)
13731 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13732 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13733 \[c]ycle through date types: %s"
13735 (all "all timestamps")
13736 (scheduled "only scheduled")
13737 (deadline "only deadline")
13738 (active "only active timestamps")
13739 (inactive "only inactive timestamps")
13740 (closed "with a closed time-stamp")
13741 (otherwise "scheduled/deadline")))
13742 (let ((answer (read-char-exclusive)))
13748 (memq type '(nil all scheduled deadline active inactive closed)))))
13749 (?d (call-interactively 'org-check-deadlines))
13750 (?b (call-interactively 'org-check-before-date))
13751 (?a (call-interactively 'org-check-after-date))
13752 (?D (call-interactively 'org-check-dates-range))
13753 (?t (call-interactively 'org-show-todo-tree))
13754 (?T (org-show-todo-tree '(4)))
13755 (?m (call-interactively 'org-match-sparse-tree))
13757 (let* ((kwd (completing-read
13758 "Property: " (mapcar #'list (org-buffer-property-keys))))
13759 (value (completing-read
13760 "Value: " (mapcar #'list (org-property-values kwd)))))
13761 (unless (string-match "\\`{.*}\\'" value)
13762 (setq value (concat "\"" value "\"")))
13763 (org-match-sparse-tree arg (concat kwd "=" value))))
13764 ((?r ?R ?/) (call-interactively 'org-occur))
13765 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13767 (defvar-local org-occur-highlights nil
13768 "List of overlays used for occur matches.")
13769 (defvar-local org-occur-parameters nil
13770 "Parameters of the active org-occur calls.
13771 This is a list, each call to org-occur pushes as cons cell,
13772 containing the regular expression and the callback, onto the list.
13773 The list can contain several entries if `org-occur' has been called
13774 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13775 will only contain one set of parameters. When the highlights are
13776 removed (for example with `C-c C-c', or with the next edit (depending
13777 on `org-remove-highlights-with-change'), this variable is emptied
13780 (defun org-occur (regexp &optional keep-previous callback)
13781 "Make a compact tree which shows all matches of REGEXP.
13783 The tree will show the lines where the regexp matches, and any other context
13784 defined in `org-show-context-detail', which see.
13786 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13787 done by a previous call to `org-occur' will be kept, to allow stacking of
13788 calls to this command.
13790 Optional argument CALLBACK can be a function of no argument. In this case,
13791 it is called with point at the end of the match, match data being set
13792 accordingly. Current match is shown only if the return value is non-nil.
13793 The function must neither move point nor alter narrowing."
13794 (interactive "sRegexp: \nP")
13795 (when (equal regexp "")
13796 (user-error "Regexp cannot be empty"))
13797 (unless keep-previous
13798 (org-remove-occur-highlights nil nil t))
13799 (push (cons regexp callback) org-occur-parameters)
13802 (goto-char (point-min))
13803 (when (or (not keep-previous) ; do not want to keep
13804 (not org-occur-highlights)) ; no previous matches
13807 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13808 (isearch-no-upper-case-p regexp t)
13809 org-occur-case-fold-search)))
13810 (while (re-search-forward regexp nil t)
13811 (when (or (not callback)
13812 (save-match-data (funcall callback)))
13813 (setq cnt (1+ cnt))
13814 (when org-highlight-sparse-tree-matches
13815 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13816 (org-show-context 'occur-tree)))))
13817 (when org-remove-highlights-with-change
13818 (add-hook 'before-change-functions 'org-remove-occur-highlights
13820 (unless org-sparse-tree-open-archived-trees
13821 (org-hide-archived-subtrees (point-min) (point-max)))
13822 (run-hooks 'org-occur-hook)
13823 (when (called-interactively-p 'interactive)
13824 (message "%d match(es) for regexp %s" cnt regexp))
13827 (defun org-occur-next-match (&optional n _reset)
13828 "Function for `next-error-function' to find sparse tree matches.
13829 N is the number of matches to move, when negative move backwards.
13830 This function always goes back to the starting point when no
13832 (let* ((limit (if (< n 0) (point-min) (point-max)))
13833 (search-func (if (< n 0)
13834 'previous-single-char-property-change
13835 'next-single-char-property-change))
13840 (while (setq p1 (funcall search-func (point) 'org-type))
13841 (when (equal p1 limit)
13843 (user-error "No more matches"))
13844 (when (equal (get-char-property p1 'org-type) 'org-occur)
13848 (throw 'exit (point))))
13851 (user-error "No more matches"))))
13853 (defun org-show-context (&optional key)
13854 "Make sure point and context are visible.
13855 Optional argument KEY, when non-nil, is a symbol. See
13856 `org-show-context-detail' for allowed values and how much is to
13858 (org-show-set-visibility
13859 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13860 ((cdr (assq key org-show-context-detail)))
13861 (t (cdr (assq 'default org-show-context-detail))))))
13863 (defun org-show-set-visibility (detail)
13864 "Set visibility around point according to DETAIL.
13865 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13866 `tree', `canonical' or t. See `org-show-context-detail' for more
13868 ;; Show current heading and possibly its entry, following headline
13869 ;; or all children.
13870 (if (and (org-at-heading-p) (not (eq detail 'local)))
13871 (org-flag-heading nil)
13873 ;; If point is hidden within a drawer or a block, make sure to
13875 (dolist (o (overlays-at (point)))
13876 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13877 (delete-overlay o)))
13878 (unless (org-before-first-heading-p)
13879 (org-with-limited-levels
13881 ((tree canonical t) (org-show-children))
13882 ((nil minimal ancestors))
13884 (outline-next-heading)
13885 (org-flag-heading nil)))))))
13886 ;; Show all siblings.
13887 (when (eq detail 'lineage) (org-show-siblings))
13888 ;; Show ancestors, possibly with their children.
13889 (when (memq detail '(ancestors lineage tree canonical t))
13891 (while (org-up-heading-safe)
13892 (org-flag-heading nil)
13893 (when (memq detail '(canonical t)) (org-show-entry))
13894 (when (memq detail '(tree canonical t)) (org-show-children))))))
13896 (defvar org-reveal-start-hook nil
13897 "Hook run before revealing a location.")
13899 (defun org-reveal (&optional siblings)
13900 "Show current entry, hierarchy above it, and the following headline.
13902 This can be used to show a consistent set of context around
13903 locations exposed with `org-show-context'.
13905 With optional argument SIBLINGS, on each level of the hierarchy all
13906 siblings are shown. This repairs the tree structure to what it would
13907 look like when opened with hierarchical calls to `org-cycle'.
13909 With a \\[universal-argument] \\[universal-argument] prefix, \
13910 go to the parent and show the entire tree."
13912 (run-hooks 'org-reveal-start-hook)
13913 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13914 ((equal siblings '(16))
13916 (when (org-up-heading-safe)
13918 (run-hook-with-args 'org-cycle-hook 'subtree))))
13919 (t (org-show-set-visibility 'lineage))))
13921 (defun org-highlight-new-match (beg end)
13922 "Highlight from BEG to END and mark the highlight is an occur headline."
13923 (let ((ov (make-overlay beg end)))
13924 (overlay-put ov 'face 'secondary-selection)
13925 (overlay-put ov 'org-type 'org-occur)
13926 (push ov org-occur-highlights)))
13928 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13929 "Remove the occur highlights from the buffer.
13930 BEG and END are ignored. If NOREMOVE is nil, remove this function
13931 from the `before-change-functions' in the current buffer."
13933 (unless org-inhibit-highlight-removal
13934 (mapc #'delete-overlay org-occur-highlights)
13935 (setq org-occur-highlights nil)
13936 (setq org-occur-parameters nil)
13938 (remove-hook 'before-change-functions
13939 'org-remove-occur-highlights 'local))))
13943 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13944 "Regular expression matching the priority indicator.")
13946 (defvar org-remove-priority-next-time nil)
13948 (defun org-priority-up ()
13949 "Increase the priority of the current item."
13951 (org-priority 'up))
13953 (defun org-priority-down ()
13954 "Decrease the priority of the current item."
13956 (org-priority 'down))
13958 (defun org-priority (&optional action _show)
13959 "Change the priority of an item.
13960 ACTION can be `set', `up', `down', or a character."
13962 (if (equal action '(4))
13963 (org-show-priority)
13964 (unless org-enable-priority-commands
13965 (user-error "Priority commands are disabled"))
13966 (setq action (or action 'set))
13967 (let (current new news have remove)
13969 (org-back-to-heading t)
13970 (when (looking-at org-priority-regexp)
13971 (setq current (string-to-char (match-string 2))
13974 ((eq action 'remove)
13975 (setq remove t new ?\ ))
13976 ((or (eq action 'set)
13978 (if (not (eq action 'set))
13980 (message "Priority %c-%c, SPC to remove: "
13981 org-highest-priority org-lowest-priority)
13983 (setq new (read-char-exclusive))))
13984 (when (and (= (upcase org-highest-priority) org-highest-priority)
13985 (= (upcase org-lowest-priority) org-lowest-priority))
13986 (setq new (upcase new)))
13987 (cond ((equal new ?\ ) (setq remove t))
13988 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13989 (user-error "Priority must be between `%c' and `%c'"
13990 org-highest-priority org-lowest-priority))))
13993 (1- current) ; normal cycling
13994 ;; last priority was empty
13995 (if (eq last-command this-command)
13996 org-lowest-priority ; wrap around empty to lowest
13998 (if org-priority-start-cycle-with-default
13999 org-default-priority
14000 (1- org-default-priority))))))
14003 (1+ current) ; normal cycling
14004 ;; last priority was empty
14005 (if (eq last-command this-command)
14006 org-highest-priority ; wrap around empty to highest
14008 (if org-priority-start-cycle-with-default
14009 org-default-priority
14010 (1+ org-default-priority))))))
14011 (t (user-error "Invalid action")))
14012 (when (or (< (upcase new) org-highest-priority)
14013 (> (upcase new) org-lowest-priority))
14014 (if (and (memq action '(up down))
14015 (not have) (not (eq last-command this-command)))
14016 ;; `new' is from default priority
14018 "The default can not be set, see `org-default-priority' why")
14019 ;; normal cycling: `new' is beyond highest/lowest priority
14020 ;; and is wrapped around to the empty priority
14022 (setq news (format "%c" new))
14025 (replace-match "" t t nil 1)
14026 (replace-match news t t nil 2))
14028 (user-error "No priority cookie found in line")
14029 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14032 (goto-char (match-end 2))
14033 (insert " [#" news "]"))
14034 (goto-char (match-beginning 3))
14035 (insert "[#" news "] "))))
14036 (org-set-tags nil 'align))
14038 (message "Priority removed")
14039 (message "Priority of current item set to %s" news)))))
14041 (defun org-show-priority ()
14042 "Show the priority of the current item.
14043 This priority is composed of the main priority given with the [#A] cookies,
14044 and by additional input from the age of a schedules or deadline entry."
14046 (let ((pri (if (eq major-mode 'org-agenda-mode)
14047 (org-get-at-bol 'priority)
14050 (beginning-of-line)
14051 (and (looking-at org-heading-regexp)
14052 (org-get-priority (match-string 0))))))))
14053 (message "Priority is %d" (if pri pri -1000))))
14055 (defun org-get-priority (s)
14056 "Find priority cookie and return priority."
14058 (if (functionp org-get-priority-function)
14059 (funcall org-get-priority-function)
14060 (if (not (string-match org-priority-regexp s))
14061 (* 1000 (- org-lowest-priority org-default-priority))
14062 (* 1000 (- org-lowest-priority
14063 (string-to-char (match-string 2 s))))))))
14067 (defvar org-agenda-archives-mode)
14068 (defvar org-map-continue-from nil
14069 "Position from where mapping should continue.
14070 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14072 (defvar org-scanner-tags nil
14073 "The current tag list while the tags scanner is running.")
14075 (defvar org-trust-scanner-tags nil
14076 "Should `org-get-tags-at' use the tags for the scanner.
14077 This is for internal dynamical scoping only.
14078 When this is non-nil, the function `org-get-tags-at' will return the value
14079 of `org-scanner-tags' instead of building the list by itself. This
14080 can lead to large speed-ups when the tags scanner is used in a file with
14081 many entries, and when the list of tags is retrieved, for example to
14082 obtain a list of properties. Building the tags list for each entry in such
14083 a file becomes an N^2 operation - but with this variable set, it scales
14086 (defvar org--matcher-tags-todo-only nil)
14088 (defun org-scan-tags (action matcher todo-only &optional start-level)
14089 "Scan headline tags with inheritance and produce output ACTION.
14091 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14092 or `agenda' to produce an entry list for an agenda view. It can also be
14093 a Lisp form or a function that should be called at each matched headline, in
14094 this case the return value is a list of all return values from these calls.
14096 MATCHER is a function accepting three arguments, returning
14097 a non-nil value whenever a given set of tags qualifies a headline
14098 for inclusion. See `org-make-tags-matcher' for more information.
14099 As a special case, it can also be set to t (respectively nil) in
14100 order to match all (respectively none) headline.
14102 When TODO-ONLY is non-nil, only lines with a TODO keyword are
14103 included in the output.
14105 START-LEVEL can be a string with asterisks, reducing the scope to
14106 headlines matching this string."
14107 (require 'org-agenda)
14108 (let* ((re (concat "^"
14110 ;; Get the correct level to match
14111 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14112 org-outline-regexp)
14114 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14115 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14116 (props (list 'face 'default
14117 'done-face 'org-agenda-done
14118 'undone-face 'default
14119 'mouse-face 'highlight
14120 'org-not-done-regexp org-not-done-regexp
14121 'org-todo-regexp org-todo-regexp
14122 'org-complex-heading-regexp org-complex-heading-regexp
14124 (format "mouse-2 or RET jump to org file %s"
14125 (abbreviate-file-name
14126 (or (buffer-file-name (buffer-base-buffer))
14127 (buffer-name (buffer-base-buffer)))))))
14128 (org-map-continue-from nil)
14129 lspos tags tags-list
14130 (tags-alist (list (cons 0 org-file-tags)))
14131 (llast 0) rtn rtn1 level category i txt
14132 todo marker entry priority
14133 ts-date ts-date-type ts-date-pair)
14134 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14135 (setq action (list 'lambda nil action)))
14137 (goto-char (point-min))
14138 (when (eq action 'sparse-tree)
14140 (org-remove-occur-highlights))
14141 (while (let (case-fold-search)
14142 (re-search-forward re nil t))
14143 (setq org-map-continue-from nil)
14146 ;; TODO: is the 1-2 difference a bug?
14147 (when (match-end 1) (match-string-no-properties 2))
14148 tags (when (match-end 4) (match-string-no-properties 4)))
14149 (goto-char (setq lspos (match-beginning 0)))
14150 (setq level (org-reduced-level (org-outline-level))
14151 category (org-get-category))
14152 (when (eq action 'agenda)
14153 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14154 ts-date (car ts-date-pair)
14155 ts-date-type (cdr ts-date-pair)))
14156 (setq i llast llast level)
14157 ;; remove tag lists from same and sublevels
14158 (while (>= i level)
14159 (when (setq entry (assoc i tags-alist))
14160 (setq tags-alist (delete entry tags-alist)))
14162 ;; add the next tags
14164 (setq tags (org-split-string tags ":")
14166 (cons (cons level tags) tags-alist)))
14167 ;; compile tags for current headline
14169 (if org-use-tag-inheritance
14170 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14172 org-scanner-tags tags-list)
14173 (when org-use-tag-inheritance
14174 (setcdr (car tags-alist)
14175 (mapcar (lambda (x)
14176 (setq x (copy-sequence x))
14177 (org-add-prop-inherited x))
14178 (cdar tags-alist))))
14179 (when (and tags org-use-tag-inheritance
14180 (or (not (eq t org-use-tag-inheritance))
14181 org-tags-exclude-from-inheritance))
14182 ;; Selective inheritance, remove uninherited ones.
14183 (setcdr (car tags-alist)
14184 (org-remove-uninherited-tags (cdar tags-alist))))
14187 ;; eval matcher only when the todo condition is OK
14188 (and (or (not todo-only) (member todo org-todo-keywords-1))
14189 (if (functionp matcher)
14190 (let ((case-fold-search t) (org-trust-scanner-tags t))
14191 (funcall matcher todo tags-list level))
14194 ;; Call the skipper, but return t if it does not
14195 ;; skip, so that the `and' form continues evaluating.
14197 (unless (eq action 'sparse-tree) (org-agenda-skip))
14200 ;; Check if timestamps are deselecting this entry
14201 (or (not todo-only)
14202 (and (member todo org-todo-keywords-1)
14203 (or (not org-agenda-tags-todo-honor-ignore-options)
14204 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14206 ;; select this headline
14208 ((eq action 'sparse-tree)
14209 (and org-highlight-sparse-tree-matches
14210 (org-get-heading) (match-end 0)
14211 (org-highlight-new-match
14212 (match-beginning 1) (match-end 1)))
14213 (org-show-context 'tags-tree))
14214 ((eq action 'agenda)
14215 (setq txt (org-agenda-format-item
14218 (if (eq org-tags-match-list-sublevels 'indented)
14219 (make-string (1- level) ?.) "")
14221 (make-string level ?\s)
14224 priority (org-get-priority txt))
14226 (setq marker (org-agenda-new-marker))
14227 (org-add-props txt props
14228 'org-marker marker 'org-hd-marker marker 'org-category category
14232 'type (concat "tagsmatch" ts-date-type))
14234 ((functionp action)
14235 (setq org-map-continue-from nil)
14237 (setq rtn1 (funcall action))
14239 (t (user-error "Invalid action")))
14241 ;; if we are to skip sublevels, jump to end of subtree
14242 (unless org-tags-match-list-sublevels
14243 (org-end-of-subtree t)
14244 (backward-char 1))))
14245 ;; Get the correct position from where to continue
14246 (if org-map-continue-from
14247 (goto-char org-map-continue-from)
14248 (and (= (point) lspos) (end-of-line 1)))))
14249 (when (and (eq action 'sparse-tree)
14250 (not org-sparse-tree-open-archived-trees))
14251 (org-hide-archived-subtrees (point-min) (point-max)))
14254 (defun org-remove-uninherited-tags (tags)
14255 "Remove all tags that are not inherited from the list TAGS."
14257 ((eq org-use-tag-inheritance t)
14258 (if org-tags-exclude-from-inheritance
14259 (org-delete-all org-tags-exclude-from-inheritance tags)
14261 ((not org-use-tag-inheritance) nil)
14262 ((stringp org-use-tag-inheritance)
14265 (if (and (string-match org-use-tag-inheritance x)
14266 (not (member x org-tags-exclude-from-inheritance)))
14269 ((listp org-use-tag-inheritance)
14272 (if (member x org-use-tag-inheritance) x nil))
14275 (defun org-match-sparse-tree (&optional todo-only match)
14276 "Create a sparse tree according to tags string MATCH.
14278 MATCH is a string with match syntax. It can contain a selection
14279 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14280 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14281 those. See the manual for details.
14283 If optional argument TODO-ONLY is non-nil, only select lines that
14284 are also TODO tasks."
14286 (org-agenda-prepare-buffers (list (current-buffer)))
14287 (let ((org--matcher-tags-todo-only todo-only))
14288 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14289 org--matcher-tags-todo-only)))
14291 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14293 (defvar org-cached-props nil)
14294 (defun org-cached-entry-get (pom property)
14295 (if (or (eq t org-use-property-inheritance)
14296 (and (stringp org-use-property-inheritance)
14297 (let ((case-fold-search t))
14298 (string-match-p org-use-property-inheritance property)))
14299 (and (listp org-use-property-inheritance)
14300 (member-ignore-case property org-use-property-inheritance)))
14301 ;; Caching is not possible, check it directly.
14302 (org-entry-get pom property 'inherit)
14303 ;; Get all properties, so we can do complicated checks easily.
14304 (cdr (assoc-string property
14305 (or org-cached-props
14306 (setq org-cached-props (org-entry-properties pom)))
14309 (defun org-global-tags-completion-table (&optional files)
14310 "Return the list of all tags in all agenda buffer/files.
14311 Optional FILES argument is a list of files which can be used
14312 instead of the agenda files."
14319 (set-buffer (find-file-noselect file))
14320 (mapcar (lambda (x)
14321 (and (stringp (car-safe x))
14322 (list (car-safe x))))
14323 (or org-current-tag-alist (org-get-buffer-tags))))
14324 (if (car-safe files) files
14325 (org-agenda-files))))))))
14327 (defun org-make-tags-matcher (match)
14328 "Create the TAGS/TODO matcher form for the selection string MATCH.
14330 Returns a cons of the selection string MATCH and a function
14331 implementing the matcher.
14333 The matcher is to be called at an Org entry, with point on the
14334 headline, and returns non-nil if the entry matches the selection
14335 string MATCH. It must be called with three arguments: the TODO
14336 keyword at the entry (or nil if none), the list of all tags at
14337 the entry including inherited ones and the reduced level of the
14338 headline. Additionally, the category of the entry, if any, must
14339 be specified as the text property `org-category' on the headline.
14341 This function sets the variable `org--matcher-tags-todo-only' to
14342 a non-nil value if the matcher restricts matching to TODO
14343 entries, otherwise it is not touched.
14345 See also `org-scan-tags'."
14347 ;; Get a new match request, with completion against the global
14348 ;; tags table and the local tags in current buffer.
14349 (let ((org-last-tags-completion-table
14351 (delq nil (append (org-get-buffer-tags)
14352 (org-global-tags-completion-table))))))
14356 'org-tags-completion-function nil nil nil 'org-tags-history))))
14358 (let ((match0 match)
14359 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14361 tagsmatch todomatch tagsmatcher todomatcher)
14363 ;; Expand group tags.
14364 (setq match (org-tags-expand match))
14366 ;; Check if there is a TODO part of this match, which would be the
14367 ;; part after a "/". To make sure that this slash is not part of
14368 ;; a property value to be matched against, we also check that
14369 ;; there is no / after that slash. First, find the last slash.
14371 (while (string-match "/+" match s)
14372 (setq start (match-beginning 0))
14373 (setq s (match-end 0))))
14374 (if (and (string-match "/+" match start)
14375 (not (string-match-p "\"" match start)))
14376 ;; Match contains also a TODO-matching request.
14378 (setq tagsmatch (substring match 0 (match-beginning 0)))
14379 (setq todomatch (substring match (match-end 0)))
14380 (when (string-prefix-p "!" todomatch)
14381 (setq org--matcher-tags-todo-only t)
14382 (setq todomatch (substring todomatch 1)))
14383 (when (string-match "\\`\\s-*\\'" todomatch)
14384 (setq todomatch nil)))
14385 ;; Only matching tags.
14386 (setq tagsmatch match)
14387 (setq todomatch nil))
14389 ;; Make the tags matcher.
14390 (when (org-string-nw-p tagsmatch)
14392 (orterms (org-split-string tagsmatch "|"))
14394 (while (setq term (pop orterms))
14395 (while (and (equal (substring term -1) "\\") orterms)
14396 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14397 (while (string-match re term)
14398 (let* ((rest (substring term (match-end 0)))
14399 (minus (and (match-end 1)
14400 (equal (match-string 1 term) "-")))
14401 (tag (save-match-data
14402 (replace-regexp-in-string
14403 "\\\\-" "-" (match-string 2 term))))
14404 (regexp (eq (string-to-char tag) ?{))
14405 (levelp (match-end 4))
14406 (propp (match-end 5))
14409 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14411 `(,(org-op-to-function (match-string 3 term))
14413 ,(string-to-number (match-string 4 term))))
14415 (let* ((gv (pcase (upcase (match-string 5 term))
14417 '(get-text-property (point) 'org-category))
14419 (p `(org-cached-entry-get nil ,p))))
14420 (pv (match-string 7 term))
14421 (regexp (eq (string-to-char pv) ?{))
14422 (strp (eq (string-to-char pv) ?\"))
14423 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14424 (po (org-op-to-function (match-string 6 term)
14425 (if timep 'time strp))))
14426 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14427 (when timep (setq pv (org-matcher-time pv)))
14428 (cond ((and regexp (eq po 'org<>))
14429 `(not (string-match ,pv (or ,gv ""))))
14430 (regexp `(string-match ,pv (or ,gv "")))
14431 (strp `(,po (or ,gv "") ,pv))
14434 (string-to-number (or ,gv ""))
14435 ,(string-to-number pv))))))
14436 (t `(member ,tag tags-list)))))
14437 (push (if minus `(not ,mm) mm) tagsmatcher)
14439 (push `(and ,@tagsmatcher) orlist)
14440 (setq tagsmatcher nil))
14441 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14443 ;; Make the TODO matcher.
14444 (when (org-string-nw-p todomatch)
14445 (let ((orlist nil))
14446 (dolist (term (org-split-string todomatch "|"))
14447 (while (string-match re term)
14448 (let* ((minus (and (match-end 1)
14449 (equal (match-string 1 term) "-")))
14450 (kwd (match-string 2 term))
14451 (regexp (eq (string-to-char kwd) ?{))
14452 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14453 `(equal todo ,kwd))))
14454 (push (if minus `(not ,mm) mm) todomatcher))
14455 (setq term (substring term (match-end 0))))
14456 (push (if (> (length todomatcher) 1)
14457 (cons 'and todomatcher)
14460 (setq todomatcher nil))
14461 (setq todomatcher (cons 'or orlist))))
14463 ;; Return the string and function of the matcher. If no
14464 ;; tags-specific or todo-specific matcher exists, match
14466 (let ((matcher (if (and tagsmatcher todomatcher)
14467 `(and ,tagsmatcher ,todomatcher)
14468 (or tagsmatcher todomatcher t))))
14469 (when org--matcher-tags-todo-only
14470 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14471 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14473 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14474 "Expand group tags in MATCH.
14476 This replaces every group tag in MATCH with a regexp tag search.
14477 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14478 will be replaced like this:
14480 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14481 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14482 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14484 Replacing by a regexp preserves the structure of the match.
14485 E.g., this expansion
14487 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14489 will match anything tagged with \"Lab\" and \"Home\", or tagged
14490 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14492 A group tag in MATCH can contain regular expressions of its own.
14493 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14494 will be replaced like this:
14496 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14498 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14499 assumed to be a single group tag, and the function will return
14500 the list of tags in this group.
14502 When DOWNCASE is non-nil, expand downcased TAGS."
14504 (let* ((case-fold-search t)
14505 (stable org-mode-syntax-table)
14506 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14507 (taggroups (if downcased
14508 (mapcar (lambda (tg) (mapcar #'downcase tg))
14511 (taggroups-keys (mapcar #'car taggroups))
14512 (return-match (if downcased (downcase match) match))
14514 (work-already-expanded tags-already-expanded)
14515 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14516 ;; @ and _ are allowed as word-components in tags.
14517 (modify-syntax-entry ?@ "w" stable)
14518 (modify-syntax-entry ?_ "w" stable)
14519 ;; Temporarily replace regexp-expressions in the match-expression.
14520 (while (string-match "{.+?}" return-match)
14522 (push (match-string 0 return-match) regexps-in-match)
14523 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14524 (while (and taggroups-keys
14525 (with-syntax-table stable
14527 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14528 (regexp-opt taggroups-keys) "\\>\\)")
14530 (let* ((dir (match-string 1 return-match))
14531 (tag (match-string 2 return-match))
14532 (tag (if downcased (downcase tag) tag)))
14533 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14534 (member tag work-already-expanded))
14535 (setq tags-in-group (assoc tag taggroups))
14536 (push tag work-already-expanded)
14537 ;; Recursively expand each tag in the group, if the tag hasn't
14538 ;; already been expanded. Restore the match-data after all recursive calls.
14540 (let (tags-expanded)
14541 (dolist (x (cdr tags-in-group))
14542 (if (and (member x taggroups-keys)
14543 (not (member x work-already-expanded)))
14544 (setq tags-expanded
14547 (org-tags-expand x t downcased
14548 work-already-expanded)
14550 (setq tags-expanded
14551 (append (list x) tags-expanded)))
14552 (setq work-already-expanded
14554 (append tags-expanded
14555 work-already-expanded))))
14556 (setq tags-in-group
14557 (delete-dups (cons (car tags-in-group)
14559 ;; Filter tag-regexps from tags.
14560 (setq regexp-in-group-escaped
14561 (delq nil (mapcar (lambda (x)
14563 (and (equal "{" (substring x 0 1))
14564 (equal "}" (substring x -1))
14569 (mapcar (lambda (x)
14570 (substring x 1 -1))
14571 regexp-in-group-escaped)
14573 (delq nil (mapcar (lambda (x)
14575 (and (not (equal "{" (substring x 0 1)))
14576 (not (equal "}" (substring x -1)))
14580 ;; If single-as-list, do no more in the while-loop.
14581 (if (not single-as-list)
14583 (when regexp-in-group
14584 (setq regexp-in-group
14586 (mapconcat 'identity regexp-in-group
14588 (setq tags-in-group
14591 (regexp-opt tags-in-group)
14595 (when (stringp tags-in-group)
14596 (org-add-props tags-in-group '(grouptag t)))
14598 (replace-match tags-in-group t t return-match)))
14599 (setq tags-in-group
14600 (append regexp-in-group-escaped tags-in-group))))
14601 (setq taggroups-keys (delete tag taggroups-keys))))
14602 ;; Add the regular expressions back into the match-expression again.
14603 (while regexps-in-match
14604 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14605 (pop regexps-in-match)
14609 (if tags-in-group tags-in-group (list return-match))
14612 (list (if downcased (downcase match) match))
14615 (defun org-op-to-function (op &optional stringp)
14616 "Turn an operator into the appropriate function."
14619 ((equal op "<" ) '(< string< org-time<))
14620 ((equal op ">" ) '(> org-string> org-time>))
14621 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14622 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14623 ((member op '("=" "==")) '(= string= org-time=))
14624 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14625 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14627 (defun org<> (a b) (not (= a b)))
14628 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14629 (defun org-string>= (a b) (not (string< a b)))
14630 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14631 (defun org-string<> (a b) (not (string= a b)))
14632 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14633 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14634 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14635 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14636 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14637 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14639 "Convert S to a floating point time.
14640 If S is already a number, just return it. If it is a string, parse
14641 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14645 (condition-case nil
14646 (float-time (apply #'encode-time (org-parse-time-string s)))
14650 (defun org-time-today ()
14651 "Time in seconds today at 0:00.
14652 Returns the float number of seconds since the beginning of the
14653 epoch to the beginning of today (00:00)."
14654 (float-time (apply 'encode-time
14655 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14657 (defun org-matcher-time (s)
14658 "Interpret a time comparison value."
14661 ((string= s "<now>") (float-time))
14662 ((string= s "<today>") (org-time-today))
14663 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14664 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14665 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14666 (+ (org-time-today)
14667 (* (string-to-number (match-string 1 s))
14668 (cdr (assoc (match-string 2 s)
14669 '(("d" . 86400.0) ("w" . 604800.0)
14670 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14673 (defun org-match-any-p (re list)
14674 "Does re match any element of list?"
14675 (setq list (mapcar (lambda (x) (string-match re x)) list))
14678 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14679 (defvar org-tags-overlay (make-overlay 1 1))
14680 (delete-overlay org-tags-overlay)
14682 (defun org-get-local-tags-at (&optional pos)
14683 "Get a list of tags defined in the current headline."
14684 (org-get-tags-at pos 'local))
14686 (defun org-get-local-tags ()
14687 "Get a list of tags defined in the current headline."
14688 (org-get-tags-at nil 'local))
14690 (defun org-get-tags-at (&optional pos local)
14691 "Get a list of all headline tags applicable at POS.
14692 POS defaults to point. If tags are inherited, the list contains
14693 the targets in the same sequence as the headlines appear, i.e.
14694 the tags of the current headline come last.
14695 When LOCAL is non-nil, only return tags from the current headline,
14696 ignore inherited ones."
14698 (if (and org-trust-scanner-tags
14699 (or (not pos) (equal pos (point)))
14702 (let (tags ltags lastpos parent)
14706 (goto-char (or pos (point)))
14709 (condition-case nil
14711 (org-back-to-heading t)
14712 (while (not (equal lastpos (point)))
14713 (setq lastpos (point))
14714 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14715 (setq ltags (org-split-string
14716 (match-string-no-properties 1) ":"))
14718 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14721 (org-remove-uninherited-tags ltags)
14724 (or org-use-tag-inheritance (throw 'done t))
14725 (when local (throw 'done t))
14726 (or (org-up-heading-safe) (error nil))
14731 (reverse (delete-dups
14733 (org-remove-uninherited-tags
14737 (defun org-add-prop-inherited (s)
14738 (add-text-properties 0 (length s) '(inherited t) s)
14741 (defun org-toggle-tag (tag &optional onoff)
14742 "Toggle the tag TAG for the current line.
14743 If ONOFF is `on' or `off', don't toggle but set to this state."
14745 (org-back-to-heading t)
14747 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14748 (line-end-position) t)
14749 (let ((tags (match-string 1)))
14750 ;; Clear current tags.
14752 ;; Reverse the tags list so any new tag is appended to
14753 ;; the current list of tags.
14754 (nreverse (org-split-string tags ":")))))
14757 (`off (setq current (delete tag current)))
14758 ((or `on (guard (not (member tag current))))
14760 (cl-pushnew tag current :test #'equal))
14761 (_ (setq current (delete tag current))))
14765 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14766 (org-set-tags nil t))
14767 (delete-horizontal-space))
14768 (run-hooks 'org-after-tags-change-hook)
14771 (defun org--align-tags-here (to-col)
14772 "Align tags on the current headline to TO-COL.
14773 Assume point is on a headline."
14774 (let ((pos (point)))
14775 (beginning-of-line)
14776 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14777 (>= pos (match-beginning 2)))
14778 ;; No tags or point within tags: do not align.
14780 (goto-char (match-beginning 1))
14781 (let ((shift (max (- (if (>= to-col 0) to-col
14782 (- (abs to-col) (string-width (match-string 2))))
14785 (replace-match (make-string shift ?\s) nil nil nil 1)
14786 ;; Preserve initial position, if possible. In any case, stop
14788 (when (< pos (point)) (goto-char pos))))))
14790 (defun org-set-tags-command (&optional arg just-align)
14791 "Call the set-tags command for the current entry."
14793 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14794 (org-set-tags arg just-align)
14796 (unless (and (org-region-active-p)
14797 org-loop-over-headlines-in-active-region)
14798 (org-back-to-heading t))
14799 (org-set-tags arg just-align))))
14801 (defun org-set-tags-to (data)
14802 "Set the tags of the current entry to DATA, replacing the current tags.
14803 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14804 If DATA is nil or the empty string, any tags will be removed."
14805 (interactive "sTags: ")
14809 ((equal data "") "")
14811 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14814 (concat ":" (mapconcat 'identity data ":") ":"))))
14817 (org-back-to-heading t)
14818 (when (let ((case-fold-search nil))
14819 (looking-at org-complex-heading-regexp))
14822 (goto-char (match-beginning 5))
14824 (delete-region (point) (point-at-eol))
14825 (org-set-tags nil 'align))
14826 (goto-char (point-at-eol))
14828 (org-set-tags nil 'align)))
14829 (beginning-of-line 1)
14830 (when (looking-at ".*?\\([ \t]+\\)$")
14831 (delete-region (match-beginning 1) (match-end 1))))))
14833 (defun org-align-all-tags ()
14834 "Align the tags in all headings."
14837 (or (ignore-errors (org-back-to-heading t))
14838 (outline-next-heading))
14839 (if (org-at-heading-p)
14841 (message "No headings"))))
14843 (defvar org-indent-indentation-per-level)
14844 (defun org-set-tags (&optional arg just-align)
14845 "Set the tags for the current headline.
14846 With prefix ARG, realign all tags in headings in the current buffer.
14847 When JUST-ALIGN is non-nil, only align tags."
14849 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14850 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14851 'region-start-level
14853 org-loop-over-headlines-in-active-region)
14855 ;; We don't use ARG and JUST-ALIGN here because these args
14856 ;; are not useful when looping over headlines.
14858 org-loop-over-headlines-in-active-region
14860 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14861 (let ((org-setting-tags t))
14864 (goto-char (point-min))
14865 (while (re-search-forward org-outline-regexp-bol nil t)
14866 (org-set-tags nil t)
14868 (message "All tags realigned to column %d" org-tags-column))
14869 (let* ((current (org-get-tags-string))
14871 (if just-align current
14872 ;; Get a new set of tags from the user.
14877 org-last-tags-completion-table
14878 ;; Uniquify tags in alists, yet preserve
14879 ;; structure (i.e., keywords).
14883 (let ((head (car pair)))
14884 (cond ((symbolp head) pair)
14885 ((member head seen) nil)
14886 (t (push head seen)
14889 (or org-current-tag-alist
14890 (org-get-buffer-tags))
14892 org-complete-tags-always-offer-all-agenda-tags
14893 (org-global-tags-completion-table
14894 (org-agenda-files))))))))
14895 (current-tags (org-split-string current ":"))
14897 (nreverse (nthcdr (length current-tags)
14898 (nreverse (org-get-tags-at))))))
14899 (replace-regexp-in-string
14902 (if (or (eq t org-use-fast-tag-selection)
14903 (and org-use-fast-tag-selection
14904 (delq nil (mapcar #'cdr table))))
14905 (org-fast-tag-selection
14906 current-tags inherited-tags table
14907 (and org-fast-tag-selection-include-todo
14908 org-todo-key-alist))
14909 (let ((org-add-colon-after-tag-completion
14910 (< 1 (length table))))
14914 #'org-tags-completion-function
14915 nil nil current 'org-tags-history))))))))))
14917 (when org-tags-sort-function
14921 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14922 org-tags-sort-function)
14925 (if (or (string= ":" tags)
14926 (string= "::" tags))
14928 (if (not (org-string-nw-p tags)) (setq tags "")
14929 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14930 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14932 ;; Insert new tags at the correct column.
14933 (unless (equal current tags)
14935 (beginning-of-line)
14936 (let ((case-fold-search nil))
14937 (looking-at org-complex-heading-regexp))
14938 ;; Remove current tags, if any.
14939 (when (match-end 5) (replace-match "" nil nil nil 5))
14940 ;; Insert new tags, if any. Otherwise, remove trailing
14943 (if (not (equal tags ""))
14944 ;; When text is being inserted on an invisible
14945 ;; region boundary, it can be inadvertently sucked
14946 ;; into invisibility.
14947 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14948 (skip-chars-backward " \t")
14949 (delete-region (point) (line-end-position)))))
14950 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14952 (unless (equal tags "")
14953 (let* ((level (save-excursion
14954 (beginning-of-line)
14955 (skip-chars-forward "\\*")))
14956 (offset (if (bound-and-true-p org-indent-mode)
14957 (* (1- org-indent-indentation-per-level)
14962 (if (> org-tags-column 0) (- offset) offset))))
14963 (org--align-tags-here tags-column))))
14964 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14966 (defun org-change-tag-in-region (beg end tag off)
14967 "Add or remove TAG for each entry in the region.
14968 This works in the agenda, and also in an Org buffer."
14970 (list (region-beginning) (region-end)
14971 (let ((org-last-tags-completion-table
14972 (if (derived-mode-p 'org-mode)
14974 (delq nil (append (org-get-buffer-tags)
14975 (org-global-tags-completion-table))))
14976 (org-global-tags-completion-table))))
14978 "Tag: " 'org-tags-completion-function nil nil nil
14979 'org-tags-history))
14981 (message "[s]et or
[r]emove? ")
14982 (equal (read-char-exclusive) ?r))))
14983 (when (fboundp 'deactivate-mark) (deactivate-mark))
14984 (let ((agendap (equal major-mode 'org-agenda-mode))
14985 l1 l2 m buf pos newhead (cnt 0))
14987 (setq l2 (1- (org-current-line)))
14989 (setq l1 (org-current-line))
14990 (cl-loop for l from l1 to l2 do
14992 (setq m (get-text-property (point) 'org-hd-marker))
14993 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14995 (setq buf (if agendap (marker-buffer m) (current-buffer))
14996 pos (if agendap m (point)))
14997 (with-current-buffer buf
15001 (setq cnt (1+ cnt))
15002 (org-toggle-tag tag (if off 'off 'on))
15003 (setq newhead (org-get-heading)))))
15004 (and agendap (org-agenda-change-all-lines newhead m))))
15005 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15007 (defun org-tags-completion-function (string _predicate &optional flag)
15008 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15009 (confirm (lambda (x) (stringp (car x)))))
15010 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15011 (setq s1 (match-string 1 string)
15012 s2 (match-string 2 string))
15013 (setq s1 "" s2 string))
15017 (setq rtn (try-completion s2 ctable confirm))
15018 (when (stringp rtn)
15020 (concat s1 s2 (substring rtn (length s2))
15021 (if (and org-add-colon-after-tag-completion
15022 (assoc rtn ctable))
15027 (all-completions s2 ctable confirm))
15030 (assoc s2 ctable)))))
15032 (defun org-fast-tag-insert (kwd tags face &optional end)
15033 "Insert KDW, and the TAGS, the latter with face FACE.
15035 (insert (format "%-12s" (concat kwd ":"))
15036 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15039 (defun org-fast-tag-show-exit (flag)
15042 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15043 (replace-match ""))
15046 (org-move-to-column (- (window-width) 19) t)
15047 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15049 (defun org-set-current-tags-overlay (current prefix)
15050 "Add an overlay to CURRENT tag with PREFIX."
15051 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15052 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15053 (org-overlay-display org-tags-overlay (concat prefix s))))
15055 (defvar org-last-tag-selection-key nil)
15056 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15057 "Fast tag selection with single keys.
15058 CURRENT is the current list of tags in the headline, INHERITED is the
15059 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15060 possibly with grouping information. TODO-TABLE is a similar table with
15061 TODO keywords, should these have keys assigned to them.
15062 If the keys are nil, a-z are automatically assigned.
15063 Returns the new tags string, or nil to not change the current settings."
15064 (let* ((fulltable (append table todo-table))
15065 (maxlen (apply 'max (mapcar
15067 (if (stringp (car x)) (string-width (car x)) 0))
15069 (buf (current-buffer))
15070 (expert (eq org-fast-tag-selection-single-key 'expert))
15072 (fwidth (+ maxlen 3 1 3))
15073 (ncol (/ (- (window-width) 4) fwidth))
15076 tg cnt e c char c1 c2 ntable tbl rtn
15077 ov-start ov-end ov-prefix
15078 (exit-after-next org-fast-tag-selection-single-key)
15079 (done-keywords org-done-keywords)
15080 groups ingroup intaggroup)
15082 (beginning-of-line 1)
15083 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15084 (setq ov-start (match-beginning 1)
15085 ov-end (match-end 1)
15087 (setq ov-start (1- (point-at-eol))
15088 ov-end (1+ ov-start))
15089 (skip-chars-forward "^\n\r")
15092 (buffer-substring (1- (point)) (point))
15093 (if (> (current-column) org-tags-column)
15095 (make-string (- org-tags-column (current-column)) ?\ ))))))
15096 (move-overlay org-tags-overlay ov-start ov-end)
15097 (save-window-excursion
15099 (set-buffer (get-buffer-create " *Org tags*"))
15100 (delete-other-windows)
15101 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15102 (org-switch-to-buffer-other-window " *Org tags*"))
15104 (setq-local org-done-keywords done-keywords)
15105 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15106 (org-fast-tag-insert "Current" current c-face "\n\n")
15107 (org-fast-tag-show-exit exit-after-next)
15108 (org-set-current-tags-overlay current ov-prefix)
15109 (setq tbl fulltable char ?a cnt 0)
15110 (while (setq e (pop tbl))
15112 ((eq (car e) :startgroup)
15113 (push '() groups) (setq ingroup t)
15114 (unless (zerop cnt)
15117 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15118 ((eq (car e) :endgroup)
15119 (setq ingroup nil cnt 0)
15120 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15121 ((eq (car e) :startgrouptag)
15122 (setq intaggroup t)
15123 (unless (zerop cnt)
15127 ((eq (car e) :endgrouptag)
15128 (setq intaggroup nil cnt 0)
15130 ((equal e '(:newline))
15131 (unless (zerop cnt)
15135 (while (equal (car tbl) '(:newline))
15137 (setq tbl (cdr tbl)))))
15138 ((equal e '(:grouptags)) (insert " : "))
15140 (setq tg (copy-sequence (car e)) c2 nil)
15143 ;; automatically assign a character.
15144 (setq c1 (string-to-char
15145 (downcase (substring
15146 tg (if (= (string-to-char tg) ?@) 1 0)))))
15147 (if (or (rassoc c1 ntable) (rassoc c1 table))
15148 (while (or (rassoc char ntable) (rassoc char table))
15149 (setq char (1+ char)))
15151 (setq c (or c2 char)))
15152 (when ingroup (push tg (car groups)))
15153 (setq tg (org-add-props tg nil 'face
15155 ((not (assoc tg table))
15156 (org-get-todo-face tg))
15157 ((member tg current) c-face)
15158 ((member tg inherited) i-face))))
15159 (when (equal (caar tbl) :grouptags)
15160 (org-add-props tg nil 'face 'org-tag-group))
15161 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15162 (insert "[" c "] " tg (make-string
15163 (- fwidth 4 (length tg)) ?\ ))
15164 (push (cons tg c) ntable)
15165 (when (= (cl-incf cnt) ncol)
15167 (when (or ingroup intaggroup) (insert " "))
15169 (setq ntable (nreverse ntable))
15171 (goto-char (point-min))
15172 (unless expert (org-fit-window-to-buffer))
15176 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
15177 (if (not groups) "no " "")
15178 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15179 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15180 (setq org-last-tag-selection-key c)
15182 ((= c ?\r) (throw 'exit t))
15184 (setq groups (not groups))
15185 (goto-char (point-min))
15186 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15189 (org-fast-tag-show-exit
15190 (setq exit-after-next (not exit-after-next)))
15192 (delete-other-windows)
15193 (set-window-buffer (split-window-vertically) " *Org tags*")
15194 (org-switch-to-buffer-other-window " *Org tags*")
15195 (org-fit-window-to-buffer)))
15197 (and (= c ?q) (not (rassoc c ntable))))
15198 (delete-overlay org-tags-overlay)
15199 (setq quit-flag t))
15202 (when exit-after-next (setq exit-after-next 'now)))
15204 (condition-case nil
15205 (setq tg (completing-read
15208 (with-current-buffer buf
15210 (org-get-buffer-tags))))))
15211 (quit (setq tg "")))
15212 (when (string-match "\\S-" tg)
15213 (cl-pushnew (list tg) buffer-tags :test #'equal)
15214 (if (member tg current)
15215 (setq current (delete tg current))
15216 (push tg current)))
15217 (when exit-after-next (setq exit-after-next 'now)))
15218 ((setq e (rassoc c todo-table) tg (car e))
15219 (with-current-buffer buf
15220 (save-excursion (org-todo tg)))
15221 (when exit-after-next (setq exit-after-next 'now)))
15222 ((setq e (rassoc c ntable) tg (car e))
15223 (if (member tg current)
15224 (setq current (delete tg current))
15225 (cl-loop for g in groups do
15226 (when (member tg g)
15227 (dolist (x g) (setq current (delete x current)))))
15229 (when exit-after-next (setq exit-after-next 'now))))
15231 ;; Create a sorted list
15235 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15236 (when (eq exit-after-next 'now) (throw 'exit t))
15237 (goto-char (point-min))
15238 (beginning-of-line 2)
15239 (delete-region (point) (point-at-eol))
15240 (org-fast-tag-insert "Current" current c-face)
15241 (org-set-current-tags-overlay current ov-prefix)
15242 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15243 (setq tg (match-string 1))
15244 (add-text-properties
15245 (match-beginning 1) (match-end 1)
15248 ((member tg current) c-face)
15249 ((member tg inherited) i-face)
15250 (t (get-text-property (match-beginning 1) 'face))))))
15251 (goto-char (point-min)))))
15252 (delete-overlay org-tags-overlay)
15254 (mapconcat 'identity current ":")
15257 (defun org-get-tags-string ()
15258 "Get the TAGS string in the current headline."
15259 (unless (org-at-heading-p t)
15260 (user-error "Not on a heading"))
15262 (beginning-of-line 1)
15263 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15264 (match-string-no-properties 1)
15267 (defun org-get-tags ()
15268 "Get the list of tags specified in the current headline."
15269 (org-split-string (org-get-tags-string) ":"))
15271 (defun org-get-buffer-tags ()
15272 "Get a table of all tags used in the buffer, for completion."
15273 (org-with-wide-buffer
15274 (goto-char (point-min))
15275 (let ((tag-re (concat org-outline-regexp-bol
15276 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15278 (while (re-search-forward tag-re nil t)
15279 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15281 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15283 ;;;; The mapping API
15285 (defvar org-agenda-skip-comment-trees)
15286 (defvar org-agenda-skip-function)
15287 (defun org-map-entries (func &optional match scope &rest skip)
15288 "Call FUNC at each headline selected by MATCH in SCOPE.
15290 FUNC is a function or a lisp form. The function will be called without
15291 arguments, with the cursor positioned at the beginning of the headline.
15292 The return values of all calls to the function will be collected and
15293 returned as a list.
15295 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15296 does not need to preserve point. After evaluation, the cursor will be
15297 moved to the end of the line (presumably of the headline of the
15298 processed entry) and search continues from there. Under some
15299 circumstances, this may not produce the wanted results. For example,
15300 if you have removed (e.g. archived) the current (sub)tree it could
15301 mean that the next entry will be skipped entirely. In such cases, you
15302 can specify the position from where search should continue by making
15303 FUNC set the variable `org-map-continue-from' to the desired buffer
15306 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15307 Only headlines that are matched by this query will be considered during
15308 the iteration. When MATCH is nil or t, all headlines will be
15309 visited by the iteration.
15311 SCOPE determines the scope of this command. It can be any of:
15313 nil The current buffer, respecting the restriction if any
15314 tree The subtree started with the entry at point
15315 region The entries within the active region, if any
15317 The entries within the active region, but only those at
15318 the same level than the first one.
15319 file The current buffer, without restriction
15321 The current buffer, and any archives associated with it
15322 agenda All agenda files
15323 agenda-with-archives
15324 All agenda files with any archive files associated with them
15326 If this is a list, all files in the list will be scanned
15328 The remaining args are treated as settings for the skipping facilities of
15329 the scanner. The following items can be given here:
15331 archive skip trees with the archive tag
15332 comment skip trees with the COMMENT keyword
15333 function or Emacs Lisp form:
15334 will be used as value for `org-agenda-skip-function', so
15335 whenever the function returns a position, FUNC will not be
15336 called for that entry and search will continue from the
15339 If your function needs to retrieve the tags including inherited tags
15340 at the *current* entry, you can use the value of the variable
15341 `org-scanner-tags' which will be much faster than getting the value
15342 with `org-get-tags-at'. If your function gets properties with
15343 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15344 to t around the call to `org-entry-properties' to get the same speedup.
15345 Note that if your function moves around to retrieve tags and properties at
15346 a *different* entry, you cannot use these techniques."
15347 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15348 (not (org-region-active-p)))
15349 (let* ((org-agenda-archives-mode nil) ; just to make sure
15350 (org-agenda-skip-archived-trees (memq 'archive skip))
15351 (org-agenda-skip-comment-trees (memq 'comment skip))
15352 (org-agenda-skip-function
15353 (car (org-delete-all '(comment archive) skip)))
15354 (org-tags-match-list-sublevels t)
15355 (start-level (eq scope 'region-start-level))
15357 org-todo-keywords-for-agenda
15358 org-done-keywords-for-agenda
15359 org-todo-keyword-alist-for-agenda
15360 org-tag-alist-for-agenda
15361 org--matcher-tags-todo-only)
15364 ((eq match t) (setq matcher t))
15365 ((eq match nil) (setq matcher t))
15366 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15370 (cond ((eq scope 'tree)
15371 (org-back-to-heading t)
15372 (org-narrow-to-subtree)
15374 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15375 (org-region-active-p))
15376 ;; If needed, set start-level to a string like "2"
15379 (goto-char (region-beginning))
15380 (unless (org-at-heading-p) (outline-next-heading))
15381 (setq start-level (org-current-level))))
15382 (narrow-to-region (region-beginning)
15384 (goto-char (region-end))
15385 (unless (and (bolp) (org-at-heading-p))
15386 (outline-next-heading))
15392 (org-agenda-prepare-buffers
15393 (and buffer-file-name (list buffer-file-name)))
15396 func matcher org--matcher-tags-todo-only start-level)))
15397 ;; Get the right scope
15399 ((and scope (listp scope) (symbolp (car scope)))
15400 (setq scope (eval scope)))
15401 ((eq scope 'agenda)
15402 (setq scope (org-agenda-files t)))
15403 ((eq scope 'agenda-with-archives)
15404 (setq scope (org-agenda-files t))
15405 (setq scope (org-add-archive-files scope)))
15407 (setq scope (and buffer-file-name (list buffer-file-name))))
15408 ((eq scope 'file-with-archives)
15409 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15410 (org-agenda-prepare-buffers scope)
15411 (dolist (file scope)
15412 (with-current-buffer (org-find-base-buffer-visiting file)
15413 (org-with-wide-buffer
15414 (goto-char (point-min))
15419 func matcher org--matcher-tags-todo-only)))))))))
15424 (defconst org-special-properties
15425 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15426 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15427 "The special properties valid in Org mode.
15428 These are properties that are not defined in the property drawer,
15429 but in some other way.")
15431 (defconst org-default-properties
15432 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15433 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15434 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15435 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15436 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15437 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15438 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15439 "Some properties that are used by Org mode for various purposes.
15440 Being in this list makes sure that they are offered for completion.")
15442 (defun org--valid-property-p (property)
15443 "Non nil when string PROPERTY is a valid property name."
15445 (or (equal property "")
15446 (string-match-p "\\s-" property))))
15448 (defun org--update-property-plist (key val props)
15449 "Associate KEY to VAL in alist PROPS.
15450 Modifications are made by side-effect. Return new alist."
15451 (let* ((appending (string= (substring key -1) "+"))
15452 (key (if appending (substring key 0 -1) key))
15453 (old (assoc-string key props t)))
15454 (if (not old) (cons (cons key val) props)
15455 (setcdr old (if appending (concat (cdr old) " " val) val))
15458 (defun org-get-property-block (&optional beg force)
15459 "Return the (beg . end) range of the body of the property drawer.
15460 BEG is the beginning of the current subtree, or of the part
15461 before the first headline. If it is not given, it will be found.
15462 If the drawer does not exist, create it if FORCE is non-nil, or
15464 (org-with-wide-buffer
15465 (when beg (goto-char beg))
15466 (unless (org-before-first-heading-p)
15467 (let ((beg (cond (beg)
15468 ((or (not (featurep 'org-inlinetask))
15469 (org-inlinetask-in-task-p))
15470 (org-back-to-heading t))
15471 (t (org-with-limited-levels (org-back-to-heading t))))))
15473 (when (looking-at-p org-planning-line-re) (forward-line))
15474 (cond ((looking-at org-property-drawer-re)
15476 (cons (point) (progn (goto-char (match-end 0))
15477 (line-beginning-position))))
15480 (org-insert-property-drawer)
15481 (let ((pos (save-excursion (search-forward ":END:")
15482 (line-beginning-position))))
15483 (cons pos pos))))))))
15485 (defun org-at-property-p ()
15486 "Non-nil when point is inside a property drawer.
15487 See `org-property-re' for match data, if applicable."
15489 (beginning-of-line)
15490 (and (looking-at org-property-re)
15491 (let ((property-drawer (save-match-data (org-get-property-block))))
15492 (and property-drawer
15493 (>= (point) (car property-drawer))
15494 (< (point) (cdr property-drawer)))))))
15496 (defun org-property-action ()
15497 "Do an action on properties."
15499 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15500 (let ((c (read-char-exclusive)))
15502 (?s (call-interactively #'org-set-property))
15503 (?d (call-interactively #'org-delete-property))
15504 (?D (call-interactively #'org-delete-property-globally))
15505 (?c (call-interactively #'org-compute-property-at-point))
15506 (otherwise (user-error "No such property action %c" c)))))
15508 (defun org-inc-effort ()
15509 "Increment the value of the effort property in the current entry."
15511 (org-set-effort nil t))
15513 (defvar org-clock-effort) ; Defined in org-clock.el.
15514 (defvar org-clock-current-task) ; Defined in org-clock.el.
15515 (defun org-set-effort (&optional value increment)
15516 "Set the effort property of the current entry.
15517 With numerical prefix arg, use the nth allowed value, 0 stands for the
15518 10th allowed value.
15520 When INCREMENT is non-nil, set the property to the next allowed value."
15522 (when (equal value 0) (setq value 10))
15523 (let* ((completion-ignore-case t)
15524 (prop org-effort-property)
15525 (cur (org-entry-get nil prop))
15526 (allowed (org-property-get-allowed-values nil prop 'table))
15527 (existing (mapcar 'list (org-property-values prop)))
15528 (heading (nth 4 (org-heading-components)))
15531 ((stringp value) value)
15532 ((and allowed (integerp value))
15533 (or (car (nth (1- value) allowed))
15534 (car (org-last allowed))))
15535 ((and allowed increment)
15536 (or (cl-caadr (member (list cur) allowed))
15537 (user-error "Allowed effort values are not set")))
15539 (message "Select 1-9,0, [RET%s]: %s"
15540 (if cur (concat "=" cur) "")
15541 (mapconcat 'car allowed " "))
15542 (setq rpl (read-char-exclusive))
15543 (if (equal rpl ?\r)
15545 (setq rpl (- rpl ?0))
15546 (when (equal rpl 0) (setq rpl 10))
15547 (if (and (> rpl 0) (<= rpl (length allowed)))
15548 (car (nth (1- rpl) allowed))
15549 (org-completing-read "Effort: " allowed nil))))
15551 (org-completing-read
15552 (concat "Effort" (and cur (string-match "\\S-" cur)
15553 (concat " [" cur "]"))
15555 existing nil nil "" nil cur)))))
15556 (unless (equal (org-entry-get nil prop) val)
15557 (org-entry-put nil prop val))
15558 (org-refresh-property
15559 '((effort . identity)
15560 (effort-minutes . org-duration-to-minutes))
15562 (when (equal heading (bound-and-true-p org-clock-current-task))
15563 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15564 (org-clock-update-mode-line))
15565 (message "%s is now %s" prop val)))
15567 (defun org-entry-properties (&optional pom which)
15568 "Get all properties of the current entry.
15570 When POM is a buffer position, get all properties from the entry
15573 This includes the TODO keyword, the tags, time strings for
15574 deadline, scheduled, and clocking, and any additional properties
15575 defined in the entry.
15577 If WHICH is nil or `all', get all properties. If WHICH is
15578 `special' or `standard', only get that subclass. If WHICH is
15579 a string, only get that property.
15581 Return value is an alist. Keys are properties, as upcased
15583 (org-with-point-at pom
15584 (when (and (derived-mode-p 'org-mode)
15585 (ignore-errors (org-back-to-heading t)))
15587 (let* ((beg (point))
15588 (specific (and (stringp which) (upcase which)))
15589 (which (cond ((not specific) which)
15590 ((member specific org-special-properties) 'special)
15593 ;; Get the special properties, like TODO and TAGS.
15594 (when (memq which '(nil all special))
15595 (when (or (not specific) (string= specific "CLOCKSUM"))
15596 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15598 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15600 (when specific (throw 'exit props)))
15601 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15602 (let ((clocksumt (get-text-property (point)
15603 :org-clock-minutes-today)))
15605 (push (cons "CLOCKSUM_T"
15606 (org-duration-from-minutes clocksumt))
15608 (when specific (throw 'exit props)))
15609 (when (or (not specific) (string= specific "ITEM"))
15610 (let ((case-fold-search nil))
15611 (when (looking-at org-complex-heading-regexp)
15613 (let ((title (match-string-no-properties 4)))
15614 (if (org-string-nw-p title)
15615 (org-remove-tabs title)
15618 (when specific (throw 'exit props)))
15619 (when (or (not specific) (string= specific "TODO"))
15620 (let ((case-fold-search nil))
15621 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15622 (push (cons "TODO" (match-string-no-properties 2)) props)))
15623 (when specific (throw 'exit props)))
15624 (when (or (not specific) (string= specific "PRIORITY"))
15625 (push (cons "PRIORITY"
15626 (if (looking-at org-priority-regexp)
15627 (match-string-no-properties 2)
15628 (char-to-string org-default-priority)))
15630 (when specific (throw 'exit props)))
15631 (when (or (not specific) (string= specific "FILE"))
15632 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15634 (when specific (throw 'exit props)))
15635 (when (or (not specific) (string= specific "TAGS"))
15636 (let ((value (org-string-nw-p (org-get-tags-string))))
15637 (when value (push (cons "TAGS" value) props)))
15638 (when specific (throw 'exit props)))
15639 (when (or (not specific) (string= specific "ALLTAGS"))
15640 (let ((value (org-get-tags-at)))
15642 (push (cons "ALLTAGS"
15643 (format ":%s:" (mapconcat #'identity value ":")))
15645 (when specific (throw 'exit props)))
15646 (when (or (not specific) (string= specific "BLOCKED"))
15647 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15648 (when specific (throw 'exit props)))
15649 (when (or (not specific)
15650 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15652 (when (looking-at-p org-planning-line-re)
15654 (let ((bol (line-beginning-position))
15655 ;; Backward compatibility: time keywords used to
15656 ;; be configurable (before 8.3). Make sure we
15657 ;; get the correct keyword.
15658 (key-assoc `(("CLOSED" . ,org-closed-string)
15659 ("DEADLINE" . ,org-deadline-string)
15660 ("SCHEDULED" . ,org-scheduled-string))))
15661 (dolist (pair (if specific (list (assoc specific key-assoc))
15664 (when (search-backward (cdr pair) bol t)
15665 (goto-char (match-end 0))
15666 (skip-chars-forward " \t")
15667 (and (looking-at org-ts-regexp-both)
15668 (push (cons (car pair)
15669 (match-string-no-properties 0))
15671 (when specific (throw 'exit props)))
15672 (when (or (not specific)
15673 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15676 ;; Fix next time-stamp before END. TS is the
15677 ;; list of time-stamps found so far.
15680 ((string= specific "TIMESTAMP")
15682 ((string= specific "TIMESTAMP_IA")
15683 org-ts-regexp-inactive)
15684 ((assoc "TIMESTAMP_IA" ts)
15686 ((assoc "TIMESTAMP" ts)
15687 org-ts-regexp-inactive)
15688 (t org-ts-regexp-both))))
15690 (while (re-search-forward regexp end t)
15692 (let ((object (org-element-context)))
15693 ;; Accept to match timestamps in node
15694 ;; properties, too.
15695 (when (memq (org-element-type object)
15696 '(node-property timestamp))
15698 (org-element-property :type object)))
15700 ((and (memq type '(active active-range))
15701 (not (equal specific "TIMESTAMP_IA")))
15702 (unless (assoc "TIMESTAMP" ts)
15703 (push (cons "TIMESTAMP"
15704 (org-element-property
15705 :raw-value object))
15707 (when specific (throw 'exit ts))))
15708 ((and (memq type '(inactive inactive-range))
15709 (not (string= specific "TIMESTAMP")))
15710 (unless (assoc "TIMESTAMP_IA" ts)
15711 (push (cons "TIMESTAMP_IA"
15712 (org-element-property
15713 :raw-value object))
15715 (when specific (throw 'exit ts))))))
15716 ;; Both timestamp types are found,
15717 ;; move to next part.
15718 (when (= (length ts) 2) (throw 'next ts)))))
15721 ;; First look for timestamps within headline.
15722 (let ((ts (funcall find-ts (line-end-position) nil)))
15723 (if (= (length ts) 2) (setq props (nconc ts props))
15724 ;; Then find timestamps in the section, skipping
15726 (let ((end (save-excursion (outline-next-heading))))
15728 (when (looking-at-p org-planning-line-re) (forward-line))
15729 (setq props (nconc (funcall find-ts end ts) props))))))))
15730 ;; Get the standard properties, like :PROP:.
15731 (when (memq which '(nil all standard))
15732 ;; If we are looking after a specific property, delegate
15733 ;; to `org-entry-get', which is faster. However, make an
15734 ;; exception for "CATEGORY", since it can be also set
15735 ;; through keywords (i.e. #+CATEGORY).
15736 (if (and specific (not (equal specific "CATEGORY")))
15737 (let ((value (org-entry-get beg specific nil t)))
15738 (throw 'exit (and value (list (cons specific value)))))
15739 (let ((range (org-get-property-block beg)))
15741 (let ((end (cdr range)) seen-base)
15742 (goto-char (car range))
15743 ;; Unlike to `org--update-property-plist', we
15744 ;; handle the case where base values is found
15745 ;; after its extension. We also forbid standard
15746 ;; properties to be named as special properties.
15747 (while (re-search-forward org-property-re end t)
15748 (let* ((key (upcase (match-string-no-properties 2)))
15749 (extendp (string-match-p "\\+\\'" key))
15750 (key-base (if extendp (substring key 0 -1) key))
15751 (value (match-string-no-properties 3)))
15753 ((member-ignore-case key-base org-special-properties))
15756 (org--update-property-plist key value props)))
15757 ((member key seen-base))
15758 (t (push key seen-base)
15759 (let ((p (assoc-string key props t)))
15760 (if p (setcdr p (concat value " " (cdr p)))
15761 (push (cons key value) props))))))))))))
15762 (unless (assoc "CATEGORY" props)
15763 (push (cons "CATEGORY" (org-get-category beg)) props)
15764 (when (string= specific "CATEGORY") (throw 'exit props)))
15768 (defun org--property-local-values (property literal-nil)
15769 "Return value for PROPERTY in current entry.
15770 Value is a list whose car is the base value for PROPERTY and cdr
15771 a list of accumulated values. Return nil if neither is found in
15772 the entry. Also return nil when PROPERTY is set to \"nil\",
15773 unless LITERAL-NIL is non-nil."
15774 (let ((range (org-get-property-block)))
15776 (goto-char (car range))
15777 (let* ((case-fold-search t)
15782 (let ((v (and (re-search-forward
15783 (org-re-property property nil t) end t)
15784 (match-string-no-properties 3))))
15785 (list (if literal-nil v (org-not-nil v)))))))
15786 ;; Find additional values.
15787 (let* ((property+ (org-re-property (concat property "+") nil t)))
15788 (while (re-search-forward property+ end t)
15789 (push (match-string-no-properties 3) value)))
15790 ;; Return final values.
15791 (and (not (equal value '(nil))) (nreverse value))))))
15793 (defun org--property-global-value (property literal-nil)
15794 "Return value for PROPERTY in current buffer.
15795 Return value is a string. Return nil if property is not set
15796 globally. Also return nil when PROPERTY is set to \"nil\",
15797 unless LITERAL-NIL is non-nil."
15799 (cdr (or (assoc-string property org-file-properties t)
15800 (assoc-string property org-global-properties t)
15801 (assoc-string property org-global-properties-fixed t)))))
15802 (if literal-nil global (org-not-nil global))))
15804 (defun org-entry-get (pom property &optional inherit literal-nil)
15805 "Get value of PROPERTY for entry or content at point-or-marker POM.
15807 If INHERIT is non-nil and the entry does not have the property,
15808 then also check higher levels of the hierarchy. If INHERIT is
15809 the symbol `selective', use inheritance only if the setting in
15810 `org-use-property-inheritance' selects PROPERTY for inheritance.
15812 If the property is present but empty, the return value is the
15813 empty string. If the property is not present at all, nil is
15814 returned. In any other case, return the value as a string.
15815 Search is case-insensitive.
15817 If LITERAL-NIL is set, return the string value \"nil\" as
15818 a string, do not interpret it as the list atom nil. This is used
15819 for inheritance when a \"nil\" value can supersede a non-nil
15820 value higher up the hierarchy."
15821 (org-with-point-at pom
15823 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15824 ;; We need a special property. Use `org-entry-properties' to
15825 ;; retrieve it, but specify the wanted property.
15826 (cdr (assoc-string property (org-entry-properties nil property))))
15828 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15829 (org-entry-get-with-inheritance property literal-nil))
15831 (let* ((local (org--property-local-values property literal-nil))
15832 (value (and local (mapconcat #'identity (delq nil local) " "))))
15833 (if literal-nil value (org-not-nil value)))))))
15835 (defun org-property-or-variable-value (var &optional inherit)
15836 "Check if there is a property fixing the value of VAR.
15837 If yes, return this value. If not, return the current value of the variable."
15838 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15839 (if (and prop (stringp prop) (string-match "\\S-" prop))
15841 (symbol-value var))))
15843 (defun org-entry-delete (pom property)
15844 "Delete PROPERTY from entry at point-or-marker POM.
15845 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15846 non-nil when a property was removed."
15847 (org-with-point-at pom
15848 (pcase (org-get-property-block)
15849 (`(,begin . ,origin)
15850 (let* ((end (copy-marker origin))
15851 (re (org-re-property
15852 (concat (regexp-quote property) "\\+?") t t)))
15854 (while (re-search-forward re end t)
15855 (delete-region (match-beginning 0) (line-beginning-position 2)))
15856 ;; If drawer is empty, remove it altogether.
15857 (when (= begin end)
15858 (delete-region (line-beginning-position 0)
15859 (line-beginning-position 2)))
15860 ;; Return non-nil if some property was removed.
15861 (prog1 (/= end origin) (set-marker end nil))))
15864 ;; Multi-values properties are properties that contain multiple values
15865 ;; These values are assumed to be single words, separated by whitespace.
15866 (defun org-entry-add-to-multivalued-property (pom property value)
15867 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15868 (let* ((old (org-entry-get pom property))
15869 (values (and old (split-string old))))
15870 (setq value (org-entry-protect-space value))
15871 (unless (member value values)
15872 (setq values (append values (list value)))
15873 (org-entry-put pom property (mapconcat #'identity values " ")))))
15875 (defun org-entry-remove-from-multivalued-property (pom property value)
15876 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15877 (let* ((old (org-entry-get pom property))
15878 (values (and old (split-string old))))
15879 (setq value (org-entry-protect-space value))
15880 (when (member value values)
15881 (setq values (delete value values))
15882 (org-entry-put pom property (mapconcat #'identity values " ")))))
15884 (defun org-entry-member-in-multivalued-property (pom property value)
15885 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15886 (let* ((old (org-entry-get pom property))
15887 (values (and old (split-string old))))
15888 (setq value (org-entry-protect-space value))
15889 (member value values)))
15891 (defun org-entry-get-multivalued-property (pom property)
15892 "Return a list of values in a multivalued property."
15893 (let* ((value (org-entry-get pom property))
15894 (values (and value (split-string value))))
15895 (mapcar #'org-entry-restore-space values)))
15897 (defun org-entry-put-multivalued-property (pom property &rest values)
15898 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15899 VALUES should be a list of strings. Spaces will be protected."
15900 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15901 (let* ((value (org-entry-get pom property))
15902 (values (and value (split-string value))))
15903 (mapcar #'org-entry-restore-space values)))
15905 (defun org-entry-protect-space (s)
15906 "Protect spaces and newline in string S."
15907 (while (string-match " " s)
15908 (setq s (replace-match "%20" t t s)))
15909 (while (string-match "\n" s)
15910 (setq s (replace-match "%0A" t t s)))
15913 (defun org-entry-restore-space (s)
15914 "Restore spaces and newline in string S."
15915 (while (string-match "%20" s)
15916 (setq s (replace-match " " t t s)))
15917 (while (string-match "%0A" s)
15918 (setq s (replace-match "\n" t t s)))
15921 (defvar org-entry-property-inherited-from (make-marker)
15922 "Marker pointing to the entry from where a property was inherited.
15923 Each call to `org-entry-get-with-inheritance' will set this marker to the
15924 location of the entry where the inheritance search matched. If there was
15925 no match, the marker will point nowhere.
15926 Note that also `org-entry-get' calls this function, if the INHERIT flag
15929 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15930 "Get PROPERTY of entry or content at point, search higher levels if needed.
15931 The search will stop at the first ancestor which has the property defined.
15932 If the value found is \"nil\", return nil to show that the property
15933 should be considered as undefined (this is the meaning of nil here).
15934 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15935 (move-marker org-entry-property-inherited-from nil)
15936 (org-with-wide-buffer
15940 (let ((v (org--property-local-values property literal-nil)))
15943 (concat (mapconcat #'identity (delq nil v) " ")
15948 (org-back-to-heading t)
15949 (move-marker org-entry-property-inherited-from (point))
15951 ((org-up-heading-safe))
15953 (let ((global (org--property-global-value property literal-nil)))
15954 (cond ((not global))
15955 (value (setq value (concat global " " value)))
15956 (t (setq value global))))
15957 (throw 'exit nil))))))
15958 (if literal-nil value (org-not-nil value)))))
15960 (defvar org-property-changed-functions nil
15961 "Hook called when the value of a property has changed.
15962 Each hook function should accept two arguments, the name of the property
15963 and the new value.")
15965 (defun org-entry-put (pom property value)
15966 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15968 If the value is nil, it is converted to the empty string. If it
15969 is not a string, an error is raised. Also raise an error on
15970 invalid property names.
15972 PROPERTY can be any regular property (see
15973 `org-special-properties'). It can also be \"TODO\",
15974 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15976 For the last two properties, VALUE may have any of the special
15977 values \"earlier\" and \"later\". The function then increases or
15978 decreases scheduled or deadline date by one day."
15979 (cond ((null value) (setq value ""))
15980 ((not (stringp value)) (error "Properties values should be strings"))
15981 ((not (org--valid-property-p property))
15982 (user-error "Invalid property name: \"%s\"" property)))
15983 (org-with-point-at pom
15984 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15985 (org-back-to-heading t)
15986 (org-with-limited-levels (org-back-to-heading t)))
15987 (let ((beg (point)))
15989 ((equal property "TODO")
15990 (cond ((not (org-string-nw-p value)) (setq value 'none))
15991 ((not (member value org-todo-keywords-1))
15992 (user-error "\"%s\" is not a valid TODO state" value)))
15994 (org-set-tags nil 'align))
15995 ((equal property "PRIORITY")
15996 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15997 (org-set-tags nil 'align))
15998 ((equal property "SCHEDULED")
16000 (if (and (looking-at-p org-planning-line-re)
16002 org-scheduled-time-regexp (line-end-position) t))
16003 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16004 ((string= value "later") (org-timestamp-change 1 'day))
16005 ((string= value "") (org-schedule '(4)))
16006 (t (org-schedule nil value)))
16007 (if (member value '("earlier" "later" ""))
16008 (call-interactively #'org-schedule)
16009 (org-schedule nil value))))
16010 ((equal property "DEADLINE")
16012 (if (and (looking-at-p org-planning-line-re)
16014 org-deadline-time-regexp (line-end-position) t))
16015 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16016 ((string= value "later") (org-timestamp-change 1 'day))
16017 ((string= value "") (org-deadline '(4)))
16018 (t (org-deadline nil value)))
16019 (if (member value '("earlier" "later" ""))
16020 (call-interactively #'org-deadline)
16021 (org-deadline nil value))))
16022 ((member property org-special-properties)
16023 (error "The %s property cannot be set with `org-entry-put'" property))
16025 (let* ((range (org-get-property-block beg 'force))
16027 (case-fold-search t))
16028 (goto-char (car range))
16029 (if (re-search-forward (org-re-property property nil t) end t)
16030 (progn (delete-region (match-beginning 0) (match-end 0))
16031 (goto-char (match-beginning 0)))
16035 (insert ":" property ":")
16036 (when value (insert " " value))
16037 (org-indent-line)))))
16038 (run-hook-with-args 'org-property-changed-functions property value)))
16040 (defun org-buffer-property-keys
16041 (&optional specials defaults columns ignore-malformed)
16042 "Get all property keys in the current buffer.
16044 When SPECIALS is non-nil, also list the special properties that
16045 reflect things like tags and TODO state.
16047 When DEFAULTS is non-nil, also include properties that has
16048 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16049 DESCRIPTION, LOCATION, and LOGGING and others.
16051 When COLUMNS in non-nil, also include property names given in
16052 COLUMN formats in the current buffer.
16054 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16055 automatically performed, such drawers will be silently ignored."
16056 (let ((case-fold-search t)
16058 (and specials org-special-properties)
16059 (and defaults (cons org-effort-property org-default-properties))
16061 (org-with-wide-buffer
16062 (goto-char (point-min))
16063 (while (re-search-forward org-property-start-re nil t)
16064 (let ((range (org-get-property-block)))
16067 (when (and (not ignore-malformed)
16068 (not (org-before-first-heading-p))
16069 (y-or-n-p (format "Malformed drawer at %d, repair?"
16070 (line-beginning-position))))
16071 (org-get-property-block nil t))
16073 (goto-char (car range))
16074 (let ((begin (car range))
16076 ;; Make sure that found property block is not located
16077 ;; before current point, as it would generate an infloop.
16078 ;; It can happen, for example, in the following
16085 ;; *************** Inlinetask
16090 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16091 (while (< (point) end)
16092 (let ((p (progn (looking-at org-property-re)
16093 (match-string-no-properties 2))))
16094 ;; Only add true property name, not extension symbol.
16095 (push (if (not (string-match-p "\\+\\'" p)) p
16096 (substring p 0 -1))
16099 (outline-next-heading)))
16101 (goto-char (point-min))
16102 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16103 (let ((element (org-element-at-point)))
16104 (when (memq (org-element-type element) '(keyword node-property))
16105 (let ((value (org-element-property :value element))
16107 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
16110 (setq start (match-end 0))
16111 (let ((p (match-string-no-properties 1 value)))
16112 (unless (member-ignore-case p org-special-properties)
16113 (push p props))))))))))
16114 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16116 (defun org-property-values (key)
16117 "List all non-nil values of property KEY in current buffer."
16118 (org-with-wide-buffer
16119 (goto-char (point-min))
16120 (let ((case-fold-search t)
16121 (re (org-re-property key))
16123 (while (re-search-forward re nil t)
16124 (push (org-entry-get (point) key) values))
16125 (delete-dups values))))
16127 (defun org-insert-property-drawer ()
16128 "Insert a property drawer into the current entry."
16129 (org-with-wide-buffer
16130 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16131 (org-back-to-heading t)
16132 (org-with-limited-levels (org-back-to-heading t)))
16134 (when (looking-at-p org-planning-line-re) (forward-line))
16135 (unless (looking-at-p org-property-drawer-re)
16136 ;; Make sure we start editing a line from current entry, not from
16137 ;; next one. It prevents extending text properties or overlays
16138 ;; belonging to the latter.
16139 (when (bolp) (backward-char))
16140 (let ((begin (1+ (point)))
16141 (inhibit-read-only t))
16142 (insert "\n:PROPERTIES:\n:END:")
16143 (when (eobp) (insert "\n"))
16144 (org-indent-region begin (point))))))
16146 (defun org-insert-drawer (&optional arg drawer)
16147 "Insert a drawer at point.
16149 When optional argument ARG is non-nil, insert a property drawer.
16151 Optional argument DRAWER, when non-nil, is a string representing
16152 drawer's name. Otherwise, the user is prompted for a name.
16154 If a region is active, insert the drawer around that region
16157 Point is left between drawer's boundaries."
16159 (let* ((drawer (if arg "PROPERTIES"
16160 (or drawer (read-from-minibuffer "Drawer: ")))))
16162 ;; With C-u, fall back on `org-insert-property-drawer'
16163 (arg (org-insert-property-drawer))
16164 ;; Check validity of suggested drawer's name.
16165 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16166 (user-error "Invalid drawer name"))
16167 ;; With an active region, insert a drawer at point.
16168 ((not (org-region-active-p))
16170 (unless (bolp) (insert "\n"))
16171 (insert (format ":%s:\n\n:END:\n" drawer))
16172 (forward-line -2)))
16173 ;; Otherwise, insert the drawer at point
16175 (let ((rbeg (region-beginning))
16176 (rend (copy-marker (region-end))))
16180 (beginning-of-line)
16181 (when (save-excursion
16182 (re-search-forward org-outline-regexp-bol rend t))
16183 (user-error "Drawers cannot contain headlines"))
16184 ;; Position point at the beginning of the first
16185 ;; non-blank line in region. Insert drawer's opening
16186 ;; there, then indent it.
16187 (org-skip-whitespace)
16188 (beginning-of-line)
16189 (insert ":" drawer ":\n")
16191 (indent-for-tab-command)
16192 ;; Move point to the beginning of the first blank line
16193 ;; after the last non-blank line in region. Insert
16194 ;; drawer's closing, then indent it.
16196 (skip-chars-backward " \r\t\n")
16198 (deactivate-mark t)
16199 (indent-for-tab-command)
16200 (unless (eolp) (insert "\n")))
16201 ;; Clear marker, whatever the outcome of insertion is.
16202 (set-marker rend nil)))))))
16204 (defvar org-property-set-functions-alist nil
16205 "Property set function alist.
16206 Each entry should have the following format:
16208 (PROPERTY . READ-FUNCTION)
16210 The read function will be called with the same argument as
16211 `org-completing-read'.")
16213 (defun org-set-property-function (property)
16214 "Get the function that should be used to set PROPERTY.
16215 This is computed according to `org-property-set-functions-alist'."
16216 (or (cdr (assoc property org-property-set-functions-alist))
16217 'org-completing-read))
16219 (defun org-read-property-value (property)
16220 "Read PROPERTY value from user."
16221 (let* ((completion-ignore-case t)
16222 (allowed (org-property-get-allowed-values nil property 'table))
16223 (cur (org-entry-get nil property))
16224 (prompt (concat property " value"
16225 (if (and cur (string-match "\\S-" cur))
16226 (concat " [" cur "]") "") ": "))
16227 (set-function (org-set-property-function property))
16229 (funcall set-function prompt allowed nil
16230 (not (get-text-property 0 'org-unrestricted
16232 (funcall set-function prompt
16233 (mapcar 'list (org-property-values property))
16234 nil nil "" nil cur))))
16237 (defvar org-last-set-property nil)
16238 (defvar org-last-set-property-value nil)
16239 (defun org-read-property-name ()
16240 "Read a property name."
16241 (let ((completion-ignore-case t)
16242 (default-prop (or (and (org-at-property-p)
16243 (match-string-no-properties 2))
16244 org-last-set-property)))
16245 (org-completing-read
16247 (if default-prop (concat " [" default-prop "]") "")
16249 (mapcar #'list (org-buffer-property-keys nil t t))
16250 nil nil nil nil default-prop)))
16252 (defun org-set-property-and-value (use-last)
16253 "Allow to set [PROPERTY]: [value] direction from prompt.
16254 When use-default, don't even ask, just use the last
16255 \"[PROPERTY]: [value]\" string from the history."
16257 (let* ((completion-ignore-case t)
16258 (pv (or (and use-last org-last-set-property-value)
16259 (org-completing-read
16260 "Enter a \"[Property]: [value]\" pair: "
16261 nil nil nil nil nil
16262 org-last-set-property-value)))
16264 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16265 (setq prop (match-string 1 pv)
16266 val (match-string 2 pv))
16267 (org-set-property prop val))))
16269 (defun org-set-property (property value)
16270 "In the current entry, set PROPERTY to VALUE.
16272 When called interactively, this will prompt for a property name, offering
16273 completion on existing and default properties. And then it will prompt
16274 for a value, offering completion either on allowed values (via an inherited
16275 xxx_ALL property) or on existing values in other instances of this property
16276 in the current file.
16278 Throw an error when trying to set a property with an invalid name."
16279 (interactive (list nil nil))
16280 (let ((property (or property (org-read-property-name))))
16281 ;; `org-entry-put' also makes the following check, but this one
16282 ;; avoids polluting `org-last-set-property' and
16283 ;; `org-last-set-property-value' needlessly.
16284 (unless (org--valid-property-p property)
16285 (user-error "Invalid property name: \"%s\"" property))
16286 (let ((value (or value (org-read-property-value property)))
16287 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16288 (setq org-last-set-property property)
16289 (setq org-last-set-property-value (concat property ": " value))
16290 ;; Possibly postprocess the inserted value:
16291 (when fn (setq value (funcall fn value)))
16292 (unless (equal (org-entry-get nil property) value)
16293 (org-entry-put nil property value)))))
16295 (defun org-find-property (property &optional value)
16296 "Find first entry in buffer that sets PROPERTY.
16298 When optional argument VALUE is non-nil, only consider an entry
16299 if it contains PROPERTY set to this value. If PROPERTY should be
16300 explicitly set to nil, use string \"nil\" for VALUE.
16302 Return position where the entry begins, or nil if there is no
16303 such entry. If narrowing is in effect, only search the visible
16304 part of the buffer."
16306 (goto-char (point-min))
16307 (let ((case-fold-search t)
16308 (re (org-re-property property nil (not value) value)))
16310 (while (re-search-forward re nil t)
16311 (when (if value (org-at-property-p)
16312 (org-entry-get (point) property nil t))
16313 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16315 (defun org-delete-property (property)
16316 "In the current entry, delete PROPERTY."
16318 (let* ((completion-ignore-case t)
16319 (cat (org-entry-get (point) "CATEGORY"))
16320 (props0 (org-entry-properties nil 'standard))
16321 (props (if cat props0
16322 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16323 (prop (if (< 1 (length props))
16324 (completing-read "Property: " props nil t)
16328 (message "No property to delete in this entry")
16329 (org-entry-delete nil property)
16330 (message "Property \"%s\" deleted" property)))
16332 (defun org-delete-property-globally (property)
16333 "Remove PROPERTY globally, from all entries.
16334 This function ignores narrowing, if any."
16336 (let* ((completion-ignore-case t)
16337 (prop (completing-read
16338 "Globally remove property: "
16339 (mapcar #'list (org-buffer-property-keys)))))
16341 (org-with-wide-buffer
16342 (goto-char (point-min))
16344 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16345 (while (re-search-forward re nil t)
16346 (when (org-entry-delete (point) property) (cl-incf count)))
16347 (message "Property \"%s\" removed from %d entries" property count))))
16349 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16351 (defun org-compute-property-at-point ()
16352 "Compute the property at point.
16353 This looks for an enclosing column format, extracts the operator and
16354 then applies it to the property in the column format's scope."
16356 (unless (org-at-property-p)
16357 (user-error "Not at a property"))
16358 (let ((prop (match-string-no-properties 2)))
16359 (org-columns-get-format-and-top-level)
16360 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16361 (user-error "No operator defined for property %s" prop))
16362 (org-columns-compute prop)))
16364 (defvar org-property-allowed-value-functions nil
16365 "Hook for functions supplying allowed values for a specific property.
16366 The functions must take a single argument, the name of the property, and
16367 return a flat list of allowed values. If \":ETC\" is one of
16368 the values, this means that these values are intended as defaults for
16369 completion, but that other values should be allowed too.
16370 The functions must return nil if they are not responsible for this
16373 (defun org-property-get-allowed-values (pom property &optional table)
16374 "Get allowed values for the property PROPERTY.
16375 When TABLE is non-nil, return an alist that can directly be used for
16379 ((equal property "TODO")
16380 (setq vals (org-with-point-at pom
16381 (append org-todo-keywords-1 '("")))))
16382 ((equal property "PRIORITY")
16383 (let ((n org-lowest-priority))
16384 (while (>= n org-highest-priority)
16385 (push (char-to-string n) vals)
16387 ((equal property "CATEGORY"))
16388 ((member property org-special-properties))
16389 ((setq vals (run-hook-with-args-until-success
16390 'org-property-allowed-value-functions property)))
16392 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16393 (when (and vals (string-match "\\S-" vals))
16394 (setq vals (car (read-from-string (concat "(" vals ")"))))
16395 (setq vals (mapcar (lambda (x)
16396 (cond ((stringp x) x)
16397 ((numberp x) (number-to-string x))
16398 ((symbolp x) (symbol-name x))
16401 (when (member ":ETC" vals)
16402 (setq vals (remove ":ETC" vals))
16403 (org-add-props (car vals) '(org-unrestricted t)))
16404 (if table (mapcar 'list vals) vals)))
16406 (defun org-property-previous-allowed-value (&optional _previous)
16407 "Switch to the next allowed value for this property."
16409 (org-property-next-allowed-value t))
16411 (defun org-property-next-allowed-value (&optional previous)
16412 "Switch to the next allowed value for this property."
16414 (unless (org-at-property-p)
16415 (user-error "Not at a property"))
16416 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16417 (key (match-string 2))
16418 (value (match-string 3))
16419 (allowed (or (org-property-get-allowed-values (point) key)
16420 (and (member value '("[ ]" "[-]" "[X]"))
16422 (heading (save-match-data (nth 4 (org-heading-components))))
16425 (user-error "Allowed values for this property have not been defined"))
16426 (when previous (setq allowed (reverse allowed)))
16427 (when (member value allowed)
16428 (setq nval (car (cdr (member value allowed)))))
16429 (setq nval (or nval (car allowed)))
16430 (when (equal nval value)
16431 (user-error "Only one allowed value for this property"))
16432 (org-at-property-p)
16433 (replace-match (concat " :" key ": " nval) t t)
16435 (beginning-of-line 1)
16436 (skip-chars-forward " \t")
16437 (when (equal prop org-effort-property)
16438 (org-refresh-property
16439 '((effort . identity)
16440 (effort-minutes . org-duration-to-minutes))
16442 (when (string= org-clock-current-task heading)
16443 (setq org-clock-effort nval)
16444 (org-clock-update-mode-line)))
16445 (run-hook-with-args 'org-property-changed-functions key nval)))
16447 (defun org-find-olp (path &optional this-buffer)
16448 "Return a marker pointing to the entry at outline path OLP.
16449 If anything goes wrong, throw an error.
16450 You can wrap this call to catch the error like this:
16452 (condition-case msg
16453 (org-mobile-locate-entry (match-string 4))
16454 (error (nth 1 msg)))
16456 The return value will then be either a string with the error message,
16457 or a marker if everything is OK.
16459 If THIS-BUFFER is set, the outline path does not contain a file,
16461 (let* ((file (if this-buffer buffer-file-name (pop path)))
16462 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16467 (unless buffer (error "File not found :%s" file))
16468 (with-current-buffer buffer
16469 (unless (derived-mode-p 'org-mode)
16470 (error "Buffer %s needs to be in Org mode" buffer))
16471 (org-with-wide-buffer
16472 (goto-char (point-min))
16473 (dolist (heading path)
16474 (let ((re (format org-complex-heading-regexp-format
16475 (regexp-quote heading)))
16477 (while (re-search-forward re end t)
16478 (setq level (- (match-end 1) (match-beginning 1)))
16479 (when (and (>= level lmin) (<= level lmax))
16480 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16482 (error "Heading not found on level %d: %s" lmax heading))
16484 (error "Heading not unique on level %d: %s" lmax heading))
16486 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16487 (setq end (save-excursion (org-end-of-subtree t t)))))
16488 (when (org-at-heading-p)
16489 (point-marker))))))
16491 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16492 "Find node HEADING in BUFFER.
16493 Return a marker to the heading if it was found, or nil if not.
16494 If POS-ONLY is set, return just the position instead of a marker.
16496 The heading text must match exact, but it may have a TODO keyword,
16497 a priority cookie and tags in the standard locations."
16498 (with-current-buffer (or buffer (current-buffer))
16499 (org-with-wide-buffer
16500 (goto-char (point-min))
16501 (let (case-fold-search)
16502 (when (re-search-forward
16503 (format org-complex-heading-regexp-format
16504 (regexp-quote heading)) nil t)
16506 (match-beginning 0)
16507 (move-marker (make-marker) (match-beginning 0))))))))
16509 (defun org-find-exact-heading-in-directory (heading &optional dir)
16510 "Find Org node headline HEADING in all .org files in directory DIR.
16511 When the target headline is found, return a marker to this location."
16512 (let ((files (directory-files (or dir default-directory)
16513 t "\\`[^.#].*\\.org\\'"))
16516 (dolist (file files)
16517 (message "trying %s" file)
16518 (setq visiting (org-find-base-buffer-visiting file))
16519 (setq buffer (or visiting (find-file-noselect file)))
16520 (setq m (org-find-exact-headline-in-buffer
16522 (when (and (not m) (not visiting)) (kill-buffer buffer))
16523 (and m (throw 'found m))))))
16525 (defun org-find-entry-with-id (ident)
16526 "Locate the entry that contains the ID property with exact value IDENT.
16527 IDENT can be a string, a symbol or a number, this function will search for
16528 the string representation of it.
16529 Return the position where this entry starts, or nil if there is no such entry."
16530 (interactive "sID: ")
16532 ((stringp ident) ident)
16533 ((symbolp ident) (symbol-name ident))
16534 ((numberp ident) (number-to-string ident))
16535 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16536 (org-with-wide-buffer (org-find-property "ID" id))))
16540 (defvar org-last-changed-timestamp nil)
16541 (defvar org-last-inserted-timestamp nil
16542 "The last time stamp inserted with `org-insert-time-stamp'.")
16544 (defun org-time-stamp (arg &optional inactive)
16545 "Prompt for a date/time and insert a time stamp.
16547 If the user specifies a time like HH:MM or if this command is
16548 called with at least one prefix argument, the time stamp contains
16549 the date and the time. Otherwise, only the date is included.
16551 All parts of a date not specified by the user are filled in from
16552 the timestamp at point, if any, or the current date/time
16555 If there is already a timestamp at the cursor, it is replaced.
16557 With two universal prefix arguments, insert an active timestamp
16558 with the current time without prompting the user.
16560 When called from lisp, the timestamp is inactive if INACTIVE is
16564 ((org-at-date-range-p t)
16565 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16566 ((org-at-timestamp-p 'lax) (match-string 0))))
16567 ;; Default time is either the timestamp at point or today.
16568 ;; When entering a range, only the range start is considered.
16569 (default-time (if (not ts) (current-time)
16570 (apply #'encode-time (org-parse-time-string ts))))
16571 (default-input (and ts (org-get-compact-tod ts)))
16573 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16574 (match-string 0 ts)))
16576 org-end-time-was-given
16578 (and (if (equal arg '(16)) (current-time)
16579 ;; Preserve `this-command' and `last-command'.
16580 (let ((this-command this-command)
16581 (last-command last-command))
16583 arg 'totime nil nil default-time default-input
16587 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16588 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16590 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16592 ;; Make sure we're on a timestamp. When in the middle of a date
16593 ;; range, move arbitrarily to range end.
16594 (unless (org-at-timestamp-p 'lax)
16595 (skip-chars-forward "-")
16596 (org-at-timestamp-p 'lax))
16598 (setq org-last-changed-timestamp
16599 (org-insert-time-stamp
16600 time (or org-time-was-given arg)
16601 inactive nil nil (list org-end-time-was-given)))
16604 (insert " " repeater)
16605 (setq org-last-changed-timestamp
16606 (concat (substring org-last-inserted-timestamp 0 -1)
16607 " " repeater ">")))
16608 (message "Timestamp updated"))
16609 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16610 (t (org-insert-time-stamp
16611 time (or org-time-was-given arg) inactive nil nil
16612 (list org-end-time-was-given))))))
16614 ;; FIXME: can we use this for something else, like computing time differences?
16615 (defun org-get-compact-tod (s)
16616 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16617 (let* ((t1 (match-string 1 s))
16618 (h1 (string-to-number (match-string 2 s)))
16619 (m1 (string-to-number (match-string 3 s)))
16620 (t2 (and (match-end 4) (match-string 5 s)))
16621 (h2 (and t2 (string-to-number (match-string 6 s))))
16622 (m2 (and t2 (string-to-number (match-string 7 s))))
16626 (setq dh (- h2 h1) dm (- m2 m1))
16627 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16628 (concat t1 "+" (number-to-string dh)
16629 (and (/= 0 dm) (format ":%02d" dm)))))))
16631 (defun org-time-stamp-inactive (&optional arg)
16632 "Insert an inactive time stamp.
16633 An inactive time stamp is enclosed in square brackets instead of angle
16634 brackets. It is inactive in the sense that it does not trigger agenda entries,
16635 does not link to the calendar and cannot be changed with the S-cursor keys.
16636 So these are more for recording a certain time/date."
16638 (org-time-stamp arg 'inactive))
16640 (defvar org-date-ovl (make-overlay 1 1))
16641 (overlay-put org-date-ovl 'face 'org-date-selected)
16642 (delete-overlay org-date-ovl)
16644 (defvar org-ans1) ; dynamically scoped parameter
16645 (defvar org-ans2) ; dynamically scoped parameter
16647 (defvar org-plain-time-of-day-regexp) ; defined below
16649 (defvar org-overriding-default-time nil) ; dynamically scoped
16650 (defvar org-read-date-overlay nil)
16651 (defvar org-dcst nil) ; dynamically scoped
16652 (defvar org-read-date-history nil)
16653 (defvar org-read-date-final-answer nil)
16654 (defvar org-read-date-analyze-futurep nil)
16655 (defvar org-read-date-analyze-forced-year nil)
16656 (defvar org-read-date-inactive)
16658 (defvar org-read-date-minibuffer-local-map
16659 (let* ((map (make-sparse-keymap)))
16660 (set-keymap-parent map minibuffer-local-map)
16661 (org-defkey map (kbd ".")
16662 (lambda () (interactive)
16663 ;; Are we at the beginning of the prompt?
16664 (if (looking-back "^[^:]+: "
16665 (let ((inhibit-field-text-motion t))
16666 (line-beginning-position)))
16667 (org-eval-in-calendar '(calendar-goto-today))
16669 (org-defkey map (kbd "C-.")
16670 (lambda () (interactive)
16671 (org-eval-in-calendar '(calendar-goto-today))))
16672 (org-defkey map [(meta shift left)]
16673 (lambda () (interactive)
16674 (org-eval-in-calendar '(calendar-backward-month 1))))
16675 (org-defkey map [(meta shift right)]
16676 (lambda () (interactive)
16677 (org-eval-in-calendar '(calendar-forward-month 1))))
16678 (org-defkey map [(meta shift up)]
16679 (lambda () (interactive)
16680 (org-eval-in-calendar '(calendar-backward-year 1))))
16681 (org-defkey map [(meta shift down)]
16682 (lambda () (interactive)
16683 (org-eval-in-calendar '(calendar-forward-year 1))))
16684 (org-defkey map [?\e (shift left)]
16685 (lambda () (interactive)
16686 (org-eval-in-calendar '(calendar-backward-month 1))))
16687 (org-defkey map [?\e (shift right)]
16688 (lambda () (interactive)
16689 (org-eval-in-calendar '(calendar-forward-month 1))))
16690 (org-defkey map [?\e (shift up)]
16691 (lambda () (interactive)
16692 (org-eval-in-calendar '(calendar-backward-year 1))))
16693 (org-defkey map [?\e (shift down)]
16694 (lambda () (interactive)
16695 (org-eval-in-calendar '(calendar-forward-year 1))))
16696 (org-defkey map [(shift up)]
16697 (lambda () (interactive)
16698 (org-eval-in-calendar '(calendar-backward-week 1))))
16699 (org-defkey map [(shift down)]
16700 (lambda () (interactive)
16701 (org-eval-in-calendar '(calendar-forward-week 1))))
16702 (org-defkey map [(shift left)]
16703 (lambda () (interactive)
16704 (org-eval-in-calendar '(calendar-backward-day 1))))
16705 (org-defkey map [(shift right)]
16706 (lambda () (interactive)
16707 (org-eval-in-calendar '(calendar-forward-day 1))))
16708 (org-defkey map "!"
16709 (lambda () (interactive)
16710 (org-eval-in-calendar '(diary-view-entries))
16712 (org-defkey map ">"
16713 (lambda () (interactive)
16714 (org-eval-in-calendar '(calendar-scroll-left 1))))
16715 (org-defkey map "<"
16716 (lambda () (interactive)
16717 (org-eval-in-calendar '(calendar-scroll-right 1))))
16718 (org-defkey map "\C-v"
16719 (lambda () (interactive)
16720 (org-eval-in-calendar
16721 '(calendar-scroll-left-three-months 1))))
16722 (org-defkey map "\M-v"
16723 (lambda () (interactive)
16724 (org-eval-in-calendar
16725 '(calendar-scroll-right-three-months 1))))
16727 "Keymap for minibuffer commands when using `org-read-date'.")
16730 (defvar org-defdecode)
16731 (defvar org-with-time)
16733 (defvar calendar-setup) ; Dynamically scoped.
16734 (defun org-read-date (&optional with-time to-time from-string prompt
16735 default-time default-input inactive)
16736 "Read a date, possibly a time, and make things smooth for the user.
16737 The prompt will suggest to enter an ISO date, but you can also enter anything
16738 which will at least partially be understood by `parse-time-string'.
16739 Unrecognized parts of the date will default to the current day, month, year,
16740 hour and minute. If this command is called to replace a timestamp at point,
16741 or to enter the second timestamp of a range, the default time is taken
16742 from the existing stamp. Furthermore, the command prefers the future,
16743 so if you are giving a date where the year is not given, and the day-month
16744 combination is already past in the current year, it will assume you
16745 mean next year. For details, see the manual. A few examples:
16747 3-2-5 --> 2003-02-05
16748 feb 15 --> currentyear-02-15
16749 2/15 --> currentyear-02-15
16750 sep 12 9 --> 2009-09-12
16751 12:45 --> today 12:45
16752 22 sept 0:34 --> currentyear-09-22 0:34
16753 12 --> currentyear-currentmonth-12
16754 Fri --> nearest Friday after today
16755 -Tue --> last Tuesday
16758 Furthermore you can specify a relative date by giving, as the *first* thing
16759 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16760 change in days weeks, months, years.
16761 With a single plus or minus, the date is relative to today. With a double
16762 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16763 +4d --> four days from today
16764 +4 --> same as above
16765 +2w --> two weeks from today
16766 ++5 --> five days from default date
16768 The function understands only English month and weekday abbreviations.
16770 While prompting, a calendar is popped up - you can also select the
16771 date with the mouse (button 1). The calendar shows a period of three
16772 months. To scroll it to other months, use the keys `>' and `<'.
16773 If you don't like the calendar, turn it off with
16774 (setq org-read-date-popup-calendar nil)
16776 With optional argument TO-TIME, the date will immediately be converted
16777 to an internal time.
16778 With an optional argument WITH-TIME, the prompt will suggest to
16779 also insert a time. Note that when WITH-TIME is not set, you can
16780 still enter a time, and this function will inform the calling routine
16781 about this change. The calling routine may then choose to change the
16782 format used to insert the time stamp into the buffer to include the time.
16783 With optional argument FROM-STRING, read from this string instead from
16784 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16785 the time/date that is used for everything that is not specified by the
16787 (require 'parse-time)
16788 (let* ((org-with-time with-time)
16789 (org-time-stamp-rounding-minutes
16790 (if (equal org-with-time '(16))
16792 org-time-stamp-rounding-minutes))
16793 (org-dcst org-display-custom-times)
16794 (ct (org-current-time))
16795 (org-def (or org-overriding-default-time default-time ct))
16796 (org-defdecode (decode-time org-def))
16797 (cur-frame (selected-frame))
16798 (mouse-autoselect-window nil) ; Don't let the mouse jump
16800 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16801 (calendar-move-hook nil)
16802 (calendar-view-diary-initially-flag nil)
16803 (calendar-view-holidays-initially-flag nil)
16804 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16805 ;; Rationalize `org-def' and `org-defdecode', if required.
16806 (when (< (nth 2 org-defdecode) org-extend-today-until)
16807 (setf (nth 2 org-defdecode) -1)
16808 (setf (nth 1 org-defdecode) 59)
16809 (setq org-def (apply #'encode-time org-defdecode))
16810 (setq org-defdecode (decode-time org-def)))
16811 (let* ((timestr (format-time-string
16812 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16814 (prompt (concat (if prompt (concat prompt " ") "")
16815 (format "Date+time [%s]: " timestr))))
16817 (from-string (setq ans from-string))
16818 (org-read-date-popup-calendar
16820 (save-window-excursion
16822 (when (eq calendar-setup 'calendar-only)
16824 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16825 (select-frame cal-frame))
16826 (org-eval-in-calendar '(setq cursor-type nil) t)
16829 (calendar-forward-day (- (time-to-days org-def)
16830 (calendar-absolute-from-gregorian
16831 (calendar-current-date))))
16832 (org-eval-in-calendar nil t)
16833 (let* ((old-map (current-local-map))
16834 (map (copy-keymap calendar-mode-map))
16835 (minibuffer-local-map
16836 (copy-keymap org-read-date-minibuffer-local-map)))
16837 (org-defkey map (kbd "RET") 'org-calendar-select)
16838 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16839 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16842 (use-local-map map)
16843 (setq org-read-date-inactive inactive)
16844 (add-hook 'post-command-hook 'org-read-date-display)
16846 (read-string prompt
16848 'org-read-date-history
16850 ;; org-ans0: from prompt
16851 ;; org-ans1: from mouse click
16852 ;; org-ans2: from calendar motion
16854 (concat org-ans0 " " (or org-ans1 org-ans2))))
16855 (remove-hook 'post-command-hook 'org-read-date-display)
16856 (use-local-map old-map)
16857 (when org-read-date-overlay
16858 (delete-overlay org-read-date-overlay)
16859 (setq org-read-date-overlay nil)))))
16860 (bury-buffer "*Calendar*")
16862 (delete-frame cal-frame)
16863 (select-frame-set-input-focus cur-frame))))))
16865 (t ; Naked prompt only
16867 (setq ans (read-string prompt default-input
16868 'org-read-date-history timestr))
16869 (when org-read-date-overlay
16870 (delete-overlay org-read-date-overlay)
16871 (setq org-read-date-overlay nil))))))
16873 (setq final (org-read-date-analyze ans org-def org-defdecode))
16875 (when org-read-date-analyze-forced-year
16876 (message "Year was forced into %s"
16877 (if org-read-date-force-compatible-dates
16878 "compatible range (1970-2037)"
16879 "range representable on this machine"))
16882 ;; One round trip to get rid of 34th of August and stuff like that....
16883 (setq final (decode-time (apply 'encode-time final)))
16885 (setq org-read-date-final-answer ans)
16888 (apply 'encode-time final)
16889 (if (and (boundp 'org-time-was-given) org-time-was-given)
16890 (format "%04d-%02d-%02d %02d:%02d"
16891 (nth 5 final) (nth 4 final) (nth 3 final)
16892 (nth 2 final) (nth 1 final))
16893 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16895 (defun org-read-date-display ()
16896 "Display the current date prompt interpretation in the minibuffer."
16897 (when org-read-date-display-live
16898 (when org-read-date-overlay
16899 (delete-overlay org-read-date-overlay))
16900 (when (minibufferp (current-buffer))
16903 (while (not (equal (buffer-substring
16904 (max (point-min) (- (point) 4)) (point))
16907 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16908 " " (or org-ans1 org-ans2)))
16909 (org-end-time-was-given nil)
16910 (f (org-read-date-analyze ans org-def org-defdecode))
16912 org-time-stamp-custom-formats
16913 org-time-stamp-formats))
16914 (fmt (if (or org-with-time
16915 (and (boundp 'org-time-was-given) org-time-was-given))
16918 (txt (format-time-string fmt (apply 'encode-time f)))
16919 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16920 (txt (concat "=> " txt)))
16921 (when (and org-end-time-was-given
16922 (string-match org-plain-time-of-day-regexp txt))
16923 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16924 org-end-time-was-given
16925 (substring txt (match-end 0)))))
16926 (when org-read-date-analyze-futurep
16927 (setq txt (concat txt " (=>F)")))
16928 (setq org-read-date-overlay
16929 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16930 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16932 (defun org-read-date-analyze (ans def defdecode)
16933 "Analyze the combined answer of the date prompt."
16934 ;; FIXME: cleanup and comment
16935 ;; Pass `current-time' result to `decode-time' (instead of calling
16936 ;; without arguments) so that only `current-time' has to be
16937 ;; overridden in tests.
16938 (let ((org-def def)
16939 (org-defdecode defdecode)
16940 (nowdecode (decode-time (current-time)))
16941 delta deltan deltaw deltadef year month day
16942 hour minute second wday pm h2 m2 tl wday1
16943 iso-year iso-weekday iso-week iso-date futurep kill-year)
16944 (setq org-read-date-analyze-futurep nil
16945 org-read-date-analyze-forced-year nil)
16946 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16949 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16950 (setq ans (replace-match "" t t ans)
16952 deltaw (nth 1 delta)
16953 deltadef (nth 2 delta)))
16955 ;; Check if there is an iso week date in there. If yes, store the
16956 ;; info and postpone interpreting it until the rest of the parsing
16958 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16959 (setq iso-year (when (match-end 1)
16960 (org-small-year-to-year
16961 (string-to-number (match-string 1 ans))))
16962 iso-weekday (when (match-end 3)
16963 (string-to-number (match-string 3 ans)))
16964 iso-week (string-to-number (match-string 2 ans)))
16965 (setq ans (replace-match "" t t ans)))
16967 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16968 (when (string-match
16969 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16970 (setq year (if (match-end 2)
16971 (string-to-number (match-string 2 ans))
16972 (progn (setq kill-year t)
16973 (string-to-number (format-time-string "%Y"))))
16974 month (string-to-number (match-string 3 ans))
16975 day (string-to-number (match-string 4 ans)))
16976 (setq year (org-small-year-to-year year))
16977 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16980 ;; Help matching dotted european dates
16981 (when (string-match
16982 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16983 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16985 (string-to-number (format-time-string "%Y")))
16986 day (string-to-number (match-string 1 ans))
16987 month (string-to-number (match-string 2 ans))
16988 ans (replace-match (format "%04d-%02d-%02d" year month day)
16991 ;; Help matching american dates, like 5/30 or 5/30/7
16992 (when (string-match
16993 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16994 (setq year (if (match-end 4)
16995 (string-to-number (match-string 4 ans))
16996 (progn (setq kill-year t)
16997 (string-to-number (format-time-string "%Y"))))
16998 month (string-to-number (match-string 1 ans))
16999 day (string-to-number (match-string 2 ans)))
17000 (setq year (org-small-year-to-year year))
17001 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17003 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17004 ;; If there is a time with am/pm, and *no* time without it, we convert
17005 ;; so that matching will be successful.
17006 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17007 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17008 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17009 (setq hour (string-to-number (match-string 1 ans))
17010 minute (if (match-end 3)
17011 (string-to-number (match-string 3 ans))
17014 (string-to-char (downcase (match-string 4 ans)))))
17015 (if (and (= hour 12) (not pm))
17017 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17018 (setq ans (replace-match (format "%02d:%02d" hour minute)
17021 ;; Check if a time range is given as a duration
17022 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17023 (setq hour (string-to-number (match-string 1 ans))
17024 h2 (+ hour (string-to-number (match-string 3 ans)))
17025 minute (string-to-number (match-string 2 ans))
17026 m2 (+ minute (if (match-end 5) (string-to-number
17027 (match-string 5 ans))0)))
17028 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17029 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17032 ;; Check if there is a time range
17033 (when (boundp 'org-end-time-was-given)
17034 (setq org-time-was-given nil)
17035 (when (and (string-match org-plain-time-of-day-regexp ans)
17037 (setq org-end-time-was-given (match-string 8 ans))
17038 (setq ans (concat (substring ans 0 (match-beginning 7))
17039 (substring ans (match-end 7))))))
17041 (setq tl (parse-time-string ans)
17042 day (or (nth 3 tl) (nth 3 org-defdecode))
17045 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17046 ;; Day was specified. Make sure DAY+MONTH
17047 ;; combination happens in the future.
17050 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17051 (nth 4 nowdecode)))
17052 (t (nth 4 org-defdecode)))
17054 (cond ((and (not kill-year) (nth 5 tl)))
17055 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17056 ;; Month was guessed in the future and is at least
17057 ;; equal to NOWDECODE's. Fix year accordingly.
17059 (if (or (> month (nth 4 nowdecode))
17060 (>= day (nth 3 nowdecode)))
17062 (1+ (nth 5 nowdecode))))
17063 ;; Month was specified. Make sure MONTH+YEAR
17064 ;; combination happens in the future.
17067 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17068 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17069 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17070 (t (nth 5 nowdecode))))
17071 (t (nth 5 org-defdecode)))
17072 hour (or (nth 2 tl) (nth 2 org-defdecode))
17073 minute (or (nth 1 tl) (nth 1 org-defdecode))
17074 second (or (nth 0 tl) 0)
17077 (when (and (eq org-read-date-prefer-future 'time)
17078 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17079 (equal day (nth 3 nowdecode))
17080 (equal month (nth 4 nowdecode))
17081 (equal year (nth 5 nowdecode))
17083 (or (< (nth 2 tl) (nth 2 nowdecode))
17084 (and (= (nth 2 tl) (nth 2 nowdecode))
17086 (< (nth 1 tl) (nth 1 nowdecode)))))
17090 ;; Special date definitions below
17093 ;; There was an iso week
17096 (setq year (or iso-year year)
17097 day (or iso-weekday wday 1)
17098 wday nil ; to make sure that the trigger below does not match
17099 iso-date (calendar-gregorian-from-absolute
17100 (calendar-iso-to-absolute
17101 (list iso-week day year))))
17102 ; FIXME: Should we also push ISO weeks into the future?
17103 ; (when (and org-read-date-prefer-future
17105 ; (< (calendar-absolute-from-gregorian iso-date)
17106 ; (time-to-days (current-time))))
17107 ; (setq year (1+ year)
17108 ; iso-date (calendar-gregorian-from-absolute
17109 ; (calendar-iso-to-absolute
17110 ; (list iso-week day year)))))
17111 (setq month (car iso-date)
17112 year (nth 2 iso-date)
17113 day (nth 1 iso-date)))
17117 ;; Pass `current-time' result to `decode-time' (instead of
17118 ;; calling without arguments) so that only `current-time' has
17119 ;; to be overridden in tests.
17120 (let ((now (decode-time (current-time))))
17121 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17122 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17123 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17124 ((equal deltaw "m") (setq month (+ month deltan)))
17125 ((equal deltaw "y") (setq year (+ year deltan)))))
17126 ((and wday (not (nth 3 tl)))
17127 ;; Weekday was given, but no day, so pick that day in the week
17128 ;; on or after the derived date.
17129 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17130 (unless (equal wday wday1)
17131 (setq day (+ day (% (- wday wday1 -7) 7))))))
17132 (when (and (boundp 'org-time-was-given)
17134 (setq org-time-was-given t))
17135 (when (< year 100) (setq year (+ 2000 year)))
17136 ;; Check of the date is representable
17137 (if org-read-date-force-compatible-dates
17139 (when (< year 1970)
17140 (setq year 1970 org-read-date-analyze-forced-year t))
17141 (when (> year 2037)
17142 (setq year 2037 org-read-date-analyze-forced-year t)))
17143 (condition-case nil
17144 (ignore (encode-time second minute hour day month year))
17146 (setq year (nth 5 org-defdecode))
17147 (setq org-read-date-analyze-forced-year t))))
17148 (setq org-read-date-analyze-futurep futurep)
17149 (list second minute hour day month year)))
17151 (defvar parse-time-weekdays)
17152 (defun org-read-date-get-relative (s today default)
17153 "Check string S for special relative date string.
17154 TODAY and DEFAULT are internal times, for today and for a default.
17155 Return shift list (N what def-flag)
17156 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17157 N is the number of WHATs to shift.
17158 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17159 the DEFAULT date rather than TODAY."
17160 (require 'parse-time)
17164 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17166 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17167 "\\([ \t]\\|$\\)") s)
17168 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17169 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17170 (string-to-char (substring (match-string 1 s) -1))
17172 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17173 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17174 (what (if (match-end 3) (match-string 3 s) "d"))
17175 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17176 (date (if rel default today))
17177 (wday (nth 6 (decode-time date)))
17181 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17182 (when (= delta 0) (setq delta 7))
17184 (setq delta (- delta 7))
17185 (when (= delta 0) (setq delta -7)))
17186 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17187 (list delta "d" rel))
17188 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17190 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17191 "Turn a user-specified date into the internal representation.
17192 The internal representation needed by the calendar is (month day year).
17193 This is a wrapper to handle the brain-dead convention in calendar that
17194 user function argument order change dependent on argument order."
17195 (pcase calendar-date-style
17196 (`american (list arg1 arg2 arg3))
17197 (`european (list arg2 arg1 arg3))
17198 (`iso (list arg2 arg3 arg1))))
17200 (defun org-eval-in-calendar (form &optional keepdate)
17201 "Eval FORM in the calendar window and return to current window.
17202 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17203 (let ((sf (selected-frame))
17204 (sw (selected-window)))
17205 (select-window (get-buffer-window "*Calendar*" t))
17207 (when (and (not keepdate) (calendar-cursor-to-date))
17208 (let* ((date (calendar-cursor-to-date))
17209 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17210 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17211 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17213 (select-frame-set-input-focus sf)))
17215 (defun org-calendar-select ()
17216 "Return to `org-read-date' with the date currently selected.
17217 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17219 (when (calendar-cursor-to-date)
17220 (let* ((date (calendar-cursor-to-date))
17221 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17222 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17223 (when (active-minibuffer-window) (exit-minibuffer))))
17225 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17226 "Insert a date stamp for the date given by the internal TIME.
17227 See `format-time-string' for the format of TIME.
17228 WITH-HM means use the stamp format that includes the time of the day.
17229 INACTIVE means use square brackets instead of angular ones, so that the
17230 stamp will not contribute to the agenda.
17231 PRE and POST are optional strings to be inserted before and after the
17233 The command returns the inserted time stamp."
17234 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17236 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17237 (insert-before-markers (or pre ""))
17238 (when (listp extra)
17239 (setq extra (car extra))
17240 (if (and (stringp extra)
17241 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17242 (setq extra (format "-%02d:%02d"
17243 (string-to-number (match-string 1 extra))
17244 (string-to-number (match-string 2 extra))))
17247 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17248 (insert-before-markers (setq stamp (format-time-string fmt time)))
17249 (insert-before-markers (or post ""))
17250 (setq org-last-inserted-timestamp stamp)))
17252 (defun org-toggle-time-stamp-overlays ()
17253 "Toggle the use of custom time stamp formats."
17255 (setq org-display-custom-times (not org-display-custom-times))
17256 (unless org-display-custom-times
17257 (let ((p (point-min)) (bmp (buffer-modified-p)))
17258 (while (setq p (next-single-property-change p 'display))
17259 (when (and (get-text-property p 'display)
17260 (eq (get-text-property p 'face) 'org-date))
17261 (remove-text-properties
17262 p (setq p (next-single-property-change p 'display))
17264 (set-buffer-modified-p bmp)))
17265 (org-restart-font-lock)
17266 (setq org-table-may-need-update t)
17267 (if org-display-custom-times
17268 (message "Time stamps are overlaid with custom format")
17269 (message "Time stamp overlays removed")))
17271 (defun org-display-custom-time (beg end)
17272 "Overlay modified time stamp format over timestamp between BEG and END."
17273 (let* ((ts (buffer-substring beg end))
17274 t1 with-hm tf time str (off 0))
17276 (setq t1 (org-parse-time-string ts t))
17277 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17278 (setq off (- (match-end 0) (match-beginning 0)))))
17279 (setq end (- end off))
17280 (setq with-hm (and (nth 1 t1) (nth 2 t1))
17281 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17282 time (org-fix-decoded-time t1)
17284 (format-time-string
17285 (substring tf 1 -1) (apply 'encode-time time))
17286 nil 'mouse-face 'highlight))
17287 (put-text-property beg end 'display str)))
17289 (defun org-fix-decoded-time (time)
17290 "Set 0 instead of nil for the first 6 elements of time.
17291 Don't touch the rest."
17293 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17295 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17296 "Difference between TIMESTAMP-STRING and now in days.
17297 If SECONDS is non-nil, return the difference in seconds."
17298 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17299 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17300 (funcall fdiff (current-time)))))
17302 (defun org-deadline-close-p (timestamp-string &optional ndays)
17303 "Is the time in TIMESTAMP-STRING close to the current date?"
17304 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17305 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17306 (not (org-entry-is-done-p))))
17308 (defun org-get-wdays (ts &optional delay zero-delay)
17309 "Get the deadline lead time appropriate for timestring TS.
17310 When DELAY is non-nil, get the delay time for scheduled items
17311 instead of the deadline lead time. When ZERO-DELAY is non-nil
17312 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17313 don't try to find the delay cookie in the scheduled timestamp."
17314 (let ((tv (if delay org-scheduled-delay-days
17315 org-deadline-warning-days)))
17317 ((or (and delay (< tv 0))
17318 (and delay zero-delay (<= tv 0))
17319 (and (not delay) (<= tv 0)))
17320 ;; Enforce this value no matter what
17322 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17323 ;; lead time is specified.
17324 (floor (* (string-to-number (match-string 1 ts))
17325 (cdr (assoc (match-string 2 ts)
17326 '(("d" . 1) ("w" . 7)
17327 ("m" . 30.4) ("y" . 365.25)
17328 ("h" . 0.041667)))))))
17329 ;; go for the default.
17332 (defun org-calendar-select-mouse (ev)
17333 "Return to `org-read-date' with the date currently selected.
17334 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17336 (mouse-set-point ev)
17337 (when (calendar-cursor-to-date)
17338 (let* ((date (calendar-cursor-to-date))
17339 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17340 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17341 (when (active-minibuffer-window) (exit-minibuffer))))
17343 (defun org-check-deadlines (ndays)
17344 "Check if there are any deadlines due or past due.
17345 A deadline is considered due if it happens within `org-deadline-warning-days'
17346 days from today's date. If the deadline appears in an entry marked DONE,
17347 it is not shown. A numeric prefix argument NDAYS can be used to test that
17348 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17351 (let* ((org-warn-days
17353 ((equal ndays '(4)) 100000)
17354 (ndays (prefix-numeric-value ndays))
17355 (t (abs org-deadline-warning-days))))
17356 (case-fold-search nil)
17357 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17359 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17360 (message "%d deadlines past-due or due within %d days"
17361 (org-occur regexp nil callback)
17364 (defsubst org-re-timestamp (type)
17365 "Return a regexp for timestamp TYPE.
17366 Allowed values for TYPE are:
17368 all: all timestamps
17369 active: only active timestamps (<...>)
17370 inactive: only inactive timestamps ([...])
17371 scheduled: only scheduled timestamps
17372 deadline: only deadline timestamps
17373 closed: only closed time-stamps
17375 When TYPE is nil, fall back on returning a regexp that matches
17376 both scheduled and deadline timestamps."
17378 (all org-ts-regexp-both)
17379 (active org-ts-regexp)
17380 (inactive org-ts-regexp-inactive)
17381 (scheduled org-scheduled-time-regexp)
17382 (deadline org-deadline-time-regexp)
17383 (closed org-closed-time-regexp)
17386 (regexp-opt (list org-deadline-string org-scheduled-string))
17387 " *<\\([^>]+\\)>"))))
17389 (defun org-check-before-date (d)
17390 "Check if there are deadlines or scheduled entries before date D."
17391 (interactive (list (org-read-date)))
17392 (let* ((case-fold-search nil)
17393 (regexp (org-re-timestamp org-ts-type))
17394 (ts-type org-ts-type)
17397 (let ((match (match-string 1)))
17398 (and (if (memq ts-type '(active inactive all))
17399 (eq (org-element-type (save-excursion
17401 (org-element-context)))
17403 (org-at-planning-p))
17405 (org-time-string-to-time match)
17406 (org-time-string-to-time d)))))))
17407 (message "%d entries before %s"
17408 (org-occur regexp nil callback)
17411 (defun org-check-after-date (d)
17412 "Check if there are deadlines or scheduled entries after date D."
17413 (interactive (list (org-read-date)))
17414 (let* ((case-fold-search nil)
17415 (regexp (org-re-timestamp org-ts-type))
17416 (ts-type org-ts-type)
17419 (let ((match (match-string 1)))
17420 (and (if (memq ts-type '(active inactive all))
17421 (eq (org-element-type (save-excursion
17423 (org-element-context)))
17425 (org-at-planning-p))
17427 (org-time-string-to-time match)
17428 (org-time-string-to-time d))))))))
17429 (message "%d entries after %s"
17430 (org-occur regexp nil callback)
17433 (defun org-check-dates-range (start-date end-date)
17434 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17435 (interactive (list (org-read-date nil nil nil "Range starts")
17436 (org-read-date nil nil nil "Range end")))
17437 (let ((case-fold-search nil)
17438 (regexp (org-re-timestamp org-ts-type))
17440 (let ((type org-ts-type))
17442 (let ((match (match-string 1)))
17444 (if (memq type '(active inactive all))
17445 (eq (org-element-type (save-excursion
17447 (org-element-context)))
17449 (org-at-planning-p))
17451 (org-time-string-to-time match)
17452 (org-time-string-to-time start-date)))
17454 (org-time-string-to-time match)
17455 (org-time-string-to-time end-date))))))))
17456 (message "%d entries between %s and %s"
17457 (org-occur regexp nil callback) start-date end-date)))
17459 (defun org-evaluate-time-range (&optional to-buffer)
17460 "Evaluate a time range by computing the difference between start and end.
17461 Normally the result is just printed in the echo area, but with prefix arg
17462 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17463 If the time range is actually in a table, the result is inserted into the
17465 For time difference computation, a year is assumed to be exactly 365
17466 days in order to avoid rounding problems."
17469 (org-clock-update-time-maybe)
17471 (unless (org-at-date-range-p t)
17472 (goto-char (point-at-bol))
17473 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17474 (unless (org-at-date-range-p t)
17475 (user-error "Not at a time-stamp range, and none found in current line")))
17476 (let* ((ts1 (match-string 1))
17477 (ts2 (match-string 2))
17478 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17479 (match-end (match-end 0))
17480 (time1 (org-time-string-to-time ts1))
17481 (time2 (org-time-string-to-time ts2))
17482 (t1 (float-time time1))
17483 (t2 (float-time time2))
17484 (diff (abs (- t2 t1)))
17485 (negative (< (- t2 t1) 0))
17486 ;; (ys (floor (* 365 24 60 60)))
17489 (fy "%dy %dd %02d:%02d")
17491 (fd "%dd %02d:%02d")
17496 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17498 d (floor (/ diff ds)) diff (mod diff ds)
17499 h (floor (/ diff hs)) diff (mod diff hs)
17500 m (floor (/ diff 60)))
17501 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17503 d (floor (+ (/ diff ds) 0.5))
17505 (if (not to-buffer)
17506 (message "%s" (org-make-tdiff-string y d h m))
17507 (if (org-at-table-p)
17509 (goto-char match-end)
17511 (and (looking-at " *|") (goto-char (match-end 0))))
17512 (goto-char match-end))
17514 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17515 (replace-match ""))
17516 (when negative (insert " -"))
17517 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17518 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17519 (insert " " (format fh h m))))
17520 (when align (org-table-align))
17521 (message "Time difference inserted")))))
17523 (defun org-make-tdiff-string (y d h m)
17527 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17530 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17533 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17536 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17538 (apply 'format fmt (nreverse l))))
17540 (defun org-time-string-to-time (s)
17541 "Convert timestamp string S into internal time."
17542 (apply #'encode-time (org-parse-time-string s)))
17544 (defun org-time-string-to-seconds (s)
17545 "Convert a timestamp string S into a number of seconds."
17546 (float-time (org-time-string-to-time s)))
17548 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17550 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17551 "Convert time stamp S to an absolute day number.
17553 If DAYNR in non-nil, and there is a specifier for a cyclic time
17554 stamp, get the closest date to DAYNR. If PREFER is
17555 `past' (respectively `future') return a date past (respectively
17556 after) or equal to DAYNR.
17558 POS is the location of time stamp S, as a buffer position in
17561 Diary sexp timestamps are matched against DAYNR, when non-nil.
17562 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17565 ((string-match "\\`%%\\((.*)\\)" s)
17566 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17567 ;; only able to match individual dates. If it fails, raise an
17570 (org-diary-sexp-entry
17571 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17573 (signal 'org-diary-sexp-no-match (list s))))
17574 (daynr (org-closest-date s daynr prefer))
17576 (condition-case errdata
17577 (apply #'encode-time (org-parse-time-string s))
17578 (error (error "Bad timestamp `%s'%s\nError was: %s"
17580 (if (not (and buffer pos)) ""
17581 (format-message " at %d in buffer `%s'" pos buffer))
17582 (cdr errdata))))))))
17584 (defun org-days-to-iso-week (days)
17585 "Return the iso week number."
17587 (car (calendar-iso-from-absolute days)))
17589 (defun org-small-year-to-year (year)
17590 "Convert 2-digit years into 4-digit years.
17591 YEAR is expanded into one of the 30 next years, if possible, or
17592 into a past one. Any year larger than 99 is returned unchanged."
17593 (if (>= year 100) year
17594 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17595 (century (/ current 100))
17596 (offset (- year (% current 100))))
17597 (cond ((> offset 30) (+ (* (1- century) 100) year))
17598 ((> offset -70) (+ (* century 100) year))
17599 (t (+ (* (1+ century) 100) year))))))
17601 (defun org-time-from-absolute (d)
17602 "Return the time corresponding to date D.
17603 D may be an absolute day number, or a calendar-type list (month day year)."
17604 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17605 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17607 (defvar org-agenda-current-date)
17608 (defun org-calendar-holiday ()
17609 "List of holidays, for Diary display in Org mode."
17610 (require 'holidays)
17611 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17612 (and hl (mapconcat #'identity hl "; "))))
17614 (defun org-diary-sexp-entry (sexp entry d)
17615 "Process a SEXP diary ENTRY for date D."
17616 (require 'diary-lib)
17617 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17619 (let* ((sexp `(let ((entry ,entry)
17621 ,(car (read-from-string sexp))))
17622 (result (if calendar-debug-sexp (eval sexp)
17623 (condition-case nil
17627 (message "Bad sexp at line %d in %s: %s"
17629 (buffer-file-name) sexp)
17631 (cond ((stringp result) (split-string result "; "))
17632 ((and (consp result)
17633 (not (consp (cdr result)))
17634 (stringp (cdr result))) (cdr result))
17635 ((and (consp result)
17636 (stringp (car result))) result)
17639 (defun org-diary-to-ical-string (frombuf)
17640 "Get iCalendar entries from diary entries in buffer FROMBUF.
17641 This uses the icalendar.el library."
17642 (let* ((tmpdir temporary-file-directory)
17643 (tmpfile (make-temp-name
17644 (expand-file-name "orgics" tmpdir)))
17646 (with-current-buffer frombuf
17647 (icalendar-export-region (point-min) (point-max) tmpfile)
17648 (setq buf (find-buffer-visiting tmpfile))
17650 (goto-char (point-min))
17651 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17652 (setq b (match-beginning 0)))
17653 (goto-char (point-max))
17654 (when (re-search-backward "^END:VEVENT" nil t)
17655 (setq e (match-end 0)))
17656 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17658 (delete-file tmpfile)
17661 (defun org-closest-date (start current prefer)
17662 "Return closest date to CURRENT starting from START.
17664 CURRENT and START are both time stamps.
17666 When PREFER is `past', return a date that is either CURRENT or
17667 past. When PREFER is `future', return a date that is either
17670 Only time stamps with a repeater are modified. Any other time
17671 stamp stay unchanged. In any case, return value is an absolute
17673 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17674 ;; No repeater. Do not shift time stamp.
17675 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17676 (let ((value (string-to-number (match-string 1 start)))
17677 (type (match-string 2 start)))
17679 ;; Repeater with a 0-value is considered as void.
17680 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17681 (let* ((base (org-date-to-gregorian start))
17682 (target (org-date-to-gregorian current))
17683 (sday (calendar-absolute-from-gregorian base))
17684 (cday (calendar-absolute-from-gregorian target))
17686 ;; If START is already past CURRENT, just return START.
17687 (if (<= cday sday) sday
17688 ;; Compute closest date before (N1) and closest date past
17692 (let ((missing-hours
17693 (mod (+ (- (* 24 (- cday sday))
17694 (nth 2 (org-parse-time-string start)))
17695 org-extend-today-until)
17697 (setf n1 (if (= missing-hours 0) cday
17698 (- cday (1+ (/ missing-hours 24)))))
17699 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17701 (let ((value (if (equal type "w") (* 7 value) value)))
17702 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17703 (setf n2 (+ n1 value))))
17707 ;; Add N months to gregorian date D, i.e.,
17708 ;; a list (MONTH DAY YEAR). Return a valid
17710 (let ((m (+ (nth 0 d) n)))
17713 (+ (/ m 12) (nth 2 d))))))
17714 (months ; Complete months to TARGET.
17715 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17716 (- (nth 0 target) (nth 0 base))
17717 ;; If START's day is greater than
17718 ;; TARGET's, remove incomplete month.
17719 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17722 (before (funcall add-months base months)))
17723 (setf n1 (calendar-absolute-from-gregorian before))
17725 (calendar-absolute-from-gregorian
17726 (funcall add-months before value)))))
17728 (let* ((d (nth 1 base))
17731 (years ; Complete years to TARGET.
17732 (* (/ (- (nth 2 target)
17734 ;; If START's month and day are
17735 ;; greater than TARGET's, remove
17736 ;; incomplete year.
17737 (if (or (> (nth 0 target) m)
17738 (and (= (nth 0 target) m)
17739 (> (nth 1 target) d)))
17744 (before (list m d (+ y years))))
17745 (setf n1 (calendar-absolute-from-gregorian before))
17746 (setf n2 (calendar-absolute-from-gregorian
17747 (list m d (+ (nth 2 before) value)))))))
17748 ;; Handle PREFER parameter, if any.
17750 ((eq prefer 'past) (if (= cday n2) n2 n1))
17751 ((eq prefer 'future) (if (= cday n1) n1 n2))
17752 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17754 (defun org-date-to-gregorian (d)
17755 "Turn any specification of date D into a Gregorian date for the calendar."
17756 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17757 ((and (listp d) (= (length d) 3)) d)
17759 (let ((d (org-parse-time-string d)))
17760 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17761 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17763 (defun org-parse-time-string (s &optional nodefault)
17764 "Parse the standard Org time string.
17766 This should be a lot faster than the normal `parse-time-string'.
17768 If time is not given, defaults to 0:00. However, with optional
17769 NODEFAULT, hour and minute fields will be nil if not given."
17770 (cond ((string-match org-ts-regexp0 s)
17772 (when (or (match-beginning 8) (not nodefault))
17773 (string-to-number (or (match-string 8 s) "0")))
17774 (when (or (match-beginning 7) (not nodefault))
17775 (string-to-number (or (match-string 7 s) "0")))
17776 (string-to-number (match-string 4 s))
17777 (string-to-number (match-string 3 s))
17778 (string-to-number (match-string 2 s))
17780 ((string-match "^<[^>]+>$" s)
17781 ;; FIXME: `decode-time' needs to be called with ZONE as its
17782 ;; second argument. However, this requires at least Emacs
17783 ;; 25.1. We can do it when we switch to this version as our
17784 ;; minimal requirement.
17785 (decode-time (seconds-to-time (org-matcher-time s))))
17786 (t (error "Not a standard Org time string: %s" s))))
17788 (defun org-timestamp-up (&optional arg)
17789 "Increase the date item at the cursor by one.
17790 If the cursor is on the year, change the year. If it is on the month,
17791 the day or the time, change that.
17792 With prefix ARG, change by that many units."
17794 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17796 (defun org-timestamp-down (&optional arg)
17797 "Decrease the date item at the cursor by one.
17798 If the cursor is on the year, change the year. If it is on the month,
17799 the day or the time, change that.
17800 With prefix ARG, change by that many units."
17802 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17804 (defun org-timestamp-up-day (&optional arg)
17805 "Increase the date in the time stamp by one day.
17806 With prefix ARG, change that many days."
17808 (if (and (not (org-at-timestamp-p 'lax))
17809 (org-at-heading-p))
17811 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17813 (defun org-timestamp-down-day (&optional arg)
17814 "Decrease the date in the time stamp by one day.
17815 With prefix ARG, change that many days."
17817 (if (and (not (org-at-timestamp-p 'lax))
17818 (org-at-heading-p))
17820 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17822 (defun org-at-timestamp-p (&optional extended)
17823 "Non-nil if point is inside a timestamp.
17825 By default, the function only consider syntactically valid active
17826 timestamps. However, the caller may have a broader definition
17827 for timestamps. As a consequence, optional argument EXTENDED can
17828 be set to the following values
17832 Include also syntactically valid inactive timestamps.
17836 Include timestamps allowed in Agenda, i.e., those in
17837 properties drawers, planning lines and clock lines.
17841 Ignore context. The function matches any part of the
17842 document looking like a timestamp. This includes comments,
17845 For backward-compatibility with Org 9.0, every other non-nil
17846 value is equivalent to `inactive'.
17848 When at a timestamp, return the position of the point as a symbol
17849 among `bracket', `after', `year', `month', `hour', `minute',
17850 `day' or a number of character from the last know part of the
17853 When matching, the match groups are the following:
17856 group 3: day number
17858 group 5: hours, if any
17859 group 6: minutes, if any"
17860 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17863 (let ((boundaries (org-in-regexp regexp)))
17865 (cond ((null boundaries) nil)
17866 ((eq extended 'lax) t)
17868 (or (and (eq extended 'agenda)
17869 (or (org-at-planning-p)
17870 (org-at-property-p)
17871 (and (bound-and-true-p
17872 org-agenda-include-inactive-timestamps)
17873 (org-at-clock-log-p))))
17876 (when (= pos (cdr boundaries)) (forward-char -1))
17877 (org-element-type (org-element-context)))))))))))
17880 ((= pos (match-beginning 0)) 'bracket)
17881 ;; Distinguish location right before the closing bracket from
17883 ((= pos (1- (match-end 0))) 'bracket)
17884 ((= pos (match-end 0)) 'after)
17885 ((org-pos-in-match-range pos 2) 'year)
17886 ((org-pos-in-match-range pos 3) 'month)
17887 ((org-pos-in-match-range pos 7) 'hour)
17888 ((org-pos-in-match-range pos 8) 'minute)
17889 ((or (org-pos-in-match-range pos 4)
17890 (org-pos-in-match-range pos 5)) 'day)
17891 ((and (> pos (or (match-end 8) (match-end 5)))
17892 (< pos (match-end 0)))
17893 (- pos (or (match-end 8) (match-end 5))))
17896 (defun org-toggle-timestamp-type ()
17897 "Toggle the type (<active> or [inactive]) of a time stamp."
17899 (when (org-at-timestamp-p 'lax)
17900 (let ((beg (match-beginning 0)) (end (match-end 0))
17901 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17904 (while (re-search-forward "[][<>]" end t)
17905 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17907 (message "Timestamp is now %sactive"
17908 (if (equal (char-after beg) ?<) "" "in")))))
17910 (defun org-at-clock-log-p ()
17911 "Non-nil if point is on a clock log line."
17912 (and (org-match-line org-clock-line-re)
17913 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17915 (defvar org-clock-history) ; defined in org-clock.el
17916 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17917 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17918 "Change the date in the time stamp at point.
17919 The date will be changed by N times WHAT. WHAT can be `day', `month',
17920 `year', `minute', `second'. If WHAT is not given, the cursor position
17921 in the timestamp determines what will be changed.
17922 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17923 (let ((origin (point))
17924 (timestamp? (org-at-timestamp-p 'lax))
17927 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17929 ts time time0 fixnext clrgx)
17930 (unless timestamp? (user-error "Not at a timestamp"))
17931 (if (and (not what) (eq timestamp? 'bracket))
17932 (org-toggle-timestamp-type)
17933 ;; Point isn't on brackets. Remember the part of the time-stamp
17934 ;; the point was in. Indeed, size of time-stamps may change,
17935 ;; but point must be kept in the same category nonetheless.
17936 (setq origin-cat timestamp?)
17937 (when (and (not what) (not (eq timestamp? 'day))
17938 org-display-custom-times
17939 (get-text-property (point) 'display)
17940 (not (get-text-property (1- (point)) 'display)))
17941 (setq timestamp? 'day))
17942 (setq timestamp? (or what timestamp?)
17943 inactive (= (char-after (match-beginning 0)) ?\[)
17944 ts (match-string 0))
17946 (when (string-match
17947 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17949 (setq extra (match-string 1 ts))
17950 (when suppress-tmp-delay
17951 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17952 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17954 (setq time0 (org-parse-time-string ts))
17956 (eq timestamp? 'minute)
17957 (not current-prefix-arg))
17958 ;; This looks like s-up and s-down. Change by one rounding step.
17959 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17960 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17961 (setcar (cdr time0) (+ (nth 1 time0)
17962 (if (> n 0) (- rem) (- dm rem))))))
17964 (apply #'encode-time
17966 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17967 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17968 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17969 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17970 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17972 (when (and (memq timestamp? '(hour minute))
17974 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17975 (setq extra (org-modify-ts-extra
17977 (if (eq timestamp? 'hour) 2 5)
17979 (when (integerp timestamp?)
17980 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17981 (when (eq what 'calendar)
17982 (let ((cal-date (org-get-date-from-calendar)))
17983 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17984 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17985 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17986 (setcar time0 (or (car time0) 0))
17987 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17988 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17989 (setq time (apply 'encode-time time0))))
17990 ;; Insert the new time-stamp, and ensure point stays in the same
17991 ;; category as before (i.e. not after the last position in that
17993 (let ((pos (point)))
17994 ;; Stay before inserted string. `save-excursion' is of no use.
17995 (setq org-last-changed-timestamp
17996 (org-insert-time-stamp time with-hm inactive nil nil extra))
17999 (looking-at org-ts-regexp3)
18002 ;; `day' category ends before `hour' if any, or at the end
18003 ;; of the day name.
18004 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18005 (`hour (min (match-end 7) origin))
18006 (`minute (min (1- (match-end 8)) origin))
18007 ((pred integerp) (min (1- (match-end 0)) origin))
18008 ;; Point was right after the time-stamp. However, the
18009 ;; time-stamp length might have changed, so refer to
18010 ;; (match-end 0) instead.
18011 (`after (match-end 0))
18012 ;; `year' and `month' have both fixed size: point couldn't
18013 ;; have moved into another part.
18015 ;; Update clock if on a CLOCK line.
18016 (org-clock-update-time-maybe)
18017 ;; Maybe adjust the closest clock in `org-clock-history'
18018 (when org-clock-adjust-closest
18019 (if (not (and (org-at-clock-log-p)
18020 (< 1 (length (delq nil (mapcar 'marker-position
18021 org-clock-history))))))
18022 (message "No clock to adjust")
18023 (cond ((save-excursion ; fix previous clock?
18024 (re-search-backward org-ts-regexp0 nil t)
18025 (looking-back (concat org-clock-string " \\[")
18026 (line-beginning-position)))
18027 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18028 ((save-excursion ; fix next clock?
18029 (re-search-backward org-ts-regexp0 nil t)
18030 (looking-at (concat org-ts-regexp0 "\\] =>")))
18031 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18032 (save-window-excursion
18033 ;; Find closest clock to point, adjust the previous/next one in history
18034 (let* ((p (save-excursion (org-back-to-heading t)))
18035 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18037 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18038 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18040 (message "No clock to adjust")
18042 (org-goto-marker-or-bmk clfixpos)
18044 (when (re-search-forward clrgx nil t)
18045 (goto-char (match-beginning 1))
18046 (let (org-clock-adjust-closest)
18047 (org-timestamp-change n timestamp? updown))
18048 (message "Clock adjusted in %s for heading: %s"
18049 (file-name-nondirectory (buffer-file-name))
18050 (org-get-heading t t)))))))))
18051 ;; Try to recenter the calendar window, if any.
18052 (when (and org-calendar-follow-timestamp-change
18053 (get-buffer-window "*Calendar*" t)
18054 (memq timestamp? '(day month year)))
18055 (org-recenter-calendar (time-to-days time))))))
18057 (defun org-modify-ts-extra (s pos n dm)
18058 "Change the different parts of the lead-time and repeat fields in timestamp."
18059 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18061 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18063 ((or (org-pos-in-match-range pos 2)
18064 (org-pos-in-match-range pos 3))
18065 (setq m (string-to-number (match-string 3 s))
18066 h (string-to-number (match-string 2 s)))
18067 (if (org-pos-in-match-range pos 2)
18069 (setq n (* dm (with-no-warnings (signum n))))
18070 (unless (= 0 (setq rem (% m dm)))
18071 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18073 (when (< m 0) (setq m (+ m 60) h (1- h)))
18074 (when (> m 59) (setq m (- m 60) h (1+ h)))
18075 (setq h (mod h 24))
18076 (setq ng 1 new (format "-%02d:%02d" h m)))
18077 ((org-pos-in-match-range pos 6)
18078 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18079 ((org-pos-in-match-range pos 5)
18080 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18082 ((org-pos-in-match-range pos 9)
18083 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18084 ((org-pos-in-match-range pos 8)
18085 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18089 (substring s 0 (match-beginning ng))
18091 (substring s (match-end ng))))))
18094 (defun org-recenter-calendar (d)
18095 "If the calendar is visible, recenter it to date D."
18096 (let ((cwin (get-buffer-window "*Calendar*" t)))
18098 (let ((calendar-move-hook nil))
18099 (with-selected-window cwin
18100 (calendar-goto-date
18101 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18103 (defun org-goto-calendar (&optional arg)
18104 "Go to the Emacs calendar at the current date.
18105 If there is a time stamp in the current line, go to that date.
18106 A prefix ARG can be used to force the current date."
18108 (let ((calendar-move-hook nil)
18109 (calendar-view-holidays-initially-flag nil)
18110 (calendar-view-diary-initially-flag nil)
18112 (when (or (org-at-timestamp-p 'lax)
18113 (org-match-line (concat ".*" org-ts-regexp)))
18114 (let ((d1 (time-to-days (current-time)))
18115 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
18116 (setq diff (- d2 d1))))
18118 (calendar-goto-today)
18119 (when (and diff (not arg)) (calendar-forward-day diff))))
18121 (defun org-get-date-from-calendar ()
18122 "Return a list (month day year) of date at point in calendar."
18123 (with-current-buffer "*Calendar*"
18125 (calendar-cursor-to-date))))
18127 (defun org-date-from-calendar ()
18128 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18129 If there is already a time stamp at the cursor position, update it."
18131 (if (org-at-timestamp-p 'lax)
18132 (org-timestamp-change 0 'calendar)
18133 (let ((cal-date (org-get-date-from-calendar)))
18134 (org-insert-time-stamp
18135 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18137 (defcustom org-effort-durations
18141 ("w" . ,(* 60 8 5))
18142 ("m" . ,(* 60 8 5 4))
18143 ("y" . ,(* 60 8 5 40)))
18144 "Conversion factor to minutes for an effort modifier.
18146 Each entry has the form (MODIFIER . MINUTES).
18148 In an effort string, a number followed by MODIFIER is multiplied
18149 by the specified number of MINUTES to obtain an effort in
18152 For example, if the value of this variable is ((\"hours\" . 60)), then an
18153 effort string \"2hours\" is equivalent to 120 minutes."
18156 :package-version '(Org . "8.3")
18157 :type '(alist :key-type (string :tag "Modifier")
18158 :value-type (number :tag "Minutes")))
18160 (defcustom org-image-actual-width t
18161 "Should we use the actual width of images when inlining them?
18163 When set to t, always use the image width.
18165 When set to a number, use imagemagick (when available) to set
18166 the image's width to this value.
18168 When set to a number in a list, try to get the width from any
18169 #+ATTR.* keyword if it matches a width specification like
18171 #+ATTR_HTML: :width 300px
18173 and fall back on that number if none is found.
18175 When set to nil, try to get the width from an #+ATTR.* keyword
18176 and fall back on the original width if none is found.
18178 This requires Emacs >= 24.1, build with imagemagick support."
18179 :group 'org-appearance
18181 :package-version '(Org . "8.0")
18183 (const :tag "Use the image width" t)
18184 (integer :tag "Use a number of pixels")
18185 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18186 (const :tag "Use #+ATTR* or don't resize" nil)))
18188 (defcustom org-agenda-inhibit-startup nil
18189 "Inhibit startup when preparing agenda buffers.
18190 When this variable is t, the initialization of the Org agenda
18191 buffers is inhibited: e.g. the visibility state is not set, the
18192 tables are not re-aligned, etc."
18195 :group 'org-agenda)
18197 (defcustom org-agenda-ignore-properties nil
18198 "Avoid updating text properties when building the agenda.
18199 Properties are used to prepare buffers for effort estimates,
18200 appointments, statistics and subtree-local categories.
18201 If you don't use these in the agenda, you can add them to this
18202 list and agenda building will be a bit faster.
18203 The value is a list, with zero or more of the symbols `effort', `appt',
18204 `stats' or `category'."
18205 :type '(set :greedy t
18211 :package-version '(Org . "8.3")
18212 :group 'org-agenda)
18216 (defun org-save-all-org-buffers ()
18217 "Save all Org buffers without user confirmation."
18219 (message "Saving all Org buffers...")
18220 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18221 (when (featurep 'org-id) (org-id-locations-save))
18222 (message "Saving all Org buffers... done"))
18224 (defun org-revert-all-org-buffers ()
18225 "Revert all Org buffers.
18226 Prompt for confirmation when there are unsaved changes.
18227 Be sure you know what you are doing before letting this function
18228 overwrite your changes.
18230 This function is useful in a setup where one tracks org files
18231 with a version control system, to revert on one machine after pulling
18232 changes from another. I believe the procedure must be like this:
18234 1. M-x org-save-all-org-buffers
18235 2. Pull changes from the other machine, resolve conflicts
18236 3. M-x org-revert-all-org-buffers"
18238 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18239 (user-error "Abort"))
18241 (save-window-excursion
18242 (dolist (b (buffer-list))
18243 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18244 (with-current-buffer b buffer-file-name))
18245 (pop-to-buffer-same-window b)
18246 (revert-buffer t 'no-confirm)))
18247 (when (and (featurep 'org-id) org-id-track-globally)
18248 (org-id-locations-load)))))
18253 (defun org-switchb (&optional arg)
18254 "Switch between Org buffers.
18256 With `\\[universal-argument]' prefix, restrict available buffers to files.
18258 With `\\[universal-argument] \\[universal-argument]' \
18259 prefix, restrict available buffers to agenda files."
18261 (let ((blist (org-buffer-list
18262 (cond ((equal arg '(4)) 'files)
18263 ((equal arg '(16)) 'agenda)))))
18264 (pop-to-buffer-same-window
18265 (completing-read "Org buffer: "
18266 (mapcar #'list (mapcar #'buffer-name blist))
18269 (defun org-buffer-list (&optional predicate exclude-tmp)
18270 "Return a list of Org buffers.
18271 PREDICATE can be `export', `files' or `agenda'.
18273 export restrict the list to Export buffers.
18274 files restrict the list to buffers visiting Org files.
18275 agenda restrict the list to buffers visiting agenda files.
18277 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18279 (agenda-files (and (eq predicate 'agenda)
18280 (mapcar 'file-truename (org-agenda-files t))))
18283 ((eq predicate 'files)
18284 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18285 ((eq predicate 'export)
18286 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18287 ((eq predicate 'agenda)
18289 (with-current-buffer b
18290 (and (derived-mode-p 'org-mode)
18291 (setq bfn (buffer-file-name b))
18292 (member (file-truename bfn) agenda-files)))))
18293 (t (lambda (b) (with-current-buffer b
18294 (or (derived-mode-p 'org-mode)
18295 (string-match "\\*Org .*Export"
18296 (buffer-name b)))))))))
18300 (if (and (funcall filter b)
18301 (or (not exclude-tmp)
18302 (not (string-match "tmp" (buffer-name b)))))
18307 (defun org-agenda-files (&optional unrestricted archives)
18308 "Get the list of agenda files.
18309 Optional UNRESTRICTED means return the full list even if a restriction
18310 is currently in place.
18311 When ARCHIVES is t, include all archive files that are really being
18312 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18313 `org-agenda-archives-mode' is t."
18316 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18317 ((stringp org-agenda-files) (org-read-agenda-file-list))
18318 ((listp org-agenda-files) org-agenda-files)
18319 (t (error "Invalid value of `org-agenda-files'")))))
18320 (setq files (apply 'append
18321 (mapcar (lambda (f)
18322 (if (file-directory-p f)
18324 f t org-agenda-file-regexp)
18327 (when org-agenda-skip-unavailable-files
18328 (setq files (delq nil
18331 (and (file-readable-p file) file)))
18333 (when (or (eq archives t)
18334 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18335 (setq files (org-add-archive-files files)))
18338 (defun org-agenda-file-p (&optional file)
18339 "Return non-nil, if FILE is an agenda file.
18340 If FILE is omitted, use the file associated with the current
18342 (let ((fname (or file (buffer-file-name))))
18344 (member (file-truename fname)
18345 (mapcar #'file-truename (org-agenda-files t))))))
18347 (defun org-edit-agenda-file-list ()
18348 "Edit the list of agenda files.
18349 Depending on setup, this either uses customize to edit the variable
18350 `org-agenda-files', or it visits the file that is holding the list. In the
18351 latter case, the buffer is set up in a way that saving it automatically kills
18352 the buffer and restores the previous window configuration."
18354 (if (stringp org-agenda-files)
18355 (let ((cw (current-window-configuration)))
18356 (find-file org-agenda-files)
18357 (setq-local org-window-configuration cw)
18358 (add-hook 'after-save-hook
18360 (set-window-configuration
18361 (prog1 org-window-configuration
18362 (kill-buffer (current-buffer))))
18363 (org-install-agenda-files-menu)
18364 (message "New agenda file list installed"))
18366 (message "%s" (substitute-command-keys
18367 "Edit list and finish with \\[save-buffer]")))
18368 (customize-variable 'org-agenda-files)))
18370 (defun org-store-new-agenda-file-list (list)
18371 "Set new value for the agenda file list and save it correctly."
18372 (if (stringp org-agenda-files)
18373 (let ((fe (org-read-agenda-file-list t)) b u)
18374 (while (setq b (find-buffer-visiting org-agenda-files))
18376 (with-temp-file org-agenda-files
18379 (lambda (f) ;; Keep un-expanded entries.
18380 (if (setq u (assoc f fe))
18385 (let ((org-mode-hook nil) (org-inhibit-startup t)
18386 (org-insert-mode-line-in-empty-file nil))
18387 (setq org-agenda-files list)
18388 (customize-save-variable 'org-agenda-files org-agenda-files))))
18390 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18391 "Read the list of agenda files from a file.
18392 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18393 filenames, used by `org-store-new-agenda-file-list' to write back
18394 un-expanded file names."
18395 (when (file-directory-p org-agenda-files)
18396 (error "`org-agenda-files' cannot be a single directory"))
18397 (when (stringp org-agenda-files)
18399 (insert-file-contents org-agenda-files)
18402 (let ((e (expand-file-name (substitute-in-file-name f)
18404 (if pair-with-expansion
18407 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18410 (defun org-cycle-agenda-files ()
18411 "Cycle through the files in `org-agenda-files'.
18412 If the current buffer visits an agenda file, find the next one in the list.
18413 If the current buffer does not, find the first agenda file."
18415 (let* ((fs (or (org-agenda-files t)
18416 (user-error "No agenda files")))
18417 (files (copy-sequence fs))
18418 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18421 (while (and (setq file (pop files))
18422 (not (equal (file-truename file) tcf)))))
18423 (find-file (car (or files fs)))
18424 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18426 (defun org-agenda-file-to-front (&optional to-end)
18427 "Move/add the current file to the top of the agenda file list.
18428 If the file is not present in the list, it is added to the front. If it is
18429 present, it is moved there. With optional argument TO-END, add/move to the
18432 (let ((org-agenda-skip-unavailable-files nil)
18433 (file-alist (mapcar (lambda (x)
18434 (cons (file-truename x) x))
18435 (org-agenda-files t)))
18436 (ctf (file-truename
18437 (or buffer-file-name
18438 (user-error "Please save the current buffer to a file"))))
18440 (setq x (assoc ctf file-alist) had x)
18442 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18444 (setq file-alist (append (delq x file-alist) (list x)))
18445 (setq file-alist (cons x (delq x file-alist))))
18446 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18447 (org-install-agenda-files-menu)
18448 (message "File %s to %s of agenda file list"
18449 (if had "moved" "added") (if to-end "end" "front"))))
18451 (defun org-remove-file (&optional file)
18452 "Remove current file from the list of files in variable `org-agenda-files'.
18453 These are the files which are being checked for agenda entries.
18454 Optional argument FILE means use this file instead of the current."
18456 (let* ((org-agenda-skip-unavailable-files nil)
18457 (file (or file buffer-file-name
18458 (user-error "Current buffer does not visit a file")))
18459 (true-file (file-truename file))
18460 (afile (abbreviate-file-name file))
18461 (files (delq nil (mapcar
18463 (unless (equal true-file
18466 (org-agenda-files t)))))
18467 (if (not (= (length files) (length (org-agenda-files t))))
18469 (org-store-new-agenda-file-list files)
18470 (org-install-agenda-files-menu)
18471 (message "Removed from Org Agenda list: %s" afile))
18472 (message "File was not in list: %s (not removed)" afile))))
18474 (defun org-file-menu-entry (file)
18475 (vector file (list 'find-file file) t))
18477 (defun org-check-agenda-file (file)
18478 "Make sure FILE exists. If not, ask user what to do."
18479 (unless (file-exists-p file)
18480 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18481 (abbreviate-file-name file))
18482 (let ((r (downcase (read-char-exclusive))))
18485 (org-remove-file file)
18486 (throw 'nextfile t))
18487 (t (user-error "Abort"))))))
18489 (defun org-get-agenda-file-buffer (file)
18490 "Get an agenda buffer visiting FILE.
18491 If the buffer needs to be created, add it to the list of buffers
18492 which might be released later."
18493 (let ((buf (org-find-base-buffer-visiting file)))
18495 buf ; just return it
18496 ;; Make a new buffer and remember it
18497 (setq buf (find-file-noselect file))
18498 (when buf (push buf org-agenda-new-buffers))
18501 (defun org-release-buffers (blist)
18502 "Release all buffers in list, asking the user for confirmation when needed.
18503 When a buffer is unmodified, it is just killed. When modified, it is saved
18504 \(if the user agrees) and then killed."
18506 (dolist (buf blist)
18507 (setq file (buffer-file-name buf))
18508 (when (and (buffer-modified-p buf)
18510 (y-or-n-p (format "Save file %s? " file)))
18511 (with-current-buffer buf (save-buffer)))
18512 (kill-buffer buf))))
18514 (defun org-agenda-prepare-buffers (files)
18515 "Create buffers for all agenda files, protect archived trees and comments."
18517 (let ((pa '(:org-archived t))
18518 (pc '(:org-comment t))
18519 (pall '(:org-archived t :org-comment t))
18520 (inhibit-read-only t)
18521 (org-inhibit-startup org-agenda-inhibit-startup)
18522 (rea (concat ":" org-archive-tag ":"))
18524 (setq org-tag-alist-for-agenda nil
18525 org-tag-groups-alist-for-agenda nil)
18528 (dolist (file files)
18532 (org-check-agenda-file file)
18533 (set-buffer (org-get-agenda-file-buffer file)))
18535 (org-set-regexps-and-options 'tags-only)
18537 (or (memq 'category org-agenda-ignore-properties)
18538 (org-refresh-category-properties))
18539 (or (memq 'stats org-agenda-ignore-properties)
18540 (org-refresh-stats-properties))
18541 (or (memq 'effort org-agenda-ignore-properties)
18542 (org-refresh-effort-properties))
18543 (or (memq 'appt org-agenda-ignore-properties)
18544 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18545 (setq org-todo-keywords-for-agenda
18546 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18547 (setq org-done-keywords-for-agenda
18548 (append org-done-keywords-for-agenda org-done-keywords))
18549 (setq org-todo-keyword-alist-for-agenda
18550 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18551 (setq org-tag-alist-for-agenda
18553 (append org-tag-alist-for-agenda
18554 org-current-tag-alist)))
18555 ;; Merge current file's tag groups into global
18556 ;; `org-tag-groups-alist-for-agenda'.
18557 (when org-group-tags
18558 (dolist (alist org-tag-groups-alist)
18559 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18561 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18562 (push alist org-tag-groups-alist-for-agenda)))))
18563 (org-with-silent-modifications
18565 (remove-text-properties (point-min) (point-max) pall)
18566 (when org-agenda-skip-archived-trees
18567 (goto-char (point-min))
18568 (while (re-search-forward rea nil t)
18569 (when (org-at-heading-p t)
18570 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18571 (goto-char (point-min))
18572 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18573 (while (re-search-forward re nil t)
18574 (when (save-match-data (org-in-commented-heading-p t))
18575 (add-text-properties
18576 (match-beginning 0) (org-end-of-subtree t) pc)))))
18577 (goto-char pos)))))
18578 (setq org-todo-keywords-for-agenda
18579 (org-uniquify org-todo-keywords-for-agenda))
18580 (setq org-todo-keyword-alist-for-agenda
18581 (org-uniquify org-todo-keyword-alist-for-agenda))))
18584 ;;;; CDLaTeX minor mode
18586 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18587 "Keymap for the minor `org-cdlatex-mode'.")
18589 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18590 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18591 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18592 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18593 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18595 (defvar org-cdlatex-texmathp-advice-is-done nil
18596 "Flag remembering if we have applied the advice to texmathp already.")
18598 (define-minor-mode org-cdlatex-mode
18599 "Toggle the minor `org-cdlatex-mode'.
18600 This mode supports entering LaTeX environment and math in LaTeX fragments
18602 \\{org-cdlatex-mode-map}"
18604 (when org-cdlatex-mode
18606 (run-hooks 'cdlatex-mode-hook)
18607 (cdlatex-compute-tables))
18608 (unless org-cdlatex-texmathp-advice-is-done
18609 (setq org-cdlatex-texmathp-advice-is-done t)
18610 (defadvice texmathp (around org-math-always-on activate)
18611 "Always return t in Org buffers.
18612 This is because we want to insert math symbols without dollars even outside
18613 the LaTeX math segments. If Org mode thinks that point is actually inside
18614 an embedded LaTeX fragment, let `texmathp' do its job.
18615 `\\[org-cdlatex-mode-map]'"
18619 ((not (derived-mode-p 'org-mode)) ad-do-it)
18620 ((eq this-command 'cdlatex-math-symbol)
18621 (setq ad-return-value t
18622 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18624 (let ((p (org-inside-LaTeX-fragment-p)))
18625 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18626 (setq ad-return-value t
18627 texmathp-why '("Org mode embedded math" . 0))
18628 (when p ad-do-it)))))))))
18630 (defun turn-on-org-cdlatex ()
18631 "Unconditionally turn on `org-cdlatex-mode'."
18632 (org-cdlatex-mode 1))
18634 (defun org-try-cdlatex-tab ()
18635 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18636 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18637 - inside a LaTeX fragment, or
18638 - after the first word in a line, where an abbreviation expansion could
18639 insert a LaTeX environment."
18640 (when org-cdlatex-mode
18642 ;; Before any word on the line: No expansion possible.
18643 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18644 ;; Just after first word on the line: Expand it. Make sure it
18645 ;; cannot happen on headlines, though.
18647 (skip-chars-backward "a-zA-Z0-9*")
18648 (skip-chars-backward " \t")
18649 (and (bolp) (not (org-at-heading-p))))
18651 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18653 (defun org-cdlatex-underscore-caret (&optional _arg)
18654 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18655 Revert to the normal definition outside of these fragments."
18657 (if (org-inside-LaTeX-fragment-p)
18658 (call-interactively 'cdlatex-sub-superscript)
18659 (let (org-cdlatex-mode)
18660 (call-interactively (key-binding (vector last-input-event))))))
18662 (defun org-cdlatex-math-modify (&optional _arg)
18663 "Execute `cdlatex-math-modify' in LaTeX fragments.
18664 Revert to the normal definition outside of these fragments."
18666 (if (org-inside-LaTeX-fragment-p)
18667 (call-interactively 'cdlatex-math-modify)
18668 (let (org-cdlatex-mode)
18669 (call-interactively (key-binding (vector last-input-event))))))
18671 (defun org-cdlatex-environment-indent (&optional environment item)
18672 "Execute `cdlatex-environment' and indent the inserted environment.
18674 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18676 The inserted environment is indented to current indentation
18677 unless point is at the beginning of the line, in which the
18678 environment remains unintended."
18680 ;; cdlatex-environment always return nil. Therefore, capture output
18681 ;; first and determine if an environment was selected.
18682 (let* ((beg (point-marker))
18683 (end (copy-marker (point) t))
18685 (ignore-errors (cdlatex-environment environment item))
18687 ;; Figure out how many lines to move forward after the
18688 ;; environment has been inserted.
18689 (lines (when inserted
18691 (- (cl-loop while (< beg (point))
18693 do (forward-line -1)
18696 (if (progn (goto-char beg)
18697 (and (progn (skip-chars-forward " \t") (eolp))
18698 (progn (skip-chars-backward " \t") (bolp))))
18700 (env (org-trim (delete-and-extract-region beg end))))
18702 ;; Get indentation of next line unless at column 0.
18703 (let ((ind (if (bolp) 0
18705 (org-return-indent)
18706 (prog1 (org-get-indentation)
18707 (when (progn (skip-chars-forward " \t") (eolp))
18708 (delete-region beg (point)))))))
18709 (bol (progn (skip-chars-backward " \t") (bolp))))
18710 ;; Insert a newline before environment unless at column zero
18711 ;; to "escape" the current line. Insert a newline if
18712 ;; something is one the same line as \end{ENVIRONMENT}.
18714 (concat (unless bol "\n") env
18715 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18716 (unless (zerop ind)
18719 (while (< (point) end)
18720 (unless (eolp) (indent-line-to ind))
18723 (forward-line lines)
18724 (indent-line-to ind)))
18725 (set-marker beg nil)
18726 (set-marker end nil)))
18729 ;;;; LaTeX fragments
18731 (defun org-inside-LaTeX-fragment-p ()
18732 "Test if point is inside a LaTeX fragment.
18733 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18734 sequence appearing also before point.
18735 Even though the matchers for math are configurable, this function assumes
18736 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18737 delimiters are skipped when they have been removed by customization.
18738 The return value is nil, or a cons cell with the delimiter and the
18739 position of this delimiter.
18741 This function does a reasonably good job, but can locally be fooled by
18742 for example currency specifications. For example it will assume being in
18743 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18744 fragments that are properly closed, but during editing, we have to live
18745 with the uncertainty caused by missing closing delimiters. This function
18746 looks only before point, not after."
18748 (let ((pos (point))
18749 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18750 (lim (save-excursion (org-backward-paragraph) (point)))
18751 dd-on str (start 0) m re)
18754 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18755 re (nth 1 (assoc "$" org-latex-regexps)))
18756 (while (string-match re str start)
18758 ((= (match-end 0) (length str))
18759 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18760 ((= (match-end 0) (- (length str) 5))
18762 (t (setq start (match-end 0))))))
18763 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18765 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18766 (and (match-beginning 2) (throw 'exit nil))
18768 (while (re-search-backward "\\$\\$" lim t)
18769 (setq dd-on (not dd-on)))
18771 (when dd-on (cons "$$" m))))))
18773 (defun org-inside-latex-macro-p ()
18774 "Is point inside a LaTeX macro or its arguments?"
18777 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18779 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18780 "Build an overlay between BEG and END using IMAGE file.
18781 Argument IMAGETYPE is the extension of the displayed image,
18782 as a string. It defaults to \"png\"."
18783 (let ((ov (make-overlay beg end))
18784 (imagetype (or (intern imagetype) 'png)))
18785 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18786 (overlay-put ov 'evaporate t)
18788 'modification-hooks
18789 (list (lambda (o _flag _beg _end &optional _l)
18790 (delete-overlay o))))
18793 (list 'image :type imagetype :file image :ascent 'center))))
18795 (defun org--list-latex-overlays (&optional beg end)
18796 "List all Org LaTeX overlays in current buffer.
18797 Limit to overlays between BEG and END when those are provided."
18799 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18800 (overlays-in (or beg (point-min)) (or end (point-max)))))
18802 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18803 "Remove all overlays with LaTeX fragment images in current buffer.
18804 When optional arguments BEG and END are non-nil, remove all
18805 overlays between them instead. Return a non-nil value when some
18806 overlays were removed, nil otherwise."
18807 (let ((overlays (org--list-latex-overlays beg end)))
18808 (mapc #'delete-overlay overlays)
18811 (defun org-toggle-latex-fragment (&optional arg)
18812 "Preview the LaTeX fragment at point, or all locally or globally.
18814 If the cursor is on a LaTeX fragment, create the image and overlay
18815 it over the source code, if there is none. Remove it otherwise.
18816 If there is no fragment at point, display all fragments in the
18819 With prefix ARG, preview or clear image for all fragments in the
18820 current subtree or in the whole buffer when used before the first
18821 headline. With a prefix ARG `\\[universal-argument] \
18822 \\[universal-argument]' preview or clear images
18823 for all fragments in the buffer."
18825 (when (display-graphic-p)
18830 ((or (equal arg '(16))
18831 (and (equal arg '(4))
18832 (org-with-limited-levels (org-before-first-heading-p))))
18833 (if (org-remove-latex-fragment-image-overlays)
18834 (progn (message "LaTeX fragments images removed from buffer")
18836 (setq msg "Creating images for buffer...")))
18838 (org-with-limited-levels (org-back-to-heading t))
18840 (setq end (progn (org-end-of-subtree t) (point)))
18841 (if (org-remove-latex-fragment-image-overlays beg end)
18843 (message "LaTeX fragment images removed from subtree")
18845 (setq msg "Creating images for subtree...")))
18846 ((let ((datum (org-element-context)))
18847 (when (memq (org-element-type datum)
18848 '(latex-environment latex-fragment))
18849 (setq beg (org-element-property :begin datum))
18850 (setq end (org-element-property :end datum))
18851 (if (org-remove-latex-fragment-image-overlays beg end)
18852 (progn (message "LaTeX fragment image removed")
18854 (setq msg "Creating image...")))))
18856 (org-with-limited-levels
18857 (setq beg (if (org-at-heading-p) (line-beginning-position)
18858 (outline-previous-heading)
18860 (setq end (progn (outline-next-heading) (point)))
18861 (if (org-remove-latex-fragment-image-overlays beg end)
18863 (message "LaTeX fragment images removed from section")
18865 (setq msg "Creating images for section...")))))
18866 (let ((file (buffer-file-name (buffer-base-buffer))))
18868 (concat org-preview-latex-image-directory "org-ltximg")
18870 ;; Emacs cannot overlay images from remote hosts. Create
18871 ;; it in `temporary-file-directory' instead.
18872 (if (or (not file) (file-remote-p file))
18873 temporary-file-directory
18875 'overlays msg 'forbuffer org-preview-latex-default-process))
18876 (message (concat msg "done")))))))
18878 (defun org-format-latex
18879 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18880 "Replace LaTeX fragments with links to an image.
18882 The function takes care of creating the replacement image.
18884 Only consider fragments between BEG and END when those are
18887 When optional argument OVERLAYS is non-nil, display the image on
18888 top of the fragment instead of replacing it.
18890 PROCESSING-TYPE is the conversion method to use, as a symbol.
18892 Some of the options can be changed using the variable
18893 `org-format-latex-options', which see."
18894 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18895 (unless (eq processing-type 'verbatim)
18896 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18899 (goto-char (or beg (point-min)))
18900 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18901 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18902 (overlay-recenter (or end (point-max))))
18903 (while (re-search-forward math-regexp end t)
18904 (unless (and overlays
18905 (eq (get-char-property (point) 'org-overlay-type)
18906 'org-latex-overlay))
18907 (let* ((context (org-element-context))
18908 (type (org-element-type context)))
18909 (when (memq type '(latex-environment latex-fragment))
18910 (let ((block-type (eq type 'latex-environment))
18911 (value (org-element-property :value context))
18912 (beg (org-element-property :begin context))
18913 (end (save-excursion
18914 (goto-char (org-element-property :end context))
18915 (skip-chars-backward " \r\t\n")
18918 ((eq processing-type 'mathjax)
18919 ;; Prepare for MathJax processing.
18920 (if (not (string-match "\\`\\$\\$?" value))
18922 (delete-region beg end)
18923 (if (string= (match-string 0 value) "$$")
18924 (insert "\\[" (substring value 2 -2) "\\]")
18925 (insert "\\(" (substring value 1 -1) "\\)"))))
18926 ((assq processing-type org-preview-latex-process-alist)
18927 ;; Process to an image.
18930 (let* ((processing-info
18931 (cdr (assq processing-type org-preview-latex-process-alist)))
18932 (face (face-at-point))
18933 ;; Get the colors from the face at point.
18935 (let ((color (plist-get org-format-latex-options
18937 (if (and forbuffer (eq color 'auto))
18938 (face-attribute face :foreground nil 'default)
18941 (let ((color (plist-get org-format-latex-options
18943 (if (and forbuffer (eq color 'auto))
18944 (face-attribute face :background nil 'default)
18946 (hash (sha1 (prin1-to-string
18947 (list org-format-latex-header
18948 org-latex-default-packages-alist
18949 org-latex-packages-alist
18950 org-format-latex-options
18951 forbuffer value fg bg))))
18952 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18953 (absprefix (expand-file-name prefix dir))
18954 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18955 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18956 (sep (and block-type "\n\n"))
18957 (link (concat sep "[[file:" linkfile "]]" sep))
18959 (org-combine-plists
18960 org-format-latex-options
18961 `(:foreground ,fg :background ,bg))))
18962 (when msg (message msg cnt))
18963 (unless checkdir-flag ; Ensure the directory exists.
18964 (setq checkdir-flag t)
18965 (let ((todir (file-name-directory absprefix)))
18966 (unless (file-directory-p todir)
18967 (make-directory todir t))))
18968 (unless (file-exists-p movefile)
18969 (org-create-formula-image
18970 value movefile options forbuffer processing-type))
18973 (dolist (o (overlays-in beg end))
18974 (when (eq (overlay-get o 'org-overlay-type)
18975 'org-latex-overlay)
18976 (delete-overlay o)))
18977 (org--format-latex-make-overlay beg end movefile imagetype)
18979 (delete-region beg end)
18981 (org-add-props link
18982 (list 'org-latex-src
18983 (replace-regexp-in-string "\"" "" value)
18984 'org-latex-src-embed-type
18985 (if block-type 'paragraph 'character)))))))
18986 ((eq processing-type 'mathml)
18987 ;; Process to MathML.
18988 (unless (org-format-latex-mathml-available-p)
18989 (user-error "LaTeX to MathML converter not configured"))
18991 (when msg (message msg cnt))
18993 (delete-region beg end)
18994 (insert (org-format-latex-as-mathml
18995 value block-type prefix dir)))
18997 (error "Unknown conversion process %s for LaTeX fragments"
18998 processing-type)))))))))))
19000 (defun org-create-math-formula (latex-frag &optional mathml-file)
19001 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19002 Use `org-latex-to-mathml-convert-command'. If the conversion is
19003 sucessful, return the portion between \"<math...> </math>\"
19004 elements otherwise return nil. When MATHML-FILE is specified,
19005 write the results in to that file. When invoked as an
19006 interactive command, prompt for LATEX-FRAG, with initial value
19007 set to the current active region and echo the results for user
19009 (interactive (list (let ((frag (when (org-region-active-p)
19010 (buffer-substring-no-properties
19011 (region-beginning) (region-end)))))
19012 (read-string "LaTeX Fragment: " frag nil frag))))
19013 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19014 (let* ((tmp-in-file
19015 (let ((file (file-relative-name
19016 (make-temp-name (expand-file-name "ltxmathml-in")))))
19017 (write-region latex-frag nil file)
19019 (tmp-out-file (file-relative-name
19020 (make-temp-name (expand-file-name "ltxmathml-out"))))
19022 org-latex-to-mathml-convert-command
19023 `((?j . ,(and org-latex-to-mathml-jar-file
19024 (shell-quote-argument
19026 org-latex-to-mathml-jar-file))))
19027 (?I . ,(shell-quote-argument tmp-in-file))
19029 (?o . ,(shell-quote-argument tmp-out-file)))))
19030 mathml shell-command-output)
19031 (when (called-interactively-p 'any)
19032 (unless (org-format-latex-mathml-available-p)
19033 (user-error "LaTeX to MathML converter not configured")))
19034 (message "Running %s" cmd)
19035 (setq shell-command-output (shell-command-to-string cmd))
19037 (when (file-readable-p tmp-out-file)
19038 (with-current-buffer (find-file-noselect tmp-out-file t)
19039 (goto-char (point-min))
19040 (when (re-search-forward
19041 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19043 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19045 (prog1 (match-string 0) (kill-buffer))))))
19049 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19051 (write-region mathml nil mathml-file))
19052 (when (called-interactively-p 'any)
19054 ((message "LaTeX to MathML conversion failed")
19055 (message shell-command-output)))
19056 (delete-file tmp-in-file)
19057 (when (file-exists-p tmp-out-file)
19058 (delete-file tmp-out-file))
19061 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19062 prefix &optional dir)
19063 "Use `org-create-math-formula' but check local cache first."
19064 (let* ((absprefix (expand-file-name prefix dir))
19065 (print-length nil) (print-level nil)
19066 (formula-id (concat
19071 org-latex-to-mathml-convert-command)))))
19072 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19073 (formula-cache-dir (file-name-directory formula-cache)))
19075 (unless (file-directory-p formula-cache-dir)
19076 (make-directory formula-cache-dir t))
19078 (unless (file-exists-p formula-cache)
19079 (org-create-math-formula latex-frag formula-cache))
19081 (if (file-exists-p formula-cache)
19082 ;; Successful conversion. Return the link to MathML file.
19084 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19085 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19086 'org-latex-src-embed-type (if latex-frag-type
19087 'paragraph 'character)))
19088 ;; Failed conversion. Return the LaTeX fragment verbatim
19091 (defun org--get-display-dpi ()
19092 "Get the DPI of the display.
19093 The function assumes that the display has the same pixel width in
19094 the horizontal and vertical directions."
19095 (if (display-graphic-p)
19096 (round (/ (display-pixel-height)
19097 (/ (display-mm-height) 25.4)))
19098 (error "Attempt to calculate the dpi of a non-graphic display")))
19100 (defun org-create-formula-image
19101 (string tofile options buffer &optional processing-type)
19102 "Create an image from LaTeX source using external processes.
19104 The LaTeX STRING is saved to a temporary LaTeX file, then
19105 converted to an image file by process PROCESSING-TYPE defined in
19106 `org-preview-latex-process-alist'. A nil value defaults to
19107 `org-preview-latex-default-process'.
19109 The generated image file is eventually moved to TOFILE.
19111 The OPTIONS argument controls the size, foreground color and
19112 background color of the generated image.
19114 When BUFFER non-nil, this function is used for LaTeX previewing.
19115 Otherwise, it is used to deal with LaTeX snippets showed in
19117 (let* ((processing-type (or processing-type
19118 org-preview-latex-default-process))
19120 (cdr (assq processing-type org-preview-latex-process-alist)))
19121 (programs (plist-get processing-info :programs))
19122 (error-message (or (plist-get processing-info :message) ""))
19123 (use-xcolor (plist-get processing-info :use-xcolor))
19124 (image-input-type (plist-get processing-info :image-input-type))
19125 (image-output-type (plist-get processing-info :image-output-type))
19126 (post-clean (or (plist-get processing-info :post-clean)
19127 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19128 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19130 (or (plist-get processing-info :latex-header)
19131 (org-latex-make-preamble
19132 (org-export-get-environment (org-export-get-backend 'latex))
19133 org-format-latex-header
19135 (latex-compiler (plist-get processing-info :latex-compiler))
19136 (image-converter (plist-get processing-info :image-converter))
19137 (tmpdir temporary-file-directory)
19138 (texfilebase (make-temp-name
19139 (expand-file-name "orgtex" tmpdir)))
19140 (texfile (concat texfilebase ".tex"))
19141 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19143 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19144 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19145 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19146 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19148 (bg (or (plist-get options (if buffer :background :html-background))
19150 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19151 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19152 (dolist (program programs)
19153 (org-check-external-command program error-message))
19155 (progn (if (eq fg 'default)
19156 (setq fg (org-latex-color :foreground))
19157 (setq fg (org-latex-color-format fg)))
19158 (if (eq bg 'default)
19159 (setq bg (org-latex-color :background))
19160 (setq bg (org-latex-color-format
19161 (if (string= bg "Transparent") "white" bg))))
19162 (with-temp-file texfile
19163 (insert latex-header)
19164 (insert "\n\\begin{document}\n"
19165 "\\definecolor{fg}{rgb}{" fg "}\n"
19166 "\\definecolor{bg}{rgb}{" bg "}\n"
19167 "\n\\pagecolor{bg}\n"
19171 "\n\\end{document}\n")))
19172 (if (eq fg 'default)
19173 (setq fg (org-dvipng-color :foreground))
19174 (unless (string= fg "Transparent")
19175 (setq fg (org-dvipng-color-format fg))))
19176 (if (eq bg 'default)
19177 (setq bg (org-dvipng-color :background))
19178 (unless (string= bg "Transparent")
19179 (setq bg (org-dvipng-color-format bg))))
19180 (with-temp-file texfile
19181 (insert latex-header)
19182 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19184 (let* ((err-msg (format "Please adjust `%s' part of \
19185 `org-preview-latex-process-alist'."
19189 texfile latex-compiler image-input-type err-msg log-buf))
19192 image-input-file image-converter image-output-type err-msg log-buf
19193 `((?F . ,(shell-quote-argument fg))
19194 (?B . ,(shell-quote-argument bg))
19195 (?D . ,(shell-quote-argument (format "%s" dpi)))
19196 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19197 (copy-file image-output-file tofile 'replace)
19198 (dolist (e post-clean)
19199 (when (file-exists-p (concat texfilebase e))
19200 (delete-file (concat texfilebase e))))
19201 image-output-file)))
19203 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19204 "Fill a LaTeX header template TPL.
19205 In the template, the following place holders will be recognized:
19207 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19208 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19209 [PACKAGES] \\usepackage statements for PKG
19210 [NO-PACKAGES] do not include PKG
19211 [EXTRA] the string EXTRA
19212 [NO-EXTRA] do not include EXTRA
19214 For backward compatibility, if both the positive and the negative place
19215 holder is missing, the positive one (without the \"NO-\") will be
19216 assumed to be present at the end of the template.
19217 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19219 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19220 (let (rpl (end ""))
19221 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19222 (setq rpl (if (or (match-end 1) (not def-pkg))
19223 "" (org-latex-packages-to-string def-pkg snippets-p t))
19224 tpl (replace-match rpl t t tpl))
19225 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19227 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19228 (setq rpl (if (or (match-end 1) (not pkg))
19229 "" (org-latex-packages-to-string pkg snippets-p t))
19230 tpl (replace-match rpl t t tpl))
19231 (when pkg (setq end
19233 (org-latex-packages-to-string pkg snippets-p)))))
19235 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19236 (setq rpl (if (or (match-end 1) (not extra))
19237 "" (concat extra "\n"))
19238 tpl (replace-match rpl t t tpl))
19239 (when (and extra (string-match "\\S-" extra))
19240 (setq end (concat end "\n" extra))))
19242 (if (string-match "\\S-" end)
19243 (concat tpl "\n" end)
19246 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19247 "Turn an alist of packages into a string with the \\usepackage macros."
19248 (setq pkg (mapconcat (lambda(p)
19251 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19252 (format "%% Package %s omitted" (cadr p)))
19253 ((equal "" (car p))
19254 (format "\\usepackage{%s}" (cadr p)))
19256 (format "\\usepackage[%s]{%s}"
19257 (car p) (cadr p)))))
19260 (if newline (concat pkg "\n") pkg))
19262 (defun org-dvipng-color (attr)
19263 "Return a RGB color specification for dvipng."
19264 (org-dvipng-color-format (face-attribute 'default attr nil)))
19266 (defun org-dvipng-color-format (color-name)
19267 "Convert COLOR-NAME to a RGB color value for dvipng."
19268 (apply #'format "rgb %s %s %s"
19269 (mapcar 'org-normalize-color
19270 (color-values color-name))))
19272 (defun org-latex-color (attr)
19273 "Return a RGB color for the LaTeX color package."
19274 (org-latex-color-format (face-attribute 'default attr nil)))
19276 (defun org-latex-color-format (color-name)
19277 "Convert COLOR-NAME to a RGB color value."
19278 (apply #'format "%s,%s,%s"
19279 (mapcar 'org-normalize-color
19280 (color-values color-name))))
19282 (defun org-normalize-color (value)
19283 "Return string to be used as color value for an RGB component."
19284 (format "%g" (/ value 65535.0)))
19290 (defvar-local org-inline-image-overlays nil)
19292 (defun org-toggle-inline-images (&optional include-linked)
19293 "Toggle the display of inline images.
19294 INCLUDE-LINKED is passed to `org-display-inline-images'."
19296 (if org-inline-image-overlays
19298 (org-remove-inline-images)
19299 (when (called-interactively-p 'interactive)
19300 (message "Inline image display turned off")))
19301 (org-display-inline-images include-linked)
19302 (when (called-interactively-p 'interactive)
19303 (message (if org-inline-image-overlays
19304 (format "%d images displayed inline"
19305 (length org-inline-image-overlays))
19306 "No images to display inline")))))
19308 (defun org-redisplay-inline-images ()
19309 "Refresh the display of inline images."
19311 (if (not org-inline-image-overlays)
19312 (org-toggle-inline-images)
19313 (org-toggle-inline-images)
19314 (org-toggle-inline-images)))
19316 (defun org-display-inline-images (&optional include-linked refresh beg end)
19317 "Display inline images.
19319 An inline image is a link which follows either of these
19322 1. Its path is a file with an extension matching return value
19323 from `image-file-name-regexp' and it has no contents.
19325 2. Its description consists in a single link of the previous
19328 When optional argument INCLUDE-LINKED is non-nil, also links with
19329 a text description part will be inlined. This can be nice for
19330 a quick look at those images, but it does not reflect what
19331 exported files will look like.
19333 When optional argument REFRESH is non-nil, refresh existing
19334 images between BEG and END. This will create new image displays
19335 only if necessary. BEG and END default to the buffer
19338 (when (display-graphic-p)
19340 (org-remove-inline-images)
19341 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19342 (org-with-wide-buffer
19343 (goto-char (or beg (point-min)))
19344 (let* ((case-fold-search t)
19345 (file-extension-re (image-file-name-regexp))
19346 (link-abbrevs (mapcar #'car
19347 (append org-link-abbrev-alist-local
19348 org-link-abbrev-alist)))
19349 ;; Check absolute, relative file names and explicit
19350 ;; "file:" links. Also check link abbreviations since
19351 ;; some might expand to "file" links.
19352 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19353 (if (not link-abbrevs) ""
19354 (format "\\|\\(?:%s:\\)"
19355 (regexp-opt link-abbrevs))))))
19356 (while (re-search-forward file-types-re end t)
19357 (let ((link (save-match-data (org-element-context))))
19358 ;; Check if we're at an inline image, i.e., an image file
19359 ;; link without a description (unless INCLUDE-LINKED is
19361 (when (and (equal "file" (org-element-property :type link))
19363 (null (org-element-contents link)))
19364 (string-match-p file-extension-re
19365 (org-element-property :path link)))
19366 (let ((file (expand-file-name
19368 (org-element-property :path link)))))
19369 (when (file-exists-p file)
19371 ;; Apply `org-image-actual-width' specifications.
19373 ((not (image-type-available-p 'imagemagick)) nil)
19374 ((eq org-image-actual-width t) nil)
19375 ((listp org-image-actual-width)
19377 ;; First try to find a width among
19378 ;; attributes associated to the paragraph
19379 ;; containing link.
19382 (while (and (setq e (org-element-property
19384 (not (eq (org-element-type e)
19389 (goto-char (org-element-property :begin paragraph))
19392 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19393 (org-element-property
19394 :post-affiliated paragraph)
19396 (string-to-number (match-string 1))))))
19397 ;; Otherwise, fall-back to provided number.
19398 (car org-image-actual-width)))
19399 ((numberp org-image-actual-width)
19400 org-image-actual-width)))
19401 (old (get-char-property-and-overlay
19402 (org-element-property :begin link)
19403 'org-image-overlay)))
19404 (if (and (car-safe old) refresh)
19405 (image-refresh (overlay-get (cdr old) 'display))
19406 (let ((image (create-image file
19407 (and width 'imagemagick)
19411 (let ((ov (make-overlay
19412 (org-element-property :begin link)
19415 (org-element-property :end link))
19416 (skip-chars-backward " \t")
19418 (overlay-put ov 'display image)
19419 (overlay-put ov 'face 'default)
19420 (overlay-put ov 'org-image-overlay t)
19422 ov 'modification-hooks
19423 (list 'org-display-inline-remove-overlay))
19424 (push ov org-inline-image-overlays)))))))))))))))
19426 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19427 "Remove inline-display overlay if a corresponding region is modified."
19428 (let ((inhibit-modification-hooks t))
19429 (when (and ov after)
19430 (delete ov org-inline-image-overlays)
19431 (delete-overlay ov))))
19433 (defun org-remove-inline-images ()
19434 "Remove inline display of images."
19436 (mapc #'delete-overlay org-inline-image-overlays)
19437 (setq org-inline-image-overlays nil))
19441 (defun org-remap (map &rest commands)
19442 "In MAP, remap the functions given in COMMANDS.
19443 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19446 (setq old (pop commands) new (pop commands))
19447 (org-defkey map (vector 'remap old) new))))
19449 ;; Outline functions from `outline-mode-prefix-map'
19450 ;; that can be remapped in Org:
19451 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19452 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19453 (define-key org-mode-map [remap outline-forward-same-level]
19454 'org-forward-heading-same-level)
19455 (define-key org-mode-map [remap outline-backward-same-level]
19456 'org-backward-heading-same-level)
19457 (define-key org-mode-map [remap outline-show-branches]
19458 'org-kill-note-or-show-branches)
19459 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19460 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19461 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19462 (define-key org-mode-map [remap outline-next-visible-heading]
19463 'org-next-visible-heading)
19464 (define-key org-mode-map [remap outline-previous-visible-heading]
19465 'org-previous-visible-heading)
19466 (define-key org-mode-map [remap show-children] 'org-show-children)
19468 ;; Outline functions from `outline-mode-prefix-map' that can not
19469 ;; be remapped in Org:
19471 ;; - the column "key binding" shows whether the Outline function is still
19472 ;; available in Org mode on the same key that it has been bound to in
19474 ;; - "overridden": key used for a different functionality in Org mode
19475 ;; - else: key still bound to the same Outline function in Org mode
19477 ;; | Outline function | key binding | Org replacement |
19478 ;; |------------------------------------+-------------+--------------------------|
19479 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19480 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19481 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19482 ;; | `show-entry' | overridden | no replacement |
19483 ;; | `show-branches' | `C-c C-k' | still same function |
19484 ;; | `show-subtree' | overridden | visibility cycling |
19485 ;; | `show-all' | overridden | no replacement |
19486 ;; | `hide-subtree' | overridden | visibility cycling |
19487 ;; | `hide-body' | overridden | no replacement |
19488 ;; | `hide-entry' | overridden | visibility cycling |
19489 ;; | `hide-leaves' | overridden | no replacement |
19490 ;; | `hide-sublevels' | overridden | no replacement |
19491 ;; | `hide-other' | overridden | no replacement |
19493 ;; Make `C-c C-x' a prefix key
19494 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19496 ;; TAB key with modifiers
19497 (org-defkey org-mode-map "\C-i" 'org-cycle)
19498 (org-defkey org-mode-map [(tab)] 'org-cycle)
19499 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19500 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19502 ;; The following line is necessary under Suse GNU/Linux
19503 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19504 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19505 (define-key org-mode-map [backtab] 'org-shifttab)
19507 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19508 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19509 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
19511 ;; Cursor keys with modifiers
19512 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19513 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19514 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19515 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19517 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19518 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19519 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19520 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19521 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19522 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19524 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19525 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19526 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19527 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19529 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19530 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19531 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19532 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19535 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19536 (dolist (pair org-babel-key-bindings)
19537 (define-key org-babel-map (car pair) (cdr pair)))
19539 ;;; Extra keys for tty access.
19540 ;; We only set them when really needed because otherwise the
19541 ;; menus don't show the simple keys
19543 (when (or org-use-extra-keys (not window-system))
19544 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19545 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19546 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19547 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19548 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19549 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19550 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19551 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19552 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19553 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19554 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19555 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19556 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19557 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19558 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19559 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19560 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19561 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19562 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19563 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19564 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19565 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19566 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19567 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19568 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19569 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19570 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19571 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19573 ;; All the other keys
19574 (org-remap org-mode-map
19575 'self-insert-command 'org-self-insert-command
19576 'delete-char 'org-delete-char
19577 'delete-backward-char 'org-delete-backward-char)
19578 (org-defkey org-mode-map "|" 'org-force-self-insert)
19580 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19581 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19582 (if (boundp 'narrow-map)
19583 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19584 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19585 (if (boundp 'narrow-map)
19586 (org-defkey narrow-map "b" 'org-narrow-to-block)
19587 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19588 (if (boundp 'narrow-map)
19589 (org-defkey narrow-map "e" 'org-narrow-to-element)
19590 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19591 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19592 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19593 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19594 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19595 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19596 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19597 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19598 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19599 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19600 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19601 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19602 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19603 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19604 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19605 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19606 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19607 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19608 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19609 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19610 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19611 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19612 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19613 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19614 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19615 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19616 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19617 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19618 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19619 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19620 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19621 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19622 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19623 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19624 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19625 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19626 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19627 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19628 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19629 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19630 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19631 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19632 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19633 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19634 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19635 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19636 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19637 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19638 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19639 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19640 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19641 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19642 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19643 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19644 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19645 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19646 (org-defkey org-mode-map "\C-c^" 'org-sort)
19647 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19648 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19649 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19650 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19651 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19652 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19653 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19654 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19655 (org-defkey org-mode-map "\C-m" 'org-return)
19656 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19657 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19658 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19659 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19660 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19661 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19662 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19663 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19664 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19665 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19666 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19667 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19668 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19669 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19670 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19671 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19672 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19673 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19674 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19675 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19676 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19677 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19678 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19679 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19680 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19682 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19683 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19684 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19686 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19687 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19688 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19689 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19690 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19691 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19692 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19693 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19694 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19695 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19696 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19697 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19698 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19699 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19700 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19701 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19702 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19703 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19704 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19705 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19706 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19707 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19709 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19710 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19711 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19712 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19713 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19715 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19717 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19719 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19720 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19722 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19725 (defconst org-speed-commands-default
19727 ("Outline Navigation")
19728 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19729 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19730 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19731 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19732 ("F" . org-next-block)
19733 ("B" . org-previous-block)
19734 ("u" . (org-speed-move-safe 'outline-up-heading))
19736 ("g" . (org-refile t))
19737 ("Outline Visibility")
19739 ("C" . org-shifttab)
19740 (" " . org-display-outline-path)
19741 ("s" . org-narrow-to-subtree)
19742 ("=" . org-columns)
19743 ("Outline Structure Editing")
19745 ("D" . org-metadown)
19746 ("r" . org-metaright)
19747 ("l" . org-metaleft)
19748 ("R" . org-shiftmetaright)
19749 ("L" . org-shiftmetaleft)
19750 ("i" . (progn (forward-char 1) (call-interactively
19751 'org-insert-heading-respect-content)))
19754 ("a" . org-archive-subtree-default-with-confirmation)
19755 ("@" . org-mark-subtree)
19756 ("#" . org-toggle-comment)
19758 ("I" . org-clock-in)
19759 ("O" . org-clock-out)
19760 ("Meta Data Editing")
19762 ("," . (org-priority))
19763 ("0" . (org-priority ?\ ))
19764 ("1" . (org-priority ?A))
19765 ("2" . (org-priority ?B))
19766 ("3" . (org-priority ?C))
19767 (":" . org-set-tags-command)
19768 ("e" . org-set-effort)
19769 ("E" . org-inc-effort)
19770 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19771 (org-entry-put (point) "APPT_WARNTIME" m)))
19772 ("Agenda Views etc")
19774 ("/" . org-sparse-tree)
19776 ("o" . org-open-at-point)
19777 ("?" . org-speed-command-help)
19778 ("<" . (org-agenda-set-restriction-lock 'subtree))
19779 (">" . (org-agenda-remove-restriction-lock))
19781 "The default speed commands.")
19783 (defun org-print-speed-command (e)
19784 (if (> (length (car e)) 1)
19789 (princ (make-string (length (car e)) ?-))
19793 (if (symbolp (cdr e))
19794 (princ (symbol-name (cdr e)))
19798 (defun org-speed-command-help ()
19799 "Show the available speed commands."
19801 (if (not org-use-speed-commands)
19802 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19803 (with-output-to-temp-buffer "*Help*"
19804 (princ "User-defined Speed commands\n===========================\n")
19805 (mapc #'org-print-speed-command org-speed-commands-user)
19807 (princ "Built-in Speed commands\n=======================\n")
19808 (mapc #'org-print-speed-command org-speed-commands-default))
19809 (with-current-buffer "*Help*"
19810 (setq truncate-lines t))))
19812 (defun org-speed-move-safe (cmd)
19813 "Execute CMD, but make sure that the cursor always ends up in a headline.
19814 If not, return to the original position and throw an error."
19816 (let ((pos (point)))
19817 (call-interactively cmd)
19818 (unless (and (bolp) (org-at-heading-p))
19820 (error "Boundary reached while executing %s" cmd))))
19822 (defvar org-self-insert-command-undo-counter 0)
19824 (defvar org-table-auto-blank-field) ; defined in org-table.el
19825 (defvar org-speed-command nil)
19827 (defun org-speed-command-activate (keys)
19828 "Hook for activating single-letter speed commands.
19829 `org-speed-commands-default' specifies a minimal command set.
19830 Use `org-speed-commands-user' for further customization."
19831 (when (or (and (bolp) (looking-at org-outline-regexp))
19832 (and (functionp org-use-speed-commands)
19833 (funcall org-use-speed-commands)))
19834 (cdr (assoc keys (append org-speed-commands-user
19835 org-speed-commands-default)))))
19837 (defun org-babel-speed-command-activate (keys)
19838 "Hook for activating single-letter code block commands."
19839 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19840 (cdr (assoc keys org-babel-key-bindings))))
19842 (defcustom org-speed-command-hook
19843 '(org-speed-command-activate org-babel-speed-command-activate)
19844 "Hook for activating speed commands at strategic locations.
19845 Hook functions are called in sequence until a valid handler is
19848 Each hook takes a single argument, a user-pressed command key
19849 which is also a `self-insert-command' from the global map.
19851 Within the hook, examine the cursor position and the command key
19852 and return nil or a valid handler as appropriate. Handler could
19853 be one of an interactive command, a function, or a form.
19855 Set `org-use-speed-commands' to non-nil value to enable this
19856 hook. The default setting is `org-speed-command-activate'."
19857 :group 'org-structure
19861 (defun org-self-insert-command (N)
19862 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19863 If the cursor is in a table looking at whitespace, the whitespace is
19864 overwritten, and the table is not marked as requiring realignment."
19866 (org-check-before-invisible-edit 'insert)
19868 ((and org-use-speed-commands
19869 (let ((kv (this-command-keys-vector)))
19870 (setq org-speed-command
19871 (run-hook-with-args-until-success
19872 'org-speed-command-hook
19873 (make-string 1 (aref kv (1- (length kv))))))))
19875 ((commandp org-speed-command)
19876 (setq this-command org-speed-command)
19877 (call-interactively org-speed-command))
19878 ((functionp org-speed-command)
19879 (funcall org-speed-command))
19880 ((and org-speed-command (listp org-speed-command))
19881 (eval org-speed-command))
19882 (t (let (org-use-speed-commands)
19883 (call-interactively 'org-self-insert-command)))))
19887 (not (org-region-active-p))
19889 ;; Check if we blank the field, and if that triggers align.
19890 (and (featurep 'org-table) org-table-auto-blank-field
19892 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19893 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19894 ;; Got extra space, this field does not determine
19896 (let (org-table-may-need-update) (org-table-blank-field))
19897 ;; No extra space, this field may determine column
19899 (org-table-blank-field)))
19901 (looking-at "[^|\n]* \\( \\)|"))
19902 ;; There is room for insertion without re-aligning the table.
19903 (delete-region (match-beginning 1) (match-end 1))
19904 (self-insert-command N))
19906 (setq org-table-may-need-update t)
19907 (self-insert-command N)
19908 (org-fix-tags-on-the-fly)
19909 (when org-self-insert-cluster-for-undo
19910 (if (not (eq last-command 'org-self-insert-command))
19911 (setq org-self-insert-command-undo-counter 1)
19912 (if (>= org-self-insert-command-undo-counter 20)
19913 (setq org-self-insert-command-undo-counter 1)
19914 (and (> org-self-insert-command-undo-counter 0)
19915 buffer-undo-list (listp buffer-undo-list)
19916 (not (cadr buffer-undo-list)) ; remove nil entry
19917 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19918 (setq org-self-insert-command-undo-counter
19919 (1+ org-self-insert-command-undo-counter))))))))
19921 (defun org-check-before-invisible-edit (kind)
19922 "Check is editing if kind KIND would be dangerous with invisible text around.
19923 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19924 ;; First, try to get out of here as quickly as possible, to reduce overhead
19925 (when (and org-catch-invisible-edits
19926 (or (not (boundp 'visible-mode)) (not visible-mode))
19927 (or (get-char-property (point) 'invisible)
19928 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19929 ;; OK, we need to take a closer look. Do not consider
19930 ;; invisibility obtained through text properties (e.g., link
19931 ;; fontification), as it cannot be toggled.
19932 (let* ((invisible-at-point
19933 (pcase (get-char-property-and-overlay (point) 'invisible)
19934 (`(,_ . ,(and (pred overlayp) o)) o)))
19935 ;; Assume that point cannot land in the middle of an
19936 ;; overlay, or between two overlays.
19937 (invisible-before-point
19938 (and (not invisible-at-point)
19940 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19941 (`(,_ . ,(and (pred overlayp) o)) o))))
19942 (border-and-ok-direction
19944 ;; Check if we are acting predictably before invisible
19946 (and invisible-at-point
19947 (memq kind '(insert delete-backward)))
19948 ;; Check if we are acting predictably after invisible text
19949 ;; This works not well, and I have turned it off. It seems
19950 ;; better to always show and stop after invisible text.
19951 ;; (and (not invisible-at-point) invisible-before-point
19952 ;; (memq kind '(insert delete)))
19954 (when (or invisible-at-point invisible-before-point)
19955 (when (eq org-catch-invisible-edits 'error)
19956 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19957 (if (and org-custom-properties-overlays
19958 (y-or-n-p "Display invisible properties in this buffer? "))
19959 (org-toggle-custom-properties-visibility)
19960 ;; Make the area visible
19962 (when invisible-before-point
19964 (previous-single-char-property-change (point) 'invisible)))
19965 ;; Remove whatever overlay is currently making yet-to-be
19966 ;; edited text invisible. Also remove nested invisibility
19967 ;; related overlays.
19968 (delete-overlay (or invisible-at-point invisible-before-point))
19969 (let ((origin (if invisible-at-point (point) (1- (point)))))
19970 (while (pcase (get-char-property-and-overlay origin 'invisible)
19971 (`(,_ . ,(and (pred overlayp) o))
19975 ((eq org-catch-invisible-edits 'show)
19976 ;; That's it, we do the edit after showing
19978 "Unfolding invisible region around point before editing")
19980 ((and (eq org-catch-invisible-edits 'smart)
19981 border-and-ok-direction)
19982 (message "Unfolding invisible region around point before editing"))
19984 ;; Don't do the edit, make the user repeat it in full visibility
19985 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19987 (defun org-fix-tags-on-the-fly ()
19988 "Align tags in headline at point.
19989 Unlike to `org-set-tags', it ignores region and sorting."
19990 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19991 (org-at-heading-p))
19992 (let ((org-ignore-region t)
19993 (org-tags-sort-function nil))
19994 (org-set-tags nil t))))
19996 (defun org-delete-backward-char (N)
19997 "Like `delete-backward-char', insert whitespace at field end in tables.
19998 When deleting backwards, in tables this function will insert whitespace in
19999 front of the next \"|\" separator, to keep the table aligned. The table will
20000 still be marked for re-alignment if the field did fill the entire column,
20001 because, in this case the deletion might narrow the column."
20004 (org-check-before-invisible-edit 'delete-backward)
20005 (if (and (org-at-table-p)
20007 (not (org-region-active-p))
20008 (string-match "|" (buffer-substring (point-at-bol) (point)))
20009 (looking-at ".*?|"))
20010 (let ((pos (point))
20011 (noalign (looking-at "[^|\n\r]* |"))
20012 (c org-table-may-need-update))
20013 (backward-delete-char N)
20014 (unless overwrite-mode
20015 (skip-chars-forward "^|")
20017 (goto-char (1- pos)))
20018 ;; noalign: if there were two spaces at the end, this field
20019 ;; does not determine the width of the column.
20020 (when noalign (setq org-table-may-need-update c)))
20021 (backward-delete-char N)
20022 (org-fix-tags-on-the-fly))))
20024 (defun org-delete-char (N)
20025 "Like `delete-char', but insert whitespace at field end in tables.
20026 When deleting characters, in tables this function will insert whitespace in
20027 front of the next \"|\" separator, to keep the table aligned. The table will
20028 still be marked for re-alignment if the field did fill the entire column,
20029 because, in this case the deletion might narrow the column."
20032 (org-check-before-invisible-edit 'delete)
20033 (if (and (org-at-table-p)
20035 (not (= (char-after) ?|))
20037 (if (looking-at ".*?|")
20038 (let ((pos (point))
20039 (noalign (looking-at "[^|\n\r]* |"))
20040 (c org-table-may-need-update))
20042 (concat (substring (match-string 0) 1 -1) " |") nil t)
20044 ;; noalign: if there were two spaces at the end, this field
20045 ;; does not determine the width of the column.
20046 (when noalign (setq org-table-may-need-update c)))
20049 (org-fix-tags-on-the-fly))))
20051 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20052 (put 'org-self-insert-command 'delete-selection
20054 (not (run-hook-with-args-until-success
20055 'self-insert-uses-region-functions))))
20056 (put 'orgtbl-self-insert-command 'delete-selection
20058 (not (run-hook-with-args-until-success
20059 'self-insert-uses-region-functions))))
20060 (put 'org-delete-char 'delete-selection 'supersede)
20061 (put 'org-delete-backward-char 'delete-selection 'supersede)
20062 (put 'org-yank 'delete-selection 'yank)
20064 ;; Make `flyspell-mode' delay after some commands
20065 (put 'org-self-insert-command 'flyspell-delayed t)
20066 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20067 (put 'org-delete-char 'flyspell-delayed t)
20068 (put 'org-delete-backward-char 'flyspell-delayed t)
20070 ;; Make pabbrev-mode expand after Org mode commands
20071 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20072 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20074 (defun org-transpose-words ()
20075 "Transpose words for Org.
20076 This uses the `org-mode-transpose-word-syntax-table' syntax
20077 table, which interprets characters in `org-emphasis-alist' as
20078 word constituents."
20080 (with-syntax-table org-mode-transpose-word-syntax-table
20081 (call-interactively 'transpose-words)))
20082 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20084 (defvar org-ctrl-c-ctrl-c-hook nil
20085 "Hook for functions attaching themselves to `C-c C-c'.
20087 This can be used to add additional functionality to the C-c C-c
20088 key which executes context-dependent commands. This hook is run
20089 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20090 run after the last test.
20092 Each function will be called with no arguments. The function
20093 must check if the context is appropriate for it to act. If yes,
20094 it should do its thing and then return a non-nil value. If the
20095 context is wrong, just do nothing and return nil.")
20097 (defvar org-ctrl-c-ctrl-c-final-hook nil
20098 "Hook for functions attaching themselves to `C-c C-c'.
20100 This can be used to add additional functionality to the C-c C-c
20101 key which executes context-dependent commands. This hook is run
20102 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20103 before the first test.
20105 Each function will be called with no arguments. The function
20106 must check if the context is appropriate for it to act. If yes,
20107 it should do its thing and then return a non-nil value. If the
20108 context is wrong, just do nothing and return nil.")
20110 (defvar org-tab-first-hook nil
20111 "Hook for functions to attach themselves to TAB.
20112 See `org-ctrl-c-ctrl-c-hook' for more information.
20113 This hook runs as the first action when TAB is pressed, even before
20114 `org-cycle' messes around with the `outline-regexp' to cater for
20115 inline tasks and plain list item folding.
20116 If any function in this hook returns t, any other actions that
20117 would have been caused by TAB (such as table field motion or visibility
20118 cycling) will not occur.")
20120 (defvar org-tab-after-check-for-table-hook nil
20121 "Hook for functions to attach themselves to TAB.
20122 See `org-ctrl-c-ctrl-c-hook' for more information.
20123 This hook runs after it has been established that the cursor is not in a
20124 table, but before checking if the cursor is in a headline or if global cycling
20126 If any function in this hook returns t, not other actions like visibility
20127 cycling will be done.")
20129 (defvar org-tab-after-check-for-cycling-hook nil
20130 "Hook for functions to attach themselves to TAB.
20131 See `org-ctrl-c-ctrl-c-hook' for more information.
20132 This hook runs after it has been established that not table field motion and
20133 not visibility should be done because of current context. This is probably
20134 the place where a package like yasnippets can hook in.")
20136 (defvar org-tab-before-tab-emulation-hook nil
20137 "Hook for functions to attach themselves to TAB.
20138 See `org-ctrl-c-ctrl-c-hook' for more information.
20139 This hook runs after every other options for TAB have been exhausted, but
20140 before indentation and \t insertion takes place.")
20142 (defvar org-metaleft-hook nil
20143 "Hook for functions attaching themselves to `M-left'.
20144 See `org-ctrl-c-ctrl-c-hook' for more information.")
20145 (defvar org-metaright-hook nil
20146 "Hook for functions attaching themselves to `M-right'.
20147 See `org-ctrl-c-ctrl-c-hook' for more information.")
20148 (defvar org-metaup-hook nil
20149 "Hook for functions attaching themselves to `M-up'.
20150 See `org-ctrl-c-ctrl-c-hook' for more information.")
20151 (defvar org-metadown-hook nil
20152 "Hook for functions attaching themselves to `M-down'.
20153 See `org-ctrl-c-ctrl-c-hook' for more information.")
20154 (defvar org-shiftmetaleft-hook nil
20155 "Hook for functions attaching themselves to `M-S-left'.
20156 See `org-ctrl-c-ctrl-c-hook' for more information.")
20157 (defvar org-shiftmetaright-hook nil
20158 "Hook for functions attaching themselves to `M-S-right'.
20159 See `org-ctrl-c-ctrl-c-hook' for more information.")
20160 (defvar org-shiftmetaup-hook nil
20161 "Hook for functions attaching themselves to `M-S-up'.
20162 See `org-ctrl-c-ctrl-c-hook' for more information.")
20163 (defvar org-shiftmetadown-hook nil
20164 "Hook for functions attaching themselves to `M-S-down'.
20165 See `org-ctrl-c-ctrl-c-hook' for more information.")
20166 (defvar org-metareturn-hook nil
20167 "Hook for functions attaching themselves to `M-RET'.
20168 See `org-ctrl-c-ctrl-c-hook' for more information.")
20169 (defvar org-shiftup-hook nil
20170 "Hook for functions attaching themselves to `S-up'.
20171 See `org-ctrl-c-ctrl-c-hook' for more information.")
20172 (defvar org-shiftup-final-hook nil
20173 "Hook for functions attaching themselves to `S-up'.
20174 This one runs after all other options except shift-select have been excluded.
20175 See `org-ctrl-c-ctrl-c-hook' for more information.")
20176 (defvar org-shiftdown-hook nil
20177 "Hook for functions attaching themselves to `S-down'.
20178 See `org-ctrl-c-ctrl-c-hook' for more information.")
20179 (defvar org-shiftdown-final-hook nil
20180 "Hook for functions attaching themselves to `S-down'.
20181 This one runs after all other options except shift-select have been excluded.
20182 See `org-ctrl-c-ctrl-c-hook' for more information.")
20183 (defvar org-shiftleft-hook nil
20184 "Hook for functions attaching themselves to `S-left'.
20185 See `org-ctrl-c-ctrl-c-hook' for more information.")
20186 (defvar org-shiftleft-final-hook nil
20187 "Hook for functions attaching themselves to `S-left'.
20188 This one runs after all other options except shift-select have been excluded.
20189 See `org-ctrl-c-ctrl-c-hook' for more information.")
20190 (defvar org-shiftright-hook nil
20191 "Hook for functions attaching themselves to `S-right'.
20192 See `org-ctrl-c-ctrl-c-hook' for more information.")
20193 (defvar org-shiftright-final-hook nil
20194 "Hook for functions attaching themselves to `S-right'.
20195 This one runs after all other options except shift-select have been excluded.
20196 See `org-ctrl-c-ctrl-c-hook' for more information.")
20198 (defun org-modifier-cursor-error ()
20199 "Throw an error, a modified cursor command was applied in wrong context."
20200 (user-error "This command is active in special context like tables, headlines or items"))
20202 (defun org-shiftselect-error ()
20203 "Throw an error because Shift-Cursor command was applied in wrong context."
20204 (if (and (boundp 'shift-select-mode) shift-select-mode)
20205 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20206 (user-error "This command works only in special context like headlines or timestamps")))
20208 (defun org-call-for-shift-select (cmd)
20209 (let ((this-command-keys-shift-translated t))
20210 (call-interactively cmd)))
20212 (defun org-shifttab (&optional arg)
20213 "Global visibility cycling or move to previous table field.
20214 Call `org-table-previous-field' within a table.
20215 When ARG is nil, cycle globally through visibility states.
20216 When ARG is a numeric prefix, show contents of this level."
20219 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20221 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20222 (message "Content view to level: %d" arg)
20223 (org-content (prefix-numeric-value arg2))
20224 (org-cycle-show-empty-lines t)
20225 (setq org-cycle-global-status 'overview)))
20226 (t (call-interactively 'org-global-cycle))))
20228 (defun org-shiftmetaleft ()
20229 "Promote subtree or delete table column.
20230 Calls `org-promote-subtree', `org-outdent-item-tree', or
20231 `org-table-delete-column', depending on context. See the
20232 individual commands for more information."
20235 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20236 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20237 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20238 ((if (not (org-region-active-p)) (org-at-item-p)
20239 (save-excursion (goto-char (region-beginning))
20241 (call-interactively 'org-outdent-item-tree))
20242 (t (org-modifier-cursor-error))))
20244 (defun org-shiftmetaright ()
20245 "Demote subtree or insert table column.
20246 Calls `org-demote-subtree', `org-indent-item-tree', or
20247 `org-table-insert-column', depending on context. See the
20248 individual commands for more information."
20251 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20252 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20253 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20254 ((if (not (org-region-active-p)) (org-at-item-p)
20255 (save-excursion (goto-char (region-beginning))
20257 (call-interactively 'org-indent-item-tree))
20258 (t (org-modifier-cursor-error))))
20260 (defun org-shiftmetaup (&optional _arg)
20261 "Drag the line at point up.
20262 In a table, kill the current row.
20263 On a clock timestamp, update the value of the timestamp like `S-<up>'
20264 but also adjust the previous clocked item in the clock history.
20265 Everywhere else, drag the line at point up."
20268 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20269 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20270 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20271 (call-interactively 'org-timestamp-up)))
20272 (t (call-interactively 'org-drag-line-backward))))
20274 (defun org-shiftmetadown (&optional _arg)
20275 "Drag the line at point down.
20276 In a table, insert an empty row at the current line.
20277 On a clock timestamp, update the value of the timestamp like `S-<down>'
20278 but also adjust the previous clocked item in the clock history.
20279 Everywhere else, drag the line at point down."
20282 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20283 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20284 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20285 (call-interactively 'org-timestamp-down)))
20286 (t (call-interactively 'org-drag-line-forward))))
20288 (defsubst org-hidden-tree-error ()
20290 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20292 (defun org-metaleft (&optional _arg)
20293 "Promote heading, list item at point or move table column left.
20295 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20296 depending on context. With no specific context, calls the Emacs
20297 default `backward-word'. See the individual commands for more
20300 This function runs the hook `org-metaleft-hook' as a first step,
20301 and returns at first non-nil value."
20304 ((run-hook-with-args-until-success 'org-metaleft-hook))
20305 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20306 ((org-with-limited-levels
20307 (or (org-at-heading-p)
20308 (and (org-region-active-p)
20310 (goto-char (region-beginning))
20311 (org-at-heading-p)))))
20312 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20313 (call-interactively 'org-do-promote))
20314 ;; At an inline task.
20315 ((org-at-heading-p)
20316 (call-interactively 'org-inlinetask-promote))
20317 ((or (org-at-item-p)
20318 (and (org-region-active-p)
20320 (goto-char (region-beginning))
20322 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20323 (call-interactively 'org-outdent-item))
20324 (t (call-interactively 'backward-word))))
20326 (defun org-metaright (&optional _arg)
20327 "Demote heading, list item at point or move table column right.
20329 In front of a drawer or a block keyword, indent it correctly.
20331 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20332 `org-indent-drawer' or `org-indent-block' depending on context.
20333 With no specific context, calls the Emacs default `forward-word'.
20334 See the individual commands for more information.
20336 This function runs the hook `org-metaright-hook' as a first step,
20337 and returns at first non-nil value."
20340 ((run-hook-with-args-until-success 'org-metaright-hook))
20341 ((org-at-table-p) (call-interactively 'org-table-move-column))
20342 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20343 ((org-at-block-p) (call-interactively 'org-indent-block))
20344 ((org-with-limited-levels
20345 (or (org-at-heading-p)
20346 (and (org-region-active-p)
20348 (goto-char (region-beginning))
20349 (org-at-heading-p)))))
20350 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20351 (call-interactively 'org-do-demote))
20352 ;; At an inline task.
20353 ((org-at-heading-p)
20354 (call-interactively 'org-inlinetask-demote))
20355 ((or (org-at-item-p)
20356 (and (org-region-active-p)
20358 (goto-char (region-beginning))
20360 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20361 (call-interactively 'org-indent-item))
20362 (t (call-interactively 'forward-word))))
20364 (defun org-check-for-hidden (what)
20365 "Check if there are hidden headlines/items in the current visual line.
20366 WHAT can be either `headlines' or `items'. If the current line is
20367 an outline or item heading and it has a folded subtree below it,
20368 this function returns t, nil otherwise."
20370 ((eq what 'headlines) org-outline-regexp-bol)
20371 ((eq what 'items) (org-item-beginning-re))
20372 (t (error "This should not happen"))))
20376 (unless (org-region-active-p)
20377 (setq beg (point-at-bol))
20378 (beginning-of-line 2)
20379 (while (and (not (eobp)) ;; this is like `next-line'
20380 (get-char-property (1- (point)) 'invisible))
20381 (beginning-of-line 2))
20384 (goto-char (point-at-eol))
20385 (setq end (max end (point)))
20386 (while (re-search-forward re end t)
20387 (when (get-char-property (match-beginning 0) 'invisible)
20391 (defun org-metaup (&optional _arg)
20392 "Move subtree up or move table row up.
20393 Calls `org-move-subtree-up' or `org-table-move-row' or
20394 `org-move-item-up', depending on context. See the individual commands
20395 for more information."
20398 ((run-hook-with-args-until-success 'org-metaup-hook))
20399 ((org-region-active-p)
20400 (let* ((a (min (region-beginning) (region-end)))
20401 (b (1- (max (region-beginning) (region-end))))
20402 (c (save-excursion (goto-char a)
20403 (move-beginning-of-line 0)))
20404 (d (save-excursion (goto-char a)
20405 (move-end-of-line 0) (point))))
20406 (transpose-regions a b c d)
20408 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20409 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20410 ((org-at-item-p) (call-interactively 'org-move-item-up))
20411 (t (org-drag-element-backward))))
20413 (defun org-metadown (&optional _arg)
20414 "Move subtree down or move table row down.
20415 Calls `org-move-subtree-down' or `org-table-move-row' or
20416 `org-move-item-down', depending on context. See the individual
20417 commands for more information."
20420 ((run-hook-with-args-until-success 'org-metadown-hook))
20421 ((org-region-active-p)
20422 (let* ((a (min (region-beginning) (region-end)))
20423 (b (max (region-beginning) (region-end)))
20424 (c (save-excursion (goto-char b)
20425 (move-beginning-of-line 1)))
20426 (d (save-excursion (goto-char b)
20427 (move-end-of-line 1) (1+ (point)))))
20428 (transpose-regions a b c d)
20430 ((org-at-table-p) (call-interactively 'org-table-move-row))
20431 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20432 ((org-at-item-p) (call-interactively 'org-move-item-down))
20433 (t (org-drag-element-forward))))
20435 (defun org-shiftup (&optional arg)
20436 "Increase item in timestamp or increase priority of current headline.
20437 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20438 depending on context. See the individual commands for more information."
20441 ((run-hook-with-args-until-success 'org-shiftup-hook))
20442 ((and org-support-shift-select (org-region-active-p))
20443 (org-call-for-shift-select 'previous-line))
20444 ((org-at-timestamp-p 'lax)
20445 (call-interactively (if org-edit-timestamp-down-means-later
20446 'org-timestamp-down 'org-timestamp-up)))
20447 ((and (not (eq org-support-shift-select 'always))
20448 org-enable-priority-commands
20449 (org-at-heading-p))
20450 (call-interactively 'org-priority-up))
20451 ((and (not org-support-shift-select) (org-at-item-p))
20452 (call-interactively 'org-previous-item))
20453 ((org-clocktable-try-shift 'up arg))
20454 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20455 (org-support-shift-select
20456 (org-call-for-shift-select 'previous-line))
20457 (t (org-shiftselect-error))))
20459 (defun org-shiftdown (&optional arg)
20460 "Decrease item in timestamp or decrease priority of current headline.
20461 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20462 depending on context. See the individual commands for more information."
20465 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20466 ((and org-support-shift-select (org-region-active-p))
20467 (org-call-for-shift-select 'next-line))
20468 ((org-at-timestamp-p 'lax)
20469 (call-interactively (if org-edit-timestamp-down-means-later
20470 'org-timestamp-up 'org-timestamp-down)))
20471 ((and (not (eq org-support-shift-select 'always))
20472 org-enable-priority-commands
20473 (org-at-heading-p))
20474 (call-interactively 'org-priority-down))
20475 ((and (not org-support-shift-select) (org-at-item-p))
20476 (call-interactively 'org-next-item))
20477 ((org-clocktable-try-shift 'down arg))
20478 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20479 (org-support-shift-select
20480 (org-call-for-shift-select 'next-line))
20481 (t (org-shiftselect-error))))
20483 (defun org-shiftright (&optional arg)
20484 "Cycle the thing at point or in the current line, depending on context.
20485 Depending on context, this does one of the following:
20487 - switch a timestamp at point one day into the future
20488 - on a headline, switch to the next TODO keyword.
20489 - on an item, switch entire list to the next bullet type
20490 - on a property line, switch to the next allowed value
20491 - on a clocktable definition line, move time block into the future"
20494 ((run-hook-with-args-until-success 'org-shiftright-hook))
20495 ((and org-support-shift-select (org-region-active-p))
20496 (org-call-for-shift-select 'forward-char))
20497 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20498 ((and (not (eq org-support-shift-select 'always))
20499 (org-at-heading-p))
20500 (let ((org-inhibit-logging
20501 (not org-treat-S-cursor-todo-selection-as-state-change))
20502 (org-inhibit-blocking
20503 (not org-treat-S-cursor-todo-selection-as-state-change)))
20504 (org-call-with-arg 'org-todo 'right)))
20505 ((or (and org-support-shift-select
20506 (not (eq org-support-shift-select 'always))
20507 (org-at-item-bullet-p))
20508 (and (not org-support-shift-select) (org-at-item-p)))
20509 (org-call-with-arg 'org-cycle-list-bullet nil))
20510 ((and (not (eq org-support-shift-select 'always))
20511 (org-at-property-p))
20512 (call-interactively 'org-property-next-allowed-value))
20513 ((org-clocktable-try-shift 'right arg))
20514 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20515 (org-support-shift-select
20516 (org-call-for-shift-select 'forward-char))
20517 (t (org-shiftselect-error))))
20519 (defun org-shiftleft (&optional arg)
20520 "Cycle the thing at point or in the current line, depending on context.
20521 Depending on context, this does one of the following:
20523 - switch a timestamp at point one day into the past
20524 - on a headline, switch to the previous TODO keyword.
20525 - on an item, switch entire list to the previous bullet type
20526 - on a property line, switch to the previous allowed value
20527 - on a clocktable definition line, move time block into the past"
20530 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20531 ((and org-support-shift-select (org-region-active-p))
20532 (org-call-for-shift-select 'backward-char))
20533 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20534 ((and (not (eq org-support-shift-select 'always))
20535 (org-at-heading-p))
20536 (let ((org-inhibit-logging
20537 (not org-treat-S-cursor-todo-selection-as-state-change))
20538 (org-inhibit-blocking
20539 (not org-treat-S-cursor-todo-selection-as-state-change)))
20540 (org-call-with-arg 'org-todo 'left)))
20541 ((or (and org-support-shift-select
20542 (not (eq org-support-shift-select 'always))
20543 (org-at-item-bullet-p))
20544 (and (not org-support-shift-select) (org-at-item-p)))
20545 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20546 ((and (not (eq org-support-shift-select 'always))
20547 (org-at-property-p))
20548 (call-interactively 'org-property-previous-allowed-value))
20549 ((org-clocktable-try-shift 'left arg))
20550 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20551 (org-support-shift-select
20552 (org-call-for-shift-select 'backward-char))
20553 (t (org-shiftselect-error))))
20555 (defun org-shiftcontrolright ()
20556 "Switch to next TODO set."
20559 ((and org-support-shift-select (org-region-active-p))
20560 (org-call-for-shift-select 'forward-word))
20561 ((and (not (eq org-support-shift-select 'always))
20562 (org-at-heading-p))
20563 (org-call-with-arg 'org-todo 'nextset))
20564 (org-support-shift-select
20565 (org-call-for-shift-select 'forward-word))
20566 (t (org-shiftselect-error))))
20568 (defun org-shiftcontrolleft ()
20569 "Switch to previous TODO set."
20572 ((and org-support-shift-select (org-region-active-p))
20573 (org-call-for-shift-select 'backward-word))
20574 ((and (not (eq org-support-shift-select 'always))
20575 (org-at-heading-p))
20576 (org-call-with-arg 'org-todo 'previousset))
20577 (org-support-shift-select
20578 (org-call-for-shift-select 'backward-word))
20579 (t (org-shiftselect-error))))
20581 (defun org-shiftcontrolup (&optional n)
20582 "Change timestamps synchronously up in CLOCK log lines.
20583 Optional argument N tells to change by that many units."
20585 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20586 (let (org-support-shift-select)
20587 (org-clock-timestamps-up n))
20588 (user-error "Not at a clock log")))
20590 (defun org-shiftcontroldown (&optional n)
20591 "Change timestamps synchronously down in CLOCK log lines.
20592 Optional argument N tells to change by that many units."
20594 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20595 (let (org-support-shift-select)
20596 (org-clock-timestamps-down n))
20597 (user-error "Not at a clock log")))
20599 (defun org-increase-number-at-point (&optional inc)
20600 "Increment the number at point.
20601 With an optional prefix numeric argument INC, increment using
20602 this numeric value."
20604 (if (not (number-at-point))
20605 (user-error "Not on a number")
20606 (unless inc (setq inc 1))
20607 (let ((pos (point))
20608 (beg (skip-chars-backward "-+^/*0-9eE."))
20609 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20610 (setq nap (buffer-substring-no-properties
20611 (+ pos beg) (+ pos beg end)))
20612 (delete-region (+ pos beg) (+ pos beg end))
20613 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20614 (when (org-at-table-p)
20616 (org-table-end-of-field 1))))
20618 (defun org-decrease-number-at-point (&optional inc)
20619 "Decrement the number at point.
20620 With an optional prefix numeric argument INC, decrement using
20621 this numeric value."
20623 (org-increase-number-at-point (- (or inc 1))))
20625 (defun org-ctrl-c-ret ()
20626 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20629 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20630 (t (call-interactively 'org-insert-heading))))
20632 (defun org-find-visible ()
20634 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20635 (get-char-property s 'invisible)))
20637 (defun org-find-invisible ()
20639 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20640 (not (get-char-property s 'invisible))))
20643 (defun org-copy-visible (beg end)
20644 "Copy the visible parts of the region."
20647 (while (/= beg end)
20648 (when (get-char-property beg 'invisible)
20649 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20650 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20651 (setq result (concat result (buffer-substring beg next)))
20653 (kill-new result)))
20655 (defun org-copy-special ()
20656 "Copy region in table or copy current subtree.
20657 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20658 context. See the individual commands for more information."
20660 (call-interactively
20661 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20663 (defun org-cut-special ()
20664 "Cut region in table or cut current subtree.
20665 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20666 context. See the individual commands for more information."
20668 (call-interactively
20669 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20671 (defun org-paste-special (arg)
20672 "Paste rectangular region into table, or past subtree relative to level.
20673 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20674 See the individual commands for more information."
20676 (if (org-at-table-p)
20677 (org-table-paste-rectangle)
20678 (org-paste-subtree arg)))
20680 (defun org-edit-special (&optional arg)
20681 "Call a special editor for the element at point.
20682 When at a table, call the formula editor with `org-table-edit-formulas'.
20683 When in a source code block, call `org-edit-src-code'.
20684 When in a fixed-width region, call `org-edit-fixed-width-region'.
20685 When in an export block, call `org-edit-export-block'.
20686 When in a LaTeX environment, call `org-edit-latex-environment'.
20687 When at an #+INCLUDE keyword, visit the included file.
20688 When at a footnote reference, call `org-edit-footnote-reference'
20689 On a link, call `ffap' to visit the link at point.
20690 Otherwise, return a user error."
20692 (let ((element (org-element-at-point)))
20693 (barf-if-buffer-read-only)
20694 (pcase (org-element-type element)
20696 (if (not arg) (org-edit-src-code)
20697 (let* ((info (org-babel-get-src-block-info))
20698 (lang (nth 0 info))
20699 (params (nth 2 info))
20700 (session (cdr (assq :session params))))
20701 (if (not session) (org-edit-src-code)
20702 ;; At a src-block with a session and function called with
20703 ;; an ARG: switch to the buffer related to the inferior
20706 (funcall (intern (concat "org-babel-prep-session:" lang))
20707 session params))))))
20709 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20710 (org-open-link-from-string
20713 (let ((value (org-element-property :value element)))
20714 (cond ((org-file-url-p value)
20715 (user-error "The file is specified as a URL, cannot be edited"))
20716 ((not (org-string-nw-p value))
20717 (user-error "No file to edit"))
20718 ((string-match "\\`\"\\(.*?\\)\"" value)
20719 (match-string 1 value))
20720 ((string-match "\\`[^ \t\"]\\S-*" value)
20721 (match-string 0 value))
20722 (t (user-error "No valid file specified")))))))
20723 (user-error "No special environment to edit here")))
20725 (if (eq (org-element-property :type element) 'table.el)
20726 (org-edit-table.el)
20727 (call-interactively 'org-table-edit-formulas)))
20728 ;; Only Org tables contain `table-row' type elements.
20729 (`table-row (call-interactively 'org-table-edit-formulas))
20730 (`example-block (org-edit-src-code))
20731 (`export-block (org-edit-export-block))
20732 (`fixed-width (org-edit-fixed-width-region))
20733 (`latex-environment (org-edit-latex-environment))
20735 ;; No notable element at point. Though, we may be at a link or
20736 ;; a footnote reference, which are objects. Thus, scan deeper.
20737 (let ((context (org-element-context element)))
20738 (pcase (org-element-type context)
20739 (`footnote-reference (org-edit-footnote-reference))
20740 (`inline-src-block (org-edit-inline-src-code))
20741 (`link (call-interactively #'ffap))
20742 (_ (user-error "No special environment to edit here"))))))))
20744 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20745 (defun org-ctrl-c-ctrl-c (&optional arg)
20746 "Set tags in headline, or update according to changed information at point.
20748 This command does many different things, depending on context:
20750 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20751 this is what we do.
20753 - If the cursor is on a statistics cookie, update it.
20755 - If the cursor is in a headline, prompt for tags and insert them
20756 into the current line, aligned to `org-tags-column'. When called
20757 with prefix arg, realign all tags in the current buffer.
20759 - If the cursor is in one of the special #+KEYWORD lines, this
20760 triggers scanning the buffer for these lines and updating the
20763 - If the cursor is inside a table, realign the table. This command
20764 works even if the automatic table editor has been turned off.
20766 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20769 - If the cursor is at a footnote reference or definition, jump to
20770 the corresponding definition or references, respectively.
20772 - If the cursor is a the beginning of a dynamic block, update it.
20774 - If the current buffer is a capture buffer, close note and file it.
20776 - If the cursor is on a <<<target>>>, update radio targets and
20777 corresponding links in this buffer.
20779 - If the cursor is on a numbered item in a plain list, renumber the
20782 - If the cursor is on a checkbox, toggle it.
20784 - If the cursor is on a code block, evaluate it. The variable
20785 `org-confirm-babel-evaluate' can be used to control prompting
20786 before code block evaluation, by default every code block
20787 evaluation requires confirmation. Code block evaluation can be
20788 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20791 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20792 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20793 (org-remove-occur-highlights)
20794 (message "Temporary highlights/overlays removed from current buffer"))
20795 ((and (local-variable-p 'org-finish-function)
20796 (fboundp org-finish-function))
20797 (funcall org-finish-function))
20798 ((org-babel-hash-at-point))
20799 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20802 (org-element-lineage
20803 (org-element-context)
20804 ;; Limit to supported contexts.
20805 '(babel-call clock dynamic-block footnote-definition
20806 footnote-reference inline-babel-call inline-src-block
20807 inlinetask item keyword node-property paragraph
20808 plain-list planning property-drawer radio-target
20809 src-block statistics-cookie table table-cell table-row
20812 (type (org-element-type context)))
20813 ;; For convenience: at the first line of a paragraph on the same
20814 ;; line as an item, apply function on that item instead.
20815 (when (eq type 'paragraph)
20816 (let ((parent (org-element-property :parent context)))
20817 (when (and (eq (org-element-type parent) 'item)
20818 (= (line-beginning-position)
20819 (org-element-property :begin parent)))
20820 (setq context parent)
20821 (setq type 'item))))
20822 ;; Act according to type of element or object at point.
20824 ;; Do nothing on a blank line, except if it is contained in
20825 ;; a src block. Hence, we first check if point is in such
20826 ;; a block and then if it is at a blank line.
20828 ((or `inline-src-block `src-block)
20829 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20830 (org-babel-eval-wipe-error-buffer)
20831 (org-babel-execute-src-block
20832 current-prefix-arg (org-babel-get-src-block-info nil context))))
20833 ((guard (org-match-line "[ \t]*$"))
20834 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20836 (substitute-command-keys
20837 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20838 ((or `babel-call `inline-babel-call)
20839 (let ((info (org-babel-lob-get-info context)))
20840 (when info (org-babel-execute-src-block nil info))))
20841 (`clock (org-clock-update-time-maybe))
20844 (goto-char (org-element-property :post-affiliated context))
20845 (org-update-dblock)))
20846 (`footnote-definition
20847 (goto-char (org-element-property :post-affiliated context))
20848 (call-interactively 'org-footnote-action))
20849 (`footnote-reference (call-interactively #'org-footnote-action))
20850 ((or `headline `inlinetask)
20851 (save-excursion (goto-char (org-element-property :begin context))
20852 (call-interactively #'org-set-tags)))
20854 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20855 ;; unconditionally, whereas `C-u' will toggle its presence.
20856 ;; Without a universal argument, if the item has a checkbox,
20857 ;; toggle it. Otherwise repair the list.
20858 (let* ((box (org-element-property :checkbox context))
20859 (struct (org-element-property :structure context))
20860 (old-struct (copy-tree struct))
20861 (parents (org-list-parents-alist struct))
20862 (prevs (org-list-prevs-alist struct))
20863 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20864 (org-list-set-checkbox
20865 (org-element-property :begin context) struct
20866 (cond ((equal arg '(16)) "[-]")
20867 ((and (not box) (equal arg '(4))) "[ ]")
20868 ((or (not box) (equal arg '(4))) nil)
20869 ((eq box 'on) "[ ]")
20871 ;; Mimic `org-list-write-struct' but with grabbing a return
20872 ;; value from `org-list-struct-fix-box'.
20873 (org-list-struct-fix-ind struct parents 2)
20874 (org-list-struct-fix-item-end struct)
20875 (org-list-struct-fix-bul struct prevs)
20876 (org-list-struct-fix-ind struct parents)
20878 (org-list-struct-fix-box struct parents prevs orderedp)))
20879 (if (and box (equal struct old-struct))
20880 (if (equal arg '(16))
20881 (message "Checkboxes already reset")
20882 (user-error "Cannot toggle this checkbox: %s"
20884 "all subitems checked"
20885 "unchecked subitems")))
20886 (org-list-struct-apply-struct struct old-struct)
20887 (org-update-checkbox-count-maybe))
20889 (message "Checkboxes were removed due to empty box at line %d"
20890 (org-current-line block-item))))))
20892 (let ((org-inhibit-startup-visibility-stuff t)
20893 (org-startup-align-all-tables nil))
20894 (when (boundp 'org-table-coordinate-overlays)
20895 (mapc #'delete-overlay org-table-coordinate-overlays)
20896 (setq org-table-coordinate-overlays nil))
20897 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20898 (message "Local setup has been refreshed"))
20900 ;; At a plain list, with a double C-u argument, set
20901 ;; checkboxes of each item to "[-]", whereas a single one
20902 ;; will toggle their presence according to the state of the
20903 ;; first item in the list. Without an argument, repair the
20905 (let* ((begin (org-element-property :contents-begin context))
20906 (beginm (move-marker (make-marker) begin))
20907 (struct (org-element-property :structure context))
20908 (old-struct (copy-tree struct))
20909 (first-box (save-excursion
20911 (looking-at org-list-full-item-re)
20912 (match-string-no-properties 3)))
20913 (new-box (cond ((equal arg '(16)) "[-]")
20914 ((equal arg '(4)) (unless first-box "[ ]"))
20915 ((equal first-box "[X]") "[ ]")
20920 (org-list-get-all-items
20921 begin struct (org-list-prevs-alist struct)))
20922 (org-list-set-checkbox pos struct new-box)))
20923 ((and first-box (eq (point) begin))
20924 ;; For convenience, when point is at bol on the first
20925 ;; item of the list and no argument is provided, simply
20926 ;; toggle checkbox of that item, if any.
20927 (org-list-set-checkbox begin struct new-box)))
20928 (org-list-write-struct
20929 struct (org-list-parents-alist struct) old-struct)
20930 (org-update-checkbox-count-maybe)
20931 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20932 ((or `property-drawer `node-property)
20933 (call-interactively #'org-property-action))
20935 (call-interactively #'org-update-radio-target-regexp))
20936 (`statistics-cookie
20937 (call-interactively #'org-update-statistics-cookies))
20938 ((or `table `table-cell `table-row)
20939 ;; At a table, recalculate every field and align it. Also
20940 ;; send the table if necessary. If the table has
20941 ;; a `table.el' type, just give up. At a table row or cell,
20942 ;; maybe recalculate line but always align table.
20943 (if (eq (org-element-property :type context) 'table.el)
20944 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20945 Use `\\[org-edit-special]' to edit table.el tables"))
20946 (if (or (eq type 'table)
20947 ;; Check if point is at a TBLFM line.
20948 (and (eq type 'table-row)
20949 (= (point) (org-element-property :end context))))
20951 (if (org-at-TBLFM-p)
20952 (progn (require 'org-table)
20953 (org-table-calc-current-TBLFM))
20954 (goto-char (org-element-property :contents-begin context))
20955 (org-call-with-arg 'org-table-recalculate (or arg t))
20956 (orgtbl-send-table 'maybe)))
20957 (org-table-maybe-eval-formula)
20958 (cond (arg (call-interactively #'org-table-recalculate))
20959 ((org-table-maybe-recalculate-line))
20960 (t (org-table-align))))))
20961 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20962 (org-timestamp-change 0 'day))
20963 ((and `nil (guard (org-at-heading-p)))
20964 ;; When point is on an unsupported object type, we can miss
20965 ;; the fact that it also is at a heading. Handle it here.
20966 (call-interactively #'org-set-tags))
20968 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20971 (substitute-command-keys
20972 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20974 (defun org-mode-restart ()
20976 (let ((indent-status (bound-and-true-p org-indent-mode)))
20977 (funcall major-mode)
20978 (hack-local-variables)
20979 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20980 (org-indent-mode -1))
20981 (org-reset-file-cache))
20982 (message "%s restarted" major-mode))
20984 (defun org-kill-note-or-show-branches ()
20985 "Abort storing current note, or call `outline-show-branches'."
20987 (if (not org-finish-function)
20989 (outline-hide-subtree)
20990 (call-interactively 'outline-show-branches))
20991 (let ((org-note-abort t))
20992 (funcall org-finish-function))))
20994 (defun org-delete-indentation (&optional arg)
20995 "Join current line to previous and fix whitespace at join.
20997 If previous line is a headline add to headline title. Otherwise
20998 the function calls `delete-indentation'.
21000 With a non-nil optional argument, join it to the following one."
21002 (if (save-excursion
21003 (beginning-of-line (if arg 1 0))
21004 (let ((case-fold-search nil))
21005 (looking-at org-complex-heading-regexp)))
21007 (let ((tags-column (when (match-beginning 5)
21008 (save-excursion (goto-char (match-beginning 5))
21009 (current-column))))
21010 (string (concat " " (progn (when arg (forward-line 1))
21011 (org-trim (delete-and-extract-region
21012 (line-beginning-position)
21013 (line-end-position)))))))
21014 (unless (bobp) (delete-region (point) (1- (point))))
21015 (goto-char (or (match-end 4)
21016 (match-beginning 5)
21018 (skip-chars-backward " \t")
21019 (save-excursion (insert string))
21020 ;; Adjust alignment of tags.
21022 ((not tags-column)) ;no tags
21023 (org-auto-align-tags (org-set-tags nil t))
21024 (t (org--align-tags-here tags-column)))) ;preserve tags column
21025 (delete-indentation arg)))
21027 (defun org-open-line (n)
21028 "Insert a new row in tables, call `open-line' elsewhere.
21029 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21030 As a special case, when a document starts with a table, allow to
21031 call `open-line' on the very first character."
21033 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21034 (org-table-insert-row)
21037 (defun org-return (&optional indent)
21038 "Goto next table row or insert a newline.
21040 Calls `org-table-next-row' or `newline', depending on context.
21042 When optional INDENT argument is non-nil, call
21043 `newline-and-indent' instead of `newline'.
21045 When `org-return-follows-link' is non-nil and point is on
21046 a timestamp or a link, call `org-open-at-point'. However, it
21047 will not happen if point is in a table or on a \"dead\"
21048 object (e.g., within a comment). In these case, you need to use
21049 `org-open-at-point' directly."
21051 (let ((context (if org-return-follows-link (org-element-context)
21052 (org-element-at-point))))
21054 ;; In a table, call `org-table-next-row'. However, before first
21055 ;; column or after last one, split the table.
21056 ((or (and (eq (org-element-type context) 'table)
21057 (>= (point) (org-element-property :contents-begin context))
21058 (< (point) (org-element-property :contents-end context)))
21059 (org-element-lineage context '(table-row table-cell) t))
21060 (if (or (looking-at-p "[ \t]*$")
21061 (save-excursion (skip-chars-backward " \t") (bolp)))
21063 (org-table-justify-field-maybe)
21064 (call-interactively #'org-table-next-row)))
21065 ;; On a link or a timestamp, call `org-open-at-point' if
21066 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21067 ;; locations, e.g., in a comment, as `org-open-at-point'.
21068 ((and org-return-follows-link
21069 (or (org-in-regexp org-ts-regexp-both nil t)
21070 (org-in-regexp org-tsr-regexp-both nil t)
21071 (org-in-regexp org-any-link-re nil t)))
21072 (call-interactively #'org-open-at-point))
21073 ;; Insert newline in heading, but preserve tags.
21075 (save-excursion (beginning-of-line)
21076 (let ((case-fold-search nil))
21077 (looking-at org-complex-heading-regexp))))
21078 ;; At headline. Split line. However, if point is on keyword,
21079 ;; priority cookie or tags, do not break any of them: add
21080 ;; a newline after the headline instead.
21081 (let ((tags-column (and (match-beginning 5)
21082 (save-excursion (goto-char (match-beginning 5))
21083 (current-column))))
21085 (when (and (match-end 4) (org-point-in-group (point) 4))
21086 (delete-and-extract-region (point) (match-end 4)))))
21087 ;; Adjust tag alignment.
21089 ((not (and tags-column string)))
21090 (org-auto-align-tags (org-set-tags nil t))
21091 (t (org--align-tags-here tags-column))) ;preserve tags column
21094 (if indent (newline-and-indent) (newline))
21095 (when string (save-excursion (insert (org-trim string))))))
21096 ;; In a list, make sure indenting keeps trailing text within.
21099 (org-element-lineage context '(item)))
21100 (let ((trailing-data
21101 (delete-and-extract-region (point) (line-end-position))))
21102 (newline-and-indent)
21103 (save-excursion (insert trailing-data))))
21104 (t (if indent (newline-and-indent) (newline))))))
21106 (defun org-return-indent ()
21107 "Goto next table row or insert a newline and indent.
21108 Calls `org-table-next-row' or `newline-and-indent', depending on
21109 context. See the individual commands for more information."
21113 (defun org-ctrl-c-star ()
21114 "Compute table, or change heading status of lines.
21115 Calls `org-table-recalculate' or `org-toggle-heading',
21116 depending on context."
21120 (call-interactively 'org-table-recalculate))
21122 ;; Convert all lines in region to list items
21123 (call-interactively 'org-toggle-heading))))
21125 (defun org-ctrl-c-minus ()
21126 "Insert separator line in table or modify bullet status of line.
21127 Also turns a plain line or a region of lines into list items.
21128 Calls `org-table-insert-hline', `org-toggle-item', or
21129 `org-cycle-list-bullet', depending on context."
21133 (call-interactively 'org-table-insert-hline))
21134 ((org-region-active-p)
21135 (call-interactively 'org-toggle-item))
21137 (call-interactively 'org-cycle-list-bullet))
21139 (call-interactively 'org-toggle-item))))
21141 (defun org-toggle-heading (&optional nstars)
21142 "Convert headings to normal text, or items or text to headings.
21143 If there is no active region, only convert the current line.
21145 With a `\\[universal-argument]' prefix, convert the whole list at
21146 point into heading.
21150 - If the first non blank line is a headline, remove the stars
21151 from all headlines in the region.
21153 - If it is a normal line, turn each and every normal line (i.e.,
21154 not an heading or an item) in the region into headings. If you
21155 want to convert only the first line of this region, use one
21156 universal prefix argument.
21158 - If it is a plain list item, turn all plain list items into headings.
21160 When converting a line into a heading, the number of stars is chosen
21161 such that the lines become children of the current entry. However,
21162 when a numeric prefix argument is given, its value determines the
21163 number of stars to add."
21167 ;; Return beginning of first non-blank line, starting from
21172 (while (org-at-comment-p) (forward-line))
21173 (skip-chars-forward " \r\t\n")
21176 ;; Determine boundaries of changes. If a universal prefix has
21177 ;; been given, put the list in a region. If region ends at a bol,
21178 ;; do not consider the last line to be in the region.
21180 (when (and current-prefix-arg (org-at-item-p))
21181 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21182 (org-mark-element))
21184 (if (org-region-active-p)
21185 (setq beg (funcall skip-blanks (region-beginning))
21186 end (copy-marker (save-excursion
21187 (goto-char (region-end))
21188 (if (bolp) (point) (point-at-eol)))))
21189 (setq beg (funcall skip-blanks (point-at-bol))
21190 end (copy-marker (point-at-eol))))
21191 ;; Ensure inline tasks don't count as headings.
21192 (org-with-limited-levels
21196 ;; Case 1. Started at an heading: de-star headings.
21197 ((org-at-heading-p)
21198 (while (< (point) end)
21199 (when (org-at-heading-p t)
21200 (looking-at org-outline-regexp) (replace-match "")
21203 ;; Case 2. Started at an item: change items into headlines.
21204 ;; One star will be added by `org-list-to-subtree'.
21206 (while (< (point) end)
21207 (when (org-at-item-p)
21208 ;; Pay attention to cases when region ends before list.
21209 (let* ((struct (org-list-struct))
21211 (min (org-list-get-bottom-point struct) (1+ end))))
21213 (narrow-to-region (point) list-end)
21214 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21217 ;; Case 3. Started at normal text: make every line an heading,
21218 ;; skipping headlines and items.
21221 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21223 (cond (nstars "") ; stars from prefix only
21224 ((equal stars "") "*") ; before first heading
21225 (org-odd-levels-only "**") ; inside heading, odd
21226 (t "*"))) ; inside heading, oddeven
21227 (rpl (concat stars add-stars " "))
21228 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21229 (while (< (point) (if (equal nstars '(4)) lend end))
21230 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21231 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21232 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21233 (forward-line)))))))
21234 (unless toggled (message "Cannot toggle heading from here"))))
21236 (defun org-meta-return (&optional arg)
21237 "Insert a new heading or wrap a region in a table.
21238 Calls `org-insert-heading', `org-insert-item' or
21239 `org-table-wrap-region', depending on context. When called with
21240 an argument, unconditionally call `org-insert-heading'."
21242 (org-check-before-invisible-edit 'insert)
21243 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21244 (call-interactively (cond (arg #'org-insert-heading)
21245 ((org-at-table-p) #'org-table-wrap-region)
21246 ((org-in-item-p) #'org-insert-item)
21247 (t #'org-insert-heading)))))
21251 (defsubst org-in-subtree-not-table-p ()
21252 "Are we in a subtree and not in a table?"
21253 (and (not (org-before-first-heading-p))
21254 (not (org-at-table-p))))
21256 ;; Define the Org mode menus
21257 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21259 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21260 ["Next Field" org-cycle (org-at-table-p)]
21261 ["Previous Field" org-shifttab (org-at-table-p)]
21262 ["Next Row" org-return (org-at-table-p)]
21264 ["Blank Field" org-table-blank-field (org-at-table-p)]
21265 ["Edit Field" org-table-edit-field (org-at-table-p)]
21266 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21269 ["Move Column Left" org-metaleft (org-at-table-p)]
21270 ["Move Column Right" org-metaright (org-at-table-p)]
21271 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21272 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21274 ["Move Row Up" org-metaup (org-at-table-p)]
21275 ["Move Row Down" org-metadown (org-at-table-p)]
21276 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21277 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21278 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21280 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21282 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21283 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21284 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21285 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21288 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21289 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21290 ["Edit Formulas" org-edit-special (org-at-table-p)]
21292 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21293 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21294 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21296 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21298 ["Sum Column/Rectangle" org-table-sum
21299 (or (org-at-table-p) (org-region-active-p))]
21300 ["Which Column?" org-table-current-column (org-at-table-p)])
21302 org-table-toggle-formula-debugger
21303 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21304 ["Show Col/Row Numbers"
21305 org-table-toggle-coordinate-overlays
21307 :selected (bound-and-true-p org-table-overlay-coordinates)]
21309 ["Create" org-table-create (not (org-at-table-p))]
21310 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21311 ["Import from File" org-table-import (not (org-at-table-p))]
21312 ["Export to File" org-table-export (org-at-table-p)]
21314 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21317 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21318 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21320 (easy-menu-define org-org-menu org-mode-map "Org menu"
21323 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21324 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21325 ["Sparse Tree..." org-sparse-tree t]
21326 ["Reveal Context" org-reveal t]
21327 ["Show All" outline-show-all t]
21329 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21331 ["New Heading" org-insert-heading t]
21332 ("Navigate Headings"
21333 ["Up" outline-up-heading t]
21334 ["Next" outline-next-visible-heading t]
21335 ["Previous" outline-previous-visible-heading t]
21336 ["Next Same Level" outline-forward-same-level t]
21337 ["Previous Same Level" outline-backward-same-level t]
21339 ["Jump" org-goto t])
21341 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21343 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21344 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21346 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21347 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21348 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21350 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21352 ["Copy visible text" org-copy-visible t]
21354 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21355 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21356 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21357 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21359 ["Sort Region/Children" org-sort t]
21361 ["Convert to odd levels" org-convert-to-odd-levels t]
21362 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21364 ["Emphasis..." org-emphasize t]
21365 ["Edit Source Example" org-edit-special t]
21367 ["Footnote new/jump" org-footnote-action t]
21368 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21370 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21372 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21373 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21374 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21378 ["Store Link (Global)" org-store-link t]
21379 ["Find existing link to here" org-occur-link-in-agenda-files t]
21380 ["Insert Link" org-insert-link t]
21381 ["Follow Link" org-open-at-point t]
21383 ["Next link" org-next-link t]
21384 ["Previous link" org-previous-link t]
21386 ["Descriptive Links"
21387 org-toggle-link-display
21389 :selected org-descriptive-links
21392 org-toggle-link-display
21394 :selected (not org-descriptive-links)])
21397 ["TODO/DONE/-" org-todo t]
21399 ["Next keyword" org-shiftright (org-at-heading-p)]
21400 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21401 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21402 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21403 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21404 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21405 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
21407 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21408 :selected org-enforce-todo-dependencies :style toggle :active t]
21409 "Settings for tree at point"
21410 ["Do Children sequentially" org-toggle-ordered-property :style radio
21411 :selected (org-entry-get nil "ORDERED")
21412 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21413 ["Do Children parallel" org-toggle-ordered-property :style radio
21414 :selected (not (org-entry-get nil "ORDERED"))
21415 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21417 ["Set Priority" org-priority t]
21418 ["Priority Up" org-shiftup t]
21419 ["Priority Down" org-shiftdown t]
21421 ["Get news from all feeds" org-feed-update-all t]
21422 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21423 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21424 ("TAGS and Properties"
21425 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21426 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21428 ["Set property" org-set-property (not (org-before-first-heading-p))]
21429 ["Column view of properties" org-columns t]
21430 ["Insert Column View DBlock" org-columns-insert-dblock t])
21431 ("Dates and Scheduling"
21432 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21433 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21435 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21436 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21437 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21438 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21439 ["Compute Time Range" org-evaluate-time-range t]
21440 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21441 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21443 ["Custom time format" org-toggle-time-stamp-overlays
21444 :style radio :selected org-display-custom-times]
21446 ["Goto Calendar" org-goto-calendar t]
21447 ["Date from Calendar" org-date-from-calendar t]
21449 ["Start/Restart Timer" org-timer-start t]
21450 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21451 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21452 ["Insert Timer String" org-timer t]
21453 ["Insert Timer Item" org-timer-item t])
21455 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21456 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21457 ["Clock out" org-clock-out t]
21458 ["Clock cancel" org-clock-cancel t]
21460 ["Mark as default task" org-clock-mark-default-task t]
21461 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21462 ["Goto running clock" org-clock-goto t]
21464 ["Display times" org-clock-display t]
21465 ["Create clock table" org-clock-report t]
21467 ["Record DONE time"
21468 (progn (setq org-log-done (not org-log-done))
21469 (message "Switching to %s will %s record a timestamp"
21470 (car org-done-keywords)
21471 (if org-log-done "automatically" "not")))
21472 :style toggle :selected org-log-done])
21474 ["Agenda Command..." org-agenda t]
21475 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21476 ("File List for Agenda")
21477 ("Special views current file"
21478 ["TODO Tree" org-show-todo-tree t]
21479 ["Check Deadlines" org-check-deadlines t]
21480 ["Tags/Property tree" org-match-sparse-tree t])
21482 ["Export/Publish..." org-export-dispatch t]
21484 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
21485 :style toggle :selected org-cdlatex-mode]
21486 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21487 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21488 ["Modify math symbol" org-cdlatex-math-modify
21489 (org-inside-LaTeX-fragment-p)]
21490 ["Insert citation" org-reftex-citation t])
21493 ["Push Files and Views" org-mobile-push t]
21494 ["Get Captured and Flagged" org-mobile-pull t]
21495 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
21497 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21500 ["Show Version" org-version t]
21501 ["Info Documentation" org-info t])
21503 ["Browse Org Group" org-customize t]
21505 ["Expand This Menu" org-create-customize-menu
21506 (fboundp 'customize-menu-create)])
21507 ["Send bug report" org-submit-bug-report t]
21510 ["Refresh setup current buffer" org-mode-restart t]
21511 ["Reload Org (after update)" org-reload t]
21512 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21515 (defun org-info (&optional node)
21516 "Read documentation for Org in the info system.
21517 With optional NODE, go directly to that node."
21519 (info (format "(org)%s" (or node ""))))
21522 (defun org-submit-bug-report ()
21523 "Submit a bug report on Org via mail.
21525 Don't hesitate to report any problems or inaccurate documentation.
21527 If you don't have setup sending mail from (X)Emacs, please copy the
21528 output buffer into your mail program, as it gives us important
21529 information about your Org version and configuration."
21531 (require 'reporter)
21532 (defvar reporter-prompt-for-summary-p)
21533 (org-load-modules-maybe)
21534 (org-require-autoloaded-modules)
21535 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21536 (reporter-submit-bug-report
21537 "emacs-orgmode@gnu.org"
21538 (org-version nil 'full)
21540 (save-window-excursion
21541 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21542 (delete-other-windows)
21544 (insert "You are about to submit a bug report to the Org mailing list.
21546 We would like to add your full Org and Outline configuration to the
21547 bug report. This greatly simplifies the work of the maintainer and
21548 other experts on the mailing list.
21550 HOWEVER, some variables you have customized may contain private
21551 information. The names of customers, colleagues, or friends, might
21552 appear in the form of file names, tags, todo states, or search strings.
21553 If you answer yes to the prompt, you might want to check and remove
21554 such private information before sending the email.")
21555 (add-text-properties (point-min) (point-max) '(face org-warning))
21556 (when (yes-or-no-p "Include your Org configuration ")
21560 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21561 (or (and (symbol-value v)
21562 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21564 (get v 'custom-type) (get v 'standard-value)
21565 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21567 (kill-buffer (get-buffer "*Warn about privacy*"))
21570 "Remember to cover the basics, that is, what you expected to happen and
21571 what in fact did happen. You don't know how to make a good report? See
21573 http://orgmode.org/manual/Feedback.html#Feedback
21575 Your bug report will be posted to the Org mailing list.
21576 ------------------------------------------------------------------------")
21578 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21579 (replace-match "\\1Bug: \\3 [\\2]")))))
21582 (defun org-install-agenda-files-menu ()
21583 (let ((bl (buffer-list)))
21586 (set-buffer (pop bl))
21587 (when (derived-mode-p 'org-mode) (setq bl nil)))
21588 (when (derived-mode-p 'org-mode)
21590 '("Org") "File List for Agenda"
21593 ["Edit File List" (org-edit-agenda-file-list) t]
21594 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21595 ["Remove Current File from List" org-remove-file t]
21596 ["Cycle through agenda files" org-cycle-agenda-files t]
21597 ["Occur in all agenda files" org-occur-in-agenda-files t]
21599 (mapcar 'org-file-menu-entry
21600 ;; Prevent initialization from failing.
21601 (ignore-errors (org-agenda-files t)))))))))
21605 (defun org-require-autoloaded-modules ()
21608 '(org-agenda org-archive org-attach org-clock org-colview org-id
21609 org-table org-timer)))
21612 (defun org-reload (&optional uncompiled)
21613 "Reload all org lisp files.
21614 With prefix arg UNCOMPILED, load the uncompiled versions."
21616 (require 'loadhist)
21617 (let* ((org-dir (org-find-library-dir "org"))
21618 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21619 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21620 (remove-re (format "\\`%s\\'"
21621 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21622 (feats (delete-dups
21623 (mapcar 'file-name-sans-extension
21624 (mapcar 'file-name-nondirectory
21626 (mapcar 'feature-file
21633 (if (and (string-match feature-re f)
21634 (not (string-match remove-re f)))
21638 (list "org-version" "org")))
21639 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21640 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21641 load-uncore load-misses)
21644 (mapcar (lambda (f)
21645 (or (org-load-noerror-mustsuffix (concat org-dir f))
21646 (and (string= org-dir contrib-dir)
21647 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21648 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21649 (add-to-list 'load-uncore f 'append)
21654 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21655 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21657 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21658 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21659 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21662 (defun org-customize ()
21663 "Call the customize function with org as argument."
21665 (org-load-modules-maybe)
21666 (org-require-autoloaded-modules)
21667 (customize-browse 'org))
21669 (defun org-create-customize-menu ()
21670 "Create a full customization menu for Org mode, insert it into the menu."
21672 (org-load-modules-maybe)
21673 (org-require-autoloaded-modules)
21674 (if (fboundp 'customize-menu-create)
21677 '("Org") "Customize"
21678 `(["Browse Org group" org-customize t]
21680 ,(customize-menu-create 'org)
21681 ["Set" Custom-set t]
21682 ["Save" Custom-save t]
21683 ["Reset to Current" Custom-reset-current t]
21684 ["Reset to Saved" Custom-reset-saved t]
21685 ["Reset to Standard Settings" Custom-reset-standard t]))
21686 (message "\"Org\"-menu now contains full customization menu"))
21687 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21689 ;;;; Miscellaneous stuff
21691 ;;; Generally useful functions
21693 (defun org-get-at-eol (property n)
21694 "Get text property PROPERTY at the end of line less N characters."
21695 (get-text-property (- (point-at-eol) n) property))
21697 (defun org-find-text-property-in-string (prop s)
21698 "Return the first non-nil value of property PROP in string S."
21699 (or (get-text-property 0 prop s)
21700 (get-text-property (or (next-single-property-change 0 prop s) 0)
21703 (defun org-display-warning (message)
21704 "Display the given MESSAGE as a warning."
21705 (display-warning 'org message :warning))
21707 (defun org-eval (form)
21708 "Eval FORM and return result."
21709 (condition-case error
21711 (error (format "%%![Error: %s]" error))))
21713 (defun org-in-clocktable-p ()
21714 "Check if the cursor is in a clocktable."
21715 (let ((pos (point)) start)
21718 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21719 (setq start (match-beginning 0))
21720 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21721 (>= (match-end 0) pos)
21724 (defun org-in-verbatim-emphasis ()
21726 (and (org-in-regexp org-verbatim-re 2)
21727 (>= (point) (match-beginning 3))
21728 (<= (point) (match-end 4)))))
21730 (defun org-overlay-display (ovl text &optional face evap)
21731 "Make overlay OVL display TEXT with face FACE."
21732 (overlay-put ovl 'display text)
21733 (if face (overlay-put ovl 'face face))
21734 (if evap (overlay-put ovl 'evaporate t)))
21736 (defun org-overlay-before-string (ovl text &optional face evap)
21737 "Make overlay OVL display TEXT with face FACE."
21738 (if face (org-add-props text nil 'face face))
21739 (overlay-put ovl 'before-string text)
21740 (if evap (overlay-put ovl 'evaporate t)))
21742 (defun org-find-overlays (prop &optional pos delete)
21743 "Find all overlays specifying PROP at POS or point.
21744 If DELETE is non-nil, delete all those overlays."
21746 (dolist (ov (overlays-at (or pos (point))) found)
21747 (cond ((not (overlay-get ov prop)))
21748 (delete (delete-overlay ov))
21749 (t (push ov found))))))
21751 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21752 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21753 (if (and marker (marker-buffer marker)
21754 (buffer-live-p (marker-buffer marker)))
21756 (pop-to-buffer-same-window (marker-buffer marker))
21757 (when (or (> marker (point-max)) (< marker (point-min)))
21760 (org-show-context 'org-goto))
21762 (bookmark-jump bookmark)
21763 (error "Cannot find location"))))
21765 (defun org-quote-csv-field (s)
21766 "Quote field for inclusion in CSV material."
21767 (if (string-match "[\",]" s)
21768 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21771 (defun org-force-self-insert (N)
21772 "Needed to enforce self-insert under remapping."
21774 (self-insert-command N))
21776 (defun org-shorten-string (s maxlength)
21777 "Shorten string S so that it is no longer than MAXLENGTH characters.
21778 If the string is shorter or has length MAXLENGTH, just return the
21779 original string. If it is longer, the functions finds a space in the
21780 string, breaks this string off at that locations and adds three dots
21781 as ellipsis. Including the ellipsis, the string will not be longer
21782 than MAXLENGTH. If finding a good breaking point in the string does
21783 not work, the string is just chopped off in the middle of a word
21785 (if (<= (length s) maxlength)
21787 (let* ((n (max (- maxlength 4) 1))
21788 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21789 (if (string-match re s)
21790 (concat (match-string 1 s) "...")
21791 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21793 (defun org-get-indentation (&optional line)
21794 "Get the indentation of the current line, interpreting tabs.
21795 When LINE is given, assume it represents a line and compute its indentation."
21797 (when (string-match "^ *" (org-remove-tabs line))
21800 (beginning-of-line 1)
21801 (skip-chars-forward " \t")
21802 (current-column))))
21804 (defun org-get-string-indentation (s)
21805 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21806 (let ((n -1) (i 0) (w tab-width) c)
21808 (while (< (setq n (1+ n)) (length s))
21809 (setq c (aref s n))
21810 (cond ((= c ?\ ) (setq i (1+ i)))
21811 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21812 (t (throw 'exit t)))))
21815 (defun org-remove-tabs (s &optional width)
21816 "Replace tabulators in S with spaces.
21817 Assumes that s is a single line, starting in column 0."
21818 (setq width (or width tab-width))
21819 (while (string-match "\t" s)
21820 (setq s (replace-match
21822 (- (* width (/ (+ (match-beginning 0) width) width))
21823 (match-beginning 0)) ?\ )
21827 (defun org-fix-indentation (line ind)
21828 "Fix indentation in LINE.
21829 IND is a cons cell with target and minimum indentation.
21830 If the current indentation in LINE is smaller than the minimum,
21831 leave it alone. If it is larger than ind, set it to the target."
21832 (let* ((l (org-remove-tabs line))
21833 (i (org-get-indentation l))
21834 (i1 (car ind)) (i2 (cdr ind)))
21835 (when (>= i i2) (setq l (substring line i2)))
21837 (concat (make-string i1 ?\ ) l)
21840 (defun org-remove-indentation (code &optional n)
21841 "Remove maximum common indentation in string CODE and return it.
21842 N may optionally be the number of columns to remove. Return CODE
21843 as-is if removal failed."
21846 (if (org-do-remove-indentation n) (buffer-string) code)))
21848 (defun org-do-remove-indentation (&optional n)
21849 "Remove the maximum common indentation from the buffer.
21850 When optional argument N is a positive integer, remove exactly
21851 that much characters from indentation, if possible. Return nil
21854 (goto-char (point-min))
21855 ;; Find maximum common indentation, if not specified.
21857 (let ((min-ind (point-max)))
21859 (while (re-search-forward "^[ \t]*\\S-" nil t)
21860 (let ((ind (1- (current-column))))
21861 (if (zerop ind) (throw :exit nil)
21862 (setq min-ind (min min-ind ind))))))
21864 (if (zerop n) (throw :exit nil)
21865 ;; Remove exactly N indentation, but give up if not possible.
21866 (while (not (eobp))
21867 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21868 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21869 ((< ind n) (throw :exit nil))
21870 (t (indent-line-to (- ind n))))
21875 (defun org-fill-template (template alist)
21876 "Find each %key of ALIST in TEMPLATE and replace it."
21877 (let ((case-fold-search nil))
21878 (dolist (entry (sort (copy-sequence alist)
21879 (lambda (a b) (< (length (car a)) (length (car b))))))
21881 (replace-regexp-in-string
21882 (concat "%" (regexp-quote (car entry)))
21883 (or (cdr entry) "") template t t)))
21886 (defun org-base-buffer (buffer)
21887 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21890 (or (buffer-base-buffer buffer)
21893 (defun org-wrap (string &optional width lines)
21894 "Wrap string to either a number of lines, or a width in characters.
21895 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21896 that costs. If there is a word longer than WIDTH, the text is actually
21897 wrapped to the length of that word.
21898 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21899 many lines, whatever width that takes.
21900 The return value is a list of lines, without newlines at the end."
21901 (let* ((words (split-string string))
21902 (maxword (apply 'max (mapcar 'org-string-width words)))
21905 (org-do-wrap words (max maxword width)))
21908 (setq ll (org-do-wrap words maxword))
21909 (if (<= (length ll) lines)
21912 (while (> (length ll) lines)
21914 (setq ll (org-do-wrap words w)))
21916 (t (error "Cannot wrap this")))))
21918 (defun org-do-wrap (words width)
21919 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21922 (setq line (pop words))
21923 (while (and words (< (+ (length line) (length (car words))) width))
21924 (setq line (concat line " " (pop words))))
21925 (setq lines (push line lines)))
21928 (defun org-quote-vert (s)
21929 "Replace \"|\" with \"\\vert\"."
21930 (while (string-match "|" s)
21931 (setq s (replace-match "\\vert" t t s)))
21934 (defun org-uuidgen-p (s)
21935 "Is S an ID created by UUIDGEN?"
21936 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21938 (defun org-in-src-block-p (&optional inside)
21939 "Whether point is in a code source block.
21940 When INSIDE is non-nil, don't consider we are within a src block
21941 when point is at #+BEGIN_SRC or #+END_SRC."
21942 (let ((case-fold-search t))
21943 (or (and (eq (get-char-property (point) 'src-block) t))
21947 (beginning-of-line)
21948 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21950 (defun org-context ()
21951 "Return a list of contexts of the current cursor position.
21952 If several contexts apply, all are returned.
21953 Each context entry is a list with a symbol naming the context, and
21954 two positions indicating start and end of the context. Possible
21957 :headline anywhere in a headline
21958 :headline-stars on the leading stars in a headline
21959 :todo-keyword on a TODO keyword (including DONE) in a headline
21960 :tags on the TAGS in a headline
21961 :priority on the priority cookie in a headline
21962 :item on the first line of a plain list item
21963 :item-bullet on the bullet/number of a plain list item
21964 :checkbox on the checkbox in a plain list item
21965 :table in an Org table
21966 :table-special on a special filed in a table
21967 :table-table in a table.el table
21968 :clocktable in a clocktable
21969 :src-block in a source block
21970 :link on a hyperlink
21971 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21972 :target on a <<target>>
21973 :radio-target on a <<<radio-target>>>
21974 :latex-fragment on a LaTeX fragment
21975 :latex-preview on a LaTeX fragment with overlaid preview image
21977 This function expects the position to be visible because it uses font-lock
21978 faces as a help to recognize the following contexts: :table-special, :link,
21980 (let* ((f (get-text-property (point) 'face))
21981 (faces (if (listp f) f (list f)))
21982 (case-fold-search t)
21983 (p (point)) clist o)
21984 ;; First the large context
21986 ((org-at-heading-p t)
21987 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21989 (beginning-of-line 1)
21990 (looking-at org-todo-line-tags-regexp))
21991 (push (org-point-in-group p 1 :headline-stars) clist)
21992 (push (org-point-in-group p 2 :todo-keyword) clist)
21993 (push (org-point-in-group p 4 :tags) clist))
21995 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21996 (when (looking-at "\\[#[A-Z0-9]\\]")
21997 (push (org-point-in-group p 0 :priority) clist)))
22000 (push (org-point-in-group p 2 :item-bullet) clist)
22001 (push (list :item (point-at-bol)
22002 (save-excursion (org-end-of-item) (point)))
22004 (and (org-at-item-checkbox-p)
22005 (push (org-point-in-group p 0 :checkbox) clist)))
22008 (push (list :table (org-table-begin) (org-table-end)) clist)
22009 (when (memq 'org-formula faces)
22010 (push (list :table-special
22011 (previous-single-property-change p 'face)
22012 (next-single-property-change p 'face)) clist)))
22013 ((org-at-table-p 'any)
22014 (push (list :table-table) clist)))
22017 (let ((case-fold-search t))
22018 ;; New the "medium" contexts: clocktables, source blocks
22019 (cond ((org-in-clocktable-p)
22020 (push (list :clocktable
22021 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22022 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22023 (match-beginning 1))
22024 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22025 (match-end 0))) clist))
22026 ((org-in-src-block-p)
22027 (push (list :src-block
22028 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22029 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22030 (match-beginning 1))
22031 (and (search-forward "#+END_SRC" nil t)
22032 (match-beginning 0))) clist))))
22035 ;; Now the small context
22037 ((org-at-timestamp-p)
22038 (push (org-point-in-group p 0 :timestamp) clist))
22039 ((memq 'org-link faces)
22041 (previous-single-property-change p 'face)
22042 (next-single-property-change p 'face)) clist))
22043 ((memq 'org-special-keyword faces)
22044 (push (list :keyword
22045 (previous-single-property-change p 'face)
22046 (next-single-property-change p 'face)) clist))
22048 (push (org-point-in-group p 0 :target) clist)
22049 (goto-char (1- (match-beginning 0)))
22050 (when (looking-at org-radio-target-regexp)
22051 (push (org-point-in-group p 0 :radio-target) clist))
22055 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22057 (overlays-at (point))))
22058 (push (list :latex-fragment
22059 (overlay-start o) (overlay-end o)) clist)
22060 (push (list :latex-preview
22061 (overlay-start o) (overlay-end o)) clist))
22062 ((org-inside-LaTeX-fragment-p)
22063 ;; FIXME: positions wrong.
22064 (push (list :latex-fragment (point) (point)) clist)))
22066 (setq clist (nreverse (delq nil clist)))
22069 (defun org-in-regexp (regexp &optional nlines visually)
22070 "Check if point is inside a match of REGEXP.
22072 Normally only the current line is checked, but you can include
22073 NLINES extra lines around point into the search. If VISUALLY is
22074 set, require that the cursor is not after the match but really
22075 on, so that the block visually is on the match.
22077 Return nil or a cons cell (BEG . END) where BEG and END are,
22078 respectively, the positions at the beginning and the end of the
22081 (let ((pos (point))
22082 (eol (line-end-position (if nlines (1+ nlines) 1))))
22084 (beginning-of-line (- 1 (or nlines 0)))
22085 (while (and (re-search-forward regexp eol t)
22086 (<= (match-beginning 0) pos))
22087 (let ((end (match-end 0)))
22088 (when (or (> end pos) (and (= end pos) (not visually)))
22089 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22091 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22092 "Non-nil when point is between matches of START-RE and END-RE.
22094 Also return a non-nil value when point is on one of the matches.
22096 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22097 buffer positions. Default values are the positions of headlines
22098 surrounding the point.
22100 The functions returns a cons cell whose car (resp. cdr) is the
22101 position before START-RE (resp. after END-RE)."
22103 (let ((pos (point))
22104 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22105 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22108 ;; Point is on a block when on START-RE or if START-RE can be
22109 ;; found before it...
22110 (and (or (org-in-regexp start-re)
22111 (re-search-backward start-re limit-up t))
22112 (setq beg (match-beginning 0))
22113 ;; ... and END-RE after it...
22114 (goto-char (match-end 0))
22115 (re-search-forward end-re limit-down t)
22116 (> (setq end (match-end 0)) pos)
22117 ;; ... without another START-RE in-between.
22118 (goto-char (match-beginning 0))
22119 (not (re-search-backward start-re (1+ beg) t))
22121 (cons beg end))))))
22123 (defun org-in-block-p (names)
22124 "Non-nil when point belongs to a block whose name belongs to NAMES.
22126 NAMES is a list of strings containing names of blocks.
22128 Return first block name matched, or nil. Beware that in case of
22129 nested blocks, the returned name may not belong to the closest
22133 (let ((case-fold-search t)
22134 (lim-up (save-excursion (outline-previous-heading)))
22135 (lim-down (save-excursion (outline-next-heading))))
22136 (dolist (name names)
22137 (let ((n (regexp-quote name)))
22138 (when (org-between-regexps-p
22139 (concat "^[ \t]*#\\+begin_" n)
22140 (concat "^[ \t]*#\\+end_" n)
22142 (throw 'exit n)))))
22145 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22146 "Call `multi-occur' with buffers for all agenda files."
22147 (interactive "sOrg-files matching: ")
22148 (let* ((files (org-agenda-files))
22149 (tnames (mapcar #'file-truename files))
22150 (extra org-agenda-text-search-extra-files))
22151 (when (eq (car extra) 'agenda-archives)
22152 (setq extra (cdr extra))
22153 (setq files (org-add-archive-files files)))
22155 (unless (member (file-truename f) tnames)
22156 (unless (member f files) (setq files (append files (list f))))
22157 (setq tnames (append tnames (list (file-truename f))))))
22159 (mapcar (lambda (x)
22160 (with-current-buffer
22161 ;; FIXME: Why not just (find-file-noselect x)?
22162 ;; Is it to avoid the "revert buffer" prompt?
22163 (or (get-file-buffer x) (find-file-noselect x))
22169 (add-hook 'occur-mode-find-occurrence-hook
22170 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22172 (defun org-occur-link-in-agenda-files ()
22173 "Create a link and search for it in the agendas.
22174 The link is not stored in `org-stored-links', it is just created
22175 for the search purpose."
22177 (let ((link (condition-case nil
22178 (org-store-link nil)
22179 (error "Unable to create a link to here"))))
22180 (org-occur-in-agenda-files (regexp-quote link))))
22182 (defun org-reverse-string (string)
22183 "Return the reverse of STRING."
22184 (apply 'string (reverse (string-to-list string))))
22186 ;; defsubst org-uniquify must be defined before first use
22188 (defun org-uniquify-alist (alist)
22189 "Merge elements of ALIST with the same key.
22191 For example, in this alist:
22193 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22194 => \\='((a 1 3) (b 2))
22196 merge (a 1) and (a 3) into (a 1 3).
22198 The function returns the new ALIST."
22200 (dolist (e alist rtn)
22202 (if (not (assoc (car e) rtn))
22204 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22205 (setq rtn (assq-delete-all (car e) rtn))
22208 (defun org-delete-all (elts list)
22209 "Remove all elements in ELTS from LIST.
22210 Comparison is done with `equal'. It is a destructive operation
22211 that may remove elements by altering the list structure."
22213 (setq list (delete (pop elts) list)))
22216 (defun org-back-over-empty-lines ()
22217 "Move backwards over whitespace, to the beginning of the first empty line.
22218 Returns the number of empty lines passed."
22219 (let ((pos (point)))
22220 (if (cdr (assq 'heading org-blank-before-new-entry))
22221 (skip-chars-backward " \t\n\r")
22223 (forward-line -1)))
22224 (beginning-of-line 2)
22225 (goto-char (min (point) pos))
22226 (count-lines (point) pos)))
22228 (defun org-skip-whitespace ()
22229 (skip-chars-forward " \t\n\r"))
22231 (defun org-point-in-group (point group &optional context)
22232 "Check if POINT is in match-group GROUP.
22233 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22234 match. If the match group does not exist or point is not inside it,
22236 (and (match-beginning group)
22237 (>= point (match-beginning group))
22238 (<= point (match-end group))
22240 (list context (match-beginning group) (match-end group))
22243 (defun org-switch-to-buffer-other-window (&rest args)
22244 "Switch to buffer in a second window on the current frame.
22245 In particular, do not allow pop-up frames.
22246 Returns the newly created buffer."
22248 (apply 'switch-to-buffer-other-window args)))
22250 (defun org-combine-plists (&rest plists)
22251 "Create a single property list from all plists in PLISTS.
22252 The process starts by copying the first list, and then setting properties
22253 from the other lists. Settings in the last list are the most significant
22254 ones and overrule settings in the other lists."
22255 (let ((rtn (copy-sequence (pop plists)))
22258 (setq ls (pop plists))
22260 (setq p (pop ls) v (pop ls))
22261 (setq rtn (plist-put rtn p v))))
22264 (defun org-replace-escapes (string table)
22265 "Replace %-escapes in STRING with values in TABLE.
22266 TABLE is an association list with keys like \"%a\" and string values.
22267 The sequences in STRING may contain normal field width and padding information,
22268 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22269 so values can contain further %-escapes if they are define later in TABLE."
22270 (let ((tbl (copy-alist table))
22271 (case-fold-search nil)
22275 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22276 (when (and (cdr e) (string-match re (cdr e)))
22277 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22279 (add-text-properties 0 3 (list 'sref sref) safe)
22280 (setcdr e (replace-match safe t t (cdr e)))))
22281 (while (string-match re string)
22282 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22284 (setq string (replace-match rpl t t string))))
22285 (while (setq pchg (next-property-change pchg string))
22286 (let ((sref (get-text-property pchg 'sref string)))
22287 (when (and sref (string-match "SREF" string pchg))
22288 (setq string (replace-match sref t t string)))))
22291 (defun org-find-base-buffer-visiting (file)
22292 "Like `find-buffer-visiting' but always return the base buffer and
22293 not an indirect buffer."
22294 (let ((buf (or (get-file-buffer file)
22295 (find-buffer-visiting file))))
22297 (or (buffer-base-buffer buf) buf)
22300 ;;; TODO: Only called once, from ox-odt which should probably use
22301 ;;; org-export-inline-image-p or something.
22302 (defun org-file-image-p (file)
22303 "Return non-nil if FILE is an image."
22305 (string-match (image-file-name-regexp) file)))
22307 (defun org-get-cursor-date (&optional with-time)
22308 "Return the date at cursor in as a time.
22309 This works in the calendar and in the agenda, anywhere else it just
22310 returns the current time.
22311 If WITH-TIME is non-nil, returns the time of the event at point (in
22312 the agenda) or the current time of the day."
22313 (let (date day defd tp hod mod)
22315 (setq tp (get-text-property (point) 'time))
22316 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22317 (setq hod (string-to-number (match-string 1 tp))
22318 mod (string-to-number (match-string 2 tp))))
22319 (or tp (let ((now (decode-time)))
22320 (setq hod (nth 2 now)
22321 mod (nth 1 now)))))
22323 ((eq major-mode 'calendar-mode)
22324 (setq date (calendar-cursor-to-date)
22325 defd (encode-time 0 (or mod 0) (or hod 0)
22326 (nth 1 date) (nth 0 date) (nth 2 date))))
22327 ((eq major-mode 'org-agenda-mode)
22328 (setq day (get-text-property (point) 'day))
22330 (setq date (calendar-gregorian-from-absolute day)
22331 defd (encode-time 0 (or mod 0) (or hod 0)
22332 (nth 1 date) (nth 0 date) (nth 2 date))))))
22333 (or defd (current-time))))
22335 (defun org-mark-subtree (&optional up)
22336 "Mark the current subtree.
22337 This puts point at the start of the current subtree, and mark at
22338 the end. If a numeric prefix UP is given, move up into the
22339 hierarchy of headlines by UP levels before marking the subtree."
22341 (org-with-limited-levels
22342 (cond ((org-at-heading-p) (beginning-of-line))
22343 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22344 (t (outline-previous-visible-heading 1))))
22345 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22346 (if (called-interactively-p 'any)
22347 (call-interactively 'org-mark-element)
22348 (org-mark-element)))
22350 (defun org-file-newer-than-p (file time)
22351 "Non-nil if FILE is newer than TIME.
22352 FILE is a filename, as a string, TIME is a list of integers, as
22353 returned by, e.g., `current-time'."
22354 (and (file-exists-p file)
22355 ;; Only compare times up to whole seconds as some file-systems
22356 ;; (e.g. HFS+) do not retain any finer granularity. As
22357 ;; a consequence, make sure we return non-nil when the two
22358 ;; times are equal.
22359 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22360 (cl-subseq time 0 2)))))
22362 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22363 "Compile a SOURCE file using PROCESS.
22365 PROCESS is either a function or a list of shell commands, as
22366 strings. EXT is a file extension, without the leading dot, as
22367 a string. It is used to check if the process actually succeeded.
22369 PROCESS must create a file with the same base name and directory
22370 as SOURCE, but ending with EXT. The function then returns its
22371 filename. Otherwise, it raises an error. The error message can
22372 then be refined by providing string ERR-MSG, which is appended to
22373 the standard message.
22375 If PROCESS is a function, it is called with a single argument:
22378 If it is a list of commands, each of them is called using
22379 `shell-command'. By default, in each command, %b, %f, %F, %o and
22380 %O are replaced with, respectively, SOURCE base name, name, full
22381 name, directory and absolute output file name. It is possible,
22382 however, to use more place-holders by specifying them in optional
22383 argument SPEC, as an alist following the pattern
22385 (CHARACTER . REPLACEMENT-STRING).
22387 When PROCESS is a list of commands, optional argument LOG-BUF can
22388 be set to a buffer or a buffer name. `shell-command' then uses
22390 (let* ((base-name (file-name-base source))
22391 (full-name (file-truename source))
22392 (out-dir (or (file-name-directory source) "./"))
22393 (output (expand-file-name (concat base-name "." ext) out-dir))
22394 (time (current-time))
22395 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22396 (save-window-excursion
22398 ((pred functionp) (funcall process (shell-quote-argument source)))
22400 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22402 `((?b . ,(shell-quote-argument base-name))
22403 (?f . ,(shell-quote-argument source))
22404 (?F . ,(shell-quote-argument full-name))
22405 (?o . ,(shell-quote-argument out-dir))
22406 (?O . ,(shell-quote-argument output))))))
22407 (dolist (command process)
22408 (shell-command (format-spec command spec) log-buf))
22409 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22410 (_ (error "No valid command to process %S%s" source err-msg))))
22411 ;; Check for process failure. Output file is expected to be
22412 ;; located in the same directory as SOURCE.
22413 (unless (org-file-newer-than-p output time)
22414 (error (format "File %S wasn't produced%s" output err-msg)))
22419 (defvar org-element-greater-elements)
22420 (defun org--get-expected-indentation (element contentsp)
22421 "Expected indentation column for current line, according to ELEMENT.
22422 ELEMENT is an element containing point. CONTENTSP is non-nil
22423 when indentation is to be computed according to contents of
22425 (let ((type (org-element-type element))
22426 (start (org-element-property :begin element))
22427 (post-affiliated (org-element-property :post-affiliated element)))
22428 (org-with-wide-buffer
22432 ((diary-sexp footnote-definition) 0)
22433 ((headline inlinetask nil)
22434 (if (not org-adapt-indentation) 0
22435 (let ((level (org-current-level)))
22436 (if level (1+ level) 0))))
22437 ((item plain-list) (org-list-item-body-column post-affiliated))
22440 (org-get-indentation))))
22441 ((memq type '(headline inlinetask nil))
22442 (if (org-match-line "[ \t]*$")
22443 (org--get-expected-indentation element t)
22445 ((memq type '(diary-sexp footnote-definition)) 0)
22446 ;; First paragraph of a footnote definition or an item.
22447 ;; Indent like parent.
22448 ((< (line-beginning-position) start)
22449 (org--get-expected-indentation
22450 (org-element-property :parent element) t))
22451 ;; At first line: indent according to previous sibling, if any,
22452 ;; ignoring footnote definitions and inline tasks, or parent's
22454 ((= (line-beginning-position) start)
22457 (if (= (point-min) start) (throw 'exit 0)
22458 (goto-char (1- start))
22459 (let* ((previous (org-element-at-point))
22461 (while (and parent (<= (org-element-property :end parent) start))
22462 (setq previous parent
22463 parent (org-element-property :parent parent)))
22465 ((not previous) (throw 'exit 0))
22466 ((> (org-element-property :end previous) start)
22467 (throw 'exit (org--get-expected-indentation previous t)))
22468 ((memq (org-element-type previous)
22469 '(footnote-definition inlinetask))
22470 (setq start (org-element-property :begin previous)))
22471 (t (goto-char (org-element-property :begin previous))
22473 (if (bolp) (org-get-indentation)
22474 ;; At first paragraph in an item or
22475 ;; a footnote definition.
22476 (org--get-expected-indentation
22477 (org-element-property :parent previous) t))))))))))
22478 ;; Otherwise, move to the first non-blank line above.
22480 (beginning-of-line)
22481 (let ((pos (point)))
22482 (skip-chars-backward " \r\t\n")
22484 ;; Two blank lines end a footnote definition or a plain
22485 ;; list. When we indent an empty line after them, the
22486 ;; containing list or footnote definition is over, so it
22487 ;; qualifies as a previous sibling. Therefore, we indent
22488 ;; like its first line.
22489 ((and (memq type '(footnote-definition plain-list))
22490 (> (count-lines (point) pos) 2))
22492 (org-get-indentation))
22493 ;; Line above is the first one of a paragraph at the
22494 ;; beginning of an item or a footnote definition. Indent
22496 ((< (line-beginning-position) start)
22497 (org--get-expected-indentation
22498 (org-element-property :parent element) t))
22499 ;; Line above is the beginning of an element, i.e., point
22500 ;; was originally on the blank lines between element's start
22502 ((= (line-beginning-position) post-affiliated)
22503 (org--get-expected-indentation element t))
22504 ;; POS is after contents in a greater element. Indent like
22505 ;; the beginning of the element.
22506 ((and (memq type org-element-greater-elements)
22507 (let ((cend (org-element-property :contents-end element)))
22508 (and cend (<= cend pos))))
22509 ;; As a special case, if point is at the end of a footnote
22510 ;; definition or an item, indent like the very last element
22511 ;; within. If that last element is an item, indent like
22513 (if (memq type '(footnote-definition item plain-list))
22514 (let ((last (org-element-at-point)))
22516 (org--get-expected-indentation
22517 last (eq (org-element-type last) 'item)))
22519 (org-get-indentation)))
22520 ;; In any other case, indent like the current line.
22521 (t (org-get-indentation)))))))))
22523 (defun org--align-node-property ()
22524 "Align node property at point.
22525 Alignment is done according to `org-property-format', which see."
22526 (when (save-excursion
22527 (beginning-of-line)
22528 (looking-at org-property-re))
22530 (concat (match-string 4)
22532 (format org-property-format (match-string 1) (match-string 3))))
22535 (defun org-indent-line ()
22536 "Indent line depending on context.
22538 Indentation is done according to the following rules:
22540 - Footnote definitions, diary sexps, headlines and inline tasks
22541 have to start at column 0.
22543 - On the very first line of an element, consider, in order, the
22544 next rules until one matches:
22546 1. If there's a sibling element before, ignoring footnote
22547 definitions and inline tasks, indent like its first line.
22549 2. If element has a parent, indent like its contents. More
22550 precisely, if parent is an item, indent after the
22551 description part, if any, or the bullet (see
22552 `org-list-description-max-indent'). Else, indent like
22553 parent's first line.
22555 3. Otherwise, indent relatively to current level, if
22556 `org-adapt-indentation' is non-nil, or to left margin.
22558 - On a blank line at the end of an element, indent according to
22559 the type of the element. More precisely
22561 1. If element is a plain list, an item, or a footnote
22562 definition, indent like the very last element within.
22564 2. If element is a paragraph, indent like its last non blank
22567 3. Otherwise, indent like its very first line.
22569 - In the code part of a source block, use language major mode
22570 to indent current line if `org-src-tab-acts-natively' is
22571 non-nil. If it is nil, do nothing.
22573 - Otherwise, indent like the first non-blank line above.
22575 The function doesn't indent an item as it could break the whole
22576 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22577 `\\[org-shiftmetaright]'.
22579 Also align node properties according to `org-property-format'."
22583 (let ((indent-line-function
22584 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22585 (indent-according-to-mode)))
22586 ((org-at-heading-p) 'noindent)
22588 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22589 (type (org-element-type element)))
22590 (cond ((and (memq type '(plain-list item))
22591 (= (line-beginning-position)
22592 (org-element-property :post-affiliated element)))
22594 ((and (eq type 'latex-environment)
22595 (>= (point) (org-element-property :post-affiliated element))
22596 (< (point) (org-with-wide-buffer
22597 (goto-char (org-element-property :end element))
22598 (skip-chars-backward " \r\t\n")
22599 (line-beginning-position 2))))
22601 ((and (eq type 'src-block)
22602 org-src-tab-acts-natively
22603 (> (line-beginning-position)
22604 (org-element-property :post-affiliated element))
22605 (< (line-beginning-position)
22606 (org-with-wide-buffer
22607 (goto-char (org-element-property :end element))
22608 (skip-chars-backward " \r\t\n")
22609 (line-beginning-position))))
22610 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22612 (let ((column (org--get-expected-indentation element nil)))
22613 ;; Preserve current column.
22614 (if (<= (current-column) (current-indentation))
22615 (indent-line-to column)
22616 (save-excursion (indent-line-to column))))
22617 ;; Align node property. Also preserve current column.
22618 (when (eq type 'node-property)
22619 (let ((column (current-column)))
22620 (org--align-node-property)
22621 (org-move-to-column column)))))))))
22623 (defun org-indent-region (start end)
22624 "Indent each non-blank line in the region.
22625 Called from a program, START and END specify the region to
22626 indent. The function will not indent contents of example blocks,
22627 verse blocks and export blocks as leading white spaces are
22628 assumed to be significant there."
22632 (skip-chars-forward " \r\t\n")
22633 (unless (eobp) (beginning-of-line))
22636 ;; Set IND as indentation for all lines between point and
22637 ;; POS. Blank lines are ignored. Leave point after POS
22639 (let ((limit (copy-marker pos)))
22640 (while (< (point) limit)
22641 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22643 (set-marker limit nil))))
22644 (end (copy-marker end)))
22645 (while (< (point) end)
22646 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22647 (let* ((element (org-element-at-point))
22648 (type (org-element-type element))
22649 (element-end (copy-marker (org-element-property :end element)))
22650 (ind (org--get-expected-indentation element nil)))
22652 ;; Element indented as a single block. Example blocks
22653 ;; preserving indentation are a special case since the
22654 ;; "contents" must not be indented whereas the block
22656 ((or (memq type '(export-block latex-environment))
22657 (and (eq type 'example-block)
22659 (or org-src-preserve-indentation
22660 (org-element-property :preserve-indent element)))))
22661 (let ((offset (- ind (org-get-indentation))))
22662 (unless (zerop offset)
22663 (indent-rigidly (org-element-property :begin element)
22664 (org-element-property :end element)
22666 (goto-char element-end))
22667 ;; Elements indented line wise. Be sure to exclude
22668 ;; example blocks (preserving indentation) and source
22669 ;; blocks from this category as they are treated
22670 ;; specially later.
22671 ((or (memq type '(paragraph table table-row))
22672 (not (or (org-element-property :contents-begin element)
22673 (memq type '(example-block src-block)))))
22674 (when (eq type 'node-property)
22675 (org--align-node-property)
22676 (beginning-of-line))
22677 (funcall indent-to ind (min element-end end)))
22678 ;; Elements consisting of three parts: before the
22679 ;; contents, the contents, and after the contents. The
22680 ;; contents are treated specially, according to the
22681 ;; element type, or not indented at all. Other parts are
22682 ;; indented as a single block.
22684 (let* ((post (copy-marker
22685 (org-element-property :post-affiliated element)))
22689 ((not (org-element-property :contents-begin element))
22690 ;; Fake contents for source blocks.
22691 (org-with-wide-buffer
22693 (line-beginning-position 2)))
22694 ((memq type '(footnote-definition item plain-list))
22695 ;; Contents in these elements could start on
22696 ;; the same line as the beginning of the
22697 ;; element. Make sure we start indenting
22698 ;; from the second line.
22699 (org-with-wide-buffer
22702 (skip-chars-forward " \r\t\n")
22703 (if (eobp) (point) (line-beginning-position))))
22704 (t (org-element-property :contents-begin element)))))
22706 (or (org-element-property :contents-end element)
22707 ;; Fake contents for source blocks.
22708 (org-with-wide-buffer
22709 (goto-char element-end)
22710 (skip-chars-backward " \r\t\n")
22711 (line-beginning-position)))
22713 ;; Do not change items indentation individually as it
22714 ;; might break the list as a whole. On the other
22715 ;; hand, when at a plain list, indent it as a whole.
22716 (cond ((eq type 'plain-list)
22717 (let ((offset (- ind (org-get-indentation))))
22718 (unless (zerop offset)
22719 (indent-rigidly (org-element-property :begin element)
22720 (org-element-property :end element)
22723 ((eq type 'item) (goto-char cbeg))
22724 (t (funcall indent-to ind (min cbeg end))))
22725 (when (< (point) end)
22727 ((example-block verse-block))
22729 ;; In a source block, indent source code
22730 ;; according to language major mode, but only if
22731 ;; `org-src-tab-acts-natively' is non-nil.
22732 (when (and (< (point) end) org-src-tab-acts-natively)
22734 (org-babel-do-in-edit-buffer
22735 (indent-region (point-min) (point-max))))))
22736 (t (org-indent-region (point) (min cend end))))
22737 (goto-char (min cend end))
22738 (when (< (point) end)
22739 (funcall indent-to ind (min element-end end))))
22740 (set-marker post nil)
22741 (set-marker cbeg nil)
22742 (set-marker cend nil))))
22743 (set-marker element-end nil))))
22744 (set-marker end nil))))
22746 (defun org-indent-drawer ()
22747 "Indent the drawer at point."
22749 (unless (save-excursion
22750 (beginning-of-line)
22751 (looking-at-p org-drawer-regexp))
22752 (user-error "Not at a drawer"))
22753 (let ((element (org-element-at-point)))
22754 (unless (memq (org-element-type element) '(drawer property-drawer))
22755 (user-error "Not at a drawer"))
22756 (org-with-wide-buffer
22757 (org-indent-region (org-element-property :begin element)
22758 (org-element-property :end element))))
22759 (message "Drawer at point indented"))
22761 (defun org-indent-block ()
22762 "Indent the block at point."
22764 (unless (save-excursion
22765 (beginning-of-line)
22766 (let ((case-fold-search t))
22767 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22768 (user-error "Not at a block"))
22769 (let ((element (org-element-at-point)))
22770 (unless (memq (org-element-type element)
22771 '(comment-block center-block dynamic-block example-block
22772 export-block quote-block special-block
22773 src-block verse-block))
22774 (user-error "Not at a block"))
22775 (org-with-wide-buffer
22776 (org-indent-region (org-element-property :begin element)
22777 (org-element-property :end element))))
22778 (message "Block at point indented"))
22783 ;; We use our own fill-paragraph and auto-fill functions.
22785 ;; `org-fill-paragraph' relies on adaptive filling and context
22786 ;; checking. Appropriate `fill-prefix' is computed with
22787 ;; `org-adaptive-fill-function'.
22789 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22790 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22791 ;; `org-adaptive-fill-function' value. Internally,
22792 ;; `org-comment-line-break-function' breaks the line.
22794 ;; `org-setup-filling' installs filling and auto-filling related
22795 ;; variables during `org-mode' initialization.
22797 (defun org-setup-filling ()
22798 (require 'org-element)
22799 ;; Prevent auto-fill from inserting unwanted new items.
22800 (when (boundp 'fill-nobreak-predicate)
22802 fill-nobreak-predicate
22804 (append fill-nobreak-predicate
22805 '(org-fill-line-break-nobreak-p
22806 org-fill-n-macro-as-item-nobreak-p
22807 org-fill-paragraph-with-timestamp-nobreak-p)))))
22808 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22809 (setq-local paragraph-start paragraph-ending)
22810 (setq-local paragraph-separate paragraph-ending))
22811 (setq-local fill-paragraph-function 'org-fill-paragraph)
22812 (setq-local auto-fill-inhibit-regexp nil)
22813 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22814 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22815 (setq-local comment-line-break-function 'org-comment-line-break-function))
22817 (defun org-fill-line-break-nobreak-p ()
22818 "Non-nil when a new line at point would create an Org line break."
22820 (skip-chars-backward "[ \t]")
22821 (skip-chars-backward "\\\\")
22822 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22824 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22825 "Non-nil when a new line at point would split a timestamp."
22826 (and (org-at-timestamp-p 'lax)
22827 (not (looking-at org-ts-regexp-both))))
22829 (defun org-fill-n-macro-as-item-nobreak-p ()
22830 "Non-nil when a new line at point would create a new list."
22831 ;; During export, a "n" macro followed by a dot or a closing
22832 ;; parenthesis can end up being parsed as a new list item.
22833 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22835 (declare-function message-in-body-p "message" ())
22836 (defvar orgtbl-line-start-regexp) ; From org-table.el
22837 (defun org-adaptive-fill-function ()
22838 "Compute a fill prefix for the current line.
22839 Return fill prefix, as a string, or nil if current line isn't
22840 meant to be filled. For convenience, if `adaptive-fill-regexp'
22841 matches in paragraphs or comments, use it."
22843 (when (derived-mode-p 'message-mode)
22845 (beginning-of-line)
22846 (cond ((not (message-in-body-p)) (throw 'exit nil))
22847 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22848 ((looking-at message-cite-prefix-regexp)
22849 (throw 'exit (match-string-no-properties 0)))
22850 ((looking-at org-outline-regexp)
22851 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22852 (org-with-wide-buffer
22853 (unless (org-at-heading-p)
22854 (let* ((p (line-beginning-position))
22855 (element (save-excursion
22856 (beginning-of-line)
22857 (org-element-at-point)))
22858 (type (org-element-type element))
22859 (post-affiliated (org-element-property :post-affiliated element)))
22860 (unless (< p post-affiliated)
22864 (beginning-of-line)
22865 (looking-at "[ \t]*")
22866 (concat (match-string 0) "# ")))
22867 (footnote-definition "")
22869 (make-string (org-list-item-body-column post-affiliated) ?\s))
22871 ;; Fill prefix is usually the same as the current line,
22872 ;; unless the paragraph is at the beginning of an item.
22873 (let ((parent (org-element-property :parent element)))
22875 (beginning-of-line)
22876 (cond ((eq (org-element-type parent) 'item)
22877 (make-string (org-list-item-body-column
22878 (org-element-property :begin parent))
22880 ((and adaptive-fill-regexp
22882 ;; `adaptive-fill-function' to let
22883 ;; `fill-context-prefix' handle
22884 ;; `adaptive-fill-regexp' variable.
22885 (let (adaptive-fill-function)
22886 (fill-context-prefix
22888 (org-element-property :end element)))))
22889 ((looking-at "[ \t]+") (match-string 0))
22892 ;; Only fill contents if P is within block boundaries.
22893 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22896 (cend (save-excursion
22897 (goto-char (org-element-property :end element))
22898 (skip-chars-backward " \r\t\n")
22899 (line-beginning-position))))
22900 (when (and (>= p cbeg) (< p cend))
22901 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22905 (declare-function message-goto-body "message" ())
22906 (defvar message-cite-prefix-regexp) ; From message.el
22908 (defun org-fill-element (&optional justify)
22909 "Fill element at point, when applicable.
22911 This function only applies to comment blocks, comments, example
22912 blocks and paragraphs. Also, as a special case, re-align table
22913 when point is at one.
22915 If JUSTIFY is non-nil (interactively, with prefix argument),
22916 justify as well. If `sentence-end-double-space' is non-nil, then
22917 period followed by one space does not end a sentence, so don't
22918 break a line there. The variable `fill-column' controls the
22921 For convenience, when point is at a plain list, an item or
22922 a footnote definition, try to fill the first paragraph within."
22923 (with-syntax-table org-mode-transpose-word-syntax-table
22924 ;; Move to end of line in order to get the first paragraph within
22925 ;; a plain list or a footnote definition.
22926 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22927 ;; First check if point is in a blank line at the beginning of
22928 ;; the buffer. In that case, ignore filling.
22929 (cl-case (org-element-type element)
22930 ;; Use major mode filling function is src blocks.
22931 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22932 ;; Align Org tables, leave table.el tables as-is.
22933 (table-row (org-table-align) t)
22935 (when (eq (org-element-property :type element) 'org)
22937 (goto-char (org-element-property :post-affiliated element))
22938 (org-table-align)))
22941 ;; Paragraphs may contain `line-break' type objects.
22942 (let ((beg (max (point-min)
22943 (org-element-property :contents-begin element)))
22944 (end (min (point-max)
22945 (org-element-property :contents-end element))))
22946 ;; Do nothing if point is at an affiliated keyword.
22947 (if (< (line-end-position) beg) t
22948 (when (derived-mode-p 'message-mode)
22949 ;; In `message-mode', do not fill following citation
22950 ;; in current paragraph nor text before message body.
22951 (let ((body-start (save-excursion (message-goto-body))))
22952 (when body-start (setq beg (max body-start beg))))
22953 (when (save-excursion
22955 (concat "^" message-cite-prefix-regexp) end t))
22956 (setq end (match-beginning 0))))
22957 ;; Fill paragraph, taking line breaks into account.
22960 (let ((cuts (list beg)))
22961 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22962 (when (eq 'line-break
22964 (save-excursion (backward-char)
22965 (org-element-context))))
22966 (push (point) cuts)))
22967 (dolist (c (delq end cuts))
22968 (fill-region-as-paragraph c end justify)
22971 ;; Contents of `comment-block' type elements should be
22972 ;; filled as plain text, but only if point is within block
22975 (let* ((case-fold-search t)
22976 (beg (save-excursion
22977 (goto-char (org-element-property :begin element))
22978 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22981 (end (save-excursion
22982 (goto-char (org-element-property :end element))
22983 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22984 (line-beginning-position))))
22985 (if (or (< (point) beg) (> (point) end)) t
22986 (fill-region-as-paragraph
22987 (save-excursion (end-of-line)
22988 (re-search-backward "^[ \t]*$" beg 'move)
22989 (line-beginning-position))
22990 (save-excursion (beginning-of-line)
22991 (re-search-forward "^[ \t]*$" end 'move)
22992 (line-beginning-position))
22996 (let ((begin (org-element-property :post-affiliated element))
22997 (end (org-element-property :end element)))
22998 (when (and (>= (point) begin) (<= (point) end))
22999 (let ((begin (save-excursion
23001 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23002 (progn (forward-line) (point))
23004 (end (save-excursion
23006 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23007 (1- (line-beginning-position))
23008 (skip-chars-backward " \r\t\n")
23009 (line-end-position)))))
23010 ;; Do not fill comments when at a blank line.
23011 (when (> end begin)
23014 (beginning-of-line)
23015 (looking-at "[ \t]*#")
23016 (let ((comment-prefix (match-string 0)))
23017 (goto-char (match-end 0))
23018 (if (looking-at adaptive-fill-regexp)
23019 (concat comment-prefix (match-string 0))
23020 (concat comment-prefix " "))))))
23022 (fill-region-as-paragraph begin end justify))))))
23024 ;; Ignore every other element.
23027 (defun org-fill-paragraph (&optional justify region)
23028 "Fill element at point, when applicable.
23030 This function only applies to comment blocks, comments, example
23031 blocks and paragraphs. Also, as a special case, re-align table
23032 when point is at one.
23034 For convenience, when point is at a plain list, an item or
23035 a footnote definition, try to fill the first paragraph within.
23037 If JUSTIFY is non-nil (interactively, with prefix argument),
23038 justify as well. If `sentence-end-double-space' is non-nil, then
23039 period followed by one space does not end a sentence, so don't
23040 break a line there. The variable `fill-column' controls the
23043 The REGION argument is non-nil if called interactively; in that
23044 case, if Transient Mark mode is enabled and the mark is active,
23045 fill each of the elements in the active region, instead of just
23046 filling the current element."
23047 (interactive (progn
23048 (barf-if-buffer-read-only)
23049 (list (if current-prefix-arg 'full) t)))
23051 ((and (derived-mode-p 'message-mode)
23052 (or (not (message-in-body-p))
23053 (save-excursion (move-beginning-of-line 1)
23054 (looking-at message-cite-prefix-regexp))))
23055 ;; First ensure filling is correct in message-mode.
23056 (let ((fill-paragraph-function
23057 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23058 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23059 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23060 (paragraph-separate
23061 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23062 (fill-paragraph nil)))
23063 ((and region transient-mark-mode mark-active
23064 (not (eq (region-beginning) (region-end))))
23065 (let ((origin (point-marker))
23066 (start (region-beginning)))
23069 (goto-char (region-end))
23070 (while (> (point) start)
23071 (org-backward-paragraph)
23072 (org-fill-element justify)))
23074 (set-marker origin nil))))
23075 (t (org-fill-element justify))))
23076 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23078 (defun org-auto-fill-function ()
23079 "Auto-fill function."
23080 ;; Check if auto-filling is meaningful.
23081 (let ((fc (current-fill-column)))
23082 (when (and fc (> (current-column) fc))
23083 (let* ((fill-prefix (org-adaptive-fill-function))
23084 ;; Enforce empty fill prefix, if required. Otherwise, it
23085 ;; will be computed again.
23086 (adaptive-fill-mode (not (equal fill-prefix ""))))
23087 (when fill-prefix (do-auto-fill))))))
23089 (defun org-comment-line-break-function (&optional soft)
23090 "Break line at point and indent, continuing comment if within one.
23091 The inserted newline is marked hard if variable
23092 `use-hard-newlines' is true, unless optional argument SOFT is
23094 (if soft (insert-and-inherit ?\n) (newline 1))
23095 (save-excursion (forward-char -1) (delete-horizontal-space))
23096 (delete-horizontal-space)
23097 (indent-to-left-margin)
23098 (insert-before-markers-and-inherit fill-prefix))
23101 ;;; Fixed Width Areas
23103 (defun org-toggle-fixed-width ()
23104 "Toggle fixed-width markup.
23106 Add or remove fixed-width markup on current line, whenever it
23107 makes sense. Return an error otherwise.
23109 If a region is active and if it contains only fixed-width areas
23110 or blank lines, remove all fixed-width markup in it. If the
23111 region contains anything else, convert all non-fixed-width lines
23112 to fixed-width ones.
23114 Blank lines at the end of the region are ignored unless the
23115 region only contains such lines."
23117 (if (not (org-region-active-p))
23120 ;; Remove fixed width marker only in a fixed-with element.
23122 ;; Add fixed width maker in paragraphs, in blank lines after
23123 ;; elements or at the beginning of a headline or an inlinetask,
23124 ;; and before any one-line elements (e.g., a clock).
23126 (beginning-of-line)
23127 (let* ((element (org-element-at-point))
23128 (type (org-element-type element)))
23130 ((and (eq type 'fixed-width)
23131 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23133 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23134 ((and (memq type '(babel-call clock comment diary-sexp headline
23135 horizontal-rule keyword paragraph
23137 (<= (org-element-property :post-affiliated element) (point)))
23138 (skip-chars-forward " \t")
23140 ((and (looking-at-p "[ \t]*$")
23141 (or (eq type 'inlinetask)
23143 (skip-chars-forward " \r\t\n")
23144 (<= (org-element-property :end element) (point)))))
23145 (delete-region (point) (line-end-position))
23148 (t (user-error "Cannot insert a fixed-width line here")))))
23150 (let* ((begin (save-excursion
23151 (goto-char (region-beginning))
23152 (line-beginning-position)))
23155 (goto-char (region-end))
23156 (unless (eolp) (beginning-of-line))
23157 (if (save-excursion (re-search-backward "\\S-" begin t))
23158 (progn (skip-chars-backward " \r\t\n") (point))
23164 (skip-chars-forward " \r\t\n")
23165 (when (eobp) (throw 'not-all-p nil))
23166 (while (< (point) end)
23167 (let ((element (org-element-at-point)))
23168 (if (eq (org-element-type element) 'fixed-width)
23169 (goto-char (org-element-property :end element))
23170 (throw 'not-all-p nil))))
23172 (if all-fixed-width-p
23175 (while (< (point) end)
23176 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23179 (if (= (line-end-position) (match-end 0)) 0 1)))
23181 (let ((min-ind (point-max)))
23182 ;; Find minimum indentation across all lines.
23185 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23188 (while (< (point) end)
23189 (unless (looking-at-p "[ \t]*$")
23190 (let ((ind (org-get-indentation)))
23191 (setq min-ind (min min-ind ind))
23192 (when (zerop ind) (throw 'zerop t))))
23194 ;; Loop over all lines and add fixed-width markup everywhere
23195 ;; but in fixed-width lines.
23198 (while (< (point) end)
23200 ((org-at-heading-p)
23203 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23206 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23207 (let* ((element (org-element-at-point))
23208 (element-end (org-element-property :end element)))
23209 (if (eq (org-element-type element) 'fixed-width)
23210 (progn (goto-char element-end)
23211 (skip-chars-backward " \r\t\n")
23213 (let ((limit (min end element-end)))
23214 (while (< (point) limit)
23215 (org-move-to-column min-ind t)
23217 (forward-line))))))
23219 (org-move-to-column min-ind t)
23221 (forward-line)))))))
23222 (set-marker end nil))))
23227 ;; Org comments syntax is quite complex. It requires the entire line
23228 ;; to be just a comment. Also, even with the right syntax at the
23229 ;; beginning of line, some elements (e.g., verse-block or
23230 ;; example-block) don't accept comments. Usual Emacs comment commands
23231 ;; cannot cope with those requirements. Therefore, Org replaces them.
23233 ;; Org still relies on `comment-dwim', but cannot trust
23234 ;; `comment-only-p'. So, `comment-region-function' and
23235 ;; `uncomment-region-function' both point
23236 ;; to`org-comment-or-uncomment-region'. Eventually,
23237 ;; `org-insert-comment' takes care of insertion of comments at the
23238 ;; beginning of line.
23240 ;; `org-setup-comments-handling' install comments related variables
23241 ;; during `org-mode' initialization.
23243 (defun org-setup-comments-handling ()
23245 (setq-local comment-use-syntax nil)
23246 (setq-local comment-start "# ")
23247 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23248 (setq-local comment-insert-comment-function 'org-insert-comment)
23249 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23250 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23252 (defun org-insert-comment ()
23253 "Insert an empty comment above current line.
23254 If the line is empty, insert comment at its beginning. When
23255 point is within a source block, comment according to the related
23257 (if (let ((element (org-element-at-point)))
23258 (and (eq (org-element-type element) 'src-block)
23260 (goto-char (org-element-property :post-affiliated element))
23261 (line-end-position))
23264 (goto-char (org-element-property :end element))
23265 (skip-chars-backward " \r\t\n")
23266 (line-beginning-position))
23268 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23269 (beginning-of-line)
23270 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23275 (defvar comment-empty-lines) ; From newcomment.el.
23276 (defun org-comment-or-uncomment-region (beg end &rest _)
23277 "Comment or uncomment each non-blank line in the region.
23278 Uncomment each non-blank line between BEG and END if it only
23279 contains commented lines. Otherwise, comment them. If region is
23280 strictly within a source block, use appropriate comment syntax."
23281 (if (let ((element (org-element-at-point)))
23282 (and (eq (org-element-type element) 'src-block)
23284 (goto-char (org-element-property :post-affiliated element))
23285 (line-end-position))
23287 (>= (save-excursion
23288 (goto-char (org-element-property :end element))
23289 (skip-chars-backward " \r\t\n")
23290 (line-beginning-position))
23292 ;; Translate region boundaries for the Org buffer to the source
23294 (let ((offset (- end beg)))
23297 (org-babel-do-in-edit-buffer
23298 (comment-or-uncomment-region (point) (+ offset (point))))))
23301 (narrow-to-region (save-excursion (goto-char beg)
23302 (skip-chars-forward " \r\t\n" end)
23303 (line-beginning-position))
23304 (save-excursion (goto-char end)
23305 (skip-chars-backward " \r\t\n" beg)
23306 (line-end-position)))
23308 ;; UNCOMMENTP is non-nil when every non blank line between
23309 ;; BEG and END is a comment.
23311 (goto-char (point-min))
23312 (while (and (not (eobp))
23313 (let ((element (org-element-at-point)))
23314 (and (eq (org-element-type element) 'comment)
23315 (goto-char (min (point-max)
23316 (org-element-property
23317 :end element)))))))
23320 ;; Only blank lines and comments in region: uncomment it.
23322 (goto-char (point-min))
23323 (while (not (eobp))
23324 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23325 (replace-match "" nil nil nil 1))
23327 ;; Comment each line in region.
23328 (let ((min-indent (point-max)))
23329 ;; First find the minimum indentation across all lines.
23331 (goto-char (point-min))
23332 (while (and (not (eobp)) (not (zerop min-indent)))
23333 (unless (looking-at "[ \t]*$")
23334 (setq min-indent (min min-indent (current-indentation))))
23336 ;; Then loop over all lines.
23338 (goto-char (point-min))
23339 (while (not (eobp))
23340 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23341 ;; Don't get fooled by invisible text (e.g. link path)
23342 ;; when moving to column MIN-INDENT.
23343 (let ((buffer-invisibility-spec nil))
23344 (org-move-to-column min-indent t))
23345 (insert comment-start))
23346 (forward-line)))))))))
23348 (defun org-comment-dwim (_arg)
23349 "Call `comment-dwim' within a source edit buffer if needed."
23351 (if (org-in-src-block-p)
23352 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23353 (call-interactively 'comment-dwim)))
23358 ;; This section contains tools to operate on timestamp objects, as
23359 ;; returned by, e.g. `org-element-context'.
23361 (defun org-timestamp--to-internal-time (timestamp &optional end)
23362 "Encode TIMESTAMP object into Emacs internal time.
23363 Use end of date range or time range when END is non-nil."
23364 (apply #'encode-time
23367 (lambda (prop) (or (org-element-property prop timestamp) 0))
23368 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23369 '(:minute-start :hour-start :day-start :month-start
23372 (defun org-timestamp-has-time-p (timestamp)
23373 "Non-nil when TIMESTAMP has a time specified."
23374 (org-element-property :hour-start timestamp))
23376 (defun org-timestamp-format (timestamp format &optional end utc)
23377 "Format a TIMESTAMP object into a string.
23379 FORMAT is a format specifier to be passed to
23380 `format-time-string'.
23382 When optional argument END is non-nil, use end of date-range or
23383 time-range, if possible.
23385 When optional argument UTC is non-nil, time will be expressed as
23387 (format-time-string
23388 format (org-timestamp--to-internal-time timestamp end)
23391 (defun org-timestamp-split-range (timestamp &optional end)
23392 "Extract a TIMESTAMP object from a date or time range.
23394 END, when non-nil, means extract the end of the range.
23395 Otherwise, extract its start.
23397 Return a new timestamp object."
23398 (let ((type (org-element-property :type timestamp)))
23399 (if (memq type '(active inactive diary)) timestamp
23400 (let ((split-ts (org-element-copy timestamp)))
23402 (org-element-put-property
23403 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23404 ;; Copy start properties over end properties if END is
23405 ;; non-nil. Otherwise, copy end properties over `start' ones.
23406 (let ((p-alist '((:minute-start . :minute-end)
23407 (:hour-start . :hour-end)
23408 (:day-start . :day-end)
23409 (:month-start . :month-end)
23410 (:year-start . :year-end))))
23411 (dolist (p-cell p-alist)
23412 (org-element-put-property
23414 (funcall (if end #'car #'cdr) p-cell)
23415 (org-element-property
23416 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23417 ;; Eventually refresh `:raw-value'.
23418 (org-element-put-property split-ts :raw-value nil)
23419 (org-element-put-property
23420 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23422 (defun org-timestamp-translate (timestamp &optional boundary)
23423 "Translate TIMESTAMP object to custom format.
23425 Format string is defined in `org-time-stamp-custom-formats',
23428 When optional argument BOUNDARY is non-nil, it is either the
23429 symbol `start' or `end'. In this case, only translate the
23430 starting or ending part of TIMESTAMP if it is a date or time
23431 range. Otherwise, translate both parts.
23433 Return timestamp as-is if `org-display-custom-times' is nil or if
23434 it has a `diary' type."
23435 (let ((type (org-element-property :type timestamp)))
23436 (if (or (not org-display-custom-times) (eq type 'diary))
23437 (org-element-interpret-data timestamp)
23438 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23439 org-time-stamp-custom-formats)))
23440 (if (and (not boundary) (memq type '(active-range inactive-range)))
23441 (concat (org-timestamp-format timestamp fmt)
23443 (org-timestamp-format timestamp fmt t))
23444 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23450 (defvar reftex-docstruct-symbol)
23453 (defun org-reftex-citation ()
23454 "Use reftex-citation to insert a citation into the buffer.
23455 This looks for a line like
23457 #+BIBLIOGRAPHY: foo plain option:-d
23459 and derives from it that foo.bib is the bibliography file relevant
23460 for this document. It then installs the necessary environment for RefTeX
23461 to work in this buffer and calls `reftex-citation' to insert a citation
23464 Export of such citations to both LaTeX and HTML is handled by the contributed
23465 package ox-bibtex by Taru Karttunen."
23467 (let ((reftex-docstruct-symbol 'org--rds)
23469 (org-with-wide-buffer
23470 (let ((case-fold-search t)
23471 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23472 (if (not (save-excursion
23473 (or (re-search-forward re nil t)
23474 (re-search-backward re nil t))))
23475 (user-error "No bibliography defined in file")
23476 (setq bib (concat (match-string 1) ".bib")
23477 org--rds (list (list 'bib bib))))))
23478 (call-interactively 'reftex-citation)))
23480 ;;;; Functions extending outline functionality
23482 (defun org-beginning-of-line (&optional n)
23483 "Go to the beginning of the current visible line.
23485 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23486 tags on the first attempt, and only move to after the tags when
23487 the cursor is already beyond the end of the headline.
23489 With argument N not nil or 1, move forward N - 1 lines first."
23491 (let ((origin (point))
23492 (special (pcase org-special-ctrl-a/e
23493 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23495 ;; First move to a visible line.
23496 (if (bound-and-true-p visual-line-mode)
23497 (beginning-of-visual-line n)
23498 (move-beginning-of-line n)
23499 ;; `move-beginning-of-line' may leave point after invisible
23500 ;; characters if line starts with such of these (e.g., with
23501 ;; a link at column 0). Really move to the beginning of the
23502 ;; current visible line.
23503 (beginning-of-line))
23505 ;; No special behavior. Point is already at the beginning of
23506 ;; a line, logical or visual.
23508 ;; `beginning-of-visual-line' left point before logical beginning
23509 ;; of line: point is at the beginning of a visual line. Bail
23511 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23512 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23513 ;; At a headline, special position is before the title, but
23514 ;; after any TODO keyword or priority cookie.
23515 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23516 (line-end-position)))
23518 (if (eq special 'reversed)
23519 (when (and (= origin bol) (eq last-command this-command))
23520 (goto-char refpos))
23521 (when (or (> origin refpos) (= origin bol))
23522 (goto-char refpos)))))
23523 ((and (looking-at org-list-full-item-re)
23524 (memq (org-element-type (save-match-data (org-element-at-point)))
23525 '(item plain-list)))
23526 ;; Set special position at first white space character after
23527 ;; bullet, and check-box, if any.
23528 (let ((after-bullet
23529 (let ((box (match-end 3)))
23530 (cond ((not box) (match-end 1))
23531 ((eq (char-after box) ?\s) (1+ box))
23533 (if (eq special 'reversed)
23534 (when (and (= (point) origin) (eq last-command this-command))
23535 (goto-char after-bullet))
23536 (when (or (> origin after-bullet) (= (point) origin))
23537 (goto-char after-bullet)))))
23538 ;; No special context. Point is already at beginning of line.
23541 (defun org-end-of-line (&optional n)
23542 "Go to the end of the line, but before ellipsis, if any.
23544 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23545 tags on the first attempt, and only move to after the tags when
23546 the cursor is already beyond the end of the headline.
23548 With argument N not nil or 1, move forward N - 1 lines first."
23550 (let ((origin (point))
23551 (special (pcase org-special-ctrl-a/e
23552 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23554 ;; First move to a visible line.
23555 (if (bound-and-true-p visual-line-mode)
23556 (beginning-of-visual-line n)
23557 (move-beginning-of-line n))
23559 ;; At a headline, with tags.
23562 (beginning-of-line)
23563 (let ((case-fold-search nil))
23564 (looking-at org-complex-heading-regexp)))
23566 (let ((tags (save-excursion
23567 (goto-char (match-beginning 5))
23568 (skip-chars-backward " \t")
23570 (visual-end (and (bound-and-true-p visual-line-mode)
23572 (end-of-visual-line)
23574 ;; If `end-of-visual-line' brings us before end of line or
23575 ;; even tags, i.e., the headline spans over multiple visual
23576 ;; lines, move there.
23577 (cond ((and visual-end
23578 (< visual-end tags)
23579 (<= origin visual-end))
23580 (goto-char visual-end))
23581 ((eq special 'reversed)
23582 (if (and (= origin (line-end-position))
23583 (eq this-command last-command))
23587 (if (or (< origin tags) (= origin (line-end-position)))
23590 ((bound-and-true-p visual-line-mode)
23591 (let ((bol (line-beginning-position)))
23592 (end-of-visual-line)
23593 ;; If `end-of-visual-line' gets us past the ellipsis at the
23594 ;; end of a line, backtrack and use `end-of-line' instead.
23595 (when (/= bol (line-beginning-position))
23598 (t (end-of-line)))))
23600 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23601 (define-key org-mode-map "\C-e" 'org-end-of-line)
23603 (defun org-backward-sentence (&optional _arg)
23604 "Go to beginning of sentence, or beginning of table field.
23605 This will call `backward-sentence' or `org-table-beginning-of-field',
23606 depending on context."
23608 (let* ((element (org-element-at-point))
23609 (contents-begin (org-element-property :contents-begin element))
23610 (table (org-element-lineage element '(table) t)))
23612 (> (point) contents-begin)
23613 (<= (point) (org-element-property :contents-end table)))
23614 (call-interactively #'org-table-beginning-of-field)
23616 (when (and contents-begin
23617 (< (point-min) contents-begin)
23618 (> (point) contents-begin))
23619 (narrow-to-region contents-begin
23620 (org-element-property :contents-end element)))
23621 (call-interactively #'backward-sentence)))))
23623 (defun org-forward-sentence (&optional _arg)
23624 "Go to end of sentence, or end of table field.
23625 This will call `forward-sentence' or `org-table-end-of-field',
23626 depending on context."
23628 (if (and (org-at-heading-p)
23629 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23631 (narrow-to-region (line-beginning-position) (line-end-position))
23632 (call-interactively #'forward-sentence))
23633 (let* ((element (org-element-at-point))
23634 (contents-end (org-element-property :contents-end element))
23635 (table (org-element-lineage element '(table) t)))
23637 (>= (point) (org-element-property :contents-begin table))
23638 (< (point) contents-end))
23639 (call-interactively #'org-table-end-of-field)
23641 (when (and contents-end
23642 (> (point-max) contents-end)
23643 ;; Skip blank lines between elements.
23644 (< (org-element-property :end element)
23645 (save-excursion (goto-char contents-end)
23646 (skip-chars-forward " \r\t\n"))))
23647 (narrow-to-region (org-element-property :contents-begin element)
23649 ;; End of heading is considered as the end of a sentence.
23650 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
23651 (call-interactively #'forward-sentence)))))))
23653 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23654 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23656 (defun org-kill-line (&optional _arg)
23657 "Kill line, to tags or end of line."
23660 ((or (not org-special-ctrl-k)
23662 (not (org-at-heading-p)))
23663 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23664 org-ctrl-k-protect-subtree
23665 (or (eq org-ctrl-k-protect-subtree 'error)
23666 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23667 (user-error "C-k aborted as it would kill a hidden subtree"))
23668 (call-interactively
23669 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23670 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23671 (kill-region (point) (match-beginning 1))
23672 (org-set-tags nil t))
23673 (t (kill-region (point) (point-at-eol)))))
23675 (define-key org-mode-map "\C-k" 'org-kill-line)
23677 (defun org-yank (&optional arg)
23678 "Yank. If the kill is a subtree, treat it specially.
23679 This command will look at the current kill and check if is a single
23680 subtree, or a series of subtrees[1]. If it passes the test, and if the
23681 cursor is at the beginning of a line or after the stars of a currently
23682 empty headline, then the yank is handled specially. How exactly depends
23683 on the value of the following variables.
23685 `org-yank-folded-subtrees'
23686 By default, this variable is non-nil, which results in
23687 subtree(s) being folded after insertion, except if doing so
23688 would swallow text after the yanked text.
23690 `org-yank-adjusted-subtrees'
23691 When non-nil (the default value is nil), the subtree will be
23692 promoted or demoted in order to fit into the local outline tree
23693 structure, which means that the level will be adjusted so that it
23694 becomes the smaller one of the two *visible* surrounding headings.
23696 Any prefix to this command will cause `yank' to be called directly with
23697 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23699 plainly yank the text as it is.
23701 \[1] The test checks if the first non-white line is a heading
23702 and if there are no other headings with fewer stars."
23704 (org-yank-generic 'yank arg))
23706 (defun org-yank-generic (command arg)
23707 "Perform some yank-like command.
23709 This function implements the behavior described in the `org-yank'
23710 documentation. However, it has been generalized to work for any
23711 interactive command with similar behavior."
23713 ;; pretend to be command COMMAND
23714 (setq this-command command)
23717 (call-interactively command)
23719 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23720 (and (org-kill-is-subtree-p)
23722 (and (looking-at "[ \t]*$")
23725 (buffer-substring (point-at-bol) (point)))))))
23728 ((and subtreep org-yank-folded-subtrees)
23729 (let ((beg (point))
23731 (if (and subtreep org-yank-adjusted-subtrees)
23732 (org-paste-subtree nil nil 'for-yank)
23733 (call-interactively command))
23737 (when (and (bolp) subtreep
23738 (not (setq swallowp
23739 (org-yank-folding-would-swallow-text beg end))))
23740 (org-with-limited-levels
23741 (or (looking-at org-outline-regexp)
23742 (re-search-forward org-outline-regexp-bol end t))
23743 (while (and (< (point) end) (looking-at org-outline-regexp))
23744 (outline-hide-subtree)
23745 (org-cycle-show-empty-lines 'folded)
23746 (condition-case nil
23747 (outline-forward-same-level 1)
23748 (error (goto-char end))))))
23751 "Inserted text not folded because that would swallow text"))
23754 (skip-chars-forward " \t\n\r")
23755 (beginning-of-line 1)
23756 (push-mark beg 'nomsg)))
23757 ((and subtreep org-yank-adjusted-subtrees)
23758 (let ((beg (point-at-bol)))
23759 (org-paste-subtree nil nil 'for-yank)
23760 (push-mark beg 'nomsg)))
23762 (call-interactively command))))))
23764 (defun org-yank-folding-would-swallow-text (beg end)
23765 "Would hide-subtree at BEG swallow any text after END?"
23767 (org-with-limited-levels
23770 (when (or (looking-at org-outline-regexp)
23771 (re-search-forward org-outline-regexp-bol end t))
23772 (setq level (org-outline-level)))
23774 (skip-chars-forward " \t\r\n\v\f")
23776 (and (bolp) (looking-at-p org-outline-regexp)
23777 (<= (org-outline-level) level))))))))
23779 (define-key org-mode-map "\C-y" 'org-yank)
23781 (defun org-truely-invisible-p ()
23782 "Check if point is at a character currently not visible.
23783 This version does not only check the character property, but also
23785 (unless (bound-and-true-p visible-mode)
23786 (org-invisible-p)))
23788 (defun org-invisible-p2 ()
23789 "Check if point is at a character currently not visible.
23791 If the point is at EOL (and not at the beginning of a buffer too),
23792 move it back by one char before doing this check."
23794 (when (and (eolp) (not (bobp)))
23796 (org-invisible-p)))
23798 (defun org-back-to-heading (&optional invisible-ok)
23799 "Call `outline-back-to-heading', but provide a better error message."
23800 (condition-case nil
23801 (outline-back-to-heading invisible-ok)
23802 (error (error "Before first headline at position %d in buffer %s"
23803 (point) (current-buffer)))))
23805 (defun org-before-first-heading-p ()
23806 "Before first heading?"
23809 (null (re-search-backward org-outline-regexp-bol nil t))))
23811 (defun org-at-heading-p (&optional ignored)
23812 (outline-on-heading-p t))
23814 (defun org-in-commented-heading-p (&optional no-inheritance)
23815 "Non-nil if point is under a commented heading.
23816 This function also checks ancestors of the current headline,
23817 unless optional argument NO-INHERITANCE is non-nil."
23819 ((org-before-first-heading-p) nil)
23820 ((let ((headline (nth 4 (org-heading-components))))
23822 (let ((case-fold-search nil))
23823 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23825 (no-inheritance nil)
23827 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23829 (defun org-at-comment-p nil
23830 "Is cursor in a commented line?"
23833 (beginning-of-line)
23834 (looking-at "^[ \t]*# "))))
23836 (defun org-at-drawer-p nil
23837 "Is cursor at a drawer keyword?"
23839 (move-beginning-of-line 1)
23840 (looking-at org-drawer-regexp)))
23842 (defun org-at-block-p nil
23843 "Is cursor at a block keyword?"
23845 (move-beginning-of-line 1)
23846 (looking-at org-block-regexp)))
23848 (defun org-point-at-end-of-empty-headline ()
23849 "If point is at the end of an empty headline, return t, else nil.
23850 If the heading only contains a TODO keyword, it is still still considered
23852 (let ((case-fold-search nil))
23853 (and (looking-at "[ \t]*$")
23854 org-todo-line-regexp
23856 (beginning-of-line)
23857 (looking-at org-todo-line-regexp)
23858 (string= (match-string 3) "")))))
23860 (defun org-at-heading-or-item-p ()
23861 (or (org-at-heading-p) (org-at-item-p)))
23863 (defun org-at-target-p ()
23864 (or (org-in-regexp org-radio-target-regexp)
23865 (org-in-regexp org-target-regexp)))
23866 ;; Compatibility alias with Org versions < 7.8.03
23867 (defalias 'org-on-target-p 'org-at-target-p)
23869 (defun org-up-heading-all (arg)
23870 "Move to the heading line of which the present line is a subheading.
23871 This function considers both visible and invisible heading lines.
23872 With argument, move up ARG levels."
23873 (outline-up-heading arg t))
23875 (defun org-up-heading-safe ()
23876 "Move to the heading line of which the present line is a subheading.
23877 This version will not throw an error. It will return the level of the
23878 headline found, or nil if no higher level is found.
23880 Also, this function will be a lot faster than `outline-up-heading',
23881 because it relies on stars being the outline starters. This can really
23882 make a significant difference in outlines with very many siblings."
23883 (when (ignore-errors (org-back-to-heading t))
23884 (let ((level-up (1- (funcall outline-level))))
23885 (and (> level-up 0)
23886 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23887 (funcall outline-level)))))
23889 (defun org-first-sibling-p ()
23890 "Is this heading the first child of its parents?"
23892 (let ((re org-outline-regexp-bol)
23894 (unless (org-at-heading-p t)
23895 (user-error "Not at a heading"))
23896 (setq level (funcall outline-level))
23898 (if (not (re-search-backward re nil t))
23900 (setq l (funcall outline-level))
23903 (defun org-goto-sibling (&optional previous)
23904 "Goto the next sibling, even if it is invisible.
23905 When PREVIOUS is set, go to the previous sibling instead. Returns t
23906 when a sibling was found. When none is found, return nil and don't
23908 (let ((fun (if previous 're-search-backward 're-search-forward))
23910 (re org-outline-regexp-bol)
23912 (when (ignore-errors (org-back-to-heading t))
23913 (setq level (funcall outline-level))
23915 (or previous (forward-char 1))
23916 (while (funcall fun re nil t)
23917 (setq l (funcall outline-level))
23918 (when (< l level) (goto-char pos) (throw 'exit nil))
23919 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23923 (defun org-show-siblings ()
23924 "Show all siblings of the current headline."
23926 (while (org-goto-sibling) (org-flag-heading nil)))
23928 (while (org-goto-sibling 'previous)
23929 (org-flag-heading nil))))
23931 (defun org-goto-first-child ()
23932 "Goto the first child, even if it is invisible.
23933 Return t when a child was found. Otherwise don't move point and
23935 (let (level (pos (point)) (re org-outline-regexp-bol))
23936 (when (ignore-errors (org-back-to-heading t))
23937 (setq level (outline-level))
23939 (if (and (re-search-forward re nil t) (> (outline-level) level))
23940 (progn (goto-char (match-beginning 0)) t)
23941 (goto-char pos) nil))))
23943 (defun org-show-hidden-entry ()
23944 "Show an entry where even the heading is hidden."
23948 (defun org-flag-heading (flag &optional entry)
23949 "Flag the current heading. FLAG non-nil means make invisible.
23950 When ENTRY is non-nil, show the entire entry."
23952 (org-back-to-heading t)
23953 ;; Check if we should show the entire entry
23958 (and (outline-next-heading)
23959 (org-flag-heading nil))))
23960 (outline-flag-region (max (point-min) (1- (point)))
23961 (save-excursion (outline-end-of-heading) (point))
23964 (defun org-get-next-sibling ()
23965 "Move to next heading of the same level, and return point.
23966 If there is no such heading, return nil.
23967 This is like outline-next-sibling, but invisible headings are ok."
23968 (let ((level (funcall outline-level)))
23969 (outline-next-heading)
23970 (while (and (not (eobp)) (> (funcall outline-level) level))
23971 (outline-next-heading))
23972 (unless (or (eobp) (< (funcall outline-level) level))
23975 (defun org-get-last-sibling ()
23976 "Move to previous heading of the same level, and return point.
23977 If there is no such heading, return nil."
23978 (let ((opoint (point))
23979 (level (funcall outline-level)))
23980 (outline-previous-heading)
23981 (when (and (/= (point) opoint) (outline-on-heading-p t))
23982 (while (and (> (funcall outline-level) level)
23984 (outline-previous-heading))
23985 (unless (< (funcall outline-level) level)
23988 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23989 "Goto to the end of a subtree."
23990 ;; This contains an exact copy of the original function, but it uses
23991 ;; `org-back-to-heading', to make it work also in invisible
23992 ;; trees. And is uses an invisible-ok argument.
23993 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23994 ;; Furthermore, when used inside Org, finding the end of a large subtree
23995 ;; with many children and grandchildren etc, this can be much faster
23996 ;; than the outline version.
23997 (org-back-to-heading invisible-ok)
23999 (level (funcall outline-level)))
24000 (if (and (derived-mode-p 'org-mode) (< level 1000))
24001 ;; A true heading (not a plain list item), in Org
24002 ;; This means we can easily find the end by looking
24003 ;; only for the right number of stars. Using a regexp to do
24004 ;; this is so much faster than using a Lisp loop.
24005 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24007 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24008 ;; something else, do it the slow way
24009 (while (and (not (eobp))
24010 (or first (> (funcall outline-level) level)))
24012 (outline-next-heading)))
24014 (when (memq (preceding-char) '(?\n ?\^M))
24015 ;; Go to end of line before heading
24017 (when (memq (preceding-char) '(?\n ?\^M))
24018 ;; leave blank line before heading
24019 (forward-char -1)))))
24022 (defun org-end-of-meta-data (&optional full)
24023 "Skip planning line and properties drawer in current entry.
24024 When optional argument FULL is non-nil, also skip empty lines,
24025 clocking lines and regular drawers at the beginning of the
24027 (org-back-to-heading t)
24029 (when (looking-at-p org-planning-line-re) (forward-line))
24030 (when (looking-at org-property-drawer-re)
24031 (goto-char (match-end 0))
24033 (when (and full (not (org-at-heading-p)))
24035 (let ((end (save-excursion (outline-next-heading) (point)))
24036 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24037 (while (not (eobp))
24038 (cond ((looking-at-p org-drawer-regexp)
24039 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24042 ((looking-at-p re) (forward-line))
24043 (t (throw 'exit t))))))))
24045 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24046 "Move forward to the ARG'th subheading at same level as this one.
24047 Stop at the first and last subheadings of a superior heading.
24048 Normally this only looks at visible headings, but when INVISIBLE-OK is
24049 non-nil it will also look at invisible ones."
24051 (let ((backward? (and arg (< arg 0))))
24052 (if (org-before-first-heading-p)
24053 (if backward? (goto-char (point-min)) (outline-next-heading))
24054 (org-back-to-heading invisible-ok)
24055 (unless backward? (end-of-line)) ;do not match current headline
24056 (let ((level (- (match-end 0) (match-beginning 0) 1))
24057 (f (if backward? #'re-search-backward #'re-search-forward))
24058 (count (if arg (abs arg) 1))
24060 (while (and (> count 0)
24061 (funcall f org-outline-regexp-bol nil 'move))
24062 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24063 (cond ((< l level) (setq count 0))
24066 (not (org-invisible-p
24067 (line-beginning-position)))))
24069 (when (= l level) (setq result (point)))))))
24070 (goto-char result))
24071 (beginning-of-line))))
24073 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24074 "Move backward to the ARG'th subheading at same level as this one.
24075 Stop at the first and last subheadings of a superior heading."
24077 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24079 (defun org-next-visible-heading (arg)
24080 "Move to the next visible heading.
24082 This function wraps `outline-next-visible-heading' with
24083 `org-with-limited-levels' in order to skip over inline tasks and
24084 respect customization of `org-odd-levels-only'."
24086 (org-with-limited-levels
24087 (outline-next-visible-heading arg)))
24089 (defun org-previous-visible-heading (arg)
24090 "Move to the previous visible heading.
24092 This function wraps `outline-previous-visible-heading' with
24093 `org-with-limited-levels' in order to skip over inline tasks and
24094 respect customization of `org-odd-levels-only'."
24096 (org-with-limited-levels
24097 (outline-previous-visible-heading arg)))
24099 (defun org-next-block (arg &optional backward block-regexp)
24100 "Jump to the next block.
24102 With a prefix argument ARG, jump forward ARG many blocks.
24104 When BACKWARD is non-nil, jump to the previous block.
24106 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24107 Match data is set according to this regexp when the function
24110 Return point at beginning of the opening line of found block.
24111 Throw an error if no block is found."
24113 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24114 (case-fold-search t)
24115 (search-fn (if backward #'re-search-backward #'re-search-forward))
24119 (if backward (beginning-of-line) (end-of-line))
24120 (while (and (> count 0) (funcall search-fn re nil t))
24121 (let ((element (save-excursion
24122 (goto-char (match-beginning 0))
24123 (save-match-data (org-element-at-point)))))
24124 (when (and (memq (org-element-type element)
24125 '(center-block comment-block dynamic-block
24126 example-block export-block quote-block
24127 special-block src-block verse-block))
24128 (<= (match-beginning 0)
24129 (org-element-property :post-affiliated element)))
24130 (setq last-element element)
24133 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24134 (save-match-data (org-show-context)))
24136 (user-error "No %s code blocks" (if backward "previous" "further")))))
24138 (defun org-previous-block (arg &optional block-regexp)
24139 "Jump to the previous block.
24140 With a prefix argument ARG, jump backward ARG many source blocks.
24141 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24143 (org-next-block arg t block-regexp))
24145 (defun org-forward-paragraph ()
24146 "Move forward to beginning of next paragraph or equivalent.
24148 The function moves point to the beginning of the next visible
24149 structural element, which can be a paragraph, a table, a list
24150 item, etc. It also provides some special moves for convenience:
24152 - On an affiliated keyword, jump to the beginning of the
24154 - On an item or a footnote definition, move to the second
24155 element inside, if any.
24156 - On a table or a property drawer, jump after it.
24157 - On a verse or source block, stop after blank lines."
24160 (let* ((deactivate-mark nil)
24161 (element (org-element-at-point))
24162 (type (org-element-type element))
24163 (post-affiliated (org-element-property :post-affiliated element))
24164 (contents-begin (org-element-property :contents-begin element))
24165 (contents-end (org-element-property :contents-end element))
24166 (end (let ((end (org-element-property :end element)) (parent element))
24167 (while (and (setq parent (org-element-property :parent parent))
24168 (= (org-element-property :contents-end parent) end))
24169 (setq end (org-element-property :end parent)))
24171 (cond ((not element)
24172 (skip-chars-forward " \r\t\n")
24173 (or (eobp) (beginning-of-line)))
24174 ;; On affiliated keywords, move to element's beginning.
24175 ((< (point) post-affiliated)
24176 (goto-char post-affiliated))
24177 ;; At a table row, move to the end of the table. Similarly,
24178 ;; at a node property, move to the end of the property
24180 ((memq type '(node-property table-row))
24181 (goto-char (org-element-property
24182 :end (org-element-property :parent element))))
24183 ((memq type '(property-drawer table)) (goto-char end))
24184 ;; Consider blank lines as separators in verse and source
24185 ;; blocks to ease editing.
24186 ((memq type '(src-block verse-block))
24187 (when (eq type 'src-block)
24189 (save-excursion (goto-char end)
24190 (skip-chars-backward " \r\t\n")
24191 (line-beginning-position))))
24192 (beginning-of-line)
24193 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24194 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24196 (skip-chars-forward " \r\t\n")
24197 (if (= (point) contents-end) (goto-char end)
24198 (beginning-of-line))))
24199 ;; With no contents, just skip element.
24200 ((not contents-begin) (goto-char end))
24201 ;; If contents are invisible, skip the element altogether.
24202 ((org-invisible-p (line-end-position))
24205 (org-with-limited-levels (outline-next-visible-heading 1)))
24206 ;; At a plain list, make sure we move to the next item
24207 ;; instead of skipping the whole list.
24208 (plain-list (forward-char)
24209 (org-forward-paragraph))
24210 (otherwise (goto-char end))))
24211 ((>= (point) contents-end) (goto-char end))
24212 ((>= (point) contents-begin)
24213 ;; This can only happen on paragraphs and plain lists.
24215 (paragraph (goto-char end))
24216 ;; At a plain list, try to move to second element in
24217 ;; first item, if possible.
24218 (plain-list (end-of-line)
24219 (org-forward-paragraph))))
24220 ;; When contents start on the middle of a line (e.g. in
24221 ;; items and footnote definitions), try to reach first
24222 ;; element starting after current line.
24223 ((> (line-end-position) contents-begin)
24225 (org-forward-paragraph))
24226 (t (goto-char contents-begin))))))
24228 (defun org-backward-paragraph ()
24229 "Move backward to start of previous paragraph or equivalent.
24231 The function moves point to the beginning of the current
24232 structural element, which can be a paragraph, a table, a list
24233 item, etc., or to the beginning of the previous visible one if
24234 point is already there. It also provides some special moves for
24237 - On an affiliated keyword, jump to the first one.
24238 - On a table or a property drawer, move to its beginning.
24239 - On comment, example, export, src and verse blocks, stop
24240 before blank lines."
24243 (let* ((deactivate-mark nil)
24244 (element (org-element-at-point))
24245 (type (org-element-type element))
24246 (contents-end (org-element-property :contents-end element))
24247 (post-affiliated (org-element-property :post-affiliated element))
24248 (begin (org-element-property :begin element))
24249 (special? ;blocks handled specially
24250 (memq type '(comment-block example-block export-block src-block
24254 ;; These types have no proper contents. Fake line
24255 ;; below the block opening line as contents beginning.
24256 (save-excursion (goto-char begin) (line-beginning-position 2))
24257 (org-element-property :contents-begin element))))
24259 ((not element) (goto-char (point-min)))
24262 (org-backward-paragraph))
24263 ((<= (point) post-affiliated) (goto-char begin))
24264 ;; Special behavior: on a table or a property drawer, move to
24266 ((memq type '(node-property table-row))
24267 (goto-char (org-element-property
24268 :post-affiliated (org-element-property :parent element))))
24270 (if (<= (point) contents-begin) (goto-char post-affiliated)
24271 ;; Inside a verse block, see blank lines as paragraph
24273 (let ((origin (point)))
24274 (skip-chars-backward " \r\t\n" contents-begin)
24275 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24276 (skip-chars-forward " \r\t\n" origin)
24277 (if (= (point) origin) (goto-char contents-begin)
24278 (beginning-of-line))))))
24279 ((eq type 'paragraph) (goto-char contents-begin)
24280 ;; When at first paragraph in an item or a footnote definition,
24281 ;; move directly to beginning of line.
24282 (let ((parent-contents
24283 (org-element-property
24284 :contents-begin (org-element-property :parent element))))
24285 (when (and parent-contents (= parent-contents contents-begin))
24286 (beginning-of-line))))
24287 ;; At the end of a greater element, move to the beginning of
24288 ;; the last element within.
24289 ((and contents-end (>= (point) contents-end))
24290 (goto-char (1- contents-end))
24291 (org-backward-paragraph))
24292 (t (goto-char (or post-affiliated begin))))
24293 ;; Ensure we never leave point invisible.
24294 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24296 (defun org-forward-element ()
24297 "Move forward by one element.
24298 Move to the next element at the same level, when possible."
24300 (cond ((eobp) (user-error "Cannot move further down"))
24301 ((org-with-limited-levels (org-at-heading-p))
24302 (let ((origin (point)))
24303 (goto-char (org-end-of-subtree nil t))
24304 (unless (org-with-limited-levels (org-at-heading-p))
24306 (user-error "Cannot move further down"))))
24308 (let* ((elem (org-element-at-point))
24309 (end (org-element-property :end elem))
24310 (parent (org-element-property :parent elem)))
24311 (cond ((and parent (= (org-element-property :contents-end parent) end))
24312 (goto-char (org-element-property :end parent)))
24313 ((integer-or-marker-p end) (goto-char end))
24314 (t (message "No element at point")))))))
24316 (defun org-backward-element ()
24317 "Move backward by one element.
24318 Move to the previous element at the same level, when possible."
24320 (cond ((bobp) (user-error "Cannot move further up"))
24321 ((org-with-limited-levels (org-at-heading-p))
24322 ;; At a headline, move to the previous one, if any, or stay
24324 (let ((origin (point)))
24325 (org-with-limited-levels (org-backward-heading-same-level 1))
24326 ;; When current headline has no sibling above, move to its
24328 (when (= (point) origin)
24329 (or (org-with-limited-levels (org-up-heading-safe))
24330 (progn (goto-char origin)
24331 (user-error "Cannot move further up"))))))
24333 (let* ((elem (org-element-at-point))
24334 (beg (org-element-property :begin elem)))
24336 ;; Move to beginning of current element if point isn't
24338 ((null beg) (message "No element at point"))
24339 ((/= (point) beg) (goto-char beg))
24341 (skip-chars-backward " \r\t\n")
24343 (let ((prev (org-element-at-point)))
24344 (goto-char (org-element-property :begin prev))
24345 (while (and (setq prev (org-element-property :parent prev))
24346 (<= (org-element-property :end prev) beg))
24347 (goto-char (org-element-property :begin prev)))))))))))
24349 (defun org-up-element ()
24350 "Move to upper element."
24352 (if (org-with-limited-levels (org-at-heading-p))
24353 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24354 (let* ((elem (org-element-at-point))
24355 (parent (org-element-property :parent elem)))
24356 (if parent (goto-char (org-element-property :begin parent))
24357 (if (org-with-limited-levels (org-before-first-heading-p))
24358 (user-error "No surrounding element")
24359 (org-with-limited-levels (org-back-to-heading)))))))
24361 (defun org-down-element ()
24362 "Move to inner element."
24364 (let ((element (org-element-at-point)))
24366 ((memq (org-element-type element) '(plain-list table))
24367 (goto-char (org-element-property :contents-begin element))
24369 ((memq (org-element-type element) org-element-greater-elements)
24370 ;; If contents are hidden, first disclose them.
24371 (when (org-invisible-p (line-end-position)) (org-cycle))
24372 (goto-char (or (org-element-property :contents-begin element)
24373 (user-error "No content for this element"))))
24374 (t (user-error "No inner element")))))
24376 (defun org-drag-element-backward ()
24377 "Move backward element at point."
24379 (let ((elem (or (org-element-at-point)
24380 (user-error "No element at point"))))
24381 (if (eq (org-element-type elem) 'headline)
24382 ;; Preserve point when moving a whole tree, even if point was
24383 ;; on blank lines below the headline.
24384 (let ((offset (skip-chars-backward " \t\n")))
24385 (unwind-protect (org-move-subtree-up)
24386 (forward-char (- offset))))
24389 (goto-char (org-element-property :begin elem))
24390 (skip-chars-backward " \r\t\n")
24392 (let* ((beg (org-element-property :begin elem))
24393 (prev (org-element-at-point))
24395 (while (and (setq up (org-element-property :parent up))
24396 (<= (org-element-property :end up) beg))
24399 ;; Error out if no previous element or previous element is
24400 ;; a parent of the current one.
24401 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24402 (user-error "Cannot drag element backward")
24403 (let ((pos (point)))
24404 (org-element-swap-A-B prev-elem elem)
24405 (goto-char (+ (org-element-property :begin prev-elem)
24406 (- pos (org-element-property :begin elem))))))))))
24408 (defun org-drag-element-forward ()
24409 "Move forward element at point."
24411 (let* ((pos (point))
24412 (elem (or (org-element-at-point)
24413 (user-error "No element at point"))))
24414 (when (= (point-max) (org-element-property :end elem))
24415 (user-error "Cannot drag element forward"))
24416 (goto-char (org-element-property :end elem))
24417 (let ((next-elem (org-element-at-point)))
24418 (when (or (org-element-nested-p elem next-elem)
24419 (and (eq (org-element-type next-elem) 'headline)
24420 (not (eq (org-element-type elem) 'headline))))
24422 (user-error "Cannot drag element forward"))
24423 ;; Compute new position of point: it's shifted by NEXT-ELEM
24424 ;; body's length (without final blanks) and by the length of
24425 ;; blanks between ELEM and NEXT-ELEM.
24426 (let ((size-next (- (save-excursion
24427 (goto-char (org-element-property :end next-elem))
24428 (skip-chars-backward " \r\t\n")
24430 ;; Small correction if buffer doesn't end
24431 ;; with a newline character.
24432 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24433 (org-element-property :begin next-elem)))
24434 (size-blank (- (org-element-property :end elem)
24436 (goto-char (org-element-property :end elem))
24437 (skip-chars-backward " \r\t\n")
24440 (org-element-swap-A-B elem next-elem)
24441 (goto-char (+ pos size-next size-blank))))))
24443 (defun org-drag-line-forward (arg)
24444 "Drag the line at point ARG lines forward."
24446 (dotimes (_ (abs arg))
24447 (let ((c (current-column)))
24450 (beginning-of-line 2)
24451 (transpose-lines 1)
24452 (beginning-of-line 0))
24453 (transpose-lines 1)
24454 (beginning-of-line -1))
24455 (org-move-to-column c))))
24457 (defun org-drag-line-backward (arg)
24458 "Drag the line at point ARG lines backward."
24460 (org-drag-line-forward (- arg)))
24462 (defun org-mark-element ()
24463 "Put point at beginning of this element, mark at end.
24465 Interactively, if this command is repeated or (in Transient Mark
24466 mode) if the mark is active, it marks the next element after the
24467 ones already marked."
24469 (let (deactivate-mark)
24470 (if (and (called-interactively-p 'any)
24471 (or (and (eq last-command this-command) (mark t))
24472 (and transient-mark-mode mark-active)))
24476 (goto-char (org-element-property :end (org-element-at-point)))))
24477 (let ((element (org-element-at-point)))
24479 (push-mark (org-element-property :end element) t t)
24480 (goto-char (org-element-property :begin element))))))
24482 (defun org-narrow-to-element ()
24483 "Narrow buffer to current element."
24485 (let ((elem (org-element-at-point)))
24487 ((eq (car elem) 'headline)
24489 (org-element-property :begin elem)
24490 (org-element-property :end elem)))
24491 ((memq (car elem) org-element-greater-elements)
24493 (org-element-property :contents-begin elem)
24494 (org-element-property :contents-end elem)))
24497 (org-element-property :begin elem)
24498 (org-element-property :end elem))))))
24500 (defun org-transpose-element ()
24501 "Transpose current and previous elements, keeping blank lines between.
24502 Point is moved after both elements."
24504 (org-skip-whitespace)
24505 (let ((end (org-element-property :end (org-element-at-point))))
24506 (org-drag-element-backward)
24509 (defun org-unindent-buffer ()
24510 "Un-indent the visible part of the buffer.
24511 Relative indentation (between items, inside blocks, etc.) isn't
24514 (unless (eq major-mode 'org-mode)
24515 (user-error "Cannot un-indent a buffer not in Org mode"))
24516 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24519 (dolist (element (reverse contents))
24520 (if (memq (org-element-type element) '(headline section))
24521 (funcall unindent-tree (org-element-contents element))
24525 (org-element-property :begin element)
24526 (org-element-property :end element))
24527 (org-do-remove-indentation))))))))
24528 (funcall unindent-tree (org-element-contents parse-tree))))
24530 (defun org-show-children (&optional level)
24531 "Show all direct subheadings of this heading.
24532 Prefix arg LEVEL is how many levels below the current level
24533 should be shown. Default is enough to cause the following
24534 heading to appear."
24536 ;; If `orgstruct-mode' is active, use the slower version.
24537 (if orgstruct-mode (call-interactively #'outline-show-children)
24539 (org-back-to-heading t)
24540 (let* ((current-level (funcall outline-level))
24541 (max-level (org-get-valid-level
24543 (if level (prefix-numeric-value level) 1)))
24544 (end (save-excursion (org-end-of-subtree t t)))
24545 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24546 (past-first-child nil)
24547 ;; Make sure to skip inlinetasks.
24548 (re (format regexp-fmt
24551 ((not (featurep 'org-inlinetask)) "")
24552 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24554 (t (1- org-inlinetask-min-level))))))
24555 ;; Display parent heading.
24556 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24558 ;; Display children. First child may be deeper than expected
24559 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24560 ;; MAX-LEVEL accordingly.
24561 (while (re-search-forward re end t)
24562 (unless past-first-child
24563 (setq re (format regexp-fmt
24565 (max (funcall outline-level) max-level)))
24566 (setq past-first-child t))
24567 (outline-flag-region
24568 (line-end-position 0) (line-end-position) nil))))))
24570 (defun org-show-subtree ()
24571 "Show everything after this heading at deeper levels."
24573 (outline-flag-region
24576 (org-end-of-subtree t t))
24579 (defun org-show-entry ()
24580 "Show the body directly following this heading.
24581 Show the heading too, if it is currently invisible."
24585 (org-back-to-heading t)
24586 (outline-flag-region
24587 (max (point-min) (1- (point)))
24589 (if (re-search-forward
24590 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24591 (match-beginning 1)
24594 (org-cycle-hide-drawers 'children))))
24596 (defun org-make-options-regexp (kwds &optional extra)
24597 "Make a regular expression for keyword lines.
24598 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24599 when non-nil, is a regexp matching keywords names."
24600 (concat "^[ \t]*#\\+\\("
24602 (and extra (concat (and kwds "\\|") extra))
24603 "\\):[ \t]*\\(.*\\)"))
24605 ;;;; Integration with and fixes for other packages
24609 (defvar-local org-imenu-markers nil
24610 "All markers currently used by Imenu.")
24612 (defun org-imenu-new-marker (&optional pos)
24613 "Return a new marker for use by Imenu, and remember the marker."
24614 (let ((m (make-marker)))
24615 (move-marker m (or pos (point)))
24616 (push m org-imenu-markers)
24619 (defun org-imenu-get-tree ()
24620 "Produce the index for Imenu."
24621 (dolist (x org-imenu-markers) (move-marker x nil))
24622 (setq org-imenu-markers nil)
24623 (let* ((case-fold-search nil)
24624 (n org-imenu-depth)
24625 (re (concat "^" (org-get-limited-outline-regexp)))
24626 (subs (make-vector (1+ n) nil))
24628 m level head0 head)
24629 (org-with-wide-buffer
24630 (goto-char (point-max))
24631 (while (re-search-backward re nil t)
24632 (setq level (org-reduced-level (funcall outline-level)))
24633 (when (and (<= level n)
24634 (looking-at org-complex-heading-regexp)
24635 (setq head0 (match-string-no-properties 4)))
24636 (setq head (org-link-display-format head0)
24637 m (org-imenu-new-marker))
24638 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24639 (if (>= level last-level)
24640 (push (cons head m) (aref subs level))
24641 (push (cons head (aref subs (1+ level))) (aref subs level))
24642 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24643 (setq last-level level))))
24646 (eval-after-load "imenu"
24648 (add-hook 'imenu-after-jump-hook
24650 (when (derived-mode-p 'org-mode)
24651 (org-show-context 'org-goto))))))
24653 (defun org-link-display-format (s)
24654 "Replace links in string S with their description.
24655 If there is no description, use the link target."
24657 (replace-regexp-in-string
24658 org-bracket-link-analytic-regexp
24660 (if (match-end 5) (match-string 5 m)
24661 (concat (match-string 1 m) (match-string 3 m))))
24664 (defun org-toggle-link-display ()
24665 "Toggle the literal or descriptive display of links."
24667 (if org-descriptive-links
24668 (progn (org-remove-from-invisibility-spec '(org-link))
24669 (org-restart-font-lock)
24670 (setq org-descriptive-links nil))
24671 (progn (add-to-invisibility-spec '(org-link))
24672 (org-restart-font-lock)
24673 (setq org-descriptive-links t))))
24675 ;; Speedbar support
24677 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24678 "Overlay marking the agenda restriction line in speedbar.")
24679 (overlay-put org-speedbar-restriction-lock-overlay
24680 'face 'org-agenda-restriction-lock)
24681 (overlay-put org-speedbar-restriction-lock-overlay
24682 'help-echo "Agendas are currently limited to this item.")
24683 (delete-overlay org-speedbar-restriction-lock-overlay)
24685 (defun org-speedbar-set-agenda-restriction ()
24686 "Restrict future agenda commands to the location at point in speedbar.
24687 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24689 (require 'org-agenda)
24690 (let (p m tp np dir txt)
24692 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24694 (setq m (get-text-property p 'org-imenu-marker))
24695 (with-current-buffer (marker-buffer m)
24697 (org-agenda-set-restriction-lock 'subtree)))
24698 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24699 'speedbar-function 'speedbar-find-file))
24700 (setq tp (previous-single-property-change
24701 (1+ p) 'speedbar-function)
24702 np (next-single-property-change
24703 tp 'speedbar-function)
24704 dir (speedbar-line-directory)
24705 txt (buffer-substring-no-properties (or tp (point-min))
24706 (or np (point-max))))
24707 (with-current-buffer (find-file-noselect
24708 (let ((default-directory dir))
24709 (expand-file-name txt)))
24710 (unless (derived-mode-p 'org-mode)
24711 (user-error "Cannot restrict to non-Org mode file"))
24712 (org-agenda-set-restriction-lock 'file)))
24713 (t (user-error "Don't know how to restrict Org mode agenda")))
24714 (move-overlay org-speedbar-restriction-lock-overlay
24715 (point-at-bol) (point-at-eol))
24716 (setq current-prefix-arg nil)
24717 (org-agenda-maybe-redo)))
24719 (defvar speedbar-file-key-map)
24720 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24721 (eval-after-load "speedbar"
24723 (speedbar-add-supported-extension ".org")
24724 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24725 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24726 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24727 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24728 (add-hook 'speedbar-visiting-tag-hook
24729 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24731 ;;; Fixes and Hacks for problems with other packages
24733 (defun org--flyspell-object-check-p (element)
24734 "Non-nil when Flyspell can check object at point.
24735 ELEMENT is the element at point."
24736 (let ((object (save-excursion
24737 (when (looking-at-p "\\>") (backward-char))
24738 (org-element-context element))))
24739 (cl-case (org-element-type object)
24740 ;; Prevent checks in links due to keybinding conflict with
24742 ((code entity export-snippet inline-babel-call
24743 inline-src-block line-break latex-fragment link macro
24744 statistics-cookie target timestamp verbatim)
24746 (footnote-reference
24747 ;; Only in inline footnotes, within the definition.
24748 (and (eq (org-element-property :type object) 'inline)
24750 (goto-char (org-element-property :begin object))
24751 (search-forward ":" nil t 2))
24755 (defun org-mode-flyspell-verify ()
24756 "Function used for `flyspell-generic-check-word-predicate'."
24757 (if (org-at-heading-p)
24758 ;; At a headline or an inlinetask, check title only. This is
24759 ;; faster than relying on `org-element-at-point'.
24760 (and (save-excursion (beginning-of-line)
24761 (and (let ((case-fold-search t))
24762 (not (looking-at-p "\\*+ END[ \t]*$")))
24763 (let ((case-fold-search nil))
24764 (looking-at org-complex-heading-regexp))))
24765 (match-beginning 4)
24766 (>= (point) (match-beginning 4))
24767 (or (not (match-beginning 5))
24768 (< (point) (match-beginning 5))))
24769 (let* ((element (org-element-at-point))
24770 (post-affiliated (org-element-property :post-affiliated element)))
24772 ;; Ignore checks in all affiliated keywords but captions.
24773 ((< (point) post-affiliated)
24774 (and (save-excursion
24775 (beginning-of-line)
24776 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24777 (> (point) (match-end 0))
24778 (org--flyspell-object-check-p element)))
24779 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24780 ((let ((log (org-log-into-drawer)))
24782 (let ((drawer (org-element-lineage element '(drawer))))
24784 (eq (compare-strings
24786 (org-element-property :drawer-name drawer) nil nil t)
24790 (cl-case (org-element-type element)
24791 ((comment quote-section) t)
24793 ;; Allow checks between block markers, not on them.
24794 (and (> (line-beginning-position) post-affiliated)
24797 (skip-chars-forward " \r\t\n")
24798 (< (point) (org-element-property :end element)))))
24799 ;; Arbitrary list of keywords where checks are meaningful.
24800 ;; Make sure point is on the value part of the element.
24802 (and (member (org-element-property :key element)
24803 '("DESCRIPTION" "TITLE"))
24805 (search-backward ":" (line-beginning-position) t))))
24806 ;; Check is globally allowed in paragraphs verse blocks and
24807 ;; table rows (after affiliated keywords) but some objects
24808 ;; must not be affected.
24809 ((paragraph table-row verse-block)
24810 (let ((cbeg (org-element-property :contents-begin element))
24811 (cend (org-element-property :contents-end element)))
24812 (and cbeg (>= (point) cbeg) (< (point) cend)
24813 (org--flyspell-object-check-p element))))))))))
24814 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24816 (defun org-remove-flyspell-overlays-in (beg end)
24817 "Remove flyspell overlays in region."
24818 (and (bound-and-true-p flyspell-mode)
24819 (fboundp 'flyspell-delete-region-overlays)
24820 (flyspell-delete-region-overlays beg end)))
24822 (defvar flyspell-delayed-commands)
24823 (eval-after-load "flyspell"
24824 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24826 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24827 (eval-after-load "bookmark"
24828 '(if (boundp 'bookmark-after-jump-hook)
24829 ;; We can use the hook
24830 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24831 ;; Hook not available, use advice
24832 (defadvice bookmark-jump (after org-make-visible activate)
24833 "Make the position visible."
24834 (org-bookmark-jump-unhide))))
24836 ;; Make sure saveplace shows the location if it was hidden
24837 (eval-after-load "saveplace"
24838 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24839 "Make the position visible."
24840 (org-bookmark-jump-unhide)))
24842 ;; Make sure ecb shows the location if it was hidden
24843 (eval-after-load "ecb"
24844 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24845 "Make hierarchy visible when jumping into location from ECB tree buffer."
24846 (when (derived-mode-p 'org-mode)
24847 (org-show-context))))
24849 (defun org-bookmark-jump-unhide ()
24850 "Unhide the current position, to show the bookmark location."
24851 (and (derived-mode-p 'org-mode)
24852 (or (org-invisible-p)
24853 (save-excursion (goto-char (max (point-min) (1- (point))))
24854 (org-invisible-p)))
24855 (org-show-context 'bookmark-jump)))
24857 (defun org-mark-jump-unhide ()
24858 "Make the point visible with `org-show-context' after jumping to the mark."
24859 (when (and (derived-mode-p 'org-mode)
24861 (org-show-context 'mark-goto)))
24863 (eval-after-load "simple"
24864 '(defadvice pop-to-mark-command (after org-make-visible activate)
24865 "Make the point visible with `org-show-context'."
24866 (org-mark-jump-unhide)))
24868 (eval-after-load "simple"
24869 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24870 "Make the point visible with `org-show-context'."
24871 (org-mark-jump-unhide)))
24873 (eval-after-load "simple"
24874 '(defadvice pop-global-mark (after org-make-visible activate)
24875 "Make the point visible with `org-show-context'."
24876 (org-mark-jump-unhide)))
24878 ;; Make session.el ignore our circular variable
24879 (defvar session-globals-exclude)
24880 (eval-after-load "session"
24881 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24887 (run-hooks 'org-load-hook)
24889 ;;; org.el ends here